<commit_before>// Copyright (c) 2021 by Apex.AI Inc. All rights reserved.
//
// 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.
//
// SPDX-License-Identifier: Apache-2.0

#include "iceoryx_posh/popo/server_options.hpp"

#include "test.hpp"

namespace
{
using namespace ::testing;

TEST(ServerOptions_test, SerializationRoundTripIsSuccessful)
{
    ::testing::Test::RecordProperty("TEST_ID", "888f49c2-0b70-4033-a13a-175dbc1b8e38");
    iox::popo::ServerOptions defaultOptions;
    iox::popo::ServerOptions testOptions;

    testOptions.requestQueueCapacity = 42;
    testOptions.nodeName = "hypnotoad";
    testOptions.offerOnCreate = false;
    testOptions.requestQueueFullPolicy = iox::popo::QueueFullPolicy::BLOCK_PRODUCER;
    testOptions.clientTooSlowPolicy = iox::popo::ConsumerTooSlowPolicy::WAIT_FOR_CONSUMER;

    iox::popo::ServerOptions::deserialize(testOptions.serialize())
        .and_then([&](auto& roundTripOptions) {
            EXPECT_THAT(roundTripOptions.requestQueueCapacity, Ne(defaultOptions.requestQueueCapacity));
            EXPECT_THAT(roundTripOptions.requestQueueCapacity, Eq(testOptions.requestQueueCapacity));

            EXPECT_THAT(roundTripOptions.nodeName, Ne(defaultOptions.nodeName));
            EXPECT_THAT(roundTripOptions.nodeName, Eq(testOptions.nodeName));

            EXPECT_THAT(roundTripOptions.offerOnCreate, Ne(defaultOptions.offerOnCreate));
            EXPECT_THAT(roundTripOptions.offerOnCreate, Eq(testOptions.offerOnCreate));

            EXPECT_THAT(roundTripOptions.requestQueueFullPolicy, Ne(defaultOptions.requestQueueFullPolicy));
            EXPECT_THAT(roundTripOptions.requestQueueFullPolicy, Eq(testOptions.requestQueueFullPolicy));

            EXPECT_THAT(roundTripOptions.clientTooSlowPolicy, Ne(defaultOptions.clientTooSlowPolicy));
            EXPECT_THAT(roundTripOptions.clientTooSlowPolicy, Eq(testOptions.clientTooSlowPolicy));
        })
        .or_else([&](auto&) { FAIL() << "Serialization/Deserialization of ServerOptions failed!"; });
}

TEST(ServerOptions_test, DeserializingBogusDataFails)
{
    ::testing::Test::RecordProperty("TEST_ID", "ebc97c23-87df-484c-8c3c-1b76f1351997");
    const auto bogusSerialization = iox::cxx::Serialization::create("hypnotoad", "brain slug", "rock star");
    iox::popo::ServerOptions::deserialize(bogusSerialization)
        .and_then([&](auto&) { GTEST_FAIL() << "Deserialization is expected to fail!"; })
        .or_else([&](auto&) { GTEST_SUCCEED(); });
}

using QueueFullPolicyUT = std::underlying_type_t<iox::popo::QueueFullPolicy>;
using ConsumerTooSlowPolicyUT = std::underlying_type_t<iox::popo::ConsumerTooSlowPolicy>;
iox::cxx::Serialization enumSerialization(QueueFullPolicyUT requsetQueueFullPolicy,
                                          ConsumerTooSlowPolicyUT clientTooSlowPolicy)
{
    constexpr uint64_t REQUEST_QUEUE_CAPACITY{42U};
    const iox::NodeName_t NODE_NAME{"harr-harr"};
    constexpr bool OFFER_ON_CREATE{true};

    return iox::cxx::Serialization::create(
        REQUEST_QUEUE_CAPACITY, NODE_NAME, OFFER_ON_CREATE, requsetQueueFullPolicy, clientTooSlowPolicy);
}

TEST(ServerOptions_test, DeserializingValidRequestQueueFullPolicyAndClientTooSlowPolicyIsSuccessful)
{
    ::testing::Test::RecordProperty("TEST_ID", "95cd1efc-63c8-4eee-9f4e-ed105e653d71");
    constexpr QueueFullPolicyUT REQUEST_QUEUE_FULL_POLICY{
        static_cast<QueueFullPolicyUT>(iox::popo::QueueFullPolicy::BLOCK_PRODUCER)};
    constexpr ConsumerTooSlowPolicyUT CLIENT_TOO_SLOW_POLICY{
        static_cast<ConsumerTooSlowPolicyUT>(iox::popo::ConsumerTooSlowPolicy::WAIT_FOR_CONSUMER)};

    const auto serialized = enumSerialization(REQUEST_QUEUE_FULL_POLICY, CLIENT_TOO_SLOW_POLICY);
    iox::popo::ServerOptions::deserialize(serialized).and_then([&](auto&) { GTEST_SUCCEED(); }).or_else([&](auto&) {
        GTEST_FAIL() << "Serialization/Deserialization of ServerOptions failed!";
    });
}

TEST(ServerOptions_test, DeserializingInvalidRequestQueueFullPolicyFails)
{
    ::testing::Test::RecordProperty("TEST_ID", "3d392b0a-6140-4b06-a08d-b06ad27f31cd");
    constexpr QueueFullPolicyUT REQUEST_QUEUE_FULL_POLICY{123};
    constexpr ConsumerTooSlowPolicyUT CLIENT_TOO_SLOW_POLICY{
        static_cast<ConsumerTooSlowPolicyUT>(iox::popo::ConsumerTooSlowPolicy::DISCARD_OLDEST_DATA)};

    const auto serialized = enumSerialization(REQUEST_QUEUE_FULL_POLICY, CLIENT_TOO_SLOW_POLICY);
    iox::popo::ServerOptions::deserialize(serialized)
        .and_then([&](auto&) { GTEST_FAIL() << "Deserialization is expected to fail!"; })
        .or_else([&](auto&) { GTEST_SUCCEED(); });
}

TEST(ServerOptions_test, DeserializingInvalidClientTooSlowPolicyFails)
{
    ::testing::Test::RecordProperty("TEST_ID", "35b85d5a-7e59-4f0c-8afc-38f1eec914b8");
    constexpr QueueFullPolicyUT REQUEST_QUEUE_FULL_POLICY{
        static_cast<QueueFullPolicyUT>(iox::popo::QueueFullPolicy::DISCARD_OLDEST_DATA)};
    constexpr ConsumerTooSlowPolicyUT CLIENT_TOO_SLOW_POLICY{111};

    const auto serialized = enumSerialization(REQUEST_QUEUE_FULL_POLICY, CLIENT_TOO_SLOW_POLICY);
    iox::popo::ServerOptions::deserialize(serialized)
        .and_then([&](auto&) { GTEST_FAIL() << "Deserialization is expected to fail!"; })
        .or_else([&](auto&) { GTEST_SUCCEED(); });
}

} // namespace
<commit_msg>iox-#27 Add tests for comparison operator for ServerOptions<commit_after>// Copyright (c) 2021 by Apex.AI Inc. All rights reserved.
//
// 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.
//
// SPDX-License-Identifier: Apache-2.0

#include "iceoryx_posh/popo/server_options.hpp"

#include "test.hpp"

namespace
{
using namespace ::testing;
using namespace iox::popo;

TEST(ServerOptions_test, SerializationRoundTripIsSuccessful)
{
    ::testing::Test::RecordProperty("TEST_ID", "888f49c2-0b70-4033-a13a-175dbc1b8e38");
    iox::popo::ServerOptions defaultOptions;
    iox::popo::ServerOptions testOptions;

    testOptions.requestQueueCapacity = 42;
    testOptions.nodeName = "hypnotoad";
    testOptions.offerOnCreate = false;
    testOptions.requestQueueFullPolicy = iox::popo::QueueFullPolicy::BLOCK_PRODUCER;
    testOptions.clientTooSlowPolicy = iox::popo::ConsumerTooSlowPolicy::WAIT_FOR_CONSUMER;

    iox::popo::ServerOptions::deserialize(testOptions.serialize())
        .and_then([&](auto& roundTripOptions) {
            EXPECT_THAT(roundTripOptions.requestQueueCapacity, Ne(defaultOptions.requestQueueCapacity));
            EXPECT_THAT(roundTripOptions.requestQueueCapacity, Eq(testOptions.requestQueueCapacity));

            EXPECT_THAT(roundTripOptions.nodeName, Ne(defaultOptions.nodeName));
            EXPECT_THAT(roundTripOptions.nodeName, Eq(testOptions.nodeName));

            EXPECT_THAT(roundTripOptions.offerOnCreate, Ne(defaultOptions.offerOnCreate));
            EXPECT_THAT(roundTripOptions.offerOnCreate, Eq(testOptions.offerOnCreate));

            EXPECT_THAT(roundTripOptions.requestQueueFullPolicy, Ne(defaultOptions.requestQueueFullPolicy));
            EXPECT_THAT(roundTripOptions.requestQueueFullPolicy, Eq(testOptions.requestQueueFullPolicy));

            EXPECT_THAT(roundTripOptions.clientTooSlowPolicy, Ne(defaultOptions.clientTooSlowPolicy));
            EXPECT_THAT(roundTripOptions.clientTooSlowPolicy, Eq(testOptions.clientTooSlowPolicy));
        })
        .or_else([&](auto&) { FAIL() << "Serialization/Deserialization of ServerOptions failed!"; });
}

TEST(ServerOptions_test, DeserializingBogusDataFails)
{
    ::testing::Test::RecordProperty("TEST_ID", "ebc97c23-87df-484c-8c3c-1b76f1351997");
    const auto bogusSerialization = iox::cxx::Serialization::create("hypnotoad", "brain slug", "rock star");
    iox::popo::ServerOptions::deserialize(bogusSerialization)
        .and_then([&](auto&) { GTEST_FAIL() << "Deserialization is expected to fail!"; })
        .or_else([&](auto&) { GTEST_SUCCEED(); });
}

using QueueFullPolicyUT = std::underlying_type_t<iox::popo::QueueFullPolicy>;
using ConsumerTooSlowPolicyUT = std::underlying_type_t<iox::popo::ConsumerTooSlowPolicy>;
iox::cxx::Serialization enumSerialization(QueueFullPolicyUT requsetQueueFullPolicy,
                                          ConsumerTooSlowPolicyUT clientTooSlowPolicy)
{
    constexpr uint64_t REQUEST_QUEUE_CAPACITY{42U};
    const iox::NodeName_t NODE_NAME{"harr-harr"};
    constexpr bool OFFER_ON_CREATE{true};

    return iox::cxx::Serialization::create(
        REQUEST_QUEUE_CAPACITY, NODE_NAME, OFFER_ON_CREATE, requsetQueueFullPolicy, clientTooSlowPolicy);
}

TEST(ServerOptions_test, DeserializingValidRequestQueueFullPolicyAndClientTooSlowPolicyIsSuccessful)
{
    ::testing::Test::RecordProperty("TEST_ID", "95cd1efc-63c8-4eee-9f4e-ed105e653d71");
    constexpr QueueFullPolicyUT REQUEST_QUEUE_FULL_POLICY{
        static_cast<QueueFullPolicyUT>(iox::popo::QueueFullPolicy::BLOCK_PRODUCER)};
    constexpr ConsumerTooSlowPolicyUT CLIENT_TOO_SLOW_POLICY{
        static_cast<ConsumerTooSlowPolicyUT>(iox::popo::ConsumerTooSlowPolicy::WAIT_FOR_CONSUMER)};

    const auto serialized = enumSerialization(REQUEST_QUEUE_FULL_POLICY, CLIENT_TOO_SLOW_POLICY);
    iox::popo::ServerOptions::deserialize(serialized).and_then([&](auto&) { GTEST_SUCCEED(); }).or_else([&](auto&) {
        GTEST_FAIL() << "Serialization/Deserialization of ServerOptions failed!";
    });
}

TEST(ServerOptions_test, DeserializingInvalidRequestQueueFullPolicyFails)
{
    ::testing::Test::RecordProperty("TEST_ID", "3d392b0a-6140-4b06-a08d-b06ad27f31cd");
    constexpr QueueFullPolicyUT REQUEST_QUEUE_FULL_POLICY{123};
    constexpr ConsumerTooSlowPolicyUT CLIENT_TOO_SLOW_POLICY{
        static_cast<ConsumerTooSlowPolicyUT>(iox::popo::ConsumerTooSlowPolicy::DISCARD_OLDEST_DATA)};

    const auto serialized = enumSerialization(REQUEST_QUEUE_FULL_POLICY, CLIENT_TOO_SLOW_POLICY);
    iox::popo::ServerOptions::deserialize(serialized)
        .and_then([&](auto&) { GTEST_FAIL() << "Deserialization is expected to fail!"; })
        .or_else([&](auto&) { GTEST_SUCCEED(); });
}

TEST(ServerOptions_test, DeserializingInvalidClientTooSlowPolicyFails)
{
    ::testing::Test::RecordProperty("TEST_ID", "35b85d5a-7e59-4f0c-8afc-38f1eec914b8");
    constexpr QueueFullPolicyUT REQUEST_QUEUE_FULL_POLICY{
        static_cast<QueueFullPolicyUT>(iox::popo::QueueFullPolicy::DISCARD_OLDEST_DATA)};
    constexpr ConsumerTooSlowPolicyUT CLIENT_TOO_SLOW_POLICY{111};

    const auto serialized = enumSerialization(REQUEST_QUEUE_FULL_POLICY, CLIENT_TOO_SLOW_POLICY);
    iox::popo::ServerOptions::deserialize(serialized)
        .and_then([&](auto&) { GTEST_FAIL() << "Deserialization is expected to fail!"; })
        .or_else([&](auto&) { GTEST_SUCCEED(); });
}

TEST(ServerOptions_test, ComparisonOperatorReturnsTrueWhenEqual)
{
    ::testing::Test::RecordProperty("TEST_ID", "98e68269-94d0-41bb-b8a8-5b06ac0b7bc0");
    ServerOptions options1;
    ServerOptions options2;

    EXPECT_TRUE(options1 == options1);
    EXPECT_TRUE(options1 == options2);
    EXPECT_TRUE(options2 == options1);
}

TEST(ServerOptions_test, ComparisonOperatorReturnsFalseWhenRequestQueueCapacityDoesNotMatch)
{
    ::testing::Test::RecordProperty("TEST_ID", "5fede46a-ddfd-426b-a237-25b3088ee011");
    ServerOptions options1;
    options1.requestQueueCapacity = 42;
    ServerOptions options2;
    options2.requestQueueCapacity = 73;

    EXPECT_FALSE(options1 == options2);
    EXPECT_FALSE(options2 == options1);
}

TEST(ServerOptions_test, ComparisonOperatorReturnsFalseWhenNodeNameDoesNotMatch)
{
    ::testing::Test::RecordProperty("TEST_ID", "fed82e4a-5037-4a77-9b28-e0ca8ec7ad5d");
    ServerOptions options1;
    options1.nodeName = "kirk";
    ServerOptions options2;
    options2.nodeName = "picard";

    EXPECT_FALSE(options1 == options2);
    EXPECT_FALSE(options2 == options1);
}

TEST(ServerOptions_test, ComparisonOperatorReturnsFalseWhenOfferOnCreateDoesNotMatch)
{
    ::testing::Test::RecordProperty("TEST_ID", "7831b7c7-72b1-4acf-8a95-fd7ee2348835");
    ServerOptions options1;
    options1.offerOnCreate = false;
    ServerOptions options2;
    options2.offerOnCreate = true;

    EXPECT_FALSE(options1 == options2);
    EXPECT_FALSE(options2 == options1);
}

TEST(ServerOptions_test, ComparisonOperatorReturnsFalseRequestQueueFullPolicyDoesNotMatch)
{
    ::testing::Test::RecordProperty("TEST_ID", "cc97e01c-94f7-41a9-8fac-19db1fd2d20e");
    ServerOptions options1;
    options1.requestQueueFullPolicy = QueueFullPolicy::BLOCK_PRODUCER;
    ServerOptions options2;
    options2.requestQueueFullPolicy = QueueFullPolicy::DISCARD_OLDEST_DATA;

    EXPECT_FALSE(options1 == options2);
    EXPECT_FALSE(options2 == options1);
}

TEST(ServerOptions_test, ComparisonOperatorReturnsFalseClientTooSlowPolicyDoesNotMatch)
{
    ::testing::Test::RecordProperty("TEST_ID", "80c7e7a3-084c-48e1-aa3c-d51688c41682");
    ServerOptions options1;
    options1.clientTooSlowPolicy = ConsumerTooSlowPolicy::WAIT_FOR_CONSUMER;
    ServerOptions options2;
    options2.clientTooSlowPolicy = ConsumerTooSlowPolicy::DISCARD_OLDEST_DATA;

    EXPECT_FALSE(options1 == options2);
    EXPECT_FALSE(options2 == options1);
}

} // namespace
<|endoftext|>


