<commit_before>#include <unistd.h>
#include <iostream>

#include <openssl/ssl.h>
#include <boost/filesystem.hpp>
#include <boost/program_options.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include <boost/uuid/uuid_io.hpp>

#include "config/config.h"
#include "package_manager/ostreemanager.h"
#include "primary/sotauptaneclient.h"
#include "version.h"

#include "utilities/aktualizr_version.h"

namespace bpo = boost::program_options;

static void finalizeIfNeeded(INvStorage &storage, PackageConfig &config) {
  std::vector<Uptane::Target> installed_versions;
  size_t pending_index = SIZE_MAX;
  storage.loadInstalledVersions("", &installed_versions, nullptr, &pending_index);

  if (pending_index < installed_versions.size()) {
    GObjectUniquePtr<OstreeSysroot> sysroot_smart = OstreeManager::LoadSysroot(config.sysroot);
    OstreeDeployment *booted_deployment = ostree_sysroot_get_booted_deployment(sysroot_smart.get());
    if (booted_deployment == nullptr) {
      throw std::runtime_error("Could not get booted deployment in " + config.sysroot.string());
    }
    std::string current_hash = ostree_deployment_get_csum(booted_deployment);

    const Uptane::Target &target = installed_versions[pending_index];
    if (current_hash == target.sha256Hash()) {
      LOG_INFO << "Marking target install complete for: " << target;
      storage.saveInstalledVersion("", target, InstalledVersionUpdateMode::kCurrent);
    }
  }
}

static std::shared_ptr<SotaUptaneClient> liteClient(Config &config, std::shared_ptr<INvStorage> storage) {
  std::string pkey;
  if (storage == nullptr) {
    storage = INvStorage::newStorage(config.storage);
  }
  storage->importData(config.import);

  EcuSerials ecu_serials;
  if (!storage->loadEcuSerials(&ecu_serials)) {
    // Set a "random" serial so we don't get warning messages.
    std::string serial = config.provision.primary_ecu_serial;
    std::string hwid = config.provision.primary_ecu_hardware_id;
    if (hwid.empty()) {
      hwid = Utils::getHostname();
    }
    if (serial.empty()) {
      boost::uuids::uuid tmp = boost::uuids::random_generator()();
      serial = boost::uuids::to_string(tmp);
    }
    ecu_serials.emplace_back(Uptane::EcuSerial(serial), Uptane::HardwareIdentifier(serial));
    storage->storeEcuSerials(ecu_serials);
  }

  auto http_client = std::make_shared<HttpClient>();
  auto bootloader = std::make_shared<Bootloader>(config.bootloader, *storage);
  auto report_queue = std::make_shared<ReportQueue>(config, http_client);

  KeyManager keys(storage, config.keymanagerConfig());
  keys.copyCertsToCurl(*http_client);

  auto client = std::make_shared<SotaUptaneClient>(config, storage, http_client, bootloader, report_queue);
  finalizeIfNeeded(*storage, config.pacman);
  return client;
}

static void log_info_target(const std::string &prefix, const Config &config, const Uptane::Target &t) {
  auto name = t.filename();
  if (t.custom_version().length() > 0) {
    name = t.custom_version();
  }
  LOG_INFO << prefix + name << "\tsha256:" << t.sha256Hash();
  if (config.pacman.type == PackageManager::kOstreeDockerApp) {
    bool shown = false;
    auto apps = t.custom_data()["docker_apps"];
    for (Json::ValueIterator i = apps.begin(); i != apps.end(); ++i) {
      if (!shown) {
        shown = true;
        LOG_INFO << "\tDocker Apps:";
      }
      if ((*i).isObject() && (*i).isMember("filename")) {
        LOG_INFO << "\t\t" << i.key().asString() << " -> " << (*i)["filename"].asString();
      } else {
        LOG_ERROR << "\t\tInvalid custom data for docker-app: " << i.key().asString();
      }
    }
  }
}

static int status_main(Config &config, const bpo::variables_map &unused) {
  (void)unused;
  auto target = liteClient(config, nullptr)->getCurrent();

  if (target.MatchTarget(Uptane::Target::Unknown())) {
    LOG_INFO << "No active deployment found";
  } else {
    auto name = target.filename();
    if (target.custom_version().length() > 0) {
      name = target.custom_version();
    }
    log_info_target("Active image is: ", config, target);
  }
  return 0;
}

static int list_main(Config &config, const bpo::variables_map &unused) {
  (void)unused;
  auto client = liteClient(config, nullptr);
  Uptane::HardwareIdentifier hwid(config.provision.primary_ecu_hardware_id);

  LOG_INFO << "Refreshing target metadata";
  if (!client->updateImagesMeta()) {
    LOG_WARNING << "Unable to update latest metadata, using local copy";
    if (!client->checkImagesMetaOffline()) {
      LOG_ERROR << "Unable to use local copy of TUF data";
      return 1;
    }
  }

  LOG_INFO << "Updates available to " << hwid << ":";
  for (auto &t : client->allTargets()) {
    for (auto const &it : t.hardwareIds()) {
      if (it == hwid) {
        log_info_target("", config, t);
        break;
      }
    }
  }
  return 0;
}

static std::unique_ptr<Uptane::Target> find_target(const std::shared_ptr<SotaUptaneClient> &client,
                                                   Uptane::HardwareIdentifier &hwid, const std::string &version) {
  std::unique_ptr<Uptane::Target> rv;
  if (!client->updateImagesMeta()) {
    LOG_WARNING << "Unable to update latest metadata, using local copy";
    if (!client->checkImagesMetaOffline()) {
      LOG_ERROR << "Unable to use local copy of TUF data";
      throw std::runtime_error("Unable to find update");
    }
  }

  bool find_latest = (version == "latest");
  std::unique_ptr<Uptane::Target> latest = nullptr;
  for (auto &t : client->allTargets()) {
    for (auto const &it : t.hardwareIds()) {
      if (it == hwid) {
        if (find_latest) {
          if (latest == nullptr || Version(latest->custom_version()) < Version(t.custom_version())) {
            latest = std_::make_unique<Uptane::Target>(t);
          }
        } else if (version == t.filename() || version == t.custom_version()) {
          return std_::make_unique<Uptane::Target>(t);
        }
      }
    }
  }
  if (find_latest) {
    return latest;
  }
  throw std::runtime_error("Unable to find update");
}

static int do_update(SotaUptaneClient &client, INvStorage &storage, Uptane::Target &target) {
  std::vector<Uptane::Target> targets{target};
  auto result = client.downloadImages(targets);
  if (result.status != result::DownloadStatus::kSuccess &&
      result.status != result::DownloadStatus::kNothingToDownload) {
    LOG_ERROR << "Unable to download update: " + result.message;
    return 1;
  }

  auto iresult = client.PackageInstall(target);
  if (iresult.result_code.num_code == data::ResultCode::Numeric::kNeedCompletion) {
    LOG_INFO << "Update complete. Please reboot the device to activate";
    storage.saveInstalledVersion("", target, InstalledVersionUpdateMode::kPending);
  } else if (iresult.result_code.num_code == data::ResultCode::Numeric::kOk) {
    storage.saveInstalledVersion("", target, InstalledVersionUpdateMode::kCurrent);
  } else {
    LOG_ERROR << "Unable to install update: " << iresult.description;
    return 1;
  }
  LOG_INFO << iresult.description;
  return 0;
}

static int update_main(Config &config, const bpo::variables_map &variables_map) {
  auto storage = INvStorage::newStorage(config.storage);
  auto client = liteClient(config, storage);
  Uptane::HardwareIdentifier hwid(config.provision.primary_ecu_hardware_id);

  std::string version("latest");
  if (variables_map.count("update-name") > 0) {
    version = variables_map["update-name"].as<std::string>();
  }
  LOG_INFO << "Finding " << version << " to update to...";
  auto target = find_target(client, hwid, version);
  LOG_INFO << "Updating to: " << *target;
  return do_update(*client, *storage, *target);
}

struct SubCommand {
  const char *name;
  int (*main)(Config &, const bpo::variables_map &);
};
static SubCommand commands[] = {
    {"status", status_main},
    {"list", list_main},
    {"update", update_main},
};

void check_info_options(const bpo::options_description &description, const bpo::variables_map &vm) {
  if (vm.count("help") != 0 || vm.count("command") == 0) {
    std::cout << description << '\n';
    exit(EXIT_SUCCESS);
  }
  if (vm.count("version") != 0) {
    std::cout << "Current aktualizr version is: " << aktualizr_version() << "\n";
    exit(EXIT_SUCCESS);
  }
}

bpo::variables_map parse_options(int argc, char *argv[]) {
  std::string subs("Command to execute: ");
  for (size_t i = 0; i < sizeof(commands) / sizeof(SubCommand); i++) {
    if (i != 0) {
      subs += ", ";
    }
    subs += commands[i].name;
  }
  bpo::options_description description("aktualizr-lite command line options");
  // clang-format off
  // Try to keep these options in the same order as Config::updateFromCommandLine().
  // The first three are commandline only.
  description.add_options()
      ("help,h", "print usage")
      ("version,v", "Current aktualizr version")
      ("config,c", bpo::value<std::vector<boost::filesystem::path> >()->composing(), "configuration file or directory")
      ("loglevel", bpo::value<int>(), "set log level 0-5 (trace, debug, info, warning, error, fatal)")
      ("repo-server", bpo::value<std::string>(), "url of the uptane repo repository")
      ("ostree-server", bpo::value<std::string>(), "url of the ostree repository")
      ("primary-ecu-hardware-id", bpo::value<std::string>(), "hardware ID of primary ecu")
      ("update-name", bpo::value<std::string>(), "optional name of the update when running \"update\". default=latest")
      ("command", bpo::value<std::string>(), subs.c_str());
  // clang-format on

  // consider the first positional argument as the aktualizr run mode
  bpo::positional_options_description pos;
  pos.add("command", 1);

  bpo::variables_map vm;
  std::vector<std::string> unregistered_options;
  try {
    bpo::basic_parsed_options<char> parsed_options =
        bpo::command_line_parser(argc, argv).options(description).positional(pos).allow_unregistered().run();
    bpo::store(parsed_options, vm);
    check_info_options(description, vm);
    bpo::notify(vm);
    unregistered_options = bpo::collect_unrecognized(parsed_options.options, bpo::exclude_positional);
    if (vm.count("help") == 0 && !unregistered_options.empty()) {
      std::cout << description << "\n";
      exit(EXIT_FAILURE);
    }
  } catch (const bpo::required_option &ex) {
    // print the error and append the default commandline option description
    std::cout << ex.what() << std::endl << description;
    exit(EXIT_FAILURE);
  } catch (const bpo::error &ex) {
    check_info_options(description, vm);

    // log boost error
    LOG_ERROR << "boost command line option error: " << ex.what();

    // print the error message to the standard output too, as the user provided
    // a non-supported commandline option
    std::cout << ex.what() << '\n';

    // set the returnValue, thereby ctest will recognize
    // that something went wrong
    exit(EXIT_FAILURE);
  }

  return vm;
}

