<commit_before>// Copyright (c) 2010 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 "chrome/browser/chromeos/login/owner_manager.h"

#include <cert.h>
#include <keyhi.h>
#include <keythi.h>  // KeyType enum
#include <pk11pub.h>
#include <stdlib.h>

#include <string>

#include "base/crypto/rsa_private_key.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/logging.h"
#include "base/nss_util_internal.h"
#include "base/nss_util.h"
#include "base/scoped_temp_dir.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/common/notification_registrar.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/notification_type.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"

using ::base::RSAPrivateKey;
using ::testing::DoAll;
using ::testing::Invoke;
using ::testing::Return;
using ::testing::SetArgumentPointee;
using ::testing::_;

namespace chromeos {

namespace {

class MockKeyUtils : public OwnerKeyUtils {
 public:
  MockKeyUtils() {}
  ~MockKeyUtils() {}
  MOCK_METHOD0(GenerateKeyPair, RSAPrivateKey*());
  MOCK_METHOD1(ExportPublicKeyViaDbus, bool(RSAPrivateKey* pair));
  MOCK_METHOD2(ExportPublicKeyToFile, bool(RSAPrivateKey* pair,
                                           const FilePath& key_file));
  MOCK_METHOD2(ImportPublicKey, bool(const FilePath& key_file,
                                     std::vector<uint8>* output));
  MOCK_METHOD1(FindPrivateKey, RSAPrivateKey*(const std::vector<uint8>& key));
  MOCK_METHOD0(GetOwnerKeyFilePath, FilePath());
 private:
  DISALLOW_COPY_AND_ASSIGN(MockKeyUtils);
};

class MockInjector : public OwnerKeyUtils::Factory {
 public:
  // Takes ownership of |mock|.
  explicit MockInjector(MockKeyUtils* mock) :
      transient_(mock),
      delete_transient_(true) {
  }

  virtual ~MockInjector() {
    if (delete_transient_)
      delete transient_;
  }

  // If this is called, its caller takes ownership of |transient_|.
  // If it's never called, |transient_| remains our problem.
  OwnerKeyUtils* CreateOwnerKeyUtils() {
    delete_transient_ = false;
    return transient_;
  }

 private:
  MockKeyUtils* transient_;
  bool delete_transient_;
  DISALLOW_COPY_AND_ASSIGN(MockInjector);
};

class KeyUser : public OwnerManager::Delegate {
 public:
  explicit KeyUser(const OwnerManager::KeyOpCode expected)
      : expected_(expected) {
  }

  virtual ~KeyUser() {}

  void OnKeyOpComplete(const OwnerManager::KeyOpCode return_code,
                       const std::string& payload) {
    MessageLoop::current()->Quit();
    EXPECT_EQ(expected_, return_code);
  }

  const OwnerManager::KeyOpCode expected_;
 private:
  DISALLOW_COPY_AND_ASSIGN(KeyUser);
};

static bool Win(RSAPrivateKey* key) {
  MessageLoop::current()->Quit();
  return true;
}

static bool Fail(RSAPrivateKey* key) {
  MessageLoop::current()->Quit();
  return false;
}

}  // anonymous namespace

class OwnerManagerTest : public ::testing::Test,
                         public NotificationObserver {
 public:
  OwnerManagerTest()
      : message_loop_(MessageLoop::TYPE_UI),
        ui_thread_(ChromeThread::UI, &message_loop_),
        file_thread_(ChromeThread::FILE),
        success_expected_(false),
        quit_on_observe_(true),
        mock_(new MockKeyUtils),
        injector_(mock_) /* injector_ takes ownership of mock_ */ {
    registrar_.Add(
        this,
        NotificationType::OWNER_KEY_FETCH_ATTEMPT_FAILED,
        NotificationService::AllSources());
    registrar_.Add(
        this,
        NotificationType::OWNER_KEY_FETCH_ATTEMPT_SUCCEEDED,
        NotificationService::AllSources());
  }
  virtual ~OwnerManagerTest() {}

  virtual void SetUp() {
    base::OpenPersistentNSSDB();  // TODO(cmasone): use test DB instead
    fake_private_key_.reset(RSAPrivateKey::Create(256));
    ASSERT_TRUE(fake_private_key_->ExportPublicKey(&fake_public_key_));

    // Mimic ownership.
    ASSERT_TRUE(tmpdir_.CreateUniqueTempDir());
    ASSERT_TRUE(file_util::CreateTemporaryFileInDir(tmpdir_.path(), &tmpfile_));

    file_thread_.Start();
    OwnerKeyUtils::set_factory(&injector_);
  }

  virtual void TearDown() {
    OwnerKeyUtils::set_factory(NULL);
  }

  void StartUnowned() {
    file_util::Delete(tmpfile_, false);
  }

  void InjectKeys(OwnerManager* manager) {
    manager->public_key_ = fake_public_key_;
    manager->private_key_.reset(fake_private_key_.release());
  }

  // NotificationObserver implementation.
  virtual void Observe(NotificationType type,
                       const NotificationSource& source,
                       const NotificationDetails& details) {
    if (type == NotificationType::OWNER_KEY_FETCH_ATTEMPT_SUCCEEDED) {
      EXPECT_TRUE(success_expected_);
      if (quit_on_observe_)
        MessageLoop::current()->Quit();
    } else if (type == NotificationType::OWNER_KEY_FETCH_ATTEMPT_FAILED) {
      EXPECT_FALSE(success_expected_);
      if (quit_on_observe_)
        MessageLoop::current()->Quit();
    }
  }

  void ExpectKeyFetchSuccess(bool should_succeed) {
    success_expected_ = should_succeed;
  }

  void SetQuitOnKeyFetch(bool should_quit) { quit_on_observe_ = should_quit; }

  ScopedTempDir tmpdir_;
  FilePath tmpfile_;

  MessageLoop message_loop_;
  ChromeThread ui_thread_;
  ChromeThread file_thread_;

  std::vector<uint8> fake_public_key_;
  scoped_ptr<RSAPrivateKey> fake_private_key_;

  NotificationRegistrar registrar_;
  bool success_expected_;
  bool quit_on_observe_;

  MockKeyUtils* mock_;
  MockInjector injector_;
};

TEST_F(OwnerManagerTest, LoadKeyUnowned) {
  StartUnowned();

  EXPECT_CALL(*mock_, GetOwnerKeyFilePath())
      .WillRepeatedly(Return(tmpfile_));

  scoped_refptr<OwnerManager> manager(new OwnerManager);
  EXPECT_FALSE(manager->StartLoadOwnerKeyAttempt());
}

TEST_F(OwnerManagerTest, LoadOwnerKeyFail) {
  EXPECT_CALL(*mock_, GetOwnerKeyFilePath())
      .WillRepeatedly(Return(tmpfile_));
  EXPECT_CALL(*mock_, ImportPublicKey(tmpfile_, _))
      .WillOnce(Return(false))
      .RetiresOnSaturation();

  scoped_refptr<OwnerManager> manager(new OwnerManager);
  EXPECT_TRUE(manager->StartLoadOwnerKeyAttempt());

  // Run remaining events, until ExportPublicKeyViaDbus().
  message_loop_.Run();
}

TEST_F(OwnerManagerTest, LoadOwnerKey) {
  ExpectKeyFetchSuccess(true);

  EXPECT_CALL(*mock_, GetOwnerKeyFilePath())
      .WillRepeatedly(Return(tmpfile_));
  EXPECT_CALL(*mock_, ImportPublicKey(tmpfile_, _))
      .WillOnce(DoAll(SetArgumentPointee<1>(fake_public_key_),
                      Return(true)))
      .RetiresOnSaturation();

  scoped_refptr<OwnerManager> manager(new OwnerManager);
  EXPECT_TRUE(manager->StartLoadOwnerKeyAttempt());

  // Run remaining events, until ExportPublicKeyViaDbus().
  message_loop_.Run();
}

TEST_F(OwnerManagerTest, TakeOwnershipAlreadyOwned) {

  EXPECT_CALL(*mock_, GetOwnerKeyFilePath())
      .WillRepeatedly(Return(tmpfile_));

  scoped_refptr<OwnerManager> manager(new OwnerManager);
  EXPECT_FALSE(manager->StartTakeOwnershipAttempt());
}

TEST_F(OwnerManagerTest, KeyGenerationFail) {
  StartUnowned();

  EXPECT_CALL(*mock_, GenerateKeyPair())
      .WillOnce(Return(reinterpret_cast<RSAPrivateKey*>(NULL)))
      .RetiresOnSaturation();
  EXPECT_CALL(*mock_, GetOwnerKeyFilePath())
      .WillRepeatedly(Return(tmpfile_));

  scoped_refptr<OwnerManager> manager(new OwnerManager);
  EXPECT_TRUE(manager->StartTakeOwnershipAttempt());

  message_loop_.Run();
}

TEST_F(OwnerManagerTest, KeyExportFail) {
  StartUnowned();

  EXPECT_CALL(*mock_, ExportPublicKeyViaDbus(fake_private_key_.get()))
      .WillOnce(Invoke(Fail))
      .RetiresOnSaturation();
  EXPECT_CALL(*mock_, GenerateKeyPair())
      .WillOnce(Return(fake_private_key_.release()))
      .RetiresOnSaturation();
  EXPECT_CALL(*mock_, GetOwnerKeyFilePath())
      .WillRepeatedly(Return(tmpfile_));

  scoped_refptr<OwnerManager> manager(new OwnerManager);
  EXPECT_TRUE(manager->StartTakeOwnershipAttempt());

  message_loop_.Run();
}

TEST_F(OwnerManagerTest, TakeOwnership) {
  StartUnowned();
  ExpectKeyFetchSuccess(true);

  EXPECT_CALL(*mock_, ExportPublicKeyViaDbus(fake_private_key_.get()))
      .WillOnce(Invoke(Win))
      .RetiresOnSaturation();
  EXPECT_CALL(*mock_, GenerateKeyPair())
      .WillOnce(Return(fake_private_key_.release()))
      .RetiresOnSaturation();
  EXPECT_CALL(*mock_, GetOwnerKeyFilePath())
      .WillRepeatedly(Return(tmpfile_));

  scoped_refptr<OwnerManager> manager(new OwnerManager);
  EXPECT_TRUE(manager->StartTakeOwnershipAttempt());

  message_loop_.Run();
}

TEST_F(OwnerManagerTest, NotYetOwnedVerify) {
  StartUnowned();

  // Since this shouldn't happen, don't want it to end the test if it does.
  SetQuitOnKeyFetch(false);

  EXPECT_CALL(*mock_, GetOwnerKeyFilePath())
      .WillRepeatedly(Return(tmpfile_));

  scoped_refptr<OwnerManager> manager(new OwnerManager);
  KeyUser delegate(OwnerManager::KEY_UNAVAILABLE);
  EXPECT_FALSE(manager->StartVerifyAttempt("", "", &delegate));
}

TEST_F(OwnerManagerTest, AlreadyHaveKeysVerify) {
  EXPECT_CALL(*mock_, GetOwnerKeyFilePath())
      .WillRepeatedly(Return(tmpfile_));

  scoped_refptr<OwnerManager> manager(new OwnerManager);
  InjectKeys(manager.get());
  KeyUser delegate(OwnerManager::SUCCESS);
  EXPECT_TRUE(manager->StartVerifyAttempt("", "", &delegate));

  message_loop_.Run();
}

TEST_F(OwnerManagerTest, GetKeyFailDuringVerify) {
  ExpectKeyFetchSuccess(false);

  EXPECT_CALL(*mock_, GetOwnerKeyFilePath())
      .WillRepeatedly(Return(tmpfile_));
  EXPECT_CALL(*mock_, ImportPublicKey(tmpfile_, _))
      .WillOnce(Return(false))
      .RetiresOnSaturation();

  scoped_refptr<OwnerManager> manager(new OwnerManager);
  KeyUser delegate(OwnerManager::KEY_UNAVAILABLE);
  EXPECT_TRUE(manager->StartVerifyAttempt("", "", &delegate));

  message_loop_.Run();
}

TEST_F(OwnerManagerTest, GetKeyAndVerify) {
  ExpectKeyFetchSuccess(true);
  SetQuitOnKeyFetch(false);

  EXPECT_CALL(*mock_, GetOwnerKeyFilePath())
      .WillRepeatedly(Return(tmpfile_));
  EXPECT_CALL(*mock_, ImportPublicKey(tmpfile_, _))
      .WillOnce(DoAll(SetArgumentPointee<1>(fake_public_key_),
                      Return(true)))
      .RetiresOnSaturation();

  scoped_refptr<OwnerManager> manager(new OwnerManager);
  KeyUser delegate(OwnerManager::SUCCESS);
  EXPECT_TRUE(manager->StartVerifyAttempt("", "", &delegate));

  message_loop_.Run();
}

}  // namespace chromeos
<commit_msg>Attempt to fix CrOS build after r56824 part 2.<commit_after>// Copyright (c) 2010 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 "chrome/browser/chromeos/login/owner_manager.h"