<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/app/chrome_dll_resource.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_layout_test.h"
#include "chrome/test/ui_test_utils.h"
#include "net/base/escape.h"
#include "net/test/test_server.h"

struct IsSearchProviderTestData;

class SearchProviderTest : public UITest {
 protected:
  SearchProviderTest();

  IsSearchProviderTestData StartIsSearchProviderInstalledTest(
      BrowserProxy* browser_proxy,
      const char* host,
      const char* expected_result);

  void FinishIsSearchProviderInstalledTest(
      const IsSearchProviderTestData& data);

  net::TestServer test_server_;

 private:
  DISALLOW_COPY_AND_ASSIGN(SearchProviderTest);
};

SearchProviderTest::SearchProviderTest()
    : test_server_(net::TestServer::TYPE_HTTP,
                   FilePath(FILE_PATH_LITERAL("chrome/test/data"))) {
  // Enable the search provider additions.
  launch_arguments_.AppendSwitch(switches::kEnableSearchProviderApiV2);

  // Map all hosts to our local server.
  std::string host_rule("MAP * " + test_server_.host_port_pair().ToString());
  launch_arguments_.AppendSwitchASCII(switches::kHostRules, host_rule);
}

struct IsSearchProviderTestData {
  IsSearchProviderTestData() {
  }

  IsSearchProviderTestData(TabProxy* t,
                           std::string h,
                           GURL url)
      : tab(t),
        host(h),
        test_url(url) {
  }

  scoped_refptr<TabProxy> tab;
  std::string host;
  GURL test_url;
};

IsSearchProviderTestData SearchProviderTest::StartIsSearchProviderInstalledTest(
    BrowserProxy* browser_proxy,
    const char* host,
    const char* expected_result) {
  // Set-up a new tab for the navigation.
  int num_tabs = 0;
  if (!browser_proxy->GetTabCount(&num_tabs)) {
    ADD_FAILURE() << "BrowserProxy::GetTabCount failed.";
    return IsSearchProviderTestData();
  }

  GURL blank(chrome::kAboutBlankURL);
  if (!browser_proxy->AppendTab(blank)) {
    ADD_FAILURE() << "BrowserProxy::AppendTab failed.";
    return IsSearchProviderTestData();
  }

  scoped_refptr<TabProxy> tab(browser_proxy->GetTab(num_tabs));
  if (!tab.get()) {
    ADD_FAILURE() << "BrowserProxy::GetTab for the new tab failed.";
    return IsSearchProviderTestData();
  }

  // Go to the test page.
  GURL local_url =
      test_server_.GetURL("files/is_search_provider_installed.html");
  GURL test_url(std::string("http://") + host + local_url.path() +
                "#" + expected_result);
  EXPECT_TRUE(tab->NavigateToURLAsync(test_url));

  // Bundle up information needed to verify the result.
  return IsSearchProviderTestData(tab, host, test_url);
}

void SearchProviderTest::FinishIsSearchProviderInstalledTest(
    const IsSearchProviderTestData& data) {
  ASSERT_TRUE(data.tab.get());

  std::string cookie_name = data.host + "testResult";
  std::string escaped_value =
      WaitUntilCookieNonEmpty(data.tab, data.test_url,
                              cookie_name.c_str(), action_max_timeout_ms());

  // Unescapes and normalizes the actual result.
  std::string value = UnescapeURLComponent(
      escaped_value,
      UnescapeRule::NORMAL | UnescapeRule::SPACES |
      UnescapeRule::URL_SPECIAL_CHARS | UnescapeRule::CONTROL_CHARS);
  value += "\n";
  ReplaceSubstringsAfterOffset(&value, 0, "\r", "");
  EXPECT_STREQ("1\n", value.c_str());
}

TEST_F(SearchProviderTest, TestIsSearchProviderInstalled) {
  ASSERT_TRUE(test_server_.Start());

  // Use the default search provider, other installed search provider, and
  // one not installed as well. (Note that yahoo isn't tested because the
  // its host name varies a lot for different locales unlike Google and Bing,
  // which would make the test fail depending on the machine's locale.)
  const char* test_hosts[] = { "www.google.com",
                               "www.bing.com",
                               "localhost" };
  const char* expected_results[] = { "2",
                                     "1",
                                     "0" };
  COMPILE_ASSERT(arraysize(test_hosts) == arraysize(expected_results),
                 there_should_be_a_result_for_each_host);
  IsSearchProviderTestData test_data[2 * arraysize(test_hosts)];

  // Start results for the normal mode.
  scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
  ASSERT_TRUE(browser.get());
  for (size_t i = 0; i < arraysize(test_hosts); ++i) {
    test_data[i] = StartIsSearchProviderInstalledTest(
        browser, test_hosts[i], expected_results[i]);
  }

  // Start tests for incognito mode (and verify the result is 0).
  ASSERT_TRUE(browser->RunCommand(IDC_NEW_INCOGNITO_WINDOW));
  scoped_refptr<BrowserProxy> incognito(automation()->GetBrowserWindow(1));
  ASSERT_TRUE(incognito.get());
  for (size_t i = 0; i < arraysize(test_hosts); ++i) {
    test_data[i + arraysize(test_hosts)] = StartIsSearchProviderInstalledTest(
        incognito, test_hosts[i], "0");
  }

  // Do the verification.
  for (size_t i = 0; i < arraysize(test_data); ++i) {
    FinishIsSearchProviderInstalledTest(test_data[i]);
  }
}
<commit_msg>Mark SearchProviderTest.TestIsSearchProviderInstalled as flaky.<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/app/chrome_dll_resource.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_layout_test.h"
#include "chrome/test/ui_test_utils.h"
#include "net/base/escape.h"
#include "net/test/test_server.h"

struct IsSearchProviderTestData;

class SearchProviderTest : public UITest {
 protected:
  SearchProviderTest();

  IsSearchProviderTestData StartIsSearchProviderInstalledTest(
      BrowserProxy* browser_proxy,
      const char* host,
      const char* expected_result);

  void FinishIsSearchProviderInstalledTest(
      const IsSearchProviderTestData& data);

  net::TestServer test_server_;

 private:
  DISALLOW_COPY_AND_ASSIGN(SearchProviderTest);
};

SearchProviderTest::SearchProviderTest()
    : test_server_(net::TestServer::TYPE_HTTP,
                   FilePath(FILE_PATH_LITERAL("chrome/test/data"))) {
  // Enable the search provider additions.
  launch_arguments_.AppendSwitch(switches::kEnableSearchProviderApiV2);

  // Map all hosts to our local server.
  std::string host_rule("MAP * " + test_server_.host_port_pair().ToString());
  launch_arguments_.AppendSwitchASCII(switches::kHostRules, host_rule);
}

struct IsSearchProviderTestData {
  IsSearchProviderTestData() {
  }

  IsSearchProviderTestData(TabProxy* t,
                           std::string h,
                           GURL url)
      : tab(t),
        host(h),
        test_url(url) {
  }

  scoped_refptr<TabProxy> tab;
  std::string host;
  GURL test_url;
};

IsSearchProviderTestData SearchProviderTest::StartIsSearchProviderInstalledTest(
    BrowserProxy* browser_proxy,
    const char* host,
    const char* expected_result) {
  // Set-up a new tab for the navigation.
  int num_tabs = 0;
  if (!browser_proxy->GetTabCount(&num_tabs)) {
    ADD_FAILURE() << "BrowserProxy::GetTabCount failed.";
    return IsSearchProviderTestData();
  }

  GURL blank(chrome::kAboutBlankURL);
  if (!browser_proxy->AppendTab(blank)) {
    ADD_FAILURE() << "BrowserProxy::AppendTab failed.";
    return IsSearchProviderTestData();
  }

  scoped_refptr<TabProxy> tab(browser_proxy->GetTab(num_tabs));
  if (!tab.get()) {
    ADD_FAILURE() << "BrowserProxy::GetTab for the new tab failed.";
    return IsSearchProviderTestData();
  }

  // Go to the test page.
  GURL local_url =
      test_server_.GetURL("files/is_search_provider_installed.html");
  GURL test_url(std::string("http://") + host + local_url.path() +
                "#" + expected_result);
  EXPECT_TRUE(tab->NavigateToURLAsync(test_url));

  // Bundle up information needed to verify the result.
  return IsSearchProviderTestData(tab, host, test_url);
}

