text:
#include <chrono>
#include <limits>
#include <memory>
#include <sstream>

#include "tests/utils/Gtest.h"
#include <boost/algorithm/string/predicate.hpp>

#include "joynr/BroadcastSubscriptionRequest.h"
#include "joynr/Directory.h"
#include "joynr/Logger.h"
#include "joynr/MulticastPublication.h"
#include "joynr/MulticastSubscriptionQos.h"
#include "joynr/MulticastSubscriptionRequest.h"
#include "joynr/OnChangeWithKeepAliveSubscriptionQos.h"
#include "joynr/Reply.h"
#include "joynr/Request.h"
#include "joynr/SingleThreadedIOService.h"
#include "joynr/SubscriptionPublication.h"
#include "joynr/SubscriptionRequest.h"
#include "joynr/Util.h"
#include "joynr/infrastructure/DacTypes/MasterAccessControlEntry.h"
#include "joynr/system/RoutingTypes/BrowserAddress.h"
#include "joynr/system/RoutingTypes/ChannelAddress.h"
#include "joynr/system/RoutingTypes/MqttAddress.h"
#include "joynr/system/RoutingTypes/WebSocketAddress.h"
#include "joynr/system/RoutingTypes/WebSocketClientAddress.h"
#include "joynr/tests/test/MethodWithErrorEnumExtendedErrorEnum.h"
#include "joynr/tests/testTypes/TestEnum.h"
#include "joynr/types/GlobalDiscoveryEntry.h"
#include "joynr/types/Localisation/Trip.h"
#include "joynr/types/ProviderQos.h"
#include "joynr/types/TestTypes/TEnum.h"
#include "joynr/types/TestTypes/TEverythingMap.h"
#include "joynr/types/TestTypes/TIntegerKeyMap.h"
#include "joynr/types/TestTypes/TStringKeyMap.h"
#include "joynr/types/TestTypes/TStringToByteBufferMap.h"
#include "joynr/types/TestTypes/TStruct.h"
#include "joynr/types/TestTypes/TStructComposition.h"
#include "joynr/types/TestTypes/TStructExtended.h"
#include "joynr/types/Version.h"

#include "tests/JoynrTest.h"
#include "tests/PrettyPrint.h"

using namespace joynr;

class JsonSerializerTest : public testing::Test
{
protected:
    ADD_LOGGER(JsonSerializerTest)
};

TEST_F(JsonSerializerTest, serialize_deserialize_SubscriptionRequest)
{
    SubscriptionRequest request;
    auto subscriptionQos = std::make_shared<SubscriptionQos>(5000);
    request.setQos(subscriptionQos);
    std::string result = joynr::serializer::serializeToJson(request);
    JOYNR_LOG_DEBUG(logger(), "result: {}", result);
    SubscriptionRequest desRequest;
    joynr::serializer::deserializeFromJson(desRequest, result);
    EXPECT_TRUE(request == desRequest);
}

TEST_F(JsonSerializerTest, serialize_deserialize_BroadcastSubscriptionRequest)
{
    BroadcastSubscriptionRequest request;
    auto qos = std::make_shared<OnChangeSubscriptionQos>(5000, 1000, 2000);
    request.setQos(qos);
    BroadcastFilterParameters filterParams;
    filterParams.setFilterParameter("MyFilter", "MyFilterValue");
    request.setFilterParameters(filterParams);
    request.setSubscribeToName("myAttribute");
    std::string requestJson = joynr::serializer::serializeToJson(request);
    JOYNR_LOG_DEBUG(logger(), requestJson);
    BroadcastSubscriptionRequest desRequest;
    joynr::serializer::deserializeFromJson(desRequest, requestJson);
    EXPECT_TRUE(request == desRequest);
}

TEST_F(JsonSerializerTest, serialize_deserialize_byte_array)
{

    // Build a list to test with
    using Uint8Vec = std::vector<std::uint8_t>;
    Uint8Vec expectedUint8Vector; //{0x01, 0x02, 0x03, 0xff, 0xfe, 0xfd};
    expectedUint8Vector.push_back(1);
    expectedUint8Vector.push_back(2);
    expectedUint8Vector.push_back(3);
    expectedUint8Vector.push_back(255);
    expectedUint8Vector.push_back(254);
    expectedUint8Vector.push_back(253);

    // Set the request method name
    joynr::Request request;
    request.setMethodName("serialize_deserialize_byte_array");

    // Set the request parameters
    request.setParamDatatypes({"List"});
    request.setParams(expectedUint8Vector);

    // Serialize the request
    std::string serializedRequestJson = joynr::serializer::serializeToJson(request);

    std::stringstream jsonStringStream;
    jsonStringStream << R"({"_typeName":"joynr.Request",)"
                     << R"("methodName":"serialize_deserialize_byte_array",)"
                     << R"("paramDatatypes":["List"],)"
                     << R"("params":[[1,2,3,255,254,253]],)"
                     << R"("requestReplyId":")" << request.getRequestReplyId() << R"("})";
    std::string expectedRequestJson = jsonStringStream.str();

    JOYNR_LOG_DEBUG(logger(), "expected: {}", expectedRequestJson);
    JOYNR_LOG_DEBUG(logger(), "serialized: {}", serializedRequestJson);
    EXPECT_EQ(expectedRequestJson, serializedRequestJson);

    // Deserialize the request
    joynr::Request deserializedRequest;
    joynr::serializer::deserializeFromJson(deserializedRequest, serializedRequestJson);
    Uint8Vec deserializedVector;
    deserializedRequest.getParams(deserializedVector);
    EXPECT_EQ(expectedUint8Vector, deserializedVector);
}

TEST_F(JsonSerializerTest, serialize_operation_with_multiple_params1)
{
    // Set the request method name
    joynr::Request request;
    request.setMethodName("methodEnumDoubleParameters");

    // Set the request parameters
    request.setParamDatatypes({"joynr.tests.testTypes.TestEnum.Enum", "Double"});
    request.setParams(tests::testTypes::TestEnum::ONE, 2.2);

    // Serialize the request
    std::string serializedContent = joynr::serializer::serializeToJson(request);

    std::stringstream expectedStringStream;
    expectedStringStream << R"({"_typeName":"joynr.Request",)";
    expectedStringStream << R"("methodName":"methodEnumDoubleParameters",)";
    expectedStringStream << R"("paramDatatypes":["joynr.tests.testTypes.TestEnum.Enum","Double"],)";
    expectedStringStream << R"("params":["ONE",2.2],)";
    expectedStringStream << R"("requestReplyId":")" << request.getRequestReplyId() << R"(")";
    expectedStringStream << R"(})";

    std::string expected = expectedStringStream.str();

    EXPECT_EQ(expected, serializedContent);
}

TEST_F(JsonSerializerTest, deserialize_operation_with_enum)
{

    tests::testTypes::TestEnum::Enum expectedEnumParam = tests::testTypes::TestEnum::ONE;
    double expectedDoubleParam = 2.2;

    // Deserialize a request containing a Java style enum parameter
    std::string serializedContent(
            R"({"_typeName":"joynr.Request",)"
            R"("methodName":"methodEnumDoubleParameters",)"
            R"("paramDatatypes":["joynr.tests.testTypes.TestEnum.Enum","Double"],)"
            R"("params":["ONE",2.2],)"
            R"("requestReplyId":"789eaj21312390"})");

    joynr::Request request;
    joynr::serializer::deserializeFromJson(request, serializedContent);

    tests::testTypes::TestEnum::Enum deserializedEnumParam;
    double deserializedDoubleParam;
    request.getParams(deserializedEnumParam, deserializedDoubleParam);

    EXPECT_EQ(expectedEnumParam, deserializedEnumParam);
    EXPECT_EQ(expectedDoubleParam, deserializedDoubleParam);
}

TEST_F(JsonSerializerTest, deserializeTypeWithEnumList)
{

    using namespace infrastructure::DacTypes;

    // Deserialize a type containing multiple enum lists
    std::string serializedContent(
            R"({"_typeName":"joynr.infrastructure.DacTypes.MasterAccessControlEntry",)"
            R"("defaultConsumerPermission": "NO",)"
            R"("defaultRequiredControlEntryChangeTrustLevel": "LOW",)"
            R"("defaultRequiredTrustLevel": "LOW",)"
            R"("domain": "unittest",)"
            R"("interfaceName": "vehicle/radio",)"
            R"("operation": "*",)"
            R"("possibleConsumerPermissions": ["YES","NO"],)"
            R"("possibleRequiredControlEntryChangeTrustLevels": ["HIGH","MID","LOW"],)"
            R"("possibleRequiredTrustLevels": ["HIGH","MID","LOW"],)"
            R"("uid": "*"})");

    infrastructure::DacTypes::MasterAccessControlEntry mac;
    joynr::serializer::deserializeFromJson(mac, serializedContent);

    // Check scalar enums
    EXPECT_EQ(Permission::NO, mac.getDefaultConsumerPermission());
    EXPECT_EQ(TrustLevel::LOW, mac.getDefaultRequiredTrustLevel());

    // Check enum lists
    std::vector<Permission::Enum> possibleRequiredPermissions;
    possibleRequiredPermissions.push_back(Permission::YES);
    possibleRequiredPermissions.push_back(Permission::NO);
    EXPECT_EQ(possibleRequiredPermissions, mac.getPossibleConsumerPermissions());

    std::vector<TrustLevel::Enum> possibleRequiredTrustLevels;
    possibleRequiredTrustLevels.push_back(TrustLevel::HIGH);
    possibleRequiredTrustLevels.push_back(TrustLevel::MID);
    possibleRequiredTrustLevels.push_back(TrustLevel::LOW);
    EXPECT_EQ(possibleRequiredTrustLevels, mac.getPossibleRequiredTrustLevels());
}

TEST_F(JsonSerializerTest, serializeDeserializeTypeWithEnumList)
{

    using namespace infrastructure::DacTypes;

    std::vector<TrustLevel::Enum> possibleTrustLevels;
    possibleTrustLevels.push_back(TrustLevel::LOW);
    possibleTrustLevels.push_back(TrustLevel::MID);
    possibleTrustLevels.push_back(TrustLevel::HIGH);
    std::vector<Permission::Enum> possiblePermissions;
    possiblePermissions.push_back(Permission::NO);
    possiblePermissions.push_back(Permission::ASK);
    possiblePermissions.push_back(Permission::YES);

    infrastructure::DacTypes::MasterAccessControlEntry expectedMac(R"(*)",
                                                                   R"(unittest)",
                                                                   R"(vehicle/radio)",
                                                                   TrustLevel::LOW,
                                                                   possibleTrustLevels,
                                                                   TrustLevel::HIGH,
                                                                   possibleTrustLevels,
                                                                   R"(*)",
                                                                   Permission::YES,
                                                                   possiblePermissions);

    // Serialize
    std::string serializedContent = joynr::serializer::serializeToJson(expectedMac);
    JOYNR_LOG_DEBUG(logger(), "Serialized expectedMac: {}", serializedContent);

    // Deserialize the result
    infrastructure::DacTypes::MasterAccessControlEntry mac;
    joynr::serializer::deserializeFromJson(mac, serializedContent);

    // Check that the object serialized/deserialized correctly
    EXPECT_EQ(expectedMac, mac);
}

using namespace infrastructure::DacTypes;

void deserializePermission(const std::string& serializedPermission,
                           const Permission::Enum& expectation)
{
    // Deserialize the result and compare
    Permission::Enum deserializedEnum;
    joynr::serializer::deserializeFromJson(deserializedEnum, serializedPermission);
    EXPECT_EQ(expectation, deserializedEnum);
}

void serializeAndDeserializePermission(const Permission::Enum& input,
                                       const std::string& inputAsString,
                                       Logger& logger)
{
    // Serialize
    std::string serializedContent = joynr::serializer::serializeToJson(input);
    JOYNR_LOG_DEBUG(
            logger, "Serialized permission for input: {}, {}", inputAsString, serializedContent);

    deserializePermission(serializedContent, input);
}