#include <cert.h>
#include <keyhi.h>
#include <keythi.h>  // KeyType enum
#include <pk11pub.h>
#include <stdlib.h>

#include <string>

#include "base/crypto/rsa_private_key.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/logging.h"
#include "base/nss_util_internal.h"
#include "base/nss_util.h"
#include "base/scoped_temp_dir.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/common/notification_observer.h"
#include "chrome/common/notification_registrar.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/notification_type.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"

using ::base::RSAPrivateKey;
using ::testing::DoAll;
using ::testing::Invoke;
using ::testing::Return;
using ::testing::SetArgumentPointee;
using ::testing::_;

namespace chromeos {

namespace {

class MockKeyUtils : public OwnerKeyUtils {
 public:
  MockKeyUtils() {}
  ~MockKeyUtils() {}
  MOCK_METHOD0(GenerateKeyPair, RSAPrivateKey*());
  MOCK_METHOD1(ExportPublicKeyViaDbus, bool(RSAPrivateKey* pair));
  MOCK_METHOD2(ExportPublicKeyToFile, bool(RSAPrivateKey* pair,
                                           const FilePath& key_file));
  MOCK_METHOD2(ImportPublicKey, bool(const FilePath& key_file,
                                     std::vector<uint8>* output));
  MOCK_METHOD1(FindPrivateKey, RSAPrivateKey*(const std::vector<uint8>& key));
  MOCK_METHOD0(GetOwnerKeyFilePath, FilePath());
 private:
  DISALLOW_COPY_AND_ASSIGN(MockKeyUtils);
};

class MockInjector : public OwnerKeyUtils::Factory {
 public:
  // Takes ownership of |mock|.
  explicit MockInjector(MockKeyUtils* mock) :
      transient_(mock),
      delete_transient_(true) {
  }

  virtual ~MockInjector() {
    if (delete_transient_)
      delete transient_;
  }

  // If this is called, its caller takes ownership of |transient_|.
  // If it's never called, |transient_| remains our problem.
  OwnerKeyUtils* CreateOwnerKeyUtils() {
    delete_transient_ = false;
    return transient_;
  }

 private:
  MockKeyUtils* transient_;
  bool delete_transient_;
  DISALLOW_COPY_AND_ASSIGN(MockInjector);
};

class KeyUser : public OwnerManager::Delegate {
 public:
  explicit KeyUser(const OwnerManager::KeyOpCode expected)
      : expected_(expected) {
  }

  virtual ~KeyUser() {}

  void OnKeyOpComplete(const OwnerManager::KeyOpCode return_code,
                       const std::string& payload) {
    MessageLoop::current()->Quit();
    EXPECT_EQ(expected_, return_code);
  }

