<commit_before>// Copyright © 2010-2015 The CefSharp Project. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
#pragma once

#include "Stdafx.h"

#include "CefBrowserWrapper.h"
#include "CefAppUnmanagedWrapper.h"
#include "JavascriptRootObjectWrapper.h"
#include "Serialization\V8Serialization.h"
#include "..\CefSharp.Core\Internals\Messaging\Messages.h"
#include "..\CefSharp.Core\Internals\Serialization\Primitives.h"

using namespace System;
using namespace System::Diagnostics;
using namespace System::Collections::Generic;
using namespace CefSharp::Internals::Messaging;
using namespace CefSharp::Internals::Serialization;

namespace CefSharp
{
    CefRefPtr<CefRenderProcessHandler> CefAppUnmanagedWrapper::GetRenderProcessHandler()
    {
        return this;
    };

    // CefRenderProcessHandler
    void CefAppUnmanagedWrapper::OnBrowserCreated(CefRefPtr<CefBrowser> browser)
    {
        auto wrapper = gcnew CefBrowserWrapper(browser);
        _onBrowserCreated->Invoke(wrapper);

        //Multiple CefBrowserWrappers created when opening popups
        _browserWrappers->Add(browser->GetIdentifier(), wrapper);
    }

    void CefAppUnmanagedWrapper::OnBrowserDestroyed(CefRefPtr<CefBrowser> browser)
    {
        auto wrapper = FindBrowserWrapper(browser->GetIdentifier(), false);

        if (wrapper != nullptr)
        {
            _browserWrappers->Remove(wrapper->BrowserId);
            _onBrowserDestroyed->Invoke(wrapper);
            delete wrapper;
        }
    };

    void CefAppUnmanagedWrapper::OnContextCreated(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, CefRefPtr<CefV8Context> context)
    {
        auto wrapper = FindBrowserWrapper(browser->GetIdentifier(), true);

        if (wrapper->JavascriptRootObject != nullptr)
        {
            auto window = context->GetGlobal();

            wrapper->JavascriptRootObjectWrapper = gcnew JavascriptRootObjectWrapper(wrapper->JavascriptRootObject, wrapper->BrowserProcess);

            wrapper->JavascriptRootObjectWrapper->V8Value = window;
            wrapper->JavascriptRootObjectWrapper->Bind();
        }
    };

    void CefAppUnmanagedWrapper::OnContextReleased(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, CefRefPtr<CefV8Context> context)
    {
        auto wrapper = FindBrowserWrapper(browser->GetIdentifier(), true);

        if (wrapper->JavascriptRootObjectWrapper != nullptr)
        {
            delete wrapper->JavascriptRootObjectWrapper;
            wrapper->JavascriptRootObjectWrapper = nullptr;
        }
    };

    CefBrowserWrapper^ CefAppUnmanagedWrapper::FindBrowserWrapper(int browserId, bool mustExist)
    {
        CefBrowserWrapper^ wrapper = nullptr;

        _browserWrappers->TryGetValue(browserId, wrapper);

        if (mustExist && wrapper == nullptr)
        {
            throw gcnew InvalidOperationException(String::Format("Failed to identify BrowserWrapper in OnContextCreated. : {0}", browserId));
        }

        return wrapper;
    }

    bool CefAppUnmanagedWrapper::OnProcessMessageReceived(CefRefPtr<CefBrowser> browser, CefProcessId sourceProcessId, CefRefPtr<CefProcessMessage> message)
    {
        auto handled = false;
        auto name = message->GetName();
        auto argList = message->GetArgumentList();

        auto browserWrapper = FindBrowserWrapper(browser->GetIdentifier(), false);

        //Error handling for missing/closed browser
        if (browserWrapper == nullptr)
        {
            if (name == kJavascriptCallbackDestroyRequest)
            {
                //If we can't find the browser wrapper then we'll just
                //ignore this as it's likely already been disposed of
                return true;
            }

            CefString responseName;
            if (name == kEvaluateJavascriptRequest)
            {
                responseName = kEvaluateJavascriptResponse;
            }
            else if (name == kJavascriptCallbackRequest)
            {
                responseName = kJavascriptCallbackResponse;
            }
            else
            {
                throw gcnew Exception("Unsupported message type");
            }

            auto callbackId = GetInt64(argList, 1);
            auto response = CefProcessMessage::Create(responseName);
            auto responseArgList = response->GetArgumentList();
            auto errorMessage = String::Format("Request BrowserId : {0} not found it's likely the browser is already closed", browser->GetIdentifier());

            //success: false
            responseArgList->SetBool(0, false);
            SetInt64(callbackId, responseArgList, 1);
            responseArgList->SetString(2, StringUtils::ToNative(errorMessage));
            browser->SendProcessMessage(sourceProcessId, response);

            return true;
        }

        //these messages are roughly handled the same way
        if (name == kEvaluateJavascriptRequest || name == kJavascriptCallbackRequest)
        {
            bool success;
            CefRefPtr<CefV8Value> result;
            CefString errorMessage;
            CefRefPtr<CefProcessMessage> response;
            //both messages have the callbackid stored at index 1
            int64 callbackId = GetInt64(argList, 1);

            if (name == kEvaluateJavascriptRequest)
            {
                auto frameId = GetInt64(argList, 0);
                auto script = argList->GetString(2);

                response = CefProcessMessage::Create(kEvaluateJavascriptResponse);

                auto frame = browser->GetFrame(frameId);
                if (frame.get())
                {
                    auto context = frame->GetV8Context();

                    if (context.get() && context->Enter())
                    {
                        try
                        {
                            CefRefPtr<CefV8Exception> exception;
                            success = context->Eval(script, result, exception);

                            //we need to do this here to be able to store the v8context
                            if (success)
                            {
                                auto responseArgList = response->GetArgumentList();
                                SerializeV8Object(result, responseArgList, 2, browserWrapper->CallbackRegistry);
                            }
                            else
                            {
                                errorMessage = exception->GetMessage();
                            }
                        }
                        finally
                        {
                            context->Exit();
                        }
                    }
                    else
                    {
                        errorMessage = "Unable to Enter Context";
                    }
                }
                else
                {
                    errorMessage = "Unable to Get Frame matching Id";
                }
            }
            else
            {
                auto jsCallbackId = GetInt64(argList, 0);
                auto parameterList = argList->GetList(2);
                CefV8ValueList params;
                for (CefV8ValueList::size_type i = 0; i < parameterList->GetSize(); i++)
                {
                    params.push_back(DeserializeV8Object(parameterList, static_cast<int>(i)));
                }

                response = CefProcessMessage::Create(kJavascriptCallbackResponse);

                auto callbackRegistry = browserWrapper->CallbackRegistry;
                auto callbackWrapper = callbackRegistry->FindWrapper(jsCallbackId);
                auto context = callbackWrapper->GetContext();
                auto value = callbackWrapper->GetValue();

                if (context.get() && context->Enter())
                {
                    try
                    {
                        result = value->ExecuteFunction(nullptr, params);
                        success = result.get() != nullptr;

                        //we need to do this here to be able to store the v8context
                        if (success)
                        {
                            auto responseArgList = response->GetArgumentList();
                            SerializeV8Object(result, responseArgList, 2, browserWrapper->CallbackRegistry);
                        }
                        else
                        {
                            auto exception = value->GetException();
                            if(exception.get())
                            {
                                errorMessage = exception->GetMessage();
                            }
                        }
                    }
                    finally
                    {
                        context->Exit();
                    }
                }
                else
                {
                    errorMessage = "Unable to Enter Context";
                }
            }

            if (response.get())
            {
                auto responseArgList = response->GetArgumentList();
                responseArgList->SetBool(0, success);
                SetInt64(callbackId, responseArgList, 1);
                if (!success)
                {
                    responseArgList->SetString(2, errorMessage);
                }
                browser->SendProcessMessage(sourceProcessId, response);
            }

            handled = true;
        }
        else if (name == kJavascriptCallbackDestroyRequest)
        {
            auto jsCallbackId = GetInt64(argList, 1);
            browserWrapper->CallbackRegistry->Deregister(jsCallbackId);

            handled = true;
        }

        return handled;
    };
}<commit_msg>Add TODO about throwing exception in CefAppUnmanagedWrapper<commit_after>// Copyright © 2010-2015 The CefSharp Project. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
#pragma once

#include "Stdafx.h"

#include "CefBrowserWrapper.h"
#include "CefAppUnmanagedWrapper.h"
#include "JavascriptRootObjectWrapper.h"
#include "Serialization\V8Serialization.h"
#include "..\CefSharp.Core\Internals\Messaging\Messages.h"
#include "..\CefSharp.Core\Internals\Serialization\Primitives.h"

using namespace System;
using namespace System::Diagnostics;
using namespace System::Collections::Generic;
using namespace CefSharp::Internals::Messaging;
using namespace CefSharp::Internals::Serialization;

namespace CefSharp
{
    CefRefPtr<CefRenderProcessHandler> CefAppUnmanagedWrapper::GetRenderProcessHandler()
    {
        return this;
    };

    // CefRenderProcessHandler
    void CefAppUnmanagedWrapper::OnBrowserCreated(CefRefPtr<CefBrowser> browser)
    {
        auto wrapper = gcnew CefBrowserWrapper(browser);
        _onBrowserCreated->Invoke(wrapper);

        //Multiple CefBrowserWrappers created when opening popups
        _browserWrappers->Add(browser->GetIdentifier(), wrapper);
    }

    void CefAppUnmanagedWrapper::OnBrowserDestroyed(CefRefPtr<CefBrowser> browser)
    {
        auto wrapper = FindBrowserWrapper(browser->GetIdentifier(), false);

        if (wrapper != nullptr)
        {
            _browserWrappers->Remove(wrapper->BrowserId);
            _onBrowserDestroyed->Invoke(wrapper);
            delete wrapper;
        }
    };