TEST_F(JsonSerializerTest, serializeDeserializeTypeEnum)
{
    using namespace infrastructure::DacTypes;

    JOYNR_ASSERT_NO_THROW(serializeAndDeserializePermission(Permission::NO, R"("NO")", logger()));

    ASSERT_ANY_THROW(
            serializeAndDeserializePermission(static_cast<Permission::Enum>(999), "999", logger()));
}

TEST_F(JsonSerializerTest, deserializeTypeEnum)
{
    using namespace infrastructure::DacTypes;

    JOYNR_ASSERT_NO_THROW(deserializePermission(R"("NO")", Permission::NO));

    ASSERT_ANY_THROW(deserializePermission("999", static_cast<Permission::Enum>(999)));
}

TEST_F(JsonSerializerTest, serialize_operation_with_multiple_params2)
{

    // Set the request method name
    Request request;
    request.setMethodName("methodStringDoubleParameters");

    // Set the request parameters
    request.setParamDatatypes({"String", "Double", "Float"});
    request.setParams("testStringParam", 3.33, 1.25e-9f);

    // Serialize the request
    std::string serializedContent = joynr::serializer::serializeToJson(request);

    std::stringstream expectedStringStream;
    expectedStringStream << R"({"_typeName":"joynr.Request",)";
    expectedStringStream << R"("methodName":"methodStringDoubleParameters",)";
    expectedStringStream << R"("paramDatatypes":["String","Double","Float"],)";
    expectedStringStream << R"("params":["testStringParam",3.33,1.2499999924031613e-9],)";
    expectedStringStream << R"("requestReplyId":")" << request.getRequestReplyId() << R"(")";
    expectedStringStream << R"(})";

    std::string expected = expectedStringStream.str();

    JOYNR_LOG_DEBUG(logger(), "Serialized method call: {}", serializedContent);
    JOYNR_LOG_DEBUG(logger(), "Expected method call: {}", expected);

    EXPECT_EQ(expected, serializedContent);
}

TEST_F(JsonSerializerTest, serialize_deserialize_TStruct)
{

    types::TestTypes::TStruct tStruct;
    tStruct.setTDouble(0.123456789);
    tStruct.setTInt64(64);
    tStruct.setTString("myTestString");

    std::string expectedTStruct(R"({)"
                                R"("_typeName":"joynr.types.TestTypes.TStruct",)"
                                R"("tDouble":0.123456789,)"
                                R"("tInt64":64,)"
                                R"("tString":"myTestString")"
                                R"(})");

    std::string serializedContent = joynr::serializer::serializeToJson(tStruct);
    JOYNR_LOG_DEBUG(logger(), serializedContent);
    EXPECT_EQ(expectedTStruct, serializedContent);

    types::TestTypes::TStruct tStructDeserialized;
    joynr::serializer::deserializeFromJson(tStructDeserialized, serializedContent);

    EXPECT_EQ(tStruct, tStructDeserialized);
}

TEST_F(JsonSerializerTest, serialize_deserialize_TStructExtended)
{

    types::TestTypes::TStructExtended tStructExt;
    tStructExt.setTDouble(0.123456789);
    tStructExt.setTInt64(64);
    tStructExt.setTString("myTestString");
    tStructExt.setTEnum(types::TestTypes::TEnum::TLITERALA);
    tStructExt.setTInt32(32);

    std::string expectedTStructExt(R"({)"
                                   R"("_typeName":"joynr.types.TestTypes.TStructExtended",)"
                                   R"("tDouble":0.123456789,)"
                                   R"("tInt64":64,)"
                                   R"("tString":"myTestString",)"
                                   R"("tEnum":"TLITERALA",)"
                                   R"("tInt32":32)"
                                   R"(})");

    std::string serializedTStructExt = joynr::serializer::serializeToJson(tStructExt);
    JOYNR_LOG_DEBUG(logger(), serializedTStructExt);

    EXPECT_EQ(expectedTStructExt, serializedTStructExt);
    types::TestTypes::TStructExtended deserializedTStructExt;
    joynr::serializer::deserializeFromJson(deserializedTStructExt, serializedTStructExt);

    EXPECT_EQ(tStructExt, deserializedTStructExt);
}

TEST_F(JsonSerializerTest, serialize_deserialize_replyWithGpsLocation)
{
    types::Localisation::GpsLocation gps1(1.1,
                                          1.2,
                                          1.3,
                                          types::Localisation::GpsFixEnum::MODE3D,
                                          1.4,
                                          1.5,
                                          1.6,
                                          1.7,
                                          18,
                                          19,
                                          110);

    // Expected literal is:
    Reply reply;
    reply.setRequestReplyId("TEST-requestReplyId");
    reply.setResponse(gps1);

    std::stringstream expectedReplyStringStream;
    expectedReplyStringStream << R"({)";
    expectedReplyStringStream << R"("_typeName":"joynr.Reply",)";
    expectedReplyStringStream << R"("response":[{)";
    expectedReplyStringStream << R"("_typeName":"joynr.types.Localisation.GpsLocation",)";
    expectedReplyStringStream << R"("longitude":1.1,)";
    expectedReplyStringStream << R"("latitude":1.2,)";
    expectedReplyStringStream << R"("altitude":1.3,)";
    expectedReplyStringStream << R"("gpsFix":"MODE3D",)";
    expectedReplyStringStream << R"("heading":1.4,)";
    expectedReplyStringStream << R"("quality":1.5,)";
    expectedReplyStringStream << R"("elevation":1.6,)";
    expectedReplyStringStream << R"("bearing":1.7,)";
    expectedReplyStringStream << R"("gpsTime":18,)";
    expectedReplyStringStream << R"("deviceTime":19,)";
    expectedReplyStringStream << R"("time":110)";
    expectedReplyStringStream << R"(}],)";
    expectedReplyStringStream << R"("requestReplyId":")" << reply.getRequestReplyId() << R"(")";
    expectedReplyStringStream << R"(})";

    std::string expectedReply = expectedReplyStringStream.str();

    std::string jsonReply = joynr::serializer::serializeToJson(reply);

    EXPECT_EQ(expectedReply, jsonReply);

    joynr::Reply receivedReply;
    joynr::serializer::deserializeFromJson(receivedReply, jsonReply);

    EXPECT_TRUE(receivedReply.hasResponse());

    types::Localisation::GpsLocation receivedGps;
    receivedReply.getResponse(receivedGps);

    EXPECT_EQ(gps1, receivedGps);
}

TEST_F(JsonSerializerTest, deserialize_replyWithVoid)
{

    joynr::Reply reply;
    reply.setRequestReplyId("TEST-requestReplyId");
    // void response
    reply.setResponse();

    std::stringstream expectedStringStream;
    expectedStringStream << R"({"_typeName":"joynr.Reply",)";
    expectedStringStream << R"("response":[],)";
    expectedStringStream << R"("requestReplyId":")" << reply.getRequestReplyId() << R"("})";
    std::string expected = expectedStringStream.str();

    std::string jsonReply = joynr::serializer::serializeToJson(reply);

    EXPECT_EQ(expected, jsonReply);

    JOYNR_LOG_DEBUG(logger(), "Serialized Reply: {}", jsonReply);

    joynr::Reply receivedReply;
    joynr::serializer::deserializeFromJson(receivedReply, jsonReply);
    EXPECT_EQ(reply, receivedReply);
}

TEST_F(JsonSerializerTest, serialize_deserialize_replyWithGpsLocationList)
{

    using GpsLocationList = std::vector<types::Localisation::GpsLocation>;
    GpsLocationList locList;
    locList.emplace_back(
            1.1, 2.2, 3.3, types::Localisation::GpsFixEnum::MODE3D, 0.0, 0.0, 0.0, 0.0, 0, 0, 17);
    locList.emplace_back(4.4,
                         5.5,
                         6.6,
                         types::Localisation::GpsFixEnum::MODENOFIX,
                         0.0,
                         0.0,
                         0.0,
                         0.0,
                         0,
                         0,
                         18);

    joynr::Reply reply;
    reply.setRequestReplyId("TEST-requestReplyId");
    reply.setResponse(locList);

    // Expected literal
    std::stringstream expectedReplyStringStream;
    expectedReplyStringStream << R"({)";
    expectedReplyStringStream << R"("_typeName":"joynr.Reply",)";
    expectedReplyStringStream << R"("response":[[{)";
    expectedReplyStringStream << R"("_typeName":"joynr.types.Localisation.GpsLocation",)";
    expectedReplyStringStream << R"("longitude":1.1,)";
    expectedReplyStringStream << R"("latitude":2.2,)";
    expectedReplyStringStream << R"("altitude":3.3,)";
    expectedReplyStringStream << R"("gpsFix":"MODE3D",)";
    expectedReplyStringStream << R"("heading":0.0,)";
    expectedReplyStringStream << R"("quality":0.0,)";
    expectedReplyStringStream << R"("elevation":0.0,)";
    expectedReplyStringStream << R"("bearing":0.0,)";
    expectedReplyStringStream << R"("gpsTime":0,)";
    expectedReplyStringStream << R"("deviceTime":0,)";
    expectedReplyStringStream << R"("time":17)";
    expectedReplyStringStream << R"(},{)";
    expectedReplyStringStream << R"("_typeName":"joynr.types.Localisation.GpsLocation",)";
    expectedReplyStringStream << R"("longitude":4.4,)";
    expectedReplyStringStream << R"("latitude":5.5,)";
    expectedReplyStringStream << R"("altitude":6.6,)";
    expectedReplyStringStream << R"("gpsFix":"MODENOFIX",)";
    expectedReplyStringStream << R"("heading":0.0,)";
    expectedReplyStringStream << R"("quality":0.0,)";
    expectedReplyStringStream << R"("elevation":0.0,)";
    expectedReplyStringStream << R"("bearing":0.0,)";
    expectedReplyStringStream << R"("gpsTime":0,)";
    expectedReplyStringStream << R"("deviceTime":0,)";
    expectedReplyStringStream << R"("time":18)";
    expectedReplyStringStream << R"(}]],)";
    expectedReplyStringStream << R"("requestReplyId":")" << reply.getRequestReplyId() << R"(")";
    expectedReplyStringStream << R"(})";

    std::string expectedReply = expectedReplyStringStream.str();

    std::string jsonReply = joynr::serializer::serializeToJson(reply);
    JOYNR_LOG_DEBUG(logger(), jsonReply);
    EXPECT_EQ(expectedReply, jsonReply);

    joynr::Reply receivedReply;
    joynr::serializer::deserializeFromJson(receivedReply, jsonReply);

    GpsLocationList receivedLocList;
    receivedReply.getResponse(receivedLocList);

    EXPECT_EQ(locList, receivedLocList);
}

