<commit_before>/**
 * Simple WASM speed test.
 *
 * Run with:
 * `bazel run --config=libc++ -c opt //test/extensions/bootstrap/wasm:wasm_speed_test`
 */
#include "common/event/dispatcher_impl.h"
#include "common/stats/isolated_store_impl.h"

#include "extensions/common/wasm/wasm.h"

#include "test/mocks/server/mocks.h"
#include "test/mocks/upstream/mocks.h"
#include "test/test_common/environment.h"
#include "test/test_common/utility.h"

#include "absl/types/optional.h"
#include "benchmark/benchmark.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "tools/cpp/runfiles/runfiles.h"

using bazel::tools::cpp::runfiles::Runfiles;

namespace Envoy {
namespace Extensions {
namespace Wasm {

class TestRoot : public Envoy::Extensions::Common::Wasm::Context {
public:
  TestRoot(Extensions::Common::Wasm::Wasm* wasm,
           const std::shared_ptr<Extensions::Common::Wasm::Plugin>& plugin)
      : Envoy::Extensions::Common::Wasm::Context(wasm, plugin) {}

  using Envoy::Extensions::Common::Wasm::Context::log;
  proxy_wasm::WasmResult log(uint32_t level, absl::string_view message) override {
    log_(static_cast<spdlog::level::level_enum>(level), message);
    return proxy_wasm::WasmResult::Ok;
  }
  MOCK_METHOD(void, log_, (spdlog::level::level_enum level, absl::string_view message));
};

static void bmWasmSimpleCallSpeedTest(benchmark::State& state, std::string test,
                                      std::string runtime) {
  Envoy::Logger::Registry::getLog(Logger::Id::wasm).set_level(spdlog::level::off);
  Stats::IsolatedStoreImpl stats_store;
  Api::ApiPtr api = Api::createApiForTest(stats_store);
  Upstream::MockClusterManager cluster_manager;
  Event::DispatcherPtr dispatcher(api->allocateDispatcher("wasm_test"));
  auto scope = Stats::ScopeSharedPtr(stats_store.createScope("wasm."));
  NiceMock<LocalInfo::MockLocalInfo> local_info;

  envoy::extensions::wasm::v3::PluginConfig plugin_config;
  *plugin_config.mutable_root_id() = "some_long_root_id";
  plugin_config.mutable_vm_config()->mutable_configuration()->set_value(test);
  auto plugin = std::make_shared<Extensions::Common::Wasm::Plugin>(
      plugin_config, envoy::config::core::v3::TrafficDirection::UNSPECIFIED, local_info, nullptr);
  auto wasm = std::make_unique<Extensions::Common::Wasm::Wasm>(plugin->wasmConfig(), "vm_key",
                                                               scope, cluster_manager, *dispatcher);
  std::string code;
  if (runtime == "null") {
    code = "WasmSpeedCpp";
  } else {
    code = TestEnvironment::readFileToStringForTest(
        TestEnvironment::runfilesPath("test/extensions/bootstrap/wasm/test_data/speed_cpp.wasm"));
  }
  EXPECT_FALSE(code.empty());
  EXPECT_TRUE(wasm->initialize(code, false));
  wasm->setCreateContextForTesting(
      nullptr,
      [](Extensions::Common::Wasm::Wasm* wasm,
         const std::shared_ptr<Extensions::Common::Wasm::Plugin>& plugin)
          -> proxy_wasm::ContextBase* { return new TestRoot(wasm, plugin); });

  auto root_context = wasm->start(plugin);
  for (__attribute__((unused)) auto _ : state) {
    root_context->onTick(0);
  }
}

#if defined(ENVOY_WASM_WAVM)
#define B(_t)                                                                                \
  BENCHMARK_CAPTURE(bmWasmSimpleCallSpeedTest, V8SpeedTest_##_t, std::string(#_t),                 \
                    std::string("v8"));                                                            \
  BENCHMARK_CAPTURE(bmWasmSimpleCallSpeedTest, NullSpeedTest_##_t, std::string(#_t),               \
                    std::string("null"));                                                          \
  BENCHMARK_CAPTURE(bmWasmSimpleCallSpeedTest, WavmSpeedTest_##_t, std::string(#_t),               \
                    std::string("wavm"));
#else
#define B(_t)                                                                                \
  BENCHMARK_CAPTURE(bmWasmSimpleCallSpeedTest, V8SpeedTest_##_t, std::string(#_t),                 \
                    std::string("v8"));                                                            \
  BENCHMARK_CAPTURE(bmWasmSimpleCallSpeedTest, NullSpeedTest_##_t, std::string(#_t),               \
                    std::string("null"));
#endif

B(empty)
B(get_current_time)
B(small_string)
B(small_string1000)
B(small_string_check_compiler)
B(small_string_check_compiler1000)
B(large_string)
B(large_string1000)
B(get_property)
B(grpc_service)
B(grpc_service1000)
B(modify_metadata)
B(modify_metadata1000)
B(json_serialize)
B(json_deserialize)
B(json_deserialize_empty)
B(convert_to_filter_state)

} // namespace Wasm
} // namespace Extensions
} // namespace Envoy

