text:
namespace cronet {

namespace {

std::string WrapJsonHeader(base::StringPiece value) {
  return base::StrCat({"[", value, "]"});
}

// Returns whether two JSON-encoded headers contain the same content, ignoring
// irrelevant encoding issues like whitespace and map element ordering.
bool JsonHeaderEquals(base::StringPiece expected, base::StringPiece actual) {
  return base::test::ParseJson(WrapJsonHeader(expected)) ==
         base::test::ParseJson(WrapJsonHeader(actual));
}

}  // namespace

TEST(URLRequestContextConfigTest, TestExperimentalOptionParsing) {
  base::test::TaskEnvironment task_environment_(
      base::test::TaskEnvironment::MainThreadType::IO);

  // Create JSON for experimental options.
  base::DictionaryValue options;
  options.SetPath({"QUIC", "max_server_configs_stored_in_properties"},
                  base::Value(2));
  options.SetPath({"QUIC", "user_agent_id"}, base::Value("Custom QUIC UAID"));
  options.SetPath({"QUIC", "idle_connection_timeout_seconds"},
                  base::Value(300));
  options.SetPath({"QUIC", "close_sessions_on_ip_change"}, base::Value(true));
  options.SetPath({"QUIC", "connection_options"}, base::Value("TIME,TBBR,REJ"));
  options.SetPath(
      {"QUIC", "set_quic_flags"},
      base::Value("FLAGS_quic_reloadable_flag_quic_testonly_default_false=true,"
                  "FLAGS_quic_restart_flag_quic_testonly_default_true=false"));
  options.SetPath({"AsyncDNS", "enable"}, base::Value(true));
  options.SetPath({"NetworkErrorLogging", "enable"}, base::Value(true));
  options.SetPath({"NetworkErrorLogging", "preloaded_report_to_headers"},
                  base::test::ParseJson(R"json(
                  [
                    {
                      "origin": "https://test-origin/",
                      "value": {
                        "group": "test-group",
                        "max_age": 86400,
                        "endpoints": [
                          {"url": "https://test-endpoint/"},
                        ],
                      },
                    },
                    {
                      "origin": "https://test-origin-2/",
                      "value": [
                        {
                          "group": "test-group-2",
                          "max_age": 86400,
                          "endpoints": [
                            {"url": "https://test-endpoint-2/"},
                          ],
                        },
                        {
                          "group": "test-group-3",
                          "max_age": 86400,
                          "endpoints": [
                            {"url": "https://test-endpoint-3/"},
                          ],
                        },
                      ],
                    },
                    {
                      "origin": "https://value-is-missing/",
                    },
                    {
                      "value": "origin is missing",
                    },
                    {
                      "origin": 123,
                      "value": "origin is not a string",
                    },
                    {
                      "origin": "this is not a URL",
                      "value": "origin not a URL",
                    },
                  ]
                  )json"));
  options.SetPath({"NetworkErrorLogging", "preloaded_nel_headers"},
                  base::test::ParseJson(R"json(
                  [
                    {
                      "origin": "https://test-origin/",
                      "value": {
                        "report_to": "test-group",
                        "max_age": 86400,
                      },
                    },
                  ]
                  )json"));
  options.SetPath({"UnknownOption", "foo"}, base::Value(true));
  options.SetPath({"HostResolverRules", "host_resolver_rules"},
                  base::Value("MAP * 127.0.0.1"));
  // See http://crbug.com/696569.
  options.SetKey("disable_ipv6_on_wifi", base::Value(true));
  options.SetKey("spdy_go_away_on_ip_change", base::Value(true));
  options.SetPath({"QUIC", "ios_network_service_type"}, base::Value(2));
  std::string options_json;
  EXPECT_TRUE(base::JSONWriter::Write(options, &options_json));

  // Initialize QUIC flags set by the config.
  FLAGS_quic_reloadable_flag_quic_testonly_default_false = false;
  FLAGS_quic_restart_flag_quic_testonly_default_true = true;

  std::unique_ptr<URLRequestContextConfig> config =
      URLRequestContextConfig::CreateURLRequestContextConfig(
          // Enable QUIC.
          true,
          // QUIC User Agent ID.
          "Default QUIC User Agent ID",
          // Enable SPDY.
          true,
          // Enable Brotli.
          false,
          // Type of http cache.
          URLRequestContextConfig::HttpCacheType::DISK,
          // Max size of http cache in bytes.
          1024000,
          // Disable caching for HTTP responses. Other information may be stored
          // in the cache.
          false,
          // Storage path for http cache and cookie storage.
          "/data/data/org.chromium.net/app_cronet_test/test_storage",
          // Accept-Language request header field.
          "foreign-language",
          // User-Agent request header field.
          "fake agent",
          // JSON encoded experimental options.
          options_json,
          // MockCertVerifier to use for testing purposes.
          std::unique_ptr<net::CertVerifier>(),
          // Enable network quality estimator.
          false,
          // Enable Public Key Pinning bypass for local trust anchors.
          true,
          // Optional network thread priority.
          absl::optional<double>(42.0));

  net::URLRequestContextBuilder builder;
  config->ConfigureURLRequestContextBuilder(&builder);
  EXPECT_FALSE(
      config->effective_experimental_options.contains("UnknownOption"));
  // Set a ProxyConfigService to avoid DCHECK failure when building.
  builder.set_proxy_config_service(
      std::make_unique<net::ProxyConfigServiceFixed>(
          net::ProxyConfigWithAnnotation::CreateDirect()));
  std::unique_ptr<net::URLRequestContext> context(builder.Build());
  const net::QuicParams* quic_params = context->quic_context()->params();
  // Check Quic Connection options.
  quic::QuicTagVector quic_connection_options;
  quic_connection_options.push_back(quic::kTIME);
  quic_connection_options.push_back(quic::kTBBR);
  quic_connection_options.push_back(quic::kREJ);
  EXPECT_EQ(quic_connection_options, quic_params->connection_options);

  // Check QUIC flags.
  EXPECT_TRUE(FLAGS_quic_reloadable_flag_quic_testonly_default_false);
  EXPECT_FALSE(FLAGS_quic_restart_flag_quic_testonly_default_true);

  // Check Custom QUIC User Agent Id.
  EXPECT_EQ("Custom QUIC UAID", quic_params->user_agent_id);

  // Check max_server_configs_stored_in_properties.
  EXPECT_EQ(2u, quic_params->max_server_configs_stored_in_properties);

  // Check idle_connection_timeout.
  EXPECT_EQ(300, quic_params->idle_connection_timeout.InSeconds());

  EXPECT_TRUE(quic_params->close_sessions_on_ip_change);
  EXPECT_FALSE(quic_params->goaway_sessions_on_ip_change);
  EXPECT_FALSE(quic_params->allow_server_migration);
  EXPECT_FALSE(quic_params->migrate_sessions_on_network_change_v2);
  EXPECT_FALSE(quic_params->migrate_sessions_early_v2);
  EXPECT_FALSE(quic_params->migrate_idle_sessions);
  EXPECT_FALSE(quic_params->retry_on_alternate_network_before_handshake);
  EXPECT_FALSE(quic_params->race_stale_dns_on_connection);
  EXPECT_FALSE(quic_params->go_away_on_path_degrading);
  EXPECT_FALSE(quic_params->allow_port_migration);
  EXPECT_FALSE(quic_params->disable_tls_zero_rtt);
  EXPECT_TRUE(quic_params->retry_without_alt_svc_on_quic_errors);
  EXPECT_FALSE(
      quic_params->initial_delay_for_broken_alternative_service.has_value());
  EXPECT_FALSE(quic_params->exponential_backoff_on_initial_delay.has_value());

  // Check network_service_type for iOS.
  EXPECT_EQ(2, quic_params->ios_network_service_type);

#if defined(ENABLE_BUILT_IN_DNS)
  // Check AsyncDNS resolver is enabled (not supported on iOS).
  EXPECT_TRUE(context->host_resolver()->GetDnsConfigAsValue());
#endif  // defined(ENABLE_BUILT_IN_DNS)

#if BUILDFLAG(ENABLE_REPORTING)
  // Check Reporting and Network Error Logging are enabled (can be disabled at
  // build time).
  EXPECT_TRUE(context->reporting_service());
  EXPECT_TRUE(context->network_error_logging_service());
#endif  // BUILDFLAG(ENABLE_REPORTING)

  ASSERT_EQ(2u, config->preloaded_report_to_headers.size());
  EXPECT_EQ(url::Origin::CreateFromNormalizedTuple("https", "test-origin", 443),
            config->preloaded_report_to_headers[0].origin);
  EXPECT_TRUE(JsonHeaderEquals(  //
      R"json(
      {
        "group": "test-group",
        "max_age": 86400,
        "endpoints": [
          {"url": "https://test-endpoint/"},
        ],
      }
      )json",
      config->preloaded_report_to_headers[0].value));
  EXPECT_EQ(
      url::Origin::CreateFromNormalizedTuple("https", "test-origin-2", 443),
      config->preloaded_report_to_headers[1].origin);
  EXPECT_TRUE(JsonHeaderEquals(  //
      R"json(
      {
        "group": "test-group-2",
        "max_age": 86400,
        "endpoints": [
          {"url": "https://test-endpoint-2/"},
        ],
      },
      {
        "group": "test-group-3",
        "max_age": 86400,
        "endpoints": [
          {"url": "https://test-endpoint-3/"},
        ],
      }
      )json",
      config->preloaded_report_to_headers[1].value));

  ASSERT_EQ(1u, config->preloaded_nel_headers.size());
  EXPECT_EQ(url::Origin::CreateFromNormalizedTuple("https", "test-origin", 443),
            config->preloaded_nel_headers[0].origin);
  EXPECT_TRUE(JsonHeaderEquals(  //
      R"json(
      {
        "report_to": "test-group",
        "max_age": 86400,
      }
      )json",
      config->preloaded_nel_headers[0].value));

  // Check IPv6 is disabled when on wifi.
  EXPECT_FALSE(context->host_resolver()
                   ->GetManagerForTesting()
                   ->check_ipv6_on_wifi_for_testing());

  const net::HttpNetworkSessionParams* params =
      context->GetNetworkSessionParams();
  EXPECT_TRUE(params->spdy_go_away_on_ip_change);

  // All host resolution expected to be mapped to an immediately-resolvable IP.
  std::unique_ptr<net::HostResolver::ResolveHostRequest> resolve_request =
      context->host_resolver()->CreateRequest(
          net::HostPortPair("abcde", 80), net::NetworkIsolationKey(),
          net::NetLogWithSource(), absl::nullopt);
  EXPECT_EQ(net::OK, resolve_request->Start(
                         base::BindOnce([](int error) { NOTREACHED(); })));

  EXPECT_TRUE(config->network_thread_priority);
  EXPECT_EQ(42.0, config->network_thread_priority.value());
  EXPECT_FALSE(config->bidi_stream_detect_broken_connection);
}