  const OwnerManager::KeyOpCode expected_;
 private:
  DISALLOW_COPY_AND_ASSIGN(KeyUser);
};

static bool Win(RSAPrivateKey* key) {
  MessageLoop::current()->Quit();
  return true;
}

static bool Fail(RSAPrivateKey* key) {
  MessageLoop::current()->Quit();
  return false;
}

}  // anonymous namespace

class OwnerManagerTest : public ::testing::Test,
                         public NotificationObserver {
 public:
  OwnerManagerTest()
      : message_loop_(MessageLoop::TYPE_UI),
        ui_thread_(ChromeThread::UI, &message_loop_),
        file_thread_(ChromeThread::FILE),
        success_expected_(false),
        quit_on_observe_(true),
        mock_(new MockKeyUtils),
        injector_(mock_) /* injector_ takes ownership of mock_ */ {
    registrar_.Add(
        this,
        NotificationType::OWNER_KEY_FETCH_ATTEMPT_FAILED,
        NotificationService::AllSources());
    registrar_.Add(
        this,
        NotificationType::OWNER_KEY_FETCH_ATTEMPT_SUCCEEDED,
        NotificationService::AllSources());
  }
  virtual ~OwnerManagerTest() {}

  virtual void SetUp() {
    base::OpenPersistentNSSDB();  // TODO(cmasone): use test DB instead
    fake_private_key_.reset(RSAPrivateKey::Create(256));
    ASSERT_TRUE(fake_private_key_->ExportPublicKey(&fake_public_key_));

    // Mimic ownership.
    ASSERT_TRUE(tmpdir_.CreateUniqueTempDir());
    ASSERT_TRUE(file_util::CreateTemporaryFileInDir(tmpdir_.path(), &tmpfile_));

    file_thread_.Start();
    OwnerKeyUtils::set_factory(&injector_);
  }

  virtual void TearDown() {
    OwnerKeyUtils::set_factory(NULL);
  }

  void StartUnowned() {
    file_util::Delete(tmpfile_, false);
  }

  void InjectKeys(OwnerManager* manager) {
    manager->public_key_ = fake_public_key_;
    manager->private_key_.reset(fake_private_key_.release());
  }

  // NotificationObserver implementation.
  virtual void Observe(NotificationType type,
                       const NotificationSource& source,
                       const NotificationDetails& details) {
    if (type == NotificationType::OWNER_KEY_FETCH_ATTEMPT_SUCCEEDED) {
      EXPECT_TRUE(success_expected_);
      if (quit_on_observe_)
        MessageLoop::current()->Quit();
    } else if (type == NotificationType::OWNER_KEY_FETCH_ATTEMPT_FAILED) {
      EXPECT_FALSE(success_expected_);
      if (quit_on_observe_)
        MessageLoop::current()->Quit();
    }
  }

  void ExpectKeyFetchSuccess(bool should_succeed) {
    success_expected_ = should_succeed;
  }

  void SetQuitOnKeyFetch(bool should_quit) { quit_on_observe_ = should_quit; }

  ScopedTempDir tmpdir_;
  FilePath tmpfile_;

  MessageLoop message_loop_;
  ChromeThread ui_thread_;
  ChromeThread file_thread_;

  std::vector<uint8> fake_public_key_;
  scoped_ptr<RSAPrivateKey> fake_private_key_;

  NotificationRegistrar registrar_;
  bool success_expected_;
  bool quit_on_observe_;

  MockKeyUtils* mock_;
  MockInjector injector_;
};

TEST_F(OwnerManagerTest, LoadKeyUnowned) {
  StartUnowned();

  EXPECT_CALL(*mock_, GetOwnerKeyFilePath())
      .WillRepeatedly(Return(tmpfile_));

  scoped_refptr<OwnerManager> manager(new OwnerManager);
  EXPECT_FALSE(manager->StartLoadOwnerKeyAttempt());
}

TEST_F(OwnerManagerTest, LoadOwnerKeyFail) {
  EXPECT_CALL(*mock_, GetOwnerKeyFilePath())
      .WillRepeatedly(Return(tmpfile_));
  EXPECT_CALL(*mock_, ImportPublicKey(tmpfile_, _))
      .WillOnce(Return(false))
      .RetiresOnSaturation();

  scoped_refptr<OwnerManager> manager(new OwnerManager);
  EXPECT_TRUE(manager->StartLoadOwnerKeyAttempt());

  // Run remaining events, until ExportPublicKeyViaDbus().
  message_loop_.Run();
}

TEST_F(OwnerManagerTest, LoadOwnerKey) {
  ExpectKeyFetchSuccess(true);

  EXPECT_CALL(*mock_, GetOwnerKeyFilePath())
      .WillRepeatedly(Return(tmpfile_));
  EXPECT_CALL(*mock_, ImportPublicKey(tmpfile_, _))
      .WillOnce(DoAll(SetArgumentPointee<1>(fake_public_key_),
                      Return(true)))
      .RetiresOnSaturation();

  scoped_refptr<OwnerManager> manager(new OwnerManager);
  EXPECT_TRUE(manager->StartLoadOwnerKeyAttempt());

  // Run remaining events, until ExportPublicKeyViaDbus().
  message_loop_.Run();
}

TEST_F(OwnerManagerTest, TakeOwnershipAlreadyOwned) {
  EXPECT_CALL(*mock_, GetOwnerKeyFilePath())
      .WillRepeatedly(Return(tmpfile_));

  scoped_refptr<OwnerManager> manager(new OwnerManager);
  EXPECT_FALSE(manager->StartTakeOwnershipAttempt());
}

TEST_F(OwnerManagerTest, KeyGenerationFail) {
  StartUnowned();

  EXPECT_CALL(*mock_, GenerateKeyPair())
      .WillOnce(Return(reinterpret_cast<RSAPrivateKey*>(NULL)))
      .RetiresOnSaturation();
  EXPECT_CALL(*mock_, GetOwnerKeyFilePath())
      .WillRepeatedly(Return(tmpfile_));

  scoped_refptr<OwnerManager> manager(new OwnerManager);
  EXPECT_TRUE(manager->StartTakeOwnershipAttempt());

  message_loop_.Run();
}

TEST_F(OwnerManagerTest, KeyExportFail) {
  StartUnowned();

  EXPECT_CALL(*mock_, ExportPublicKeyViaDbus(fake_private_key_.get()))
      .WillOnce(Invoke(Fail))
      .RetiresOnSaturation();
  EXPECT_CALL(*mock_, GenerateKeyPair())
      .WillOnce(Return(fake_private_key_.release()))
      .RetiresOnSaturation();
  EXPECT_CALL(*mock_, GetOwnerKeyFilePath())
      .WillRepeatedly(Return(tmpfile_));

  scoped_refptr<OwnerManager> manager(new OwnerManager);
  EXPECT_TRUE(manager->StartTakeOwnershipAttempt());

  message_loop_.Run();
}

TEST_F(OwnerManagerTest, TakeOwnership) {
  StartUnowned();
  ExpectKeyFetchSuccess(true);

  EXPECT_CALL(*mock_, ExportPublicKeyViaDbus(fake_private_key_.get()))
      .WillOnce(Invoke(Win))
      .RetiresOnSaturation();
  EXPECT_CALL(*mock_, GenerateKeyPair())
      .WillOnce(Return(fake_private_key_.release()))
      .RetiresOnSaturation();
  EXPECT_CALL(*mock_, GetOwnerKeyFilePath())
      .WillRepeatedly(Return(tmpfile_));

  scoped_refptr<OwnerManager> manager(new OwnerManager);
  EXPECT_TRUE(manager->StartTakeOwnershipAttempt());

  message_loop_.Run();
}

TEST_F(OwnerManagerTest, NotYetOwnedVerify) {
  StartUnowned();

  // Since this shouldn't happen, don't want it to end the test if it does.
  SetQuitOnKeyFetch(false);

  EXPECT_CALL(*mock_, GetOwnerKeyFilePath())
      .WillRepeatedly(Return(tmpfile_));

  scoped_refptr<OwnerManager> manager(new OwnerManager);
  KeyUser delegate(OwnerManager::KEY_UNAVAILABLE);
  EXPECT_FALSE(manager->StartVerifyAttempt("", "", &delegate));
}

TEST_F(OwnerManagerTest, AlreadyHaveKeysVerify) {
  EXPECT_CALL(*mock_, GetOwnerKeyFilePath())
      .WillRepeatedly(Return(tmpfile_));

  scoped_refptr<OwnerManager> manager(new OwnerManager);
  InjectKeys(manager.get());
  KeyUser delegate(OwnerManager::SUCCESS);
  EXPECT_TRUE(manager->StartVerifyAttempt("", "", &delegate));

  message_loop_.Run();
}

TEST_F(OwnerManagerTest, GetKeyFailDuringVerify) {
  ExpectKeyFetchSuccess(false);

  EXPECT_CALL(*mock_, GetOwnerKeyFilePath())
      .WillRepeatedly(Return(tmpfile_));
  EXPECT_CALL(*mock_, ImportPublicKey(tmpfile_, _))
      .WillOnce(Return(false))
      .RetiresOnSaturation();

  scoped_refptr<OwnerManager> manager(new OwnerManager);
  KeyUser delegate(OwnerManager::KEY_UNAVAILABLE);
  EXPECT_TRUE(manager->StartVerifyAttempt("", "", &delegate));

  message_loop_.Run();
}

TEST_F(OwnerManagerTest, GetKeyAndVerify) {
  ExpectKeyFetchSuccess(true);
  SetQuitOnKeyFetch(false);

  EXPECT_CALL(*mock_, GetOwnerKeyFilePath())
      .WillRepeatedly(Return(tmpfile_));
  EXPECT_CALL(*mock_, ImportPublicKey(tmpfile_, _))
      .WillOnce(DoAll(SetArgumentPointee<1>(fake_public_key_),
                      Return(true)))
      .RetiresOnSaturation();

  scoped_refptr<OwnerManager> manager(new OwnerManager);
  KeyUser delegate(OwnerManager::SUCCESS);
  EXPECT_TRUE(manager->StartVerifyAttempt("", "", &delegate));

  message_loop_.Run();
}

}  // namespace chromeos
<|endoftext|>


<commit_before>#include <iostream>
#include <vector>
#include <atomic>
#include <gtest/gtest.h>
#include "../parallel_async.h"
#include "../task.h"

class ConsumerProducerTest : testing::Test { };

TEST(ConsumerProducerTest, Test1)
{
	const size_t N = 100;
	std::atomic<size_t> f;
	f = 0;
	auto task = asyncply::parallel_async(
		[&]()
		{
			for (size_t i = 0; i < (N + 1); ++i)
			{
				f += i;
			}
		},
		[&]()
		{
			for (size_t i = 0; i < N; ++i)
			{
				f -= i;
			}
		});
	task->get();
	ASSERT_EQ(f, N);
}

<commit_msg>comment tests<commit_after>#include <iostream>
#include <vector>
#include <atomic>
#include <gtest/gtest.h>
#include "../parallel_async.h"
#include "../task.h"

class ConsumerProducerTest : testing::Test { };

#if 0

TEST(ConsumerProducerTest, Test1)
{
	const size_t N = 100;
	std::atomic<size_t> f;
	f = 0;
	auto task = asyncply::parallel_async(
		[&]()
		{
			for (size_t i = 0; i < (N + 1); ++i)
			{
				f += i;
			}
		},
		[&]()
		{
			for (size_t i = 0; i < N; ++i)
			{
				f -= i;
			}
		});
	task->get();
	ASSERT_EQ(f, N);
}

#endif

<|endoftext|>