TEST_F(JsonSerializerTest, serialize_deserialize_trip)
{
    std::vector<types::Localisation::GpsLocation> locations;
    locations.push_back(types::Localisation::GpsLocation(
            1.1, 2.2, 3.3, types::Localisation::GpsFixEnum::MODE3D, 0.0, 0.0, 0.0, 0.0, 0, 0, 17));
    locations.push_back(types::Localisation::GpsLocation(
            4.4, 5.5, 6.6, types::Localisation::GpsFixEnum::MODE3D, 0.0, 0.0, 0.0, 0.0, 0, 0, 317));
    locations.push_back(types::Localisation::GpsLocation(7.7,
                                                         8.8,
                                                         9.9,
                                                         types::Localisation::GpsFixEnum::MODE3D,
                                                         0.0,
                                                         0.0,
                                                         0.0,
                                                         0.0,
                                                         0,
                                                         0,
                                                         3317));

    std::string expected(R"({"_typeName":"joynr.types.Localisation.Trip",)"
                         R"("locations":[{"_typeName":"joynr.types.Localisation.GpsLocation",)"
                         R"("longitude":1.1,)"
                         R"("latitude":2.2,)"
                         R"("altitude":3.3,)"
                         R"("gpsFix":"MODE3D",)"
                         R"("heading":0.0,)"
                         R"("quality":0.0,)"
                         R"("elevation":0.0,)"
                         R"("bearing":0.0,)"
                         R"("gpsTime":0,)"
                         R"("deviceTime":0,)"
                         R"("time":17},)"
                         R"({"_typeName":"joynr.types.Localisation.GpsLocation",)"
                         R"("longitude":4.4,)"
                         R"("latitude":5.5,)"
                         R"("altitude":6.6,)"
                         R"("gpsFix":"MODE3D",)"
                         R"("heading":0.0,)"
                         R"("quality":0.0,)"
                         R"("elevation":0.0,)"
                         R"("bearing":0.0,)"
                         R"("gpsTime":0,)"
                         R"("deviceTime":0,)"
                         R"("time":317},)"
                         R"({"_typeName":"joynr.types.Localisation.GpsLocation",)"
                         R"("longitude":7.7,)"
                         R"("latitude":8.8,)"
                         R"("altitude":9.9,)"
                         R"("gpsFix":"MODE3D",)"
                         R"("heading":0.0,)"
                         R"("quality":0.0,)"
                         R"("elevation":0.0,)"
                         R"("bearing":0.0,)"
                         R"("gpsTime":0,)"
                         R"("deviceTime":0,)"
                         R"("time":3317}],)"
                         R"("tripTitle":"trip1_name"})");

    // Expected literal is:
    types::Localisation::Trip trip1(locations, "trip1_name");

    std::string serializedContent = joynr::serializer::serializeToJson(trip1);
    EXPECT_EQ(expected, serializedContent);

    types::Localisation::Trip trip2;
    joynr::serializer::deserializeFromJson(trip2, serializedContent);
    EXPECT_EQ(trip1, trip2) << "trips \n trip1: " << trip1.toString().c_str()
                            << " and \n trip2: " << trip2.toString().c_str()
                            << "\n are not the same";
}

TEST_F(JsonSerializerTest, serialize_deserialize_JsonRequestWithLists)
{

    // creating Request
    using GpsLocationList = std::vector<types::Localisation::GpsLocation>;
    GpsLocationList inputLocationList;
    inputLocationList.push_back(types::Localisation::GpsLocation(
            1.1, 2.2, 3.3, types::Localisation::GpsFixEnum::MODE3D, 0.0, 0.0, 0.0, 0.0, 0, 0, 17));
    inputLocationList.push_back(types::Localisation::GpsLocation(
            4.4, 5.5, 6.6, types::Localisation::GpsFixEnum::MODE3D, 0.0, 0.0, 0.0, 0.0, 0, 0, 317));
    inputLocationList.push_back(
            types::Localisation::GpsLocation(7.7,
                                             8.8,
                                             9.9,
                                             types::Localisation::GpsFixEnum::MODE3D,
                                             0.0,
                                             0.0,
                                             0.0,
                                             0.0,
                                             0,
                                             0,
                                             3317));

    joynr::Request request1;
    request1.setMethodName("serialize_deserialize_JsonRequestTest_method");
    request1.setParams(inputLocationList);
    request1.setParamDatatypes({"List"});

    std::stringstream expectedStringStream;
    expectedStringStream << R"({"_typeName":"joynr.Request",)";
    expectedStringStream << R"("methodName":"serialize_deserialize_JsonRequestTest_method",)";
    expectedStringStream << R"("paramDatatypes":["List"],)";
    expectedStringStream << R"("params":[[{"_typeName":"joynr.types.Localisation.GpsLocation",)";
    expectedStringStream << R"("longitude":1.1,)";
    expectedStringStream << R"("latitude":2.2,)";
    expectedStringStream << R"("altitude":3.3,)";
    expectedStringStream << R"("gpsFix":"MODE3D",)";
    expectedStringStream << R"("heading":0.0,)";
    expectedStringStream << R"("quality":0.0,)";
    expectedStringStream << R"("elevation":0.0,)";
    expectedStringStream << R"("bearing":0.0,)";
    expectedStringStream << R"("gpsTime":0,)";
    expectedStringStream << R"("deviceTime":0,)";
    expectedStringStream << R"("time":17},)";
    expectedStringStream << R"({"_typeName":"joynr.types.Localisation.GpsLocation",)";
    expectedStringStream << R"("longitude":4.4,)";
    expectedStringStream << R"("latitude":5.5,)";
    expectedStringStream << R"("altitude":6.6,)";
    expectedStringStream << R"("gpsFix":"MODE3D",)";
    expectedStringStream << R"("heading":0.0,)";
    expectedStringStream << R"("quality":0.0,)";
    expectedStringStream << R"("elevation":0.0,)";
    expectedStringStream << R"("bearing":0.0,)";
    expectedStringStream << R"("gpsTime":0,)";
    expectedStringStream << R"("deviceTime":0,)";
    expectedStringStream << R"("time":317},)";
    expectedStringStream << R"({"_typeName":"joynr.types.Localisation.GpsLocation",)";
    expectedStringStream << R"("longitude":7.7,)";
    expectedStringStream << R"("latitude":8.8,)";
    expectedStringStream << R"("altitude":9.9,)";
    expectedStringStream << R"("gpsFix":"MODE3D",)";
    expectedStringStream << R"("heading":0.0,)";
    expectedStringStream << R"("quality":0.0,)";
    expectedStringStream << R"("elevation":0.0,)";
    expectedStringStream << R"("bearing":0.0,)";
    expectedStringStream << R"("gpsTime":0,)";
    expectedStringStream << R"("deviceTime":0,)";
    expectedStringStream << R"("time":3317}]],)";
    expectedStringStream << R"("requestReplyId":")" << request1.getRequestReplyId() << R"("})";

    std::string expected = expectedStringStream.str();

    // serializing Request
    std::string serializedContent = joynr::serializer::serializeToJson(request1);
    EXPECT_EQ(expected, serializedContent);

    // deserializing Request
    joynr::Request request2;
    joynr::serializer::deserializeFromJson(request2, serializedContent);
    GpsLocationList deserializedLocationList;
    request2.getParams(deserializedLocationList);
    EXPECT_EQ(inputLocationList, deserializedLocationList);
}

TEST_F(JsonSerializerTest, serialize_deserialize_EndpointAddress)
{
    joynr::system::RoutingTypes::ChannelAddress joynr(
            "TEST_channelId", "TEST_messagingEndpointUrl");
    joynr::system::RoutingTypes::WebSocketAddress wsServer(
            joynr::system::RoutingTypes::WebSocketProtocol::WS, "localhost", 42, "some/path");
    joynr::system::RoutingTypes::WebSocketClientAddress wsClient("TEST_clientId");

    // serialize
    std::string joynrSerialized = joynr::serializer::serializeToJson(joynr);
    std::string wsServerSerialized = joynr::serializer::serializeToJson(wsServer);
    std::string wsClientSerialized = joynr::serializer::serializeToJson(wsClient);

    JOYNR_LOG_DEBUG(logger(), "serialized Joynr address: {}", joynrSerialized);
    JOYNR_LOG_DEBUG(logger(), "serialized WS server address: {}", wsServerSerialized);
    JOYNR_LOG_DEBUG(logger(), "serialized WS client address: {}", wsClientSerialized);

    // deserialize
    joynr::system::RoutingTypes::ChannelAddress joynrDeserialized;
    joynr::serializer::deserializeFromJson(joynrDeserialized, joynrSerialized);
    joynr::system::RoutingTypes::WebSocketAddress wsServerDeserialized;
    joynr::serializer::deserializeFromJson(wsServerDeserialized, wsServerSerialized);
    joynr::system::RoutingTypes::WebSocketClientAddress wsClientDeserialized;
    joynr::serializer::deserializeFromJson(wsClientDeserialized, wsClientSerialized);

    EXPECT_EQ(joynr, joynrDeserialized);
    EXPECT_EQ(wsServer, wsServerDeserialized);
    EXPECT_EQ(wsClient, wsClientDeserialized);
}

TEST_F(JsonSerializerTest, serialize_deserialize_GlobalDiscoveryEntry)
{

    std::string expected(
            R"({"_typeName":"joynr.types.GlobalDiscoveryEntry",)"
            R"("providerVersion":{"_typeName":"joynr.types.Version","majorVersion":-1,")"
            R"(minorVersion":-1},)"
            R"("domain":"domain",)"
            R"("interfaceName":"testInterface",)"
            R"("participantId":"someParticipant",)"
            R"("qos":{)"
            R"("_typeName":"joynr.types.ProviderQos",)"
            R"("customParameters":[],)"
            R"("priority":2,)"
            R"("scope":"GLOBAL",)"
            R"("supportsOnChangeSubscriptions":false},)"
            R"("lastSeenDateMs":123,)"
            R"("expiryDateMs":1234,)"
            R"("publicKeyId":"publicKeyId",)"
            R"("address":"serialized_address"})");

    types::ProviderQos qos;
    qos.setPriority(2);
    types::GlobalDiscoveryEntry globalDiscoveryEntry;
    globalDiscoveryEntry.setDomain("domain");
    globalDiscoveryEntry.setQos(qos);
    globalDiscoveryEntry.setLastSeenDateMs(123);
    globalDiscoveryEntry.setExpiryDateMs(1234);
    globalDiscoveryEntry.setParticipantId("someParticipant");
    globalDiscoveryEntry.setAddress("serialized_address");
    globalDiscoveryEntry.setInterfaceName("testInterface");
    globalDiscoveryEntry.setPublicKeyId("publicKeyId");
    JOYNR_LOG_DEBUG(logger(), "GlobalDiscoveryEntry {}", globalDiscoveryEntry.toString());

    std::string serialized = joynr::serializer::serializeToJson(globalDiscoveryEntry);
    JOYNR_LOG_DEBUG(logger(), "serialized GlobalDiscoveryEntry {} ", serialized);
    EXPECT_EQ(expected, serialized);

    types::GlobalDiscoveryEntry deserializedGDE;
    joynr::serializer::deserializeFromJson(deserializedGDE, serialized);

    EXPECT_EQ(globalDiscoveryEntry, deserializedGDE);
    JOYNR_LOG_DEBUG(logger(), "deserialized GlobalDiscoveryEntry {}", deserializedGDE.toString());
}

TEST_F(JsonSerializerTest, deserialize_ProviderQos)
{
    joynr::types::ProviderQos qos;

    std::string jsonProviderQos("{\"_typeName\":\"joynr.types.ProviderQos\",\"customParameters\":[]"
                                ",\"priority\":5,\"scope\":\"LOCAL\","
                                "\"supportsOnChangeSubscriptions\":false}");

    joynr::types::ProviderQos providerQos;
    joynr::serializer::deserializeFromJson(providerQos, jsonProviderQos);

    EXPECT_EQ(providerQos.getScope(), joynr::types::ProviderScope::LOCAL);
    EXPECT_EQ(providerQos.getPriority(), 5);
}

TEST_F(JsonSerializerTest, serialize_ProviderQos)
{
    joynr::types::ProviderQos qos;
    qos.setScope(joynr::types::ProviderScope::LOCAL);
    qos.setPriority(5);

    std::string jsonProviderQos("{\"_typeName\":\"joynr.types.ProviderQos\",\"customParameters\":[]"
                                ",\"priority\":5,\"scope\":\"LOCAL\","
                                "\"supportsOnChangeSubscriptions\":false}");

    std::string result = joynr::serializer::serializeToJson(qos);

    EXPECT_EQ(jsonProviderQos, result);
}

TEST_F(JsonSerializerTest, deserialize_GPSLocation)
{

    std::string jsonGPS(R"({"_typeName":"joynr.types.Localisation.GpsLocation",)"
                        R"("longitude": 1.1,)"
                        R"("latitude": 2.2,)"
                        R"("altitude": 3.3,)"
                        R"("gpsFix": "MODE3D",)"
                        R"("heading": 0.0,)"
                        R"("quality": 0.0,)"
                        R"("elevation": 0.0,)"
                        R"("bearing": 0.0,)"
                        R"("gpsTime": 0,)"
                        R"("deviceTime": 0,)"
                        R"("time": 17})");

    joynr::types::Localisation::GpsLocation receivedGps;
    joynr::serializer::deserializeFromJson(receivedGps, jsonGPS);
    EXPECT_EQ(3.3, receivedGps.getAltitude());
}