TEST(URLRequestContextConfigTest, SetSupportedQuicVersion) {
  // Note that this test covers the legacy mechanism which relies on
  // QuicVersionToString. We should now be using ALPNs instead.
  base::test::TaskEnvironment task_environment_(
      base::test::TaskEnvironment::MainThreadType::IO);

  quic::ParsedQuicVersion version =
      quic::AllSupportedVersionsWithQuicCrypto().front();
  std::string experimental_options =
      "{\"QUIC\":{\"quic_version\":\"" +
      quic::QuicVersionToString(version.transport_version) + "\"}}";

  std::unique_ptr<URLRequestContextConfig> config =
      URLRequestContextConfig::CreateURLRequestContextConfig(
          // Enable QUIC.
          true,
          // QUIC User Agent ID.
          "Default QUIC User Agent ID",
          // Enable SPDY.
          true,
          // Enable Brotli.
          false,
          // Type of http cache.
          URLRequestContextConfig::HttpCacheType::DISK,
          // Max size of http cache in bytes.
          1024000,
          // Disable caching for HTTP responses. Other information may be stored
          // in the cache.
          false,
          // Storage path for http cache and cookie storage.
          "/data/data/org.chromium.net/app_cronet_test/test_storage",
          // Accept-Language request header field.
          "foreign-language",
          // User-Agent request header field.
          "fake agent",
          // JSON encoded experimental options.
          experimental_options,
          // MockCertVerifier to use for testing purposes.
          std::unique_ptr<net::CertVerifier>(),
          // Enable network quality estimator.
          false,
          // Enable Public Key Pinning bypass for local trust anchors.
          true,
          // Optional network thread priority.
          absl::optional<double>());

  net::URLRequestContextBuilder builder;
  config->ConfigureURLRequestContextBuilder(&builder);
  // Set a ProxyConfigService to avoid DCHECK failure when building.
  builder.set_proxy_config_service(
      std::make_unique<net::ProxyConfigServiceFixed>(
          net::ProxyConfigWithAnnotation::CreateDirect()));
  std::unique_ptr<net::URLRequestContext> context(builder.Build());
  const net::QuicParams* quic_params = context->quic_context()->params();
  EXPECT_EQ(quic_params->supported_versions.size(), 1u);
  EXPECT_EQ(quic_params->supported_versions[0], version);
}

TEST(URLRequestContextConfigTest, SetSupportedQuicVersionByAlpn) {
  base::test::TaskEnvironment task_environment_(
      base::test::TaskEnvironment::MainThreadType::IO);

  quic::ParsedQuicVersion version = quic::AllSupportedVersions().front();
  std::string experimental_options = "{\"QUIC\":{\"quic_version\":\"" +
                                     quic::ParsedQuicVersionToString(version) +
                                     "\"}}";

  std::unique_ptr<URLRequestContextConfig> config =
      URLRequestContextConfig::CreateURLRequestContextConfig(
          // Enable QUIC.
          true,
          // QUIC User Agent ID.
          "Default QUIC User Agent ID",
          // Enable SPDY.
          true,
          // Enable Brotli.
          false,
          // Type of http cache.
          URLRequestContextConfig::HttpCacheType::DISK,
          // Max size of http cache in bytes.
          1024000,
          // Disable caching for HTTP responses. Other information may be stored
          // in the cache.
          false,
          // Storage path for http cache and cookie storage.
          "/data/data/org.chromium.net/app_cronet_test/test_storage",
          // Accept-Language request header field.
          "foreign-language",
          // User-Agent request header field.
          "fake agent",
          // JSON encoded experimental options.
          experimental_options,
          // MockCertVerifier to use for testing purposes.
          std::unique_ptr<net::CertVerifier>(),
          // Enable network quality estimator.
          false,
          // Enable Public Key Pinning bypass for local trust anchors.
          true,
          // Optional network thread priority.
          absl::optional<double>());

  net::URLRequestContextBuilder builder;
  config->ConfigureURLRequestContextBuilder(&builder);
  // Set a ProxyConfigService to avoid DCHECK failure when building.
  builder.set_proxy_config_service(
      std::make_unique<net::ProxyConfigServiceFixed>(
          net::ProxyConfigWithAnnotation::CreateDirect()));
  std::unique_ptr<net::URLRequestContext> context(builder.Build());
  const net::QuicParams* quic_params = context->quic_context()->params();
  EXPECT_EQ(quic_params->supported_versions.size(), 1u);
  EXPECT_EQ(quic_params->supported_versions[0], version);
}

TEST(URLRequestContextConfigTest, SetUnsupportedQuicVersion) {
  base::test::TaskEnvironment task_environment_(
      base::test::TaskEnvironment::MainThreadType::IO);

  std::unique_ptr<URLRequestContextConfig> config =
      URLRequestContextConfig::CreateURLRequestContextConfig(
          // Enable QUIC.
          true,
          // QUIC User Agent ID.
          "Default QUIC User Agent ID",
          // Enable SPDY.
          true,
          // Enable Brotli.
          false,
          // Type of http cache.
          URLRequestContextConfig::HttpCacheType::DISK,
          // Max size of http cache in bytes.
          1024000,
          // Disable caching for HTTP responses. Other information may be stored
          // in the cache.
          false,
          // Storage path for http cache and cookie storage.
          "/data/data/org.chromium.net/app_cronet_test/test_storage",
          // Accept-Language request header field.
          "foreign-language",
          // User-Agent request header field.
          "fake agent",
          // JSON encoded experimental options.
          "{\"QUIC\":{\"quic_version\":\"h3-Q047\"}}",
          // MockCertVerifier to use for testing purposes.
          std::unique_ptr<net::CertVerifier>(),
          // Enable network quality estimator.
          false,
          // Enable Public Key Pinning bypass for local trust anchors.
          true,
          // Optional network thread priority.
          absl::optional<double>());

  net::URLRequestContextBuilder builder;
  config->ConfigureURLRequestContextBuilder(&builder);
  // Set a ProxyConfigService to avoid DCHECK failure when building.
  builder.set_proxy_config_service(
      std::make_unique<net::ProxyConfigServiceFixed>(
          net::ProxyConfigWithAnnotation::CreateDirect()));
  std::unique_ptr<net::URLRequestContext> context(builder.Build());
  const net::QuicParams* quic_params = context->quic_context()->params();
  EXPECT_EQ(quic_params->supported_versions,
            net::DefaultSupportedQuicVersions());
}

TEST(URLRequestContextConfigTest, SetObsoleteQuicVersion) {
  // This test configures cronet with an obsolete QUIC version and validates
  // that cronet ignores that version and uses the default versions.
  base::test::TaskEnvironment task_environment_(
      base::test::TaskEnvironment::MainThreadType::IO);

  std::unique_ptr<URLRequestContextConfig> config =
      URLRequestContextConfig::CreateURLRequestContextConfig(
          // Enable QUIC.
          true,
          // QUIC User Agent ID.
          "Default QUIC User Agent ID",
          // Enable SPDY.
          true,
          // Enable Brotli.
          false,
          // Type of http cache.
          URLRequestContextConfig::HttpCacheType::DISK,
          // Max size of http cache in bytes.
          1024000,
          // Disable caching for HTTP responses. Other information may be stored
          // in the cache.
          false,
          // Storage path for http cache and cookie storage.
          "/data/data/org.chromium.net/app_cronet_test/test_storage",
          // Accept-Language request header field.
          "foreign-language",
          // User-Agent request header field.
          "fake agent",
          // JSON encoded experimental options.
          std::string("{\"QUIC\":{\"quic_version\":\"") +
              quic::ParsedQuicVersionToString(
                  net::ObsoleteQuicVersions().back()) +
              "\"}}",
          // MockCertVerifier to use for testing purposes.
          std::unique_ptr<net::CertVerifier>(),
          // Enable network quality estimator.
          false,
          // Enable Public Key Pinning bypass for local trust anchors.
          true,
          // Optional network thread priority.
          absl::optional<double>());

  net::URLRequestContextBuilder builder;
  config->ConfigureURLRequestContextBuilder(&builder);
  // Set a ProxyConfigService to avoid DCHECK failure when building.
  builder.set_proxy_config_service(
      std::make_unique<net::ProxyConfigServiceFixed>(
          net::ProxyConfigWithAnnotation::CreateDirect()));
  std::unique_ptr<net::URLRequestContext> context(builder.Build());
  const net::QuicParams* quic_params = context->quic_context()->params();
  EXPECT_EQ(quic_params->supported_versions,
            net::DefaultSupportedQuicVersions());
}

TEST(URLRequestContextConfigTest, SetObsoleteQuicVersionWhenAllowed) {
  // This test configures cronet with an obsolete QUIC version and explicitly
  // allows it, then validates that cronet uses that version.
  base::test::TaskEnvironment task_environment_(
      base::test::TaskEnvironment::MainThreadType::IO);

  std::unique_ptr<URLRequestContextConfig> config =
      URLRequestContextConfig::CreateURLRequestContextConfig(
          // Enable QUIC.
          true,
          // QUIC User Agent ID.
          "Default QUIC User Agent ID",
          // Enable SPDY.
          true,
          // Enable Brotli.
          false,
          // Type of http cache.
          URLRequestContextConfig::HttpCacheType::DISK,
          // Max size of http cache in bytes.
          1024000,
          // Disable caching for HTTP responses. Other information may be stored
          // in the cache.
          false,
          // Storage path for http cache and cookie storage.
          "/data/data/org.chromium.net/app_cronet_test/test_storage",
          // Accept-Language request header field.
          "foreign-language",
          // User-Agent request header field.
          "fake agent",
          // JSON encoded experimental options.
          std::string("{\"QUIC\":{\"quic_version\":\"") +
              quic::ParsedQuicVersionToString(
                  net::ObsoleteQuicVersions().back()) +
              "\",\"obsolete_versions_allowed\":true}}",
          // MockCertVerifier to use for testing purposes.
          std::unique_ptr<net::CertVerifier>(),
          // Enable network quality estimator.
          false,
          // Enable Public Key Pinning bypass for local trust anchors.
          true,
          // Optional network thread priority.
          absl::optional<double>());

  net::URLRequestContextBuilder builder;
  config->ConfigureURLRequestContextBuilder(&builder);
  // Set a ProxyConfigService to avoid DCHECK failure when building.
  builder.set_proxy_config_service(
      std::make_unique<net::ProxyConfigServiceFixed>(
          net::ProxyConfigWithAnnotation::CreateDirect()));
  std::unique_ptr<net::URLRequestContext> context(builder.Build());
  const net::QuicParams* quic_params = context->quic_context()->params();
  quic::ParsedQuicVersionVector supported_versions = {
      net::ObsoleteQuicVersions().back()};
  EXPECT_EQ(quic_params->supported_versions, supported_versions);
}

TEST(URLRequestContextConfigTest, SetQuicServerMigrationOptions) {
  base::test::TaskEnvironment task_environment_(
      base::test::TaskEnvironment::MainThreadType::IO);

  std::unique_ptr<URLRequestContextConfig> config =
      URLRequestContextConfig::CreateURLRequestContextConfig(
          // Enable QUIC.
          true,
          // QUIC User Agent ID.
          "Default QUIC User Agent ID",
          // Enable SPDY.
          true,
          // Enable Brotli.
          false,
          // Type of http cache.
          URLRequestContextConfig::HttpCacheType::DISK,
          // Max size of http cache in bytes.
          1024000,
          // Disable caching for HTTP responses. Other information may be stored
          // in the cache.
          false,
          // Storage path for http cache and cookie storage.
          "/data/data/org.chromium.net/app_cronet_test/test_storage",
          // Accept-Language request header field.
          "foreign-language",
          // User-Agent request header field.
          "fake agent",
          // JSON encoded experimental options.
          "{\"QUIC\":{\"allow_server_migration\":true}}",
          // MockCertVerifier to use for testing purposes.
          std::unique_ptr<net::CertVerifier>(),
          // Enable network quality estimator.
          false,
          // Enable Public Key Pinning bypass for local trust anchors.
          true,
          // Optional network thread priority.
          absl::optional<double>());

  net::URLRequestContextBuilder builder;
  config->ConfigureURLRequestContextBuilder(&builder);
  // Set a ProxyConfigService to avoid DCHECK failure when building.
  builder.set_proxy_config_service(
      std::make_unique<net::ProxyConfigServiceFixed>(
          net::ProxyConfigWithAnnotation::CreateDirect()));
  std::unique_ptr<net::URLRequestContext> context(builder.Build());
  const net::QuicParams* quic_params = context->quic_context()->params();

  EXPECT_FALSE(quic_params->close_sessions_on_ip_change);
  EXPECT_TRUE(quic_params->allow_server_migration);
}