void SearchProviderTest::FinishIsSearchProviderInstalledTest(
    const IsSearchProviderTestData& data) {
  ASSERT_TRUE(data.tab.get());

  std::string cookie_name = data.host + "testResult";
  std::string escaped_value =
      WaitUntilCookieNonEmpty(data.tab, data.test_url,
                              cookie_name.c_str(), action_max_timeout_ms());

  // Unescapes and normalizes the actual result.
  std::string value = UnescapeURLComponent(
      escaped_value,
      UnescapeRule::NORMAL | UnescapeRule::SPACES |
      UnescapeRule::URL_SPECIAL_CHARS | UnescapeRule::CONTROL_CHARS);
  value += "\n";
  ReplaceSubstringsAfterOffset(&value, 0, "\r", "");
  EXPECT_STREQ("1\n", value.c_str());
}

// Flaky, http://crbug.com/57405.
TEST_F(SearchProviderTest, FLAKY_TestIsSearchProviderInstalled) {
  ASSERT_TRUE(test_server_.Start());

  // Use the default search provider, other installed search provider, and
  // one not installed as well. (Note that yahoo isn't tested because the
  // its host name varies a lot for different locales unlike Google and Bing,
  // which would make the test fail depending on the machine's locale.)
  const char* test_hosts[] = { "www.google.com",
                               "www.bing.com",
                               "localhost" };
  const char* expected_results[] = { "2",
                                     "1",
                                     "0" };
  COMPILE_ASSERT(arraysize(test_hosts) == arraysize(expected_results),
                 there_should_be_a_result_for_each_host);
  IsSearchProviderTestData test_data[2 * arraysize(test_hosts)];

  // Start results for the normal mode.
  scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
  ASSERT_TRUE(browser.get());
  for (size_t i = 0; i < arraysize(test_hosts); ++i) {
    test_data[i] = StartIsSearchProviderInstalledTest(
        browser, test_hosts[i], expected_results[i]);
  }

  // Start tests for incognito mode (and verify the result is 0).
  ASSERT_TRUE(browser->RunCommand(IDC_NEW_INCOGNITO_WINDOW));
  scoped_refptr<BrowserProxy> incognito(automation()->GetBrowserWindow(1));
  ASSERT_TRUE(incognito.get());
  for (size_t i = 0; i < arraysize(test_hosts); ++i) {
    test_data[i + arraysize(test_hosts)] = StartIsSearchProviderInstalledTest(
        incognito, test_hosts[i], "0");
  }

  // Do the verification.
  for (size_t i = 0; i < arraysize(test_data); ++i) {
    FinishIsSearchProviderInstalledTest(test_data[i]);
  }
}
<|endoftext|>


<commit_before>/* $Id: middlewareGeneralTests.cpp,v 1.1.2.7 2013/02/01 17:26:58 matthewmulhern Exp $
 *
 * OpenMAMA: The open middleware agnostic messaging API
 * Copyright (C) 2011 NYSE Technologies, Inc.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301 USA
 */

#include <gtest/gtest.h>
#include "mama/mama.h"
#include "MainUnitTestC.h"
#include <iostream>
#include "bridge.h"
#include "mama/types.h"

using std::cout;
using std::endl;

class MiddlewareGeneralTests : public ::testing::Test
{
protected:
    MiddlewareGeneralTests(void);
    virtual ~MiddlewareGeneralTests(void);

    virtual void SetUp(void);
    virtual void TearDown(void);

    mamaBridge mBridge;
};

MiddlewareGeneralTests::MiddlewareGeneralTests(void)
{
}

MiddlewareGeneralTests::~MiddlewareGeneralTests(void)
{
}

void MiddlewareGeneralTests::SetUp(void)
{
	mama_loadBridge (&mBridge,getMiddleware());
}

void MiddlewareGeneralTests::TearDown(void)
{
}

/*===================================================================
 =                      Used in mama.c                              =
 ====================================================================*/
TEST_F (MiddlewareGeneralTests, open)
{
    ASSERT_EQ (MAMA_STATUS_OK, mBridge->bridgeOpen(mBridge));
}
TEST_F (MiddlewareGeneralTests, openInvalid)
{
    ASSERT_EQ (MAMA_STATUS_NULL_ARG, mBridge->bridgeOpen(NULL));
}

TEST_F (MiddlewareGeneralTests, DISABLED_openClose)
/*calling bridgeClose in this test causes next test to seg fault always*/
{
    ASSERT_EQ (MAMA_STATUS_OK, mBridge->bridgeOpen(mBridge));
    ASSERT_EQ (MAMA_STATUS_OK, mBridge->bridgeClose(mBridge));
}

TEST_F (MiddlewareGeneralTests, closeInvalid)
{
    ASSERT_EQ (MAMA_STATUS_NULL_ARG, mBridge->bridgeClose(NULL));
}

TEST_F (MiddlewareGeneralTests, DISABLED_startStop)
/* hangs, bridgeClose never executed */
/* MH - Seems to be an issue in wSemaphore.c with the sem_timedwait() function */
{
    mamaQueue defaultEventQueue = NULL;

    ASSERT_EQ (MAMA_STATUS_OK,
               mama_getDefaultEventQueue(mBridge, &defaultEventQueue));

    ASSERT_EQ (MAMA_STATUS_OK,
               mBridge->bridgeStart(defaultEventQueue));

    ASSERT_EQ (MAMA_STATUS_OK,
               mBridge->bridgeStop(defaultEventQueue));
}

TEST_F (MiddlewareGeneralTests, startInvalid)
{
    ASSERT_EQ (MAMA_STATUS_NULL_ARG, mBridge->bridgeStart(NULL));
}

TEST_F (MiddlewareGeneralTests, stopInvalid)
{
    ASSERT_EQ (MAMA_STATUS_NULL_ARG, mBridge->bridgeStop(NULL));
}

TEST_F (MiddlewareGeneralTests, getVersion)
{
    const char* res = "0.0";

    res = mBridge->bridgeGetVersion();

	ASSERT_TRUE (res != NULL);
}

TEST_F (MiddlewareGeneralTests, getName)
{
    const char* res = "name";

    res = mBridge->bridgeGetName();

	ASSERT_TRUE (res != NULL);
}

TEST_F (MiddlewareGeneralTests, getDefaultPayloadId)
{
    char** names = {NULL};
    char*  id    = "id";

    ASSERT_EQ (MAMA_STATUS_OK,
               mBridge-> bridgeGetDefaultPayloadId(&names,&id));
}

TEST_F (MiddlewareGeneralTests, getDefaultPayloadIdInvalidName)
{
    char* id = "id";

    ASSERT_EQ (MAMA_STATUS_NULL_ARG,
               mBridge-> bridgeGetDefaultPayloadId(NULL,&id));
}

TEST_F (MiddlewareGeneralTests, getDefaultPayloadIdInvalidId)
{
    char ** names;

    ASSERT_EQ (MAMA_STATUS_NULL_ARG,
               mBridge-> bridgeGetDefaultPayloadId(&names,NULL));
}

<commit_msg>UNIT TESTS: Changes to middleware general tests.<commit_after>/* $Id: middlewareGeneralTests.cpp,v 1.1.2.7 2013/02/01 17:26:58 matthewmulhern Exp $
 *
 * OpenMAMA: The open middleware agnostic messaging API
 * Copyright (C) 2011 NYSE Technologies, Inc.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301 USA
 */

#include <gtest/gtest.h>
#include "mama/mama.h"
#include "MainUnitTestC.h"
#include <iostream>
#include "bridge.h"
#include "mama/types.h"

using std::cout;
using std::endl;

class MiddlewareGeneralTests : public ::testing::Test
{
protected:
    MiddlewareGeneralTests(void);
    virtual ~MiddlewareGeneralTests(void);

    virtual void SetUp(void);
    virtual void TearDown(void);

    mamaBridge mBridge;
};

MiddlewareGeneralTests::MiddlewareGeneralTests(void)
{
}

MiddlewareGeneralTests::~MiddlewareGeneralTests(void)
{
}

void MiddlewareGeneralTests::SetUp(void)
{
	mama_loadBridge (&mBridge,getMiddleware());
}

void MiddlewareGeneralTests::TearDown(void)
{
}

/*===================================================================
 =                      Used in mama.c                              =
 ====================================================================*/
/* TODO: Rewrite this test to call bridgeStart on a separate thread, since it is
 * a blocking call. Otherwise, bridgeStop is never called.
 *
 */
TEST_F (MiddlewareGeneralTests, DISABLED_startStop)
{
    mamaQueue defaultEventQueue = NULL;

    ASSERT_EQ (MAMA_STATUS_OK,
               mama_getDefaultEventQueue(mBridge, &defaultEventQueue));

    ASSERT_EQ (MAMA_STATUS_OK,
               mBridge->bridgeStart(defaultEventQueue));

    ASSERT_EQ (MAMA_STATUS_OK,
               mBridge->bridgeStop(defaultEventQueue));
}

TEST_F (MiddlewareGeneralTests, startInvalid)
{
    ASSERT_EQ (MAMA_STATUS_NULL_ARG, mBridge->bridgeStart(NULL));
}

TEST_F (MiddlewareGeneralTests, stopInvalid)
{
    ASSERT_EQ (MAMA_STATUS_NULL_ARG, mBridge->bridgeStop(NULL));
}

TEST_F (MiddlewareGeneralTests, getVersion)
{
    const char* res = "0.0";

    res = mBridge->bridgeGetVersion();

	ASSERT_TRUE (res != NULL);
}

TEST_F (MiddlewareGeneralTests, getName)
{
    const char* res = "name";

    res = mBridge->bridgeGetName();

	ASSERT_TRUE (res != NULL);
}

TEST_F (MiddlewareGeneralTests, getDefaultPayloadId)
{
    char** names = {NULL};
    char*  id    = "id";

    ASSERT_EQ (MAMA_STATUS_OK,
               mBridge-> bridgeGetDefaultPayloadId(&names,&id));
}

TEST_F (MiddlewareGeneralTests, getDefaultPayloadIdInvalidName)
{
    char* id = "id";

    ASSERT_EQ (MAMA_STATUS_NULL_ARG,
               mBridge-> bridgeGetDefaultPayloadId(NULL,&id));
}

TEST_F (MiddlewareGeneralTests, getDefaultPayloadIdInvalidId)
{
    char ** names;

    ASSERT_EQ (MAMA_STATUS_NULL_ARG,
               mBridge-> bridgeGetDefaultPayloadId(&names,NULL));
}

<|endoftext|>


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

#include "chrome/test/base/test_web_dialog_observer.h"

#include "chrome/test/base/ui_test_utils.h"
#include "content/public/browser/notification_service.h"
#include "content/public/browser/navigation_controller.h"
#include "content/public/browser/notification_details.h"
#include "content/public/browser/notification_source.h"
#include "content/public/browser/notification_types.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_ui.h"
#include "content/public/test/js_injection_ready_observer.h"
#include "content/public/test/test_utils.h"

using content::NavigationController;

TestWebDialogObserver::TestWebDialogObserver(
    content::JsInjectionReadyObserver* js_injection_ready_observer)
    : js_injection_ready_observer_(js_injection_ready_observer),
      web_ui_(NULL),
      done_(false),
      running_(false) {
}

TestWebDialogObserver::~TestWebDialogObserver() {
}

void TestWebDialogObserver::Observe(
    int type,
    const content::NotificationSource& source,
    const content::NotificationDetails& details) {
  switch (type) {
      break;
    case content::NOTIFICATION_LOAD_STOP:
      DCHECK(web_ui_);
      registrar_.Remove(this, content::NOTIFICATION_LOAD_STOP,
                        content::Source<NavigationController>(
                            &web_ui_->GetWebContents()->GetController()));
      done_ = true;
      // If the message loop is running stop it.
      if (running_) {
        running_ = false;
        message_loop_runner_->Quit();
      }
      break;
    default:
      NOTREACHED();
  };
}

void TestWebDialogObserver::OnDialogShown(
      content::WebUI* webui,
      content::RenderViewHost* render_view_host) {
  if (js_injection_ready_observer_) {
    js_injection_ready_observer_->OnJsInjectionReady(render_view_host);
  }
  web_ui_ = webui;
  // Wait for navigation on the new WebUI instance to complete. This depends
  // on receiving the notification of the WebDialog being shown before the
  // NavigationController finishes loading. The WebDialog notification is
  // issued from web_dialog_ui.cc on RenderView creation which results from
  // the call to render_manager_.Navigate in the method
  // WebContents::NavigateToEntry. The new RenderView is later told to
  // navigate in this method, ensuring that this is not a race condition.
  registrar_.Add(this, content::NOTIFICATION_LOAD_STOP,
                 content::Source<NavigationController>(
                     &web_ui_->GetWebContents()->GetController()));
}