TEST_F(JsonSerializerTest, serialize_OnchangeWithKeepAliveSubscription)
{

    OnChangeWithKeepAliveSubscriptionQos qos(750, 1000, 100, 900, 1050);

    std::string jsonQos = joynr::serializer::serializeToJson(qos);
    JOYNR_LOG_DEBUG(logger(), "serialized OnChangeWithKeepAliveSubscriptionQos {}", jsonQos);

    OnChangeWithKeepAliveSubscriptionQos desQos;
    joynr::serializer::deserializeFromJson(desQos, jsonQos);

    jsonQos = joynr::serializer::serializeToJson(desQos);
    JOYNR_LOG_DEBUG(logger(), "serialized OnChangeWithKeepAliveSubscriptionQos {}", jsonQos);

    EXPECT_EQ(qos, desQos);
}

struct RoutingEntry {
    RoutingEntry() : address(nullptr), isGloballyVisible(true)
    {
    }
    explicit RoutingEntry(std::shared_ptr<const joynr::system::RoutingTypes::Address> addressLocal,
                          bool isGloballyVisibleLocal)
            : address(std::move(addressLocal)), isGloballyVisible(isGloballyVisibleLocal)
    {
    }

    template <typename Archive>
    void serialize(Archive& archive)
    {
        archive(MUESLI_NVP(address), MUESLI_NVP(isGloballyVisible));
    }

    std::shared_ptr<const joynr::system::RoutingTypes::Address> address;
    bool isGloballyVisible;
};

TEST_F(JsonSerializerTest, RoutingTypeAddressesSerializerTest)
{
    using RoutingTable = Directory<std::string, RoutingEntry>;
    auto singleThreadedIoService = std::make_shared<SingleThreadedIOService>();
    RoutingTable routingTable("routingTable", singleThreadedIoService->getIOService());

    bool isGloballyVisible = true;
    auto ptrToRoutingWebSocketEntry = std::make_shared<RoutingEntry>(
            std::make_shared<joynr::system::RoutingTypes::WebSocketAddress>(), !isGloballyVisible);
    auto ptrToRoutingChannelAddressEntry = std::make_shared<RoutingEntry>(
            std::make_shared<joynr::system::RoutingTypes::ChannelAddress>(), isGloballyVisible);
    auto ptrToRoutingMqttAddressEntry = std::make_shared<RoutingEntry>(
            std::make_shared<joynr::system::RoutingTypes::MqttAddress>(), isGloballyVisible);
    auto ptrToRoutingBrowserAddressEntry = std::make_shared<RoutingEntry>(
            std::make_shared<joynr::system::RoutingTypes::BrowserAddress>(), !isGloballyVisible);
    auto ptrToRoutingWebSocketClientAddressEntry = std::make_shared<RoutingEntry>(
            std::make_shared<joynr::system::RoutingTypes::WebSocketClientAddress>(),
            !isGloballyVisible);

    routingTable.add("WebSocketAddress", ptrToRoutingWebSocketEntry);
    routingTable.add("ChannelAddress", ptrToRoutingChannelAddressEntry);
    routingTable.add("MqttAddress", ptrToRoutingMqttAddressEntry);
    routingTable.add("BrowserAddress", ptrToRoutingBrowserAddressEntry);
    routingTable.add("WebSocketClientAddress", ptrToRoutingWebSocketClientAddressEntry);

    const std::string serializedRoutingTable = joynr::serializer::serializeToJson(routingTable);
    JOYNR_LOG_TRACE(logger(), serializedRoutingTable);

    RoutingTable deserializedRoutingTable(
            "deserializedRoutingTable", singleThreadedIoService->getIOService());
    joynr::serializer::deserializeFromJson(deserializedRoutingTable, serializedRoutingTable);

    EXPECT_TRUE(boost::starts_with(
            deserializedRoutingTable.lookup("WebSocketAddress")->address->toString(),
            "WebSocketAddress"));
    EXPECT_TRUE(boost::starts_with(
            deserializedRoutingTable.lookup("ChannelAddress")->address->toString(),
            "ChannelAddress"));
    EXPECT_TRUE(boost::starts_with(
            deserializedRoutingTable.lookup("MqttAddress")->address->toString(), "MqttAddress"));
    EXPECT_TRUE(boost::starts_with(
            deserializedRoutingTable.lookup("BrowserAddress")->address->toString(),
            "BrowserAddress"));
    EXPECT_TRUE(boost::starts_with(
            deserializedRoutingTable.lookup("WebSocketClientAddress")->address->toString(),
            "WebSocketClientAddress"));

    EXPECT_FALSE(deserializedRoutingTable.lookup("WebSocketAddress")->isGloballyVisible);
    EXPECT_TRUE(deserializedRoutingTable.lookup("ChannelAddress")->isGloballyVisible);
    EXPECT_TRUE(deserializedRoutingTable.lookup("MqttAddress")->isGloballyVisible);
    EXPECT_FALSE(deserializedRoutingTable.lookup("BrowserAddress")->isGloballyVisible);
    EXPECT_FALSE(deserializedRoutingTable.lookup("WebSocketClientAddress")->isGloballyVisible);
}

TEST_F(JsonSerializerTest, exampleDeserializerApplicationException)
{
    std::string literal = joynr::tests::test::MethodWithErrorEnumExtendedErrorEnum::getLiteral(
            joynr::tests::test::MethodWithErrorEnumExtendedErrorEnum::BASE_ERROR_TYPECOLLECTION);
    // Create a ApplicationException
    exceptions::ApplicationException exception(
            literal,
            std::make_shared<joynr::tests::test::MethodWithErrorEnumExtendedErrorEnum>(literal));

    // Serialize into JSON
    std::string json = joynr::serializer::serializeToJson(exception);
    JOYNR_LOG_TRACE(logger(), "exceptions::ApplicationException JSON: {}", json);

    // Deserialize from JSON
    exceptions::ApplicationException t;
    joynr::serializer::deserializeFromJson(t, json);
    ASSERT_EQ(t.getMessage(), exception.getMessage());
    ASSERT_EQ(t.getName(), exception.getName());
}

TEST_F(JsonSerializerTest, exampleDeserializerProviderRuntimeException)
{
    // Create a ProviderRuntimeException
    exceptions::ProviderRuntimeException exception;
    std::string detailMessage{"Message of ProviderRuntimeException"};
    exception.setMessage(detailMessage);

    // Serialize into JSON
    std::string json = joynr::serializer::serializeToJson(exception);
    JOYNR_LOG_TRACE(logger(), "exceptions::ProviderRuntimeException JSON: {}", json);

    // Deserialize from JSON

    exceptions::ProviderRuntimeException t;
    joynr::serializer::deserializeFromJson(t, json);
    ASSERT_EQ(t.getMessage(), detailMessage);
}

TEST_F(JsonSerializerTest, exampleDeserializerDiscoveryException)
{
    // Create a DiscoveryException
    exceptions::DiscoveryException exception;
    std::string detailMessage{"Message of DiscoveryException"};
    exception.setMessage(detailMessage);

    // Serialize into JSON
    std::string json = joynr::serializer::serializeToJson(exception);
    JOYNR_LOG_TRACE(logger(), "exceptions::DiscoveryException JSON: {}", json);

    // Deserialize from JSON

    exceptions::DiscoveryException t;
    joynr::serializer::deserializeFromJson(t, json);
    ASSERT_EQ(t.getMessage(), detailMessage);
}

TEST_F(JsonSerializerTest, exampleDeserializerMethodInvocationException)
{
    // Create a MethodInvocationException
    exceptions::MethodInvocationException exception;
    std::string expectedDetailMessage{"Message of MethodInvocationException"};
    types::Version expectedProviderVersion(47, 11);
    exception.setMessage(expectedDetailMessage);
    exception.setProviderVersion(expectedProviderVersion);

    // Serialize into JSON
    std::string json = joynr::serializer::serializeToJson(exception);
    JOYNR_LOG_TRACE(logger(), "exceptions::MethodInvocationException JSON: {}", json);

    // Deserialize from JSON
    exceptions::MethodInvocationException deserializedException;
    joynr::serializer::deserializeFromJson(deserializedException, json);
    ASSERT_EQ(expectedDetailMessage, deserializedException.getMessage());
    ASSERT_EQ(expectedProviderVersion, deserializedException.getProviderVersion());
}

TEST_F(JsonSerializerTest, serializeDeserializerEmptyStruct)
{
    // Create a PublicationMissedException
    using namespace joynr::system::RoutingTypes;

    // fully qualified type required here to avoid ambiguity with
    // gtest/gmock Address
    joynr::system::RoutingTypes::Address expectedAddress;

    // Serialize into JSON
    std::string json = joynr::serializer::serializeToJson(expectedAddress);
    JOYNR_LOG_TRACE(logger(), "Address JSON: {}", json);

    // Deserialize from JSON

    // fully qualified type required here to avoid ambiguity with
    // gtest/gmock Address
    joynr::system::RoutingTypes::Address actualAddress;
    joynr::serializer::deserializeFromJson(actualAddress, json);
    EXPECT_EQ(expectedAddress, actualAddress);
}

TEST_F(JsonSerializerTest, exampleDeserializerPublicationMissedException)
{
    // Create a PublicationMissedException
    exceptions::PublicationMissedException exception;
    std::string subscriptionId{"SubscriptionId of PublicationMissedException"};
    exception.setSubscriptionId(subscriptionId);

    // Serialize into JSON
    std::string json = joynr::serializer::serializeToJson(exception);
    JOYNR_LOG_TRACE(logger(), "exceptions::PublicationMissedException JSON: {}", json);

    // Deserialize from JSON
    exceptions::PublicationMissedException t;
    joynr::serializer::deserializeFromJson(t, json);
    ASSERT_EQ(t.getSubscriptionId(), subscriptionId);
    ASSERT_EQ(t.getMessage(), subscriptionId);
}
TEST_F(JsonSerializerTest, exampleDeserializerJoynrTimeOutException)
{
    // Create a JoynrTimeOutException
    exceptions::JoynrTimeOutException exception;
    std::string detailMessage{"Message of JoynrTimeOutException"};
    exception.setMessage(detailMessage);

    // Serialize into JSON
    std::string json = joynr::serializer::serializeToJson(exception);
    JOYNR_LOG_TRACE(logger(), "exceptions::JoynrTimeOutException JSON: {}", json);

    // Deserialize from JSON
    exceptions::JoynrTimeOutException t;
    joynr::serializer::deserializeFromJson(t, json);
    ASSERT_EQ(t.getMessage(), detailMessage);
}

TEST_F(JsonSerializerTest,
       exampleDeserializerJoynrSubscriptionPublicationWithProviderRuntimeException)
{
    // Create a Publication
    SubscriptionPublication publication;
    publication.setSubscriptionId("testSubscriptionId");
    publication.setError(std::make_shared<exceptions::ProviderRuntimeException>(
            "Message of ProviderRuntimeException"));

    // Serialize into JSON
    std::string json = joynr::serializer::serializeToJson(publication);
    JOYNR_LOG_TRACE(logger(), "SubscriptionPublication JSON: {}", json);

    SubscriptionPublication deserializedSubscriptionPublication;
    joynr::serializer::deserializeFromJson(deserializedSubscriptionPublication, json);

    EXPECT_EQ(publication, deserializedSubscriptionPublication);
}