<commit_before>/*
 * The MIT License
 *
 * Copyright 2017-2018 Norwegian University of Technology
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING  FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

#define BOOST_TEST_MODULE ControlledTemperature_Modeldescription_Test

#include <string>
#include <boost/test/unit_test.hpp>
#include <fmicpp/tools/os_util.hpp>
#include <fmicpp/fmi2/fmicpp.hpp>

using namespace std;
using namespace fmicpp::fmi2;

const string fmu_path = string(getenv("TEST_FMUs"))
                        + "/FMI_2.0/CoSimulation/" + getOs() +
                        "/20sim/4.6.4.8004/ControlledTemperature/ControlledTemperature.fmu";

BOOST_AUTO_TEST_CASE(test1) {

    import::Fmu fmu(fmu_path);
    auto md = fmu.getModelDescription();
    auto md_cs = md.asCoSimulationModelDescription();

    BOOST_CHECK_EQUAL("2.0", md.fmiVersion());
    BOOST_CHECK_EQUAL("ControlledTemperature", md.modelName());

    BOOST_CHECK_EQUAL("{06c2700b-b39c-4895-9151-304ddde28443}", md.guid());
    BOOST_CHECK_EQUAL("{06c2700b-b39c-4895-9151-304ddde28443}", md_cs->guid());
    BOOST_CHECK_EQUAL("20-sim", md.generationTool());
    BOOST_CHECK_EQUAL("20-sim", md_cs->generationTool());

    BOOST_CHECK_EQUAL(true, md.supportsCoSimulation());
    BOOST_CHECK_EQUAL(false, md.supportsModelExchange());

    BOOST_CHECK_EQUAL(120, md.modelVariables().size());
    BOOST_CHECK_EQUAL(120, md_cs->modelVariables().size());

    auto heatCapatacity1 = md.getVariableByName("HeatCapacity1.T0").asRealVariable();
    BOOST_CHECK_EQUAL(1, heatCapatacity1.getValueReference());
    BOOST_CHECK_EQUAL(nullptr, heatCapatacity1.getMin());
    BOOST_CHECK_EQUAL(nullptr, heatCapatacity1.getMax());
    BOOST_CHECK_EQUAL(298.0, *heatCapatacity1.getStart());
    BOOST_CHECK_EQUAL("starting temperature", heatCapatacity1.getDescription());
    BOOST_CHECK_EQUAL(nullptr, heatCapatacity1.getQuantity());

    auto thermalConductor = md.getVariableByValueReference(12);
    BOOST_CHECK_EQUAL("TemperatureSource.T", thermalConductor.getName());
    BOOST_CHECK(fmi2Variability::tunable == thermalConductor.getVariability());
    BOOST_CHECK(fmi2Causality::parameter == thermalConductor.getCausality());

    auto sourceFiles = md_cs->sourceFiles();
    BOOST_CHECK_EQUAL(10, sourceFiles.size());
    BOOST_CHECK_EQUAL("EulerAngles.c", sourceFiles.at(0).name());

    auto outputs = md.modelStructure().outputs();
    BOOST_CHECK_EQUAL(2, outputs.size());
    BOOST_CHECK_EQUAL(115, outputs[0].index());
    BOOST_CHECK_EQUAL(116, outputs[1].index());

}<commit_msg>add more tests<commit_after>/*
 * The MIT License
 *
 * Copyright 2017-2018 Norwegian University of Technology
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING  FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

#define BOOST_TEST_MODULE ControlledTemperature_Modeldescription_Test

#include <string>
#include <boost/test/unit_test.hpp>
#include <fmicpp/tools/os_util.hpp>
#include <fmicpp/fmi2/fmicpp.hpp>

using namespace std;
using namespace fmicpp::fmi2;

const string fmu_path = string(getenv("TEST_FMUs"))
                        + "/FMI_2.0/CoSimulation/" + getOs() +
                        "/20sim/4.6.4.8004/ControlledTemperature/ControlledTemperature.fmu";

BOOST_AUTO_TEST_CASE(test1) {

    import::Fmu fmu(fmu_path);
    auto md = fmu.getModelDescription();
    auto md_cs = md.asCoSimulationModelDescription();

    BOOST_CHECK_EQUAL("2.0", md.fmiVersion());
    BOOST_CHECK_EQUAL("ControlledTemperature", md.modelName());

    BOOST_CHECK_EQUAL("{06c2700b-b39c-4895-9151-304ddde28443}", md.guid());
    BOOST_CHECK_EQUAL("{06c2700b-b39c-4895-9151-304ddde28443}", md_cs->guid());
    BOOST_CHECK_EQUAL("20-sim", md.generationTool());
    BOOST_CHECK_EQUAL("20-sim", md_cs->generationTool());

    BOOST_CHECK_EQUAL(true, md.supportsCoSimulation());
    BOOST_CHECK_EQUAL(false, md.supportsModelExchange());

    BOOST_CHECK_EQUAL(120, md.modelVariables().size());
    BOOST_CHECK_EQUAL(120, md_cs->modelVariables().size());

    auto heatCapatacity1 = md.getVariableByName("HeatCapacity1.T0").asRealVariable();
    BOOST_CHECK_EQUAL(1, heatCapatacity1.getValueReference());
    BOOST_CHECK_EQUAL(nullptr, heatCapatacity1.getMin());
    BOOST_CHECK_EQUAL(nullptr, heatCapatacity1.getMax());
    BOOST_CHECK_EQUAL(298.0, *heatCapatacity1.getStart());
    BOOST_CHECK_EQUAL("starting temperature", heatCapatacity1.getDescription());
    BOOST_CHECK_EQUAL(nullptr, heatCapatacity1.getQuantity());

    auto thermalConductor = md.getVariableByValueReference(12);
    BOOST_CHECK_EQUAL("TemperatureSource.T", thermalConductor.getName());
    BOOST_CHECK(fmi2Variability::tunable == thermalConductor.getVariability());
    BOOST_CHECK(fmi2Causality::parameter == thermalConductor.getCausality());

    auto sourceFiles = md_cs->sourceFiles();
    BOOST_CHECK_EQUAL(10, sourceFiles.size());
    BOOST_CHECK_EQUAL("EulerAngles.c", sourceFiles.at(0).name());

    auto outputs = md.modelStructure().outputs();
    BOOST_CHECK_EQUAL(2, outputs.size());
    BOOST_CHECK_EQUAL(115, outputs[0].index());
    BOOST_CHECK_EQUAL(116, outputs[1].index());

    auto de = md.defaultExperiment();
    BOOST_CHECK(de != nullptr);
    BOOST_CHECK_EQUAL(0.0, *de->startTime());
    BOOST_CHECK_EQUAL(20.0, *de->stopTime());
    BOOST_CHECK_EQUAL(1E-4, *de->stepSize());
    BOOST_CHECK_EQUAL(nullptr, de->tolerance());

}<|endoftext|>


<commit_before>#include <iostream>
#include <vector>
#include <cmath>
#include "../parallel.h"
#include "../sequence.h"
#include "../task.h"

int main(int, const char**)
{
	try
	{
		for (int i = 0; i < 100; ++i)
		{
			std::vector<asyncply::task_t< asyncply::task_t<double> > > vjobs;
			asyncply::_parallel(vjobs,
				[&]()
				{
					return asyncply::sequence(7.0,
						[](double data)
						{
							return data + 3.0;
						},
						[](double data)
						{
							return data + 4.0;
						});
				},
				[&]()
				{
					return asyncply::sequence(9.0,
						[](double data)
						{
							return data + 5.0;
						},
						[](double data)
						{
							return data + 4.0;
						});
				});
			double aggregation = 0.0;
			for (auto& job : vjobs)
			{
				try
				{
					// double get get
					double partial = job->get()->get();
					aggregation += partial;
				}
				catch (std::exception& e)
				{
					std::cout << "exception: " << e.what() << std::endl;
				}
			}
			if (std::abs(aggregation - 32.0) > 1e-3)
			{
				std::cout << "invalid total " << aggregation << std::endl;
				throw std::exception();
			}
			// std::cout << "aggregation = " << aggregation << std::endl;
		}
		std::cout << "result ok" << std::endl;
	}
	catch (std::exception& e)
	{
		std::cout << "general exception " << e.what() << std::endl;
		return 1;
	}
	return 0;
}

<commit_msg>Update test_parallel_sequence.cpp<commit_after>#include <iostream>
#include <vector>
#include <cmath>
#include "../parallel.h"
#include "../sequence.h"
#include "../task.h"
#include <gtest/gtest.h>

class ParallelSequenceTest : testing::Test
{

};

TEST(ParallelSequenceTest, Test1)
{
	std::vector<asyncply::task_t< asyncply::task_t<double> > > vjobs;
	asyncply::_parallel(vjobs,
		[&]()
		{
			return asyncply::sequence(7.0,
				[](double data)
				{
					return data + 3.0;
				},
				[](double data)
				{
					return data + 4.0;
				});
		},
		[&]()
		{
			return asyncply::sequence(9.0,
				[](double data)
				{
					return data + 5.0;
				},
				[](double data)
				{
					return data + 4.0;
				});
		});
	double aggregation = 0.0;
	for (auto& job : vjobs)
	{
		try
		{
			double partial = job->get()->get();
			aggregation += partial;
		}
		catch (std::exception& e)
		{
			std::cout << "exception: " << e.what() << std::endl;
		}
	}
	ASSERT_EQ(aggregation, 32.0);
}
<|endoftext|>


<commit_before>#include "Mescaline/API.h"
#include "Mescaline/Audio/Client.hpp"
#include "Mescaline/Audio/IO/Client.hpp"
#include "Mescaline/Audio/IO/JackDriver.hpp"
#include "Mescaline/Audio/Group.hpp"
#include "Mescaline/Audio/Synth.hpp"
#include "Mescaline/Audio/SynthDef.hpp"

#include <cstdlib>
#include <cstring>
#include <iostream>

#include "lilv/lilv.h"
#include "lv2/lv2plug.in/ns/ext/atom/atom.h"
#include "lv2/lv2plug.in/ns/ext/atom/forge.h"
#include "lv2/lv2plug.in/ns/ext/atom/util.h"

class MyLoader : public Mescaline::Audio::Plugin::StaticLoader
{
public:
    MyLoader()
        : Mescaline::Audio::Plugin::StaticLoader(descriptorFunctions())
    {
        const char* bundlePath = getenv("MESCALINE_LV2_PATH");
        if (bundlePath) {
            setenv("LV2_PATH", bundlePath, 1);
        } else {
            setenv("LV2_PATH", "/Users/sk/Library/Audio/Plug-Ins/LV2", 1);
        }
    }

    static Mescaline::Audio::Plugin::StaticLoader::DescriptorFunctionMap descriptorFunctions()
    {
        Mescaline::Audio::Plugin::StaticLoader::DescriptorFunctionMap dfs;
        extern const LV2_Descriptor* puesnada_sine_lv2_descriptor(uint32_t index);
        dfs["http://mescaline.puesnada.es/lv2/plugins/sine"] = puesnada_sine_lv2_descriptor;
        return dfs;
    }
};

class MyEngine : public Mescaline::Audio::Engine
{
public:
    MyEngine(MyLoader* loader)
        : Mescaline::Audio::Engine(loader)
    { }

    virtual void configure(const Mescaline::Audio::IO::Driver& driver)
    {
        Mescaline::Audio::Engine::configure(driver);

        // Create sine instance
        const Mescaline::Audio::Plugin::Manager::PluginHandle& def = env().plugins().lookup(
            "http://mescaline.puesnada.es/lv2/plugins/sine" );
        Mescaline::Audio::Synth* synth = Mescaline::Audio::Synth::construct(env(), env().nextResourceId(), env().rootNode(), *def);
        env().rootNode()->addToTail(*synth);
        synth->mapOutput(0, env().audioBus(Mescaline::Audio::ResourceId(3)), Mescaline::Audio::kOut);

//        const Mescaline::Audio::SynthDef& scopeDef = environment()->lookupSynthDef("scope");
//        Mescaline::Audio::Synth* scope = Mescaline::Audio::Synth::construct(*environment(), 2, environment()->rootNode(), scopeDef);
//        environment()->rootNode()->addToTail(*scope);
//        scope->mapInput(0, Mescaline::Audio::AudioBusId(Mescaline::Audio::AudioBusId::kOutput, 0), Mescaline::Audio::kIn);
//        m_scope = scope->synth<Mescaline::Audio::ScopeSynth>();
    }
};

using namespace std;

struct Mescaline_Engine
{
    Mescaline::Audio::Engine*     m_engine;
    Mescaline::Audio::IO::Driver* m_audioDriver;
};

Mescaline_Engine* Mescaline_Engine_new()
{
    cout << "Mescaline_Engine_new" << endl;
    Mescaline_Engine* engine = new Mescaline_Engine;
    engine->m_engine = new MyEngine(new MyLoader());
    engine->m_audioDriver = new Mescaline::Audio::IO::JackDriver(engine->m_engine);
    return engine;
}

void Mescaline_Engine_free(Mescaline_Engine* engine)
{
    cout << "Mescaline_Engine_free" << endl;
    Mescaline_Engine_stop(engine);
    delete engine->m_engine;
    delete engine->m_audioDriver;
    delete engine;
}

void Mescaline_Engine_start(Mescaline_Engine* engine)
{
    cout << "Mescaline_Engine_start" << endl;
    engine->m_audioDriver->start();
}

void Mescaline_Engine_stop(Mescaline_Engine* engine)
{
    cout << "Mescaline_Engine_stop" << endl;
    engine->m_audioDriver->stop();
}

LV2_URID Mescaline_Engine_mapUri(Mescaline_Engine* engine, const char* uri)
{
	return engine->m_engine->env().mapUri(uri);
}

const char* Mescaline_Engine_unmapUri(Mescaline_Engine* engine, LV2_URID urid)
{
	return engine->m_engine->env().unmapUri(urid);
}

void Mescaline_Engine_request(Mescaline_Engine* engine, LV2_Atom* request, Mescaline_HandleResponse handler, void* handlerData)
{
    engine->m_engine->env().request(request, handler, handlerData);
}
<commit_msg>Disable debug output<commit_after>#include "Mescaline/API.h"
#include "Mescaline/Audio/Client.hpp"
#include "Mescaline/Audio/IO/Client.hpp"
#include "Mescaline/Audio/IO/JackDriver.hpp"
#include "Mescaline/Audio/Group.hpp"
#include "Mescaline/Audio/Synth.hpp"
#include "Mescaline/Audio/SynthDef.hpp"

#include <cstdlib>
#include <cstring>
#include <iostream>

#include "lilv/lilv.h"
#include "lv2/lv2plug.in/ns/ext/atom/atom.h"
#include "lv2/lv2plug.in/ns/ext/atom/forge.h"
#include "lv2/lv2plug.in/ns/ext/atom/util.h"

class MyLoader : public Mescaline::Audio::Plugin::StaticLoader
{
public:
    MyLoader()
        : Mescaline::Audio::Plugin::StaticLoader(descriptorFunctions())
    {
        const char* bundlePath = getenv("MESCALINE_LV2_PATH");
        if (bundlePath) {
            setenv("LV2_PATH", bundlePath, 1);
        } else {
            setenv("LV2_PATH", "/Users/sk/Library/Audio/Plug-Ins/LV2", 1);
        }
    }

    static Mescaline::Audio::Plugin::StaticLoader::DescriptorFunctionMap descriptorFunctions()
    {
        Mescaline::Audio::Plugin::StaticLoader::DescriptorFunctionMap dfs;
        extern const LV2_Descriptor* puesnada_sine_lv2_descriptor(uint32_t index);
        dfs["http://mescaline.puesnada.es/lv2/plugins/sine"] = puesnada_sine_lv2_descriptor;
        return dfs;
    }
};

class MyEngine : public Mescaline::Audio::Engine
{
public:
    MyEngine(MyLoader* loader)
        : Mescaline::Audio::Engine(loader)
    { }

    virtual void configure(const Mescaline::Audio::IO::Driver& driver)
    {
        Mescaline::Audio::Engine::configure(driver);

        // Create sine instance
        const Mescaline::Audio::Plugin::Manager::PluginHandle& def = env().plugins().lookup(
            "http://mescaline.puesnada.es/lv2/plugins/sine" );
        Mescaline::Audio::Synth* synth = Mescaline::Audio::Synth::construct(env(), env().nextResourceId(), env().rootNode(), *def);
        env().rootNode()->addToTail(*synth);
        synth->mapOutput(0, env().audioBus(Mescaline::Audio::ResourceId(3)), Mescaline::Audio::kOut);

//        const Mescaline::Audio::SynthDef& scopeDef = environment()->lookupSynthDef("scope");
//        Mescaline::Audio::Synth* scope = Mescaline::Audio::Synth::construct(*environment(), 2, environment()->rootNode(), scopeDef);
//        environment()->rootNode()->addToTail(*scope);
//        scope->mapInput(0, Mescaline::Audio::AudioBusId(Mescaline::Audio::AudioBusId::kOutput, 0), Mescaline::Audio::kIn);
//        m_scope = scope->synth<Mescaline::Audio::ScopeSynth>();
    }
};

using namespace std;

struct Mescaline_Engine
{
    Mescaline::Audio::Engine*     m_engine;
    Mescaline::Audio::IO::Driver* m_audioDriver;
};

Mescaline_Engine* Mescaline_Engine_new()
{
    // cout << "Mescaline_Engine_new" << endl;
    Mescaline_Engine* engine = new Mescaline_Engine;
    engine->m_engine = new MyEngine(new MyLoader());
    engine->m_audioDriver = new Mescaline::Audio::IO::JackDriver(engine->m_engine);
    return engine;
}

void Mescaline_Engine_free(Mescaline_Engine* engine)
{
    // cout << "Mescaline_Engine_free" << endl;
    Mescaline_Engine_stop(engine);
    delete engine->m_engine;
    delete engine->m_audioDriver;
    delete engine;
}

void Mescaline_Engine_start(Mescaline_Engine* engine)
{
    // cout << "Mescaline_Engine_start" << endl;
    engine->m_audioDriver->start();
}

void Mescaline_Engine_stop(Mescaline_Engine* engine)
{
    // cout << "Mescaline_Engine_stop" << endl;
    engine->m_audioDriver->stop();
}

LV2_URID Mescaline_Engine_mapUri(Mescaline_Engine* engine, const char* uri)
{
	return engine->m_engine->env().mapUri(uri);
}

const char* Mescaline_Engine_unmapUri(Mescaline_Engine* engine, LV2_URID urid)
{
	return engine->m_engine->env().unmapUri(urid);
}

void Mescaline_Engine_request(Mescaline_Engine* engine, LV2_Atom* request, Mescaline_HandleResponse handler, void* handlerData)
{
    engine->m_engine->env().request(request, handler, handlerData);
}
<|endoftext|>


<commit_before>//////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2008, Image Engine Design Inc. 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 Image Engine Design nor the names of any
//       other contributors to this software 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 OWNER 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 "IECore/PrimitiveEvaluator.h"

using namespace IECore;

PrimitiveEvaluator::CreatorMap &PrimitiveEvaluator::getCreateFns()
{
	static CreatorMap *g_createFns = new CreatorMap();
	assert( g_createFns );
	return *g_createFns;
}

void PrimitiveEvaluator::registerCreator( TypeId id, CreatorFn f )
{
	assert( f );

        CreatorMap &createFns = getCreateFns();

        assert( createFns.find( id ) == createFns.end() );

        createFns.insert( CreatorMap::value_type( id, f) );
}

PrimitiveEvaluatorPtr PrimitiveEvaluator::create( ConstPrimitivePtr primitive )
{
	assert( primitive );

        const CreatorMap &createFns = getCreateFns();

        CreatorMap::const_iterator it = createFns.find( primitive->typeId() );
        if (it == createFns.end())
        {
                return 0;
        }

        return (it->second)(primitive);
}

PrimitiveEvaluator::~PrimitiveEvaluator()
{
}

PrimitiveEvaluator::Result::~Result()
{
}
<commit_msg>Added assert<commit_after>//////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2008, Image Engine Design Inc. 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 Image Engine Design nor the names of any
//       other contributors to this software 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 OWNER 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 "IECore/PrimitiveEvaluator.h"

using namespace IECore;

PrimitiveEvaluator::CreatorMap &PrimitiveEvaluator::getCreateFns()
{
	static CreatorMap *g_createFns = new CreatorMap();
	assert( g_createFns );
	return *g_createFns;
}

void PrimitiveEvaluator::registerCreator( TypeId id, CreatorFn f )
{
	assert( f );
	assert( f != &PrimitiveEvaluator::create );

        CreatorMap &createFns = getCreateFns();

        assert( createFns.find( id ) == createFns.end() );

        createFns.insert( CreatorMap::value_type( id, f) );
}

PrimitiveEvaluatorPtr PrimitiveEvaluator::create( ConstPrimitivePtr primitive )
{
	assert( primitive );

        const CreatorMap &createFns = getCreateFns();

        CreatorMap::const_iterator it = createFns.find( primitive->typeId() );
        if (it == createFns.end())
        {
                return 0;
        }

        return (it->second)(primitive);
}

PrimitiveEvaluator::~PrimitiveEvaluator()
{
}

PrimitiveEvaluator::Result::~Result()
{
}
<|endoftext|>


<commit_before>/**
 * @file
 * @author  Mohammad S. Babaei <info@babaei.net>
 * @version 0.1.0
 *
 * @section LICENSE
 *
 * (The MIT License)
 *
 * Copyright (c) 2016 Mohammad S. Babaei
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 * @section DESCRIPTION
 *
 * Main entry for the web application.
 */