content::WebUI* TestWebDialogObserver::GetWebUI() {
  if (!done_) {
    EXPECT_FALSE(running_);
    running_ = true;
    message_loop_runner_ = new content::MessageLoopRunner;
    message_loop_runner_->Run();
  }
  return web_ui_;
}
<commit_msg>chrome: Remove unused include from test_web_dialog_observer.cc<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/test/base/test_web_dialog_observer.h"

#include "base/logging.h"
#include "content/public/browser/notification_service.h"
#include "content/public/browser/navigation_controller.h"
#include "content/public/browser/notification_details.h"
#include "content/public/browser/notification_source.h"
#include "content/public/browser/notification_types.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_ui.h"
#include "content/public/test/js_injection_ready_observer.h"
#include "content/public/test/test_utils.h"

using content::NavigationController;

TestWebDialogObserver::TestWebDialogObserver(
    content::JsInjectionReadyObserver* js_injection_ready_observer)
    : js_injection_ready_observer_(js_injection_ready_observer),
      web_ui_(NULL),
      done_(false),
      running_(false) {
}

TestWebDialogObserver::~TestWebDialogObserver() {
}

void TestWebDialogObserver::Observe(
    int type,
    const content::NotificationSource& source,
    const content::NotificationDetails& details) {
  switch (type) {
      break;
    case content::NOTIFICATION_LOAD_STOP:
      DCHECK(web_ui_);
      registrar_.Remove(this, content::NOTIFICATION_LOAD_STOP,
                        content::Source<NavigationController>(
                            &web_ui_->GetWebContents()->GetController()));
      done_ = true;
      // If the message loop is running stop it.
      if (running_) {
        running_ = false;
        message_loop_runner_->Quit();
      }
      break;
    default:
      NOTREACHED();
  };
}

void TestWebDialogObserver::OnDialogShown(
      content::WebUI* webui,
      content::RenderViewHost* render_view_host) {
  if (js_injection_ready_observer_) {
    js_injection_ready_observer_->OnJsInjectionReady(render_view_host);
  }
  web_ui_ = webui;
  // Wait for navigation on the new WebUI instance to complete. This depends
  // on receiving the notification of the WebDialog being shown before the
  // NavigationController finishes loading. The WebDialog notification is
  // issued from web_dialog_ui.cc on RenderView creation which results from
  // the call to render_manager_.Navigate in the method
  // WebContents::NavigateToEntry. The new RenderView is later told to
  // navigate in this method, ensuring that this is not a race condition.
  registrar_.Add(this, content::NOTIFICATION_LOAD_STOP,
                 content::Source<NavigationController>(
                     &web_ui_->GetWebContents()->GetController()));
}

content::WebUI* TestWebDialogObserver::GetWebUI() {
  if (!done_) {
    DCHECK(running_ == false);
    running_ = true;
    message_loop_runner_ = new content::MessageLoopRunner;
    message_loop_runner_->Run();
  }
  return web_ui_;
}
<|endoftext|>


<commit_before>#include "callback_parameter.hpp"
#include "callback_object.hpp"
#include "cpp/ylikuutio/common/any_value.hpp"
#include "cpp/ylikuutio/hierarchy/hierarchy_templates.hpp"

// Include standard headers
#include <iostream> // std::cout, std::cin, std::cerr
#include <string>   // std::string

namespace callback_system
{
    CallbackParameter::CallbackParameter(std::string name, AnyValue any_value, bool is_reference, callback_system::CallbackObject* parent_pointer)
    {
        // constructor.
        this->name = name;
        this->any_value = any_value;
        this->is_reference = is_reference;
    }

    CallbackParameter::~CallbackParameter()
    {
        // destructor.
        std::cout << "Callback parameter with childID " << this->childID << " will be destroyed.\n";

        // set pointer to this object to nullptr.
        this->parent_pointer->set_callback_parameter_pointer(this->childID, nullptr);
    }

    void CallbackParameter::bind_to_parent()
    {
        callback_system::CallbackObject* parent_pointer;
        parent_pointer = this->parent_pointer;

        std::vector<void*> callback_parameter_void_pointer_vector;
        callback_parameter_void_pointer_vector.assign(parent_pointer->callback_parameter_pointer_vector.begin(), parent_pointer->callback_parameter_pointer_vector.end());
        hierarchy::bind_child_to_parent<callback_system::CallbackParameter*>(this, callback_parameter_void_pointer_vector, parent_pointer->free_callback_parameterID_queue);
    }
}
<commit_msg>`parent_pointer` of each `CallbackParameter` gets set now.<commit_after>#include "callback_parameter.hpp"
#include "callback_object.hpp"
#include "cpp/ylikuutio/common/any_value.hpp"
#include "cpp/ylikuutio/hierarchy/hierarchy_templates.hpp"

// Include standard headers
#include <iostream> // std::cout, std::cin, std::cerr
#include <string>   // std::string

namespace callback_system
{
    CallbackParameter::CallbackParameter(std::string name, AnyValue any_value, bool is_reference, callback_system::CallbackObject* parent_pointer)
    {
        // constructor.
        this->name = name;
        this->any_value = any_value;
        this->is_reference = is_reference;
        this->parent_pointer = parent_pointer;
    }

    CallbackParameter::~CallbackParameter()
    {
        // destructor.
        std::cout << "Callback parameter with childID " << this->childID << " will be destroyed.\n";

        // set pointer to this object to nullptr.
        this->parent_pointer->set_callback_parameter_pointer(this->childID, nullptr);
    }

    void CallbackParameter::bind_to_parent()
    {
        callback_system::CallbackObject* parent_pointer;
        parent_pointer = this->parent_pointer;

        std::vector<void*> callback_parameter_void_pointer_vector;
        callback_parameter_void_pointer_vector.assign(parent_pointer->callback_parameter_pointer_vector.begin(), parent_pointer->callback_parameter_pointer_vector.end());
        hierarchy::bind_child_to_parent<callback_system::CallbackParameter*>(this, callback_parameter_void_pointer_vector, parent_pointer->free_callback_parameterID_queue);
    }
}
<|endoftext|>


<commit_before>// $Id: DCDFile.C,v 1.5 2000/12/20 18:39:02 anker Exp $

#include <BALL/FORMAT/DCDFile.h>
#include <BALL/MOLMEC/COMMON/snapShot.h>

using namespace std;

namespace BALL
{

	DCDFile::DCDFile()
		throw()
		: TrajectoryFile(),
			header_(),
			swap_bytes_(false)
	{
		if (sizeof(int) != 4)
		{
			Log.error() << "DCDFile::DCDFile(): "
				<< "Size of int is not equal to 4 on this machine." << endl;
		}

		if (sizeof(double) != 8)
		{
			Log.error() << "DCDFile::DCDFile(): "
				<< "Size of double is not equal to 4 on this machine." << endl;
		}
	}

	DCDFile::DCDFile(const DCDFile& file)
		throw()
		:	TrajectoryFile(),
			header_(file.header_),
			swap_bytes_(file.swap_bytes_)
	{
		if (sizeof(int) != 4)
		{
			Log.error() << "DCDFile::DCDFile(): "
				<< "Size of int is not equal to 4 on this machine." << endl;
		}

		if (sizeof(double) != 8)
		{
			Log.error() << "DCDFile::DCDFile(): "
				<< "Size of double is not equal to 4 on this machine." << endl;
		}
	}

	DCDFile::DCDFile(const String& name, File::OpenMode open_mode)
		throw()
		: TrajectoryFile(name, open_mode),
			header_(),
			swap_bytes_(false)
	{
		if (sizeof(int) != 4)
		{
			Log.error() << "DCDFile::DCDFile(): "
				<< "Size of int is not equal to 4 on this machine." << endl;
		}

		if (sizeof(double) != 8)
		{
			Log.error() << "DCDFile::DCDFile(): "
				<< "Size of double is not equal to 4 on this machine." << endl;
		}
	}

	DCDFile::~DCDFile()
		throw()
	{
		clear();
	}

	const DCDFile& DCDFile::operator = (const DCDFile& file)
		throw()
	{
		TrajectoryFile::operator = (file);
		header_ = file.header_;

		return *this;
	}

	void DCDFile::clear()
		throw()
	{
		header_ = DCDHeader();
		swap_bytes_ = false;
		TrajectoryFile::clear();
	}

	bool DCDFile::operator == (const DCDFile& file)
		throw()
	{
		// BAUSTELLE: Header vergleichen. Was heit gleich eigentlich in diesem
		// Fall?
		return (TrajectoryFile::operator == (file));
	}

	bool DCDFile::readHeader()
		throw()
	{

		return true;

		/*
		char			fourbytes[4];
		char			eightyfourbytes[84];
		int				tmp_int;

		DCDHeader	tmp_header;

		File::read(fourbytes, 4);
		tmp_int = *((int*)fourbytes);
		if (tmp_int != 84)
		{
			// it might be a problem of endianness, so swap the bytes and test
			// again.
			// tmp_int = swapFourBytes(tmp_int);
			if (tmp_int != 84)
			{
				Log.error() << "DCDFile::readHeader(): "
					<< "file seems corrupted (wrong magic number)" << endl;
				return false;
			}
			else
			{
				// we have to swap bytes...
				// if (verbosity > 1)
				// {
					Log.info() << "DCDFile::readHeader(): enabling byte swap" << endl;
				// }
				swap_bytes_ = true;
			}
		}

		// read this block
		File::read(eightyfourbytes, 84);
		if (swap_bytes_)
		{
			// BAUSTELLE
		}
		else
		{
			// check for "CORD" signature
			if ((eightyfourbytes[0] != 'C') || (eightyfourbytes[1] != 'O')
				|| (eightyfourbytes[2] != 'O') || (eightyfourbytes[3] != 'D'))
			{
				Log.error() << "DCDFile::readHeader() "
					<< "File seems to be corrupted (CORD missing)" << endl;
				return false;
			}
			tmp_header.number_of_coordinate_sets = *((int*)(eightyfourbytes + 4));
			tmp_header.step_number_of_starting_time = *((int*)(eightyfourbytes + 8));
			tmp_header.steps_between_saves = *((int*)(eightyfourbytes + 12));
			tmp_header.time_step_length = *((double*)(eightyfourbytes + 40));

			// check if the block is terminated correctly
			File::read(fourbytes, 4);
			tmp_int = *((int*)fourbytes);
			if (tmp_int != 84)
			{
				Log.error() << "DCDFile::readHeader() "
					<< "File seems to be corrupted (84 bytes incorrectly terninated)"
					<< endl;
				return false;
			}

			// now handle the next block
			File::read(fourbytes, 4);
			tmp_int = *((int*)fourbytes);

			// check if the length of the next block allows n titles of 80 chars
			// length

			int number_of_titles;
			if (((tmp_int - 4) % 80) == 0)
			{
				File::read(fourbytes, 4);
				number_of_titles = *((int*)fourbytes);
				// here we believe that the number stated in the file is correct.
				for (int i = 0; i < number_of_titles; ++i)
				{
					File::read(eightyfourbytes, 80);
					// BAUSTELLE jetzt noch was mit den titeln tun...
				}
			}
			else
			{
				Log.error() << "DCDFile::readHeader() "
					<< "File seems to be corrupted (number of titles wrong)"
					<< endl;
				return false;
			}
			File::read(fourbytes, 4);
			tmp_int = *((int*)fourbytes);

			if (tmp_int != number_of_titles)
			{
				Log.error() << "DCDFile::readHeader(): "
					<< "File seems to be corrupted (title block terminated incorrectly"
					<< endl;
				return false;
			}

			// GROSSBAUSTELLE
		}

		return false;
		*/
	}

	bool DCDFile::updateHeader(const SnapShotManager& manager)
		throw()
	{
		// BAUSTELLE
		header_.number_of_coordinate_sets = manager.getNumberOfSnapShots();
		header_.number_of_atoms = manager.getNumberOfAtoms();
		return true;
	}