// Test that goaway_sessions_on_ip_change is set on by default for iOS.
#if BUILDFLAG(IS_IOS)
#define MAYBE_SetQuicGoAwaySessionsOnIPChangeByDefault \
  SetQuicGoAwaySessionsOnIPChangeByDefault
#else
#define MAYBE_SetQuicGoAwaySessionsOnIPChangeByDefault \
  DISABLED_SetQuicGoAwaySessionsOnIPChangeByDefault
#endif
TEST(URLRequestContextConfigTest,
     MAYBE_SetQuicGoAwaySessionsOnIPChangeByDefault) {
  base::test::TaskEnvironment task_environment_(
      base::test::TaskEnvironment::MainThreadType::IO);

  std::unique_ptr<URLRequestContextConfig> config =
      URLRequestContextConfig::CreateURLRequestContextConfig(
          // Enable QUIC.
          true,
          // QUIC User Agent ID.
          "Default QUIC User Agent ID",
          // Enable SPDY.
          true,
          // Enable Brotli.
          false,
          // Type of http cache.
          URLRequestContextConfig::HttpCacheType::DISK,
          // Max size of http cache in bytes.
          1024000,
          // Disable caching for HTTP responses. Other information may be stored
          // in the cache.
          false,
          // Storage path for http cache and cookie storage.
          "/data/data/org.chromium.net/app_cronet_test/test_storage",
          // Accept-Language request header field.
          "foreign-language",
          // User-Agent request header field.
          "fake agent",
          // JSON encoded experimental options.
          "{\"QUIC\":{}}",
          // MockCertVerifier to use for testing purposes.
          std::unique_ptr<net::CertVerifier>(),
          // Enable network quality estimator.
          false,
          // Enable Public Key Pinning bypass for local trust anchors.
          true,
          // Optional network thread priority.
          absl::optional<double>());

  net::URLRequestContextBuilder builder;
  config->ConfigureURLRequestContextBuilder(&builder);
  // Set a ProxyConfigService to avoid DCHECK failure when building.
  builder.set_proxy_config_service(
      std::make_unique<net::ProxyConfigServiceFixed>(
          net::ProxyConfigWithAnnotation::CreateDirect()));
  std::unique_ptr<net::URLRequestContext> context(builder.Build());
  const net::QuicParams* quic_params = context->quic_context()->params();

  EXPECT_FALSE(quic_params->close_sessions_on_ip_change);
  EXPECT_TRUE(quic_params->goaway_sessions_on_ip_change);
}

// Tests that goaway_sessions_on_ip_changes can be set on via
// experimental options on non-iOS.
#if !BUILDFLAG(IS_IOS)
#define MAYBE_SetQuicGoAwaySessionsOnIPChangeViaExperimentOptions \
  SetQuicGoAwaySessionsOnIPChangeViaExperimentOptions
#else
#define MAYBE_SetQuicGoAwaySessionsOnIPChangeViaExperimentOptions \
  DISABLED_SetQuicGoAwaySessionsOnIPChangeViaExperimentOptions
#endif
TEST(URLRequestContextConfigTest,
     MAYBE_SetQuicGoAwaySessionsOnIPChangeViaExperimentOptions) {
  base::test::TaskEnvironment task_environment_(
      base::test::TaskEnvironment::MainThreadType::IO);

  std::unique_ptr<URLRequestContextConfig> config =
      URLRequestContextConfig::CreateURLRequestContextConfig(
          // Enable QUIC.
          true,
          // QUIC User Agent ID.
          "Default QUIC User Agent ID",
          // Enable SPDY.
          true,
          // Enable Brotli.
          false,
          // Type of http cache.
          URLRequestContextConfig::HttpCacheType::DISK,
          // Max size of http cache in bytes.
          1024000,
          // Disable caching for HTTP responses. Other information may be stored
          // in the cache.
          false,
          // Storage path for http cache and cookie storage.
          "/data/data/org.chromium.net/app_cronet_test/test_storage",
          // Accept-Language request header field.
          "foreign-language",
          // User-Agent request header field.
          "fake agent",
          // JSON encoded experimental options.
          "{\"QUIC\":{\"goaway_sessions_on_ip_change\":true}}",
          // MockCertVerifier to use for testing purposes.
          std::unique_ptr<net::CertVerifier>(),
          // Enable network quality estimator.
          false,
          // Enable Public Key Pinning bypass for local trust anchors.
          true,
          // Optional network thread priority.
          absl::optional<double>());

  net::URLRequestContextBuilder builder;
  config->ConfigureURLRequestContextBuilder(&builder);
  // Set a ProxyConfigService to avoid DCHECK failure when building.
  builder.set_proxy_config_service(
      std::make_unique<net::ProxyConfigServiceFixed>(
          net::ProxyConfigWithAnnotation::CreateDirect()));
  std::unique_ptr<net::URLRequestContext> context(builder.Build());
  const net::QuicParams* quic_params = context->quic_context()->params();

  EXPECT_FALSE(quic_params->close_sessions_on_ip_change);
  EXPECT_TRUE(quic_params->goaway_sessions_on_ip_change);
}

// Test that goaway_sessions_on_ip_change can be set to false via
// experimental options on iOS.
#if BUILDFLAG(IS_IOS)
#define MAYBE_DisableQuicGoAwaySessionsOnIPChangeViaExperimentOptions \
  DisableQuicGoAwaySessionsOnIPChangeViaExperimentOptions
#else
#define MAYBE_DisableQuicGoAwaySessionsOnIPChangeViaExperimentOptions \
  DISABLED_DisableQuicGoAwaySessionsOnIPChangeViaExperimentOptions
#endif
TEST(URLRequestContextConfigTest,
     MAYBE_DisableQuicGoAwaySessionsOnIPChangeViaExperimentOptions) {
  base::test::TaskEnvironment task_environment_(
      base::test::TaskEnvironment::MainThreadType::IO);

  std::unique_ptr<URLRequestContextConfig> config =
      URLRequestContextConfig::CreateURLRequestContextConfig(
          // Enable QUIC.
          true,
          // QUIC User Agent ID.
          "Default QUIC User Agent ID",
          // Enable SPDY.
          true,
          // Enable Brotli.
          false,
          // Type of http cache.
          URLRequestContextConfig::HttpCacheType::DISK,
          // Max size of http cache in bytes.
          1024000,
          // Disable caching for HTTP responses. Other information may be stored
          // in the cache.
          false,
          // Storage path for http cache and cookie storage.
          "/data/data/org.chromium.net/app_cronet_test/test_storage",
          // Accept-Language request header field.
          "foreign-language",
          // User-Agent request header field.
          "fake agent",
          // JSON encoded experimental options.
          "{\"QUIC\":{\"goaway_sessions_on_ip_change\":false}}",
          // MockCertVerifier to use for testing purposes.
          std::unique_ptr<net::CertVerifier>(),
          // Enable network quality estimator.
          false,
          // Enable Public Key Pinning bypass for local trust anchors.
          true,
          // Optional network thread priority.
          absl::optional<double>());

  net::URLRequestContextBuilder builder;
  config->ConfigureURLRequestContextBuilder(&builder);
  // Set a ProxyConfigService to avoid DCHECK failure when building.
  builder.set_proxy_config_service(
      std::make_unique<net::ProxyConfigServiceFixed>(
          net::ProxyConfigWithAnnotation::CreateDirect()));
  std::unique_ptr<net::URLRequestContext> context(builder.Build());
  const net::QuicParams* quic_params = context->quic_context()->params();

  EXPECT_FALSE(quic_params->close_sessions_on_ip_change);
  EXPECT_FALSE(quic_params->goaway_sessions_on_ip_change);
}

TEST(URLRequestContextConfigTest, SetQuicConnectionMigrationV2Options) {
  base::test::TaskEnvironment task_environment_(
      base::test::TaskEnvironment::MainThreadType::IO);

  std::unique_ptr<URLRequestContextConfig> config =
      URLRequestContextConfig::CreateURLRequestContextConfig(
          // Enable QUIC.
          true,
          // QUIC User Agent ID.
          "Default QUIC User Agent ID",
          // Enable SPDY.
          true,
          // Enable Brotli.
          false,
          // Type of http cache.
          URLRequestContextConfig::HttpCacheType::DISK,
          // Max size of http cache in bytes.
          1024000,
          // Disable caching for HTTP responses. Other information may be stored
          // in the cache.
          false,
          // Storage path for http cache and cookie storage.
          "/data/data/org.chromium.net/app_cronet_test/test_storage",
          // Accept-Language request header field.
          "foreign-language",
          // User-Agent request header field.
          "fake agent",
          // JSON encoded experimental options.
          // Explicitly turn off "goaway_sessions_on_ip_change" which is default
          // enabled on iOS but cannot be simultaneously set with migration
          // option.
          "{\"QUIC\":{\"migrate_sessions_on_network_change_v2\":true,"
          "\"goaway_sessions_on_ip_change\":false,"
          "\"migrate_sessions_early_v2\":true,"
          "\"retry_on_alternate_network_before_handshake\":true,"
          "\"migrate_idle_sessions\":true,"
          "\"retransmittable_on_wire_timeout_milliseconds\":1000,"
          "\"idle_session_migration_period_seconds\":15,"
          "\"max_time_on_non_default_network_seconds\":10,"
          "\"max_migrations_to_non_default_network_on_write_error\":3,"
          "\"max_migrations_to_non_default_network_on_path_degrading\":4}}",
          // MockCertVerifier to use for testing purposes.
          std::unique_ptr<net::CertVerifier>(),
          // Enable network quality estimator.
          false,
          // Enable Public Key Pinning bypass for local trust anchors.
          true,
          // Optional network thread priority.
          absl::optional<double>());

  net::URLRequestContextBuilder builder;
  config->ConfigureURLRequestContextBuilder(&builder);
  // Set a ProxyConfigService to avoid DCHECK failure when building.
  builder.set_proxy_config_service(
      std::make_unique<net::ProxyConfigServiceFixed>(
          net::ProxyConfigWithAnnotation::CreateDirect()));
  std::unique_ptr<net::URLRequestContext> context(builder.Build());
  const net::QuicParams* quic_params = context->quic_context()->params();

  EXPECT_TRUE(quic_params->migrate_sessions_on_network_change_v2);
  EXPECT_TRUE(quic_params->migrate_sessions_early_v2);
  EXPECT_TRUE(quic_params->retry_on_alternate_network_before_handshake);
  EXPECT_EQ(1000,
            quic_params->retransmittable_on_wire_timeout.InMilliseconds());
  EXPECT_TRUE(quic_params->migrate_idle_sessions);
  EXPECT_EQ(base::Seconds(15), quic_params->idle_session_migration_period);
  EXPECT_EQ(base::Seconds(10), quic_params->max_time_on_non_default_network);
  EXPECT_EQ(3,
            quic_params->max_migrations_to_non_default_network_on_write_error);
  EXPECT_EQ(
      4, quic_params->max_migrations_to_non_default_network_on_path_degrading);
  EXPECT_EQ(net::DefaultSupportedQuicVersions(),
            quic_params->supported_versions);
}