    void CefAppUnmanagedWrapper::OnContextCreated(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, CefRefPtr<CefV8Context> context)
    {
        auto wrapper = FindBrowserWrapper(browser->GetIdentifier(), true);

        if (wrapper->JavascriptRootObject != nullptr)
        {
            auto window = context->GetGlobal();

            wrapper->JavascriptRootObjectWrapper = gcnew JavascriptRootObjectWrapper(wrapper->JavascriptRootObject, wrapper->BrowserProcess);

            wrapper->JavascriptRootObjectWrapper->V8Value = window;
            wrapper->JavascriptRootObjectWrapper->Bind();
        }
    };

    void CefAppUnmanagedWrapper::OnContextReleased(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, CefRefPtr<CefV8Context> context)
    {
        auto wrapper = FindBrowserWrapper(browser->GetIdentifier(), true);

        if (wrapper->JavascriptRootObjectWrapper != nullptr)
        {
            delete wrapper->JavascriptRootObjectWrapper;
            wrapper->JavascriptRootObjectWrapper = nullptr;
        }
    };

    CefBrowserWrapper^ CefAppUnmanagedWrapper::FindBrowserWrapper(int browserId, bool mustExist)
    {
        CefBrowserWrapper^ wrapper = nullptr;

        _browserWrappers->TryGetValue(browserId, wrapper);

        if (mustExist && wrapper == nullptr)
        {
            throw gcnew InvalidOperationException(String::Format("Failed to identify BrowserWrapper in OnContextCreated. : {0}", browserId));
        }

        return wrapper;
    }

    bool CefAppUnmanagedWrapper::OnProcessMessageReceived(CefRefPtr<CefBrowser> browser, CefProcessId sourceProcessId, CefRefPtr<CefProcessMessage> message)
    {
        auto handled = false;
        auto name = message->GetName();
        auto argList = message->GetArgumentList();

        auto browserWrapper = FindBrowserWrapper(browser->GetIdentifier(), false);

        //Error handling for missing/closed browser
        if (browserWrapper == nullptr)
        {
            if (name == kJavascriptCallbackDestroyRequest)
            {
                //If we can't find the browser wrapper then we'll just
                //ignore this as it's likely already been disposed of
                return true;
            }

            CefString responseName;
            if (name == kEvaluateJavascriptRequest)
            {
                responseName = kEvaluateJavascriptResponse;
            }
            else if (name == kJavascriptCallbackRequest)
            {
                responseName = kJavascriptCallbackResponse;
            }
            else
            {
                //TODO: Should be throw an exception here? It's likely that only a CefSharp developer would see this
                // when they added a new message and havn't yet implemented the render process functionality.
                throw gcnew Exception("Unsupported message type");
            }

            auto callbackId = GetInt64(argList, 1);
            auto response = CefProcessMessage::Create(responseName);
            auto responseArgList = response->GetArgumentList();
            auto errorMessage = String::Format("Request BrowserId : {0} not found it's likely the browser is already closed", browser->GetIdentifier());

            //success: false
            responseArgList->SetBool(0, false);
            SetInt64(callbackId, responseArgList, 1);
            responseArgList->SetString(2, StringUtils::ToNative(errorMessage));
            browser->SendProcessMessage(sourceProcessId, response);

            return true;
        }

        //these messages are roughly handled the same way
        if (name == kEvaluateJavascriptRequest || name == kJavascriptCallbackRequest)
        {
            bool success;
            CefRefPtr<CefV8Value> result;
            CefString errorMessage;
            CefRefPtr<CefProcessMessage> response;
            //both messages have the callbackid stored at index 1
            int64 callbackId = GetInt64(argList, 1);

            if (name == kEvaluateJavascriptRequest)
            {
                auto frameId = GetInt64(argList, 0);
                auto script = argList->GetString(2);

                response = CefProcessMessage::Create(kEvaluateJavascriptResponse);

                auto frame = browser->GetFrame(frameId);
                if (frame.get())
                {
                    auto context = frame->GetV8Context();

                    if (context.get() && context->Enter())
                    {
                        try
                        {
                            CefRefPtr<CefV8Exception> exception;
                            success = context->Eval(script, result, exception);

                            //we need to do this here to be able to store the v8context
                            if (success)
                            {
                                auto responseArgList = response->GetArgumentList();
                                SerializeV8Object(result, responseArgList, 2, browserWrapper->CallbackRegistry);
                            }
                            else
                            {
                                errorMessage = exception->GetMessage();
                            }
                        }
                        finally
                        {
                            context->Exit();
                        }
                    }
                    else
                    {
                        errorMessage = "Unable to Enter Context";
                    }
                }
                else
                {
                    errorMessage = "Unable to Get Frame matching Id";
                }
            }
            else
            {
                auto jsCallbackId = GetInt64(argList, 0);
                auto parameterList = argList->GetList(2);
                CefV8ValueList params;
                for (CefV8ValueList::size_type i = 0; i < parameterList->GetSize(); i++)
                {
                    params.push_back(DeserializeV8Object(parameterList, static_cast<int>(i)));
                }

                response = CefProcessMessage::Create(kJavascriptCallbackResponse);

                auto callbackRegistry = browserWrapper->CallbackRegistry;
                auto callbackWrapper = callbackRegistry->FindWrapper(jsCallbackId);
                auto context = callbackWrapper->GetContext();
                auto value = callbackWrapper->GetValue();

                if (context.get() && context->Enter())
                {
                    try
                    {
                        result = value->ExecuteFunction(nullptr, params);
                        success = result.get() != nullptr;

                        //we need to do this here to be able to store the v8context
                        if (success)
                        {
                            auto responseArgList = response->GetArgumentList();
                            SerializeV8Object(result, responseArgList, 2, browserWrapper->CallbackRegistry);
                        }
                        else
                        {
                            auto exception = value->GetException();
                            if(exception.get())
                            {
                                errorMessage = exception->GetMessage();
                            }
                        }
                    }
                    finally
                    {
                        context->Exit();
                    }
                }
                else
                {
                    errorMessage = "Unable to Enter Context";
                }
            }

            if (response.get())
            {
                auto responseArgList = response->GetArgumentList();
                responseArgList->SetBool(0, success);
                SetInt64(callbackId, responseArgList, 1);
                if (!success)
                {
                    responseArgList->SetString(2, errorMessage);
                }
                browser->SendProcessMessage(sourceProcessId, response);
            }

            handled = true;
        }
        else if (name == kJavascriptCallbackDestroyRequest)
        {
            auto jsCallbackId = GetInt64(argList, 1);
            browserWrapper->CallbackRegistry->Deregister(jsCallbackId);

            handled = true;
        }

        return handled;
    };
}<|endoftext|>


<commit_before>#ifndef __AIDA_CXXSTUB_CLIENT_CC__
#define __AIDA_CXXSTUB_CLIENT_CC__

#include <semaphore.h>

namespace { // Anon

namespace __AIDA_Local__ {
using namespace Aida;

static inline sem_t*
thread_semaphore()
{
  class DeletableSemaphore {
    DeletableSemaphore (const DeletableSemaphore&) = delete;            // disable copy ctor
    DeletableSemaphore& operator= (const DeletableSemaphore&) = delete; // disable copy assignment
  public:
    sem_t semaphore = sem_t();
    DeletableSemaphore()
    {
      const int ret = sem_init (&semaphore, 0 /*pshared*/, 0 /*value*/);
      AIDA_ASSERT_RETURN (ret == 0);
    }
    ~DeletableSemaphore()
    {
      sem_destroy (&semaphore);
    }
  };
  static thread_local DeletableSemaphore thread_local_semaphore;
  return &thread_local_semaphore.semaphore;
}

template<class T, class... I, class... A> void
remote_callv (Aida::RemoteHandle &h, void (T::*const mfp) (I...), A... args)
{
  sem_t *const semp = thread_semaphore();
  T *const self = dynamic_cast<T*> (h.__iface_ptr__().get());
  std::function<void()> wrapper = [semp, self, mfp, &args...] () {
    (self->*mfp) (args...);
    sem_post (semp);
  };
  self->__execution_context_mt__()->enqueue_mt (&wrapper);
  sem_wait (semp);
}

template<class T, class R, class... I, class... A> R
remote_callr (Aida::RemoteHandle &h, R (T::*const mfp) (I...), A... args)
{
  sem_t *const semp = thread_semaphore();
  T *const self = dynamic_cast<T*> (h.__iface_ptr__().get());
  R r {};
  std::function<void()> wrapper = [semp, self, mfp, &args..., &r] () {
    r = (self->*mfp) (args...);
    sem_post (semp);
  };
  self->__execution_context_mt__()->enqueue_mt (&wrapper);
  sem_wait (semp);
  return r;
}

template<class T, class R, class... I, class... A> R
remote_callc (const Aida::RemoteHandle &h, R (T::*const mfp) (I...) const, A... args)
{
  sem_t *const semp = thread_semaphore();
  T *const self = dynamic_cast<T*> (const_cast<Aida::RemoteHandle&> (h).__iface_ptr__().get());
  R r {};
  std::function<void()> wrapper = [semp, self, mfp, &args..., &r] () {
    r = (self->*mfp) (args...);
    sem_post (semp);
  };
  self->__execution_context_mt__()->enqueue_mt (&wrapper);
  sem_wait (semp);
  return r;
}

// helper
static inline ProtoMsg*
new_emit_result (const ProtoMsg *fb, uint64 h, uint64 l, uint32 n)
{
  return ProtoMsg::renew_into_result (const_cast<ProtoMsg*> (fb), Aida::MSGID_EMIT_RESULT, h, l, n);
}

} } // Anon::__AIDA_Local__