	bool DCDFile::writeHeader()
		throw()
	{
		// the following would be nice. Unfortunately the compiler does strange
		// things when storing the struct in memory...
		// *this << BinaryFileAdaptor<struct DCDHeader>(header_);

		Size i;

		*this << BinaryFileAdaptor<Size>(header_.start_info_block);
		for (i = 0; i < 4; ++i)
		{
			*this << BinaryFileAdaptor<char>(header_.CORD[i]);
		}
		*this << BinaryFileAdaptor<Size>(header_.number_of_coordinate_sets);
		*this << BinaryFileAdaptor<Size>(header_.step_number_of_starting_time);
		*this << BinaryFileAdaptor<Size>(header_.steps_between_saves);
		for (i = 0; i < 6; ++i)
		{
			*this << BinaryFileAdaptor<Size>(header_.unused_1[i]);
		}
		*this << BinaryFileAdaptor<DoubleReal>(header_.time_step_length);
		for (i = 0; i < 9; ++i)
		{
			*this << BinaryFileAdaptor<Size>(header_.unused_2[i]);
		}
		*this << BinaryFileAdaptor<Size>(header_.end_info_block);
		*this << BinaryFileAdaptor<Size>(header_.start_title_block);
		*this << BinaryFileAdaptor<Size>(header_.number_of_comments);
		for (i = 0; i < 160; ++i)
		{
			*this << BinaryFileAdaptor<char>(header_.title[i]);
		}
		*this << BinaryFileAdaptor<Size>(header_.end_title_block);
		*this << BinaryFileAdaptor<Size>(header_.start_atomnumber_block);
		*this << BinaryFileAdaptor<Size>(header_.number_of_atoms);
		*this << BinaryFileAdaptor<Size>(header_.end_atomnumber_block);
		return true;
	}

	bool DCDFile::read(SnapShotManager& /* manager */)
		throw(Exception::NotImplemented)
	{
		throw Exception::NotImplemented(__FILE__, __LINE__);
		return false;
	}

	bool DCDFile::write(const SnapShotManager& /* manager */)
		throw(Exception::NotImplemented)
	{
		throw Exception::NotImplemented(__FILE__, __LINE__);
		return false;
	}

	bool DCDFile::append(const SnapShot& snapshot)
		throw()
	{
		Size noa = snapshot.getNumberOfAtoms();
		vector<Vector3> positions = snapshot.getAtomPositions();
		if (positions.size() == 0)
		{
			Log.error() << "DCDFile::append(): "
				<< "No atom positions available" << endl;
			return false;
		}

		*this << BinaryFileAdaptor<Size>(4*noa);
		for (Size atom = 0; atom < noa; ++atom)
		{
			*this << BinaryFileAdaptor<Real>((Real) positions[atom].x);
		}
		*this << BinaryFileAdaptor<Size>(4*noa);
		*this << BinaryFileAdaptor<Size>(4*noa);
		for (Size atom = 0; atom < noa; ++atom)
		{
			*this << BinaryFileAdaptor<Real>((Real) positions[atom].y);
		}
		*this << BinaryFileAdaptor<Size>(4*noa);
		*this << BinaryFileAdaptor<Size>(4*noa);
		for (Size atom = 0; atom < noa; ++atom)
		{
			*this << BinaryFileAdaptor<Real>((Real) positions[atom].z);
		}
		*this << BinaryFileAdaptor<Size>(4*noa);

		return true;
	}

} // namespace BALL
<commit_msg>fixed: compiler warning because of unreachable code<commit_after>// $Id: DCDFile.C,v 1.6 2001/03/02 14:49:49 anker Exp $

#include <BALL/FORMAT/DCDFile.h>
#include <BALL/MOLMEC/COMMON/snapShot.h>

using namespace std;

namespace BALL
{

	DCDFile::DCDFile()
		throw()
		: TrajectoryFile(),
			header_(),
			swap_bytes_(false)
	{
		if (sizeof(int) != 4)
		{
			Log.error() << "DCDFile::DCDFile(): "
				<< "Size of int is not equal to 4 on this machine." << endl;
		}

		if (sizeof(double) != 8)
		{
			Log.error() << "DCDFile::DCDFile(): "
				<< "Size of double is not equal to 4 on this machine." << endl;
		}
	}

	DCDFile::DCDFile(const DCDFile& file)
		throw()
		:	TrajectoryFile(),
			header_(file.header_),
			swap_bytes_(file.swap_bytes_)
	{
		if (sizeof(int) != 4)
		{
			Log.error() << "DCDFile::DCDFile(): "
				<< "Size of int is not equal to 4 on this machine." << endl;
		}

		if (sizeof(double) != 8)
		{
			Log.error() << "DCDFile::DCDFile(): "
				<< "Size of double is not equal to 4 on this machine." << endl;
		}
	}

	DCDFile::DCDFile(const String& name, File::OpenMode open_mode)
		throw()
		: TrajectoryFile(name, open_mode),
			header_(),
			swap_bytes_(false)
	{
		if (sizeof(int) != 4)
		{
			Log.error() << "DCDFile::DCDFile(): "
				<< "Size of int is not equal to 4 on this machine." << endl;
		}

		if (sizeof(double) != 8)
		{
			Log.error() << "DCDFile::DCDFile(): "
				<< "Size of double is not equal to 4 on this machine." << endl;
		}
	}

	DCDFile::~DCDFile()
		throw()
	{
		clear();
	}

	const DCDFile& DCDFile::operator = (const DCDFile& file)
		throw()
	{
		TrajectoryFile::operator = (file);
		header_ = file.header_;

		return *this;
	}

	void DCDFile::clear()
		throw()
	{
		header_ = DCDHeader();
		swap_bytes_ = false;
		TrajectoryFile::clear();
	}

	bool DCDFile::operator == (const DCDFile& file)
		throw()
	{
		// BAUSTELLE: Header vergleichen. Was heit gleich eigentlich in diesem
		// Fall?
		return (TrajectoryFile::operator == (file));
	}

	bool DCDFile::readHeader()
		throw()
	{

		return true;

		/*
		char			fourbytes[4];
		char			eightyfourbytes[84];
		int				tmp_int;

		DCDHeader	tmp_header;

		File::read(fourbytes, 4);
		tmp_int = *((int*)fourbytes);
		if (tmp_int != 84)
		{
			// it might be a problem of endianness, so swap the bytes and test
			// again.
			// tmp_int = swapFourBytes(tmp_int);
			if (tmp_int != 84)
			{
				Log.error() << "DCDFile::readHeader(): "
					<< "file seems corrupted (wrong magic number)" << endl;
				return false;
			}
			else
			{
				// we have to swap bytes...
				// if (verbosity > 1)
				// {
					Log.info() << "DCDFile::readHeader(): enabling byte swap" << endl;
				// }
				swap_bytes_ = true;
			}
		}

		// read this block
		File::read(eightyfourbytes, 84);
		if (swap_bytes_)
		{
			// BAUSTELLE
		}
		else
		{
			// check for "CORD" signature
			if ((eightyfourbytes[0] != 'C') || (eightyfourbytes[1] != 'O')
				|| (eightyfourbytes[2] != 'O') || (eightyfourbytes[3] != 'D'))
			{
				Log.error() << "DCDFile::readHeader() "
					<< "File seems to be corrupted (CORD missing)" << endl;
				return false;
			}
			tmp_header.number_of_coordinate_sets = *((int*)(eightyfourbytes + 4));
			tmp_header.step_number_of_starting_time = *((int*)(eightyfourbytes + 8));
			tmp_header.steps_between_saves = *((int*)(eightyfourbytes + 12));
			tmp_header.time_step_length = *((double*)(eightyfourbytes + 40));

			// check if the block is terminated correctly
			File::read(fourbytes, 4);
			tmp_int = *((int*)fourbytes);
			if (tmp_int != 84)
			{
				Log.error() << "DCDFile::readHeader() "
					<< "File seems to be corrupted (84 bytes incorrectly terninated)"
					<< endl;
				return false;
			}

			// now handle the next block
			File::read(fourbytes, 4);
			tmp_int = *((int*)fourbytes);

			// check if the length of the next block allows n titles of 80 chars
			// length

			int number_of_titles;
			if (((tmp_int - 4) % 80) == 0)
			{
				File::read(fourbytes, 4);
				number_of_titles = *((int*)fourbytes);
				// here we believe that the number stated in the file is correct.
				for (int i = 0; i < number_of_titles; ++i)
				{
					File::read(eightyfourbytes, 80);
					// BAUSTELLE jetzt noch was mit den titeln tun...
				}
			}
			else
			{
				Log.error() << "DCDFile::readHeader() "
					<< "File seems to be corrupted (number of titles wrong)"
					<< endl;
				return false;
			}
			File::read(fourbytes, 4);
			tmp_int = *((int*)fourbytes);

			if (tmp_int != number_of_titles)
			{
				Log.error() << "DCDFile::readHeader(): "
					<< "File seems to be corrupted (title block terminated incorrectly"
					<< endl;
				return false;
			}

			// GROSSBAUSTELLE
		}

		return false;
		*/
	}

	bool DCDFile::updateHeader(const SnapShotManager& manager)
		throw()
	{
		// BAUSTELLE
		header_.number_of_coordinate_sets = manager.getNumberOfSnapShots();
		header_.number_of_atoms = manager.getNumberOfAtoms();
		return true;
	}

	bool DCDFile::writeHeader()
		throw()
	{
		// the following would be nice. Unfortunately the compiler does strange
		// things when storing the struct in memory...
		// *this << BinaryFileAdaptor<struct DCDHeader>(header_);

		Size i;

		*this << BinaryFileAdaptor<Size>(header_.start_info_block);
		for (i = 0; i < 4; ++i)
		{
			*this << BinaryFileAdaptor<char>(header_.CORD[i]);
		}
		*this << BinaryFileAdaptor<Size>(header_.number_of_coordinate_sets);
		*this << BinaryFileAdaptor<Size>(header_.step_number_of_starting_time);
		*this << BinaryFileAdaptor<Size>(header_.steps_between_saves);
		for (i = 0; i < 6; ++i)
		{
			*this << BinaryFileAdaptor<Size>(header_.unused_1[i]);
		}
		*this << BinaryFileAdaptor<DoubleReal>(header_.time_step_length);
		for (i = 0; i < 9; ++i)
		{
			*this << BinaryFileAdaptor<Size>(header_.unused_2[i]);
		}
		*this << BinaryFileAdaptor<Size>(header_.end_info_block);
		*this << BinaryFileAdaptor<Size>(header_.start_title_block);
		*this << BinaryFileAdaptor<Size>(header_.number_of_comments);
		for (i = 0; i < 160; ++i)
		{
			*this << BinaryFileAdaptor<char>(header_.title[i]);
		}
		*this << BinaryFileAdaptor<Size>(header_.end_title_block);
		*this << BinaryFileAdaptor<Size>(header_.start_atomnumber_block);
		*this << BinaryFileAdaptor<Size>(header_.number_of_atoms);
		*this << BinaryFileAdaptor<Size>(header_.end_atomnumber_block);
		return true;
	}

	bool DCDFile::read(SnapShotManager& /* manager */)
		throw(Exception::NotImplemented)
	{
		throw Exception::NotImplemented(__FILE__, __LINE__);
	}

	bool DCDFile::write(const SnapShotManager& /* manager */)
		throw(Exception::NotImplemented)
	{
		throw Exception::NotImplemented(__FILE__, __LINE__);
	}

	bool DCDFile::append(const SnapShot& snapshot)
		throw()
	{
		Size noa = snapshot.getNumberOfAtoms();
		vector<Vector3> positions = snapshot.getAtomPositions();
		if (positions.size() == 0)
		{
			Log.error() << "DCDFile::append(): "
				<< "No atom positions available" << endl;
			return false;
		}

		*this << BinaryFileAdaptor<Size>(4*noa);
		for (Size atom = 0; atom < noa; ++atom)
		{
			*this << BinaryFileAdaptor<Real>((Real) positions[atom].x);
		}
		*this << BinaryFileAdaptor<Size>(4*noa);
		*this << BinaryFileAdaptor<Size>(4*noa);
		for (Size atom = 0; atom < noa; ++atom)
		{
			*this << BinaryFileAdaptor<Real>((Real) positions[atom].y);
		}
		*this << BinaryFileAdaptor<Size>(4*noa);
		*this << BinaryFileAdaptor<Size>(4*noa);
		for (Size atom = 0; atom < noa; ++atom)
		{
			*this << BinaryFileAdaptor<Real>((Real) positions[atom].z);
		}
		*this << BinaryFileAdaptor<Size>(4*noa);

		return true;
	}

} // namespace BALL
<|endoftext|>


<commit_before>#include <QChildEvent>
#include "ButtonItem.h"
#include "LayoutItem.h"
#include "ModeItem.h"

ModeItem::ModeItem(QQuickItem *parent):
	QQuickItem(parent),
	m_layout(0)
{
	setVisible(false);
	setLayout(new LayoutItem());
}