TEST(URLRequestContextConfigTest, SetQuicStaleDNSracing) {
  base::test::TaskEnvironment task_environment_(
      base::test::TaskEnvironment::MainThreadType::IO);

  std::unique_ptr<URLRequestContextConfig> config =
      URLRequestContextConfig::CreateURLRequestContextConfig(
          // Enable QUIC.
          true,
          // QUIC User Agent ID.
          "Default QUIC User Agent ID",
          // Enable SPDY.
          true,
          // Enable Brotli.
          false,
          // Type of http cache.
          URLRequestContextConfig::HttpCacheType::DISK,
          // Max size of http cache in bytes.
          1024000,
          // Disable caching for HTTP responses. Other information may be stored
          // in the cache.
          false,
          // Storage path for http cache and cookie storage.
          "/data/data/org.chromium.net/app_cronet_test/test_storage",
          // Accept-Language request header field.
          "foreign-language",
          // User-Agent request header field.
          "fake agent",
          // JSON encoded experimental options.
          "{\"QUIC\":{\"race_stale_dns_on_connection\":true}}",
          // MockCertVerifier to use for testing purposes.
          std::unique_ptr<net::CertVerifier>(),
          // Enable network quality estimator.
          false,
          // Enable Public Key Pinning bypass for local trust anchors.
          true,
          // Optional network thread priority.
          absl::optional<double>());

  net::URLRequestContextBuilder builder;
  config->ConfigureURLRequestContextBuilder(&builder);
  // Set a ProxyConfigService to avoid DCHECK failure when building.
  builder.set_proxy_config_service(
      std::make_unique<net::ProxyConfigServiceFixed>(
          net::ProxyConfigWithAnnotation::CreateDirect()));
  std::unique_ptr<net::URLRequestContext> context(builder.Build());
  const net::QuicParams* quic_params = context->quic_context()->params();

  EXPECT_TRUE(quic_params->race_stale_dns_on_connection);
}

TEST(URLRequestContextConfigTest, SetQuicAllowPortMigration) {
  base::test::TaskEnvironment task_environment_(
      base::test::TaskEnvironment::MainThreadType::IO);
  std::unique_ptr<URLRequestContextConfig> config =
      URLRequestContextConfig::CreateURLRequestContextConfig(
          // Enable QUIC.
          true,
          // QUIC User Agent ID.
          "Default QUIC User Agent ID",
          // Enable SPDY.
          true,
          // Enable Brotli.
          false,
          // Type of http cache.
          URLRequestContextConfig::HttpCacheType::DISK,
          // Max size of http cache in bytes.
          1024000,
          // Disable caching for HTTP responses. Other information may be stored
          // in the cache.
          false,
          // Storage path for http cache and cookie storage.
          "/data/data/org.chromium.net/app_cronet_test/test_storage",
          // Accept-Language request header field.
          "foreign-language",
          // User-Agent request header field.
          "fake agent",
          // JSON encoded experimental options.
          "{\"QUIC\":{\"allow_port_migration\":true}}",
          // MockCertVerifier to use for testing purposes.
          std::unique_ptr<net::CertVerifier>(),
          // Enable network quality estimator.
          false,
          // Enable Public Key Pinning bypass for local trust anchors.
          true,
          // Optional network thread priority.
          absl::optional<double>());

  net::URLRequestContextBuilder builder;
  config->ConfigureURLRequestContextBuilder(&builder);
  // Set a ProxyConfigService to avoid DCHECK failure when building.
  builder.set_proxy_config_service(
      std::make_unique<net::ProxyConfigServiceFixed>(
          net::ProxyConfigWithAnnotation::CreateDirect()));
  std::unique_ptr<net::URLRequestContext> context(builder.Build());
  const net::QuicParams* quic_params = context->quic_context()->params();

  EXPECT_TRUE(quic_params->allow_port_migration);
}

TEST(URLRequestContextConfigTest, DisableQuicRetryWithoutAltSvcOnQuicErrors) {
  base::test::TaskEnvironment task_environment_(
      base::test::TaskEnvironment::MainThreadType::IO);
  std::unique_ptr<URLRequestContextConfig> config =
      URLRequestContextConfig::CreateURLRequestContextConfig(
          // Enable QUIC.
          true,
          // QUIC User Agent ID.
          "Default QUIC User Agent ID",
          // Enable SPDY.
          true,
          // Enable Brotli.
          false,
          // Type of http cache.
          URLRequestContextConfig::HttpCacheType::DISK,
          // Max size of http cache in bytes.
          1024000,
          // Disable caching for HTTP responses. Other information may be stored
          // in the cache.
          false,
          // Storage path for http cache and cookie storage.
          "/data/data/org.chromium.net/app_cronet_test/test_storage",
          // Accept-Language request header field.
          "foreign-language",
          // User-Agent request header field.
          "fake agent",
          // JSON encoded experimental options.
          "{\"QUIC\":{\"retry_without_alt_svc_on_quic_errors\":false}}",
          // MockCertVerifier to use for testing purposes.
          std::unique_ptr<net::CertVerifier>(),
          // Enable network quality estimator.
          false,
          // Enable Public Key Pinning bypass for local trust anchors.
          true,
          // Optional network thread priority.
          absl::optional<double>());

  net::URLRequestContextBuilder builder;
  config->ConfigureURLRequestContextBuilder(&builder);
  // Set a ProxyConfigService to avoid DCHECK failure when building.
  builder.set_proxy_config_service(
      std::make_unique<net::ProxyConfigServiceFixed>(
          net::ProxyConfigWithAnnotation::CreateDirect()));
  std::unique_ptr<net::URLRequestContext> context(builder.Build());
  const net::QuicParams* quic_params = context->quic_context()->params();

  EXPECT_FALSE(quic_params->retry_without_alt_svc_on_quic_errors);
}

TEST(URLRequestContextConfigTest, BrokenAlternativeServiceDelayParams1) {
  base::test::TaskEnvironment task_environment_(
      base::test::TaskEnvironment::MainThreadType::IO);
  std::unique_ptr<URLRequestContextConfig> config =
      URLRequestContextConfig::CreateURLRequestContextConfig(
          // Enable QUIC.
          true,
          // QUIC User Agent ID.
          "Default QUIC User Agent ID",
          // Enable SPDY.
          true,
          // Enable Brotli.
          false,
          // Type of http cache.
          URLRequestContextConfig::HttpCacheType::DISK,
          // Max size of http cache in bytes.
          1024000,
          // Disable caching for HTTP responses. Other information may be stored
          // in the cache.
          false,
          // Storage path for http cache and cookie storage.
          "/data/data/org.chromium.net/app_cronet_test/test_storage",
          // Accept-Language request header field.
          "foreign-language",
          // User-Agent request header field.
          "fake agent",
          // JSON encoded experimental options.
          "{\"QUIC\":{\"initial_delay_for_broken_alternative_service_seconds\":"
          "1,"
          "\"exponential_backoff_on_initial_delay\":true}}",
          // MockCertVerifier to use for testing purposes.
          std::unique_ptr<net::CertVerifier>(),
          // Enable network quality estimator.
          false,
          // Enable Public Key Pinning bypass for local trust anchors.
          true,
          // Optional network thread priority.
          absl::optional<double>());

  net::URLRequestContextBuilder builder;
  config->ConfigureURLRequestContextBuilder(&builder);
  // Set a ProxyConfigService to avoid DCHECK failure when building.
  builder.set_proxy_config_service(
      std::make_unique<net::ProxyConfigServiceFixed>(
          net::ProxyConfigWithAnnotation::CreateDirect()));
  std::unique_ptr<net::URLRequestContext> context(builder.Build());
  const net::QuicParams* quic_params = context->quic_context()->params();

  ASSERT_TRUE(
      quic_params->initial_delay_for_broken_alternative_service.has_value());
  EXPECT_EQ(base::Seconds(1),
            quic_params->initial_delay_for_broken_alternative_service.value());
  ASSERT_TRUE(quic_params->exponential_backoff_on_initial_delay.has_value());
  EXPECT_TRUE(quic_params->exponential_backoff_on_initial_delay.value());
}

TEST(URLRequestContextConfigTest, BrokenAlternativeServiceDelayParams2) {
  base::test::TaskEnvironment task_environment_(
      base::test::TaskEnvironment::MainThreadType::IO);
  std::unique_ptr<URLRequestContextConfig> config =
      URLRequestContextConfig::CreateURLRequestContextConfig(
          // Enable QUIC.
          true,
          // QUIC User Agent ID.
          "Default QUIC User Agent ID",
          // Enable SPDY.
          true,
          // Enable Brotli.
          false,
          // Type of http cache.
          URLRequestContextConfig::HttpCacheType::DISK,
          // Max size of http cache in bytes.
          1024000,
          // Disable caching for HTTP responses. Other information may be stored
          // in the cache.
          false,
          // Storage path for http cache and cookie storage.
          "/data/data/org.chromium.net/app_cronet_test/test_storage",
          // Accept-Language request header field.
          "foreign-language",
          // User-Agent request header field.
          "fake agent",
          // JSON encoded experimental options.
          "{\"QUIC\":{\"initial_delay_for_broken_alternative_service_seconds\":"
          "5,"
          "\"exponential_backoff_on_initial_delay\":false}}",
          // MockCertVerifier to use for testing purposes.
          std::unique_ptr<net::CertVerifier>(),
          // Enable network quality estimator.
          false,
          // Enable Public Key Pinning bypass for local trust anchors.
          true,
          // Optional network thread priority.
          absl::optional<double>());

  net::URLRequestContextBuilder builder;
  config->ConfigureURLRequestContextBuilder(&builder);
  // Set a ProxyConfigService to avoid DCHECK failure when building.
  builder.set_proxy_config_service(
      std::make_unique<net::ProxyConfigServiceFixed>(
          net::ProxyConfigWithAnnotation::CreateDirect()));
  std::unique_ptr<net::URLRequestContext> context(builder.Build());
  const net::QuicParams* quic_params = context->quic_context()->params();

  ASSERT_TRUE(
      quic_params->initial_delay_for_broken_alternative_service.has_value());
  EXPECT_EQ(base::Seconds(5),
            quic_params->initial_delay_for_broken_alternative_service.value());
  ASSERT_TRUE(quic_params->exponential_backoff_on_initial_delay.has_value());
  EXPECT_FALSE(quic_params->exponential_backoff_on_initial_delay.value());
}