int main(int argc, char *argv[]) {
  logger_init(isatty(1) == 1);
  logger_set_threshold(boost::log::trivial::info);

  bpo::variables_map commandline_map = parse_options(argc, argv);

  int r = EXIT_FAILURE;
  try {
    if (geteuid() != 0) {
      LOG_WARNING << "\033[31mRunning as non-root and may not work as expected!\033[0m\n";
    }

    Config config(commandline_map);
    config.storage.uptane_metadata_path = BasedPath(config.storage.path / "metadata");
    if (config.logger.loglevel <= boost::log::trivial::debug) {
      SSL_load_error_strings();
    }
    LOG_DEBUG << "Current directory: " << boost::filesystem::current_path().string();

    std::string cmd = commandline_map["command"].as<std::string>();
    for (size_t i = 0; i < sizeof(commands) / sizeof(SubCommand); i++) {
      if (cmd == commands[i].name) {
        return commands[i].main(config, commandline_map);
      }
    }
    throw bpo::invalid_option_value(cmd);
    r = EXIT_SUCCESS;
  } catch (const std::exception &ex) {
    LOG_ERROR << ex.what();
  }
  return r;
}
<commit_msg>aktualizr-lite: Fix incorrect storing of ecu hwid<commit_after>#include <unistd.h>
#include <iostream>

#include <openssl/ssl.h>
#include <boost/filesystem.hpp>
#include <boost/program_options.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include <boost/uuid/uuid_io.hpp>

#include "config/config.h"
#include "package_manager/ostreemanager.h"
#include "primary/sotauptaneclient.h"
#include "version.h"

#include "utilities/aktualizr_version.h"

namespace bpo = boost::program_options;

static void finalizeIfNeeded(INvStorage &storage, PackageConfig &config) {
  std::vector<Uptane::Target> installed_versions;
  size_t pending_index = SIZE_MAX;
  storage.loadInstalledVersions("", &installed_versions, nullptr, &pending_index);

  if (pending_index < installed_versions.size()) {
    GObjectUniquePtr<OstreeSysroot> sysroot_smart = OstreeManager::LoadSysroot(config.sysroot);
    OstreeDeployment *booted_deployment = ostree_sysroot_get_booted_deployment(sysroot_smart.get());
    if (booted_deployment == nullptr) {
      throw std::runtime_error("Could not get booted deployment in " + config.sysroot.string());
    }
    std::string current_hash = ostree_deployment_get_csum(booted_deployment);

    const Uptane::Target &target = installed_versions[pending_index];
    if (current_hash == target.sha256Hash()) {
      LOG_INFO << "Marking target install complete for: " << target;
      storage.saveInstalledVersion("", target, InstalledVersionUpdateMode::kCurrent);
    }
  }
}

static std::shared_ptr<SotaUptaneClient> liteClient(Config &config, std::shared_ptr<INvStorage> storage) {
  std::string pkey;
  if (storage == nullptr) {
    storage = INvStorage::newStorage(config.storage);
  }
  storage->importData(config.import);

  EcuSerials ecu_serials;
  if (!storage->loadEcuSerials(&ecu_serials)) {
    // Set a "random" serial so we don't get warning messages.
    std::string serial = config.provision.primary_ecu_serial;
    std::string hwid = config.provision.primary_ecu_hardware_id;
    if (hwid.empty()) {
      hwid = Utils::getHostname();
    }
    if (serial.empty()) {
      boost::uuids::uuid tmp = boost::uuids::random_generator()();
      serial = boost::uuids::to_string(tmp);
    }
    ecu_serials.emplace_back(Uptane::EcuSerial(serial), Uptane::HardwareIdentifier(hwid));
    storage->storeEcuSerials(ecu_serials);
  }

  auto http_client = std::make_shared<HttpClient>();
  auto bootloader = std::make_shared<Bootloader>(config.bootloader, *storage);
  auto report_queue = std::make_shared<ReportQueue>(config, http_client);

  KeyManager keys(storage, config.keymanagerConfig());
  keys.copyCertsToCurl(*http_client);

  auto client = std::make_shared<SotaUptaneClient>(config, storage, http_client, bootloader, report_queue);
  finalizeIfNeeded(*storage, config.pacman);
  return client;
}

static void log_info_target(const std::string &prefix, const Config &config, const Uptane::Target &t) {
  auto name = t.filename();
  if (t.custom_version().length() > 0) {
    name = t.custom_version();
  }
  LOG_INFO << prefix + name << "\tsha256:" << t.sha256Hash();
  if (config.pacman.type == PackageManager::kOstreeDockerApp) {
    bool shown = false;
    auto apps = t.custom_data()["docker_apps"];
    for (Json::ValueIterator i = apps.begin(); i != apps.end(); ++i) {
      if (!shown) {
        shown = true;
        LOG_INFO << "\tDocker Apps:";
      }
      if ((*i).isObject() && (*i).isMember("filename")) {
        LOG_INFO << "\t\t" << i.key().asString() << " -> " << (*i)["filename"].asString();
      } else {
        LOG_ERROR << "\t\tInvalid custom data for docker-app: " << i.key().asString();
      }
    }
  }
}

static int status_main(Config &config, const bpo::variables_map &unused) {
  (void)unused;
  auto target = liteClient(config, nullptr)->getCurrent();

  if (target.MatchTarget(Uptane::Target::Unknown())) {
    LOG_INFO << "No active deployment found";
  } else {
    auto name = target.filename();
    if (target.custom_version().length() > 0) {
      name = target.custom_version();
    }
    log_info_target("Active image is: ", config, target);
  }
  return 0;
}

static int list_main(Config &config, const bpo::variables_map &unused) {
  (void)unused;
  auto client = liteClient(config, nullptr);
  Uptane::HardwareIdentifier hwid(config.provision.primary_ecu_hardware_id);

  LOG_INFO << "Refreshing target metadata";
  if (!client->updateImagesMeta()) {
    LOG_WARNING << "Unable to update latest metadata, using local copy";
    if (!client->checkImagesMetaOffline()) {
      LOG_ERROR << "Unable to use local copy of TUF data";
      return 1;
    }
  }

  LOG_INFO << "Updates available to " << hwid << ":";
  for (auto &t : client->allTargets()) {
    for (auto const &it : t.hardwareIds()) {
      if (it == hwid) {
        log_info_target("", config, t);
        break;
      }
    }
  }
  return 0;
}

static std::unique_ptr<Uptane::Target> find_target(const std::shared_ptr<SotaUptaneClient> &client,
                                                   Uptane::HardwareIdentifier &hwid, const std::string &version) {
  std::unique_ptr<Uptane::Target> rv;
  if (!client->updateImagesMeta()) {
    LOG_WARNING << "Unable to update latest metadata, using local copy";
    if (!client->checkImagesMetaOffline()) {
      LOG_ERROR << "Unable to use local copy of TUF data";
      throw std::runtime_error("Unable to find update");
    }
  }

  bool find_latest = (version == "latest");
  std::unique_ptr<Uptane::Target> latest = nullptr;
  for (auto &t : client->allTargets()) {
    for (auto const &it : t.hardwareIds()) {
      if (it == hwid) {
        if (find_latest) {
          if (latest == nullptr || Version(latest->custom_version()) < Version(t.custom_version())) {
            latest = std_::make_unique<Uptane::Target>(t);
          }
        } else if (version == t.filename() || version == t.custom_version()) {
          return std_::make_unique<Uptane::Target>(t);
        }
      }
    }
  }
  if (find_latest) {
    return latest;
  }
  throw std::runtime_error("Unable to find update");
}

static int do_update(SotaUptaneClient &client, INvStorage &storage, Uptane::Target &target) {
  std::vector<Uptane::Target> targets{target};
  auto result = client.downloadImages(targets);
  if (result.status != result::DownloadStatus::kSuccess &&
      result.status != result::DownloadStatus::kNothingToDownload) {
    LOG_ERROR << "Unable to download update: " + result.message;
    return 1;
  }

  auto iresult = client.PackageInstall(target);
  if (iresult.result_code.num_code == data::ResultCode::Numeric::kNeedCompletion) {
    LOG_INFO << "Update complete. Please reboot the device to activate";
    storage.saveInstalledVersion("", target, InstalledVersionUpdateMode::kPending);
  } else if (iresult.result_code.num_code == data::ResultCode::Numeric::kOk) {
    storage.saveInstalledVersion("", target, InstalledVersionUpdateMode::kCurrent);
  } else {
    LOG_ERROR << "Unable to install update: " << iresult.description;
    return 1;
  }
  LOG_INFO << iresult.description;
  return 0;
}

static int update_main(Config &config, const bpo::variables_map &variables_map) {
  auto storage = INvStorage::newStorage(config.storage);
  auto client = liteClient(config, storage);
  Uptane::HardwareIdentifier hwid(config.provision.primary_ecu_hardware_id);

  std::string version("latest");
  if (variables_map.count("update-name") > 0) {
    version = variables_map["update-name"].as<std::string>();
  }
  LOG_INFO << "Finding " << version << " to update to...";
  auto target = find_target(client, hwid, version);
  LOG_INFO << "Updating to: " << *target;
  return do_update(*client, *storage, *target);
}

struct SubCommand {
  const char *name;
  int (*main)(Config &, const bpo::variables_map &);
};
static SubCommand commands[] = {
    {"status", status_main},
    {"list", list_main},
    {"update", update_main},
};

void check_info_options(const bpo::options_description &description, const bpo::variables_map &vm) {
  if (vm.count("help") != 0 || vm.count("command") == 0) {
    std::cout << description << '\n';
    exit(EXIT_SUCCESS);
  }
  if (vm.count("version") != 0) {
    std::cout << "Current aktualizr version is: " << aktualizr_version() << "\n";
    exit(EXIT_SUCCESS);
  }
}

bpo::variables_map parse_options(int argc, char *argv[]) {
  std::string subs("Command to execute: ");
  for (size_t i = 0; i < sizeof(commands) / sizeof(SubCommand); i++) {
    if (i != 0) {
      subs += ", ";
    }
    subs += commands[i].name;
  }
  bpo::options_description description("aktualizr-lite command line options");
  // clang-format off
  // Try to keep these options in the same order as Config::updateFromCommandLine().
  // The first three are commandline only.
  description.add_options()
      ("help,h", "print usage")
      ("version,v", "Current aktualizr version")
      ("config,c", bpo::value<std::vector<boost::filesystem::path> >()->composing(), "configuration file or directory")
      ("loglevel", bpo::value<int>(), "set log level 0-5 (trace, debug, info, warning, error, fatal)")
      ("repo-server", bpo::value<std::string>(), "url of the uptane repo repository")
      ("ostree-server", bpo::value<std::string>(), "url of the ostree repository")
      ("primary-ecu-hardware-id", bpo::value<std::string>(), "hardware ID of primary ecu")
      ("update-name", bpo::value<std::string>(), "optional name of the update when running \"update\". default=latest")
      ("command", bpo::value<std::string>(), subs.c_str());
  // clang-format on

  // consider the first positional argument as the aktualizr run mode
  bpo::positional_options_description pos;
  pos.add("command", 1);

  bpo::variables_map vm;
  std::vector<std::string> unregistered_options;
  try {
    bpo::basic_parsed_options<char> parsed_options =
        bpo::command_line_parser(argc, argv).options(description).positional(pos).allow_unregistered().run();
    bpo::store(parsed_options, vm);
    check_info_options(description, vm);
    bpo::notify(vm);
    unregistered_options = bpo::collect_unrecognized(parsed_options.options, bpo::exclude_positional);
    if (vm.count("help") == 0 && !unregistered_options.empty()) {
      std::cout << description << "\n";
      exit(EXIT_FAILURE);
    }
  } catch (const bpo::required_option &ex) {
    // print the error and append the default commandline option description
    std::cout << ex.what() << std::endl << description;
    exit(EXIT_FAILURE);
  } catch (const bpo::error &ex) {
    check_info_options(description, vm);

    // log boost error
    LOG_ERROR << "boost command line option error: " << ex.what();

    // print the error message to the standard output too, as the user provided
    // a non-supported commandline option
    std::cout << ex.what() << '\n';

    // set the returnValue, thereby ctest will recognize
    // that something went wrong
    exit(EXIT_FAILURE);
  }

  return vm;
}