#include <csignal>
#include <cstdlib>
#if defined ( _WIN32 )
#include <windows.h>
#else
#include <unistd.h>
#endif  // defined ( _WIN32 )
#include <boost/algorithm/string.hpp>
#include <boost/exception/diagnostic_information.hpp>
#include <boost/filesystem/exception.hpp>
#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/format.hpp>
#include <Wt/WServer>
#if MAGICKPP_BACKEND == MAGICKPP_GM
#include <GraphicsMagick/Magick++.h>
#elif MAGICKPP_BACKEND == MAGICKPP_IM
#include <ImageMagick-6/Magick++.h>
#endif // MAGICKPP_BACKEND == MAGICKPP_GM
#include <statgrab.h>
#include <CoreLib/CoreLib.hpp>
#include <CoreLib/Database.hpp>
#include <CoreLib/Exception.hpp>
#include <CoreLib/Log.hpp>
#include <CoreLib/make_unique.hpp>
#include <CoreLib/System.hpp>
#include "CgiRoot.hpp"
#include "Exception.hpp"
#include "Pool.hpp"
#include "VersionInfo.hpp"

void Terminate [[noreturn]] (int signo);
void InitializeDatabase();

#if defined ( __unix__ )
int main(int argc, char **argv, char **envp)
#else
int main(int argc, char **argv)
#endif  // defined ( __unix__ )
{
    try {
        /// Gracefully handling SIGTERM
        void (*prev_fn)(int);
        prev_fn = signal(SIGTERM, Terminate);
        if (prev_fn == SIG_IGN)
            signal(SIGTERM, SIG_IGN);

        /// Extract the executable path and name
        boost::filesystem::path path(boost::filesystem::initial_path<boost::filesystem::path>());
        if (argc > 0 && argv[0] != NULL)
            path = boost::filesystem::system_complete(boost::filesystem::path(argv[0]));
        std::string appId(path.filename().string());
        std::string appPath(boost::algorithm::replace_last_copy(path.string(), appId, ""));
        Service::Pool::Storage()->AppPath = appPath;

        /// Force changing the current path to executable path
        boost::filesystem::current_path(appPath);

        /// Initializing CoreLib
        CoreLib::CoreLibInitialize(argc, argv);

        /// Initializing log system
        CoreLib::Log::Initialize(std::cout,
                                 (boost::filesystem::path(appPath)
                                  / boost::filesystem::path("..")
                                  / boost::filesystem::path("log")).string(),
                                 "JobApplicationSystemServer");

        /// Acquiring process lock
        std::string lockId;
#if defined ( __unix__ )
        int lock;
        lockId = (boost::filesystem::path(appPath)
                  / boost::filesystem::path("..")
                  / boost::filesystem::path("tmp")
                  / (appId + ".lock")).string();
#elif defined ( _WIN32 )
        HANDLE lock;
        lockId = appId;
#endif  // defined ( __unix__ )

        /// Logging application info
        LOG_INFO("Version Information", "", "BUILD_COMPILER             " VERSION_INFO_BUILD_COMPILER, "BUILD_DATE                 " VERSION_INFO_BUILD_DATE, "BUILD_HOST                 " VERSION_INFO_BUILD_HOST, "BUILD_PROCESSOR            " VERSION_INFO_BUILD_PROCESSOR, "BUILD_SYSTEM               " VERSION_INFO_BUILD_SYSTEM, "PRODUCT_COMPANY_NAME       " VERSION_INFO_PRODUCT_COMPANY_NAME, "PRODUCT_COPYRIGHT          " VERSION_INFO_PRODUCT_COPYRIGHT, "PRODUCT_INTERNAL_NAME      " VERSION_INFO_PRODUCT_INTERNAL_NAME, "PRODUCT_NAME               " VERSION_INFO_PRODUCT_NAME, "PRODUCT_VERSION            " VERSION_INFO_PRODUCT_VERSION, "PRODUCT_DESCRIPTION        " VERSION_INFO_PRODUCT_DESCRIPTION);

        if(!CoreLib::System::GetLock(lockId, lock)) {
            LOG_WARNING("Process is already running!");
        } else {
            LOG_INFO("Got the process lock!");
        }

        /*! Initializing Magick++ or You'll crash HARD!! */
        Magick::InitializeMagick(*argv);

        /// Initialize libstatgrab
#if defined ( __unix__ )
#if defined ( __FreeBSD__ )
        sg_init(1);
#else
        sg_init(0);
#endif  // defined ( __FreeBSD__ )
#elif defined ( _WIN32 )
        /// In order to make it work, we have to call it twice
        sg_snapshot();
        sg_snapshot();
#endif  // defined ( __unix__ )
        /// Drop setuid/setgid privileges.
        if (sg_drop_privileges() != SG_ERROR_NONE) {
            LOG_ERROR("Error: Failed to drop privileges!");
        }

        /// Initialize the whole database
        InitializeDatabase();

        /// Starting the server, otherwise going down
        LOG_INFO("Starting the server...");
        Wt::WServer server(argv[0]);
        server.setServerConfiguration(argc, argv, WTHTTP_CONFIGURATION);
        server.addEntryPoint(Wt::Application, Service::CgiRoot::CreateApplication, "", "favicon.ico");
        if (server.start()) {
            int sig = Wt::WServer::waitForShutdown();
            server.stop();

#if defined ( __unix__ )
            /// Experimental, UNIX only
            if (sig == SIGHUP)
                Wt::WServer::restart(argc, argv, envp);
#endif  // defined ( __unix__ )
        }

        /// Shutdown libstatgrab before return
        sg_shutdown();
    }

    catch (Service::Exception &ex) {
        LOG_ERROR(ex.what());
    }

    catch (CoreLib::Exception &ex) {
        LOG_ERROR(ex.what());
    }

    catch (Wt::WServer::Exception &ex) {
        LOG_ERROR(ex.what());
    }

    catch (boost::exception &ex) {
        LOG_ERROR(boost::diagnostic_information(ex));
    }

    catch (std::exception &ex) {
        LOG_ERROR(ex.what());
    }

    catch (...) {
        LOG_ERROR("Unknown error!");
    }

    return EXIT_SUCCESS;
}