TEST_F(JsonSerializerTest, exampleDeserializerSubscriptionPublication)
{
    // Create a publication
    SubscriptionPublication expectedPublication;
    std::string someString{"Hello World"};
    const std::int32_t expectedInt = 101;
    const float expectedFloat = 9.99f;
    bool expectedBool = true;

    expectedPublication.setResponse(someString, expectedInt, expectedFloat, expectedBool);
    expectedPublication.setSubscriptionId("000-10000-01101");

    // Serialize into JSON
    std::string json = joynr::serializer::serializeToJson(expectedPublication);
    JOYNR_LOG_TRACE(logger(), "SubscriptionPublication JSON: {}", json);

    SubscriptionPublication deserializedSubscriptionPublication;
    joynr::serializer::deserializeFromJson(deserializedSubscriptionPublication, json);

    EXPECT_EQ(expectedPublication, deserializedSubscriptionPublication);
}
TEST_F(JsonSerializerTest, exampleDeserializerMulticastSubscriptionRequest)
{
    // Create a multicast subscription request
    MulticastSubscriptionRequest expectedRequest;
    expectedRequest.setMulticastId("multicastId");
    expectedRequest.setSubscriptionId("000-10000-01101");
    expectedRequest.setSubscribeToName("subscribeToName");
    auto qos = std::make_shared<MulticastSubscriptionQos>();
    expectedRequest.setQos(qos);

    // Serialize into JSON
    std::string json = joynr::serializer::serializeToJson(expectedRequest);
    JOYNR_LOG_TRACE(logger(), "MulticastSubscriptionRequest JSON: {}", json);

    MulticastSubscriptionRequest deserializedMulticastSubscriptionRequest;
    joynr::serializer::deserializeFromJson(deserializedMulticastSubscriptionRequest, json);

    EXPECT_EQ(expectedRequest, deserializedMulticastSubscriptionRequest);
}

TEST_F(JsonSerializerTest, deserializerMulticastPublicationWithProviderRuntimeException)
{
    // Create a Publication
    MulticastPublication publication;
    publication.setMulticastId("testSubscriptionId");
    publication.setError(std::make_shared<exceptions::ProviderRuntimeException>(
            "Message of ProviderRuntimeException"));

    // Serialize into JSON
    std::string json = joynr::serializer::serializeToJson(publication);
    JOYNR_LOG_TRACE(logger(), "MulticastPublication JSON: {}", json);

    MulticastPublication deserializedMulticastPublication;
    joynr::serializer::deserializeFromJson(deserializedMulticastPublication, json);

    EXPECT_EQ(publication, deserializedMulticastPublication);
}

TEST_F(JsonSerializerTest, deserializerMulticastPublication)
{
    // Create a publication
    MulticastPublication expectedPublication;
    std::string someString{"Hello World"};
    const std::int32_t expectedInt = 101;
    const float expectedFloat = 9.99f;
    bool expectedBool = true;

    expectedPublication.setResponse(someString, expectedInt, expectedFloat, expectedBool);
    expectedPublication.setMulticastId("000-10000-01101");

    // Serialize into JSON
    std::string json = joynr::serializer::serializeToJson(expectedPublication);
    JOYNR_LOG_TRACE(logger(), "MulticastPublication JSON: {}", json);

    MulticastPublication deserializedMulticastPublication;
    joynr::serializer::deserializeFromJson(deserializedMulticastPublication, json);

    EXPECT_EQ(expectedPublication, deserializedMulticastPublication);
}

// test with real MasterAccessControlEntry
TEST_F(JsonSerializerTest, serializeDeserializeMasterAccessControlEntry)
{
    using namespace joynr::infrastructure::DacTypes;

    std::vector<TrustLevel::Enum> possibleTrustLevels(
            {TrustLevel::LOW, TrustLevel::MID, TrustLevel::HIGH});

    std::vector<Permission::Enum> possiblePermissions(
            {Permission::NO, Permission::ASK, Permission::YES});

    MasterAccessControlEntry expectedMac(R"(*)",
                                         R"(unittest)",
                                         R"(vehicle/radio)",
                                         TrustLevel::LOW,
                                         possibleTrustLevels,
                                         TrustLevel::HIGH,
                                         possibleTrustLevels,
                                         R"(*)",
                                         Permission::YES,
                                         possiblePermissions);

    // Serialize
    std::string json = joynr::serializer::serializeToJson(expectedMac);

    JOYNR_LOG_TRACE(logger(), "MAC JSON: {}", json);

    // Deserialize
    MasterAccessControlEntry mac;
    joynr::serializer::deserializeFromJson(mac, json);

    // Check that the object serialized/deserialized correctly
    EXPECT_EQ(expectedMac.getDefaultConsumerPermission(), mac.getDefaultConsumerPermission());
    EXPECT_EQ(expectedMac.getDefaultRequiredControlEntryChangeTrustLevel(),
              mac.getDefaultRequiredControlEntryChangeTrustLevel());
    EXPECT_EQ(expectedMac.getDefaultRequiredTrustLevel(), mac.getDefaultRequiredTrustLevel());
    EXPECT_EQ(expectedMac.getDomain(), mac.getDomain());
    EXPECT_EQ(expectedMac.getInterfaceName(), mac.getInterfaceName());
    EXPECT_EQ(expectedMac.getOperation(), mac.getOperation());
    EXPECT_EQ(expectedMac.getPossibleConsumerPermissions(), mac.getPossibleConsumerPermissions());
    EXPECT_EQ(expectedMac.getPossibleRequiredControlEntryChangeTrustLevels(),
              mac.getPossibleRequiredControlEntryChangeTrustLevels());
    EXPECT_EQ(expectedMac.getPossibleRequiredTrustLevels(), mac.getPossibleRequiredTrustLevels());
    EXPECT_EQ(expectedMac.getUid(), mac.getUid());
    EXPECT_EQ(expectedMac, mac);
}

template <typename T>
void serializeDeserializeMap(const T& expectedMap, Logger& logger)
{
    // Serialize
    std::string json = joynr::serializer::serializeToJson(expectedMap);

    JOYNR_LOG_DEBUG(logger, "ExpectedMap Json: {}", json);

    // Deserialize
    T actualMap;
    joynr::serializer::deserializeFromJson(actualMap, json);

    // Check that the object serialized/deserialized correctly
    EXPECT_EQ(expectedMap, actualMap);
}

TEST_F(JsonSerializerTest, serializeDeserializeTIntegerKeyMap)
{
    using namespace joynr::types::TestTypes;
    TIntegerKeyMap expectedMap;
    expectedMap.insert({1, "StringValue1"});
    expectedMap.insert({2, "StringValue2"});

    serializeDeserializeMap<TIntegerKeyMap>(expectedMap, logger());
}

TEST_F(JsonSerializerTest, serializeDeserializeTEverythingMap)
{
    using namespace joynr::types::TestTypes;

    TEverythingMap expectedMap;
    expectedMap.insert({TEnum::TLITERALA, TEverythingExtendedStruct()});
    expectedMap.insert({TEnum::TLITERALB, TEverythingExtendedStruct()});

    serializeDeserializeMap<TEverythingMap>(expectedMap, logger());
}

TEST_F(JsonSerializerTest, serializeDeserializeTStringKeyMap)
{
    using namespace joynr::types::TestTypes;

    TStringKeyMap expectedMap;
    expectedMap.insert({"StringKey1", "StringValue1"});
    expectedMap.insert({"StringKey2", "StringValue2"});

    serializeDeserializeMap<TStringKeyMap>(expectedMap, logger());
}

TEST_F(JsonSerializerTest, serializeDeserializeTStringToByteBufferMap)
{
    using namespace joynr::types::TestTypes;

    TStringToByteBufferMap expectedMap;
    expectedMap.insert({"StringKey1", {0, 1, 2, 3, 4, 5}});
    expectedMap.insert({"StringKey2", {10, 9, 8, 7, 6}});

    serializeDeserializeMap<TStringToByteBufferMap>(expectedMap, logger());
}

// test with TEverythingStruct
TEST_F(JsonSerializerTest, serializeDeserializeTEverythingStruct)
{
    using namespace joynr::types::TestTypes;

    ByteBuffer byteBuffer({1, 2, 3});
    std::vector<std::uint8_t> uInt8Array({3, 2, 1});
    std::vector<TEnum::Enum> enumArray({TEnum::TLITERALB});
    std::vector<std::string> stringArray({"one", "four"});
    std::vector<Vowel::Enum> vowelinies({Vowel::A, Vowel::E});
    Word wordWithVowelinies{vowelinies};
    Word wordEmpty{};
    std::vector<Word> words({wordWithVowelinies, wordEmpty});
    TStringKeyMap stringMap;
    stringMap.insert({"StringKey", "StringValue"});

    TypeDefForTStruct typeDefForTStruct{};

    TEverythingStruct expectedEverythingStruct{1,
                                               2,
                                               3,
                                               4,
                                               5,
                                               6,
                                               7,
                                               8,
                                               9.012,
                                               10.101f,
                                               "const std::string &tString",
                                               true,
                                               byteBuffer,
                                               uInt8Array,
                                               TEnum::TLITERALA,
                                               enumArray,
                                               stringArray,
                                               wordWithVowelinies,
                                               words,
                                               stringMap,
                                               typeDefForTStruct};

    // Serialize
    std::string json = joynr::serializer::serializeToJson(expectedEverythingStruct);

    JOYNR_LOG_TRACE(logger(), "TEverythingStruct JSON: {}", json);

    // Deserialize
    TEverythingStruct everythingStruct;
    joynr::serializer::deserializeFromJson(everythingStruct, json);

    // Check that the object serialized/deserialized correctly
    EXPECT_EQ(expectedEverythingStruct, everythingStruct);
}


text:
start_mysql(){
    /usr/bin/mysqld_safe --datadir=/config/databases > /dev/null 2>&1 &
    RET=1
    while [[ RET -ne 0 ]]; do
        mysql -uroot -e "status" > /dev/null 2>&1
        RET=$?
        sleep 1
    done
}

# If databases do not exist, create them
if [ -f /config/databases/guacamole/guacamole_user.ibd ]; then
  echo "Database exists."
else
  echo "Initializing Data Directory."
  /usr/bin/mysql_install_db --datadir=/config/databases >/dev/null 2>&1
  echo "Installation complete."
  start_mysql
  echo "Creating user and database."
  mysql -uroot -e "CREATE DATABASE guacamole"
  PW=$(cat /config/guacamole/guacamole.properties | grep -m 1 "mysql-password:\s" | sed 's/mysql-password:\s//')
  mysql -uroot -e "CREATE USER 'guacamole'@'localhost' IDENTIFIED BY '$PW'"
  echo "Database created. Granting access to 'guacamole' user for localhost."
  mysql -uroot -e "GRANT SELECT,INSERT,UPDATE,DELETE ON guacamole.* TO 'guacamole'@'localhost'"
  mysql -uroot -e "FLUSH PRIVILEGES"
  mysql -uroot guacamole < /root/001-create-schema.sql
  mysql -uroot guacamole < /root/002-create-admin-user.sql
  echo "Shutting down."
  mysqladmin -u root shutdown
  sleep 3
  echo "chown time"
  chown -R nobody:users /config/databases
  chmod -R 755 /config/databases
  sleep 3
  echo "Initialization complete."
fi

echo "Starting MariaDB..."
/usr/bin/mysqld_safe --skip-syslog --datadir='/config/databases'

redpajama_set_name: RedPajamaGithub


text:
package de.fhg.iais.cortex.im.rest;

import javax.inject.Inject;
import javax.ws.rs.DELETE;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import de.fhg.iais.commons.annotation.UsedBy;
import de.fhg.iais.cortex.im.service.ImIngestService;

/**
 * This class contains the declaration of the REST-services, that are responsible to delete objects ingested
 * for a production lines.
 */
@Path("/")
@UsedBy("jersey" + "guice")
public class ImDeleteResource {
    private static final Logger LOG = LoggerFactory.getLogger(ImDeleteResource.class);
    private static final String ACCEPT_CHARSET_UTF_8 = ";charset=utf-8";

    private final ImIngestService imIngestService;

    @Inject
    public ImDeleteResource(ImIngestService imIngestService) {
        this.imIngestService = imIngestService;
    }