#endif // __AIDA_CXXSTUB_CLIENT_CC__
<commit_msg>AIDACC: CxxStub-client: remote_call*(): avoid copying instances<commit_after>#ifndef __AIDA_CXXSTUB_CLIENT_CC__
#define __AIDA_CXXSTUB_CLIENT_CC__

#include <semaphore.h>

namespace { // Anon

namespace __AIDA_Local__ {
using namespace Aida;

static inline sem_t*
thread_semaphore()
{
  class DeletableSemaphore {
    DeletableSemaphore (const DeletableSemaphore&) = delete;            // disable copy ctor
    DeletableSemaphore& operator= (const DeletableSemaphore&) = delete; // disable copy assignment
  public:
    sem_t semaphore = sem_t();
    DeletableSemaphore()
    {
      const int ret = sem_init (&semaphore, 0 /*pshared*/, 0 /*value*/);
      AIDA_ASSERT_RETURN (ret == 0);
    }
    ~DeletableSemaphore()
    {
      sem_destroy (&semaphore);
    }
  };
  static thread_local DeletableSemaphore thread_local_semaphore;
  return &thread_local_semaphore.semaphore;
}

template<class T, class... I, class... A> void
remote_callv (Aida::RemoteHandle &h, void (T::*const mfp) (I...), A&... args)
{
  sem_t *const semp = thread_semaphore();
  T *const self = dynamic_cast<T*> (h.__iface_ptr__().get());
  std::function<void()> wrapper = [semp, self, mfp, &args...] () {
    (self->*mfp) (args...);
    sem_post (semp);
  };
  self->__execution_context_mt__()->enqueue_mt (&wrapper);
  sem_wait (semp);
}

template<class T, class R, class... I, class... A> R
remote_callr (Aida::RemoteHandle &h, R (T::*const mfp) (I...), A&... args)
{
  sem_t *const semp = thread_semaphore();
  T *const self = dynamic_cast<T*> (h.__iface_ptr__().get());
  R r {};
  std::function<void()> wrapper = [semp, self, mfp, &args..., &r] () {
    r = (self->*mfp) (args...);
    sem_post (semp);
  };
  self->__execution_context_mt__()->enqueue_mt (&wrapper);
  sem_wait (semp);
  return r;
}

template<class T, class R, class... I, class... A> R
remote_callc (const Aida::RemoteHandle &h, R (T::*const mfp) (I...) const, A&... args)
{
  sem_t *const semp = thread_semaphore();
  T *const self = dynamic_cast<T*> (const_cast<Aida::RemoteHandle&> (h).__iface_ptr__().get());
  R r {};
  std::function<void()> wrapper = [semp, self, mfp, &args..., &r] () {
    r = (self->*mfp) (args...);
    sem_post (semp);
  };
  self->__execution_context_mt__()->enqueue_mt (&wrapper);
  sem_wait (semp);
  return r;
}

// helper
static inline ProtoMsg*
new_emit_result (const ProtoMsg *fb, uint64 h, uint64 l, uint32 n)
{
  return ProtoMsg::renew_into_result (const_cast<ProtoMsg*> (fb), Aida::MSGID_EMIT_RESULT, h, l, n);
}

} } // Anon::__AIDA_Local__

#endif // __AIDA_CXXSTUB_CLIENT_CC__
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.
 */

#include <base/logging.h>
#include <io/event_manager.h>
#include <tbb/task.h>
#include <base/task.h>

#include <boost/shared_ptr.hpp>

#include "cfg/cfg_init.h"
#include "cfg/cfg_interface.h"
#include "oper/operdb_init.h"
#include "controller/controller_init.h"
#include "pkt/pkt_init.h"
#include "services/services_init.h"
#include "ksync/ksync_init.h"
#include "oper/agent_route_walker.h"
#include "openstack/instance_service_server.h"
#include "test_cmn_util.h"
#include "kstate/test/test_kstate_util.h"
#include "vr_types.h"

using namespace std;

void RouterIdDepInit() {
}

static void ValidateSandeshResponse(Sandesh *sandesh, vector<int> &result) {
    //TBD
    //Validate the response by the expectation
}

struct PortInfo input_1[] = {
    {"vnet1", 1, "1.1.1.10", "00:00:01:01:01:10", 1, 1},
};

struct PortInfo input_2[] = {
    {"vnet2", 2, "2.2.2.20", "00:00:02:02:02:20", 2, 2},
};

class AgentRouteWalkerTest : public AgentRouteWalker, public ::testing::Test {
public:
    AgentRouteWalkerTest() : AgentRouteWalker(AgentRouteWalker::ALL),
    default_tunnel_type_(TunnelType::MPLS_GRE) {
        vrf_name_1_ = "vrf1";
        vrf_name_2_ = "vrf2";
        server_ip_ = Ip4Address::from_string("10.1.1.11");
        local_vm_ip_1_ = Ip4Address::from_string("1.1.1.10");
        local_vm_ip_2_ = Ip4Address::from_string("2.2.2.20");
        remote_vm_ip_ = Ip4Address::from_string("1.1.1.11");
        local_vm_mac_1_ = (struct ether_addr *)malloc(sizeof(struct ether_addr));
        local_vm_mac_2_ = (struct ether_addr *)malloc(sizeof(struct ether_addr));
        remote_vm_mac_ = (struct ether_addr *)malloc(sizeof(struct ether_addr));
        memcpy (local_vm_mac_1_, ether_aton("00:00:01:01:01:10"),
                sizeof(struct ether_addr));
        memcpy (local_vm_mac_2_, ether_aton("00:00:02:02:02:20"),
                sizeof(struct ether_addr));
        memcpy (remote_vm_mac_, ether_aton("00:00:01:01:01:11"),
                sizeof(struct ether_addr));
        route_notifications_ = 0;
        vrf_notifications_ = vrf_notifications_count_ = 0;
        total_rt_vrf_walk_done_ = 0;
    };
    ~AgentRouteWalkerTest() { };

    virtual void SetUp() {
        client->Reset();
        VxLanNetworkIdentifierMode(false);
        client->WaitForIdle();
        AddEncapList("MPLSoGRE", "MPLSoUDP", "VXLAN");
        client->WaitForIdle();

        //Create a VRF
        VrfAddReq(vrf_name_1_.c_str());
        VrfAddReq(vrf_name_2_.c_str());
        Agent::GetInstance()->GetDefaultInet4UnicastRouteTable()->AddResolveRoute(
                Agent::GetInstance()->GetDefaultVrf(), server_ip_, 24);
        client->WaitForIdle();
        client->WaitForIdle();
        CreateVmportEnv(input_1, 1);
        CreateVmportEnv(input_2, 1);
        client->WaitForIdle();
        client->Reset();
    }

    virtual void TearDown() {
        client->Reset();
        DeleteVmportEnv(input_1, 1, true);
        DeleteVmportEnv(input_2, 1, true);
        client->WaitForIdle();
        DelEncapList();
        client->WaitForIdle();

        VrfDelReq(vrf_name_1_.c_str());
        VrfDelReq(vrf_name_2_.c_str());
        client->WaitForIdle();
        WAIT_FOR(100, 100, (VrfFind(vrf_name_1_.c_str()) != true));
        WAIT_FOR(100, 100, (VrfFind(vrf_name_2_.c_str()) != true));
    }

    virtual bool RouteWalkNotify(DBTablePartBase *partition, DBEntryBase *e) {
        //Fabric VRF
        //0.0.0.0/32; 10.1.1.0/24; 10.1.1.1/32; 10.1.1.254/3; 10.1.1.255/32;
        //169.254.1.3/32; 169.254.2.4/32; 255.255.255.255
        //vrf1
        //1.1.1.10/32; 255.255.255.255; 0:0:1:1:1:10; ff:ff:ff:ff:ff:ff
        //vrf2
        //2.2.2.20/32; 255.255.255.255; 0:0:2:2:2:20; ff:ff:ff:ff:ff:ff
        route_notifications_++;
        return true;
    }

    virtual void RouteWalkDone(DBTableBase *part) {
        total_rt_vrf_walk_done_++;
    }

    virtual bool VrfWalkNotify(DBTablePartBase *partition, DBEntryBase *e) {
        vrf_notifications_++;
        VrfEntry *vrf = static_cast<VrfEntry *>(e);
        StartRouteWalk(vrf);
        return true;
    }

    virtual void VrfWalkDone(DBTableBase *part) {
        vrf_notifications_count_++;
    }

    void VerifyNotifications(uint32_t route_notifications,
                             uint32_t vrf_notifications,
                             uint32_t vrf_notifications_count,
                             uint32_t total_rt_vrf_walk_done) {
        client->WaitForIdle(10);
        WAIT_FOR(100, 1000, (route_notifications_ == route_notifications_));
        ASSERT_TRUE(route_notifications_ == route_notifications);
        ASSERT_TRUE(vrf_notifications_ == vrf_notifications);
        ASSERT_TRUE(vrf_notifications_count_ == vrf_notifications_count);
        ASSERT_TRUE(total_rt_vrf_walk_done_ == total_rt_vrf_walk_done);
    }

    TunnelType::Type default_tunnel_type_;
    std::string vrf_name_1_;
    std::string vrf_name_2_;
    Ip4Address  local_vm_ip_1_;
    Ip4Address  local_vm_ip_2_;
    Ip4Address  remote_vm_ip_;
    Ip4Address  server_ip_;
    struct ether_addr *local_vm_mac_1_;
    struct ether_addr *local_vm_mac_2_;
    struct ether_addr *remote_vm_mac_;
    static TunnelType::Type type_;
    uint32_t route_notifications_;
    uint32_t vrf_notifications_;
    uint32_t vrf_notifications_count_;
    uint32_t total_rt_vrf_walk_done_;
    RouteTableTypeWalkid route_table_type_walkid_;
};