void Terminate(int signo)
{
    LOG_WARNING((boost::format("Terminating by signal %1%...") % signo).str());
    exit(1);
}

void InitializeDatabase()
{
    try {
        Service::Pool::Database()->RegisterTable("ROOT", "root",
                                                 " username VARCHAR(16) NOT NULL PRIMARY KEY, "
                                                 " email VARCHAR(254) NOT NULL UNIQUE, "
                                                 " last_login_ip VARCHAR(15), "
                                                 " last_login_location VARCHAR(96), "
                                                 " last_login_rawtime VARCHAR(19), "
                                                 " last_login_gdate VARCHAR(10), "
                                                 " last_login_jdate VARCHAR(10), "
                                                 " last_login_time VARCHAR(10), "
                                                 " last_login_user_agent VARCHAR(256), "
                                                 " last_login_referer VARCHAR(2083), "
                                                 " pwd TEXT NOT NULL, "
                                                 " recovery_pwd TEXT ");

        Service::Pool::Database()->RegisterTable("CONTACTS", "contacts",
                                                 " recipient VARCHAR(64) NOT NULL PRIMARY KEY, "
                                                 " email VARCHAR(254) NOT NULL ");

        Service::Pool::Database()->RegisterTable("SUBSCRIBERS", "subscribers",
                                                 " email VARCHAR(254) NOT NULL PRIMARY KEY, "
                                                 " uuid VARCHAR(36) NOT NULL UNIQUE ");

        Service::Pool::Database()->Initialize();

        cppdb::transaction guard(Service::Pool::Database()->Sql());

        cppdb::result r = Service::Pool::Database()->Sql()
                << (boost::format("SELECT username"
                                  " FROM %1% WHERE username=?;")
                    % Service::Pool::Database()->GetTableName("ROOT")).str()
                << Service::Pool::Storage()->RootUsername() << cppdb::row;

        if (r.empty()) {
            Service::Pool::Database()->Insert("ROOT", "username, email, pwd",
                                              {
                                                  Service::Pool::Storage()->RootUsername(),
                                                  Service::Pool::Storage()->RootInitialEmail(),
                                                  Service::Pool::Storage()->RootInitialPassword()
                                              });

            guard.commit();
        } else {
            guard.rollback();
        }
    }

    catch (std::exception &ex) {
        LOG_ERROR(ex.what());
    }

    catch (...) {
        LOG_ERROR("Unknown error!");
    }
}

<commit_msg>fixed sql init commands<commit_after>/**
 * @file
 * @author  Mohammad S. Babaei <info@babaei.net>
 * @version 0.1.0
 *
 * @section LICENSE
 *
 * (The MIT License)
 *
 * Copyright (c) 2016 Mohammad S. Babaei
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 * @section DESCRIPTION
 *
 * Main entry for the web application.
 */

#include <csignal>
#include <cstdlib>
#if defined ( _WIN32 )
#include <windows.h>
#else
#include <unistd.h>
#endif  // defined ( _WIN32 )
#include <boost/algorithm/string.hpp>
#include <boost/exception/diagnostic_information.hpp>
#include <boost/filesystem/exception.hpp>
#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/format.hpp>
#include <Wt/WServer>
#if MAGICKPP_BACKEND == MAGICKPP_GM
#include <GraphicsMagick/Magick++.h>
#elif MAGICKPP_BACKEND == MAGICKPP_IM
#include <ImageMagick-6/Magick++.h>
#endif // MAGICKPP_BACKEND == MAGICKPP_GM
#include <statgrab.h>
#include <CoreLib/CoreLib.hpp>
#include <CoreLib/Database.hpp>
#include <CoreLib/Exception.hpp>
#include <CoreLib/Log.hpp>
#include <CoreLib/make_unique.hpp>
#include <CoreLib/System.hpp>
#include "CgiRoot.hpp"
#include "Exception.hpp"
#include "Pool.hpp"
#include "VersionInfo.hpp"

void Terminate [[noreturn]] (int signo);
void InitializeDatabase();