int main(int argc, char *argv[]) {
  logger_init(isatty(1) == 1);
  logger_set_threshold(boost::log::trivial::info);

  bpo::variables_map commandline_map = parse_options(argc, argv);

  int r = EXIT_FAILURE;
  try {
    if (geteuid() != 0) {
      LOG_WARNING << "\033[31mRunning as non-root and may not work as expected!\033[0m\n";
    }

    Config config(commandline_map);
    config.storage.uptane_metadata_path = BasedPath(config.storage.path / "metadata");
    if (config.logger.loglevel <= boost::log::trivial::debug) {
      SSL_load_error_strings();
    }
    LOG_DEBUG << "Current directory: " << boost::filesystem::current_path().string();

    std::string cmd = commandline_map["command"].as<std::string>();
    for (size_t i = 0; i < sizeof(commands) / sizeof(SubCommand); i++) {
      if (cmd == commands[i].name) {
        return commands[i].main(config, commandline_map);
      }
    }
    throw bpo::invalid_option_value(cmd);
    r = EXIT_SUCCESS;
  } catch (const std::exception &ex) {
    LOG_ERROR << ex.what();
  }
  return r;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: formlayerexport.cxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: sab $ $Date: 2001-03-16 14:36:39 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include <stdio.h>

#ifndef _XMLOFF_FORMLAYEREXPORT_HXX_
#include "formlayerexport.hxx"
#endif
#ifndef _XMLOFF_FORMS_STRINGS_HXX_
#include "strings.hxx"
#endif
#ifndef _XMLOFF_ELEMENTEXPORT_HXX_
#include "elementexport.hxx"
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include "xmlnmspe.hxx"
#endif
#ifndef _XMLOFF_XMLEXP_HXX
#include "xmlexp.hxx"
#endif
#ifndef _XMLOFF_FORMS_LAYEREXPORT_HXX_
#include "layerexport.hxx"
#endif
#ifndef _XMLOFF_FORMS_PROPERTYEXPORT_HXX_
#include "propertyexport.hxx"
#endif
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
#ifndef _COMPHELPER_EXTRACT_HXX_
#include <comphelper/extract.hxx>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COMPHELPER_STLTYPES_HXX_
#include <comphelper/stl_types.hxx>
#endif

//.........................................................................
namespace xmloff
{
//.........................................................................

    using namespace ::com::sun::star::uno;
    using namespace ::com::sun::star::lang;
    using namespace ::com::sun::star::beans;
    using namespace ::com::sun::star::container;
    using namespace ::com::sun::star::drawing;

    //=====================================================================
    //= OFormLayerXMLExport
    //=====================================================================

    //---------------------------------------------------------------------
    OFormLayerXMLExport::OFormLayerXMLExport(SvXMLExport& _rContext)
        :m_rContext(_rContext)
        ,m_pImpl(new OFormLayerXMLExport_Impl(_rContext))
    {
    }

    //---------------------------------------------------------------------
    OFormLayerXMLExport::~OFormLayerXMLExport()
    {
        delete m_pImpl;
        m_pImpl = NULL;
    }

    //---------------------------------------------------------------------
    sal_Bool OFormLayerXMLExport::seekPage(const Reference< XDrawPage >& _rxDrawPage)
    {
        return m_pImpl->seekPage(_rxDrawPage);
    }

    //---------------------------------------------------------------------
    ::rtl::OUString OFormLayerXMLExport::getControlId(const Reference< XPropertySet >& _rxControl)
    {
        return m_pImpl->getControlId(_rxControl);
    }

    //---------------------------------------------------------------------
    void OFormLayerXMLExport::exportAutoStyles()
    {
        OSL_ENSURE(sal_False, "OFormLayerXMLExport::exportAutoStyles: obsolete method called!");
    }

    //---------------------------------------------------------------------
    ::vos::ORef< SvXMLExportPropertyMapper > OFormLayerXMLExport::getStylePropertyMapper()
    {
        return m_pImpl->getStylePropertyMapper();
    }

    //---------------------------------------------------------------------
    void OFormLayerXMLExport::initialize()
    {
        m_pImpl->clear();
    }

    //---------------------------------------------------------------------
    void OFormLayerXMLExport::examineForms(const Reference< XDrawPage >& _rxDrawPage)
    {
        try
        {
            m_pImpl->examineForms(_rxDrawPage);
        }
        catch(Exception&)
        {
            OSL_ENSURE(sal_False, "OFormLayerXMLExport::examine: could not examine the draw page!");
        }
    }

    //---------------------------------------------------------------------
    void OFormLayerXMLExport::exportForms(const Reference< XDrawPage >& _rxDrawPage)
    {
        m_pImpl->exportForms(_rxDrawPage);
    }

//.........................................................................
}   // namespace xmloff
//.........................................................................

/*************************************************************************
 * history:
 *  $Log: not supported by cvs2svn $
 *  Revision 1.7  2001/02/01 09:46:47  fs
 *  no own style handling anymore - the shape exporter is responsible for our styles now
 *
 *  Revision 1.6  2000/12/18 16:22:35  fs
 *  forgot an & on the getControlId parameter
 *
 *  Revision 1.5  2000/12/18 15:14:35  fs
 *  some changes ... now exporting/importing styles
 *
 *  Revision 1.4  2000/12/06 17:28:05  fs
 *  changes for the formlayer import - still under construction
 *
 *  Revision 1.3  2000/12/03 10:57:06  fs
 *  some changes to support more than one page to be examined/exported
 *
 *  Revision 1.2  2000/11/29 10:32:13  mh
 *  add: header for Solaris8
 *
 *  Revision 1.1  2000/11/17 19:02:16  fs
 *  initial checkin - export and/or import the applications form layer
 *
 *
 *  Revision 1.0 13.11.00 14:58:17  fs
 ************************************************************************/

<commit_msg>removed exportAutoStyles (was obsolete)<commit_after>/*************************************************************************
 *
 *  $RCSfile: formlayerexport.cxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: fs $ $Date: 2001-03-20 08:04:08 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include <stdio.h>

#ifndef _XMLOFF_FORMLAYEREXPORT_HXX_
#include "formlayerexport.hxx"
#endif
#ifndef _XMLOFF_FORMS_STRINGS_HXX_
#include "strings.hxx"
#endif
#ifndef _XMLOFF_ELEMENTEXPORT_HXX_
#include "elementexport.hxx"
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include "xmlnmspe.hxx"
#endif
#ifndef _XMLOFF_XMLEXP_HXX
#include "xmlexp.hxx"
#endif
#ifndef _XMLOFF_FORMS_LAYEREXPORT_HXX_
#include "layerexport.hxx"
#endif
#ifndef _XMLOFF_FORMS_PROPERTYEXPORT_HXX_
#include "propertyexport.hxx"
#endif
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
#ifndef _COMPHELPER_EXTRACT_HXX_
#include <comphelper/extract.hxx>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COMPHELPER_STLTYPES_HXX_
#include <comphelper/stl_types.hxx>
#endif

//.........................................................................
namespace xmloff
{
//.........................................................................

    using namespace ::com::sun::star::uno;
    using namespace ::com::sun::star::lang;
    using namespace ::com::sun::star::beans;
    using namespace ::com::sun::star::container;
    using namespace ::com::sun::star::drawing;

    //=====================================================================
    //= OFormLayerXMLExport
    //=====================================================================

    //---------------------------------------------------------------------
    OFormLayerXMLExport::OFormLayerXMLExport(SvXMLExport& _rContext)
        :m_rContext(_rContext)
        ,m_pImpl(new OFormLayerXMLExport_Impl(_rContext))
    {
    }

    //---------------------------------------------------------------------
    OFormLayerXMLExport::~OFormLayerXMLExport()
    {
        delete m_pImpl;
        m_pImpl = NULL;
    }

    //---------------------------------------------------------------------
    sal_Bool OFormLayerXMLExport::seekPage(const Reference< XDrawPage >& _rxDrawPage)
    {
        return m_pImpl->seekPage(_rxDrawPage);
    }

    //---------------------------------------------------------------------
    ::rtl::OUString OFormLayerXMLExport::getControlId(const Reference< XPropertySet >& _rxControl)
    {
        return m_pImpl->getControlId(_rxControl);
    }

    //---------------------------------------------------------------------
    ::vos::ORef< SvXMLExportPropertyMapper > OFormLayerXMLExport::getStylePropertyMapper()
    {
        return m_pImpl->getStylePropertyMapper();
    }

    //---------------------------------------------------------------------
    void OFormLayerXMLExport::initialize()
    {
        m_pImpl->clear();
    }

    //---------------------------------------------------------------------
    void OFormLayerXMLExport::examineForms(const Reference< XDrawPage >& _rxDrawPage)
    {
        try
        {
            m_pImpl->examineForms(_rxDrawPage);
        }
        catch(Exception&)
        {
            OSL_ENSURE(sal_False, "OFormLayerXMLExport::examine: could not examine the draw page!");
        }
    }

    //---------------------------------------------------------------------
    void OFormLayerXMLExport::exportForms(const Reference< XDrawPage >& _rxDrawPage)
    {
        m_pImpl->exportForms(_rxDrawPage);
    }

//.........................................................................
}   // namespace xmloff
//.........................................................................

/*************************************************************************
 * history:
 *  $Log: not supported by cvs2svn $
 *  Revision 1.8  2001/03/16 14:36:39  sab
 *  did the required change (move of extract.hxx form cppuhelper to comphelper)
 *
 *  Revision 1.7  2001/02/01 09:46:47  fs
 *  no own style handling anymore - the shape exporter is responsible for our styles now
 *
 *  Revision 1.6  2000/12/18 16:22:35  fs
 *  forgot an & on the getControlId parameter
 *
 *  Revision 1.5  2000/12/18 15:14:35  fs
 *  some changes ... now exporting/importing styles
 *
 *  Revision 1.4  2000/12/06 17:28:05  fs
 *  changes for the formlayer import - still under construction
 *
 *  Revision 1.3  2000/12/03 10:57:06  fs
 *  some changes to support more than one page to be examined/exported
 *
 *  Revision 1.2  2000/11/29 10:32:13  mh
 *  add: header for Solaris8
 *
 *  Revision 1.1  2000/11/17 19:02:16  fs
 *  initial checkin - export and/or import the applications form layer
 *
 *
 *  Revision 1.0 13.11.00 14:58:17  fs
 ************************************************************************/

<|endoftext|>


<commit_before>#include "AppClass.h"
#include "GameObject.h"
void App::InitWindow(String a_sWindowName)
{
	super::InitWindow("Sandbox"); // Window Name

	// Set the clear color based on Microsoft's CornflowerBlue (default in XNA)
	//if this line is in Init Application it will depend on the .cfg file, if it
	//is on the InitVariables it will always force it regardless of the .cfg
	m_v4ClearColor = vector4(0.4f, 0.6f, 0.9f, 0.0f);
}

void App::InitVariables(void)
{
	GameObject::init();

	//Reset the selection to -1, -1
	m_selection = std::pair<int, int>(-1, -1);
	//Set the camera position
	m_pCameraMngr->SetPositionTargetAndView(
		vector3(0.0f, -7.f, 13.0f),//Camera position
		vector3(0.0f, -0.75f, 0.0f),//What Im looking at
		REAXISY);//What is up

	Table = new PinballTable();

	new GameObject();
	GameObject::setDebugMode(true);
}

void App::Update(void)
{
	//Update the system's time
	m_pSystem->UpdateTime();

	//Update the mesh manager's time without updating for collision detection
	m_pMeshMngr->Update();

	//First person camera movement
	if (m_bFPC == true)
		CameraRotation();

	//Call the arcball method
	ArcBall();

	//Set the model matrix for the first model to be the arcball
	m_pMeshMngr->SetModelMatrix(ToMatrix4(m_qArcBall), 0);

	GameObject::updateAll(m_pSystem->LapClock());

	//Adds all loaded instance to the render list
	m_pMeshMngr->AddInstanceToRenderList("ALL");

	//Indicate the FPS
	int nFPS = m_pSystem->GetFPS();
	//print info into the console
	//printf("FPS: %d            \r", nFPS);//print the Frames per Second
	//Print info on the screen
	m_pMeshMngr->PrintLine(m_pSystem->GetAppName(), REYELLOW);

	m_pMeshMngr->Print("Selection: ");
	m_pMeshMngr->PrintLine(m_pMeshMngr->GetInstanceGroupName(m_selection.first, m_selection.second), REYELLOW);

	m_pMeshMngr->Print("FPS:");
	m_pMeshMngr->Print(std::to_string(nFPS), RERED);
}

void App::Display(void)
{
	//clear the screen
	ClearScreen();

	//Render the grid based on the camera's mode:
	switch (m_pCameraMngr->GetCameraMode())
	{
	default: //Perspective
		m_pMeshMngr->AddGridToQueue(1.0f, REAXIS::XY); //renders the XY grid with a 100% scale
		break;
	case CAMERAMODE::CAMROTHOX:
		m_pMeshMngr->AddGridToQueue(1.0f, REAXIS::YZ, RERED * 0.75f); //renders the YZ grid with a 100% scale
		break;
	case CAMERAMODE::CAMROTHOY:
		m_pMeshMngr->AddGridToQueue(1.0f, REAXIS::XZ, REGREEN * 0.75f); //renders the XZ grid with a 100% scale
		break;
	case CAMERAMODE::CAMROTHOZ:
		m_pMeshMngr->AddGridToQueue(1.0f, REAXIS::XY, REBLUE * 0.75f); //renders the XY grid with a 100% scale
		break;
	}

	Table->Render(m_pCameraMngr->GetProjectionMatrix(), m_pCameraMngr->GetViewMatrix());
	matrix4 projection = m_pCameraMngr->GetProjectionMatrix();
	matrix4 view = m_pCameraMngr->GetViewMatrix();

	GameObject::renderAll(projection, view);
	//Table->Render(projection, view);

	m_pMeshMngr->Render(); //renders the render list

	m_pGLSystem->GLSwapBuffers(); //Swaps the OpenGL buffers
}

void App::Release(void)
{
	super::Release(); //release the memory of the inherited fields

	delete Table;
}<commit_msg>fix window name<commit_after>#include "AppClass.h"
#include "GameObject.h"
void App::InitWindow(String a_sWindowName)
{
	super::InitWindow("xXxXtreme-PinballxXx"); // Window Name

	// Set the clear color based on Microsoft's CornflowerBlue (default in XNA)
	//if this line is in Init Application it will depend on the .cfg file, if it
	//is on the InitVariables it will always force it regardless of the .cfg
	m_v4ClearColor = vector4(0.4f, 0.6f, 0.9f, 0.0f);
}

void App::InitVariables(void)
{
	GameObject::init();

	//Reset the selection to -1, -1
	m_selection = std::pair<int, int>(-1, -1);
	//Set the camera position
	m_pCameraMngr->SetPositionTargetAndView(
		vector3(0.0f, -7.f, 13.0f),//Camera position
		vector3(0.0f, -0.75f, 0.0f),//What Im looking at
		REAXISY);//What is up

	Table = new PinballTable();

	new GameObject();
	GameObject::setDebugMode(true);
}

void App::Update(void)
{
	//Update the system's time
	m_pSystem->UpdateTime();

	//Update the mesh manager's time without updating for collision detection
	m_pMeshMngr->Update();

	//First person camera movement
	if (m_bFPC == true)
		CameraRotation();

	//Call the arcball method
	ArcBall();

	//Set the model matrix for the first model to be the arcball
	m_pMeshMngr->SetModelMatrix(ToMatrix4(m_qArcBall), 0);

	GameObject::updateAll(m_pSystem->LapClock());

	//Adds all loaded instance to the render list
	m_pMeshMngr->AddInstanceToRenderList("ALL");

	//Indicate the FPS
	int nFPS = m_pSystem->GetFPS();
	//print info into the console
	//printf("FPS: %d            \r", nFPS);//print the Frames per Second
	//Print info on the screen
	m_pMeshMngr->PrintLine(m_pSystem->GetAppName(), REYELLOW);

	m_pMeshMngr->Print("Selection: ");
	m_pMeshMngr->PrintLine(m_pMeshMngr->GetInstanceGroupName(m_selection.first, m_selection.second), REYELLOW);

	m_pMeshMngr->Print("FPS:");
	m_pMeshMngr->Print(std::to_string(nFPS), RERED);
}

void App::Display(void)
{
	//clear the screen
	ClearScreen();

	//Render the grid based on the camera's mode:
	switch (m_pCameraMngr->GetCameraMode())
	{
	default: //Perspective
		m_pMeshMngr->AddGridToQueue(1.0f, REAXIS::XY); //renders the XY grid with a 100% scale
		break;
	case CAMERAMODE::CAMROTHOX:
		m_pMeshMngr->AddGridToQueue(1.0f, REAXIS::YZ, RERED * 0.75f); //renders the YZ grid with a 100% scale
		break;
	case CAMERAMODE::CAMROTHOY:
		m_pMeshMngr->AddGridToQueue(1.0f, REAXIS::XZ, REGREEN * 0.75f); //renders the XZ grid with a 100% scale
		break;
	case CAMERAMODE::CAMROTHOZ:
		m_pMeshMngr->AddGridToQueue(1.0f, REAXIS::XY, REBLUE * 0.75f); //renders the XY grid with a 100% scale
		break;
	}

	Table->Render(m_pCameraMngr->GetProjectionMatrix(), m_pCameraMngr->GetViewMatrix());
	matrix4 projection = m_pCameraMngr->GetProjectionMatrix();
	matrix4 view = m_pCameraMngr->GetViewMatrix();

	GameObject::renderAll(projection, view);
	//Table->Render(projection, view);

	m_pMeshMngr->Render(); //renders the render list

	m_pGLSystem->GLSwapBuffers(); //Swaps the OpenGL buffers
}

void App::Release(void)
{
	super::Release(); //release the memory of the inherited fields

	delete Table;
}<|endoftext|>


<commit_before>/** @file gsFunctionSet.hpp

    @brief implementation of default functions of the gsFunctionSet

    This file is part of the G+Smo library.

    This Source Code Form is subject to the terms of the Mozilla Public
    License, v. 2.0. If a copy of the MPL was not distributed with this
    file, You can obtain one at http://mozilla.org/MPL/2.0/.

    Author(s): A. Bressan
**/

#include <gsCore/gsFuncData.h>
#include <gsCore/gsFunction.h>
#include <gsCore/gsBasis.h>

namespace gismo
{

template <class T>
gsFunctionSet<T>::gsFunctionSet() {}

template <class T>
gsFunctionSet<T>::gsFunctionSet(const gsFunctionSet &) {}

template <class T>
gsFunctionSet<T>::~gsFunctionSet () {}

template <class T>
const gsFunction<T>& gsFunctionSet<T>::function(const index_t k) const
{
    GISMO_ASSERT(dynamic_cast<const gsFunction<T>*>(&piece(k)),
                 "No function found, instead: "<< piece(k));
    return static_cast<const gsFunction<T>&>(piece(k));
}

template <class T>
const gsBasis<T>& gsFunctionSet<T>::basis(const index_t k) const
{
    GISMO_ASSERT(dynamic_cast<const gsBasis<T>*>(&piece(k)),
                 "No basis found, instead: "<< piece(k));
    return static_cast<const gsBasis<T>&>(piece(k));
}

// support (domain of definition)
template <class T>
gsMatrix<T> gsFunctionSet<T>::support() const
{
    return gsMatrix<T>();
}

// actives

template <typename T>
void gsFunctionSet<T>::active_into (const gsMatrix<T> &, gsMatrix<unsigned> &) const
{
    GISMO_NO_IMPLEMENTATION
    // Single function 0 globally active:
    // result.setConstant(1,u.cols(),0);
}

// evaluation

template <typename T>
void gsFunctionSet<T>::eval_into (const gsMatrix<T> &, gsMatrix<T> &) const
{GISMO_NO_IMPLEMENTATION}

template <typename T>
void gsFunctionSet<T>::deriv_into (const gsMatrix<T> &, gsMatrix<T> &) const
{GISMO_NO_IMPLEMENTATION}

template <typename T>
void gsFunctionSet<T>::deriv2_into (const gsMatrix<T> &, gsMatrix<T> &) const
{GISMO_NO_IMPLEMENTATION}

template <typename T>
void gsFunctionSet<T>::evalAllDers_into(const gsMatrix<T> & u, const int n,
                                        std::vector<gsMatrix<T> > & result) const
{
    result.resize(n+1);

    switch(n)
    {
    case 0:
        eval_into(u, result[0]);
        break;
    case 1:
        eval_into (u, result[0]);
        deriv_into(u, result[1]);
        break;
    case 2:
        eval_into  (u, result[0]);
        deriv_into (u, result[1]);
        deriv2_into(u, result[2]);
        break;
    default:
        GISMO_ERROR("evalAllDers implemented for order up to 2<"<<n ); //<< " for "<<*this);
        break;
    }
}

template <class T>
gsMatrix<T>
gsFunctionSet<T>::eval(const gsMatrix<T>& u) const
{
    gsMatrix<T> result;
    this->eval_into( u, result );
    return result;
}

template <class T>
gsMatrix<T>
gsFunctionSet<T>::deriv(const gsMatrix<T>& u) const
{
    gsMatrix<T> result;
    this->deriv_into( u, result );
    return result;
}

template <class T>
gsMatrix<T>
gsFunctionSet<T>::deriv2(const gsMatrix<T>& u) const
{
    gsMatrix<T> result;
    this->deriv2_into( u, result );
    return result;
}

/*
template <typename T>
void gsFunctionSet<T>::div_into       (const gsMatrix<T> & u, gsMatrix<T> &result) const
{
    gsMatrix<T> tmp;
    deriv_into(u,tmp);
    convertValue<T>::derivToDiv(tmp, result, info());
}

template <typename T>
void gsFunctionSet<T>::curl_into      (const gsMatrix<T> & u, gsMatrix<T> &result) const
{
    gsMatrix<T> tmp;
    deriv_into(u,tmp);
    convertValue<T>::derivToCurl(tmp, result, info());
}

template <typename T>
void gsFunctionSet<T>::laplacian_into (const gsMatrix<T> & u, gsMatrix<T> &result) const
{
    gsMatrix<T> tmp;
    deriv2_into(u,tmp);
    convertValue<T>::deriv2ToLaplacian(tmp, result, info());
}
*/

// Returns quantities either on the target domain or on the parametric
// domain depending on the representation of the object
template <typename T>
void gsFunctionSet<T>::compute(const gsMatrix<T> & in,
                               gsFuncData<T> & out   ) const
{
    const unsigned flags = out.flags;

    out.dim = this->dimensions();
    //gsDebugVar(&out);

    const int md = out.maxDeriv();
    if (md != -1)
        evalAllDers_into(in, md, out.values);

    if (flags & NEED_ACTIVE && flags & SAME_ELEMENT)
    {
        GISMO_ASSERT(0!=in.cols(), "The points are empty.");
        active_into(in.col(0), out.actives);
    }
    else if (flags & NEED_ACTIVE)
        active_into(in, out.actives);

    // if ( flags & NEED_DIV )
    //     convertValue<T>::derivToDiv(out.values[1], out.divs, info());
    // if ( flags & NEED_CURL )
    //     convertValue<T>::derivToCurl(out.values[1], out.curls, info());
    if (flags & NEED_LAPLACIAN)
    {
        const index_t dsz    = out.derivSize();
        const index_t numact = out.values[2].rows() / dsz;
        out.laplacians.resize(numact, in.cols());
        for (index_t i=0; i!= numact; ++i)
            out.laplacians.row(i) =
                out.values[2].middleRows(dsz*i,out.dim.first).colwise().sum();
    }
}

} // namespace gismo
<commit_msg>bug fix<commit_after>/** @file gsFunctionSet.hpp

    @brief implementation of default functions of the gsFunctionSet

    This file is part of the G+Smo library.

    This Source Code Form is subject to the terms of the Mozilla Public
    License, v. 2.0. If a copy of the MPL was not distributed with this
    file, You can obtain one at http://mozilla.org/MPL/2.0/.

    Author(s): A. Bressan
**/

#include <gsCore/gsFuncData.h>
#include <gsCore/gsFunction.h>
#include <gsCore/gsBasis.h>

namespace gismo
{

template <class T>
gsFunctionSet<T>::gsFunctionSet() {}

template <class T>
gsFunctionSet<T>::gsFunctionSet(const gsFunctionSet &) {}

template <class T>
gsFunctionSet<T>::~gsFunctionSet () {}

template <class T>
const gsFunction<T>& gsFunctionSet<T>::function(const index_t k) const
{
    GISMO_ASSERT(dynamic_cast<const gsFunction<T>*>(&piece(k)),
                 "No function found, instead: "<< piece(k));
    return static_cast<const gsFunction<T>&>(piece(k));
}

template <class T>
const gsBasis<T>& gsFunctionSet<T>::basis(const index_t k) const
{
    GISMO_ASSERT(dynamic_cast<const gsBasis<T>*>(&piece(k)),
                 "No basis found, instead: "<< piece(k));
    return static_cast<const gsBasis<T>&>(piece(k));
}

// support (domain of definition)
template <class T>
gsMatrix<T> gsFunctionSet<T>::support() const
{
    return gsMatrix<T>();
}

// actives

template <typename T>
void gsFunctionSet<T>::active_into (const gsMatrix<T> &, gsMatrix<unsigned> &) const
{
    GISMO_NO_IMPLEMENTATION
    // Single function 0 globally active:
    // result.setConstant(1,u.cols(),0);
}

// evaluation

template <typename T>
void gsFunctionSet<T>::eval_into (const gsMatrix<T> &, gsMatrix<T> &) const
{GISMO_NO_IMPLEMENTATION}

template <typename T>
void gsFunctionSet<T>::deriv_into (const gsMatrix<T> &, gsMatrix<T> &) const
{GISMO_NO_IMPLEMENTATION}

template <typename T>
void gsFunctionSet<T>::deriv2_into (const gsMatrix<T> &, gsMatrix<T> &) const
{GISMO_NO_IMPLEMENTATION}

template <typename T>
void gsFunctionSet<T>::evalAllDers_into(const gsMatrix<T> & u, const int n,
                                        std::vector<gsMatrix<T> > & result) const
{
    result.resize(n+1);

    switch(n)
    {
    case 0:
        eval_into(u, result[0]);
        break;
    case 1:
        eval_into (u, result[0]);
        deriv_into(u, result[1]);
        break;
    case 2:
        eval_into  (u, result[0]);
        deriv_into (u, result[1]);
        deriv2_into(u, result[2]);
        break;
    default:
        GISMO_ERROR("evalAllDers implemented for order up to 2<"<<n ); //<< " for "<<*this);
        break;
    }
}

template <class T>
gsMatrix<T>
gsFunctionSet<T>::eval(const gsMatrix<T>& u) const
{
    gsMatrix<T> result;
    this->eval_into( u, result );
    return result;
}

template <class T>
gsMatrix<T>
gsFunctionSet<T>::deriv(const gsMatrix<T>& u) const
{
    gsMatrix<T> result;
    this->deriv_into( u, result );
    return result;
}

template <class T>
gsMatrix<T>
gsFunctionSet<T>::deriv2(const gsMatrix<T>& u) const
{
    gsMatrix<T> result;
    this->deriv2_into( u, result );
    return result;
}

/*
template <typename T>
void gsFunctionSet<T>::div_into       (const gsMatrix<T> & u, gsMatrix<T> &result) const
{
    gsMatrix<T> tmp;
    deriv_into(u,tmp);
    convertValue<T>::derivToDiv(tmp, result, info());
}

template <typename T>
void gsFunctionSet<T>::curl_into      (const gsMatrix<T> & u, gsMatrix<T> &result) const
{
    gsMatrix<T> tmp;
    deriv_into(u,tmp);
    convertValue<T>::derivToCurl(tmp, result, info());
}

template <typename T>
void gsFunctionSet<T>::laplacian_into (const gsMatrix<T> & u, gsMatrix<T> &result) const
{
    gsMatrix<T> tmp;
    deriv2_into(u,tmp);
    convertValue<T>::deriv2ToLaplacian(tmp, result, info());
}
*/

// Returns quantities either on the target domain or on the parametric
// domain depending on the representation of the object
template <typename T>
void gsFunctionSet<T>::compute(const gsMatrix<T> & in,
                               gsFuncData<T> & out   ) const
{
    const unsigned flags = out.flags;

    out.dim = this->dimensions();
    //gsDebugVar(&out);

    const int md = out.maxDeriv();
    if (md != -1)
        evalAllDers_into(in, md, out.values);

    if (flags & NEED_ACTIVE && flags & SAME_ELEMENT)
    {
        GISMO_ASSERT(0!=in.cols(), "The points are empty.");
        active_into(in.col(0), out.actives);
    }
    else if (flags & NEED_ACTIVE)
        active_into(in, out.actives);

    // if ( flags & NEED_DIV )
    //     convertValue<T>::derivToDiv(out.values[1], out.divs, info());
    // if ( flags & NEED_CURL )
    //     convertValue<T>::derivToCurl(out.values[1], out.curls, info());
    if (flags & NEED_LAPLACIAN)
    {
        const index_t dsz    = out.deriv2Size();
        const index_t numact = out.values[2].rows() / dsz;
        out.laplacians.resize(numact, in.cols());
        for (index_t i=0; i!= numact; ++i)
            out.laplacians.row(i) =
                out.values[2].middleRows(dsz*i,out.dim.first).colwise().sum();
    }
}

} // namespace gismo
<|endoftext|>


<commit_before>/*
 * #%L
 * %%
 * Copyright (C) 2011 - 2017 BMW Car IT GmbH
 * %%
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * #L%
 */

#include <memory>

#include <gtest/gtest.h>
#include <gmock/gmock.h>

#include "joynr/JoynrClusterControllerRuntime.h"
#include "joynr/exceptions/JoynrException.h"
#include "joynr/tests/testProxy.h"
#include "joynr/Settings.h"

#include "tests/mock/MockSubscriptionListener.h"
#include "tests/mock/MockTestProvider.h"

#include "tests/JoynrTest.h"
#include "tests/utils/PtrUtils.h"

using namespace ::testing;
using namespace joynr;

class AsyncProxyBuilderTest : public ::testing::Test
{
public:
    void SetUp() override
    {
        discoveryQos.setArbitrationStrategy(DiscoveryQos::ArbitrationStrategy::HIGHEST_PRIORITY);
        discoveryQos.setDiscoveryTimeoutMs(100);
        auto integrationSettings =
                std::make_unique<Settings>("test-resources/libjoynrSystemIntegration1.settings");
        Settings settings("test-resources/MqttSystemIntegrationTest1.settings");
        Settings::merge(settings, *integrationSettings, false);
        runtime = std::make_shared<JoynrClusterControllerRuntime>(
                std::move(integrationSettings), failOnFatalRuntimeError);
        runtime->init();
        runtime->start();
    }

    void TearDown() override
    {
        runtime->shutdown();
        test::util::resetAndWaitUntilDestroyed(runtime);

        // Delete persisted files
        test::util::removeAllCreatedSettingsAndPersistencyFiles();
    }

protected:
    std::shared_ptr<JoynrClusterControllerRuntime> runtime;
    DiscoveryQos discoveryQos;
};

TEST_F(AsyncProxyBuilderTest, createProxyAsync_succeeds)
{
    const std::string domain = "testDomain";
    auto testProvider = std::make_shared<MockTestProvider>();

    types::ProviderQos providerQos;
    providerQos.setPriority(2);
    providerQos.setScope(types::ProviderScope::LOCAL);

    std::string participantId =
            runtime->registerProvider<tests::testProvider>(domain, testProvider, providerQos);

    std::shared_ptr<ProxyBuilder<tests::testProxy>> testProxyBuilder =
            runtime->createProxyBuilder<tests::testProxy>(domain);

    Semaphore onSuccessCalledSemaphore;

    auto onSuccess = [&onSuccessCalledSemaphore](std::shared_ptr<tests::testProxy> proxy) {
        onSuccessCalledSemaphore.notify();
        EXPECT_NE(nullptr, proxy);
    };

    auto onFailure = [](const joynr::exceptions::DiscoveryException&) { FAIL(); };

    testProxyBuilder->setMessagingQos(MessagingQos(50000))
            ->setDiscoveryQos(discoveryQos)
            ->buildAsync(onSuccess, onFailure);

    EXPECT_TRUE(onSuccessCalledSemaphore.waitFor(std::chrono::seconds(10)));
    runtime->unregisterProvider(participantId);
}

TEST_F(AsyncProxyBuilderTest, createProxyAsync_exceptionThrown)
{
    std::shared_ptr<ProxyBuilder<tests::testProxy>> testProxyBuilder =
            runtime->createProxyBuilder<tests::testProxy>("unknownDomain");

    Semaphore onErrorCalledSemaphore;

    auto onSuccess = [](std::shared_ptr<tests::testProxy>) { FAIL(); };

    auto onFailure = [&onErrorCalledSemaphore](const joynr::exceptions::DiscoveryException&) {
        onErrorCalledSemaphore.notify();
    };

    testProxyBuilder->setMessagingQos(MessagingQos(50000))
            ->setDiscoveryQos(discoveryQos)
            ->buildAsync(onSuccess, onFailure);

    EXPECT_TRUE(onErrorCalledSemaphore.waitFor(std::chrono::seconds(10)));
}
<commit_msg>[C++] Add system integration tests for ProxyBuilder::build(arbitrationResult)<commit_after>/*
 * #%L
 * %%
 * Copyright (C) 2011 - 2017 BMW Car IT GmbH
 * %%
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * #L%
 */

#include <memory>

#include <gtest/gtest.h>
#include <gmock/gmock.h>

#include "joynr/JoynrClusterControllerRuntime.h"
#include "joynr/exceptions/JoynrException.h"
#include "joynr/tests/testProxy.h"
#include "joynr/Settings.h"

#include "tests/mock/MockSubscriptionListener.h"
#include "tests/mock/MockTestProvider.h"

#include "tests/JoynrTest.h"
#include "tests/utils/PtrUtils.h"

using namespace ::testing;
using namespace joynr;

class AsyncProxyBuilderTest : public ::testing::Test
{
public:
    void SetUp() override
    {
        discoveryQos.setArbitrationStrategy(DiscoveryQos::ArbitrationStrategy::HIGHEST_PRIORITY);
        discoveryQos.setDiscoveryTimeoutMs(100);
        auto integrationSettings =
                std::make_unique<Settings>("test-resources/libjoynrSystemIntegration1.settings");
        Settings settings("test-resources/MqttSystemIntegrationTest1.settings");
        Settings::merge(settings, *integrationSettings, false);
        runtime = std::make_shared<JoynrClusterControllerRuntime>(
                std::move(integrationSettings), failOnFatalRuntimeError);
        runtime->init();
        runtime->start();
    }

    void TearDown() override
    {
        runtime->shutdown();
        test::util::resetAndWaitUntilDestroyed(runtime);

        // Delete persisted files
        test::util::removeAllCreatedSettingsAndPersistencyFiles();
    }

protected:
    std::shared_ptr<JoynrClusterControllerRuntime> runtime;
    DiscoveryQos discoveryQos;
};

TEST_F(AsyncProxyBuilderTest, createProxyAsync_succeeds)
{
    const std::string domain = "testDomain";
    auto testProvider = std::make_shared<MockTestProvider>();

    types::ProviderQos providerQos;
    providerQos.setPriority(2);
    providerQos.setScope(types::ProviderScope::LOCAL);

    std::string participantId =
            runtime->registerProvider<tests::testProvider>(domain, testProvider, providerQos);

    std::shared_ptr<ProxyBuilder<tests::testProxy>> testProxyBuilder =
            runtime->createProxyBuilder<tests::testProxy>(domain);

    Semaphore onSuccessCalledSemaphore;

    auto onSuccess = [&onSuccessCalledSemaphore](std::shared_ptr<tests::testProxy> proxy) {
        onSuccessCalledSemaphore.notify();
        EXPECT_NE(nullptr, proxy);
    };

    auto onFailure = [](const joynr::exceptions::DiscoveryException&) { FAIL(); };

    testProxyBuilder->setMessagingQos(MessagingQos(50000))
            ->setDiscoveryQos(discoveryQos)
            ->buildAsync(onSuccess, onFailure);

    EXPECT_TRUE(onSuccessCalledSemaphore.waitFor(std::chrono::seconds(10)));
    runtime->unregisterProvider(participantId);
}

TEST_F(AsyncProxyBuilderTest, createProxyAsync_exceptionThrown)
{
    std::shared_ptr<ProxyBuilder<tests::testProxy>> testProxyBuilder =
            runtime->createProxyBuilder<tests::testProxy>("unknownDomain");

    Semaphore onErrorCalledSemaphore;

    auto onSuccess = [](std::shared_ptr<tests::testProxy>) { FAIL(); };

    auto onFailure = [&onErrorCalledSemaphore](const joynr::exceptions::DiscoveryException&) {
        onErrorCalledSemaphore.notify();
    };

    testProxyBuilder->setMessagingQos(MessagingQos(50000))
            ->setDiscoveryQos(discoveryQos)
            ->buildAsync(onSuccess, onFailure);

    EXPECT_TRUE(onErrorCalledSemaphore.waitFor(std::chrono::seconds(10)));
}

TEST_F(AsyncProxyBuilderTest, buildProxyWithArbitrationResult_succeeds)
{
    const std::string domain = "testArbitrationResultSuccessDomain";
    auto testProvider = std::make_shared<MockTestProvider>();

    types::ProviderQos providerQos;
    providerQos.setPriority(2);
    providerQos.setScope(types::ProviderScope::LOCAL);

    std::string participantId =
            runtime->registerProvider<tests::testProvider>(domain, testProvider, providerQos);

    std::shared_ptr<ProxyBuilder<tests::testProxy>> testProxyBuilder =
            runtime->createProxyBuilder<tests::testProxy>(domain);

    // Fake ArbitrationResult to build proxy
    joynr::types::Version interfaceVersion(tests::testProvider::MAJOR_VERSION, tests::testProvider::MINOR_VERSION);
    types::DiscoveryEntryWithMetaInfo discoveryEntry = types::DiscoveryEntryWithMetaInfo(interfaceVersion,
                                                                                domain,
                                                                                tests::testProvider::INTERFACE_NAME(),
                                                                                "participantId1",
                                                                                providerQos,
                                                                                9900,
                                                                                15000,
                                                                                "_publicKeyId1",
                                                                                true);

    std::vector<joynr::types::DiscoveryEntryWithMetaInfo> discoveryEntries {discoveryEntry};
    ArbitrationResult arbitrationResult = ArbitrationResult(discoveryEntries);

    std::shared_ptr<tests::testProxy> proxy = testProxyBuilder
            ->setMessagingQos(MessagingQos(50000))
            ->setDiscoveryQos(discoveryQos)
            ->build(arbitrationResult);
    EXPECT_NE(nullptr, proxy);

    runtime->unregisterProvider(participantId);
}

TEST_F(AsyncProxyBuilderTest, buildProxyWithArbitrationResult_throwsException_whenArbitrationResultEmpty)
{
    const std::string domain = "testArbitrationResultSuccessDomain";
    auto testProvider = std::make_shared<MockTestProvider>();

    types::ProviderQos providerQos;
    providerQos.setPriority(2);
    providerQos.setScope(types::ProviderScope::LOCAL);

    std::string participantId =
            runtime->registerProvider<tests::testProvider>(domain, testProvider, providerQos);

    std::shared_ptr<ProxyBuilder<tests::testProxy>> testProxyBuilder =
            runtime->createProxyBuilder<tests::testProxy>(domain);

    ArbitrationResult arbitrationResult = ArbitrationResult();

    bool exceptionThrown = false;
    bool messageFound = false;
    try {
        std::shared_ptr<tests::testProxy> proxy = testProxyBuilder
                ->setMessagingQos(MessagingQos(50000))
                ->setDiscoveryQos(discoveryQos)
                ->build(arbitrationResult);
    } catch (const exceptions::DiscoveryException& e) {
        std::string exceptionMessage = e.getMessage();
        std::string expectedSubstring = "ArbitrationResult is empty";
        messageFound = exceptionMessage.find(expectedSubstring) != std::string::npos ? true : false;
        exceptionThrown = true;
    }

    EXPECT_TRUE(exceptionThrown);
    EXPECT_TRUE(messageFound);

    runtime->unregisterProvider(participantId);
}

TEST_F(AsyncProxyBuilderTest, buildProxyWithArbitrationResult_throwsException_whenParticipantIdEmpty)
{
    const std::string domain = "testArbitrationResultSuccessDomain";
    auto testProvider = std::make_shared<MockTestProvider>();

    types::ProviderQos providerQos;
    providerQos.setPriority(2);
    providerQos.setScope(types::ProviderScope::LOCAL);

    std::string participantId =
            runtime->registerProvider<tests::testProvider>(domain, testProvider, providerQos);

    std::shared_ptr<ProxyBuilder<tests::testProxy>> testProxyBuilder =
            runtime->createProxyBuilder<tests::testProxy>(domain);

    // Fake ArbitrationResult to build proxy
    joynr::types::Version interfaceVersion(tests::testProvider::MAJOR_VERSION, tests::testProvider::MINOR_VERSION);
    types::DiscoveryEntryWithMetaInfo discoveryEntry = types::DiscoveryEntryWithMetaInfo(interfaceVersion,
                                                                                domain,
                                                                                tests::testProvider::INTERFACE_NAME(),
                                                                                "",
                                                                                providerQos,
                                                                                9900,
                                                                                15000,
                                                                                "_publicKeyId1",
                                                                                true);

    std::vector<joynr::types::DiscoveryEntryWithMetaInfo> discoveryEntries {discoveryEntry};
    ArbitrationResult arbitrationResult = ArbitrationResult(discoveryEntries);

    bool exceptionThrown = false;
    bool messageFound = false;
    try {
        std::shared_ptr<tests::testProxy> proxy = testProxyBuilder
                ->setMessagingQos(MessagingQos(50000))
                ->setDiscoveryQos(discoveryQos)
                ->build(arbitrationResult);
    } catch (const exceptions::DiscoveryException& e) {
        std::string exceptionMessage = e.getMessage();
        std::string expectedSubstring = "ParticipantId is empty";
        messageFound = exceptionMessage.find(expectedSubstring) != std::string::npos ? true : false;
        exceptionThrown = true;
    }

    EXPECT_TRUE(exceptionThrown);
    EXPECT_TRUE(messageFound);

    runtime->unregisterProvider(participantId);
}
<|endoftext|>


<commit_before>/**
 * Copyright (C) 2005-2007 Christoph Rupp (chris@crupp.de).
 * All rights reserved. See file LICENSE for licence and copyright
 * information.
 *
 * unit tests for hamsterdb.h/hamsterdb.c
 *
 */

#include <stdexcept>
#include <cppunit/extensions/HelperMacros.h>
#include <ham/hamsterdb.h>
#include "memtracker.h"
#include "../src/db.h"
#include "../src/version.h"

class HamsterdbTest : public CppUnit::TestFixture
{
    CPPUNIT_TEST_SUITE(HamsterdbTest);
    CPPUNIT_TEST      (versionTest);
    CPPUNIT_TEST      (newTest);
    CPPUNIT_TEST      (deleteTest);
    CPPUNIT_TEST      (openTest);
    CPPUNIT_TEST      (createTest);
    CPPUNIT_TEST      (getErrorTest);
    CPPUNIT_TEST      (setPrefixCompareTest);
    CPPUNIT_TEST      (setCompareTest);
    CPPUNIT_TEST      (findTest);
    CPPUNIT_TEST      (insertTest);
    CPPUNIT_TEST      (eraseTest);
    CPPUNIT_TEST      (flushTest);
    CPPUNIT_TEST      (closeTest);
    CPPUNIT_TEST      (cursorCreateTest);
    CPPUNIT_TEST      (cursorCloneTest);
    CPPUNIT_TEST      (cursorMoveTest);
    CPPUNIT_TEST      (cursorReplaceTest);
    CPPUNIT_TEST      (cursorFindTest);
    CPPUNIT_TEST      (cursorInsertTest);
    CPPUNIT_TEST      (cursorEraseTest);
    CPPUNIT_TEST      (cursorCloseTest);
    CPPUNIT_TEST_SUITE_END();

protected:
    ham_db_t *m_db;
    memtracker_t *m_alloc;

public:
    void setUp()
    {
        CPPUNIT_ASSERT((m_alloc=memtracker_new())!=0);
        CPPUNIT_ASSERT_EQUAL(0, ham_new(&m_db));
        db_set_allocator(m_db, (mem_allocator_t *)m_alloc);
        CPPUNIT_ASSERT_EQUAL(0, ham_create(m_db, 0, HAM_IN_MEMORY_DB, 0));
    }

    void tearDown()
    {
        ham_close(m_db);
        ham_delete(m_db);
        CPPUNIT_ASSERT(!memtracker_get_leaks(m_alloc));
    }

    void versionTest(void)
    {
        ham_u32_t major, minor, revision;

        ham_get_version(&major, &minor, &revision);

        CPPUNIT_ASSERT_EQUAL((ham_u32_t)HAM_VERSION_MAJ, major);
        CPPUNIT_ASSERT_EQUAL((ham_u32_t)HAM_VERSION_MIN, minor);
        CPPUNIT_ASSERT_EQUAL((ham_u32_t)HAM_VERSION_REV, revision);
    };

    void newTest(void)
    {
        CPPUNIT_ASSERT_EQUAL(HAM_INV_PARAMETER, ham_new(0));
    }

    void deleteTest(void)
    {
        CPPUNIT_ASSERT_EQUAL(HAM_INV_PARAMETER, ham_delete(0));
    }

    void openTest(void)
    {
        ham_db_t *db;

        CPPUNIT_ASSERT_EQUAL(0, ham_new(&db));

        CPPUNIT_ASSERT_EQUAL(HAM_INV_PARAMETER,
                ham_open(0, "test.db", 0));
        CPPUNIT_ASSERT_EQUAL(HAM_INV_PARAMETER,
                ham_open(db, 0, 0));
        CPPUNIT_ASSERT_EQUAL(HAM_INV_PARAMETER,
                ham_open(db, 0, HAM_IN_MEMORY_DB));
        CPPUNIT_ASSERT_EQUAL(HAM_FILE_NOT_FOUND,
                ham_open(db, "xxxx...", 0));

#if WIN32
        CPPUNIT_ASSERT_EQUAL(HAM_IO_ERROR,
                ham_open(db, "c:\\windows", 0));
#else
        CPPUNIT_ASSERT_EQUAL(HAM_IO_ERROR,
                ham_open(db, "/dev", 0));
#endif

        ham_delete(db);
    }

    void createTest(void)
    {
        ham_db_t *db;
        ham_parameter_t cs[]={{HAM_PARAM_CACHESIZE, 1024}, {0, 0}};
        ham_parameter_t ps[]={{HAM_PARAM_PAGESIZE,   512}, {0, 0}};

        CPPUNIT_ASSERT_EQUAL(0, ham_new(&db));

        CPPUNIT_ASSERT_EQUAL(HAM_INV_PARAMETER,
                ham_create(0, "test.db", 0, 0664));
        CPPUNIT_ASSERT_EQUAL(HAM_INV_PARAMETER,
                ham_create(db, 0, 0, 0664));
        CPPUNIT_ASSERT_EQUAL(HAM_INV_PARAMETER,
                ham_create(db, 0, HAM_IN_MEMORY_DB|HAM_CACHE_STRICT, 0));
        CPPUNIT_ASSERT_EQUAL(HAM_INV_PARAMETER,
                ham_create_ex(db, 0, HAM_IN_MEMORY_DB, 0, &cs[0]));
        CPPUNIT_ASSERT_EQUAL(HAM_INV_PAGESIZE,
                ham_create_ex(db, ".test", 0, 0, &ps[0]));
#if WIN32
        CPPUNIT_ASSERT_EQUAL(HAM_IO_ERROR,
                ham_create(db, "c:\\windows", 0, 0664));
#else
        CPPUNIT_ASSERT_EQUAL(HAM_IO_ERROR,
                ham_create(db, "/home", 0, 0664));
#endif
        ham_delete(db);
    }

    void getErrorTest(void)
    {
        CPPUNIT_ASSERT_EQUAL(0, ham_get_error(0));
    }

    void setPrefixCompareTest(void)
    {
        CPPUNIT_ASSERT_EQUAL(HAM_INV_PARAMETER,
                ham_set_prefix_compare_func(0, 0));
    }

    void setCompareTest(void)
    {
        CPPUNIT_ASSERT_EQUAL(HAM_INV_PARAMETER,
                ham_set_compare_func(0, 0));
    }

    void findTest(void)
    {
        ham_key_t key;
        ham_record_t rec;
        ::memset(&key, 0, sizeof(key));
        ::memset(&rec, 0, sizeof(rec));

        CPPUNIT_ASSERT_EQUAL(HAM_INV_PARAMETER,
                ham_find(0, 0, &key, &rec, 0));
        CPPUNIT_ASSERT_EQUAL(HAM_INV_PARAMETER,
                ham_find(m_db, 0, 0, &rec, 0));
        CPPUNIT_ASSERT_EQUAL(HAM_INV_PARAMETER,
                ham_find(m_db, 0, &key, 0, 0));
        CPPUNIT_ASSERT_EQUAL(HAM_KEY_NOT_FOUND,
                ham_find(m_db, 0, &key, &rec, 0));
    }

    void insertTest(void)
    {
        ham_key_t key;
        ham_record_t rec;
        ::memset(&key, 0, sizeof(key));
        ::memset(&rec, 0, sizeof(rec));

        CPPUNIT_ASSERT_EQUAL(HAM_INV_PARAMETER,
                ham_insert(0, 0, &key, &rec, 0));
        CPPUNIT_ASSERT_EQUAL(HAM_INV_PARAMETER,
                ham_insert(m_db, 0, 0, &rec, 0));
        CPPUNIT_ASSERT_EQUAL(HAM_INV_PARAMETER,
                ham_insert(m_db, 0, &key, 0, 0));
        CPPUNIT_ASSERT_EQUAL(0,
                ham_insert(m_db, 0, &key, &rec, 0));
    }

    void eraseTest(void)
    {
        ham_key_t key;
        ham_record_t rec;
        ::memset(&key, 0, sizeof(key));
        ::memset(&rec, 0, sizeof(rec));

        CPPUNIT_ASSERT_EQUAL(HAM_INV_PARAMETER,
                ham_erase(0, 0, &key, 0));
        CPPUNIT_ASSERT_EQUAL(HAM_INV_PARAMETER,
                ham_erase(m_db, 0, 0, 0));
        CPPUNIT_ASSERT_EQUAL(HAM_KEY_NOT_FOUND,
                ham_erase(m_db, 0, &key, 0));
    }

    void flushTest(void)
    {
        CPPUNIT_ASSERT_EQUAL(HAM_INV_PARAMETER,
                ham_flush(0, 0));
    }

    void closeTest(void)
    {
        CPPUNIT_ASSERT_EQUAL(HAM_INV_PARAMETER, ham_close(0));
    }

    void cursorCreateTest(void)
    {
        ham_cursor_t *cursor;

        CPPUNIT_ASSERT_EQUAL(HAM_INV_PARAMETER,
                ham_cursor_create(0, 0, 0, &cursor));
        CPPUNIT_ASSERT_EQUAL(HAM_INV_PARAMETER,
                ham_cursor_create(m_db, 0, 0, 0));
    }

    void cursorCloneTest(void)
    {
        ham_cursor_t src, *dest;

        CPPUNIT_ASSERT_EQUAL(HAM_INV_PARAMETER,
                ham_cursor_clone(0, &dest));
        CPPUNIT_ASSERT_EQUAL(HAM_INV_PARAMETER,
                ham_cursor_clone(&src, 0));
    }

    void cursorMoveTest(void)
    {
        ham_cursor_t *cursor;
        ham_key_t key;
        ::memset(&key, 0, sizeof(key));

        CPPUNIT_ASSERT_EQUAL(0, ham_cursor_create(m_db, 0, 0, &cursor));

        CPPUNIT_ASSERT_EQUAL(HAM_INV_PARAMETER,
                ham_cursor_move(0, 0, 0, 0));
        CPPUNIT_ASSERT_EQUAL(HAM_CURSOR_IS_NIL,
                ham_cursor_move(cursor, &key, 0, 0));
        CPPUNIT_ASSERT_EQUAL(HAM_KEY_NOT_FOUND,
                ham_cursor_move(cursor, &key, 0, HAM_CURSOR_FIRST));
        CPPUNIT_ASSERT_EQUAL(HAM_KEY_NOT_FOUND,
                ham_cursor_move(cursor, &key, 0, HAM_CURSOR_LAST));
        CPPUNIT_ASSERT_EQUAL(HAM_KEY_NOT_FOUND,
                ham_cursor_move(cursor, &key, 0, HAM_CURSOR_NEXT));
        CPPUNIT_ASSERT_EQUAL(HAM_KEY_NOT_FOUND,
                ham_cursor_move(cursor, &key, 0, HAM_CURSOR_PREVIOUS));

        ham_cursor_close(cursor);
    }

    void cursorReplaceTest(void)
    {
        ham_cursor_t cursor;
        ham_record_t *record;

        CPPUNIT_ASSERT_EQUAL(HAM_INV_PARAMETER,
                ham_cursor_replace(0, record, 0));
        CPPUNIT_ASSERT_EQUAL(HAM_INV_PARAMETER,
                ham_cursor_replace(&cursor, 0, 0));
    }

    void cursorFindTest(void)
    {
        ham_cursor_t cursor;
        ham_key_t *key;

        CPPUNIT_ASSERT_EQUAL(HAM_INV_PARAMETER,
                ham_cursor_find(0, key, 0));
        CPPUNIT_ASSERT_EQUAL(HAM_INV_PARAMETER,
                ham_cursor_find(&cursor, 0, 0));
    }

    void cursorInsertTest(void)
    {
        ham_cursor_t cursor;
        ham_key_t key;
        ham_record_t rec;
        ::memset(&key, 0, sizeof(key));
        ::memset(&rec, 0, sizeof(rec));

        CPPUNIT_ASSERT_EQUAL(HAM_INV_PARAMETER,
                ham_cursor_insert(0, &key, &rec, 0));
        CPPUNIT_ASSERT_EQUAL(HAM_INV_PARAMETER,
                ham_cursor_insert(&cursor, 0, &rec, 0));
        CPPUNIT_ASSERT_EQUAL(HAM_INV_PARAMETER,
                ham_cursor_insert(&cursor, &key, 0, 0));
    }

    void cursorEraseTest(void)
    {
        CPPUNIT_ASSERT_EQUAL(HAM_INV_PARAMETER,
                ham_cursor_erase(0, 0));
    }

    void cursorCloseTest(void)
    {
        CPPUNIT_ASSERT_EQUAL(HAM_INV_PARAMETER,
                ham_cursor_close(0));
    }
};

CPPUNIT_TEST_SUITE_REGISTRATION(HamsterdbTest);

<commit_msg>small fix - now runs on cygwin<commit_after>/**
 * Copyright (C) 2005-2007 Christoph Rupp (chris@crupp.de).
 * All rights reserved. See file LICENSE for licence and copyright
 * information.
 *
 * unit tests for hamsterdb.h/hamsterdb.c
 *
 */

#include <stdexcept>
#include <cppunit/extensions/HelperMacros.h>
#include <ham/hamsterdb.h>
#include "memtracker.h"
#include "../src/db.h"
#include "../src/version.h"

class HamsterdbTest : public CppUnit::TestFixture
{
    CPPUNIT_TEST_SUITE(HamsterdbTest);
    CPPUNIT_TEST      (versionTest);
    CPPUNIT_TEST      (newTest);
    CPPUNIT_TEST      (deleteTest);
    CPPUNIT_TEST      (openTest);
    CPPUNIT_TEST      (createTest);
    CPPUNIT_TEST      (getErrorTest);
    CPPUNIT_TEST      (setPrefixCompareTest);
    CPPUNIT_TEST      (setCompareTest);
    CPPUNIT_TEST      (findTest);
    CPPUNIT_TEST      (insertTest);
    CPPUNIT_TEST      (eraseTest);
    CPPUNIT_TEST      (flushTest);
    CPPUNIT_TEST      (closeTest);
    CPPUNIT_TEST      (cursorCreateTest);
    CPPUNIT_TEST      (cursorCloneTest);
    CPPUNIT_TEST      (cursorMoveTest);
    CPPUNIT_TEST      (cursorReplaceTest);
    CPPUNIT_TEST      (cursorFindTest);
    CPPUNIT_TEST      (cursorInsertTest);
    CPPUNIT_TEST      (cursorEraseTest);
    CPPUNIT_TEST      (cursorCloseTest);
    CPPUNIT_TEST_SUITE_END();

protected:
    ham_db_t *m_db;
    memtracker_t *m_alloc;

public:
    void setUp()
    {
        CPPUNIT_ASSERT((m_alloc=memtracker_new())!=0);
        CPPUNIT_ASSERT_EQUAL(0, ham_new(&m_db));
        db_set_allocator(m_db, (mem_allocator_t *)m_alloc);
        CPPUNIT_ASSERT_EQUAL(0, ham_create(m_db, 0, HAM_IN_MEMORY_DB, 0));
    }

    void tearDown()
    {
        ham_close(m_db);
        ham_delete(m_db);
        CPPUNIT_ASSERT(!memtracker_get_leaks(m_alloc));
    }

    void versionTest(void)
    {
        ham_u32_t major, minor, revision;

        ham_get_version(&major, &minor, &revision);

        CPPUNIT_ASSERT_EQUAL((ham_u32_t)HAM_VERSION_MAJ, major);
        CPPUNIT_ASSERT_EQUAL((ham_u32_t)HAM_VERSION_MIN, minor);
        CPPUNIT_ASSERT_EQUAL((ham_u32_t)HAM_VERSION_REV, revision);
    };

    void newTest(void)
    {
        CPPUNIT_ASSERT_EQUAL(HAM_INV_PARAMETER, ham_new(0));
    }

    void deleteTest(void)
    {
        CPPUNIT_ASSERT_EQUAL(HAM_INV_PARAMETER, ham_delete(0));
    }

    void openTest(void)
    {
        ham_db_t *db;

        CPPUNIT_ASSERT_EQUAL(0, ham_new(&db));

        CPPUNIT_ASSERT_EQUAL(HAM_INV_PARAMETER,
                ham_open(0, "test.db", 0));
        CPPUNIT_ASSERT_EQUAL(HAM_INV_PARAMETER,
                ham_open(db, 0, 0));
        CPPUNIT_ASSERT_EQUAL(HAM_INV_PARAMETER,
                ham_open(db, 0, HAM_IN_MEMORY_DB));
        CPPUNIT_ASSERT_EQUAL(HAM_FILE_NOT_FOUND,
                ham_open(db, "xxxx...", 0));

#if WIN32
        CPPUNIT_ASSERT_EQUAL(HAM_IO_ERROR,
                ham_open(db, "c:\\windows", 0));
#else
        CPPUNIT_ASSERT_EQUAL(HAM_IO_ERROR,
                ham_open(db, "/usr", 0));
#endif

        ham_delete(db);
    }

    void createTest(void)
    {
        ham_db_t *db;
        ham_parameter_t cs[]={{HAM_PARAM_CACHESIZE, 1024}, {0, 0}};
        ham_parameter_t ps[]={{HAM_PARAM_PAGESIZE,   512}, {0, 0}};

        CPPUNIT_ASSERT_EQUAL(0, ham_new(&db));

        CPPUNIT_ASSERT_EQUAL(HAM_INV_PARAMETER,
                ham_create(0, "test.db", 0, 0664));
        CPPUNIT_ASSERT_EQUAL(HAM_INV_PARAMETER,
                ham_create(db, 0, 0, 0664));
        CPPUNIT_ASSERT_EQUAL(HAM_INV_PARAMETER,
                ham_create(db, 0, HAM_IN_MEMORY_DB|HAM_CACHE_STRICT, 0));
        CPPUNIT_ASSERT_EQUAL(HAM_INV_PARAMETER,
                ham_create_ex(db, 0, HAM_IN_MEMORY_DB, 0, &cs[0]));
        CPPUNIT_ASSERT_EQUAL(HAM_INV_PAGESIZE,
                ham_create_ex(db, ".test", 0, 0, &ps[0]));
#if WIN32
        CPPUNIT_ASSERT_EQUAL(HAM_IO_ERROR,
                ham_create(db, "c:\\windows", 0, 0664));
#else
        CPPUNIT_ASSERT_EQUAL(HAM_IO_ERROR,
                ham_create(db, "/home", 0, 0664));
#endif
        ham_delete(db);
    }

    void getErrorTest(void)
    {
        CPPUNIT_ASSERT_EQUAL(0, ham_get_error(0));
    }

    void setPrefixCompareTest(void)
    {
        CPPUNIT_ASSERT_EQUAL(HAM_INV_PARAMETER,
                ham_set_prefix_compare_func(0, 0));
    }

    void setCompareTest(void)
    {
        CPPUNIT_ASSERT_EQUAL(HAM_INV_PARAMETER,
                ham_set_compare_func(0, 0));
    }

    void findTest(void)
    {
        ham_key_t key;
        ham_record_t rec;
        ::memset(&key, 0, sizeof(key));
        ::memset(&rec, 0, sizeof(rec));

        CPPUNIT_ASSERT_EQUAL(HAM_INV_PARAMETER,
                ham_find(0, 0, &key, &rec, 0));
        CPPUNIT_ASSERT_EQUAL(HAM_INV_PARAMETER,
                ham_find(m_db, 0, 0, &rec, 0));
        CPPUNIT_ASSERT_EQUAL(HAM_INV_PARAMETER,
                ham_find(m_db, 0, &key, 0, 0));
        CPPUNIT_ASSERT_EQUAL(HAM_KEY_NOT_FOUND,
                ham_find(m_db, 0, &key, &rec, 0));
    }

    void insertTest(void)
    {
        ham_key_t key;
        ham_record_t rec;
        ::memset(&key, 0, sizeof(key));
        ::memset(&rec, 0, sizeof(rec));

        CPPUNIT_ASSERT_EQUAL(HAM_INV_PARAMETER,
                ham_insert(0, 0, &key, &rec, 0));
        CPPUNIT_ASSERT_EQUAL(HAM_INV_PARAMETER,
                ham_insert(m_db, 0, 0, &rec, 0));
        CPPUNIT_ASSERT_EQUAL(HAM_INV_PARAMETER,
                ham_insert(m_db, 0, &key, 0, 0));
        CPPUNIT_ASSERT_EQUAL(0,
                ham_insert(m_db, 0, &key, &rec, 0));
    }

    void eraseTest(void)
    {
        ham_key_t key;
        ham_record_t rec;
        ::memset(&key, 0, sizeof(key));
        ::memset(&rec, 0, sizeof(rec));

        CPPUNIT_ASSERT_EQUAL(HAM_INV_PARAMETER,
                ham_erase(0, 0, &key, 0));
        CPPUNIT_ASSERT_EQUAL(HAM_INV_PARAMETER,
                ham_erase(m_db, 0, 0, 0));
        CPPUNIT_ASSERT_EQUAL(HAM_KEY_NOT_FOUND,
                ham_erase(m_db, 0, &key, 0));
    }

    void flushTest(void)
    {
        CPPUNIT_ASSERT_EQUAL(HAM_INV_PARAMETER,
                ham_flush(0, 0));
    }

    void closeTest(void)
    {
        CPPUNIT_ASSERT_EQUAL(HAM_INV_PARAMETER, ham_close(0));
    }

    void cursorCreateTest(void)
    {
        ham_cursor_t *cursor;

        CPPUNIT_ASSERT_EQUAL(HAM_INV_PARAMETER,
                ham_cursor_create(0, 0, 0, &cursor));
        CPPUNIT_ASSERT_EQUAL(HAM_INV_PARAMETER,
                ham_cursor_create(m_db, 0, 0, 0));
    }

    void cursorCloneTest(void)
    {
        ham_cursor_t src, *dest;

        CPPUNIT_ASSERT_EQUAL(HAM_INV_PARAMETER,
                ham_cursor_clone(0, &dest));
        CPPUNIT_ASSERT_EQUAL(HAM_INV_PARAMETER,
                ham_cursor_clone(&src, 0));
    }

    void cursorMoveTest(void)
    {
        ham_cursor_t *cursor;
        ham_key_t key;
        ::memset(&key, 0, sizeof(key));

        CPPUNIT_ASSERT_EQUAL(0, ham_cursor_create(m_db, 0, 0, &cursor));

        CPPUNIT_ASSERT_EQUAL(HAM_INV_PARAMETER,
                ham_cursor_move(0, 0, 0, 0));
        CPPUNIT_ASSERT_EQUAL(HAM_CURSOR_IS_NIL,
                ham_cursor_move(cursor, &key, 0, 0));
        CPPUNIT_ASSERT_EQUAL(HAM_KEY_NOT_FOUND,
                ham_cursor_move(cursor, &key, 0, HAM_CURSOR_FIRST));
        CPPUNIT_ASSERT_EQUAL(HAM_KEY_NOT_FOUND,
                ham_cursor_move(cursor, &key, 0, HAM_CURSOR_LAST));
        CPPUNIT_ASSERT_EQUAL(HAM_KEY_NOT_FOUND,
                ham_cursor_move(cursor, &key, 0, HAM_CURSOR_NEXT));
        CPPUNIT_ASSERT_EQUAL(HAM_KEY_NOT_FOUND,
                ham_cursor_move(cursor, &key, 0, HAM_CURSOR_PREVIOUS));

        ham_cursor_close(cursor);
    }

    void cursorReplaceTest(void)
    {
        ham_cursor_t cursor;
        ham_record_t *record;

        CPPUNIT_ASSERT_EQUAL(HAM_INV_PARAMETER,
                ham_cursor_replace(0, record, 0));
        CPPUNIT_ASSERT_EQUAL(HAM_INV_PARAMETER,
                ham_cursor_replace(&cursor, 0, 0));
    }

    void cursorFindTest(void)
    {
        ham_cursor_t cursor;
        ham_key_t *key;

        CPPUNIT_ASSERT_EQUAL(HAM_INV_PARAMETER,
                ham_cursor_find(0, key, 0));
        CPPUNIT_ASSERT_EQUAL(HAM_INV_PARAMETER,
                ham_cursor_find(&cursor, 0, 0));
    }

    void cursorInsertTest(void)
    {
        ham_cursor_t cursor;
        ham_key_t key;
        ham_record_t rec;
        ::memset(&key, 0, sizeof(key));
        ::memset(&rec, 0, sizeof(rec));

        CPPUNIT_ASSERT_EQUAL(HAM_INV_PARAMETER,
                ham_cursor_insert(0, &key, &rec, 0));
        CPPUNIT_ASSERT_EQUAL(HAM_INV_PARAMETER,
                ham_cursor_insert(&cursor, 0, &rec, 0));
        CPPUNIT_ASSERT_EQUAL(HAM_INV_PARAMETER,
                ham_cursor_insert(&cursor, &key, 0, 0));
    }

    void cursorEraseTest(void)
    {
        CPPUNIT_ASSERT_EQUAL(HAM_INV_PARAMETER,
                ham_cursor_erase(0, 0));
    }

    void cursorCloseTest(void)
    {
        CPPUNIT_ASSERT_EQUAL(HAM_INV_PARAMETER,
                ham_cursor_close(0));
    }
};

CPPUNIT_TEST_SUITE_REGISTRATION(HamsterdbTest);

<|endoftext|>