TEST_F(AgentRouteWalkerTest, walk_all_routes) {
    client->Reset();
    StartVrfWalk();
    VerifyNotifications(16, 3, 1, 9);
}

int main(int argc, char **argv) {
    GETUSERARGS();

    client = TestInit(init_file, ksync_init);
    int ret = RUN_ALL_TESTS();
    client->WaitForIdle();
    TestShutdown();
    delete client;
    return ret;
}
<commit_msg>fix test case<commit_after>/*
 * Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.
 */

#include <base/logging.h>
#include <io/event_manager.h>
#include <tbb/task.h>
#include <base/task.h>

#include <boost/shared_ptr.hpp>

#include "cfg/cfg_init.h"
#include "cfg/cfg_interface.h"
#include "oper/operdb_init.h"
#include "controller/controller_init.h"
#include "pkt/pkt_init.h"
#include "services/services_init.h"
#include "ksync/ksync_init.h"
#include "oper/agent_route_walker.h"
#include "openstack/instance_service_server.h"
#include "test_cmn_util.h"
#include "kstate/test/test_kstate_util.h"
#include "vr_types.h"

using namespace std;

void RouterIdDepInit() {
}

static void ValidateSandeshResponse(Sandesh *sandesh, vector<int> &result) {
    //TBD
    //Validate the response by the expectation
}

struct PortInfo input_1[] = {
    {"vnet1", 1, "1.1.1.10", "00:00:01:01:01:10", 1, 1},
};

struct PortInfo input_2[] = {
    {"vnet2", 2, "2.2.2.20", "00:00:02:02:02:20", 2, 2},
};

class AgentRouteWalkerTest : public AgentRouteWalker, public ::testing::Test {
public:
    AgentRouteWalkerTest() : AgentRouteWalker(AgentRouteWalker::ALL),
    default_tunnel_type_(TunnelType::MPLS_GRE) {
        vrf_name_1_ = "vrf1";
        vrf_name_2_ = "vrf2";
        server_ip_ = Ip4Address::from_string("10.1.1.11");
        local_vm_ip_1_ = Ip4Address::from_string("1.1.1.10");
        local_vm_ip_2_ = Ip4Address::from_string("2.2.2.20");
        remote_vm_ip_ = Ip4Address::from_string("1.1.1.11");
        local_vm_mac_1_ = (struct ether_addr *)malloc(sizeof(struct ether_addr));
        local_vm_mac_2_ = (struct ether_addr *)malloc(sizeof(struct ether_addr));
        remote_vm_mac_ = (struct ether_addr *)malloc(sizeof(struct ether_addr));
        memcpy (local_vm_mac_1_, ether_aton("00:00:01:01:01:10"),
                sizeof(struct ether_addr));
        memcpy (local_vm_mac_2_, ether_aton("00:00:02:02:02:20"),
                sizeof(struct ether_addr));
        memcpy (remote_vm_mac_, ether_aton("00:00:01:01:01:11"),
                sizeof(struct ether_addr));
        route_notifications_ = 0;
        vrf_notifications_ = vrf_notifications_count_ = 0;
        total_rt_vrf_walk_done_ = 0;
    };
    ~AgentRouteWalkerTest() { };

    virtual void SetUp() {
        client->Reset();
        VxLanNetworkIdentifierMode(false);
        client->WaitForIdle();
        AddEncapList("MPLSoGRE", "MPLSoUDP", "VXLAN");
        client->WaitForIdle();

        //Create a VRF
        VrfAddReq(vrf_name_1_.c_str());
        VrfAddReq(vrf_name_2_.c_str());
        Agent::GetInstance()->GetDefaultInet4UnicastRouteTable()->AddResolveRoute(
                Agent::GetInstance()->GetDefaultVrf(), server_ip_, 24);
        client->WaitForIdle();
        client->WaitForIdle();
        CreateVmportEnv(input_1, 1);
        CreateVmportEnv(input_2, 1);
        client->WaitForIdle();
        client->Reset();
    }

    virtual void TearDown() {
        client->Reset();
        DeleteVmportEnv(input_1, 1, true);
        DeleteVmportEnv(input_2, 1, true);
        client->WaitForIdle();
        DelEncapList();
        client->WaitForIdle();

        VrfDelReq(vrf_name_1_.c_str());
        VrfDelReq(vrf_name_2_.c_str());
        client->WaitForIdle();
        WAIT_FOR(100, 100, (VrfFind(vrf_name_1_.c_str()) != true));
        WAIT_FOR(100, 100, (VrfFind(vrf_name_2_.c_str()) != true));
    }

    virtual bool RouteWalkNotify(DBTablePartBase *partition, DBEntryBase *e) {
        //Fabric VRF
        //0.0.0.0/32; 10.1.1.0/24; 10.1.1.1/32; 10.1.1.254/3; 10.1.1.255/32;
        //169.254.1.3/32; 169.254.2.4/32; 255.255.255.255
        //vrf1
        //1.1.1.10/32; 255.255.255.255; 0:0:1:1:1:10; ff:ff:ff:ff:ff:ff
        //vrf2
        //2.2.2.20/32; 255.255.255.255; 0:0:2:2:2:20; ff:ff:ff:ff:ff:ff
        route_notifications_++;
        return true;
    }

    virtual void RouteWalkDone(DBTableBase *part) {
        total_rt_vrf_walk_done_++;
    }

    virtual bool VrfWalkNotify(DBTablePartBase *partition, DBEntryBase *e) {
        vrf_notifications_++;
        VrfEntry *vrf = static_cast<VrfEntry *>(e);
        StartRouteWalk(vrf);
        return true;
    }

    virtual void VrfWalkDone(DBTableBase *part) {
        vrf_notifications_count_++;
    }

    void VerifyNotifications(uint32_t route_notifications,
                             uint32_t vrf_notifications,
                             uint32_t vrf_notifications_count,
                             uint32_t total_rt_vrf_walk_done) {
        client->WaitForIdle(10);
        WAIT_FOR(100, 1000, (route_notifications_ == route_notifications_));
        ASSERT_TRUE(route_notifications_ == route_notifications);
        ASSERT_TRUE(vrf_notifications_ == vrf_notifications);
        ASSERT_TRUE(vrf_notifications_count_ == vrf_notifications_count);
        ASSERT_TRUE(total_rt_vrf_walk_done_ == total_rt_vrf_walk_done);
    }

    TunnelType::Type default_tunnel_type_;
    std::string vrf_name_1_;
    std::string vrf_name_2_;
    Ip4Address  local_vm_ip_1_;
    Ip4Address  local_vm_ip_2_;
    Ip4Address  remote_vm_ip_;
    Ip4Address  server_ip_;
    struct ether_addr *local_vm_mac_1_;
    struct ether_addr *local_vm_mac_2_;
    struct ether_addr *remote_vm_mac_;
    static TunnelType::Type type_;
    uint32_t route_notifications_;
    uint32_t vrf_notifications_;
    uint32_t vrf_notifications_count_;
    uint32_t total_rt_vrf_walk_done_;
    RouteWalkerIdList route_table_type_walkid_;
};

TEST_F(AgentRouteWalkerTest, walk_all_routes) {
    client->Reset();
    StartVrfWalk();
    VerifyNotifications(16, 3, 1, 9);
}

int main(int argc, char **argv) {
    GETUSERARGS();

    client = TestInit(init_file, ksync_init);
    int ret = RUN_ALL_TESTS();
    client->WaitForIdle();
    TestShutdown();
    delete client;
    return ret;
}
<|endoftext|>


<commit_before><commit_msg>Modern loop<commit_after><|endoftext|>


<commit_before>//
//
// C++ Implementation: $MODULE$
//
// Description:
//
//
// Author: sven <sven@ares>, (C) 2003
//
// Copyright: See COPYING file that comes with this distribution
//
//

#include "CMetabNameInterface.h"

#include "report/CCopasiContainer.h"
#include "model/CModel.h"
#include "report/CKeyFactory.h"
//#include "utilities/CCopasiVector.h"

std::string CMetabNameInterface::empty_string = "";

CMetabNameInterface::~CMetabNameInterface()
{}

const std::string & CMetabNameInterface::getDisplayName(const CModel* model, const std::string & key)
{
  CMetab * metab = (CMetab*)(CCopasiContainer*)CKeyFactory::get(key);
  if (metab)
    return getDisplayName(model, *metab);
  else
    return empty_string;
}

const std::string & CMetabNameInterface::getDisplayName(const CModel* model, const CMetab & metab)
{
  return metab.getName();
}

std::string CMetabNameInterface::getMetaboliteKey(const CModel* model, const std::string & name)
{
  CMetab * metab = getMetabolite(model, name);
  if (metab)
    return metab->getKey();
  else
    return empty_string;
}

CMetab * CMetabNameInterface::getMetabolite(const CModel* model, const std::string & name)
{
  C_INT32 index = model->findMetabByName(name);
  if (index == -1)
    return NULL;
  else
    return model->getMetabolites()[index];
}

bool CMetabNameInterface::isUnique(const CModel* model, const std::string & name)
{
  bool unique = true;
  unsigned C_INT32 i;
  CCopasiVector< CMetab > metabs = model->getMetabolites();
  std::string metabName;

  for (i = 0; i < metabs.size(); i++)
    {
      metabName = metabs[i]->getName();
      if (metabName == name)
        {
          if (unique)
            unique = false;
          else
            return true;
        }
    }

  return unique;
}