TEST(URLRequestContextConfigTest, SetDisableTlsZeroRtt) {
  base::test::TaskEnvironment task_environment_(
      base::test::TaskEnvironment::MainThreadType::IO);
  std::unique_ptr<URLRequestContextConfig> config =
      URLRequestContextConfig::CreateURLRequestContextConfig(
          // Enable QUIC.
          true,
          // QUIC User Agent ID.
          "Default QUIC User Agent ID",
          // Enable SPDY.
          true,
          // Enable Brotli.
          false,
          // Type of http cache.
          URLRequestContextConfig::HttpCacheType::DISK,
          // Max size of http cache in bytes.
          1024000,
          // Disable caching for HTTP responses. Other information may be stored
          // in the cache.
          false,
          // Storage path for http cache and cookie storage.
          "/data/data/org.chromium.net/app_cronet_test/test_storage",
          // Accept-Language request header field.
          "foreign-language",
          // User-Agent request header field.
          "fake agent",
          // JSON encoded experimental options.
          "{\"QUIC\":{\"disable_tls_zero_rtt\":true}}",
          // MockCertVerifier to use for testing purposes.
          std::unique_ptr<net::CertVerifier>(),
          // Enable network quality estimator.
          false,
          // Enable Public Key Pinning bypass for local trust anchors.
          true,
          // Optional network thread priority.
          absl::optional<double>());

  net::URLRequestContextBuilder builder;
  config->ConfigureURLRequestContextBuilder(&builder);
  // Set a ProxyConfigService to avoid DCHECK failure when building.
  builder.set_proxy_config_service(
      std::make_unique<net::ProxyConfigServiceFixed>(
          net::ProxyConfigWithAnnotation::CreateDirect()));
  std::unique_ptr<net::URLRequestContext> context(builder.Build());
  const net::QuicParams* quic_params = context->quic_context()->params();

  EXPECT_TRUE(quic_params->disable_tls_zero_rtt);
}

TEST(URLRequestContextConfigTest, SetQuicGoawayOnPathDegrading) {
  base::test::TaskEnvironment task_environment_(
      base::test::TaskEnvironment::MainThreadType::IO);

  std::unique_ptr<URLRequestContextConfig> config =
      URLRequestContextConfig::CreateURLRequestContextConfig(
          // Enable QUIC.
          true,
          // QUIC User Agent ID.
          "Default QUIC User Agent ID",
          // Enable SPDY.
          true,
          // Enable Brotli.
          false,
          // Type of http cache.
          URLRequestContextConfig::HttpCacheType::DISK,
          // Max size of http cache in bytes.
          1024000,
          // Disable caching for HTTP responses. Other information may be stored
          // in the cache.
          false,
          // Storage path for http cache and cookie storage.
          "/data/data/org.chromium.net/app_cronet_test/test_storage",
          // Accept-Language request header field.
          "foreign-language",
          // User-Agent request header field.
          "fake agent",
          // JSON encoded experimental options.
          "{\"QUIC\":{\"go_away_on_path_degrading\":true}}",
          // MockCertVerifier to use for testing purposes.
          std::unique_ptr<net::CertVerifier>(),
          // Enable network quality estimator.
          false,
          // Enable Public Key Pinning bypass for local trust anchors.
          true,
          // Optional network thread priority.
          absl::optional<double>());

  net::URLRequestContextBuilder builder;
  config->ConfigureURLRequestContextBuilder(&builder);
  // Set a ProxyConfigService to avoid DCHECK failure when building.
  builder.set_proxy_config_service(
      std::make_unique<net::ProxyConfigServiceFixed>(
          net::ProxyConfigWithAnnotation::CreateDirect()));
  std::unique_ptr<net::URLRequestContext> context(builder.Build());
  const net::QuicParams* quic_params = context->quic_context()->params();

  EXPECT_TRUE(quic_params->go_away_on_path_degrading);
}

TEST(URLRequestContextConfigTest, SetQuicHostWhitelist) {
  base::test::TaskEnvironment task_environment_(
      base::test::TaskEnvironment::MainThreadType::IO);

  std::unique_ptr<URLRequestContextConfig> config =
      URLRequestContextConfig::CreateURLRequestContextConfig(
          // Enable QUIC.
          true,
          // QUIC User Agent ID.
          "Default QUIC User Agent ID",
          // Enable SPDY.
          true,
          // Enable Brotli.
          false,
          // Type of http cache.
          URLRequestContextConfig::HttpCacheType::DISK,
          // Max size of http cache in bytes.
          1024000,
          // Disable caching for HTTP responses. Other information may be stored
          // in the cache.
          false,
          // Storage path for http cache and cookie storage.
          "/data/data/org.chromium.net/app_cronet_test/test_storage",
          // Accept-Language request header field.
          "foreign-language",
          // User-Agent request header field.
          "fake agent",
          // JSON encoded experimental options.
          "{\"QUIC\":{\"host_whitelist\":\"www.example.com,www.example.org\"}}",
          // MockCertVerifier to use for testing purposes.
          std::unique_ptr<net::CertVerifier>(),
          // Enable network quality estimator.
          false,
          // Enable Public Key Pinning bypass for local trust anchors.
          true,
          // Optional network thread priority.
          absl::optional<double>());

  net::URLRequestContextBuilder builder;
  config->ConfigureURLRequestContextBuilder(&builder);
  // Set a ProxyConfigService to avoid DCHECK failure when building.
  builder.set_proxy_config_service(
      std::make_unique<net::ProxyConfigServiceFixed>(
          net::ProxyConfigWithAnnotation::CreateDirect()));
  std::unique_ptr<net::URLRequestContext> context(builder.Build());
  const net::HttpNetworkSessionParams* params =
      context->GetNetworkSessionParams();

  EXPECT_TRUE(base::Contains(params->quic_host_allowlist, "www.example.com"));
  EXPECT_TRUE(base::Contains(params->quic_host_allowlist, "www.example.org"));
}

TEST(URLRequestContextConfigTest, SetQuicMaxTimeBeforeCryptoHandshake) {
  base::test::TaskEnvironment task_environment_(
      base::test::TaskEnvironment::MainThreadType::IO);

  std::unique_ptr<URLRequestContextConfig> config =
      URLRequestContextConfig::CreateURLRequestContextConfig(
          // Enable QUIC.
          true,
          // QUIC User Agent ID.
          "Default QUIC User Agent ID",
          // Enable SPDY.
          true,
          // Enable Brotli.
          false,
          // Type of http cache.
          URLRequestContextConfig::HttpCacheType::DISK,
          // Max size of http cache in bytes.
          1024000,
          // Disable caching for HTTP responses. Other information may be stored
          // in the cache.
          false,
          // Storage path for http cache and cookie storage.
          "/data/data/org.chromium.net/app_cronet_test/test_storage",
          // Accept-Language request header field.
          "foreign-language",
          // User-Agent request header field.
          "fake agent",
          // JSON encoded experimental options.
          "{\"QUIC\":{\"max_time_before_crypto_handshake_seconds\":7,"
          "\"max_idle_time_before_crypto_handshake_seconds\":11}}",
          // MockCertVerifier to use for testing purposes.
          std::unique_ptr<net::CertVerifier>(),
          // Enable network quality estimator.
          false,
          // Enable Public Key Pinning bypass for local trust anchors.
          true,
          // Optional network thread priority.
          absl::optional<double>());

  net::URLRequestContextBuilder builder;
  config->ConfigureURLRequestContextBuilder(&builder);
  // Set a ProxyConfigService to avoid DCHECK failure when building.
  builder.set_proxy_config_service(
      std::make_unique<net::ProxyConfigServiceFixed>(
          net::ProxyConfigWithAnnotation::CreateDirect()));
  std::unique_ptr<net::URLRequestContext> context(builder.Build());
  const net::QuicParams* quic_params = context->quic_context()->params();

  EXPECT_EQ(7, quic_params->max_time_before_crypto_handshake.InSeconds());
  EXPECT_EQ(11, quic_params->max_idle_time_before_crypto_handshake.InSeconds());
}

TEST(URLURLRequestContextConfigTest, SetQuicConnectionOptions) {
  base::test::TaskEnvironment task_environment_(
      base::test::TaskEnvironment::MainThreadType::IO);

  std::unique_ptr<URLRequestContextConfig> config =
      URLRequestContextConfig::CreateURLRequestContextConfig(
          // Enable QUIC.
          true,
          // QUIC User Agent ID.
          "Default QUIC User Agent ID",
          // Enable SPDY.
          true,
          // Enable Brotli.
          false,
          // Type of http cache.
          URLRequestContextConfig::HttpCacheType::DISK,
          // Max size of http cache in bytes.
          1024000,
          // Disable caching for HTTP responses. Other information may be stored
          // in the cache.
          false,
          // Storage path for http cache and cookie storage.
          "/data/data/org.chromium.net/app_cronet_test/test_storage",
          // Accept-Language request header field.
          "foreign-language",
          // User-Agent request header field.
          "fake agent",
          // JSON encoded experimental options.
          "{\"QUIC\":{\"connection_options\":\"TIME,TBBR,REJ\","
          "\"client_connection_options\":\"TBBR,1RTT\"}}",
          // MockCertVerifier to use for testing purposes.
          std::unique_ptr<net::CertVerifier>(),
          // Enable network quality estimator.
          false,
          // Enable Public Key Pinning bypass for local trust anchors.
          true,
          // Optional network thread priority.
          absl::optional<double>());

  net::URLRequestContextBuilder builder;
  config->ConfigureURLRequestContextBuilder(&builder);
  // Set a ProxyConfigService to avoid DCHECK failure when building.
  builder.set_proxy_config_service(
      std::make_unique<net::ProxyConfigServiceFixed>(
          net::ProxyConfigWithAnnotation::CreateDirect()));
  std::unique_ptr<net::URLRequestContext> context(builder.Build());
  const net::QuicParams* quic_params = context->quic_context()->params();

  quic::QuicTagVector connection_options;
  connection_options.push_back(quic::kTIME);
  connection_options.push_back(quic::kTBBR);
  connection_options.push_back(quic::kREJ);
  EXPECT_EQ(connection_options, quic_params->connection_options);

  quic::QuicTagVector client_connection_options;
  client_connection_options.push_back(quic::kTBBR);
  client_connection_options.push_back(quic::k1RTT);
  EXPECT_EQ(client_connection_options, quic_params->client_connection_options);
}

TEST(URLURLRequestContextConfigTest, SetAcceptLanguageAndUserAgent) {
  base::test::TaskEnvironment task_environment_(
      base::test::TaskEnvironment::MainThreadType::IO);

  std::unique_ptr<URLRequestContextConfig> config =
      URLRequestContextConfig::CreateURLRequestContextConfig(
          // Enable QUIC.
          true,
          // QUIC User Agent ID.
          "Default QUIC User Agent ID",
          // Enable SPDY.
          true,
          // Enable Brotli.
          false,
          // Type of http cache.
          URLRequestContextConfig::HttpCacheType::DISK,
          // Max size of http cache in bytes.
          1024000,
          // Disable caching for HTTP responses. Other information may be stored
          // in the cache.
          false,
          // Storage path for http cache and cookie storage.
          "/data/data/org.chromium.net/app_cronet_test/test_storage",
          // Accept-Language request header field.
          "foreign-language",
          // User-Agent request header field.
          "fake agent",
          // JSON encoded experimental options.
          "{}",
          // MockCertVerifier to use for testing purposes.
          std::unique_ptr<net::CertVerifier>(),
          // Enable network quality estimator.
          false,
          // Enable Public Key Pinning bypass for local trust anchors.
          true,
          // Optional network thread priority.
          absl::optional<double>());

  net::URLRequestContextBuilder builder;
  config->ConfigureURLRequestContextBuilder(&builder);
  // Set a ProxyConfigService to avoid DCHECK failure when building.
  builder.set_proxy_config_service(
      std::make_unique<net::ProxyConfigServiceFixed>(
          net::ProxyConfigWithAnnotation::CreateDirect()));
  std::unique_ptr<net::URLRequestContext> context(builder.Build());
  EXPECT_EQ("foreign-language",
            context->http_user_agent_settings()->GetAcceptLanguage());
  EXPECT_EQ("fake agent", context->http_user_agent_settings()->GetUserAgent());
}