#if defined ( __unix__ )
int main(int argc, char **argv, char **envp)
#else
int main(int argc, char **argv)
#endif  // defined ( __unix__ )
{
    try {
        /// Gracefully handling SIGTERM
        void (*prev_fn)(int);
        prev_fn = signal(SIGTERM, Terminate);
        if (prev_fn == SIG_IGN)
            signal(SIGTERM, SIG_IGN);

        /// Extract the executable path and name
        boost::filesystem::path path(boost::filesystem::initial_path<boost::filesystem::path>());
        if (argc > 0 && argv[0] != NULL)
            path = boost::filesystem::system_complete(boost::filesystem::path(argv[0]));
        std::string appId(path.filename().string());
        std::string appPath(boost::algorithm::replace_last_copy(path.string(), appId, ""));
        Service::Pool::Storage()->AppPath = appPath;

        /// Force changing the current path to executable path
        boost::filesystem::current_path(appPath);

        /// Initializing CoreLib
        CoreLib::CoreLibInitialize(argc, argv);

        /// Initializing log system
        CoreLib::Log::Initialize(std::cout,
                                 (boost::filesystem::path(appPath)
                                  / boost::filesystem::path("..")
                                  / boost::filesystem::path("log")).string(),
                                 "JobApplicationSystemServer");

        /// Acquiring process lock
        std::string lockId;
#if defined ( __unix__ )
        int lock;
        lockId = (boost::filesystem::path(appPath)
                  / boost::filesystem::path("..")
                  / boost::filesystem::path("tmp")
                  / (appId + ".lock")).string();
#elif defined ( _WIN32 )
        HANDLE lock;
        lockId = appId;
#endif  // defined ( __unix__ )

        /// Logging application info
        LOG_INFO("Version Information", "", "BUILD_COMPILER             " VERSION_INFO_BUILD_COMPILER, "BUILD_DATE                 " VERSION_INFO_BUILD_DATE, "BUILD_HOST                 " VERSION_INFO_BUILD_HOST, "BUILD_PROCESSOR            " VERSION_INFO_BUILD_PROCESSOR, "BUILD_SYSTEM               " VERSION_INFO_BUILD_SYSTEM, "PRODUCT_COMPANY_NAME       " VERSION_INFO_PRODUCT_COMPANY_NAME, "PRODUCT_COPYRIGHT          " VERSION_INFO_PRODUCT_COPYRIGHT, "PRODUCT_INTERNAL_NAME      " VERSION_INFO_PRODUCT_INTERNAL_NAME, "PRODUCT_NAME               " VERSION_INFO_PRODUCT_NAME, "PRODUCT_VERSION            " VERSION_INFO_PRODUCT_VERSION, "PRODUCT_DESCRIPTION        " VERSION_INFO_PRODUCT_DESCRIPTION);

        if(!CoreLib::System::GetLock(lockId, lock)) {
            LOG_WARNING("Process is already running!");
        } else {
            LOG_INFO("Got the process lock!");
        }

        /*! Initializing Magick++ or You'll crash HARD!! */
        Magick::InitializeMagick(*argv);

        /// Initialize libstatgrab
#if defined ( __unix__ )
#if defined ( __FreeBSD__ )
        sg_init(1);
#else
        sg_init(0);
#endif  // defined ( __FreeBSD__ )
#elif defined ( _WIN32 )
        /// In order to make it work, we have to call it twice
        sg_snapshot();
        sg_snapshot();
#endif  // defined ( __unix__ )
        /// Drop setuid/setgid privileges.
        if (sg_drop_privileges() != SG_ERROR_NONE) {
            LOG_ERROR("Error: Failed to drop privileges!");
        }

        /// Initialize the whole database
        InitializeDatabase();

        /// Starting the server, otherwise going down
        LOG_INFO("Starting the server...");
        Wt::WServer server(argv[0]);
        server.setServerConfiguration(argc, argv, WTHTTP_CONFIGURATION);
        server.addEntryPoint(Wt::Application, Service::CgiRoot::CreateApplication, "", "favicon.ico");
        if (server.start()) {
            int sig = Wt::WServer::waitForShutdown();
            server.stop();

#if defined ( __unix__ )
            /// Experimental, UNIX only
            if (sig == SIGHUP)
                Wt::WServer::restart(argc, argv, envp);
#endif  // defined ( __unix__ )
        }

        /// Shutdown libstatgrab before return
        sg_shutdown();
    }

    catch (Service::Exception &ex) {
        LOG_ERROR(ex.what());
    }

    catch (CoreLib::Exception &ex) {
        LOG_ERROR(ex.what());
    }

    catch (Wt::WServer::Exception &ex) {
        LOG_ERROR(ex.what());
    }

    catch (boost::exception &ex) {
        LOG_ERROR(boost::diagnostic_information(ex));
    }

    catch (std::exception &ex) {
        LOG_ERROR(ex.what());
    }

    catch (...) {
        LOG_ERROR("Unknown error!");
    }

    return EXIT_SUCCESS;
}

void Terminate(int signo)
{
    LOG_WARNING((boost::format("Terminating by signal %1%...") % signo).str());
    exit(1);
}

void InitializeDatabase()
{
    try {
        Service::Pool::Database()->RegisterTable("ROOT", "root",
                                                 " username TEXT NOT NULL PRIMARY KEY, "
                                                 " email TEXT NOT NULL UNIQUE, "
                                                 " last_login_ip TEXT, "
                                                 " last_login_location TEXT, "
                                                 " last_login_rawtime TEXT, "
                                                 " last_login_gdate TEXT, "
                                                 " last_login_jdate TEXT, "
                                                 " last_login_time TEXT, "
                                                 " last_login_user_agent TEXT, "
                                                 " last_login_referer TEXT, "
                                                 " pwd TEXT NOT NULL, "
                                                 " recovery_pwd TEXT ");

        Service::Pool::Database()->RegisterTable("CONTACTS", "contacts",
                                                 " recipient TEXT NOT NULL PRIMARY KEY, "
                                                 " email TEXT NOT NULL ");

        Service::Pool::Database()->RegisterTable("SUBSCRIBERS", "subscribers",
                                                 " email TEXT NOT NULL PRIMARY KEY, "
                                                 " uuid TEXT NOT NULL UNIQUE ");

        Service::Pool::Database()->Initialize();

        cppdb::transaction guard(Service::Pool::Database()->Sql());

        cppdb::result r = Service::Pool::Database()->Sql()
                << (boost::format("SELECT username"
                                  " FROM %1% WHERE username=?;")
                    % Service::Pool::Database()->GetTableName("ROOT")).str()
                << Service::Pool::Storage()->RootUsername() << cppdb::row;

        if (r.empty()) {
            Service::Pool::Database()->Insert("ROOT", "username, email, pwd",
                                              {
                                                  Service::Pool::Storage()->RootUsername(),
                                                  Service::Pool::Storage()->RootInitialEmail(),
                                                  Service::Pool::Storage()->RootInitialPassword()
                                              });

            guard.commit();
        } else {
            guard.rollback();
        }
    }

    catch (std::exception &ex) {
        LOG_ERROR(ex.what());
    }

    catch (...) {
        LOG_ERROR("Unknown error!");
    }
}

<|endoftext|>


<commit_before>#include "../ris_lib/ris_resources_from_file.h"
#include "../ris_lib/ris_bundle_compression.h"
#include "../ris_lib/ris_writing_files.h"
#include "../ris_lib/template.h"
#include "../ris_lib/ris_resource_loader.h"
#include "../ris_lib/ris_default_or_from_file.h"
#include "../ris_lib/ris_resource_snapshot.h"
#include "../ris_lib/ris_late_context.h"
#include "../ris_lib/ris_late.h"
#include "../ris_lib/ris_resource_loader.h"

#include <iostream>
#include <string>
#include <stdexcept>
#include <unordered_map>

#include <boost/filesystem.hpp>

void print_usage() {
    std::cout
        << "---      ris v0.3.0            ---" << std::endl
        << "a simple resource compiler for c++" << std::endl
        << "https://github.com/d-led/ris" << std::endl
        << "USAGE:" << std::endl
        << "       ris <path_to>/<resources>.[json/yml/yaml] [<template_overrides>.[json/yml/yaml]]" << std::endl
        << "Available algorithms: " << ris::bundle_compression().available_algorithms() << std::endl;
        ;
}

template <typename TResource>
std::string member_name(TResource const& res) {
    if (!res.member_name.empty())
        return res.member_name;
    return res.name;
}

void process(std::string const& path, std::string const& source_template) {
    auto full_path = absolute(boost::filesystem::path(path));
    full_path.make_preferred();
    std::cout << "reading " << full_path.generic_string() << std::endl;

    auto user_resources = ris::load_resources_from_file(path);
    auto lookup = user_resources.to_lookup();
    std::cout << "read " << user_resources.resources().resources.size() << " resources" << std::endl;

    auto compression = ris::bundle_compression();
    auto ris_res = ris::default_or_from_file<ris::Resource>(source_template);
    auto template_snapshot = ris::resource_snapshot(ris_res);
    bool any_with_compression = std::any_of(std::begin(user_resources.resources().resources),
        std::end(user_resources.resources().resources),
        [&compression](ris::resource const& res) {
        return compression.is_legal(res.compression);
    });

    ris::write_to_temp_first_then_move header([&ris_res, &template_snapshot, &user_resources,&lookup](std::ostream& s) {
        template_snapshot["namespace_name"] = user_resources.namespace_();
        template_snapshot["class_name"] = user_resources.class_();
        auto lazy = ris::get_context(template_snapshot);
        lazy
            .lazy("header", [&lazy, &ris_res](std::ostream& s) {
                ris::render(ris_res.Get("header"), lazy, s);
            })
            .lazy("header_declarations", [&ris_res,&user_resources,&lazy](std::ostream& s) {
                for (auto& resource : user_resources.resources().resources) {
                    lazy.lazy("resource_member_name", [&resource](std::ostream& s){
                        s << member_name(resource);
                    });
                    ris::render(ris_res.Get("header_single_declaration"), lazy, s);
                }
            })
            .lazy("header_resource_names", [&ris_res, &user_resources, &lazy](std::ostream& s) {
                for (auto& resource : user_resources.resources().resources) {
                    lazy.lazy("resource_name", [&resource](std::ostream& s){
                        s << resource.name;
                    });
                    ris::render(ris_res.Get("header_single_resource_name"), lazy, s);
                }
            })
        ;
        ris::render("{{header}}", lazy, s);
    }, user_resources.header());
    header.start();

    ris::write_to_temp_first_then_move source([&](std::ostream& s) {
        template_snapshot["namespace_name"] = user_resources.namespace_();
        template_snapshot["class_name"] = user_resources.class_();
        auto lazy = ris::get_context(template_snapshot);
        lazy
            .lazy("source", [&lazy, &ris_res](std::ostream& s) {
                ris::render(ris_res.Get("source"), lazy, s);
            })
            .lazy("optional_compression_header", [&](std::ostream& s) {
                if (any_with_compression)
                    s << "#include <bundle.hpp>\n";
            })
            .lazy("source_default_include", [&](std::ostream& s) {
                s << "#include \"" << boost::filesystem::path(user_resources.header()).filename().generic_string() << "\"";
            })
            .lazy("source_definitions", [&](std::ostream& s) {
                for (auto& resource : user_resources.resources().resources) {
                    lazy
                    .lazy("resource_member_name", [&](std::ostream& s){
                        s << member_name(resource);
                    })
                    .lazy("source_literal_bytes", [&](std::ostream& s){
                        static const unsigned MAX_IN_ONE_LINE = 100;
                        std::string data = ris::resource_loader(resource, user_resources.base_path()).get();

                        auto raw_size = data.size();

                        if (compression.is_legal(resource.compression)) {
                            data = compression.pack(resource.compression, data);
                            auto new_size = data.size();
                            std::cout << "[" << resource.compression << "] "
                                << resource.name << ": "
                                << new_size << "/" << raw_size
                                << " (" << ((double)new_size / raw_size*100.0) << "%)" << std::endl;
                        }

                        int count = 0;

                        for (char c : data) {
                            if (count > MAX_IN_ONE_LINE - 1) {
                                count = 0;
                            }

                            if (count == 0) {
                                s << "\n        ";
                            }

                            s << static_cast<short>(c) << ", ";

                            count++;
                        }
                    })
                    .lazy("source_return_literal", [&](std::ostream& s) {
                        if (compression.is_legal(resource.compression)) {
                            ris::render(ris_res.Get("source_return_compressed_literal"), lazy, s);
                        }
                        else {
                            ris::render(ris_res.Get("source_return_plain_literal"), lazy, s);
                        }
                    })
                    ;
                    ris::render(ris_res.Get("source_single_definition"), lazy, s);
                }
            })
            .lazy("source_getters", [&](std::ostream& s) {
                for (auto& resource : user_resources.resources().resources) {
                    lazy
                    .lazy("resource_name", [&resource](std::ostream& s){
                        s << resource.name;
                    })
                    .lazy("resource_member_name", [&](std::ostream& s){
                        s << member_name(resource);
                    })
                    ;
                    ris::render(ris_res.Get("source_single_getter"), lazy, s);
                }
            })
        ;
        ris::render("{{source}}", lazy, s);
    }, user_resources.source());
    source.start();
}