ModeItem::~ModeItem()
{
}

LayoutItem *ModeItem::layout() const
{
	return m_layout;
}

void ModeItem::setLayout(LayoutItem *layout)
{
	if (m_layout == layout) {
		return;
	}

	if (m_layout) {
		m_layout->setParentItem(0);
		delete m_layout;
	}

	if (layout) {
		layout->setParentItem(this);
		foreach (ButtonItem *button, m_buttons) {
			m_layout->addButton(button);
		}
		layout->property("anchors").value<QObject *>()->setProperty("fill", QVariant::fromValue<QQuickItem *>(this));
	}
	m_layout = layout;
}

QQmlListProperty<ButtonItem> ModeItem::buttons()
{
	return QQmlListProperty<ButtonItem>(
		this,
		&m_buttons,
		&ModeItem::buttons_append,
		&ModeItem::buttons_count,
		&ModeItem::buttons_at,
		&ModeItem::buttons_clear
	);
}

void ModeItem::buttons_append(QQmlListProperty<ButtonItem> *property, ButtonItem *button)
{
	ModeItem *that = static_cast<ModeItem *>(property->object);
	button->setParentItem(that);
	that->m_buttons.append(button);
	if (that->m_layout) {
		that->m_layout->addButton(button);
	}
	QObject::connect(button, SIGNAL(symbolTriggered(const QString &)), that, SLOT(onSymbolTriggered(const QString &)));
}

int ModeItem::buttons_count(QQmlListProperty<ButtonItem> *property)
{
	ModeItem *that = static_cast<ModeItem *>(property->object);
	return that->m_buttons.count();
}

ButtonItem *ModeItem::buttons_at(QQmlListProperty<ButtonItem> *property, int idx)
{
	ModeItem *that = static_cast<ModeItem *>(property->object);
	return that->m_buttons.value(idx, 0);
}

void ModeItem::buttons_clear(QQmlListProperty<ButtonItem> *property)
{
	ModeItem *that = static_cast<ModeItem *>(property->object);
	if (that->m_layout) {
		that->m_layout->clearButtons();
	}
	foreach (ButtonItem *button, that->m_buttons) {
		QObject::disconnect(button, SIGNAL(symbolTriggered(const QString &)), that, SLOT(onSymbolTriggered(const QString &)));
		button->setParentItem(0);
	}
	that->m_buttons.clear();
}

void ModeItem::onSymbolTriggered(const QString &symbol)
{
}

<commit_msg>Changed default layout to GridLayout.<commit_after>#include <QChildEvent>
#include "ButtonItem.h"
#include "GridLayoutItem.h"
#include "ModeItem.h"

ModeItem::ModeItem(QQuickItem *parent):
	QQuickItem(parent),
	m_layout(0)
{
	setVisible(false);
	setLayout(new GridLayoutItem());
}

ModeItem::~ModeItem()
{
}

LayoutItem *ModeItem::layout() const
{
	return m_layout;
}

void ModeItem::setLayout(LayoutItem *layout)
{
	if (m_layout == layout) {
		return;
	}

	if (m_layout) {
		m_layout->setParentItem(0);
		delete m_layout;
	}

	if (layout) {
		layout->setParentItem(this);
		foreach (ButtonItem *button, m_buttons) {
			m_layout->addButton(button);
		}
		layout->property("anchors").value<QObject *>()->setProperty("fill", QVariant::fromValue<QQuickItem *>(this));
	}
	m_layout = layout;
}

QQmlListProperty<ButtonItem> ModeItem::buttons()
{
	return QQmlListProperty<ButtonItem>(
		this,
		&m_buttons,
		&ModeItem::buttons_append,
		&ModeItem::buttons_count,
		&ModeItem::buttons_at,
		&ModeItem::buttons_clear
	);
}

void ModeItem::buttons_append(QQmlListProperty<ButtonItem> *property, ButtonItem *button)
{
	ModeItem *that = static_cast<ModeItem *>(property->object);
	button->setParentItem(that);
	that->m_buttons.append(button);
	if (that->m_layout) {
		that->m_layout->addButton(button);
	}
	QObject::connect(button, SIGNAL(symbolTriggered(const QString &)), that, SLOT(onSymbolTriggered(const QString &)));
}

int ModeItem::buttons_count(QQmlListProperty<ButtonItem> *property)
{
	ModeItem *that = static_cast<ModeItem *>(property->object);
	return that->m_buttons.count();
}

ButtonItem *ModeItem::buttons_at(QQmlListProperty<ButtonItem> *property, int idx)
{
	ModeItem *that = static_cast<ModeItem *>(property->object);
	return that->m_buttons.value(idx, 0);
}

void ModeItem::buttons_clear(QQmlListProperty<ButtonItem> *property)
{
	ModeItem *that = static_cast<ModeItem *>(property->object);
	if (that->m_layout) {
		that->m_layout->clearButtons();
	}
	foreach (ButtonItem *button, that->m_buttons) {
		QObject::disconnect(button, SIGNAL(symbolTriggered(const QString &)), that, SLOT(onSymbolTriggered(const QString &)));
		button->setParentItem(0);
	}
	that->m_buttons.clear();
}

void ModeItem::onSymbolTriggered(const QString &symbol)
{
}

<|endoftext|>


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

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_desktop.hxx"

#include "configinit.hxx"

#include "desktop.hrc"
#include "app.hxx"

#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif
#include <uno/current_context.hxx>
#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif
#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
#include <stdio.h>
#include <map>

#ifndef _COM_SUN_STAR_LANG_SERVICENOTREGISTEREDEXCEPTION_HPP_
#include <com/sun/star/lang/ServiceNotRegisteredException.hpp>
#endif
#include <com/sun/star/configuration/CannotLoadConfigurationException.hpp>
#include <com/sun/star/configuration/InvalidBootstrapFileException.hpp>
#include <com/sun/star/configuration/backend/BackendSetupException.hpp>
#include <com/sun/star/configuration/backend/CannotConnectException.hpp>

// ----------------------------------------------------------------------------

namespace uno           = ::com::sun::star::uno;
namespace lang          = ::com::sun::star::lang;
namespace configuration = ::com::sun::star::configuration;
namespace backend       = ::com::sun::star::configuration::backend;
using rtl::OUString;
using uno::UNO_QUERY;
using desktop::Desktop;

// ----------------------------------------------------------------------------
static char const CONFIGURATION_PROVIDER[]  = "com.sun.star.configuration.ConfigurationProvider";

static char const CONFIGURATION_ERROR_HANDLER[]  = "com.sun.star.configuration.backend.InteractionHandler";

// must be aligned with configmgr/source/misc/configinteractionhandler
static char const CONFIG_ERROR_HANDLER[] = "configuration.interaction-handler";
// ----------------------------------------------------------------------------

// ----------------------------------------------------------------------------
#define arraysize( arr ) ( sizeof (arr)/sizeof *(arr) )

typedef uno::Reference< lang::XMultiServiceFactory > ConfigurationProvider;

#define OUSTRING( constascii ) OUString( RTL_CONSTASCII_USTRINGPARAM( constascii ) )

#define OU2O( ustr, enc ) rtl::OUStringToOString( (ustr), RTL_TEXTENCODING_ ## enc )

#define k_PROVIDER OUSTRING( CONFIGURATION_PROVIDER )
#define k_ERRORHANDLER OUSTRING( CONFIGURATION_ERROR_HANDLER )
// ----------------------------------------------------------------------------
// Get a message string securely. There is a fallback string if the resource
// is not available. Adapted from Desktop::GetMsgString()

OUString getMsgString( USHORT nId, char const * aFallBackMsg )
{
    ResMgr* pResMgr = Desktop::GetDesktopResManager();
    if ( !pResMgr || !nId )
        return OUString::createFromAscii(aFallBackMsg);
    else
        return OUString( String(ResId( nId, pResMgr )));
}
// ----------------------------------------------------------------------------
/** Creates the normal configuration provider.

*/
static
ConfigurationProvider createDefaultConfigurationProvider( )
{
    uno::Reference< lang::XMultiServiceFactory > xServiceManager = ::comphelper::getProcessServiceFactory();

    OSL_ENSURE( xServiceManager.is(),"No ServiceManager set for CreateApplicationConfigurationProvider");

    ConfigurationProvider xProvider;

    if (xServiceManager.is())
    {

            xProvider.set( xServiceManager->createInstance(k_PROVIDER),  UNO_QUERY);
    }

    if (!xProvider.is())
    {
        OUString const sMsg = OUSTRING("Service \"") + k_PROVIDER +
                                OUSTRING("\" is not available at the service manager.");

        throw lang::ServiceNotRegisteredException(sMsg, xServiceManager);
    }

    return xProvider;
}
// ----------------------------------------------------------------------------
/// @attention this method must be called from a catch statement!
static void handleGeneralException(uno::Exception& aException,
                                   const rtl::OUString& aMessage)
{
    aException.Message = aMessage ;
    throw ;
}
// ----------------------------------------------------------------------------

uno::Reference< lang::XMultiServiceFactory > CreateApplicationConfigurationProvider( )
{
    uno::Reference< lang::XMultiServiceFactory > xProvider;

    try
    {
        xProvider = createDefaultConfigurationProvider( );
    }
    catch (configuration::InvalidBootstrapFileException & exception)
    {
        handleGeneralException(exception,
                getMsgString( STR_CONFIG_ERR_SETTINGS_INCOMPLETE,
                            "The startup settings for your configuration settings are incomplete. "));
    }
     catch (backend::CannotConnectException & exception)
    {
        handleGeneralException(exception,
                getMsgString( STR_CONFIG_ERR_CANNOT_CONNECT,
                            "A connection to your configuration settings could not be established. "));
    }
    catch (backend::BackendSetupException & exception)
    {
        handleGeneralException(exception,
                getMsgString( STR_CONFIG_ERR_CANNOT_CONNECT,
                            "A connection to your configuration settings could not be established. "));
    }
    catch (configuration::CannotLoadConfigurationException & exception)
    {
        handleGeneralException(exception,
                getMsgString( STR_CONFIG_ERR_CANNOT_CONNECT,
                            "A connection to your configuration settings could not be established. "));
    }
    catch (uno::Exception & exception)
    {
        handleGeneralException(exception,
                getMsgString( STR_CONFIG_ERR_ACCESS_GENERAL,
                            "A general error occurred while accessing your configuration settings."));
    }

    return xProvider ;
}
// ----------------------------------------------------------------------------

// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ConfigurationErrorHandler
// ----------------------------------------------------------------------------

namespace
{
    typedef uno::Reference< uno::XCurrentContext > CurrentContext;
    class SimpleCurrentContext : public cppu::WeakImplHelper1< uno::XCurrentContext >
    {
        CurrentContext m_xChainedContext;
    public:
        explicit
        SimpleCurrentContext(const CurrentContext & xChainedContext)
        : m_xChainedContext(xChainedContext)
        {}

        void install()      { uno::setCurrentContext(this); }
        void deinstall()    { uno::setCurrentContext(m_xChainedContext); }

        uno::Any getChainedValueByName( OUString const & aName) const
        {
            return m_xChainedContext.is()
                            ? m_xChainedContext->getValueByName(aName)
                            : uno::Any();
        }

        // XCurrentContext
        virtual uno::Any SAL_CALL
            getValueByName( OUString const & aName)
                throw (uno::RuntimeException);
    };

    uno::Any SAL_CALL
        SimpleCurrentContext::getValueByName( OUString const & aName)
            throw (uno::RuntimeException)
    {
        return getChainedValueByName(aName);
    }

}

// ----------------------------------------------------------------------------
class ConfigurationErrorHandler::Context : public SimpleCurrentContext
{
public:
    Context()
    : SimpleCurrentContext( uno::getCurrentContext() )
    {
    }

    ~Context()
    {
    }

    // XCurrentContext
    virtual uno::Any SAL_CALL
        getValueByName( OUString const & aName)
            throw (uno::RuntimeException);

private:
    InteractionHandler  m_xHandler;
};

//------------------------------------------------------------------------------
uno::Any SAL_CALL ConfigurationErrorHandler::Context::getValueByName( OUString const & aName)
        throw (uno::RuntimeException)
{
    if ( aName.equalsAscii( CONFIG_ERROR_HANDLER ) )
    {
        if ( !m_xHandler.is() )
            m_xHandler = ConfigurationErrorHandler::getDefaultInteractionHandler();
        return uno::Any( m_xHandler );
    }
    return SimpleCurrentContext::getValueByName( aName );
}

//------------------------------------------------------------------------------
ConfigurationErrorHandler::~ConfigurationErrorHandler()
{
    deactivate();
}