TEST(URLURLRequestContextConfigTest, TurningOffQuic) {
  base::test::TaskEnvironment task_environment_(
      base::test::TaskEnvironment::MainThreadType::IO);

  std::unique_ptr<URLRequestContextConfig> config =
      URLRequestContextConfig::CreateURLRequestContextConfig(
          // Enable QUIC.
          false,
          // QUIC User Agent ID.
          "Default QUIC User Agent ID",
          // Enable SPDY.
          true,
          // Enable Brotli.
          false,
          // Type of http cache.
          URLRequestContextConfig::HttpCacheType::DISK,
          // Max size of http cache in bytes.
          1024000,
          // Disable caching for HTTP responses. Other information may be stored
          // in the cache.
          false,
          // Storage path for http cache and cookie storage.
          "/data/data/org.chromium.net/app_cronet_test/test_storage",
          // Accept-Language request header field.
          "foreign-language",
          // User-Agent request header field.
          "fake agent",
          // JSON encoded experimental options.
          "{}",
          // MockCertVerifier to use for testing purposes.
          std::unique_ptr<net::CertVerifier>(),
          // Enable network quality estimator.
          false,
          // Enable Public Key Pinning bypass for local trust anchors.
          true,
          // Optional network thread priority.
          absl::optional<double>());

  net::URLRequestContextBuilder builder;
  config->ConfigureURLRequestContextBuilder(&builder);
  // Set a ProxyConfigService to avoid DCHECK failure when building.
  builder.set_proxy_config_service(
      std::make_unique<net::ProxyConfigServiceFixed>(
          net::ProxyConfigWithAnnotation::CreateDirect()));
  std::unique_ptr<net::URLRequestContext> context(builder.Build());
  const net::HttpNetworkSessionParams* params =
      context->GetNetworkSessionParams();
  EXPECT_EQ(false, params->enable_quic);
}

TEST(URLURLRequestContextConfigTest, DefaultEnableQuic) {
  base::test::TaskEnvironment task_environment_(
      base::test::TaskEnvironment::MainThreadType::IO);

  URLRequestContextConfigBuilder config_builder;
  std::unique_ptr<URLRequestContextConfig> config = config_builder.Build();
  net::URLRequestContextBuilder builder;
  config->ConfigureURLRequestContextBuilder(&builder);
  // Set a ProxyConfigService to avoid DCHECK failure when building.
  builder.set_proxy_config_service(
      std::make_unique<net::ProxyConfigServiceFixed>(
          net::ProxyConfigWithAnnotation::CreateDirect()));
  std::unique_ptr<net::URLRequestContext> context(builder.Build());
  const net::HttpNetworkSessionParams* params =
      context->GetNetworkSessionParams();
  EXPECT_EQ(true, params->enable_quic);
}

TEST(URLRequestContextConfigTest, SetSpdyGoAwayOnIPChange) {
  base::test::TaskEnvironment task_environment_(
      base::test::TaskEnvironment::MainThreadType::IO);

  std::unique_ptr<URLRequestContextConfig> config =
      URLRequestContextConfig::CreateURLRequestContextConfig(
          // Enable QUIC.
          true,
          // QUIC User Agent ID.
          "Default QUIC User Agent ID",
          // Enable SPDY.
          true,
          // Enable Brotli.
          false,
          // Type of http cache.
          URLRequestContextConfig::HttpCacheType::DISK,
          // Max size of http cache in bytes.
          1024000,
          // Disable caching for HTTP responses. Other information may be stored
          // in the cache.
          false,
          // Storage path for http cache and cookie storage.
          "/data/data/org.chromium.net/app_cronet_test/test_storage",
          // Accept-Language request header field.
          "foreign-language",
          // User-Agent request header field.
          "fake agent",
          // JSON encoded experimental options.
          "{\"spdy_go_away_on_ip_change\":false}",
          // MockCertVerifier to use for testing purposes.
          std::unique_ptr<net::CertVerifier>(),
          // Enable network quality estimator.
          false,
          // Enable Public Key Pinning bypass for local trust anchors.
          true,
          // Optional network thread priority.
          absl::optional<double>());

  net::URLRequestContextBuilder builder;
  config->ConfigureURLRequestContextBuilder(&builder);
  // Set a ProxyConfigService to avoid DCHECK failure when building.
  builder.set_proxy_config_service(
      std::make_unique<net::ProxyConfigServiceFixed>(
          net::ProxyConfigWithAnnotation::CreateDirect()));
  std::unique_ptr<net::URLRequestContext> context(builder.Build());
  const net::HttpNetworkSessionParams* params =
      context->GetNetworkSessionParams();
  EXPECT_FALSE(params->spdy_go_away_on_ip_change);
}

TEST(URLRequestContextConfigTest, WrongSpdyGoAwayOnIPChangeValue) {
  base::test::TaskEnvironment task_environment_(
      base::test::TaskEnvironment::MainThreadType::IO);

  std::unique_ptr<URLRequestContextConfig> config =
      URLRequestContextConfig::CreateURLRequestContextConfig(
          // Enable QUIC.
          true,
          // QUIC User Agent ID.
          "Default QUIC User Agent ID",
          // Enable SPDY.
          true,
          // Enable Brotli.
          false,
          // Type of http cache.
          URLRequestContextConfig::HttpCacheType::DISK,
          // Max size of http cache in bytes.
          1024000,
          // Disable caching for HTTP responses. Other information may be stored
          // in the cache.
          false,
          // Storage path for http cache and cookie storage.
          "/data/data/org.chromium.net/app_cronet_test/test_storage",
          // Accept-Language request header field.
          "foreign-language",
          // User-Agent request header field.
          "fake agent",
          // JSON encoded experimental options.
          "{\"spdy_go_away_on_ip_change\":\"not a bool\"}",
          // MockCertVerifier to use for testing purposes.
          std::unique_ptr<net::CertVerifier>(),
          // Enable network quality estimator.
          false,
          // Enable Public Key Pinning bypass for local trust anchors.
          true,
          // Optional network thread priority.
          absl::optional<double>());

  net::URLRequestContextBuilder builder;
  config->ConfigureURLRequestContextBuilder(&builder);
  EXPECT_FALSE(config->effective_experimental_options.contains(
      "spdy_go_away_on_ip_change"));
}

TEST(URLRequestContextConfigTest, BidiStreamDetectBrokenConnection) {
  base::test::TaskEnvironment task_environment_(
      base::test::TaskEnvironment::MainThreadType::IO);

  std::unique_ptr<URLRequestContextConfig> config =
      URLRequestContextConfig::CreateURLRequestContextConfig(
          // Enable QUIC.
          true,
          // QUIC User Agent ID.
          "Default QUIC User Agent ID",
          // Enable SPDY.
          true,
          // Enable Brotli.
          false,
          // Type of http cache.
          URLRequestContextConfig::HttpCacheType::DISK,
          // Max size of http cache in bytes.
          1024000,
          // Disable caching for HTTP responses. Other information may be stored
          // in the cache.
          false,
          // Storage path for http cache and cookie storage.
          "/data/data/org.chromium.net/app_cronet_test/test_storage",
          // Accept-Language request header field.
          "foreign-language",
          // User-Agent request header field.
          "fake agent",
          // JSON encoded experimental options.
          "{\"bidi_stream_detect_broken_connection\":10}",
          // MockCertVerifier to use for testing purposes.
          std::unique_ptr<net::CertVerifier>(),
          // Enable network quality estimator.
          false,
          // Enable Public Key Pinning bypass for local trust anchors.
          true,
          // Optional network thread priority.
          absl::optional<double>());

  net::URLRequestContextBuilder builder;
  config->ConfigureURLRequestContextBuilder(&builder);
  EXPECT_TRUE(config->effective_experimental_options.contains(
      "bidi_stream_detect_broken_connection"));
  EXPECT_TRUE(config->bidi_stream_detect_broken_connection);
  EXPECT_EQ(config->heartbeat_interval, base::Seconds(10));
}

TEST(URLRequestContextConfigTest, WrongBidiStreamDetectBrokenConnectionValue) {
  base::test::TaskEnvironment task_environment_(
      base::test::TaskEnvironment::MainThreadType::IO);

  std::unique_ptr<URLRequestContextConfig> config =
      URLRequestContextConfig::CreateURLRequestContextConfig(
          // Enable QUIC.
          true,
          // QUIC User Agent ID.
          "Default QUIC User Agent ID",
          // Enable SPDY.
          true,
          // Enable Brotli.
          false,
          // Type of http cache.
          URLRequestContextConfig::HttpCacheType::DISK,
          // Max size of http cache in bytes.
          1024000,
          // Disable caching for HTTP responses. Other information may be stored
          // in the cache.
          false,
          // Storage path for http cache and cookie storage.
          "/data/data/org.chromium.net/app_cronet_test/test_storage",
          // Accept-Language request header field.
          "foreign-language",
          // User-Agent request header field.
          "fake agent",
          // JSON encoded experimental options.
          "{\"bidi_stream_detect_broken_connection\": \"not an int\"}",
          // MockCertVerifier to use for testing purposes.
          std::unique_ptr<net::CertVerifier>(),
          // Enable network quality estimator.
          false,
          // Enable Public Key Pinning bypass for local trust anchors.
          true,
          // Optional network thread priority.
          absl::optional<double>());

  net::URLRequestContextBuilder builder;
  config->ConfigureURLRequestContextBuilder(&builder);
  EXPECT_FALSE(config->effective_experimental_options.contains(
      "bidi_stream_detect_broken_connection"));
}

// See stale_host_resolver_unittest.cc for test of StaleDNS options.

}  // namespace cronet


text:
require 'faraday'

module FaradayMiddleware
  class PaytureAuth < Faraday::Middleware
    def call(env)

      if env[:url].query.nil?
        query = {}
      else
        query = Faraday::Utils.parse_query(env[:url].query)
      end

      auth_params = {}

      if @access_token
        auth_params.merge!('VWID' => @access_token)
      end

      if @password
        auth_params.merge!('Password' => @password)
      end
      env[:url].query = Faraday::Utils.build_query(query.merge(auth_params))
      @app.call env
    end

    def initialize(app, params = {})
      @app = app
      @access_token = params[:access_token]
      @password = params[:password]
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
<?php
/**
 * Created by PhpStorm.
 * User: tonysantucci
 * Date: 5/26/17
 * Time: 9:05 AM.
 */

namespace Rocketcode\Progress\Facades;

class ProgressFacade
{
    protected static function getFacadeAccessor()
    {
        return 'Rocketcode\Progress';
    }
}


text:
package org.encog.engine.network.flat;

import org.encog.engine.EncogEngine;
import org.encog.engine.network.activation.ActivationFunction;
import org.encog.engine.util.EngineArray;

/**
 * Used to configure a flat layer. Flat layers are not kept by a Flat Network,
 * beyond setup.
 */
public class FlatLayer {

	/**
	 * The activation function.
	 */
	private final ActivationFunction activation;

	/**
	 * The neuron count.
	 */
	private final int count;

	/**
	 * The bias activation, usually 1 for bias or 0 for no bias.
	 */
	private final double biasActivation;