int main(int argc, char** argv) {
  ::benchmark::Initialize(&argc, argv);
  Envoy::TestEnvironment::initializeOptions(argc, argv);
  // Create a Runfiles object for runfiles lookup.
  // https://github.com/bazelbuild/bazel/blob/master/tools/cpp/runfiles/runfiles_src.h#L32
  std::string error;
  std::unique_ptr<Runfiles> runfiles(Runfiles::Create(argv[0], &error));
  RELEASE_ASSERT(Envoy::TestEnvironment::getOptionalEnvVar("NORUNFILES").has_value() ||
                     runfiles != nullptr,
                 error);
  Envoy::TestEnvironment::setRunfiles(runfiles.get());
  Envoy::TestEnvironment::setEnvVar("ENVOY_IP_TEST_VERSIONS", "all", 0);
  Envoy::Event::Libevent::Global::initialize();
  if (::benchmark::ReportUnrecognizedArguments(argc, argv)) {
    return 1;
  }
  ::benchmark::RunSpecifiedBenchmarks();
  return 0;
}
<commit_msg>wasm: fix benchmarks when using non-V8 Wasm runtime. (#15214)<commit_after>/**
 * Simple WASM speed test.
 *
 * Run with:
 * `bazel run --config=libc++ -c opt //test/extensions/bootstrap/wasm:wasm_speed_test`
 */
#include "common/event/dispatcher_impl.h"
#include "common/stats/isolated_store_impl.h"

#include "extensions/common/wasm/wasm.h"

#include "test/mocks/server/mocks.h"
#include "test/mocks/upstream/mocks.h"
#include "test/test_common/environment.h"
#include "test/test_common/utility.h"

#include "absl/types/optional.h"
#include "benchmark/benchmark.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "tools/cpp/runfiles/runfiles.h"

using bazel::tools::cpp::runfiles::Runfiles;

namespace Envoy {
namespace Extensions {
namespace Wasm {

class TestRoot : public Envoy::Extensions::Common::Wasm::Context {
public:
  TestRoot(Extensions::Common::Wasm::Wasm* wasm,
           const std::shared_ptr<Extensions::Common::Wasm::Plugin>& plugin)
      : Envoy::Extensions::Common::Wasm::Context(wasm, plugin) {}

  using Envoy::Extensions::Common::Wasm::Context::log;
  proxy_wasm::WasmResult log(uint32_t level, absl::string_view message) override {
    log_(static_cast<spdlog::level::level_enum>(level), message);
    return proxy_wasm::WasmResult::Ok;
  }
  MOCK_METHOD(void, log_, (spdlog::level::level_enum level, absl::string_view message));
};

static void bmWasmSimpleCallSpeedTest(benchmark::State& state, std::string test,
                                      std::string runtime) {
  Envoy::Logger::Registry::getLog(Logger::Id::wasm).set_level(spdlog::level::off);
  Stats::IsolatedStoreImpl stats_store;
  Api::ApiPtr api = Api::createApiForTest(stats_store);
  Upstream::MockClusterManager cluster_manager;
  Event::DispatcherPtr dispatcher(api->allocateDispatcher("wasm_test"));
  auto scope = Stats::ScopeSharedPtr(stats_store.createScope("wasm."));
  NiceMock<LocalInfo::MockLocalInfo> local_info;

  envoy::extensions::wasm::v3::PluginConfig plugin_config;
  *plugin_config.mutable_root_id() = "some_long_root_id";
  plugin_config.mutable_vm_config()->mutable_configuration()->set_value(test);
  auto plugin = std::make_shared<Extensions::Common::Wasm::Plugin>(
      plugin_config, envoy::config::core::v3::TrafficDirection::UNSPECIFIED, local_info, nullptr);
  auto wasm = std::make_unique<Extensions::Common::Wasm::Wasm>(plugin->wasmConfig(), "vm_key",
                                                               scope, cluster_manager, *dispatcher);
  std::string code;
  if (runtime == "null") {
    code = "WasmSpeedCpp";
  } else {
    code = TestEnvironment::readFileToStringForTest(
        TestEnvironment::runfilesPath("test/extensions/bootstrap/wasm/test_data/speed_cpp.wasm"));
  }
  EXPECT_FALSE(code.empty());
  EXPECT_TRUE(wasm->initialize(code, false));
  wasm->setCreateContextForTesting(
      nullptr,
      [](Extensions::Common::Wasm::Wasm* wasm,
         const std::shared_ptr<Extensions::Common::Wasm::Plugin>& plugin)
          -> proxy_wasm::ContextBase* { return new TestRoot(wasm, plugin); });

  auto root_context = wasm->start(plugin);
  for (__attribute__((unused)) auto _ : state) {
    root_context->onTick(0);
  }
}

#if defined(ENVOY_WASM_V8)
#define B(_t)                                                                                \
  BENCHMARK_CAPTURE(bmWasmSimpleCallSpeedTest, NullSpeedTest_##_t, std::string(#_t),               \
                    std::string("null"));                                                          \
  BENCHMARK_CAPTURE(bmWasmSimpleCallSpeedTest, WasmSpeedTest_##_t, std::string(#_t),               \
                    std::string("v8"));
#elif defined(ENVOY_WASM_WAVM)
#define B(_t)                                                                                \
  BENCHMARK_CAPTURE(bmWasmSimpleCallSpeedTest, NullSpeedTest_##_t, std::string(#_t),               \
                    std::string("null"));                                                          \
  BENCHMARK_CAPTURE(bmWasmSimpleCallSpeedTest, WasmSpeedTest_##_t, std::string(#_t),               \
                    std::string("wavm"));
#elif defined(ENVOY_WASM_WASMTIME)
#define B(_t)                                                                                \
  BENCHMARK_CAPTURE(bmWasmSimpleCallSpeedTest, NullSpeedTest_##_t, std::string(#_t),               \
                    std::string("null"));                                                          \
  BENCHMARK_CAPTURE(bmWasmSimpleCallSpeedTest, WasmSpeedTest_##_t, std::string(#_t),               \
                    std::string("wasmtime"));
#else
#define B(_t)                                                                                \
  BENCHMARK_CAPTURE(bmWasmSimpleCallSpeedTest, NullSpeedTest_##_t, std::string(#_t),               \
                    std::string("null"));
#endif

B(empty)
B(get_current_time)
B(small_string)
B(small_string1000)
B(small_string_check_compiler)
B(small_string_check_compiler1000)
B(large_string)
B(large_string1000)
B(get_property)
B(grpc_service)
B(grpc_service1000)
B(modify_metadata)
B(modify_metadata1000)
B(json_serialize)
B(json_deserialize)
B(json_deserialize_empty)
B(convert_to_filter_state)

} // namespace Wasm
} // namespace Extensions
} // namespace Envoy

int main(int argc, char** argv) {
  ::benchmark::Initialize(&argc, argv);
  Envoy::TestEnvironment::initializeOptions(argc, argv);
  // Create a Runfiles object for runfiles lookup.
  // https://github.com/bazelbuild/bazel/blob/master/tools/cpp/runfiles/runfiles_src.h#L32
  std::string error;
  std::unique_ptr<Runfiles> runfiles(Runfiles::Create(argv[0], &error));
  RELEASE_ASSERT(Envoy::TestEnvironment::getOptionalEnvVar("NORUNFILES").has_value() ||
                     runfiles != nullptr,
                 error);
  Envoy::TestEnvironment::setRunfiles(runfiles.get());
  Envoy::TestEnvironment::setEnvVar("ENVOY_IP_TEST_VERSIONS", "all", 0);
  Envoy::Event::Libevent::Global::initialize();
  if (::benchmark::ReportUnrecognizedArguments(argc, argv)) {
    return 1;
  }
  ::benchmark::RunSpecifiedBenchmarks();
  return 0;
}
<|endoftext|>


<commit_before>#include "envoy/config/bootstrap/v2/bootstrap.pb.h"
#include "envoy/registry/registry.h"

#include "common/config/well_known_names.h"
#include "common/protobuf/utility.h"

#include "extensions/stat_sinks/common/statsd/statsd.h"
#include "extensions/stat_sinks/statsd/config.h"
#include "extensions/stat_sinks/well_known_names.h"

#include "test/mocks/server/mocks.h"
#include "test/test_common/environment.h"
#include "test/test_common/network_utility.h"
#include "test/test_common/utility.h"

#include "gmock/gmock.h"
#include "gtest/gtest.h"

using testing::NiceMock;
using testing::Return;
using testing::ReturnRef;
using testing::_;

namespace Envoy {
namespace Extensions {
namespace StatSinks {
namespace Statsd {

TEST(StatsConfigTest, ValidTcpStatsd) {
  const std::string name = StatsSinkNames::get().STATSD;

  envoy::config::metrics::v2::StatsdSink sink_config;
  sink_config.set_tcp_cluster_name("fake_cluster");

  Server::Configuration::StatsSinkFactory* factory =
      Registry::FactoryRegistry<Server::Configuration::StatsSinkFactory>::getFactory(name);
  ASSERT_NE(factory, nullptr);

  ProtobufTypes::MessagePtr message = factory->createEmptyConfigProto();
  MessageUtil::jsonConvert(sink_config, *message);

  NiceMock<Server::MockInstance> server;
  Stats::SinkPtr sink = factory->createStatsSink(*message, server);
  EXPECT_NE(sink, nullptr);
  EXPECT_NE(dynamic_cast<Common::Statsd::TcpStatsdSink*>(sink.get()), nullptr);
}

TEST(StatsConfigTest, UdpSinkDefaultPrefix) {
  const std::string name = StatsSinkNames::get().STATSD;
  auto defaultPrefix = Common::Statsd::getDefaultPrefix();

  envoy::config::metrics::v2::StatsdSink sink_config;
  envoy::api::v2::core::Address& address = *sink_config.mutable_address();
  envoy::api::v2::core::SocketAddress& socket_address = *address.mutable_socket_address();
  socket_address.set_protocol(envoy::api::v2::core::SocketAddress::UDP);
  socket_address.set_address("127.0.0.1");
  socket_address.set_port_value(8125);
  EXPECT_EQ(sink_config.prefix(), "");

  Server::Configuration::StatsSinkFactory* factory =
      Registry::FactoryRegistry<Server::Configuration::StatsSinkFactory>::getFactory(name);
  ASSERT_NE(factory, nullptr);
  ProtobufTypes::MessagePtr message = factory->createEmptyConfigProto();
  MessageUtil::jsonConvert(sink_config, *message);

  NiceMock<Server::MockInstance> server;
  Stats::SinkPtr sink = factory->createStatsSink(*message, server);
  ASSERT_NE(sink, nullptr);

  auto udp_sink = dynamic_cast<Common::Statsd::UdpStatsdSink*>(sink.get());
  ASSERT_NE(udp_sink, nullptr);
  EXPECT_EQ(udp_sink->getPrefix(), defaultPrefix);
}

TEST(StatsConfigTest, UdpSinkCustomPrefix) {
  const std::string name = StatsSinkNames::get().STATSD;
  const std::string customPrefix = "prefix.test";

  envoy::config::metrics::v2::StatsdSink sink_config;
  envoy::api::v2::core::Address& address = *sink_config.mutable_address();
  envoy::api::v2::core::SocketAddress& socket_address = *address.mutable_socket_address();
  socket_address.set_protocol(envoy::api::v2::core::SocketAddress::UDP);
  socket_address.set_address("127.0.0.1");
  socket_address.set_port_value(8125);
  sink_config.set_prefix(customPrefix);
  EXPECT_NE(sink_config.prefix(), "");

  Server::Configuration::StatsSinkFactory* factory =
      Registry::FactoryRegistry<Server::Configuration::StatsSinkFactory>::getFactory(name);
  ASSERT_NE(factory, nullptr);
  ProtobufTypes::MessagePtr message = factory->createEmptyConfigProto();
  MessageUtil::jsonConvert(sink_config, *message);

  NiceMock<Server::MockInstance> server;
  Stats::SinkPtr sink = factory->createStatsSink(*message, server);
  ASSERT_NE(sink, nullptr);

  auto udp_sink = dynamic_cast<Common::Statsd::UdpStatsdSink*>(sink.get());
  ASSERT_NE(udp_sink, nullptr);
  EXPECT_EQ(udp_sink->getPrefix(), customPrefix);
}

TEST(StatsConfigTest, TcpSinkDefaultPrefix) {
  const std::string name = StatsSinkNames::get().STATSD;

  envoy::config::metrics::v2::StatsdSink sink_config;
  auto defaultPrefix = Common::Statsd::getDefaultPrefix();
  sink_config.set_tcp_cluster_name("fake_cluster");

  Server::Configuration::StatsSinkFactory* factory =
      Registry::FactoryRegistry<Server::Configuration::StatsSinkFactory>::getFactory(name);
  ASSERT_NE(factory, nullptr);
  EXPECT_EQ(sink_config.prefix(), "");
  ProtobufTypes::MessagePtr message = factory->createEmptyConfigProto();
  MessageUtil::jsonConvert(sink_config, *message);

  NiceMock<Server::MockInstance> server;
  Stats::SinkPtr sink = factory->createStatsSink(*message, server);
  ASSERT_NE(sink, nullptr);

  auto tcp_sink = dynamic_cast<Common::Statsd::TcpStatsdSink*>(sink.get());
  ASSERT_NE(tcp_sink, nullptr);
  EXPECT_EQ(tcp_sink->getPrefix(), defaultPrefix);
}

TEST(StatsConfigTest, TcpSinkCustomPrefix) {
  const std::string name = StatsSinkNames::get().STATSD;

  envoy::config::metrics::v2::StatsdSink sink_config;
  std::string prefix = "prefixTest";
  sink_config.set_tcp_cluster_name("fake_cluster");
  ASSERT_NE(sink_config.prefix(), prefix);
  sink_config.set_prefix(prefix);
  EXPECT_EQ(sink_config.prefix(), prefix);
  Server::Configuration::StatsSinkFactory* factory =
      Registry::FactoryRegistry<Server::Configuration::StatsSinkFactory>::getFactory(name);
  ASSERT_NE(factory, nullptr);

  ProtobufTypes::MessagePtr message = factory->createEmptyConfigProto();
  MessageUtil::jsonConvert(sink_config, *message);

  NiceMock<Server::MockInstance> server;
  Stats::SinkPtr sink = factory->createStatsSink(*message, server);
  ASSERT_NE(sink, nullptr);

  auto tcp_sink = dynamic_cast<Common::Statsd::TcpStatsdSink*>(sink.get());
  ASSERT_NE(tcp_sink, nullptr);
  EXPECT_EQ(tcp_sink->getPrefix(), prefix);
}

class StatsConfigLoopbackTest : public testing::TestWithParam<Network::Address::IpVersion> {};
INSTANTIATE_TEST_CASE_P(IpVersions, StatsConfigLoopbackTest,
                        testing::ValuesIn(TestEnvironment::getIpVersionsForTest()),
                        TestUtility::ipTestParamsToString);

TEST_P(StatsConfigLoopbackTest, ValidUdpIpStatsd) {
  const std::string name = StatsSinkNames::get().STATSD;

  envoy::config::metrics::v2::StatsdSink sink_config;
  envoy::api::v2::core::Address& address = *sink_config.mutable_address();
  envoy::api::v2::core::SocketAddress& socket_address = *address.mutable_socket_address();
  socket_address.set_protocol(envoy::api::v2::core::SocketAddress::UDP);
  auto loopback_flavor = Network::Test::getCanonicalLoopbackAddress(GetParam());
  socket_address.set_address(loopback_flavor->ip()->addressAsString());
  socket_address.set_port_value(8125);

  Server::Configuration::StatsSinkFactory* factory =
      Registry::FactoryRegistry<Server::Configuration::StatsSinkFactory>::getFactory(name);
  ASSERT_NE(factory, nullptr);

  ProtobufTypes::MessagePtr message = factory->createEmptyConfigProto();
  MessageUtil::jsonConvert(sink_config, *message);

  NiceMock<Server::MockInstance> server;
  Stats::SinkPtr sink = factory->createStatsSink(*message, server);
  EXPECT_NE(sink, nullptr);
  EXPECT_NE(dynamic_cast<Common::Statsd::UdpStatsdSink*>(sink.get()), nullptr);
  EXPECT_EQ(dynamic_cast<Common::Statsd::UdpStatsdSink*>(sink.get())->getUseTagForTest(), false);
}

// Negative test for protoc-gen-validate constraints for statsd.
TEST(StatsdConfigTest, ValidateFail) {
  NiceMock<Server::MockInstance> server;
  EXPECT_THROW(
      StatsdSinkFactory().createStatsSink(envoy::config::metrics::v2::StatsdSink(), server),
      ProtoValidationException);
}

} // namespace Statsd
} // namespace StatSinks
} // namespace Extensions
} // namespace Envoy
<commit_msg>tests: Parameterize StatsConfigTest by IP version (#3241)<commit_after>#include "envoy/config/bootstrap/v2/bootstrap.pb.h"
#include "envoy/network/address.h"
#include "envoy/registry/registry.h"

#include "common/config/well_known_names.h"
#include "common/protobuf/utility.h"

#include "extensions/stat_sinks/common/statsd/statsd.h"
#include "extensions/stat_sinks/statsd/config.h"
#include "extensions/stat_sinks/well_known_names.h"

#include "test/mocks/server/mocks.h"
#include "test/test_common/environment.h"
#include "test/test_common/network_utility.h"
#include "test/test_common/utility.h"

#include "gmock/gmock.h"
#include "gtest/gtest.h"

using testing::NiceMock;
using testing::Return;
using testing::ReturnRef;
using testing::_;

namespace Envoy {
namespace Extensions {
namespace StatSinks {
namespace Statsd {

TEST(StatsConfigTest, ValidTcpStatsd) {
  const std::string name = StatsSinkNames::get().STATSD;

  envoy::config::metrics::v2::StatsdSink sink_config;
  sink_config.set_tcp_cluster_name("fake_cluster");

  Server::Configuration::StatsSinkFactory* factory =
      Registry::FactoryRegistry<Server::Configuration::StatsSinkFactory>::getFactory(name);
  ASSERT_NE(factory, nullptr);

  ProtobufTypes::MessagePtr message = factory->createEmptyConfigProto();
  MessageUtil::jsonConvert(sink_config, *message);

  NiceMock<Server::MockInstance> server;
  Stats::SinkPtr sink = factory->createStatsSink(*message, server);
  EXPECT_NE(sink, nullptr);
  EXPECT_NE(dynamic_cast<Common::Statsd::TcpStatsdSink*>(sink.get()), nullptr);
}

class StatsConfigParameterizedTest : public testing::TestWithParam<Network::Address::IpVersion> {};

INSTANTIATE_TEST_CASE_P(IpVersions, StatsConfigParameterizedTest,
                        testing::ValuesIn(TestEnvironment::getIpVersionsForTest()),
                        TestUtility::ipTestParamsToString);

TEST_P(StatsConfigParameterizedTest, UdpSinkDefaultPrefix) {
  const std::string name = StatsSinkNames::get().STATSD;
  auto defaultPrefix = Common::Statsd::getDefaultPrefix();

  envoy::config::metrics::v2::StatsdSink sink_config;
  envoy::api::v2::core::Address& address = *sink_config.mutable_address();
  envoy::api::v2::core::SocketAddress& socket_address = *address.mutable_socket_address();
  socket_address.set_protocol(envoy::api::v2::core::SocketAddress::UDP);
  if (GetParam() == Network::Address::IpVersion::v4) {
    socket_address.set_address("127.0.0.1");
  } else {
    socket_address.set_address("::1");
  }
  socket_address.set_port_value(8125);
  EXPECT_EQ(sink_config.prefix(), "");

  Server::Configuration::StatsSinkFactory* factory =
      Registry::FactoryRegistry<Server::Configuration::StatsSinkFactory>::getFactory(name);
  ASSERT_NE(factory, nullptr);
  ProtobufTypes::MessagePtr message = factory->createEmptyConfigProto();
  MessageUtil::jsonConvert(sink_config, *message);

  NiceMock<Server::MockInstance> server;
  Stats::SinkPtr sink = factory->createStatsSink(*message, server);
  ASSERT_NE(sink, nullptr);

  auto udp_sink = dynamic_cast<Common::Statsd::UdpStatsdSink*>(sink.get());
  ASSERT_NE(udp_sink, nullptr);
  EXPECT_EQ(udp_sink->getPrefix(), defaultPrefix);
}

TEST_P(StatsConfigParameterizedTest, UdpSinkCustomPrefix) {
  const std::string name = StatsSinkNames::get().STATSD;
  const std::string customPrefix = "prefix.test";

  envoy::config::metrics::v2::StatsdSink sink_config;
  envoy::api::v2::core::Address& address = *sink_config.mutable_address();
  envoy::api::v2::core::SocketAddress& socket_address = *address.mutable_socket_address();
  socket_address.set_protocol(envoy::api::v2::core::SocketAddress::UDP);
  if (GetParam() == Network::Address::IpVersion::v4) {
    socket_address.set_address("127.0.0.1");
  } else {
    socket_address.set_address("::1");
  }
  socket_address.set_port_value(8125);
  sink_config.set_prefix(customPrefix);
  EXPECT_NE(sink_config.prefix(), "");

  Server::Configuration::StatsSinkFactory* factory =
      Registry::FactoryRegistry<Server::Configuration::StatsSinkFactory>::getFactory(name);
  ASSERT_NE(factory, nullptr);
  ProtobufTypes::MessagePtr message = factory->createEmptyConfigProto();
  MessageUtil::jsonConvert(sink_config, *message);

  NiceMock<Server::MockInstance> server;
  Stats::SinkPtr sink = factory->createStatsSink(*message, server);
  ASSERT_NE(sink, nullptr);

  auto udp_sink = dynamic_cast<Common::Statsd::UdpStatsdSink*>(sink.get());
  ASSERT_NE(udp_sink, nullptr);
  EXPECT_EQ(udp_sink->getPrefix(), customPrefix);
}

TEST(StatsConfigTest, TcpSinkDefaultPrefix) {
  const std::string name = StatsSinkNames::get().STATSD;

  envoy::config::metrics::v2::StatsdSink sink_config;
  auto defaultPrefix = Common::Statsd::getDefaultPrefix();
  sink_config.set_tcp_cluster_name("fake_cluster");

  Server::Configuration::StatsSinkFactory* factory =
      Registry::FactoryRegistry<Server::Configuration::StatsSinkFactory>::getFactory(name);
  ASSERT_NE(factory, nullptr);
  EXPECT_EQ(sink_config.prefix(), "");
  ProtobufTypes::MessagePtr message = factory->createEmptyConfigProto();
  MessageUtil::jsonConvert(sink_config, *message);

  NiceMock<Server::MockInstance> server;
  Stats::SinkPtr sink = factory->createStatsSink(*message, server);
  ASSERT_NE(sink, nullptr);

  auto tcp_sink = dynamic_cast<Common::Statsd::TcpStatsdSink*>(sink.get());
  ASSERT_NE(tcp_sink, nullptr);
  EXPECT_EQ(tcp_sink->getPrefix(), defaultPrefix);
}

TEST(StatsConfigTest, TcpSinkCustomPrefix) {
  const std::string name = StatsSinkNames::get().STATSD;

  envoy::config::metrics::v2::StatsdSink sink_config;
  ProtobufTypes::String prefix = "prefixTest";
  sink_config.set_tcp_cluster_name("fake_cluster");
  ASSERT_NE(sink_config.prefix(), prefix);
  sink_config.set_prefix(prefix);
  EXPECT_EQ(sink_config.prefix(), prefix);
  Server::Configuration::StatsSinkFactory* factory =
      Registry::FactoryRegistry<Server::Configuration::StatsSinkFactory>::getFactory(name);
  ASSERT_NE(factory, nullptr);

  ProtobufTypes::MessagePtr message = factory->createEmptyConfigProto();
  MessageUtil::jsonConvert(sink_config, *message);

  NiceMock<Server::MockInstance> server;
  Stats::SinkPtr sink = factory->createStatsSink(*message, server);
  ASSERT_NE(sink, nullptr);

  auto tcp_sink = dynamic_cast<Common::Statsd::TcpStatsdSink*>(sink.get());
  ASSERT_NE(tcp_sink, nullptr);
  EXPECT_EQ(tcp_sink->getPrefix(), prefix);
}

class StatsConfigLoopbackTest : public testing::TestWithParam<Network::Address::IpVersion> {};
INSTANTIATE_TEST_CASE_P(IpVersions, StatsConfigLoopbackTest,
                        testing::ValuesIn(TestEnvironment::getIpVersionsForTest()),
                        TestUtility::ipTestParamsToString);

TEST_P(StatsConfigLoopbackTest, ValidUdpIpStatsd) {
  const std::string name = StatsSinkNames::get().STATSD;

  envoy::config::metrics::v2::StatsdSink sink_config;
  envoy::api::v2::core::Address& address = *sink_config.mutable_address();
  envoy::api::v2::core::SocketAddress& socket_address = *address.mutable_socket_address();
  socket_address.set_protocol(envoy::api::v2::core::SocketAddress::UDP);
  auto loopback_flavor = Network::Test::getCanonicalLoopbackAddress(GetParam());
  socket_address.set_address(loopback_flavor->ip()->addressAsString());
  socket_address.set_port_value(8125);

  Server::Configuration::StatsSinkFactory* factory =
      Registry::FactoryRegistry<Server::Configuration::StatsSinkFactory>::getFactory(name);
  ASSERT_NE(factory, nullptr);

  ProtobufTypes::MessagePtr message = factory->createEmptyConfigProto();
  MessageUtil::jsonConvert(sink_config, *message);

  NiceMock<Server::MockInstance> server;
  Stats::SinkPtr sink = factory->createStatsSink(*message, server);
  EXPECT_NE(sink, nullptr);
  EXPECT_NE(dynamic_cast<Common::Statsd::UdpStatsdSink*>(sink.get()), nullptr);
  EXPECT_EQ(dynamic_cast<Common::Statsd::UdpStatsdSink*>(sink.get())->getUseTagForTest(), false);
}

// Negative test for protoc-gen-validate constraints for statsd.
TEST(StatsdConfigTest, ValidateFail) {
  NiceMock<Server::MockInstance> server;
  EXPECT_THROW(
      StatsdSinkFactory().createStatsSink(envoy::config::metrics::v2::StatsdSink(), server),
      ProtoValidationException);
}

} // namespace Statsd
} // namespace StatSinks
} // namespace Extensions
} // namespace Envoy
<|endoftext|>


<commit_before>////////////////////////////////////////////////////////////////////////////////
// Name:      style.cpp
// Purpose:   Implementation of wxExStyle class
// Author:    Anton van Wezenbeek
// Copyright: (c) 2011 Anton van Wezenbeek
////////////////////////////////////////////////////////////////////////////////

#include <wx/wxprec.h>
#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif
#include <wx/config.h>
#include <wx/log.h>
#include <wx/stc/stc.h>
#include <wx/tokenzr.h>
#include <wx/extension/style.h>
#include <wx/extension/lexers.h>

wxExStyle::wxExStyle()
  : m_No()
  , m_Value()
{
}

wxExStyle::wxExStyle(const wxXmlNode* node)
{
  Set(node);
}

wxExStyle::wxExStyle(const wxString& no, const wxString& value)
  : m_Value(value)
{
  SetNo(no);
}

void wxExStyle::Apply(wxStyledTextCtrl* stc) const
{
  // Currently the default style is constructed using
  // default constructor.
  // If this is the only style, reset STC.
  if (m_No.empty())
  {
    stc->StyleResetDefault();
  }
  else
  {
    for (
      auto it = m_No.begin();
      it != m_No.end();
      ++it)
    {
      stc->StyleSetSpec(*it, m_Value);
    }
  }
}

bool wxExStyle::ContainsDefaultStyle() const
{
  const auto it = m_No.find(wxSTC_STYLE_DEFAULT);
  return (it != m_No.end());
}

bool wxExStyle::IsOk() const
{
  return !m_No.empty() && !m_Value.empty();
}

void wxExStyle::Set(const wxXmlNode* node)
{
  SetNo(wxExLexers::Get()->ApplyMacro(node->GetAttribute("no", "0")));

  m_Value = node->GetNodeContent().Strip(wxString::both);

  const auto it =
    wxExLexers::Get()->GetThemeMacros().find(m_Value);

  if (it != wxExLexers::Get()->GetThemeMacros().end())
  {
    wxString value = it->second;

    if (value.Contains("default-font"))
    {
      const wxFont font(wxConfigBase::Get()->ReadObject(_("Default font"),
        wxSystemSettings::GetFont(wxSYS_OEM_FIXED_FONT)));

      value.Replace("default-font",
        wxString::Format("face:%s,size:%d",
          font.GetFaceName().c_str(), font.GetPointSize()));
    }

    m_Value = value;
  }

  if (!IsOk())
  {
    wxLogError(_("Illegal style: %s on line: %d"),
      m_Value.c_str(), node->GetLineNumber());
  }
}

void wxExStyle::SetNo(const wxString& no)
{
  m_No.clear();

  wxStringTokenizer no_fields(no, ",");

  // Collect each single no in the vector.
  while (no_fields.HasMoreTokens())
  {
    const wxString single =
      wxExLexers::Get()->ApplyMacro(no_fields.GetNextToken());

    if (single.IsNumber())
    {
      m_No.insert(atoi(single.c_str()));
    }
    else
    {
      wxLogError(_("Illegal style: %s"), no.c_str());
    }
  }
}
<commit_msg>added option for italic and bold, does not work<commit_after>////////////////////////////////////////////////////////////////////////////////
// Name:      style.cpp
// Purpose:   Implementation of wxExStyle class
// Author:    Anton van Wezenbeek
// Copyright: (c) 2011 Anton van Wezenbeek
////////////////////////////////////////////////////////////////////////////////

#include <wx/wxprec.h>
#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif
#include <wx/config.h>
#include <wx/log.h>
#include <wx/stc/stc.h>
#include <wx/tokenzr.h>
#include <wx/extension/style.h>
#include <wx/extension/lexers.h>

wxExStyle::wxExStyle()
  : m_No()
  , m_Value()
{
}

wxExStyle::wxExStyle(const wxXmlNode* node)
{
  Set(node);
}

wxExStyle::wxExStyle(const wxString& no, const wxString& value)
  : m_Value(value)
{
  SetNo(no);
}

void wxExStyle::Apply(wxStyledTextCtrl* stc) const
{
  // Currently the default style is constructed using
  // default constructor.
  // If this is the only style, reset STC.
  if (m_No.empty())
  {
    stc->StyleResetDefault();
  }
  else
  {
    for (
      auto it = m_No.begin();
      it != m_No.end();
      ++it)
    {
      stc->StyleSetSpec(*it, m_Value);
    }
  }
}

bool wxExStyle::ContainsDefaultStyle() const
{
  const auto it = m_No.find(wxSTC_STYLE_DEFAULT);
  return (it != m_No.end());
}

bool wxExStyle::IsOk() const
{
  return !m_No.empty() && !m_Value.empty();
}

void wxExStyle::Set(const wxXmlNode* node)
{
  SetNo(wxExLexers::Get()->ApplyMacro(node->GetAttribute("no", "0")));

  m_Value = node->GetNodeContent().Strip(wxString::both);

  const auto it =
    wxExLexers::Get()->GetThemeMacros().find(m_Value);

  if (it != wxExLexers::Get()->GetThemeMacros().end())
  {
    wxString value = it->second;

    if (value.Contains("default-font"))
    {
      const wxFont font(wxConfigBase::Get()->ReadObject(_("Default font"),
        wxSystemSettings::GetFont(wxSYS_OEM_FIXED_FONT)));

      value.Replace("default-font",
        wxString::Format("face:%s,size:%d",
          font.GetFaceName().c_str(), font.GetPointSize()));

      if (
        (font.GetStyle() & wxFONTSTYLE_ITALIC) ||
        (font.GetStyle() & wxFONTSTYLE_SLANT))
      {
        // This does not work (2.9.2)
        // value += ",italic";
      }

      if (font.GetWeight() & wxFONTWEIGHT_BOLD)
      {
        value += ",bold";
      }

      if (font.GetUnderlined())
      {
        value += ",underline";
      }
    }

    m_Value = value;
  }

  if (!IsOk())
  {
    wxLogError(_("Illegal style: %s on line: %d"),
      m_Value.c_str(), node->GetLineNumber());
  }
}

void wxExStyle::SetNo(const wxString& no)
{
  m_No.clear();

  wxStringTokenizer no_fields(no, ",");

  // Collect each single no in the vector.
  while (no_fields.HasMoreTokens())
  {
    const wxString single =
      wxExLexers::Get()->ApplyMacro(no_fields.GetNextToken());

    if (single.IsNumber())
    {
      m_No.insert(atoi(single.c_str()));
    }
    else
    {
      wxLogError(_("Illegal style: %s"), no.c_str());
    }
  }
}
<|endoftext|>


<commit_before>#include <cstdlib>
#include <cstdint>
#include <string>
#include <vector>
#include <kj/common.h>
#include <kj/debug.h>
#include <kj/main.h>
#include <kj/string.h>
#include <glog/logging.h>
#include <turbo/ipc/posix/pipe.hpp>
#include <turbo/process/posix/spawn.hpp>

namespace tpp = turbo::process::posix;

struct config
{
    config() : port(0), bot_arg_count(0), bot_arg_offset(0) { }
    std::string address;
    int port;
    std::string bot_path;
    unsigned short bot_arg_count;
    unsigned short bot_arg_offset;
};

void parse_cmd_args(int argc, char* argv[], config& conf)
{
    kj::TopLevelProcessContext context(argv[0]);
    kj::MainFunc parse = kj::MainBuilder(
	    context,
	    "Robocup 2D Simulation Client v0.0",
	    "Launches bot and connects to the server")
	.expectArg("address", [&] (kj::StringPtr arg)
	{
	    conf.address = arg.cStr();
	    ++conf.bot_arg_offset;
	    return true;
	})
	.expectArg("port", [&] (kj::StringPtr arg)
	{
	    conf.port = atoi(arg.cStr());
	    ++conf.bot_arg_offset;
	    return true;
	})
	.expectArg("bot_path", [&] (kj::StringPtr arg)
	{
	    conf.bot_path = arg.cStr();
	    ++conf.bot_arg_offset;
	    return true;
	})
	.expectZeroOrMoreArgs("bot_arg", [&] (kj::StringPtr)
	{
	    ++conf.bot_arg_count;
	    return true;
	})
	.build();
    KJ_STACK_ARRAY(kj::StringPtr, params, argc - 1, 8, 32);
    for (int iter = 1; iter < argc; ++iter)
    {
	params[iter - 1] = argv[iter];
    }
    parse(argv[0], params);
}

int main(int argc, char* argv[])
{
    config conf;
    parse_cmd_args(argc, argv, conf);
    tpp::child&& bot = tpp::spawn(conf.bot_path.c_str(), &argv[conf.bot_arg_offset], {}, 2 << 16);
    google::InitGoogleLogging(argv[0]);
    FLAGS_logtostderr = true;
    FLAGS_minloglevel = (kj::_::Debug::shouldLog(kj::_::Debug::Severity::INFO)) ? 0 : 1;
    google::InstallFailureSignalHandler();
    return 0;
}
<commit_msg>* added in goalie, team and uniform to the command line argument parser; these are needed for the InitRequest message * the port and uniform number arguments now have range checking<commit_after>#include <cstdlib>
#include <cstdint>
#include <limits>
#include <string>
#include <vector>
#include <kj/common.h>
#include <kj/debug.h>
#include <kj/main.h>
#include <kj/string.h>
#include <glog/logging.h>
#include <turbo/ipc/posix/pipe.hpp>
#include <turbo/process/posix/spawn.hpp>

namespace tpp = turbo::process::posix;

struct config
{
    config() :
	    goalie(false),
	    port(0),
	    bot_arg_count(0),
	    bot_arg_offset(0)
    { }
    bool goalie;
    std::string address;
    uint16_t port;
    std::string team;
    uint8_t uniform;
    std::string bot_path;
    unsigned short bot_arg_count;
    unsigned short bot_arg_offset;
};

void parse_cmd_args(int argc, char* argv[], config& conf)
{
    kj::TopLevelProcessContext context(argv[0]);
    kj::MainFunc parse = kj::MainBuilder(
	    context,
	    "Robocup 2D Simulation Client v0.0",
	    "Launches bot and connects to the server")
	.addOption({'g', "goalie"}, [&] ()
	{
	    conf.goalie = true;
	    ++conf.bot_arg_offset;
	    return true;
	},
	"The bot is playing as the goalie.")
	.expectArg("address", [&] (kj::StringPtr arg)
	{
	    conf.address = arg.cStr();
	    ++conf.bot_arg_offset;
	    return true;
	})
	.expectArg("port", [&] (kj::StringPtr arg)
	{
	    int tmp = atoi(arg.cStr());
	    if (std::numeric_limits<decltype(conf.port)>::min() <= tmp &&
		    tmp <= std::numeric_limits<decltype(conf.port)>::max())
	    {
		conf.port = static_cast<decltype(conf.port)>(tmp);
		++conf.bot_arg_offset;
		return kj::MainBuilder::Validity(true);
	    }
	    else
	    {
		return kj::MainBuilder::Validity(kj::str(
			"port number must be int the range ",
			std::numeric_limits<decltype(conf.port)>::min(),
			" to ",
			std::numeric_limits<decltype(conf.port)>::max()));
	    }
	})
	.expectArg("team", [&] (kj::StringPtr arg)
	{
	    conf.team = arg.cStr();
	    ++conf.bot_arg_offset;
	    return true;
	})
	.expectArg("uniform", [&] (kj::StringPtr arg)
	{
	    int tmp = atoi(arg.cStr());
	    if (std::numeric_limits<decltype(conf.uniform)>::min() <= tmp &&
		    tmp <= std::numeric_limits<decltype(conf.uniform)>::max())
	    {
		conf.uniform = static_cast<decltype(conf.uniform)>(tmp);
		++conf.bot_arg_offset;
		return kj::MainBuilder::Validity(true);
	    }
	    else
	    {
		return kj::MainBuilder::Validity(kj::str(
			"uniform number must be in the range ",
			std::numeric_limits<decltype(conf.uniform)>::min(),
			" to ",
			std::numeric_limits<decltype(conf.uniform)>::max()));
	    }
	})
	.expectArg("bot_path", [&] (kj::StringPtr arg)
	{
	    conf.bot_path = arg.cStr();
	    ++conf.bot_arg_offset;
	    return true;
	})
	.expectZeroOrMoreArgs("bot_arg", [&] (kj::StringPtr)
	{
	    ++conf.bot_arg_count;
	    return true;
	})
	.build();
    KJ_STACK_ARRAY(kj::StringPtr, params, argc - 1, 8, 32);
    for (int iter = 1; iter < argc; ++iter)
    {
	params[iter - 1] = argv[iter];
    }
    parse(argv[0], params);
}

int main(int argc, char* argv[])
{
    config conf;
    parse_cmd_args(argc, argv, conf);
    tpp::child&& bot = tpp::spawn(conf.bot_path.c_str(), &argv[conf.bot_arg_offset], {}, 2 << 16);
    google::InitGoogleLogging(argv[0]);
    FLAGS_logtostderr = true;
    FLAGS_minloglevel = (kj::_::Debug::shouldLog(kj::_::Debug::Severity::INFO)) ? 0 : 1;
    google::InstallFailureSignalHandler();
    return 0;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <iterator>
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>

int main(void) {
  cv::Scalar black(0, 0, 0);
  cv::Scalar white(255, 255, 255);
  std::string input;

  std::getline(std::cin, input);
  if (std::cin.eof()) {
    exit(0);
  }
  int width, height;
  if (sscanf(input.c_str(), "[%dx%d]", &width, &height) != 2) {
    std::cout << "Invalid input for [WxH]:" << input << std::endl;
    exit(1);
  }
  cv::Mat image(width, height, CV_8U);

  while (1) {
    std::getline(std::cin, input);
    if (std::cin.eof()) {
      exit(0);
    }
    int x, y;
    if (sscanf(input.c_str(), "%d,%d", &x, &y) != 2) {
      std::cout << "Invalid input:" << input << std::endl;
      continue;
    }
    if (x < 0 || y < 0) {
      continue;
    }
    image = black;
    cv::circle(image, cv::Point(x, y), 20, white, -1);
    std::string window_name = "circle";
    cv::putText(image, std::to_string(x) + ',' + std::to_string(y),
                cv::Point(30, 30), cv::FONT_HERSHEY_SIMPLEX, 1,
                cv::Scalar(200, 200, 250));
    cv::imshow(window_name.c_str(), image);
    char c = static_cast<char>(cv::waitKey(10));
    if (c == 27) exit(0);
  }
}
<commit_msg>make image black when x,y are negative too<commit_after>#include <iostream>
#include <iterator>
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>

int main(void) {
  cv::Scalar black(0, 0, 0);
  cv::Scalar white(255, 255, 255);
  std::string input;

  std::getline(std::cin, input);
  if (std::cin.eof()) {
    exit(0);
  }
  int width, height;
  if (sscanf(input.c_str(), "[%dx%d]", &width, &height) != 2) {
    std::cout << "Invalid input for [WxH]:" << input << std::endl;
    exit(1);
  }
  cv::Mat image(width, height, CV_8U);

  while (1) {
    std::getline(std::cin, input);
    if (std::cin.eof()) {
      exit(0);
    }
    int x, y;
    if (sscanf(input.c_str(), "%d,%d", &x, &y) != 2) {
      std::cout << "Invalid input:" << input << std::endl;
      continue;
    }
    image = black;
    if (x < 0 || y < 0) {
      continue;
    }
    cv::circle(image, cv::Point(x, y), 20, white, -1);
    std::string window_name = "circle";
    cv::putText(image, std::to_string(x) + ',' + std::to_string(y),
                cv::Point(30, 30), cv::FONT_HERSHEY_SIMPLEX, 1,
                cv::Scalar(200, 200, 250));
    cv::imshow(window_name.c_str(), image);
    char c = static_cast<char>(cv::waitKey(10));
    if (c == 27) exit(0);
  }
}
<|endoftext|>


<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2013-2016.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================

#include <vector.hpp>
#include <string.hpp>

#include "arp_layer.hpp"
#include "arp_cache.hpp"
#include "ip_layer.hpp"
#include "logging.hpp"
#include "kernel_utils.hpp"
#include "network.hpp"

namespace {

//TODO

} //end of anonymous namespace

void network::arp::decode(network::ethernet::packet& packet){
    header* arp_header = reinterpret_cast<header*>(packet.payload + packet.index);

    logging::logf(logging::log_level::TRACE, "arp: Start ARP packet handling\n");

    auto hw_type = switch_endian_16(arp_header->hw_type);
    auto protocol_type = switch_endian_16(arp_header->protocol_type);

    // We only support ethernet hardware frames
    if(hw_type != 0x1){
        logging::logf(logging::log_level::ERROR, "arp: Unhandled hardware type %h\n", size_t(hw_type));
        return;
    }

    // We only support IPV4 protocol
    if(protocol_type != 0x800){
        logging::logf(logging::log_level::ERROR, "arp: Unhandled protocol type %h\n", size_t(protocol_type));
        return;
    }

    auto hw_len = arp_header->hw_len;
    auto protocol_len = arp_header->protocol_len;
    auto operation = switch_endian_16(arp_header->operation);

    // This should never happen
    if(hw_len != 0x6 || protocol_len != 0x4){
        logging::logf(logging::log_level::ERROR, "arp: Unable to process the given length hw:%h prot:%h\n", size_t(hw_len), size_t(protocol_len));
        return;
    }

    if (operation != 0x1 && operation != 0x2) {
        logging::logf(logging::log_level::TRACE, "arp: Unhandled operation %h\n", size_t(operation));
        return;
    }

    size_t source_hw = 0;
    size_t target_hw = 0;

    for(size_t i = 0; i < 3; ++i){
        source_hw |= uint64_t(switch_endian_16(arp_header->source_hw_addr[i])) << ((2 - i) * 16);
        target_hw |= uint64_t(switch_endian_16(arp_header->target_hw_addr[i])) << ((2 - i) * 16);
    }

    logging::logf(logging::log_level::TRACE, "arp: Source HW Address %h \n", source_hw);
    logging::logf(logging::log_level::TRACE, "arp: Target HW Address %h \n", target_hw);

    network::ip::address source_prot;
    network::ip::address target_prot;

    for(size_t i = 0; i < 2; ++i){
        auto source = switch_endian_16(arp_header->source_protocol_addr[i]);
        auto target = switch_endian_16(arp_header->target_protocol_addr[i]);

        source_prot.set_sub(2*i, source >> 8);
        source_prot.set_sub(2*i+1, source);

        target_prot.set_sub(2*i, target >> 8);
        target_prot.set_sub(2*i+1, target);
    }

    logging::logf(logging::log_level::TRACE, "arp: Source Protocol Address %u.%u.%u.%u \n",
        uint64_t(source_prot(0)), uint64_t(source_prot(1)), uint64_t(source_prot(2)), uint64_t(source_prot(3)));
    logging::logf(logging::log_level::TRACE, "arp: Target Protocol Address %u.%u.%u.%u \n",
        uint64_t(target_prot(0)), uint64_t(target_prot(1)), uint64_t(target_prot(2)), uint64_t(target_prot(3)));

    //TODO Only do that is not an ARP probe
    network::arp::update_cache(source_hw, source_prot);

    if(operation == 0x1){
        logging::logf(logging::log_level::TRACE, "arp: Handle Request\n");

        // Ask the ethernet layer to craft a packet
        auto packet = network::ethernet::prepare_packet(sizeof(header), source_hw, ethernet::ether_type::ARP);

        auto* arp_reply_header = reinterpret_cast<header*>(packet.payload + packet.index);

        arp_reply_header->hw_type = switch_endian_16(0x1); // ethernet
        arp_reply_header->protocol_type = switch_endian_16(0x800); // IPV4
        arp_reply_header->hw_len = 0x6; // MAC Address
        arp_reply_header->protocol_len = 0x4; // IP Address
        arp_reply_header->operation = switch_endian_16(0x2); //ARP Reply

        auto& inter = network::interface(0); //TODO Select the interface ?
        auto source_mac = inter.mac_address;

        for(size_t i = 0; i < 3; ++i){
            arp_reply_header->target_hw_addr[i] = arp_header->source_hw_addr[i];

            arp_reply_header->source_hw_addr[i] = switch_endian_16(uint16_t(source_mac >> ((2 - i) * 16)));
        }

        for(size_t i = 0; i < 2; ++i){
            arp_reply_header->source_protocol_addr[i] = arp_header->target_protocol_addr[i];
            arp_reply_header->target_protocol_addr[i] = arp_header->source_protocol_addr[i];
        }

        network::ethernet::finalize_packet(packet);
    } else if(operation == 0x2){
        logging::logf(logging::log_level::TRACE, "arp: Handle Reply\n");

        //TODO
    }
}
<commit_msg>Only update the cache if not an ARP probe<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2013-2016.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================

#include <vector.hpp>
#include <string.hpp>

#include "arp_layer.hpp"
#include "arp_cache.hpp"
#include "ip_layer.hpp"
#include "logging.hpp"
#include "kernel_utils.hpp"
#include "network.hpp"

namespace {

//TODO

} //end of anonymous namespace

void network::arp::decode(network::ethernet::packet& packet){
    header* arp_header = reinterpret_cast<header*>(packet.payload + packet.index);

    logging::logf(logging::log_level::TRACE, "arp: Start ARP packet handling\n");

    auto hw_type = switch_endian_16(arp_header->hw_type);
    auto protocol_type = switch_endian_16(arp_header->protocol_type);

    // We only support ethernet hardware frames
    if(hw_type != 0x1){
        logging::logf(logging::log_level::ERROR, "arp: Unhandled hardware type %h\n", size_t(hw_type));
        return;
    }

    // We only support IPV4 protocol
    if(protocol_type != 0x800){
        logging::logf(logging::log_level::ERROR, "arp: Unhandled protocol type %h\n", size_t(protocol_type));
        return;
    }

    auto hw_len = arp_header->hw_len;
    auto protocol_len = arp_header->protocol_len;
    auto operation = switch_endian_16(arp_header->operation);

    // This should never happen
    if(hw_len != 0x6 || protocol_len != 0x4){
        logging::logf(logging::log_level::ERROR, "arp: Unable to process the given length hw:%h prot:%h\n", size_t(hw_len), size_t(protocol_len));
        return;
    }

    if (operation != 0x1 && operation != 0x2) {
        logging::logf(logging::log_level::TRACE, "arp: Unhandled operation %h\n", size_t(operation));
        return;
    }

    size_t source_hw = 0;
    size_t target_hw = 0;

    for(size_t i = 0; i < 3; ++i){
        source_hw |= uint64_t(switch_endian_16(arp_header->source_hw_addr[i])) << ((2 - i) * 16);
        target_hw |= uint64_t(switch_endian_16(arp_header->target_hw_addr[i])) << ((2 - i) * 16);
    }

    logging::logf(logging::log_level::TRACE, "arp: Source HW Address %h \n", source_hw);
    logging::logf(logging::log_level::TRACE, "arp: Target HW Address %h \n", target_hw);

    network::ip::address source_prot;
    network::ip::address target_prot;

    for(size_t i = 0; i < 2; ++i){
        auto source = switch_endian_16(arp_header->source_protocol_addr[i]);
        auto target = switch_endian_16(arp_header->target_protocol_addr[i]);

        source_prot.set_sub(2*i, source >> 8);
        source_prot.set_sub(2*i+1, source);

        target_prot.set_sub(2*i, target >> 8);
        target_prot.set_sub(2*i+1, target);
    }

    logging::logf(logging::log_level::TRACE, "arp: Source Protocol Address %u.%u.%u.%u \n",
        uint64_t(source_prot(0)), uint64_t(source_prot(1)), uint64_t(source_prot(2)), uint64_t(source_prot(3)));
    logging::logf(logging::log_level::TRACE, "arp: Target Protocol Address %u.%u.%u.%u \n",
        uint64_t(target_prot(0)), uint64_t(target_prot(1)), uint64_t(target_prot(2)), uint64_t(target_prot(3)));

    // If not an ARP Probe, update the ARP cache
    if(source_prot.raw_address == 0x0){
        network::arp::update_cache(source_hw, source_prot);
    }

    if(operation == 0x1){
        logging::logf(logging::log_level::TRACE, "arp: Handle Request\n");

        // Ask the ethernet layer to craft a packet
        auto packet = network::ethernet::prepare_packet(sizeof(header), source_hw, ethernet::ether_type::ARP);

        auto* arp_reply_header = reinterpret_cast<header*>(packet.payload + packet.index);

        arp_reply_header->hw_type = switch_endian_16(0x1); // ethernet
        arp_reply_header->protocol_type = switch_endian_16(0x800); // IPV4
        arp_reply_header->hw_len = 0x6; // MAC Address
        arp_reply_header->protocol_len = 0x4; // IP Address
        arp_reply_header->operation = switch_endian_16(0x2); //ARP Reply

        auto& inter = network::interface(0); //TODO Select the interface ?
        auto source_mac = inter.mac_address;

        for(size_t i = 0; i < 3; ++i){
            arp_reply_header->target_hw_addr[i] = arp_header->source_hw_addr[i];

            arp_reply_header->source_hw_addr[i] = switch_endian_16(uint16_t(source_mac >> ((2 - i) * 16)));
        }

        for(size_t i = 0; i < 2; ++i){
            arp_reply_header->source_protocol_addr[i] = arp_header->target_protocol_addr[i];
            arp_reply_header->target_protocol_addr[i] = arp_header->source_protocol_addr[i];
        }

        network::ethernet::finalize_packet(packet);
    } else if(operation == 0x2){
        logging::logf(logging::log_level::TRACE, "arp: Handle Reply\n");

        //TODO
    }
}
<|endoftext|>


<commit_before>///////////////////////////////////////////////////////////////////////////////
//
// script templates example
//
// templates.cpp
//
// Copyright (c) 2012-2016 Eric Lombrozo
//
// All Rights Reserved.

#include <CoinQ/CoinQ_script.h>
#include <CoinQ/scriptnum.h>
#include <CoinCore/Base58Check.h>
#include <CoinCore/hash.h>

#include <iostream>
#include <sstream>
#include <stdexcept>
#include <string>

using namespace Coin;
using namespace CoinQ::Script;
using namespace std;

const unsigned char ADDRESS_VERSIONS[] = {30, 50};

string help(char* appName)
{
    stringstream ss;
    ss  << "# Usage: " << appName << " <type> [params]" << endl
        << "#   p2pk    <pubkey>" << endl
        << "#   p2pkh   <pubkey>" << endl
        << "#   mofn    <m> <pubkey1> [pubkey2] ..." << endl
        << "#   cltv    <master pubkey> <timelock pubkey> <locktime>" << endl
        << "#   witness <redeemscript>";
    return ss.str();
}

int main(int argc, char* argv[])
{
    if (argc < 2)
    {
        cerr << help(argv[0]) << endl;
        return -1;
    }

    try
    {
        string type(argv[1]);
        if (type == "p2pk")
        {
            if (argc != 3) throw runtime_error(help(argv[0]));

            uchar_vector pubkey(argv[2]);
            if (pubkey.size() != 33) throw runtime_error("Invalid pubkey length.");

            uchar_vector outPattern;
            outPattern << OP_PUBKEY << 0 << OP_CHECKSIG;
            ScriptTemplate outTemplate(outPattern);

            uchar_vector inPattern;
            inPattern << OP_0;
            ScriptTemplate inTemplate(inPattern);

            cout << "txoutscript:   " << outTemplate.script(pubkey).getHex() << endl;
            cout << "txinscript:    " << inTemplate.script(pubkey).getHex() << endl;
            cout << "address:       " << toBase58Check(hash160(pubkey), ADDRESS_VERSIONS[0]) << endl;
        }
        else if (type == "p2pkh")
        {
            if (argc != 3) throw runtime_error(help(argv[0]));

            uchar_vector pubkey(argv[2]);
            if (pubkey.size() != 33) throw runtime_error("Invalid pubkey length.");

            uchar_vector outPattern;
            outPattern << OP_DUP << OP_HASH160 << OP_PUBKEYHASH << 0 << OP_EQUALVERIFY << OP_CHECKSIG;
            ScriptTemplate outTemplate(outPattern);

            uchar_vector inPattern;
            inPattern << OP_0 << OP_PUBKEY << 0;
            ScriptTemplate inTemplate(inPattern);

            cout << "txoutscript:   " << outTemplate.script(pubkey).getHex() << endl;
            cout << "txinscript:    " << inTemplate.script(pubkey).getHex() << endl;
            cout << "address:       " << toBase58Check(hash160(pubkey), ADDRESS_VERSIONS[0]) << endl;
        }
        else if (type == "mofn")
        {
            if (argc < 4) throw runtime_error(help(argv[0]));

            int minsigs = strtol(argv[2], NULL, 0);
            if (minsigs < 1 || minsigs > 15)
                throw runtime_error("Invalid minsigs.");

            vector<bytes_t> pubkeys;
            for (int i = 3; i < argc; i++)
            {
                uchar_vector pubkey(argv[i]);
                if (pubkey.size() != 33) throw runtime_error("Invalid pubkey length.");

                pubkeys.push_back(pubkey);
            }
            if ((int)pubkeys.size() < minsigs || pubkeys.size() > 15)
                throw runtime_error("Invalid pubkey count.");

            uchar_vector redeemPattern, emptySigs;
            redeemPattern << (OP_1_OFFSET + minsigs);
            for (size_t i = 0; i < pubkeys.size(); i++)
            {
                redeemPattern << OP_PUBKEY << i;
                emptySigs << OP_0;
            }
            redeemPattern << (OP_1_OFFSET + pubkeys.size()) << OP_CHECKMULTISIG;

            SymmetricKeyGroup keyGroup(pubkeys);
            ScriptTemplate redeemTemplate(redeemPattern);
            uchar_vector redeemscript = redeemTemplate.script(keyGroup.pubkeys());

            uchar_vector txoutscript;
            txoutscript << OP_HASH160 << pushStackItem(hash160(redeemscript)) << OP_EQUAL;

            uchar_vector txinscript;
            txinscript << OP_0 << emptySigs << pushStackItem(redeemscript);

            cout << "redeemscript:  " << redeemscript.getHex() << endl;
            cout << "txoutscript:   " << txoutscript.getHex() << endl;
            cout << "txinscript:    " << txinscript.getHex() << endl;
            cout << "address:       " << toBase58Check(hash160(redeemscript), ADDRESS_VERSIONS[1]) << endl;
        }
        else if (type == "cltv")
        {
            if (argc != 5) throw runtime_error(help(argv[0]));

            uchar_vector master_pubkey(argv[2]);
                if (master_pubkey.size() != 33) throw runtime_error("Invalid master pubkey.");

            uchar_vector timelock_pubkey(argv[3]);
                if (timelock_pubkey.size() != 33) throw runtime_error("Invalid timelock pubkey.");

            uint32_t locktime = strtoul(argv[4], NULL, 0);

            uchar_vector redeemPattern;
            redeemPattern   <<  OP_DUP
                            <<  OP_PUBKEY << 1 << OP_CHECKSIG
                            <<  OP_IF
                            <<      pushStackItem(CScriptNum::serialize(locktime))
                            <<      OP_CHECKLOCKTIMEVERIFY << OP_DROP
                            <<  OP_ELSE
                            <<      OP_PUBKEY << 0 << OP_CHECKSIG
                            <<  OP_ENDIF;

            ScriptTemplate redeemTemplate1(redeemPattern);
            ScriptTemplate redeemTemplate2(redeemTemplate1.script(master_pubkey));
            uchar_vector redeemscript = redeemTemplate2.script(timelock_pubkey);

            uchar_vector txoutscript;
            txoutscript << OP_HASH160 << pushStackItem(hash160(redeemscript)) << OP_EQUAL;

            uchar_vector txinscript;
            txinscript << OP_0 << pushStackItem(redeemscript);

            cout << "redeemscript:  " << redeemscript.getHex() << endl;
            cout << "txoutscript:   " << txoutscript.getHex() << endl;
            cout << "txinscript:    " << txinscript.getHex() << endl;
            cout << "address:       " << toBase58Check(hash160(redeemscript), ADDRESS_VERSIONS[1]) << endl;
/*
        redeemscript.push_back(OP_DUP);
        redeemscript += opPushData(locked_pubkey.size());
        redeemscript += locked_pubkey;
        redeemscript.push_back(OP_CHECKSIG);
        redeemscript.push_back(OP_IF);
            // We're using the locked pubkey
            redeemscript += opPushData(serialized_locktime.size());
            redeemscript += serialized_locktime;
            redeemscript.push_back(OP_CHECKLOCKTIMEVERIFY);
            redeemscript.push_back(OP_DROP);
        redeemscript.push_back(OP_ELSE);
            // We're using the unlocked pubkey
            redeemscript += opPushData(unlocked_pubkey.size());
            redeemscript += unlocked_pubkey;
            redeemscript.push_back(OP_CHECKSIG);
        redeemscript.push_back(OP_ENDIF);
*/
        }
        else if (type == "witness")
        {
            if (argc != 3) throw runtime_error(help(argv[0]));

            uchar_vector redeemscript(argv[2]);
            WitnessProgram wp(redeemscript);
            cout << "witnessscript: " << wp.witnessscript().getHex() << endl;
            cout << "redeemscript:  " << wp.redeemscript().getHex() << endl;
            cout << "txoutscript:   " << wp.txoutscript().getHex() << endl;
            cout << "txinscript:    " << wp.txinscript(). getHex() << endl;
            cout << "address:       " << wp.address(ADDRESS_VERSIONS) << endl;
        }
        else
        {
            throw runtime_error(help(argv[0]));
        }

    }
    catch (const exception& e)
    {
        cerr << e.what() << endl;
        return -2;
    }

    return 0;
}
<commit_msg>Use multistep ScriptTemplate reduction in example<commit_after>///////////////////////////////////////////////////////////////////////////////
//
// script templates example
//
// templates.cpp
//
// Copyright (c) 2012-2016 Eric Lombrozo
//
// All Rights Reserved.

#include <CoinQ/CoinQ_script.h>
#include <CoinQ/scriptnum.h>
#include <CoinCore/Base58Check.h>
#include <CoinCore/hash.h>

#include <iostream>
#include <sstream>
#include <stdexcept>
#include <string>

using namespace Coin;
using namespace CoinQ::Script;
using namespace std;

const unsigned char ADDRESS_VERSIONS[] = {30, 50};

string help(char* appName)
{
    stringstream ss;
    ss  << "# Usage: " << appName << " <type> [params]" << endl
        << "#   p2pk    <pubkey>" << endl
        << "#   p2pkh   <pubkey>" << endl
        << "#   mofn    <m> <pubkey1> [pubkey2] ..." << endl
        << "#   cltv    <master pubkey> <timelock pubkey> <locktime>" << endl
        << "#   witness <redeemscript>";
    return ss.str();
}

int main(int argc, char* argv[])
{
    if (argc < 2)
    {
        cerr << help(argv[0]) << endl;
        return -1;
    }

    try
    {
        string type(argv[1]);
        if (type == "p2pk")
        {
            if (argc != 3) throw runtime_error(help(argv[0]));

            uchar_vector pubkey(argv[2]);
            if (pubkey.size() != 33) throw runtime_error("Invalid pubkey length.");

            uchar_vector outPattern;
            outPattern << OP_PUBKEY << 0 << OP_CHECKSIG;
            ScriptTemplate outTemplate(outPattern);

            uchar_vector inPattern;
            inPattern << OP_0;
            ScriptTemplate inTemplate(inPattern);

            cout << "txoutscript:   " << outTemplate.script(pubkey).getHex() << endl;
            cout << "txinscript:    " << inTemplate.script(pubkey).getHex() << endl;
            cout << "address:       " << toBase58Check(hash160(pubkey), ADDRESS_VERSIONS[0]) << endl;
        }
        else if (type == "p2pkh")
        {
            if (argc != 3) throw runtime_error(help(argv[0]));

            uchar_vector pubkey(argv[2]);
            if (pubkey.size() != 33) throw runtime_error("Invalid pubkey length.");

            uchar_vector outPattern;
            outPattern << OP_DUP << OP_HASH160 << OP_PUBKEYHASH << 0 << OP_EQUALVERIFY << OP_CHECKSIG;
            ScriptTemplate outTemplate(outPattern);

            uchar_vector inPattern;
            inPattern << OP_0 << OP_PUBKEY << 0;
            ScriptTemplate inTemplate(inPattern);

            cout << "txoutscript:   " << outTemplate.script(pubkey).getHex() << endl;
            cout << "txinscript:    " << inTemplate.script(pubkey).getHex() << endl;
            cout << "address:       " << toBase58Check(hash160(pubkey), ADDRESS_VERSIONS[0]) << endl;
        }
        else if (type == "mofn")
        {
            if (argc < 4) throw runtime_error(help(argv[0]));

            int minsigs = strtol(argv[2], NULL, 0);
            if (minsigs < 1 || minsigs > 15)
                throw runtime_error("Invalid minsigs.");

            vector<bytes_t> pubkeys;
            for (int i = 3; i < argc; i++)
            {
                uchar_vector pubkey(argv[i]);
                if (pubkey.size() != 33) throw runtime_error("Invalid pubkey length.");

                pubkeys.push_back(pubkey);
            }
            if ((int)pubkeys.size() < minsigs || pubkeys.size() > 15)
                throw runtime_error("Invalid pubkey count.");

            uchar_vector redeemPattern, emptySigs;
            redeemPattern << (OP_1_OFFSET + minsigs);
            for (size_t i = 0; i < pubkeys.size(); i++)
            {
                redeemPattern << OP_PUBKEY << i;
                emptySigs << OP_0;
            }
            redeemPattern << (OP_1_OFFSET + pubkeys.size()) << OP_CHECKMULTISIG;

            SymmetricKeyGroup keyGroup(pubkeys);
            ScriptTemplate redeemTemplate(redeemPattern);
            uchar_vector redeemscript = redeemTemplate.script(keyGroup.pubkeys());

            uchar_vector txoutscript;
            txoutscript << OP_HASH160 << pushStackItem(hash160(redeemscript)) << OP_EQUAL;

            uchar_vector txinscript;
            txinscript << OP_0 << emptySigs << pushStackItem(redeemscript);

            cout << "redeemscript:  " << redeemscript.getHex() << endl;
            cout << "txoutscript:   " << txoutscript.getHex() << endl;
            cout << "txinscript:    " << txinscript.getHex() << endl;
            cout << "address:       " << toBase58Check(hash160(redeemscript), ADDRESS_VERSIONS[1]) << endl;
        }
        else if (type == "cltv")
        {
            if (argc != 5) throw runtime_error(help(argv[0]));

            uchar_vector master_pubkey(argv[2]);
                if (master_pubkey.size() != 33) throw runtime_error("Invalid master pubkey.");

            uchar_vector timelock_pubkey(argv[3]);
                if (timelock_pubkey.size() != 33) throw runtime_error("Invalid timelock pubkey.");

            uint32_t locktime = strtoul(argv[4], NULL, 0);

            uchar_vector redeemPattern;
            redeemPattern   <<  OP_DUP
                            <<  OP_PUBKEY << 1 << OP_CHECKSIG
                            <<  OP_IF
                            <<      pushStackItem(CScriptNum::serialize(locktime))
                            <<      OP_CHECKLOCKTIMEVERIFY << OP_DROP
                            <<  OP_ELSE
                            <<      OP_PUBKEY << 0 << OP_CHECKSIG
                            <<  OP_ENDIF;

            ScriptTemplate redeemTemplate(redeemPattern);
            redeemTemplate.reduce(master_pubkey);
            redeemTemplate.reduce(timelock_pubkey);
            uchar_vector redeemscript = redeemTemplate.script();

            uchar_vector txoutscript;
            txoutscript << OP_HASH160 << pushStackItem(hash160(redeemscript)) << OP_EQUAL;

            uchar_vector txinscript;
            txinscript << OP_0 << pushStackItem(redeemscript);

            cout << "redeemscript:  " << redeemscript.getHex() << endl;
            cout << "txoutscript:   " << txoutscript.getHex() << endl;
            cout << "txinscript:    " << txinscript.getHex() << endl;
            cout << "address:       " << toBase58Check(hash160(redeemscript), ADDRESS_VERSIONS[1]) << endl;
        }
        else if (type == "witness")
        {
            if (argc != 3) throw runtime_error(help(argv[0]));

            uchar_vector redeemscript(argv[2]);
            WitnessProgram wp(redeemscript);
            cout << "witnessscript: " << wp.witnessscript().getHex() << endl;
            cout << "redeemscript:  " << wp.redeemscript().getHex() << endl;
            cout << "txoutscript:   " << wp.txoutscript().getHex() << endl;
            cout << "txinscript:    " << wp.txinscript(). getHex() << endl;
            cout << "address:       " << wp.address(ADDRESS_VERSIONS) << endl;
        }
        else
        {
            throw runtime_error(help(argv[0]));
        }

    }
    catch (const exception& e)
    {
        cerr << e.what() << endl;
        return -2;
    }

    return 0;
}
<|endoftext|>


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

#include "cppuhelper/implbase3.hxx"
#include "cppuhelper/implementationentry.hxx"
#include "rtl/ustrbuf.hxx"
#include "rtl/ustring.h"
#include "rtl/ustring.hxx"
#include "sal/types.h"
#include "boost/scoped_array.hpp"
#include "com/sun/star/lang/XServiceInfo.hpp"
#include "com/sun/star/lang/XInitialization.hpp"
#include "com/sun/star/task/XJob.hpp"

namespace css = com::sun::star;

namespace migration
{

rtl::OUString jvmfwk_getImplementationName();

css::uno::Sequence< rtl::OUString > jvmfwk_getSupportedServiceNames();

css::uno::Reference< css::uno::XInterface > SAL_CALL jvmfwk_create(
    css::uno::Reference< css::uno::XComponentContext > const & )
    throw (css::uno::Exception);

} //end blind namespace

<commit_msg>INTEGRATION: CWS ooo19126 (1.3.178); FILE MERGED 2005/09/05 17:50:53 rt 1.3.178.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: jvmfwk.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 17:41:49 $
 *
 *  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
 *
 ************************************************************************/

#include "cppuhelper/implbase3.hxx"
#include "cppuhelper/implementationentry.hxx"
#include "rtl/ustrbuf.hxx"
#include "rtl/ustring.h"
#include "rtl/ustring.hxx"
#include "sal/types.h"
#include "boost/scoped_array.hpp"
#include "com/sun/star/lang/XServiceInfo.hpp"
#include "com/sun/star/lang/XInitialization.hpp"
#include "com/sun/star/task/XJob.hpp"

namespace css = com::sun::star;

namespace migration
{

rtl::OUString jvmfwk_getImplementationName();

css::uno::Sequence< rtl::OUString > jvmfwk_getSupportedServiceNames();

css::uno::Reference< css::uno::XInterface > SAL_CALL jvmfwk_create(
    css::uno::Reference< css::uno::XComponentContext > const & )
    throw (css::uno::Exception);

} //end blind namespace

<|endoftext|>