bool CMetabNameInterface::doesExist(const CModel* model, const std::string & name)
{
  C_INT32 pos = name.find('{'), i;
  CCompartment *comp;
  CCopasiVectorNS<CMetab> metabs;

  if (pos >= 0)    //compartment specified, so check if the metabolite exists in this compartment
    {
      if (!pos)
        return false;

      std::string metabName = name. substr(0, pos), s;
      C_INT32 len = name.find('}') - pos - 1;

      C_INT32 index = model -> findCompartment(name.substr(pos + 1, len));
      if (index < 0)   // the specified compartment does not exist
        return false;

      comp = (model->getCompartments())[index];
      metabs = comp->getMetabolites();

      for (i = 0; i < metabs.size(); i++)
        {
          s = metabs[i]->getName();
          if (s == metabName)
            return true;
        }

      return false;
    }
  else
    //model->findMetab returns -1 if the metabolite is not found and a non-negative integer otherwise
    return (model->findMetabByName(name) + 1);
}

std::string CMetabNameInterface::extractCompartmentName(const CModel* model, const std::string & name)
{
  // name is expected to be in the format of "metabolite{compartment}" or simply "metabolite"
  C_INT32 pos1 = name.find('{'), pos2;
  const CCompartment *comp;

  if (pos1 > 0)  // extract the compartment name from the string if specified
    {
      pos2 = name.find('}');
      return name.substr(pos1 + 1, pos2 - pos1 - 1);
    }
  else
    {
      CCopasiVector< CMetab > metabs = model->getMetabolites();
      C_INT32 index = model->findMetabByName(name);

      if (index < 0)  // the metabolite doesn't exist, so return the first compartment of the model
        {
          CCopasiVectorNS< CCompartment > comps = model->getCompartments();
          comp = comps[0];
          return comp->getName();
        }
      else  //return the first compartment where the metabolite is present
        {
          CMetab *metb = metabs[index];
          comp = metb->getCompartment();
          return comp->getName();
        }
    }
}

std::string CMetabNameInterface::extractMetabName(const CModel* model, const std::string & name)
{
  // name is expected to be in the format of "metabolite{compartment}" or simply "metabolite"
  C_INT32 namelength = name.find('{');

  if (namelength >= 0) // compartment is specified, so strip that off
    return name.substr(0, namelength);
  else  //compartment is not specified
    return name;
}

bool CMetabNameInterface::isValidMetabName(const std::string name)
{
  // a valid name does not contain white spaces, and contains either matching or no curly braces
  C_INT32 pos1, pos2, pos3;

  // make sure the name is not an empty string
  unsigned C_INT32 len = name.length();
  if (len < 1)
    return false;

  // check for white spaces
  pos1 = name.find(" ");
  if (pos1 >= 0)
    return false;

  // curly braces: '{' is not the first character in the string, and appears before '}'
  // if present, '}' should be the last character in the string
  pos1 = name.find('{');
  pos2 = name.find('}');
  pos3 = name.rfind('{');

  // ok if no braces appear
  if ((pos1 < 0) && (pos2 < 0))
    return true;

  // ok  if only one '{' and one '}', braces match, compartment name is not an empty string, and '}' is the last character
  if ((pos1 > 0) && (pos1 == pos3) && (pos2 > pos1 + 1) && (pos2 + 1 == len))
    return true;

  // otherwise the name is not valid
  return false;
}
<commit_msg>implemented the getMetab() method.<commit_after>//
//
// C++ Implementation: $MODULE$
//
// Description:
//
//
// Author: sven <sven@ares>, (C) 2003
//
// Copyright: See COPYING file that comes with this distribution
//
//

#include "CMetabNameInterface.h"

#include "report/CCopasiContainer.h"
#include "model/CModel.h"
#include "report/CKeyFactory.h"
//#include "utilities/CCopasiVector.h"

std::string CMetabNameInterface::empty_string = "";

CMetabNameInterface::~CMetabNameInterface()
{}

const std::string & CMetabNameInterface::getDisplayName(const CModel* model, const std::string & key)
{
  CMetab * metab = (CMetab*)(CCopasiContainer*)CKeyFactory::get(key);
  if (metab)
    return getDisplayName(model, *metab);
  else
    return empty_string;
}

const std::string & CMetabNameInterface::getDisplayName(const CModel* model, const CMetab & metab)
{
  return metab.getName();
}

std::string CMetabNameInterface::getMetaboliteKey(const CModel* model, const std::string & name)
{
  CMetab * metab = getMetabolite(model, name);
  if (metab)
    return metab->getKey();
  else
    return empty_string;
}

CMetab * CMetabNameInterface::getMetabolite(const CModel* model, const std::string & name)
{
  C_INT32 pos = name.find('{');

  if (pos >= 0)
    {
      std::string metabName = CMetabNameInterface::extractMetabName(model, name);
      std::string compName = CMetabNameInterface::extractCompartmentName(model, name);
      return (model->getCompartments()[compName])->getMetabolites()[metabName];
    }
  else
    {
      C_INT32 index = model->findMetabByName(name);
      if (index == -1)
        return NULL;
      else
        return model->getMetabolites()[index];
    }

  std::string metabName = CMetabNameInterface::extractMetabName(model, name);
  C_INT32 index = model->findMetabByName(name);
  if (index == -1)
    return NULL;
  else
    return model->getMetabolites()[index];
}

bool CMetabNameInterface::isUnique(const CModel* model, const std::string & name)
{
  bool unique = true;
  unsigned C_INT32 i;
  CCopasiVector< CMetab > metabs = model->getMetabolites();
  std::string metabName;

  for (i = 0; i < metabs.size(); i++)
    {
      metabName = metabs[i]->getName();
      if (metabName == name)
        {
          if (unique)
            unique = false;
          else
            return true;
        }
    }

  return unique;
}

bool CMetabNameInterface::doesExist(const CModel* model, const std::string & name)
{
  C_INT32 pos = name.find('{'), i;
  CCompartment *comp;
  CCopasiVectorNS<CMetab> metabs;

  if (pos >= 0)    //compartment specified, so check if the metabolite exists in this compartment
    {
      if (!pos)
        return false;

      std::string metabName = name. substr(0, pos), s;
      C_INT32 len = name.find('}') - pos - 1;

      C_INT32 index = model -> findCompartment(name.substr(pos + 1, len));
      if (index < 0)   // the specified compartment does not exist
        return false;

      comp = (model->getCompartments())[index];
      metabs = comp->getMetabolites();

      for (i = 0; i < metabs.size(); i++)
        {
          s = metabs[i]->getName();
          if (s == metabName)
            return true;
        }

      return false;
    }
  else
    //model->findMetab returns -1 if the metabolite is not found and a non-negative integer otherwise
    return (model->findMetabByName(name) + 1);
}

std::string CMetabNameInterface::extractCompartmentName(const CModel* model, const std::string & name)
{
  // name is expected to be in the format of "metabolite{compartment}" or simply "metabolite"
  C_INT32 pos1 = name.find('{'), pos2;
  const CCompartment *comp;

  if (pos1 > 0)  // extract the compartment name from the string if specified
    {
      pos2 = name.find('}');
      return name.substr(pos1 + 1, pos2 - pos1 - 1);
    }
  else
    {
      CCopasiVector< CMetab > metabs = model->getMetabolites();
      C_INT32 index = model->findMetabByName(name);

      if (index < 0)  // the metabolite doesn't exist, so return the first compartment of the model
        {
          CCopasiVectorNS< CCompartment > comps = model->getCompartments();
          comp = comps[0];
          return comp->getName();
        }
      else  //return the first compartment where the metabolite is present
        {
          CMetab *metb = metabs[index];
          comp = metb->getCompartment();
          return comp->getName();
        }
    }
}

std::string CMetabNameInterface::extractMetabName(const CModel* model, const std::string & name)
{
  // name is expected to be in the format of "metabolite{compartment}" or simply "metabolite"
  C_INT32 namelength = name.find('{');

  if (namelength >= 0) // compartment is specified, so strip that off
    return name.substr(0, namelength);
  else  //compartment is not specified
    return name;
}

bool CMetabNameInterface::isValidMetabName(const std::string name)
{
  // a valid name does not contain white spaces, and contains either matching or no curly braces
  C_INT32 pos1, pos2, pos3;

  // make sure the name is not an empty string
  unsigned C_INT32 len = name.length();
  if (len < 1)
    return false;

  // check for white spaces
  pos1 = name.find(" ");
  if (pos1 >= 0)
    return false;

  // curly braces: '{' is not the first character in the string, and appears before '}'
  // if present, '}' should be the last character in the string
  pos1 = name.find('{');
  pos2 = name.find('}');
  pos3 = name.rfind('{');

  // ok if no braces appear
  if ((pos1 < 0) && (pos2 < 0))
    return true;

  // ok  if only one '{' and one '}', braces match, compartment name is not an empty string, and '}' is the last character
  if ((pos1 > 0) && (pos1 == pos3) && (pos2 > pos1 + 1) && (pos2 + 1 == len))
    return true;

  // otherwise the name is not valid
  return false;
}
<|endoftext|>


<commit_before>	//
//  libavg - Media Playback Engine.
//  Copyright (C) 2003-2008 Ulrich von Zadow
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Lesser General Public
//  License as published by the Free Software Foundation; either
//  version 2 of the License, or (at your option) any later version.
//
//  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
//
//  Current versions can be found at www.libavg.de
//
//  Original author of this file is Jan Boelsche (regular.gonzales@googlemail.com).
//

#include <string>
#include <iostream>

#include "../Node.h"
#include "../NodeDefinition.h"

#include "../../base/Logger.h"
#include "../../graphics/Pixel32.h"
#include "../../wrapper/WrapHelper.h"

using namespace std;
using namespace boost::python;

namespace avg {

class ColorNode : public Node {
public:
	static NodePtr create(const ArgList& Args, bool bFromXML);
	static NodeDefinition createNodeDefinition();

	ColorNode(const ArgList& Args, bool bFromXML);
	virtual ~ColorNode() {}