int main(int argc, char ** argv) {
    std::string source_template;

    switch (argc) {
        case 3:
            source_template = argv[2];
            // fall through
        case 2:
            try {
                process(argv[1], source_template);
            }
            catch (std::exception& e) {
                std::cerr << "Error: " << e.what() << std::endl;
                return 1;
            }
            break;
        default:
            print_usage();
    }
}
<commit_msg>added a minimal YAML resource upon usage<commit_after>#include "../ris_lib/ris_resources_from_file.h"
#include "../ris_lib/ris_bundle_compression.h"
#include "../ris_lib/ris_writing_files.h"
#include "../ris_lib/template.h"
#include "../ris_lib/ris_resource_loader.h"
#include "../ris_lib/ris_default_or_from_file.h"
#include "../ris_lib/ris_resource_snapshot.h"
#include "../ris_lib/ris_late_context.h"
#include "../ris_lib/ris_late.h"
#include "../ris_lib/ris_resource_loader.h"

#include <iostream>
#include <string>
#include <stdexcept>
#include <unordered_map>

#include <boost/filesystem.hpp>

void print_usage() {
    std::cout
        << "---      ris v0.3.0            ---" << std::endl
        << "a simple resource compiler for c++" << std::endl
        << "https://github.com/d-led/ris" << std::endl
        << "USAGE:" << std::endl
        << "       ris <path_to>/<resources>.[json/yml/yaml] [<template_overrides>.[json/yml/yaml]]" << std::endl
        << "Available algorithms: " << ris::bundle_compression().available_algorithms() << std::endl
        << "Minimal YAML resource file:"
        <<
R"(
#------------------------
header: "res.h"
source: "res.cpp"

resources:
  -
    compression: "LZ4F"
    name: "some_text"
    source: "some text"
    source_type: "string"
#------------------------
)" << std::endl
        ;
}

template <typename TResource>
std::string member_name(TResource const& res) {
    if (!res.member_name.empty())
        return res.member_name;
    return res.name;
}

void process(std::string const& path, std::string const& source_template) {
    auto full_path = absolute(boost::filesystem::path(path));
    full_path.make_preferred();
    std::cout << "reading " << full_path.generic_string() << std::endl;

    auto user_resources = ris::load_resources_from_file(path);
    auto lookup = user_resources.to_lookup();
    std::cout << "read " << user_resources.resources().resources.size() << " resources" << std::endl;

    auto compression = ris::bundle_compression();
    auto ris_res = ris::default_or_from_file<ris::Resource>(source_template);
    auto template_snapshot = ris::resource_snapshot(ris_res);
    bool any_with_compression = std::any_of(std::begin(user_resources.resources().resources),
        std::end(user_resources.resources().resources),
        [&compression](ris::resource const& res) {
        return compression.is_legal(res.compression);
    });

    ris::write_to_temp_first_then_move header([&ris_res, &template_snapshot, &user_resources,&lookup](std::ostream& s) {
        template_snapshot["namespace_name"] = user_resources.namespace_();
        template_snapshot["class_name"] = user_resources.class_();
        auto lazy = ris::get_context(template_snapshot);
        lazy
            .lazy("header", [&lazy, &ris_res](std::ostream& s) {
                ris::render(ris_res.Get("header"), lazy, s);
            })
            .lazy("header_declarations", [&ris_res,&user_resources,&lazy](std::ostream& s) {
                for (auto& resource : user_resources.resources().resources) {
                    lazy.lazy("resource_member_name", [&resource](std::ostream& s){
                        s << member_name(resource);
                    });
                    ris::render(ris_res.Get("header_single_declaration"), lazy, s);
                }
            })
            .lazy("header_resource_names", [&ris_res, &user_resources, &lazy](std::ostream& s) {
                for (auto& resource : user_resources.resources().resources) {
                    lazy.lazy("resource_name", [&resource](std::ostream& s){
                        s << resource.name;
                    });
                    ris::render(ris_res.Get("header_single_resource_name"), lazy, s);
                }
            })
        ;
        ris::render("{{header}}", lazy, s);
    }, user_resources.header());
    header.start();

    ris::write_to_temp_first_then_move source([&](std::ostream& s) {
        template_snapshot["namespace_name"] = user_resources.namespace_();
        template_snapshot["class_name"] = user_resources.class_();
        auto lazy = ris::get_context(template_snapshot);
        lazy
            .lazy("source", [&lazy, &ris_res](std::ostream& s) {
                ris::render(ris_res.Get("source"), lazy, s);
            })
            .lazy("optional_compression_header", [&](std::ostream& s) {
                if (any_with_compression)
                    s << "#include <bundle.hpp>\n";
            })
            .lazy("source_default_include", [&](std::ostream& s) {
                s << "#include \"" << boost::filesystem::path(user_resources.header()).filename().generic_string() << "\"";
            })
            .lazy("source_definitions", [&](std::ostream& s) {
                for (auto& resource : user_resources.resources().resources) {
                    lazy
                    .lazy("resource_member_name", [&](std::ostream& s){
                        s << member_name(resource);
                    })
                    .lazy("source_literal_bytes", [&](std::ostream& s){
                        static const unsigned MAX_IN_ONE_LINE = 100;
                        std::string data = ris::resource_loader(resource, user_resources.base_path()).get();

                        auto raw_size = data.size();

                        if (compression.is_legal(resource.compression)) {
                            data = compression.pack(resource.compression, data);
                            auto new_size = data.size();
                            std::cout << "[" << resource.compression << "] "
                                << resource.name << ": "
                                << new_size << "/" << raw_size
                                << " (" << ((double)new_size / raw_size*100.0) << "%)" << std::endl;
                        }

                        int count = 0;

                        for (char c : data) {
                            if (count > MAX_IN_ONE_LINE - 1) {
                                count = 0;
                            }

                            if (count == 0) {
                                s << "\n        ";
                            }

                            s << static_cast<short>(c) << ", ";

                            count++;
                        }
                    })
                    .lazy("source_return_literal", [&](std::ostream& s) {
                        if (compression.is_legal(resource.compression)) {
                            ris::render(ris_res.Get("source_return_compressed_literal"), lazy, s);
                        }
                        else {
                            ris::render(ris_res.Get("source_return_plain_literal"), lazy, s);
                        }
                    })
                    ;
                    ris::render(ris_res.Get("source_single_definition"), lazy, s);
                }
            })
            .lazy("source_getters", [&](std::ostream& s) {
                for (auto& resource : user_resources.resources().resources) {
                    lazy
                    .lazy("resource_name", [&resource](std::ostream& s){
                        s << resource.name;
                    })
                    .lazy("resource_member_name", [&](std::ostream& s){
                        s << member_name(resource);
                    })
                    ;
                    ris::render(ris_res.Get("source_single_getter"), lazy, s);
                }
            })
        ;
        ris::render("{{source}}", lazy, s);
    }, user_resources.source());
    source.start();
}

int main(int argc, char ** argv) {
    std::string source_template;

    switch (argc) {
        case 3:
            source_template = argv[2];
            // fall through
        case 2:
            try {
                process(argv[1], source_template);
            }
            catch (std::exception& e) {
                std::cerr << "Error: " << e.what() << std::endl;
                return 1;
            }
            break;
        default:
            print_usage();
    }
}
<|endoftext|>


<commit_before>forall<&{{global_syncname}}>( {{inputsym}}.data, [=]({{tuple_type}}& {{tuple_name}}) {
{{inner_code}}
}<commit_msg>typo in code gen<commit_after>forall<&{{global_syncname}}>( {{inputsym}}.data, [=]({{tuple_type}}& {{tuple_name}}) {
{{inner_code}}
});<|endoftext|>