//------------------------------------------------------------------------------
/// installs the handler into the current context
void ConfigurationErrorHandler::activate()
{
    if (!m_pContext)
    {
        m_pContext = new Context;
        m_pContext->acquire();
    }
    m_pContext->install();
}

//------------------------------------------------------------------------------
/// deinstalls the handler from the current context, restoring the previous context
void ConfigurationErrorHandler::deactivate()
{
    if (m_pContext)
    {
        m_pContext->deinstall();
        m_pContext->release();
        m_pContext = 0;
    }
}
//------------------------------------------------------------------------------

ConfigurationErrorHandler::InteractionHandler ConfigurationErrorHandler::getDefaultInteractionHandler()
{
    uno::Reference< lang::XMultiServiceFactory > xServiceManager = ::comphelper::getProcessServiceFactory();

    OSL_ENSURE( xServiceManager.is(),"No ServiceManager set for ConfigurationErrorHandler");

    InteractionHandler xHandler;

    if (xServiceManager.is())
    {
        xHandler.set( xServiceManager->createInstance(k_ERRORHANDLER), UNO_QUERY );
    }

    return xHandler;
}
//------------------------------------------------------------------------------

<commit_msg>INTEGRATION: CWS residcleanup (1.13.114); FILE MERGED 2007/02/24 19:59:49 pl 1.13.114.1: #i74635# residcleanup<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: configinit.cxx,v $
 *
 *  $Revision: 1.14 $
 *
 *  last change: $Author: rt $ $Date: 2007-04-26 08:22:20 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_desktop.hxx"

#include "configinit.hxx"

#include "desktop.hrc"
#include "app.hxx"

#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif
#include <uno/current_context.hxx>
#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif
#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
#include <stdio.h>
#include <map>

#ifndef _COM_SUN_STAR_LANG_SERVICENOTREGISTEREDEXCEPTION_HPP_
#include <com/sun/star/lang/ServiceNotRegisteredException.hpp>
#endif
#include <com/sun/star/configuration/CannotLoadConfigurationException.hpp>
#include <com/sun/star/configuration/InvalidBootstrapFileException.hpp>
#include <com/sun/star/configuration/backend/BackendSetupException.hpp>
#include <com/sun/star/configuration/backend/CannotConnectException.hpp>

// ----------------------------------------------------------------------------

namespace uno           = ::com::sun::star::uno;
namespace lang          = ::com::sun::star::lang;
namespace configuration = ::com::sun::star::configuration;
namespace backend       = ::com::sun::star::configuration::backend;
using rtl::OUString;
using uno::UNO_QUERY;
using desktop::Desktop;

// ----------------------------------------------------------------------------
static char const CONFIGURATION_PROVIDER[]  = "com.sun.star.configuration.ConfigurationProvider";

static char const CONFIGURATION_ERROR_HANDLER[]  = "com.sun.star.configuration.backend.InteractionHandler";

// must be aligned with configmgr/source/misc/configinteractionhandler
static char const CONFIG_ERROR_HANDLER[] = "configuration.interaction-handler";
// ----------------------------------------------------------------------------

// ----------------------------------------------------------------------------
#define arraysize( arr ) ( sizeof (arr)/sizeof *(arr) )

typedef uno::Reference< lang::XMultiServiceFactory > ConfigurationProvider;

#define OUSTRING( constascii ) OUString( RTL_CONSTASCII_USTRINGPARAM( constascii ) )

#define OU2O( ustr, enc ) rtl::OUStringToOString( (ustr), RTL_TEXTENCODING_ ## enc )

#define k_PROVIDER OUSTRING( CONFIGURATION_PROVIDER )
#define k_ERRORHANDLER OUSTRING( CONFIGURATION_ERROR_HANDLER )
// ----------------------------------------------------------------------------
// Get a message string securely. There is a fallback string if the resource
// is not available. Adapted from Desktop::GetMsgString()

OUString getMsgString( USHORT nId, char const * aFallBackMsg )
{
    ResMgr* pResMgr = Desktop::GetDesktopResManager();
    if ( !pResMgr || !nId )
        return OUString::createFromAscii(aFallBackMsg);
    else
        return OUString( String(ResId( nId, *pResMgr )));
}
// ----------------------------------------------------------------------------
/** Creates the normal configuration provider.

*/
static
ConfigurationProvider createDefaultConfigurationProvider( )
{
    uno::Reference< lang::XMultiServiceFactory > xServiceManager = ::comphelper::getProcessServiceFactory();

    OSL_ENSURE( xServiceManager.is(),"No ServiceManager set for CreateApplicationConfigurationProvider");

    ConfigurationProvider xProvider;

    if (xServiceManager.is())
    {

            xProvider.set( xServiceManager->createInstance(k_PROVIDER),  UNO_QUERY);
    }

    if (!xProvider.is())
    {
        OUString const sMsg = OUSTRING("Service \"") + k_PROVIDER +
                                OUSTRING("\" is not available at the service manager.");

        throw lang::ServiceNotRegisteredException(sMsg, xServiceManager);
    }

    return xProvider;
}
// ----------------------------------------------------------------------------
/// @attention this method must be called from a catch statement!
static void handleGeneralException(uno::Exception& aException,
                                   const rtl::OUString& aMessage)
{
    aException.Message = aMessage ;
    throw ;
}
// ----------------------------------------------------------------------------

uno::Reference< lang::XMultiServiceFactory > CreateApplicationConfigurationProvider( )
{
    uno::Reference< lang::XMultiServiceFactory > xProvider;

    try
    {
        xProvider = createDefaultConfigurationProvider( );
    }
    catch (configuration::InvalidBootstrapFileException & exception)
    {
        handleGeneralException(exception,
                getMsgString( STR_CONFIG_ERR_SETTINGS_INCOMPLETE,
                            "The startup settings for your configuration settings are incomplete. "));
    }
     catch (backend::CannotConnectException & exception)
    {
        handleGeneralException(exception,
                getMsgString( STR_CONFIG_ERR_CANNOT_CONNECT,
                            "A connection to your configuration settings could not be established. "));
    }
    catch (backend::BackendSetupException & exception)
    {
        handleGeneralException(exception,
                getMsgString( STR_CONFIG_ERR_CANNOT_CONNECT,
                            "A connection to your configuration settings could not be established. "));
    }
    catch (configuration::CannotLoadConfigurationException & exception)
    {
        handleGeneralException(exception,
                getMsgString( STR_CONFIG_ERR_CANNOT_CONNECT,
                            "A connection to your configuration settings could not be established. "));
    }
    catch (uno::Exception & exception)
    {
        handleGeneralException(exception,
                getMsgString( STR_CONFIG_ERR_ACCESS_GENERAL,
                            "A general error occurred while accessing your configuration settings."));
    }

    return xProvider ;
}
// ----------------------------------------------------------------------------

// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ConfigurationErrorHandler
// ----------------------------------------------------------------------------

namespace
{
    typedef uno::Reference< uno::XCurrentContext > CurrentContext;
    class SimpleCurrentContext : public cppu::WeakImplHelper1< uno::XCurrentContext >
    {
        CurrentContext m_xChainedContext;
    public:
        explicit
        SimpleCurrentContext(const CurrentContext & xChainedContext)
        : m_xChainedContext(xChainedContext)
        {}

        void install()      { uno::setCurrentContext(this); }
        void deinstall()    { uno::setCurrentContext(m_xChainedContext); }

        uno::Any getChainedValueByName( OUString const & aName) const
        {
            return m_xChainedContext.is()
                            ? m_xChainedContext->getValueByName(aName)
                            : uno::Any();
        }

        // XCurrentContext
        virtual uno::Any SAL_CALL
            getValueByName( OUString const & aName)
                throw (uno::RuntimeException);
    };

    uno::Any SAL_CALL
        SimpleCurrentContext::getValueByName( OUString const & aName)
            throw (uno::RuntimeException)
    {
        return getChainedValueByName(aName);
    }

}

// ----------------------------------------------------------------------------
class ConfigurationErrorHandler::Context : public SimpleCurrentContext
{
public:
    Context()
    : SimpleCurrentContext( uno::getCurrentContext() )
    {
    }

    ~Context()
    {
    }

    // XCurrentContext
    virtual uno::Any SAL_CALL
        getValueByName( OUString const & aName)
            throw (uno::RuntimeException);

private:
    InteractionHandler  m_xHandler;
};

//------------------------------------------------------------------------------
uno::Any SAL_CALL ConfigurationErrorHandler::Context::getValueByName( OUString const & aName)
        throw (uno::RuntimeException)
{
    if ( aName.equalsAscii( CONFIG_ERROR_HANDLER ) )
    {
        if ( !m_xHandler.is() )
            m_xHandler = ConfigurationErrorHandler::getDefaultInteractionHandler();
        return uno::Any( m_xHandler );
    }
    return SimpleCurrentContext::getValueByName( aName );
}

//------------------------------------------------------------------------------
ConfigurationErrorHandler::~ConfigurationErrorHandler()
{
    deactivate();
}

//------------------------------------------------------------------------------
/// installs the handler into the current context
void ConfigurationErrorHandler::activate()
{
    if (!m_pContext)
    {
        m_pContext = new Context;
        m_pContext->acquire();
    }
    m_pContext->install();
}

//------------------------------------------------------------------------------
/// deinstalls the handler from the current context, restoring the previous context
void ConfigurationErrorHandler::deactivate()
{
    if (m_pContext)
    {
        m_pContext->deinstall();
        m_pContext->release();
        m_pContext = 0;
    }
}
//------------------------------------------------------------------------------

ConfigurationErrorHandler::InteractionHandler ConfigurationErrorHandler::getDefaultInteractionHandler()
{
    uno::Reference< lang::XMultiServiceFactory > xServiceManager = ::comphelper::getProcessServiceFactory();

    OSL_ENSURE( xServiceManager.is(),"No ServiceManager set for ConfigurationErrorHandler");

    InteractionHandler xHandler;

    if (xServiceManager.is())
    {
        xHandler.set( xServiceManager->createInstance(k_ERRORHANDLER), UNO_QUERY );
    }

    return xHandler;
}
//------------------------------------------------------------------------------

<|endoftext|>


<commit_before>#include "t200_thruster.h"
//#include "sub_thruster_library/seabotix_thruster.h"
#include "generic_thruster.h"
#include "sub_trajectory/ThrusterCmd.h"
#include <json/json.h>

#include <ros/ros.h>
#include <std_srvs/Empty.h>
#include <diagnostic_msgs/DiagnosticStatus.h>
#include <diagnostic_msgs/SelfTest.h> //TODO: implement self tests
#include <self_test/self_test.h>

#include <iostream>
#include <fstream>
#include <memory>

inline const std::string BoolToString(const bool b); //http://stackoverflow.com/a/29798

class ThrusterManager {
    ros::NodeHandle nh_;
    ros::Subscriber command_subscriber;
    ros::Publisher diagnostics_output;
    self_test::TestRunner self_test_;

    sub_trajectory::ThrusterCmd savedMsg;

    std::map<int, std::unique_ptr<GenericThruster>> thrusterMap;

    int updateRate;

    ros::ServiceServer initServer;

public:
    ThrusterManager() : self_test_()
    {
        for(int i = 0; i < 8; i++) {
            savedMsg.cmd.push_back(0.0);
        }

        command_subscriber = nh_.subscribe("/thrusters/cmd_vel", 1000, &ThrusterManager::thrusterCb, this);

        diagnostics_output = nh_.advertise<diagnostic_msgs::DiagnosticArray>("/diagnostics", 1000);

        self_test_.add("Test connections", this, &ThrusterManager::testThrusterConnections);

        initServer = nh_.advertiseService("initThrusters", &ThrusterManager::initService, this);

    	nh_.param("/updateRate", updateRate, 30);
    }

    Json::Value loadConfig(std::string filename)
    {
        ifstream configFile(filename);
        if(!configFile.is_open()){
            ROS_ERROR("Thruster controller couldn't open config file");
            //status.summary(diagnostic_msgs::DiagnosticStatus::ERROR, "Config file didn't load");
            Json::Value obj;
            return obj;
        }

        ROS_INFO("Thruster controller config loading");
        Json::Value obj;
        configFile >> obj;
        ROS_INFO("Thruster controller config loaded");
        return obj;
    }
    bool initService(std_srvs::Empty::Request& req, std_srvs::Empty::Response& resp)
    {
        init();
        return true;
    }