	void setFillColor(const std::string& sColor);
    const std::string& getFillColor() const;
private:
	std::string m_sFillColorName;
    Pixel32 m_FillColor;
};

ColorNode::ColorNode(const ArgList& Args, bool bFromXML) :
	m_sFillColorName("FFFFFF")
{

    ArgMap am = Args.getArgMap();
    ArgMap::iterator i = am.begin();
    while(i != am.end()) {
        string key = i->first;
        string value = Args.getArgVal<string>(key);
        AVG_TRACE(Logger::PLUGIN, "ColorNode constructed with key=" << key << " value=" << value);
        ++i;
    };

	Args.setMembers(this);
	AVG_TRACE(Logger::PLUGIN, "ColorNode constructed with " << m_sFillColorName);

    m_FillColor = colorStringToColor(m_sFillColorName);
}

void ColorNode::setFillColor(const string& sFillColor)
{
	AVG_TRACE(Logger::PLUGIN, "setFillColor called with " << sFillColor);
    if (sFillColor != m_sFillColorName) {
     	m_sFillColorName = sFillColor;
        m_FillColor = colorStringToColor(m_sFillColorName);
        //setDrawNeeded(true);
    }
}

const std::string& ColorNode::getFillColor() const
{
    return m_sFillColorName;
}

NodePtr ColorNode::create(const ArgList& Args, bool bFromXML)
{
	return NodePtr(new ColorNode(Args, bFromXML));
}

NodeDefinition ColorNode::createNodeDefinition()
{
	class_<ColorNode, bases<Node>, boost::noncopyable>("ColorNode", no_init)
        .add_property("fillcolor", make_function(&ColorNode::getFillColor,
		return_value_policy<copy_const_reference>()), &ColorNode::setFillColor);

	return NodeDefinition("colornode", (NodeBuilder)ColorNode::create)
		.extendDefinition(Node::createDefinition())
		.addArg(Arg<string>("fillcolor", "FFFFFF", false,
                offsetof(ColorNode, m_sFillColorName)));
}

}

extern "C" avg::NodeDefinition getNodeDefinition() {
	return avg::ColorNode::createNodeDefinition();
}

<commit_msg>strange test result: ColorNode c'tor gets wrong value for fillcolor from XML parser (on linux only)<commit_after>	//
//  libavg - Media Playback Engine.
//  Copyright (C) 2003-2008 Ulrich von Zadow
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Lesser General Public
//  License as published by the Free Software Foundation; either
//  version 2 of the License, or (at your option) any later version.
//
//  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
//
//  Current versions can be found at www.libavg.de
//
//  Original author of this file is Jan Boelsche (regular.gonzales@googlemail.com).
//

#include <string>
#include <iostream>

#include "../Node.h"
#include "../NodeDefinition.h"

#include "../../base/Logger.h"
#include "../../graphics/Pixel32.h"
#include "../../wrapper/WrapHelper.h"

using namespace std;
using namespace boost::python;

namespace avg {

class ColorNode : public Node {
public:
	static NodePtr create(const ArgList& Args, bool bFromXML);
	static NodeDefinition createNodeDefinition();

	ColorNode(const ArgList& Args, bool bFromXML);
	virtual ~ColorNode() {}

	void setFillColor(const std::string& sColor);
    const std::string& getFillColor() const;
private:
	std::string m_sFillColorName;
    Pixel32 m_FillColor;
};

ColorNode::ColorNode(const ArgList& Args, bool bFromXML) :
	m_sFillColorName("FFFFFF")
{

    /* this crashes on mac and linux
    // probalby the iterator becomes invalid
    ArgMap am = Args.getArgMap();
    ArgMap::iterator i = am.begin();
    while(i != am.end()) {
        string key = i->first;
        string value = Args.getArgVal<string>(key);
        AVG_TRACE(Logger::PLUGIN, "ColorNode constructed with key=" << key << " value=" << value);
        ++i;
    };
    */

     AVG_TRACE(Logger::PLUGIN, "ColorNode c'tor gets Argument fillcolor= "  << Args.getArgVal<string>("fillcolor"));

	Args.setMembers(this);
	AVG_TRACE(Logger::PLUGIN, "ColorNode constructed with " << m_sFillColorName);

    m_FillColor = colorStringToColor(m_sFillColorName);
}

void ColorNode::setFillColor(const string& sFillColor)
{
	AVG_TRACE(Logger::PLUGIN, "setFillColor called with " << sFillColor);
    if (sFillColor != m_sFillColorName) {
     	m_sFillColorName = sFillColor;
        m_FillColor = colorStringToColor(m_sFillColorName);
        //setDrawNeeded(true);
    }
}

const std::string& ColorNode::getFillColor() const
{
    return m_sFillColorName;
}

NodePtr ColorNode::create(const ArgList& Args, bool bFromXML)
{
	return NodePtr(new ColorNode(Args, bFromXML));
}

NodeDefinition ColorNode::createNodeDefinition()
{
	class_<ColorNode, bases<Node>, boost::noncopyable>("ColorNode", no_init)
        .add_property("fillcolor", make_function(&ColorNode::getFillColor,
		return_value_policy<copy_const_reference>()), &ColorNode::setFillColor);

	return NodeDefinition("colornode", (NodeBuilder)ColorNode::create)
		.extendDefinition(Node::createDefinition())
		.addArg(Arg<string>("fillcolor", "FFFFFF", false,
                offsetof(ColorNode, m_sFillColorName)));
}

}

extern "C" avg::NodeDefinition getNodeDefinition() {
	return avg::ColorNode::createNodeDefinition();
}

<|endoftext|>


<commit_before>// __BEGIN_LICENSE__
// Copyright (C) 2006, 2007 United States Government as represented by
// the Administrator of the National Aeronautics and Space Administration.
// All Rights Reserved.
// __END_LICENSE__

#include <vw/Math/Matrix.h>
#include <vw/Core/Exception.h>
#include <vw/Cartography/GeoReferenceResourceGDAL.h>
#include <vw/FileIO/DiskImageResourceGDAL.h>
#include <vw/Cartography/GeoReference.h>

//FIXME: can probably trim down these headers
// GDAL Headers
#include "gdal.h"
#include "gdal_priv.h"
#include "cpl_string.h"
#include "ogr_spatialref.h"
#include "ogr_api.h"

// For boost::split
#include <boost/algorithm/string.hpp>

namespace vw {
namespace cartography {