	/**
	 * The layer that feeds this layer's context.
	 */
	private FlatLayer contextFedBy;

	/**
	 * Construct a flat layer.
	 *
	 * @param activation
	 *            The activation function.
	 * @param count
	 *            The neuron count.
	 * @param biasActivation
	 *            The bias activation.
	 * @param params
	 *            The parameters.
	 */
	public FlatLayer(final ActivationFunction activation, final int count,
			final double biasActivation, final double[] params) {
		this.activation = activation;
		this.count = count;
		this.biasActivation = biasActivation;
		this.contextFedBy = null;
	}

	/**
	 * @return the activation
	 */
	public ActivationFunction getActivation() {
		return this.activation;
	}

	/**
	 * @return Get the bias activation.
	 */
	public double getBiasActivation() {
		return this.biasActivation;
	}

	/**
	 * @return The number of neurons our context is fed by.
	 */
	public int getContectCount() {
		if (this.contextFedBy == null) {
			return 0;
		} else {
			return this.contextFedBy.getCount();
		}
	}

	/**
	 * @return The layer that feeds this layer's context.
	 */
	public FlatLayer getContextFedBy() {
		return this.contextFedBy;
	}

	/**
	 * @return the count
	 */
	public int getCount() {
		return this.count;
	}

	/**
	 * @return The total number of neurons on this layer, includes context, bias
	 *         and regular.
	 */
	public int getTotalCount() {
		if (this.contextFedBy == null) {
			return getCount() + (isBias() ? 1 : 0);
		} else {
			return getCount() + (isBias() ? 1 : 0)
					+ this.contextFedBy.getCount();
		}
	}

	/**
	 * @return the bias
	 */
	public boolean isBias() {
		return Math.abs(this.biasActivation) > EncogEngine.DEFAULT_ZERO_TOLERANCE;
	}