    void init()
    {
        thrusterMap.clear();
        Json::Value thrustersJson = loadConfig("config.json")["COMPUTE"];

        savedMsg = sub_trajectory::ThrusterCmd();
        savedMsg.cmd.resize(thrustersJson.size(), 0.0);

        diagnostic_msgs::DiagnosticArray diag;

        for(int i = 0; i < thrustersJson.size(); i++) {
            int thrusterID = thrustersJson[i]["ID"].asInt();
            int thrusterType = thrustersJson[i]["Type"].asInt(); //TODO: support for multiple thruster types
            int thrusterAddress = thrustersJson[i]["Address"].asInt();
            ROS_INFO("Initializing thruster %d", thrusterID);
            try{
                  thrusterMap[i] = std::unique_ptr<GenericThruster>(new T200Thruster(1,thrusterAddress));
            }
            catch(I2CException e){
                //If we get here there's a bus problem
                ROS_ERROR("I2C error while connecting to thruster address %x", thrusterAddress);
                thrusterMap.erase(i);
                //Publish an error message for the diagnostic system to do something about
                diagnostic_msgs::DiagnosticStatus status;
                status.name = "Thrusters";
                status.hardware_id = "Thrusters_"+thrustersJson[i]["Address"].asString();
                status.level = status.ERROR;
                diag.status.push_back(status)
            }
        }
        diagnostics_output.publish(diag);
        ros::spinOnce();
        ROS_INFO("Done initializing thrusters");
    }

    void spin()
    {
        diagnostic_msgs::DiagnosticArray diag;
        ros::Rate rate(updateRate);
        while(ros::ok()) {
            //Publish diagnostic data here
            ROS_DEBUG("Updating thrusters");
            for(auto& iter:thrusterMap)
            {
                diagnostic_msgs::DiagnosticStatus status;
                status.name = "Thrusters";
                status.hardware_id = "Thruster_"+std::to_string(iter.first);
                try {
                    iter.second->updateStatus();
                    iter.second->setVelocityRatio(savedMsg.cmd.at(iter.first));
                } catch(I2CException e) {
                    //Publish an error message for the diagnostic system to do something about
                    status.level = status.ERROR;
                }

                if (thrusterOk(iter.second) && status.level != status.ERROR)
                    status.level = status.OK;
                else
                    status.level = status.ERROR;

                PushDiagData(status, iter.second, std::to_string(iter.first));
                diag.status.push_back(status);
            }

            diagnostics_output.publish(diag);
            ros::spinOnce();
            self_test_.checkTest();
            rate.sleep();
        }
    }

    bool thrusterOk (std::unique_ptr<GenericThruster> & thruster)
    {
        return thruster->isAlive() && thruster->inLimits();
    }

    void PushDiagData(diagnostic_msgs::DiagnosticStatus & statusmsg, std::unique_ptr<GenericThruster> & thruster, std::string thrusterName)
    {
        diagnostic_msgs::KeyValue thrusterValue;

        thrusterValue.key = "Thruster Type";
        thrusterValue.value = thruster->getType();
        statusmsg.values.push_back(thrusterValue);

        thrusterValue.key = thrusterName + " Alive";
        thrusterValue.value = BoolToString(thruster->isAlive());
        statusmsg.values.push_back(thrusterValue);

        thrusterValue.key = thrusterName + " Voltage";
        thrusterValue.value = std::to_string(thruster->getVoltage());
        statusmsg.values.push_back(thrusterValue);

        thrusterValue.key = thrusterName + " Current";
        thrusterValue.value = std::to_string(thruster->getCurrent());
        statusmsg.values.push_back(thrusterValue);

        thrusterValue.key = thrusterName + " Temperature";
        thrusterValue.value = std::to_string(thruster->getTemperature());
        statusmsg.values.push_back(thrusterValue);
    }

    void thrusterCb(const sub_trajectory::ThrusterCmd &msg)
    {
		savedMsg = msg;
    }

    //Self test function
    void testThrusterConnections(diagnostic_updater::DiagnosticStatusWrapper& status)
    {
        self_test_.setID("thrusterController");
        std::stringstream failedThrusters;
        Json::Value& thrustersJson = loadConfig("config.json")["COMPUTE"];
        for(int i = 0; i < thrustersJson.size(); i++)
		{
            int thrusterID = thrustersJson[i]["ID"].asInt();
            int thrusterType = thrustersJson[i]["Type"].asInt(); //TODO: support for multiple thruster types
            int thrusterAddress = thrustersJson[i]["Address"].asInt();

            try{
                T200Thruster(1, thrusterAddress).updateStatus();
            }
            catch(I2CException e){
                failedThrusters << thrusterAddress << " ";
            }
        }

        if(failedThrusters.str().length() > 0){
            status.add("Failures", failedThrusters.str());
            status.summary(diagnostic_msgs::DiagnosticStatus::ERROR, "Thruster couldn't connect");
        } else {
            status.summary(diagnostic_msgs::DiagnosticStatus::OK, "All thrusters OK");
        }
    }
};

int main(int argc, char** argv)
{
    ros::init(argc, argv, "thruster_driver");
    ThrusterManager tc;
    tc.init();
    ROS_INFO("Thruster controller initialized, spinning");
    tc.spin();
    return 0;
}

inline const std::string BoolToString(const bool b)
{
  return b ? "true" : "false";
}
<commit_msg>missing semicolon<commit_after>#include "t200_thruster.h"
//#include "sub_thruster_library/seabotix_thruster.h"
#include "generic_thruster.h"
#include "sub_trajectory/ThrusterCmd.h"
#include <json/json.h>

#include <ros/ros.h>
#include <std_srvs/Empty.h>
#include <diagnostic_msgs/DiagnosticStatus.h>
#include <diagnostic_msgs/SelfTest.h> //TODO: implement self tests
#include <self_test/self_test.h>

#include <iostream>
#include <fstream>
#include <memory>

inline const std::string BoolToString(const bool b); //http://stackoverflow.com/a/29798

class ThrusterManager {
    ros::NodeHandle nh_;
    ros::Subscriber command_subscriber;
    ros::Publisher diagnostics_output;
    self_test::TestRunner self_test_;

    sub_trajectory::ThrusterCmd savedMsg;

    std::map<int, std::unique_ptr<GenericThruster>> thrusterMap;

    int updateRate;

    ros::ServiceServer initServer;

public:
    ThrusterManager() : self_test_()
    {
        for(int i = 0; i < 8; i++) {
            savedMsg.cmd.push_back(0.0);
        }

        command_subscriber = nh_.subscribe("/thrusters/cmd_vel", 1000, &ThrusterManager::thrusterCb, this);

        diagnostics_output = nh_.advertise<diagnostic_msgs::DiagnosticArray>("/diagnostics", 1000);

        self_test_.add("Test connections", this, &ThrusterManager::testThrusterConnections);

        initServer = nh_.advertiseService("initThrusters", &ThrusterManager::initService, this);

    	nh_.param("/updateRate", updateRate, 30);
    }

    Json::Value loadConfig(std::string filename)
    {
        ifstream configFile(filename);
        if(!configFile.is_open()){
            ROS_ERROR("Thruster controller couldn't open config file");
            //status.summary(diagnostic_msgs::DiagnosticStatus::ERROR, "Config file didn't load");
            Json::Value obj;
            return obj;
        }

        ROS_INFO("Thruster controller config loading");
        Json::Value obj;
        configFile >> obj;
        ROS_INFO("Thruster controller config loaded");
        return obj;
    }
    bool initService(std_srvs::Empty::Request& req, std_srvs::Empty::Response& resp)
    {
        init();
        return true;
    }

    void init()
    {
        thrusterMap.clear();
        Json::Value thrustersJson = loadConfig("config.json")["COMPUTE"];

        savedMsg = sub_trajectory::ThrusterCmd();
        savedMsg.cmd.resize(thrustersJson.size(), 0.0);

        diagnostic_msgs::DiagnosticArray diag;

        for(int i = 0; i < thrustersJson.size(); i++) {
            int thrusterID = thrustersJson[i]["ID"].asInt();
            int thrusterType = thrustersJson[i]["Type"].asInt(); //TODO: support for multiple thruster types
            int thrusterAddress = thrustersJson[i]["Address"].asInt();
            ROS_INFO("Initializing thruster %d", thrusterID);
            try{
                  thrusterMap[i] = std::unique_ptr<GenericThruster>(new T200Thruster(1,thrusterAddress));
            }
            catch(I2CException e){
                //If we get here there's a bus problem
                ROS_ERROR("I2C error while connecting to thruster address %x", thrusterAddress);
                thrusterMap.erase(i);
                //Publish an error message for the diagnostic system to do something about
                diagnostic_msgs::DiagnosticStatus status;
                status.name = "Thrusters";
                status.hardware_id = "Thrusters_"+thrustersJson[i]["Address"].asString();
                status.level = status.ERROR;
                diag.status.push_back(status);
            }
        }
        diagnostics_output.publish(diag);
        ros::spinOnce();
        ROS_INFO("Done initializing thrusters");
    }

    void spin()
    {
        diagnostic_msgs::DiagnosticArray diag;
        ros::Rate rate(updateRate);
        while(ros::ok()) {
            //Publish diagnostic data here
            ROS_DEBUG("Updating thrusters");
            for(auto& iter:thrusterMap)
            {
                diagnostic_msgs::DiagnosticStatus status;
                status.name = "Thrusters";
                status.hardware_id = "Thruster_"+std::to_string(iter.first);
                try {
                    iter.second->updateStatus();
                    iter.second->setVelocityRatio(savedMsg.cmd.at(iter.first));
                } catch(I2CException e) {
                    //Publish an error message for the diagnostic system to do something about
                    status.level = status.ERROR;
                }

                if (thrusterOk(iter.second) && status.level != status.ERROR)
                    status.level = status.OK;
                else
                    status.level = status.ERROR;

                PushDiagData(status, iter.second, std::to_string(iter.first));
                diag.status.push_back(status);
            }

            diagnostics_output.publish(diag);
            ros::spinOnce();
            self_test_.checkTest();
            rate.sleep();
        }
    }

    bool thrusterOk (std::unique_ptr<GenericThruster> & thruster)
    {
        return thruster->isAlive() && thruster->inLimits();
    }

    void PushDiagData(diagnostic_msgs::DiagnosticStatus & statusmsg, std::unique_ptr<GenericThruster> & thruster, std::string thrusterName)
    {
        diagnostic_msgs::KeyValue thrusterValue;

        thrusterValue.key = "Thruster Type";
        thrusterValue.value = thruster->getType();
        statusmsg.values.push_back(thrusterValue);

        thrusterValue.key = thrusterName + " Alive";
        thrusterValue.value = BoolToString(thruster->isAlive());
        statusmsg.values.push_back(thrusterValue);

        thrusterValue.key = thrusterName + " Voltage";
        thrusterValue.value = std::to_string(thruster->getVoltage());
        statusmsg.values.push_back(thrusterValue);

        thrusterValue.key = thrusterName + " Current";
        thrusterValue.value = std::to_string(thruster->getCurrent());
        statusmsg.values.push_back(thrusterValue);

        thrusterValue.key = thrusterName + " Temperature";
        thrusterValue.value = std::to_string(thruster->getTemperature());
        statusmsg.values.push_back(thrusterValue);
    }

    void thrusterCb(const sub_trajectory::ThrusterCmd &msg)
    {
		savedMsg = msg;
    }

    //Self test function
    void testThrusterConnections(diagnostic_updater::DiagnosticStatusWrapper& status)
    {
        self_test_.setID("thrusterController");
        std::stringstream failedThrusters;
        Json::Value& thrustersJson = loadConfig("config.json")["COMPUTE"];
        for(int i = 0; i < thrustersJson.size(); i++)
		{
            int thrusterID = thrustersJson[i]["ID"].asInt();
            int thrusterType = thrustersJson[i]["Type"].asInt(); //TODO: support for multiple thruster types
            int thrusterAddress = thrustersJson[i]["Address"].asInt();

            try{
                T200Thruster(1, thrusterAddress).updateStatus();
            }
            catch(I2CException e){
                failedThrusters << thrusterAddress << " ";
            }
        }

        if(failedThrusters.str().length() > 0){
            status.add("Failures", failedThrusters.str());
            status.summary(diagnostic_msgs::DiagnosticStatus::ERROR, "Thruster couldn't connect");
        } else {
            status.summary(diagnostic_msgs::DiagnosticStatus::OK, "All thrusters OK");
        }
    }
};

int main(int argc, char** argv)
{
    ros::init(argc, argv, "thruster_driver");
    ThrusterManager tc;
    tc.init();
    ROS_INFO("Thruster controller initialized, spinning");
    tc.spin();
    return 0;
}

inline const std::string BoolToString(const bool b)
{
  return b ? "true" : "false";
}
<|endoftext|>