  void read_gdal_georeference( GeoReference& georef, DiskImageResourceGDAL const& resource ) {
    GDALDataset *dataset = static_cast<GDALDataset*>(resource.get_read_dataset_ptr());
    if (!dataset)
      vw_throw( LogicErr() << "read_gdal_georeference: Could not read georeference. No file has been opened." );

    // Pull the projection and datum information out of the file if available
    if( dataset->GetProjectionRef() != NULL ) {

      // Create a GDAL spatial ref object
      OGRSpatialReference gdal_spatial_ref;
      const char* wkt = dataset->GetProjectionRef();
      char** wkt_ptr = (char**)(&wkt);
      gdal_spatial_ref.importFromWkt(wkt_ptr);

      // Read projection information out of the file
      char* proj_str_tmp;
      gdal_spatial_ref.exportToProj4(&proj_str_tmp);
      std::string proj4_str = proj_str_tmp;
      CPLFree( proj_str_tmp );
      // For debugging:
      //      vw_out(0) << "PROJ in --> " << proj4_str << "\n";

      std::vector<std::string> input_strings;
      std::vector<std::string> output_strings;
      std::vector<std::string> datum_strings;
      std::string trimmed_proj4_str = boost::trim_copy(proj4_str);
      boost::split( input_strings, trimmed_proj4_str, boost::is_any_of(" ") );
      for (unsigned int i = 0; i < input_strings.size(); ++i) {

        // Pick out the parts of the projection string that pertain to
        // map projections.  We essentially want to eliminate all of
        // the strings that have to do with the datum, since those are
        // handled by interacting directly with the
        // OGRSpatialReference below. This is sort of messy, but it's
        // the easiest way to do this, as far as I can tell.
        if ((input_strings[i].find("+proj=") == 0) ||
            (input_strings[i].find("+x_0=") == 0) ||
            (input_strings[i].find("+y_0=") == 0) ||
            (input_strings[i].find("+lon") == 0) ||
            (input_strings[i].find("+lat") == 0) ||
            (input_strings[i].find("+k=") == 0) ||
            (input_strings[i].find("+lat_ts=") == 0) ||
            (input_strings[i].find("+ns") == 0) ||
            (input_strings[i].find("+no_cut") == 0) ||
            (input_strings[i].find("+h=") == 0) ||
            (input_strings[i].find("+W=") == 0) ||
            (input_strings[i].find("+units=") == 0) ||
            (input_strings[i].find("+zone=") == 0)) {
          output_strings.push_back(input_strings[i]);
        } else if ((input_strings[i].find("+ellps=") == 0) ||
                   (input_strings[i].find("+datum=") == 0)) {
          // We put these in the proj4_str for the Datum class.
          datum_strings.push_back(input_strings[i]);
        }
      }
      std::ostringstream strm;
      for (unsigned int i = 0; i < output_strings.size(); ++i) {
        strm << output_strings[i] << " ";
      }
      // For debugging:
      //      vw_out(0) << "     out --> " << strm.str() << "\n";

      // If the file contains no projection related information, we
      // supply proj.4 with a "default" interpretation that the file
      // is in geographic (unprojected) coordinates.
      if (output_strings.size() == 0)
        georef.set_proj4_projection_str("+proj=longlat");
      else
        georef.set_proj4_projection_str(strm.str());

      // Read in the datum information
      Datum datum;
      const char* datum_name = gdal_spatial_ref.GetAttrValue("DATUM");
      if (datum_name) { datum.name() = datum_name; }
      const char* spheroid_name = gdal_spatial_ref.GetAttrValue("SPHEROID");
      if (spheroid_name) { datum.spheroid_name() = spheroid_name; }
      const char* meridian_name = gdal_spatial_ref.GetAttrValue("PRIMEM");
      if (meridian_name) { datum.meridian_name() = meridian_name; }
      OGRErr e1, e2;
      double semi_major = gdal_spatial_ref.GetSemiMajor(&e1);
      double semi_minor = gdal_spatial_ref.GetSemiMinor(&e2);
      if (e1 != OGRERR_FAILURE && e2 != OGRERR_FAILURE) {
        datum.set_semi_major_axis(semi_major);
        datum.set_semi_minor_axis(semi_minor);
      }
      datum.meridian_offset() = gdal_spatial_ref.GetPrimeMeridian();
      // Set the proj4 string for datum.
      std::stringstream datum_proj4_ss;
      for(unsigned i=0; i < datum_strings.size(); i++)
          datum_proj4_ss << datum_strings[i] << ' ';
      // Add the current proj4 string in the case that our ellipse/datum
      // values are empty.
      if(boost::trim_copy(datum_proj4_ss.str()) == "")
        datum_proj4_ss << datum.proj4_str();
      datum.proj4_str() = boost::trim_copy(datum_proj4_ss.str());
      georef.set_datum(datum);
    }

    double geo_transform[6];
    Matrix<double,3,3> transform;
    if( dataset->GetGeoTransform( geo_transform ) == CE_None ) {
      transform.set_identity();
      transform(0,0) = geo_transform[1];
      transform(0,1) = geo_transform[2];
      transform(0,2) = geo_transform[0];
      transform(1,0) = geo_transform[4];
      transform(1,1) = geo_transform[5];
      transform(1,2) = geo_transform[3];
      georef.set_transform(transform);

      // Determine the pixel interpretation for the image.  See the
      // comments in GeoReference for more information.  If nothing is
      // encoded in the file, the default is to assume PixelAsArea.
      georef.set_pixel_interpretation(GeoReference::PixelAsArea);
      char **metadata = dataset->GetMetadata();
      if( CSLCount(metadata) > 0 ) {
        for( int i = 0; metadata[i] != NULL; i++ ) {
          std::vector<std::string> split_vec;
          boost::split(split_vec, metadata[i], boost::is_any_of("=") );
          if (split_vec[0] == GDALMD_AREA_OR_POINT && split_vec.size() >= 2)
            if (boost::trim_copy(split_vec[1]) == GDALMD_AOP_POINT)
              georef.set_pixel_interpretation(GeoReference::PixelAsPoint);
        }
      }
    }

    // Georeference functions need not be invertible.  When we perform a reverse
    // lookup (e.g. during a geotransformation) we rely on PROJ.4 to pick one
    // possible value.  However, the georeference might actually place the image
    // at another (equivalent) location in the projected space.  This is hard to
    // recover from at run-time, and we currently have no generic solution to this
    // problem.  In the mean time, we at least test whether the georefernce is
    // likely to run into this problem (and warn the user) by checking whether
    // forward- and reverse-projecting the origin pixel lands us back at the origin.
    Vector2 origin = georef.lonlat_to_pixel( georef.pixel_to_lonlat( Vector2() ) );
    if( origin.x()*origin.x() + origin.y()*origin.y() > 0.1 ) {
      vw_out(WarningMessage) << "read_gdal_georeference(): WARNING! Resource file " <<
	resource.filename() << " contains a non-normal georeference.  Bad things "
	"may happen: puppies dying, rainbows fading, mortage foreclosures, etc." << std::endl;
    }
  }

  void write_gdal_georeference( DiskImageResourceGDAL& resource, GeoReference const& georef ) {

    GDALDataset *dataset = static_cast<GDALDataset*>(resource.get_write_dataset_ptr());
    if (!dataset)
      vw_throw( LogicErr() << "GeoReferenceHelperGDAL: Could not write georeference. No file has been opened." );

    // Store the transform matrix
    double geo_transform[6] = { georef.transform()(0,2), georef.transform()(0,0), georef.transform()(0,1),
                                georef.transform()(1,2), georef.transform()(1,0), georef.transform()(1,1) };
    dataset->SetGeoTransform( geo_transform );

    // This is a little ridiculous, but GDAL can't write geotiffs
    // without a string of Well Known Text (WKT), so we must conjure
    // up an OGRSpatialReference here and use it to convert from
    // proj.4 to WKT.
    //
    // However, we first set the datum parameters in the
    // ORGSpatialReference object directly.
    OGRSpatialReference gdal_spatial_ref;
    gdal_spatial_ref.importFromProj4(georef.proj4_str().c_str());
    gdal_spatial_ref.SetGeogCS( "Geographic Coordinate System",
                                georef.datum().name().c_str(),
                                georef.datum().spheroid_name().c_str(),
                                georef.datum().semi_major_axis(),
                                georef.datum().inverse_flattening(),
                                georef.datum().meridian_name().c_str(),
                                georef.datum().meridian_offset() );

    char* wkt_str_tmp;
    gdal_spatial_ref.exportToWkt(&wkt_str_tmp);
    std::string wkt_str = wkt_str_tmp;
    OGRFree(wkt_str_tmp);

    dataset->SetProjection( wkt_str.c_str() );

    // Set the pixel interpretation for the image.  See the comments
    // in GeoReference for more information.
    if (georef.pixel_interpretation() == GeoReference::PixelAsArea)
      dataset->SetMetadataItem(GDALMD_AREA_OR_POINT, GDALMD_AOP_AREA);
    else // PixelAsPoint
      dataset->SetMetadataItem(GDALMD_AREA_OR_POINT, GDALMD_AOP_POINT);
  }

}} // namespace vw::cartography
<commit_msg>gdal UTM zone fix<commit_after>// __BEGIN_LICENSE__
// Copyright (C) 2006, 2007 United States Government as represented by
// the Administrator of the National Aeronautics and Space Administration.
// All Rights Reserved.
// __END_LICENSE__

#include <vw/Math/Matrix.h>
#include <vw/Core/Exception.h>
#include <vw/Cartography/GeoReferenceResourceGDAL.h>
#include <vw/FileIO/DiskImageResourceGDAL.h>
#include <vw/Cartography/GeoReference.h>

//FIXME: can probably trim down these headers
// GDAL Headers
#include "gdal.h"
#include "gdal_priv.h"
#include "cpl_string.h"
#include "ogr_spatialref.h"
#include "ogr_api.h"

// For boost::split
#include <boost/algorithm/string.hpp>

namespace vw {
namespace cartography {