    /**
     * Deletes an item from index and archive by identifier.
     *
     * @param id The item identifier.
     * @param productionLine The production line affected.
     * @return Response containing the item identifier.
     */
    @Path("/deleteItem/{id}/{productionLine}")
    @DELETE
    @Produces(MediaType.APPLICATION_JSON + ACCEPT_CHARSET_UTF_8)
    public Response deleteById(@PathParam("id") final String id, @PathParam("productionLine") final String productionLine) //
    {
        try {
            String deleteById = this.imIngestService.deleteById(id, productionLine);
            return Response.ok().entity(deleteById).build();
        } catch ( final Exception e ) {
            LOG.warn("HTTP status 500 returned to caller", e);
            throw new WebApplicationException(e, Response.Status.INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * Deletes all items of an ingest from index and archive.
     *
     * @param providerId The provider identifier.
     * @param ingestId The ingest identifier.
     * @param productionLine The production line affected.
     * @return Response containing the identifiers of all deleted items.
     */
    @Path("/deleteIngest/{providerId}/{ingestId}/{productionLine}")
    @DELETE
    @Produces(MediaType.APPLICATION_JSON + ACCEPT_CHARSET_UTF_8)
    public Response deleteByIngestId(
        @PathParam("providerId") final String providerId,
        @PathParam("ingestId") final String ingestId,
        @PathParam("productionLine") final String productionLine) //
    {
        try {
            String deleteByIngestId = this.imIngestService.deleteByIngestId(providerId, ingestId, productionLine);
            return Response.ok().entity(deleteByIngestId).build();
        } catch ( final Exception e ) {
            LOG.warn("HTTP status 500 returned to caller", e);
            throw new WebApplicationException(e, Response.Status.INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * Deletes all items of a provider from index and archive.
     *
     * @param id The provider identifier.
     * @param productionLine The production line affected.
     * @return Response containing the identifiers of all deleted items.
     */
    @Path("/deleteProvider/{id}/{productionLine}")
    @DELETE
    @Produces(MediaType.APPLICATION_JSON + ACCEPT_CHARSET_UTF_8)
    public Response deleteByProviderId(@PathParam("id") final String providerId, @PathParam("productionLine") final String productionLine) //
    {
        try {
            String deleteByProviderId = this.imIngestService.deleteByProviderId(providerId, productionLine);
            return Response.ok().entity(deleteByProviderId).build();
        } catch ( final Exception e ) {
            LOG.warn("HTTP status 500 returned to caller", e);
            throw new WebApplicationException(e, Response.Status.INTERNAL_SERVER_ERROR);
        }
    }
}


text:
<!DOCTYPE>

  <title>RTL page with composited elements</title>


text:
<?php

declare(strict_types=1);

namespace spec\Sylius\Component\Mailer\Provider;

use PhpSpec\ObjectBehavior;
use Sylius\Component\Mailer\Factory\EmailFactoryInterface;
use Sylius\Component\Mailer\Model\EmailInterface;
use Sylius\Component\Mailer\Provider\EmailProviderInterface;

/**
 * @author Paweł Jędrzejewski <pawel@sylius.org>
 */
final class EmailProviderSpec extends ObjectBehavior
{
    function let(EmailFactoryInterface $emailFactory): void
    {
        $emails = [
            'user_confirmation' => [
                'enabled' => false,
                'subject' => 'Hello test!',
                'template' => 'SyliusMailerBundle::default.html.twig',
                'sender' => [
                    'name' => 'John Doe',
                    'address' => 'john@doe.com',
                ],
            ],
            'order_cancelled' => [
                'enabled' => false,
                'subject' => 'Hi test!',
                'template' => 'SyliusMailerBundle::default.html.twig',
                'sender' => [
                    'name' => 'Rick Doe',
                    'address' => 'john@doe.com',
                ],
            ],
        ];

        $this->beConstructedWith($emailFactory, $emails);
    }

    function it_implements_email_provider_interface(): void
    {
        $this->shouldImplement(EmailProviderInterface::class);
    }

    function it_looks_for_an_email_in_configuration_when_it_cannot_be_found_via_repository(
        EmailInterface $email,
        EmailFactoryInterface $emailFactory
    ): void {
        $emailFactory->createNew()->willReturn($email);

        $email->setCode('user_confirmation')->shouldBeCalled();
        $email->setSubject('Hello test!')->shouldBeCalled();
        $email->setTemplate('SyliusMailerBundle::default.html.twig')->shouldBeCalled();
        $email->setSenderName('John Doe')->shouldBeCalled();
        $email->setSenderAddress('john@doe.com')->shouldBeCalled();
        $email->setEnabled(false)->shouldBeCalled();

        $this->getEmail('user_confirmation')->shouldReturn($email);
    }
}


text:
.PHONY: clean clean-test clean-pyc clean-build docs help
.DEFAULT_GOAL := help
define PRINT_HELP_PYSCRIPT
import re, sys

for line in sys.stdin:
	match = re.match(r'^([a-zA-Z_-]+):.*?## (.*)$$', line)
	if match:
		target, help = match.groups()
		print("%-20s %s" % (target, help))
endef
export PRINT_HELP_PYSCRIPT

help:
	@python -c "$$PRINT_HELP_PYSCRIPT" < $(MAKEFILE_LIST)

ci: dist install develop test docs

dist: clean ## builds source and wheel package
	poetry build
	ls -l dist

install:
	pip install -U dist/*.whl

develop:  ## create virtualenv and install dependencies
	poetry install

test: ## run tests quickly with the default Python
	poetry run pytest

test-all: clean tox docs ## test every Python version with tox

clean: clean-build clean-pyc clean-test ## remove all build, test, coverage and Python artifacts
	rm -fr .tox/

clean-build: ## remove build artifacts
	rm -fr build/
	rm -fr dist/
	rm -fr .eggs/
	find . -name '*.egg-info' -exec rm -fr {} +
	find . -name '*.egg' -exec rm -f {} +

clean-pyc: ## remove Python file artifacts
	find . -name '*.pyc' -exec rm -f {} +
	find . -name '*.pyo' -exec rm -f {} +
	find . -name '*~' -exec rm -f {} +
	find . -name '__pycache__' -exec rm -fr {} +

clean-test: ## remove test and coverage artifacts
	rm -f .coverage
	rm -f coverage.xml
	rm -fr htmlcov/

tox:
	poetry run tox --skip-missing-interpreters

docs: ## generate Sphinx HTML documentation
	poetry run $(MAKE) -C docs clean
	poetry run $(MAKE) -C docs html

release: ## package and upload a release
	poetry publish


text:
package org.jfree.chart.editor;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.util.ResourceBundle;

import javax.swing.BorderFactory;
import javax.swing.JCheckBox;
import javax.swing.JColorChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;

import org.jfree.chart.axis.Axis;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.util.ResourceBundleWrapper;
import org.jfree.layout.LCBLayout;
import org.jfree.ui.PaintSample;
import org.jfree.ui.StrokeChooserPanel;
import org.jfree.ui.StrokeSample;

/**
 * A panel for editing the properties of a value axis.
 */
class DefaultNumberAxisEditor extends DefaultAxisEditor
        implements FocusListener {

    /** A flag that indicates whether or not the axis range is determined
     *  automatically.
     */
    private boolean autoRange;

    /** The lowest value in the axis range. */
    private double minimumValue;

    /** The highest value in the axis range. */
    private double maximumValue;

    /** A checkbox that indicates whether or not the axis range is determined
     *  automatically.
     */
    private JCheckBox autoRangeCheckBox;

    /** A text field for entering the minimum value in the axis range. */
    private JTextField minimumRangeValue;

    /** A text field for entering the maximum value in the axis range. */
    private JTextField maximumRangeValue;

    /** The paint selected for drawing the gridlines. */
    private PaintSample gridPaintSample;

    /** The stroke selected for drawing the gridlines. */
    private StrokeSample gridStrokeSample;

    /** An array of stroke samples to choose from (since I haven't written a
     *  decent StrokeChooser component yet).
     */
    private StrokeSample[] availableStrokeSamples;

    /** The resourceBundle for the localization. */
    protected static ResourceBundle localizationResources
            = ResourceBundleWrapper.getBundle(
                "org.jfree.chart.editor.LocalizationBundle");

    /**
     * Standard constructor: builds a property panel for the specified axis.
     *
     * @param axis  the axis, which should be changed.
     */
    public DefaultNumberAxisEditor(NumberAxis axis) {

        super(axis);

        this.autoRange = axis.isAutoRange();
        this.minimumValue = axis.getLowerBound();
        this.maximumValue = axis.getUpperBound();

        this.gridPaintSample = new PaintSample(Color.blue);
        this.gridStrokeSample = new StrokeSample(new BasicStroke(1.0f));

        this.availableStrokeSamples = new StrokeSample[3];
        this.availableStrokeSamples[0] = new StrokeSample(
                new BasicStroke(1.0f));
        this.availableStrokeSamples[1] = new StrokeSample(
                new BasicStroke(2.0f));
        this.availableStrokeSamples[2] = new StrokeSample(
                new BasicStroke(3.0f));

        JTabbedPane other = getOtherTabs();

        JPanel range = new JPanel(new LCBLayout(3));
        range.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));

        range.add(new JPanel());
        this.autoRangeCheckBox = new JCheckBox(localizationResources.getString(
                "Auto-adjust_range"), this.autoRange);
        this.autoRangeCheckBox.setActionCommand("AutoRangeOnOff");
        this.autoRangeCheckBox.addActionListener(this);
        range.add(this.autoRangeCheckBox);
        range.add(new JPanel());

        range.add(new JLabel(localizationResources.getString(
                "Minimum_range_value")));
        this.minimumRangeValue = new JTextField(Double.toString(
                this.minimumValue));
        this.minimumRangeValue.setEnabled(!this.autoRange);
        this.minimumRangeValue.setActionCommand("MinimumRange");
        this.minimumRangeValue.addActionListener(this);
        this.minimumRangeValue.addFocusListener(this);
        range.add(this.minimumRangeValue);
        range.add(new JPanel());

        range.add(new JLabel(localizationResources.getString(
                "Maximum_range_value")));
        this.maximumRangeValue = new JTextField(Double.toString(
                this.maximumValue));
        this.maximumRangeValue.setEnabled(!this.autoRange);
        this.maximumRangeValue.setActionCommand("MaximumRange");
        this.maximumRangeValue.addActionListener(this);
        this.maximumRangeValue.addFocusListener(this);
        range.add(this.maximumRangeValue);
        range.add(new JPanel());

        other.add(localizationResources.getString("Range"), range);

    }

    /**
     * Returns the current setting of the auto-range property.
     *
     * @return true if auto range is enabled.
     */
    public boolean isAutoRange() {
        return this.autoRange;
    }

    /**
     * Returns the current setting of the minimum value in the axis range.
     *
     * @return The current setting of the minimum value in the axis range.
     */
    public double getMinimumValue() {
        return this.minimumValue;
    }

    /**
     * Returns the current setting of the maximum value in the axis range.
     *
     * @return The current setting of the maximum value in the axis range.
     */
    public double getMaximumValue() {
        return this.maximumValue;
    }

    /**
     * Handles actions from within the property panel.
     * @param event an event.
     */
    public void actionPerformed(ActionEvent event) {
        String command = event.getActionCommand();
        if (command.equals("GridStroke")) {
            attemptGridStrokeSelection();
        }
        else if (command.equals("GridPaint")) {
            attemptGridPaintSelection();
        }
        else if (command.equals("AutoRangeOnOff")) {
            toggleAutoRange();
        }
        else if (command.equals("MinimumRange")) {
            validateMinimum();
        }
        else if (command.equals("MaximumRange")) {
            validateMaximum();
        }
        else {
            // pass to the super-class for handling
            super.actionPerformed(event);
        }
    }

    /**
     * Handle a grid stroke selection.
     */
    private void attemptGridStrokeSelection() {
        StrokeChooserPanel panel = new StrokeChooserPanel(this.gridStrokeSample,
                this.availableStrokeSamples);
        int result = JOptionPane.showConfirmDialog(this, panel,
                localizationResources.getString("Stroke_Selection"),
                JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);

        if (result == JOptionPane.OK_OPTION) {
            this.gridStrokeSample.setStroke(panel.getSelectedStroke());
        }
    }

    /**
     * Handle a grid paint selection.
     */
    private void attemptGridPaintSelection() {
        Color c;
        c = JColorChooser.showDialog(this, localizationResources.getString(
                "Grid_Color"), Color.blue);
        if (c != null) {
            this.gridPaintSample.setPaint(c);
        }
    }

    /**
     * Does nothing.
     *
     * @param event  the event.
     */
    public void focusGained(FocusEvent event) {
        // don't need to do anything
    }

    /**
     *  Revalidates minimum/maximum range.
     *
     *  @param event  the event.
     */
    public void focusLost(FocusEvent event) {
        if (event.getSource() == this.minimumRangeValue) {
            validateMinimum();
        }
        else if (event.getSource() == this.maximumRangeValue) {
            validateMaximum();
        }
    }

    /**
     *  Toggle the auto range setting.
     */
    public void toggleAutoRange() {
        this.autoRange = this.autoRangeCheckBox.isSelected();
        if (this.autoRange) {
            this.minimumRangeValue.setText(Double.toString(this.minimumValue));
            this.minimumRangeValue.setEnabled(false);
            this.maximumRangeValue.setText(Double.toString(this.maximumValue));
            this.maximumRangeValue.setEnabled(false);
        }
        else {
            this.minimumRangeValue.setEnabled(true);
            this.maximumRangeValue.setEnabled(true);
        }
    }

    /**
     * Revalidate the range minimum.
     */
    public void validateMinimum() {
        double newMin;
        try {
            newMin = Double.parseDouble(this.minimumRangeValue.getText());
            if (newMin >= this.maximumValue) {
                newMin = this.minimumValue;
            }
        }
        catch (NumberFormatException e) {
            newMin = this.minimumValue;
        }

        this.minimumValue = newMin;
        this.minimumRangeValue.setText(Double.toString(this.minimumValue));
    }

    /**
     * Revalidate the range maximum.
     */
    public void validateMaximum() {
        double newMax;
        try {
            newMax = Double.parseDouble(this.maximumRangeValue.getText());
            if (newMax <= this.minimumValue) {
                newMax = this.maximumValue;
            }
        }
        catch (NumberFormatException e) {
            newMax = this.maximumValue;
        }

        this.maximumValue = newMax;
        this.maximumRangeValue.setText(Double.toString(this.maximumValue));
    }

    /**
     * Sets the properties of the specified axis to match the properties
     * defined on this panel.
     *
     * @param axis  the axis.
     */
    public void setAxisProperties(Axis axis) {
        super.setAxisProperties(axis);
        NumberAxis numberAxis = (NumberAxis) axis;
        numberAxis.setAutoRange(this.autoRange);
        if (!this.autoRange) {
            numberAxis.setRange(this.minimumValue, this.maximumValue);
        }
    }

}


text:
package org.jboss.netty.handler.codec.bayeux;

import java.util.List;
import org.junit.Test;
import static org.junit.Assert.*;

/**
 *
 * @author daijun
 */
public class BayeuxUtilTest {

    @Test
    public void testGetCurrentTime() {
        System.out.println("getCurrentTime:");
        System.out.println(BayeuxUtil.getCurrentTime());
    }

    @Test
    public void testGenerateUUID() {
        System.out.println("getCurrentTime:");
        System.out.println(BayeuxUtil.generateUUID());
    }

    @Test
    public void testPrefixMatch(){
        System.out.println("Prefix matchingy...");
        String[] strings = {"/channel/*","/channel/**","/channel/a","/channel/a/aa","/channel/*/aa"};
        String[] expResult = {"/channel/*","/channel/**"};
        List<String> result =  BayeuxUtil.prefixMatch("/channel/abc", strings);
        assertArrayEquals(expResult, result.toArray());

        String[] expResult2 = {"/channel/*","/channel/**","/channel/a"};
        List<String> result2 =  BayeuxUtil.prefixMatch("/channel/*", strings);
        assertArrayEquals(expResult2, result2.toArray());

        String[] expResult3 = {"/channel/*","/channel/**","/channel/a","/channel/a/aa"};
        List<String> result3 =  BayeuxUtil.prefixMatch("/channel/**", strings);
        assertArrayEquals(expResult3, result3.toArray());
    }
}


text:
package io.netty.buffer;

import io.netty.util.Recycler;
import io.netty.util.Recycler.Handle;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;

abstract class PooledByteBuf<T> extends AbstractReferenceCountedByteBuf {

    private final Recycler.Handle<PooledByteBuf<T>> recyclerHandle;

    protected PoolChunk<T> chunk;
    protected long handle;
    protected T memory;
    protected int offset;
    protected int length;
    int maxLength;
    Thread initThread;
    private ByteBuffer tmpNioBuf;

    @SuppressWarnings("unchecked")
    protected PooledByteBuf(Recycler.Handle<? extends PooledByteBuf<T>> recyclerHandle, int maxCapacity) {
        super(maxCapacity);
        this.recyclerHandle = (Handle<PooledByteBuf<T>>) recyclerHandle;
    }

    void init(PoolChunk<T> chunk, long handle, int offset, int length, int maxLength) {
        assert handle >= 0;
        assert chunk != null;

        this.chunk = chunk;
        this.handle = handle;
        memory = chunk.memory;
        this.offset = offset;
        this.length = length;
        this.maxLength = maxLength;
        setIndex(0, 0);
        tmpNioBuf = null;
        initThread = Thread.currentThread();
    }

    void initUnpooled(PoolChunk<T> chunk, int length) {
        assert chunk != null;

        this.chunk = chunk;
        handle = 0;
        memory = chunk.memory;
        offset = 0;
        this.length = maxLength = length;
        setIndex(0, 0);
        tmpNioBuf = null;
        initThread = Thread.currentThread();
    }

    @Override
    public final int capacity() {
        return length;
    }

    @Override
    public final ByteBuf capacity(int newCapacity) {
        ensureAccessible();

        // If the request capacity does not require reallocation, just update the length of the memory.
        if (chunk.unpooled) {
            if (newCapacity == length) {
                return this;
            }
        } else {
            if (newCapacity > length) {
                if (newCapacity <= maxLength) {
                    length = newCapacity;
                    return this;
                }
            } else if (newCapacity < length) {
                if (newCapacity > maxLength >>> 1) {
                    if (maxLength <= 512) {
                        if (newCapacity > maxLength - 16) {
                            length = newCapacity;
                            setIndex(Math.min(readerIndex(), newCapacity), Math.min(writerIndex(), newCapacity));
                            return this;
                        }
                    } else { // > 512 (i.e. >= 1024)
                        length = newCapacity;
                        setIndex(Math.min(readerIndex(), newCapacity), Math.min(writerIndex(), newCapacity));
                        return this;
                    }
                }
            } else {
                return this;
            }
        }

        // Reallocation required.
        chunk.arena.reallocate(this, newCapacity, true);
        return this;
    }

    @Override
    public final ByteBufAllocator alloc() {
        return chunk.arena.parent;
    }

    @Override
    public final ByteOrder order() {
        return ByteOrder.BIG_ENDIAN;
    }

    @Override
    public final ByteBuf unwrap() {
        return null;
    }

    protected final ByteBuffer internalNioBuffer() {
        ByteBuffer tmpNioBuf = this.tmpNioBuf;
        if (tmpNioBuf == null) {
            this.tmpNioBuf = tmpNioBuf = newInternalNioBuffer(memory);
        }
        return tmpNioBuf;
    }

    protected abstract ByteBuffer newInternalNioBuffer(T memory);

    @Override
    protected final void deallocate() {
        if (handle >= 0) {
            final long handle = this.handle;
            this.handle = -1;
            memory = null;
            boolean sameThread = initThread == Thread.currentThread();
            initThread = null;
            chunk.arena.free(chunk, handle, maxLength, sameThread);
            recycle();
        }
    }

    private void recycle() {
        recyclerHandle.recycle(this);
    }

    protected final int idx(int index) {
        return offset + index;
    }
}


text:
Thank you for your intention to contribute to the Apache Flink project. As an open-source community, we highly appreciate external contributions to our project.

To make the process smooth for the project *committers* (those who review and accept changes) and *contributors* (those who propose new changes via pull requests), there are a few rules to follow.

## Contribution Guidelines

Please check out the [How to Contribute guide](https://flink.apache.org/contributing/how-to-contribute.html) to understand how contributions are made.
A detailed explanation can be found in our [Contribute Code Guide](https://flink.apache.org/contributing/contribute-code.html) which also contains a list of coding guidelines that you should follow.
For pull requests, there is a [check list](PULL_REQUEST_TEMPLATE.md) with criteria taken from the How to Contribute Guide and the Coding Guidelines.


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace DemoContentBuilder
{
    /// <summary>
    /// Holds already-loaded files in memory to avoid hitting the disk repeatedly.
    /// </summary>
    /// <remarks>Because memory really isn't an issue.</remarks>
    public class ShaderFileCache
    {
        Dictionary<string, string> cache = new Dictionary<string, string>();

        public bool TryLoad(string path, out string shaderText)
        {
            lock (cache)
            {
                if (cache.TryGetValue(path, out shaderText))
                {
                    return true;
                }
            }

            //Have to look it up on disk.
            //Note that other threads may currently be looking it up too. We could have a waiting system, but the error handling involved in that is gross. The cache should be hit most of the time.
            //This is an optimization, after all, not a correctness issue.
            if (File.Exists(path))
            {
                using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    using (StreamReader reader = new StreamReader(stream))
                    {
                        shaderText = reader.ReadToEnd();
                    }
                }
                lock (cache)
                {
                    //Add or replace the path in the cache.
                    cache[path] = shaderText;
                }
                return true;
            }
            //This file does not exist.
            return false;

        }
    }
}


text:
const mongoose = require('mongoose');
mongoose.Promise = require('bluebird');

const ResultSchema = new mongoose.Schema(
    {
        type: { type: mongoose.Schema.Types.String, required: true },
        modifiedOn: { type: mongoose.Schema.Types.Date, required: false },
        modifiedBy: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
        score: { type: mongoose.Schema.Types.Number, default: 0 },
        details: { type: mongoose.Schema.Types.String }, // json containing result details
    },
    {
        usePushEach: true,
    }
);

module.exports = ResultSchema;


text:
namespace {

// The maximum class value in class definition tables.
const uint16_t kMaxClassDefValue = 0xFFFF;
// The maximum class value in the glyph class definision table.
const uint16_t kMaxGlyphClassDefValue = 4;
// The maximum format number of caret value tables.
// We don't support format 3 for now. See the comment in
// ParseLigCaretListTable() for the reason.
const uint16_t kMaxCaretValueFormat = 2;

bool ParseGlyphClassDefTable(ots::OpenTypeFile *file, const uint8_t *data,
                             size_t length, const uint16_t num_glyphs) {
  return ots::ParseClassDefTable(file, data, length, num_glyphs,
                                 kMaxGlyphClassDefValue);
}

bool ParseAttachListTable(ots::OpenTypeFile *file, const uint8_t *data,
                          size_t length, const uint16_t num_glyphs) {
  ots::Buffer subtable(data, length);

  uint16_t offset_coverage = 0;
  uint16_t glyph_count = 0;
  if (!subtable.ReadU16(&offset_coverage) ||
      !subtable.ReadU16(&glyph_count)) {
    return OTS_FAILURE_MSG("Failed to read gdef header");
  }
  const unsigned attach_points_end =
      2 * static_cast<unsigned>(glyph_count) + 4;
  if (attach_points_end > std::numeric_limits<uint16_t>::max()) {
    return OTS_FAILURE_MSG("Bad glyph count in gdef");
  }
  if (offset_coverage == 0 || offset_coverage >= length ||
      offset_coverage < attach_points_end) {
    return OTS_FAILURE_MSG("Bad coverage offset %d", offset_coverage);
  }
  if (glyph_count > num_glyphs) {
    return OTS_FAILURE_MSG("Bad glyph count %u", glyph_count);
  }

  std::vector<uint16_t> attach_points;
  attach_points.resize(glyph_count);
  for (unsigned i = 0; i < glyph_count; ++i) {
    if (!subtable.ReadU16(&attach_points[i])) {
      return OTS_FAILURE_MSG("Can't read attachment point %d", i);
    }
    if (attach_points[i] >= length ||
        attach_points[i] < attach_points_end) {
      return OTS_FAILURE_MSG("Bad attachment point %d of %d", i, attach_points[i]);
    }
  }

  // Parse coverage table
  if (!ots::ParseCoverageTable(file, data + offset_coverage,
                               length - offset_coverage, num_glyphs)) {
    return OTS_FAILURE_MSG("Bad coverage table");
  }

  // Parse attach point table
  for (unsigned i = 0; i < attach_points.size(); ++i) {
    subtable.set_offset(attach_points[i]);
    uint16_t point_count = 0;
    if (!subtable.ReadU16(&point_count)) {
      return OTS_FAILURE_MSG("Can't read point count %d", i);
    }
    if (point_count == 0) {
      return OTS_FAILURE_MSG("zero point count %d", i);
    }
    uint16_t last_point_index = 0;
    uint16_t point_index = 0;
    for (unsigned j = 0; j < point_count; ++j) {
      if (!subtable.ReadU16(&point_index)) {
        return OTS_FAILURE_MSG("Can't read point index %d in point %d", j, i);
      }
      // Contour point indeces are in increasing numerical order
      if (last_point_index != 0 && last_point_index >= point_index) {
        return OTS_FAILURE_MSG("bad contour indeces: %u >= %u",
                    last_point_index, point_index);
      }
      last_point_index = point_index;
    }
  }
  return true;
}

bool ParseLigCaretListTable(ots::OpenTypeFile *file, const uint8_t *data,
                            size_t length, const uint16_t num_glyphs) {
  ots::Buffer subtable(data, length);
  uint16_t offset_coverage = 0;
  uint16_t lig_glyph_count = 0;
  if (!subtable.ReadU16(&offset_coverage) ||
      !subtable.ReadU16(&lig_glyph_count)) {
    return OTS_FAILURE_MSG("Can't read caret structure");
  }
  const unsigned lig_glyphs_end =
      2 * static_cast<unsigned>(lig_glyph_count) + 4;
  if (lig_glyphs_end > std::numeric_limits<uint16_t>::max()) {
    return OTS_FAILURE_MSG("Bad caret structure");
  }
  if (offset_coverage == 0 || offset_coverage >= length ||
      offset_coverage < lig_glyphs_end) {
    return OTS_FAILURE_MSG("Bad caret coverate offset %d", offset_coverage);
  }
  if (lig_glyph_count > num_glyphs) {
    return OTS_FAILURE_MSG("bad ligature glyph count: %u", lig_glyph_count);
  }

  std::vector<uint16_t> lig_glyphs;
  lig_glyphs.resize(lig_glyph_count);
  for (unsigned i = 0; i < lig_glyph_count; ++i) {
    if (!subtable.ReadU16(&lig_glyphs[i])) {
      return OTS_FAILURE_MSG("Can't read ligature glyph location %d", i);
    }
    if (lig_glyphs[i] >= length || lig_glyphs[i] < lig_glyphs_end) {
      return OTS_FAILURE_MSG("Bad ligature glyph location %d in glyph %d", lig_glyphs[i], i);
    }
  }

  // Parse coverage table
  if (!ots::ParseCoverageTable(file, data + offset_coverage,
                               length - offset_coverage, num_glyphs)) {
    return OTS_FAILURE_MSG("Can't parse caret coverage table");
  }

  // Parse ligature glyph table
  for (unsigned i = 0; i < lig_glyphs.size(); ++i) {
    subtable.set_offset(lig_glyphs[i]);
    uint16_t caret_count = 0;
    if (!subtable.ReadU16(&caret_count)) {
      return OTS_FAILURE_MSG("Can't read caret count for glyph %d", i);
    }
    if (caret_count == 0) {
      return OTS_FAILURE_MSG("bad caret value count: %u", caret_count);
    }

    std::vector<uint16_t> caret_value_offsets;
    caret_value_offsets.resize(caret_count);
    unsigned caret_value_offsets_end = 2 * static_cast<unsigned>(caret_count) + 2;
    for (unsigned j = 0; j < caret_count; ++j) {
      if (!subtable.ReadU16(&caret_value_offsets[j])) {
        return OTS_FAILURE_MSG("Can't read caret offset %d for glyph %d", j, i);
      }
      if (caret_value_offsets[j] >= length || caret_value_offsets[j] < caret_value_offsets_end) {
        return OTS_FAILURE_MSG("Bad caret offset %d for caret %d glyph %d", caret_value_offsets[j], j, i);
      }
    }

    // Parse caret values table
    for (unsigned j = 0; j < caret_count; ++j) {
      subtable.set_offset(lig_glyphs[i] + caret_value_offsets[j]);
      uint16_t caret_format = 0;
      if (!subtable.ReadU16(&caret_format)) {
        return OTS_FAILURE_MSG("Can't read caret values table %d in glyph %d", j, i);
      }
      // TODO(bashi): We only support caret value format 1 and 2 for now
      // because there are no fonts which contain caret value format 3
      // as far as we investigated.
      if (caret_format == 0 || caret_format > kMaxCaretValueFormat) {
        return OTS_FAILURE_MSG("bad caret value format: %u", caret_format);
      }
      // CaretValueFormats contain a 2-byte field which could be
      // arbitrary value.
      if (!subtable.Skip(2)) {
        return OTS_FAILURE_MSG("Bad caret value table structure %d in glyph %d", j, i);
      }
    }
  }
  return true;
}

bool ParseMarkAttachClassDefTable(ots::OpenTypeFile *file, const uint8_t *data,
                                  size_t length, const uint16_t num_glyphs) {
  return ots::ParseClassDefTable(file, data, length, num_glyphs, kMaxClassDefValue);
}

bool ParseMarkGlyphSetsDefTable(ots::OpenTypeFile *file, const uint8_t *data,
                                size_t length, const uint16_t num_glyphs) {
  ots::Buffer subtable(data, length);
  uint16_t format = 0;
  uint16_t mark_set_count = 0;
  if (!subtable.ReadU16(&format) ||
      !subtable.ReadU16(&mark_set_count)) {
    return OTS_FAILURE_MSG("Can' read mark glyph table structure");
  }
  if (format != 1) {
    return OTS_FAILURE_MSG("bad mark glyph set table format: %u", format);
  }

  const unsigned mark_sets_end = 2 * static_cast<unsigned>(mark_set_count) + 4;
  if (mark_sets_end > std::numeric_limits<uint16_t>::max()) {
    return OTS_FAILURE_MSG("Bad mark_set %d", mark_sets_end);
  }
  for (unsigned i = 0; i < mark_set_count; ++i) {
    uint32_t offset_coverage = 0;
    if (!subtable.ReadU32(&offset_coverage)) {
      return OTS_FAILURE_MSG("Can't read covrage location for mark set %d", i);
    }
    if (offset_coverage >= length ||
        offset_coverage < mark_sets_end) {
      return OTS_FAILURE_MSG("Bad coverage location %d for mark set %d", offset_coverage, i);
    }
    if (!ots::ParseCoverageTable(file, data + offset_coverage,
                                 length - offset_coverage, num_glyphs)) {
      return OTS_FAILURE_MSG("Failed to parse coverage table for mark set %d", i);
    }
  }
  file->gdef->num_mark_glyph_sets = mark_set_count;
  return true;
}

}  // namespace

#define DROP_THIS_TABLE(msg_) \
  do { \
    OTS_FAILURE_MSG(msg_ ", table discarded"); \
    file->gdef->data = 0; \
    file->gdef->length = 0; \
  } while (0)

namespace ots {

bool ots_gdef_parse(OpenTypeFile *file, const uint8_t *data, size_t length) {
  // Grab the number of glyphs in the file from the maxp table to check
  // GlyphIDs in GDEF table.
  if (!file->maxp) {
    return OTS_FAILURE_MSG("No maxp table in font, needed by GDEF");
  }
  const uint16_t num_glyphs = file->maxp->num_glyphs;

  Buffer table(data, length);

  OpenTypeGDEF *gdef = new OpenTypeGDEF;
  file->gdef = gdef;

  uint32_t version = 0;
  if (!table.ReadU32(&version)) {
    DROP_THIS_TABLE("Incomplete table");
    return true;
  }
  if (version < 0x00010000 || version == 0x00010001) {
    DROP_THIS_TABLE("Bad version");
    return true;
  }

  if (version >= 0x00010002) {
    gdef->version_2 = true;
  }

  uint16_t offset_glyph_class_def = 0;
  uint16_t offset_attach_list = 0;
  uint16_t offset_lig_caret_list = 0;
  uint16_t offset_mark_attach_class_def = 0;
  if (!table.ReadU16(&offset_glyph_class_def) ||
      !table.ReadU16(&offset_attach_list) ||
      !table.ReadU16(&offset_lig_caret_list) ||
      !table.ReadU16(&offset_mark_attach_class_def)) {
    DROP_THIS_TABLE("Incomplete table");
    return true;
  }
  uint16_t offset_mark_glyph_sets_def = 0;
  if (gdef->version_2) {
    if (!table.ReadU16(&offset_mark_glyph_sets_def)) {
      DROP_THIS_TABLE("Incomplete table");
      return true;
    }
  }

  unsigned gdef_header_end = 4 + 4 * 2;
  if (gdef->version_2)
    gdef_header_end += 2;

  // Parse subtables
  if (offset_glyph_class_def) {
    if (offset_glyph_class_def >= length ||
        offset_glyph_class_def < gdef_header_end) {
      DROP_THIS_TABLE("Invalid offset to glyph classes");
      return true;
    }
    if (!ParseGlyphClassDefTable(file, data + offset_glyph_class_def,
                                 length - offset_glyph_class_def,
                                 num_glyphs)) {
      DROP_THIS_TABLE("Invalid glyph classes");
      return true;
    }
    gdef->has_glyph_class_def = true;
  }

  if (offset_attach_list) {
    if (offset_attach_list >= length ||
        offset_attach_list < gdef_header_end) {
      DROP_THIS_TABLE("Invalid offset to attachment list");
      return true;
    }
    if (!ParseAttachListTable(file, data + offset_attach_list,
                              length - offset_attach_list,
                              num_glyphs)) {
      DROP_THIS_TABLE("Invalid attachment list");
      return true;
    }
  }

  if (offset_lig_caret_list) {
    if (offset_lig_caret_list >= length ||
        offset_lig_caret_list < gdef_header_end) {
      DROP_THIS_TABLE("Invalid offset to ligature caret list");
      return true;
    }
    if (!ParseLigCaretListTable(file, data + offset_lig_caret_list,
                              length - offset_lig_caret_list,
                              num_glyphs)) {
      DROP_THIS_TABLE("Invalid ligature caret list");
      return true;
    }
  }

  if (offset_mark_attach_class_def) {
    if (offset_mark_attach_class_def >= length ||
        offset_mark_attach_class_def < gdef_header_end) {
      return OTS_FAILURE_MSG("Invalid offset to mark attachment list");
    }
    if (!ParseMarkAttachClassDefTable(file,
                                      data + offset_mark_attach_class_def,
                                      length - offset_mark_attach_class_def,
                                      num_glyphs)) {
      DROP_THIS_TABLE("Invalid mark attachment list");
      return true;
    }
    gdef->has_mark_attachment_class_def = true;
  }

  if (offset_mark_glyph_sets_def) {
    if (offset_mark_glyph_sets_def >= length ||
        offset_mark_glyph_sets_def < gdef_header_end) {
      return OTS_FAILURE_MSG("invalid offset to mark glyph sets");
    }
    if (!ParseMarkGlyphSetsDefTable(file,
                                    data + offset_mark_glyph_sets_def,
                                    length - offset_mark_glyph_sets_def,
                                    num_glyphs)) {
      DROP_THIS_TABLE("Invalid mark glyph sets");
      return true;
    }
    gdef->has_mark_glyph_sets_def = true;
  }
  gdef->data = data;
  gdef->length = length;
  return true;
}

bool ots_gdef_should_serialise(OpenTypeFile *file) {
  return file->gdef != NULL && file->gdef->data != NULL;
}

bool ots_gdef_serialise(OTSStream *out, OpenTypeFile *file) {
  if (!out->Write(file->gdef->data, file->gdef->length)) {
    return OTS_FAILURE_MSG("Failed to write GDEF table");
  }

  return true;
}

void ots_gdef_free(OpenTypeFile *file) {
  delete file->gdef;
}

}  // namespace ots

#undef TABLE_NAME
#undef DROP_THIS_TABLE