	/**
	 * Set the layer that this layer's context is fed by.
	 *
	 * @param from
	 *            The layer feeding.
	 */
	public void setContextFedBy(final FlatLayer from) {
		this.contextFedBy = from;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public String toString() {
		final StringBuilder result = new StringBuilder();
		result.append("[FlatLayer: count=");
		result.append(this.count);
		result.append(",bias=");

		if (isBias()) {
			result.append(this.biasActivation);
		} else {
			result.append("false");
		}
		if (this.contextFedBy != null) {
			result.append(",contextFed=");
			if (this.contextFedBy == this) {
				result.append("itself");
			} else {
				result.append(this.contextFedBy);
			}
		}
		result.append("]");
		return result.toString();
	}
}


text:
//
//  AppDelegate.m
//  TestPopGestureSolution6
//
//  Created by liuhuan on 2017/8/23.
//  Copyright © 2017年 zqq. All rights reserved.
//

#import "AppDelegate.h"
#import "LHMainViewController.h"

@interface AppDelegate ()

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    LHMainViewController *mianVC = [[LHMainViewController alloc] init];
    self.window.rootViewController = mianVC;
    [self.window makeKeyAndVisible];
    [self setupUIStyle];
    return YES;

}
- (void)setupUIStyle
{
    // 设置返回按钮的背景图片
    UIImage *img = [UIImage imageNamed:@"navi_back_white"];
    //img = [img resizableImageWithCapInsets:UIEdgeInsetsMake(10, 10, 10, 10)];
    [[UIBarButtonItem appearance] setBackButtonBackgroundImage:img
                                                      forState:UIControlStateNormal
                                                    barMetrics:UIBarMetricsDefault];
    // 设置文本与图片的偏移量
    [[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(0, 0)
                                                         forBarMetrics:UIBarMetricsDefault];
    // 设置文本的属性
    NSDictionary *attributes = @{UITextAttributeFont:[UIFont systemFontOfSize:16],
                                 UITextAttributeTextShadowOffset:[NSValue valueWithUIOffset:UIOffsetZero],
                                 NSForegroundColorAttributeName:[UIColor redColor],
                                 NSBackgroundColorAttributeName:[UIColor redColor]};
    [[UIBarButtonItem appearance] setTitleTextAttributes:attributes forState:UIControlStateNormal];

//    CGRect frame = [[UIScreen mainScreen] bounds];
//
//    UIGraphicsBeginImageContext(frame.size);
//    CGContextRef context = UIGraphicsGetCurrentContext();
//
//    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
//    CGFloat locations[] = { 0.0, 1.0 };
//    NSArray *colors = @[(__bridge id)[UIColor redColor].CGColor,(__bridge id)[UIColor redColor].CGColor];
//
//    CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (__bridge CFArrayRef) colors, locations);
//
//    CGPoint startPoint = CGPointMake(0, 0);
//    CGPoint endPoint = CGPointMake(CGRectGetWidth(frame), 0);
//
//    CGContextSaveGState(context);
//    CGContextClip(context);
//    CGContextDrawLinearGradient(context, gradient, startPoint, endPoint, 0);
//    CGContextRestoreGState(context);
//
//    CGGradientRelease(gradient);
//    CGColorSpaceRelease(colorSpace);
//
//    UIImage *backgroundImg = UIGraphicsGetImageFromCurrentImageContext();
//    UIGraphicsEndImageContext();
//
//    [[UINavigationBar appearance] setBackgroundImage:backgroundImg forBarMetrics:UIBarMetricsDefault];
//
//    if ( [UINavigationBar instancesRespondToSelector:@selector(setShadowImage:)] ) {
//        CGRect rect = CGRectMake( 0, 0, [UIScreen mainScreen].bounds.size.width, 1.0f );
//        UIGraphicsBeginImageContext(rect.size);
//        CGContextRef context = UIGraphicsGetCurrentContext();
//        CGContextSetFillColorWithColor( context, [[UIColor clearColor] CGColor] );
//        CGContextFillRect( context, rect );
//        UIImage * shadowImage = UIGraphicsGetImageFromCurrentImageContext();
//        UIGraphicsEndImageContext();
//        [[UINavigationBar appearance] setShadowImage:shadowImage];
//    }
//
//    /**
//     * 导航标题大小和颜色修改
//     */
//
//    NSShadow *shadow = [[NSShadow alloc] init];
//    shadow.shadowColor = [UIColor clearColor];
//    shadow.shadowOffset = CGSizeMake(0, 0);
//    [[UINavigationBar appearance] setTitleTextAttributes: [NSDictionary dictionaryWithObjectsAndKeys:
//                                                           [UIColor whiteColor], NSForegroundColorAttributeName,
//                                                           shadow, NSShadowAttributeName,
//                                                           [UIFont systemFontOfSize:18], NSFontAttributeName,
//                                                           nil]];
//
//    [[UINavigationBar appearance] setTintColor:[UIColor clearColor]];
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end


text:
package com.intellij.util.io;

import java.io.DataOutput;
import java.io.IOException;
import java.io.OutputStream;

public final class CompactDataOutput implements DataOutput {
  private final OutputStream out;
  private final byte[] writeBuffer = IOUtil.allocReadWriteUTFBuffer();

  public CompactDataOutput(OutputStream out) {
    this.out = out;
  }

  @Override
  public void write(int b) throws IOException {
    out.write(b);
  }

  @Override
  public void write(byte[] b) throws IOException {
    out.write(b);
  }

  @Override
  public void write(byte[] b, int off, int len) throws IOException {
    out.write(b, off, len);
  }

  @Override
  public void writeBoolean(boolean v) throws IOException {
    out.write(v ? 1 : 0);
  }

  @Override
  public void writeByte(int v) throws IOException {
    out.write(v);
  }

  @Override
  public void writeShort(int v) throws IOException {
    out.write((v >>> 8) & 0xFF);
    out.write(v & 0xFF);
  }

  @Override
  public void writeChar(int v) throws IOException {
    out.write((v >>> 8) & 0xFF);
    out.write(v & 0xFF);
  }

  @Override
  public void writeInt(int val) throws IOException {
    DataInputOutputUtil.writeINT(this, val);
  }

  @Override
  public void writeLong(long v) throws IOException { // TODO: Make longs actually compact
    writeBuffer[0] = (byte)(v >>> 56);
    writeBuffer[1] = (byte)(v >>> 48);
    writeBuffer[2] = (byte)(v >>> 40);
    writeBuffer[3] = (byte)(v >>> 32);
    writeBuffer[4] = (byte)(v >>> 24);
    writeBuffer[5] = (byte)(v >>> 16);
    writeBuffer[6] = (byte)(v >>>  8);
    writeBuffer[7] = (byte)(v >>>  0);
    out.write(writeBuffer, 0, 8);
  }

  @Override
  public void writeFloat(float v) throws IOException {
    writeInt(Float.floatToIntBits(v));
  }

  @Override
  public void writeDouble(double v) throws IOException {
    writeLong(Double.doubleToLongBits(v));
  }

  @Override
  public void writeBytes(String s) throws IOException {
    int len = s.length();
    for (int i = 0 ; i < len ; i++) {
        out.write((byte)s.charAt(i));
    }
  }

  @Override
  public void writeChars(String s) throws IOException {
    int len = s.length();
    for (int i = 0 ; i < len ; i++) {
        int v = s.charAt(i);
        out.write((v >>> 8) & 0xFF);
        out.write((v >>> 0) & 0xFF);
    }
  }

  @Override
  public void writeUTF(String s) throws IOException {
    IOUtil.writeUTFFast(writeBuffer, this, s);
  }
}


text:
<?xml version="1.0" encoding="UTF-8"?>

<!--
  ~ Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
  ~
  ~ WSO2 Inc. licenses this file to you under the Apache License,
  ~ Version 2.0 (the "License"); you may not use this file except
  ~ in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~ http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing,
  ~ software distributed under the License is distributed on an
  ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  ~ KIND, either express or implied. See the License for the
  ~ specific language governing permissions and limitations
  ~ under the License.
  -->

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

    <parent>
        <groupId>org.wso2.ei</groupId>
        <artifactId>mb-integration-tests</artifactId>
        <version>6.7.0-SNAPSHOT</version>
        <relativePath>../../pom.xml</relativePath>
    </parent>

    <modelVersion>4.0.0</modelVersion>
    <name>WSO2 MB - Integration Test Common Utils Module</name>
    <artifactId>org.wso2.ei.mb.integration.common.utils</artifactId>
    <packaging>jar</packaging>

    <dependencies>
        <dependency>
            <groupId>org.wso2.carbon.automation</groupId>
            <artifactId>org.wso2.carbon.automation.engine</artifactId>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.wso2.ei</groupId>
            <artifactId>org.wso2.ei.mb.integration.common.clients</artifactId>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.wso2.carbon.automationutils</groupId>
            <artifactId>org.wso2.carbon.integration.common.utils</artifactId>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.wso2.carbon</groupId>
            <artifactId>org.wso2.carbon.authenticator.stub</artifactId>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.wso2.carbon.automation</groupId>
            <artifactId>org.wso2.carbon.automation.extensions</artifactId>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>commons-jxpath</groupId>
            <artifactId>commons-jxpath</artifactId>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>commons-configuration</groupId>
            <artifactId>commons-configuration</artifactId>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.wso2.andes.wso2</groupId>
            <artifactId>andes</artifactId>
            <scope>compile</scope>
        </dependency>
    </dependencies>

</project>


text:
/* globals svgEditor */

/**
 * @class ExplorerButton
 */
export class ExplorerButton extends HTMLElement {
  /**
    * @function constructor
    */
  constructor () {
    super()
    // create the shadowDom and insert the template
    // create the shadowDom and insert the template
    this.imgPath = svgEditor.configObj.curConfig.imgPath
    this.template = this.createTemplate(this.imgPath)
    this._shadowRoot = this.attachShadow({ mode: 'open' })
    this._shadowRoot.append(this.template.content.cloneNode(true))
    // locate the component
    this.$button = this._shadowRoot.querySelector('.menu-button')
    this.$overall = this._shadowRoot.querySelector('.overall')
    this.$img = this._shadowRoot.querySelector('.menu-button img')
    this.$menu = this._shadowRoot.querySelector('.menu')
    this.$handle = this._shadowRoot.querySelector('.handle')
    this.$lib = this._shadowRoot.querySelector('.image-lib')
    this.files = []
    this.request = new XMLHttpRequest()
    this.imgPath = svgEditor.configObj.curConfig.imgPath
  }

  /**
   * @function createTemplate
   * @param {string} imgPath
   * @returns {any} template
   */

  createTemplate (imgPath) {
    const template = document.createElement('template')
    template.innerHTML = `

        <se-button></se-button>

menu

`
    return template
  }

  /**
   * @function observedAttributes
   * @returns {any} observed
   */
  static get observedAttributes () {
    return ['title', 'pressed', 'disabled', 'lib', 'src']
  }

  /**
   * @function attributeChangedCallback
   * @param {string} name
   * @param {string} oldValue
   * @param {string} newValue
   * @returns {void}
   */
  async attributeChangedCallback (name, oldValue, newValue) {
    if (oldValue === newValue) return
    switch (name) {
      case 'title':
        {
          const shortcut = this.getAttribute('shortcut')
          this.$button.setAttribute('title', `${newValue} [${shortcut}]`)
        }
        break
      case 'pressed':
        if (newValue) {
          this.$overall.classList.add('pressed')
        } else {
          this.$overall.classList.remove('pressed')
        }
        break
      case 'disabled':
        if (newValue) {
          this.$overall.classList.add('disabled')
        } else {
          this.$overall.classList.remove('disabled')
        }
        break
      case 'lib':
        try {
          const response = await fetch(`${newValue}index.json`)
          const json = await response.json()
          const { lib } = json
          this.$menu.innerHTML = lib.map((menu, i) => (
          `<div data-menu="${menu}" class="menu-item ${(i === 0) ? 'pressed' : ''} ">${menu}</div>`
          )).join('')
          await this.updateLib(lib[0])
        } catch (error) {
          console.error(error)
        }
        break
      case 'src':
        this.$img.setAttribute('src', this.imgPath + '/' + newValue)
        break
      default:
        console.error(`unknown attribute: ${name}`)
        break
    }
  }

  /**
   * @function get
   * @returns {any}
   */
  get title () {
    return this.getAttribute('title')
  }

  /**
   * @function set
   * @returns {void}
   */
  set title (value) {
    this.setAttribute('title', value)
  }

  /**
   * @function get
   * @returns {any}
   */
  get pressed () {
    return this.hasAttribute('pressed')
  }

  /**
   * @function set
   * @returns {void}
   */
  set pressed (value) {
    // boolean value => existence = true
    if (value) {
      this.setAttribute('pressed', 'true')
    } else {
      this.removeAttribute('pressed', '')
    }
  }

  /**
   * @function get
   * @returns {any}
   */
  get disabled () {
    return this.hasAttribute('disabled')
  }

  /**
   * @function set
   * @returns {void}
   */
  set disabled (value) {
    // boolean value => existence = true
    if (value) {
      this.setAttribute('disabled', 'true')
    } else {
      this.removeAttribute('disabled', '')
    }
  }

  /**
   * @function connectedCallback
   * @returns {void}
   */
  connectedCallback () {
    // capture click event on the button to manage the logic
    const onClickHandler = (ev) => {
      ev.stopPropagation()
      switch (ev.target.nodeName) {
        case 'SE-EXPLORERBUTTON':
          this.$menu.classList.add('open')
          this.$lib.classList.add('open-lib')
          break
        case 'SE-BUTTON':
        // change to the current action
          this.currentAction = ev.target
          this.$img.setAttribute('src', this.currentAction.getAttribute('src'))
          this.dataset.draw = this.data[this.currentAction.dataset.shape]
          this._shadowRoot.querySelectorAll('.image-lib [pressed]').forEach((b) => { b.pressed = false })
          this.currentAction.setAttribute('pressed', 'pressed')
          // and close the menu
          this.$menu.classList.remove('open')
          this.$lib.classList.remove('open-lib')
          break
        case 'DIV':
          if (ev.target.classList[0] === 'handle') {
          // this is a click on the handle so let's open/close the menu.
            this.$menu.classList.toggle('open')
            this.$lib.classList.toggle('open-lib')
          } else {
            this._shadowRoot.querySelectorAll('.menu > .pressed').forEach((b) => { b.classList.remove('pressed') })
            ev.target.classList.add('pressed')
            this.updateLib(ev.target.dataset.menu)
          }
          break
        default:
          console.error('unknown nodeName for:', ev.target, ev.target.className)
      }
    }
    // capture event from slots
    svgEditor.$click(this, onClickHandler)
    svgEditor.$click(this.$menu, onClickHandler)
    svgEditor.$click(this.$lib, onClickHandler)
    svgEditor.$click(this.$handle, onClickHandler)
  }

  /**
   * @function updateLib
   * @param {string} lib
   * @returns {void}
   */
  async updateLib (lib) {
    const libDir = this.getAttribute('lib')
    try {
      // initialize buttons for all shapes defined for this library
      const response = await fetch(`${libDir}${lib}.json`)
      const json = await response.json()
      this.data = json.data
      const size = json.size ?? 300
      const fill = json.fill ? '#333' : 'none'
      const off = size * 0.05
      const vb = [-off, -off, size + off * 2, size + off * 2].join(' ')
      const stroke = json.fill ? 0 : (size / 30)
      this.$lib.innerHTML = Object.entries(this.data).map(([key, path]) => {
        const encoded = btoa(`
        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24">
          <svg viewBox="${vb}"><path fill="${fill}" stroke="#f8bb00" stroke-width="${stroke}" d="${path}"></path></svg>
        </svg>`)
        return `<se-button data-shape="${key}"src="data:image/svg+xml;base64,${encoded}"></se-button>`
      }).join('')
    } catch (error) {
      console.error(`could not read file:${libDir}${lib}.json`, error)
    }
  }
}

// Register
customElements.define('se-explorerbutton', ExplorerButton)


text:
Chrome extension that uses Watson's API to translate and/or read selected text.

Add your API keys inside `/scripts/main.js`.

Translate Watson API : https://www.ibm.com/watson/developercloud/language-translator/api/v2/

Text To Speech Watson API : https://www.ibm.com/watson/developercloud/text-to-speech/api/v1/


text:
package org.apache.activemq.artemis.json;

import java.math.BigDecimal;
import java.math.BigInteger;

/**
 * A JsonObjectBuilder can be used to build {@link JsonObject JsonObjects}.
 * Instances are not thread safe.
 *
 * Calling any of those methods with either the {@code name} or {@code value} param as {@code null}
 * will result in a {@code NullPointerException}
 */
public interface JsonObjectBuilder {
   /**
    * Add the given JsonValue value to the JsonObject to be created.
    * If a value with that name already exists it will be replaced by the new value.
    * @param name the JSON attribute name
    * @param value the JsonValue to add
    * @return the current JsonObjectBuilder
    */
   JsonObjectBuilder add(String name, JsonValue value);

   /**
    * Add the given String value to the JsonObject to be created.
    * If a value with that name already exists it will be replaced by the new value.
    * @param name the JSON attribute name
    * @param value the String value to add
    * @return the current JsonObjectBuilder
    */
   JsonObjectBuilder add(String name, String value);
   JsonObjectBuilder add(String name, String value, JsonValue defaultValue);

   /**
    * Add the given BigInteger value to the JsonObject to be created.
    * If a value with that name already exists it will be replaced by the new value.
    * @param name the JSON attribute name
    * @param value the BigInteger value to add
    * @return the current JsonObjectBuilder
    */
   JsonObjectBuilder add(String name, BigInteger value);
   JsonObjectBuilder add(String name, BigInteger value, JsonValue defaultValue);

   /**
    * Add the given BigDecimal value to the JsonObject to be created.
    * If a value with that name already exists it will be replaced by the new value.
    * @param name the JSON attribute name
    * @param value the BigDecimal value to add
    * @return the current JsonObjectBuilder
    */
   JsonObjectBuilder add(String name, BigDecimal value);
   JsonObjectBuilder add(String name, BigDecimal value, JsonValue defaultValue);

   /**
    * Add the given int value to the JsonObject to be created.
    * If a value with that name already exists it will be replaced by the new value.
    * @param name the JSON attribute name
    * @param value to add
    * @return the current JsonObjectBuilder
    */
   JsonObjectBuilder add(String name, int value);

   /**
    * Add the given long value to the JsonObject to be created.
    * If a value with that name already exists it will be replaced by the new value.
    * @param name the JSON attribute name
    * @param value to add
    * @return the current JsonObjectBuilder
    */
   JsonObjectBuilder add(String name, long value);

   /**
    * Add the given double value to the JsonObject to be created.
    * If a value with that name already exists it will be replaced by the new value.
    * @param name the JSON attribute name
    * @param value to add
    * @return the current JsonObjectBuilder
    */
   JsonObjectBuilder add(String name, double value);

   /**
    * Add the given boolean value to the JsonObject to be created.
    * If a value with that name already exists it will be replaced by the new value.
    * @param name the JSON attribute name
    * @param value to add
    * @return the current JsonObjectBuilder
    */
   JsonObjectBuilder add(String name, boolean value);

   /**
    * Add a {@link JsonValue#NULL} value to the JsonObject to be created.
    * If a value with that name already exists it will be replaced by the null value.
    * @param name the JSON attribute name
    * @return the current JsonObjectBuilder
    */
   JsonObjectBuilder addNull(String name);

   /**
    * Use the given {@link JsonObjectBuilder} to create a {@link JsonObject} which will be
    * added to the JsonObject to be created by this builder.
    * If a value with that name already exists it will be replaced by the new value.
    * @param name the JSON attribute name
    * @param builder for creating the JsonObject to add
    * @return the current JsonObjectBuilder
    */
   JsonObjectBuilder add(String name, JsonObjectBuilder builder);

   /**
    * Use the given {@link JsonArrayBuilder} to create a {@link JsonArray} which will be
    * added to the JsonObject to be created by this builder.
    * If a value with that name already exists it will be replaced by the new value.
    * @param name the JSON attribute name
    * @param builder for creating the JsonArray to add
    * @return the current JsonObjectBuilder
    */
   JsonObjectBuilder add(String name, JsonArrayBuilder builder);

   /**
    * @return a {@link JsonObject} based on the added values.
    */
   JsonObject build();

   /**
    * Add all of the attributes of the given {@link JsonObjectBuilder} to the current one
    *
    * @since 1.1
    */
   default JsonObjectBuilder addAll(JsonObjectBuilder builder) {
      throw new UnsupportedOperationException();
   }

   /**
    * Remove the attribute with the given name from the builder.
    *
    * @since 1.1
    */
   default JsonObjectBuilder remove(String name) {
      throw new UnsupportedOperationException();
   }
}