  void read_gdal_georeference( GeoReference& georef, DiskImageResourceGDAL const& resource ) {
    GDALDataset *dataset = static_cast<GDALDataset*>(resource.get_read_dataset_ptr());
    if (!dataset)
      vw_throw( LogicErr() << "read_gdal_georeference: Could not read georeference. No file has been opened." );

    // Pull the projection and datum information out of the file if available
    if( dataset->GetProjectionRef() != NULL ) {

      // Create a GDAL spatial ref object
      OGRSpatialReference gdal_spatial_ref;
      const char* wkt = dataset->GetProjectionRef();
      char** wkt_ptr = (char**)(&wkt);
      gdal_spatial_ref.importFromWkt(wkt_ptr);

      // Read projection information out of the file
      char* proj_str_tmp;
      gdal_spatial_ref.exportToProj4(&proj_str_tmp);
      std::string proj4_str = proj_str_tmp;
      CPLFree( proj_str_tmp );
      // For debugging:
      //      vw_out(0) << "PROJ in --> " << proj4_str << "\n";

      std::vector<std::string> input_strings;
      std::vector<std::string> output_strings;
      std::vector<std::string> datum_strings;
      std::string trimmed_proj4_str = boost::trim_copy(proj4_str);
      boost::split( input_strings, trimmed_proj4_str, boost::is_any_of(" ") );
      for (unsigned int i = 0; i < input_strings.size(); ++i) {

        // Pick out the parts of the projection string that pertain to
        // map projections.  We essentially want to eliminate all of
        // the strings that have to do with the datum, since those are
        // handled by interacting directly with the
        // OGRSpatialReference below. This is sort of messy, but it's
        // the easiest way to do this, as far as I can tell.
        if ((input_strings[i].find("+proj=") == 0) ||
            (input_strings[i].find("+x_0=") == 0) ||
            (input_strings[i].find("+y_0=") == 0) ||
            (input_strings[i].find("+lon") == 0) ||
            (input_strings[i].find("+lat") == 0) ||
            (input_strings[i].find("+k=") == 0) ||
            (input_strings[i].find("+lat_ts=") == 0) ||
            (input_strings[i].find("+ns") == 0) ||
            (input_strings[i].find("+no_cut") == 0) ||
            (input_strings[i].find("+h=") == 0) ||
            (input_strings[i].find("+W=") == 0) ||
            (input_strings[i].find("+units=") == 0) ||
            (input_strings[i].find("+zone=") == 0)) {
          output_strings.push_back(input_strings[i]);
        } else if ((input_strings[i].find("+ellps=") == 0) ||
                   (input_strings[i].find("+datum=") == 0)) {
          // We put these in the proj4_str for the Datum class.
          datum_strings.push_back(input_strings[i]);
        }
      }
      std::ostringstream strm;
      for (unsigned int i = 0; i < output_strings.size(); ++i) {
        strm << output_strings[i] << " ";
      }
      // For debugging:
      //      vw_out(0) << "     out --> " << strm.str() << "\n";

      // If the file contains no projection related information, we
      // supply proj.4 with a "default" interpretation that the file
      // is in geographic (unprojected) coordinates.
      if (output_strings.size() == 0)
        georef.set_proj4_projection_str("+proj=longlat");
      else
        georef.set_proj4_projection_str(strm.str());

      int utm_north = 0;
      int utm_zone = gdal_spatial_ref.GetUTMZone(&utm_north);
      if (utm_zone)
        georef.set_UTM(utm_zone, utm_north);

      // Read in the datum information
      Datum datum;
      const char* datum_name = gdal_spatial_ref.GetAttrValue("DATUM");
      if (datum_name) { datum.name() = datum_name; }
      const char* spheroid_name = gdal_spatial_ref.GetAttrValue("SPHEROID");
      if (spheroid_name) { datum.spheroid_name() = spheroid_name; }
      const char* meridian_name = gdal_spatial_ref.GetAttrValue("PRIMEM");
      if (meridian_name) { datum.meridian_name() = meridian_name; }
      OGRErr e1, e2;
      double semi_major = gdal_spatial_ref.GetSemiMajor(&e1);
      double semi_minor = gdal_spatial_ref.GetSemiMinor(&e2);
      if (e1 != OGRERR_FAILURE && e2 != OGRERR_FAILURE) {
        datum.set_semi_major_axis(semi_major);
        datum.set_semi_minor_axis(semi_minor);
      }
      datum.meridian_offset() = gdal_spatial_ref.GetPrimeMeridian();
      // Set the proj4 string for datum.
      std::stringstream datum_proj4_ss;
      for(unsigned i=0; i < datum_strings.size(); i++)
          datum_proj4_ss << datum_strings[i] << ' ';
      // Add the current proj4 string in the case that our ellipse/datum
      // values are empty.
      if(boost::trim_copy(datum_proj4_ss.str()) == "")
        datum_proj4_ss << datum.proj4_str();
      datum.proj4_str() = boost::trim_copy(datum_proj4_ss.str());
      georef.set_datum(datum);
    }

    double geo_transform[6];
    Matrix<double,3,3> transform;
    if( dataset->GetGeoTransform( geo_transform ) == CE_None ) {
      transform.set_identity();
      transform(0,0) = geo_transform[1];
      transform(0,1) = geo_transform[2];
      transform(0,2) = geo_transform[0];
      transform(1,0) = geo_transform[4];
      transform(1,1) = geo_transform[5];
      transform(1,2) = geo_transform[3];
      georef.set_transform(transform);

      // Determine the pixel interpretation for the image.  See the
      // comments in GeoReference for more information.  If nothing is
      // encoded in the file, the default is to assume PixelAsArea.
      georef.set_pixel_interpretation(GeoReference::PixelAsArea);
      char **metadata = dataset->GetMetadata();
      if( CSLCount(metadata) > 0 ) {
        for( int i = 0; metadata[i] != NULL; i++ ) {
          std::vector<std::string> split_vec;
          boost::split(split_vec, metadata[i], boost::is_any_of("=") );
          if (split_vec[0] == GDALMD_AREA_OR_POINT && split_vec.size() >= 2)
            if (boost::trim_copy(split_vec[1]) == GDALMD_AOP_POINT)
              georef.set_pixel_interpretation(GeoReference::PixelAsPoint);
        }
      }
    }

    // Georeference functions need not be invertible.  When we perform a reverse
    // lookup (e.g. during a geotransformation) we rely on PROJ.4 to pick one
    // possible value.  However, the georeference might actually place the image
    // at another (equivalent) location in the projected space.  This is hard to
    // recover from at run-time, and we currently have no generic solution to this
    // problem.  In the mean time, we at least test whether the georefernce is
    // likely to run into this problem (and warn the user) by checking whether
    // forward- and reverse-projecting the origin pixel lands us back at the origin.
    Vector2 origin = georef.lonlat_to_pixel( georef.pixel_to_lonlat( Vector2() ) );
    if( origin.x()*origin.x() + origin.y()*origin.y() > 0.1 ) {
      vw_out(WarningMessage) << "read_gdal_georeference(): WARNING! Resource file " <<
	resource.filename() << " contains a non-normal georeference.  Bad things "
	"may happen: puppies dying, rainbows fading, mortage foreclosures, etc." << std::endl;
    }
  }

  void write_gdal_georeference( DiskImageResourceGDAL& resource, GeoReference const& georef ) {

    GDALDataset *dataset = static_cast<GDALDataset*>(resource.get_write_dataset_ptr());
    if (!dataset)
      vw_throw( LogicErr() << "GeoReferenceHelperGDAL: Could not write georeference. No file has been opened." );

    // Store the transform matrix
    double geo_transform[6] = { georef.transform()(0,2), georef.transform()(0,0), georef.transform()(0,1),
                                georef.transform()(1,2), georef.transform()(1,0), georef.transform()(1,1) };
    dataset->SetGeoTransform( geo_transform );

    // This is a little ridiculous, but GDAL can't write geotiffs
    // without a string of Well Known Text (WKT), so we must conjure
    // up an OGRSpatialReference here and use it to convert from
    // proj.4 to WKT.
    //
    // However, we first set the datum parameters in the
    // ORGSpatialReference object directly.
    OGRSpatialReference gdal_spatial_ref;
    gdal_spatial_ref.importFromProj4(georef.proj4_str().c_str());
    gdal_spatial_ref.SetGeogCS( "Geographic Coordinate System",
                                georef.datum().name().c_str(),
                                georef.datum().spheroid_name().c_str(),
                                georef.datum().semi_major_axis(),
                                georef.datum().inverse_flattening(),
                                georef.datum().meridian_name().c_str(),
                                georef.datum().meridian_offset() );

    char* wkt_str_tmp;
    gdal_spatial_ref.exportToWkt(&wkt_str_tmp);
    std::string wkt_str = wkt_str_tmp;
    OGRFree(wkt_str_tmp);

    dataset->SetProjection( wkt_str.c_str() );

    // Set the pixel interpretation for the image.  See the comments
    // in GeoReference for more information.
    if (georef.pixel_interpretation() == GeoReference::PixelAsArea)
      dataset->SetMetadataItem(GDALMD_AREA_OR_POINT, GDALMD_AOP_AREA);
    else // PixelAsPoint
      dataset->SetMetadataItem(GDALMD_AREA_OR_POINT, GDALMD_AOP_POINT);
  }

}} // namespace vw::cartography
<|endoftext|>


<commit_before>/***********************************************************************************************************************
**
** Copyright (c) 2011, 2014 ETH Zurich
** All rights reserved.
**
** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
** following conditions are met:
**
** * Redistributions of source code must retain the above copyright notice, this list of conditions and the following
** disclaimer.
** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
** following disclaimer in the documentation and/or other materials provided with the distribution.
** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products
** derived from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
***********************************************************************************************************************/

#include "Commit.h"

namespace FilePersistence {

Signature::Signature()
{
	dateTime_ = QDateTime::currentDateTimeUtc();
	timeZone_ = QTimeZone(QTimeZone::systemTimeZoneId());
}

CommitFile::CommitFile()
{
	relativePath_ = QString();
	size_ = 0;
	content_ = nullptr;
}

CommitFile::CommitFile(QString relativePath, qint64 size, const char* content)
{
	relativePath_ = relativePath;
	size_ = size;
	content_ = content;
}

CommitFile::~CommitFile()
{
	delete[] content_;
}

Commit::Commit() {}

Commit::~Commit()
{
	for (auto file : files_.values())
		delete file;
}

void Commit::setMetaData(CommitMetaData data)
{
	information_ = data;
}

CommitMetaData Commit::metaData() const
{
	return information_;
}

void Commit::addFile(QString relativePath, qint64 size, const char* content)
{
	files_.insert(relativePath, new CommitFile(relativePath, size, content));
}

bool Commit::getFileContent(QString fileName, const char*& content, int& contentSize) const
{
	QHash<QString, CommitFile*>::const_iterator iter = files_.find(fileName);
	if (iter != files_.constEnd())
	{
		contentSize = iter.value()->size_;
		content = iter.value()->content_;

		return true;
	}
	else
		return false;
}

} /* namespace FilePersistence */
<commit_msg>Use SAFE_DELETE in destructor of Commit<commit_after>/***********************************************************************************************************************
**
** Copyright (c) 2011, 2014 ETH Zurich
** All rights reserved.
**
** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
** following conditions are met:
**
** * Redistributions of source code must retain the above copyright notice, this list of conditions and the following
** disclaimer.
** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
** following disclaimer in the documentation and/or other materials provided with the distribution.
** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products
** derived from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
***********************************************************************************************************************/

#include "Commit.h"

namespace FilePersistence {

Signature::Signature()
{
	dateTime_ = QDateTime::currentDateTimeUtc();
	timeZone_ = QTimeZone(QTimeZone::systemTimeZoneId());
}

CommitFile::CommitFile()
{
	relativePath_ = QString();
	size_ = 0;
	content_ = nullptr;
}

CommitFile::CommitFile(QString relativePath, qint64 size, const char* content)
{
	relativePath_ = relativePath;
	size_ = size;
	content_ = content;
}

CommitFile::~CommitFile()
{
	delete[] content_;
}

Commit::Commit() {}

Commit::~Commit()
{
	for (auto file : files_.values())
		SAFE_DELETE(file);
}

void Commit::setMetaData(CommitMetaData data)
{
	information_ = data;
}

CommitMetaData Commit::metaData() const
{
	return information_;
}

void Commit::addFile(QString relativePath, qint64 size, const char* content)
{
	files_.insert(relativePath, new CommitFile(relativePath, size, content));
}

bool Commit::getFileContent(QString fileName, const char*& content, int& contentSize) const
{
	QHash<QString, CommitFile*>::const_iterator iter = files_.find(fileName);
	if (iter != files_.constEnd())
	{
		contentSize = iter.value()->size_;
		content = iter.value()->content_;

		return true;
	}
	else
		return false;
}

} /* namespace FilePersistence */
<|endoftext|>