public RequestData(HttpMethod method, string path, PostData<object> data, IConnectionConfigurationValues global, IRequestConfiguration local, IMemoryStreamFactory memoryStreamFactory)
		{
			this.ConnectionSettings = global;
			this.MemoryStreamFactory = memoryStreamFactory;
			this.Method = method;
			this.PostData = data;
			this.Path = this.CreatePathWithQueryStrings(path, this.ConnectionSettings, null);

			this.Pipelined = global.HttpPipeliningEnabled || (local?.EnableHttpPipelining).GetValueOrDefault(false);
			this.HttpCompression = global.EnableHttpCompression;
			this.ContentType = local?.ContentType ?? MimeType;
			this.Headers = global.Headers;

			this.RequestTimeout = local?.RequestTimeout ?? global.RequestTimeout;
			this.PingTimeout = 
				local?.PingTimeout
				?? global?.PingTimeout
				?? (global.ConnectionPool.UsingSsl ? ConnectionConfiguration.DefaultPingTimeoutOnSSL : ConnectionConfiguration.DefaultPingTimeout);

			this.KeepAliveInterval = (int)(global.KeepAliveInterval?.TotalMilliseconds ?? 2000);
			this.KeepAliveTime = (int)(global.KeepAliveTime?.TotalMilliseconds ?? 2000);

			this.ProxyAddress = global.ProxyAddress;
			this.ProxyUsername = global.ProxyUsername;
			this.ProxyPassword = global.ProxyPassword;
			this.DisableAutomaticProxyDetection = global.DisableAutomaticProxyDetection;
			this.BasicAuthorizationCredentials = local?.BasicAuthenticationCredentials ?? global.BasicAuthenticationCredentials;
			this.CancellationToken = local?.CancellationToken ?? CancellationToken.None;
			this.AllowedStatusCodes = local?.AllowedStatusCodes ?? Enumerable.Empty<int>();
		}
		/// <summary>
		/// Initializes a new instance of the <see cref="HttpClientConnection"/> class.
		/// </summary>
		/// <param name="settings">The settings.</param>
		/// <param name="handler">The handler.</param>
		public HttpClientConnection(IConnectionConfigurationValues settings, HttpClientHandler handler = null)
		{
			_settings = settings;
			if (settings.ConnectionPool.UsingSsl)
				this.AddressScheme = TransportAddressScheme.Https;
			
			DefaultContentType = "application/json";

			var innerHandler = handler ?? new WebRequestHandler();

			if (innerHandler.SupportsProxy && !string.IsNullOrWhiteSpace(_settings.ProxyAddress))
			{
				innerHandler.Proxy = new WebProxy(_settings.ProxyAddress)
				{

					Credentials = new NetworkCredential(_settings.ProxyUsername, _settings.ProxyPassword),
				};

				innerHandler.UseProxy = true;
			}

			Client = new HttpClient(new InternalHttpMessageHandler(innerHandler), false)
			{
				Timeout = TimeSpan.FromMilliseconds(_settings.Timeout)
			};
			if (settings.EnableCompressedResponses || settings.EnableHttpCompression && innerHandler.SupportsAutomaticDecompression)
			{
				innerHandler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
				Client.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("gzip"));
				Client.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("deflate"));
			}

		}
Beispiel #3
0
        public static ElasticsearchResponse<Stream> Bad(
			IConnectionConfigurationValues config, 
			string method = "GET",
			string path = "/")
        {
            return ElasticsearchResponse<Stream>.Create(config, 503, method, path, null);
        }
        public static ElasticsearchResponse<Dictionary<string, object>> Ok(
			IConnectionConfigurationValues config, 
			string method = "GET",
			string path = "/")
        {
            return ElasticsearchResponse<Dictionary<string, object>>.Create(config, 200, method, path, null);
        }
		private async Task AssertOn(IConnectionConfigurationValues settings)
		{ 

			/** Although each implicitly types behaves slightly differently */
			await Post(()=>@string, writes: Utf8Bytes(@string), storesBytes: true, settings: settings);

			await Post(()=>bytes, writes: bytes, storesBytes: true, settings: settings);
			
			/** When passing a list of strings we assume its a list of valid serialized json that we 
			* join with newlinefeeds making sure there is a trailing linefeed */
			await Post(()=>listOfStrings, writes: multiStringJson, storesBytes: true, settings: settings);

			/**
			* When passing a list of object we assume its a list of objects we need to serialize
			* individually to json and join with newlinefeeds aking sure there is a trailing linefeed 
			*/
			await Post(()=>listOfObjects, writes: multiObjectJson, storesBytes: false, settings: settings);
			
			/** In all other cases postdata is serialized as is. */
			await Post(()=>@object, writes: objectJson, storesBytes: false, settings: settings);

			/** If you want to maintain a copy of the request that went out use the following settings */
			settings = new ConnectionSettings().DisableDirectStreaming();

			/** by forcing `DisableDirectStreaming` serializing happens first in a private MemoryStream 
			* so we can get a hold of the serialized bytes */
			await Post(()=>listOfObjects, writes: multiObjectJson, storesBytes: true, settings: settings);
			
			/** this behavior can also be observed when serializing a simple object using `DisableDirectStreaming` */
			await Post(()=>@object, writes: objectJson, storesBytes: true, settings: settings);
		}
        public static Task<ElasticsearchResponse<Stream>> AnyAsync(
			IConnectionConfigurationValues config, 
			int statusCode,
			string method = "GET",
			string path = "/")
        {
            return Task.FromResult(ElasticsearchResponse<Stream>.Create(config, statusCode, method, path, null));
        }
        public static Task<ElasticsearchResponse<Stream>> BadAsync(
			IConnectionConfigurationValues config, 
			string method = "GET",
			string path = "/",
			Stream response = null)
        {
            return Task.FromResult(ElasticsearchResponse<Stream>.Create(config, 503, method, path, null, response));
        }
        public static ElasticsearchResponse<Stream> Ok(
			IConnectionConfigurationValues config, 
			string method = "GET",
			string path = "/",
			Stream response = null)
        {
            return ElasticsearchResponse<Stream>.Create(config, 200, method, path, null, response);
        }
Beispiel #9
0
		public RequestData(HttpMethod method, string path, PostData<object> data, IConnectionConfigurationValues global, IRequestParameters local, IMemoryStreamFactory memoryStreamFactory)
#pragma warning disable CS0618 // Type or member is obsolete
			: this(method, path, data, global, (IRequestConfiguration)local?.RequestConfiguration, memoryStreamFactory)
#pragma warning restore CS0618 // Type or member is obsolete
		{
			this.CustomConverter = local?.DeserializationOverride;
			this.Path = this.CreatePathWithQueryStrings(path, this.ConnectionSettings, local);
		}
        public static Task<ElasticsearchResponse<Stream>> OkAsync(
			IConnectionConfigurationValues config, 
			string method = "GET",
			string path = "/",
			Stream response = null)
        {
            response = response ?? new MemoryStream(Encoding.UTF8.GetBytes("{}"));
            return Task.FromResult(ElasticsearchResponse<Stream>.Create(config, 200, method, path, null, response));
        }
        public NoopConnection(
			IConnectionConfigurationValues configValues
			, IUriObserver uriObserver
			, IResponseGenerator responseGenerator)
        {
            _uriObserver = uriObserver;
            _responseGenerator = responseGenerator;
            _configValues = configValues;
        }
 /// <summary>
 /// Initializes a new instance of the AwsHttpConnection class.
 /// </summary>
 /// <param name="settings">The NEST/Elasticsearch.Net settings.</param>
 /// <param name="awsSettings">AWS specific settings required for signing requests.</param>
 public AwsHttpConnection(IConnectionConfigurationValues settings, AwsSettings awsSettings)
     : base(settings)
 {
     if (awsSettings == null) throw new ArgumentNullException("awsSettings");
     if (string.IsNullOrWhiteSpace(awsSettings.SecretKey)) throw new ArgumentException("awsSettings.SecretKey is invalid.", "awsSettings");
     if (string.IsNullOrWhiteSpace(awsSettings.Region)) throw new ArgumentException("awsSettings.Region is invalid.", "awsSettings");
     _accessKey = awsSettings.AccessKey;
     _secretKey = awsSettings.SecretKey;
     _region = awsSettings.Region.ToLowerInvariant();
 }
		public static ElasticsearchResponse<Stream> AnyWithException(
			IConnectionConfigurationValues config, 
			int statusCode,
			string method = "GET",
			string path = "/",
			Stream response = null,
			Exception innerException = null)
		{
			 return ElasticsearchResponse<Stream>.Create(config, statusCode, method, path, null, response, innerException);
		}
		public ThriftConnection(IConnectionConfigurationValues connectionSettings, TProtocolFactory protocolFactory = null)
		{
			this._connectionSettings = connectionSettings;
			this._protocolFactory = protocolFactory;
			this._timeout = connectionSettings.Timeout;

			this._maximumConnections = this._connectionSettings.MaximumAsyncConnections;
			if (this._maximumConnections > 0)
				this._resourceLock = new Semaphore(this._maximumConnections, this._maximumConnections);

		}
		private string CreatePathWithQueryStrings(string path, IConnectionConfigurationValues global, IRequestParameters request = null)
		{
			//Make sure we append global query string as well the request specific query string parameters
			var copy = new NameValueCollection(global.QueryStringParameters);
			var formatter = new UrlFormatProvider(this.ConnectionSettings);
			if (request != null)
				copy.Add(request.QueryString.ToNameValueCollection(formatter));
			if (!copy.HasKeys()) return path;

			var queryString = copy.ToQueryString();
			path += queryString;
			return path;
		}
		public HttpConnection(IConnectionConfigurationValues settings)
		{
			if (settings == null)
				throw new ArgumentNullException("settings");

			this.ConnectionSettings = settings;
			if (settings.MaximumAsyncConnections > 0)
			{
				var semaphore = Math.Max(1, settings.MaximumAsyncConnections);
				this._resourceLock = new Semaphore(semaphore, semaphore);
			}
			this._enableTrace = settings.TraceEnabled;
		}
		private static IEnumerable<AliasDefinition> AliasesPointingToIndex(IConnectionConfigurationValues settings, IUrlParameter indices, IGetAliasResponse aliasesResponse)
		{
			if (!aliasesResponse.IsValid || !aliasesResponse.Indices.HasAny())
				return Enumerable.Empty<AliasDefinition>();

			var indexNames = indices.GetString(settings).Split(',');

			var aliases = new List<AliasDefinition>();
			foreach (var indexName in indexNames)
				if (aliasesResponse.Indices.ContainsKey(indexName))
					aliases.AddRange(aliasesResponse.Indices[indexName]);

			return aliases;
		}
		private static IEnumerable<string> IndicesPointingToAlias(IConnectionConfigurationValues settings, Names alias, IGetAliasResponse aliasesResponse)
		{
			if (!aliasesResponse.IsValid
			    || !aliasesResponse.Indices.HasAny())
				return new string[] { };

			var aliases = alias.GetString(settings).Split(',');

			var indices = from i in aliasesResponse.Indices
				where i.Value.Any(a => aliases.Contains(a.Name))
				select i.Key;

			return indices.ToList();
		}
        public static IReturnValueConfiguration<Task<ElasticsearchResponse<Stream>>> SniffAsync(
			AutoFake fake, 
			IConnectionConfigurationValues configurationValues = null,
			IList<Uri> nodes = null
			)
        {
            var sniffCall = A.CallTo(() => fake.Resolve<IConnection>().Get(
                A<Uri>.That.Matches(IsSniffUrl()),
                A<IRequestConnectionConfiguration>._));
            if (nodes == null) return sniffCall;
            var stream = SniffResponse(nodes);
            var response = FakeResponse.Ok(configurationValues, "GET", "/_nodes/_all/clear", stream);
            sniffCall.Returns(Task.FromResult(response));
            return sniffCall;
        }
		private string CreatePathWithQueryStrings(string path, IConnectionConfigurationValues global, IRequestParameters request = null)
		{

			//Make sure we append global query string as well the request specific query string parameters
			var copy = new NameValueCollection(global.QueryStringParameters);
			var formatter = new UrlFormatProvider(this.ConnectionSettings);
			if (request != null)
				copy.Add(request.QueryString.ToNameValueCollection(formatter));
			if (!copy.HasKeys()) return path;

			var queryString = copy.ToQueryString();
			var tempUri = new Uri("http://localhost:9200/" + path).Purify();
			if (tempUri.Query.IsNullOrEmpty())
				path += queryString;
			else 
				path += "&" + queryString.Substring(1, queryString.Length - 1);
			return path;
		}
Beispiel #21
0
        public Transport(
			IConnectionConfigurationValues configurationValues,
			IConnection connection, 
			IElasticsearchSerializer serializer,
			IDateTimeProvider dateTimeProvider = null
			)
        {
            this._configurationValues = configurationValues;
            this._connection = connection?? new HttpConnection(configurationValues);
            this._serializer = serializer ?? new ElasticsearchDefaultSerializer();
            this._connectionPool = this._configurationValues.ConnectionPool;

            //TODO: take the datetimeprovider from the connection pool?
            this._dateTimeProvider = dateTimeProvider ?? new DateTimeProvider();

            if (this._configurationValues.SniffsOnStartup)
                this.Sniff(fromStartup: true);
            else
                this._lastSniff = this._dateTimeProvider.Now();
        }
        public ThriftConnection(IConnectionConfigurationValues connectionSettings)
        {
            this._connectionSettings = connectionSettings;
            this._timeout = connectionSettings.Timeout;
            this._poolSize = Math.Max(1, connectionSettings.MaximumAsyncConnections);

            this._resourceLock = new Semaphore(_poolSize, _poolSize);
            int seed; bool shouldPingHint;
            for (var i = 0; i <= connectionSettings.MaximumAsyncConnections; i++)
            {
                var uri = this._connectionSettings.ConnectionPool.GetNext(null, out seed, out shouldPingHint);
                var host = uri.Host;
                var port = uri.Port;
                var tsocket = new TSocket(host, port);
                var transport = new TBufferedTransport(tsocket, 1024);
                var protocol = new TBinaryProtocol(transport);
                var client = new Rest.Client(protocol);
                _clients.Enqueue(client);
            }
        }
		private RequestData(
			HttpMethod method,
			string path,
			PostData<object> data,
			IConnectionConfigurationValues global,
			IRequestConfiguration local,
			IMemoryStreamFactory memoryStreamFactory)
		{
			this.ConnectionSettings = global;
			this.MemoryStreamFactory = memoryStreamFactory;
			this.Method = method;
			this.PostData = data;

			if (data != null)
				data.DisableDirectStreaming = local?.DisableDirectStreaming ?? global.DisableDirectStreaming;

			this.Path = this.CreatePathWithQueryStrings(path, this.ConnectionSettings, null);

			this.Pipelined = local?.EnableHttpPipelining ?? global.HttpPipeliningEnabled;
			this.HttpCompression = global.EnableHttpCompression;
			this.ContentType = local?.ContentType ?? MimeType;
			this.Accept = local?.Accept ?? MimeType;
			this.Headers = global.Headers != null ? new NameValueCollection(global.Headers) : new NameValueCollection();
			this.RunAs = local?.RunAs;

			this.RequestTimeout = local?.RequestTimeout ?? global.RequestTimeout;
			this.PingTimeout =
				local?.PingTimeout
				?? global?.PingTimeout
				?? (global.ConnectionPool.UsingSsl ? ConnectionConfiguration.DefaultPingTimeoutOnSSL : ConnectionConfiguration.DefaultPingTimeout);

			this.KeepAliveInterval = (int)(global.KeepAliveInterval?.TotalMilliseconds ?? 2000);
			this.KeepAliveTime = (int)(global.KeepAliveTime?.TotalMilliseconds ?? 2000);

			this.ProxyAddress = global.ProxyAddress;
			this.ProxyUsername = global.ProxyUsername;
			this.ProxyPassword = global.ProxyPassword;
			this.DisableAutomaticProxyDetection = global.DisableAutomaticProxyDetection;
			this.BasicAuthorizationCredentials = local?.BasicAuthenticationCredentials ?? global.BasicAuthenticationCredentials;
			this.AllowedStatusCodes = local?.AllowedStatusCodes ?? Enumerable.Empty<int>();
		}
		/// <summary>
		/// Initializes a new instance of the <see cref="HttpClientConnection"/> class.
		/// </summary>
		/// <param name="settings">The settings.</param>
		/// <param name="handler">The handler.</param>
		public HttpClientConnection(IConnectionConfigurationValues settings, HttpClientHandler handler = null)
		{
			_settings = settings;
			DefaultContentType = "application/json";

			var innerHandler = handler ?? new WebRequestHandler();

			if (innerHandler.SupportsProxy && !string.IsNullOrWhiteSpace(_settings.ProxyAddress))
			{
				innerHandler.Proxy = new WebProxy(_settings.ProxyAddress)
				{
					Credentials = new NetworkCredential(_settings.ProxyUsername, _settings.ProxyPassword),
				};

				innerHandler.UseProxy = true;
			}

			Client = new HttpClient(new InternalHttpMessageHandler(innerHandler), false)
			{
				Timeout = TimeSpan.FromMilliseconds(_settings.Timeout)
			};
		}
		public ThriftConnection(IConnectionConfigurationValues connectionSettings)
		{
			this._connectionSettings = connectionSettings;
			this._timeout = connectionSettings.Timeout;
			var connectionPool = this._connectionSettings.ConnectionPool;
			var maximumConnections = Math.Max(1, connectionSettings.MaximumAsyncConnections);
			var maximumUrls = connectionPool.MaxRetries + 1;
			this._poolSize = maximumConnections;
			this._resourceLock = new Semaphore(_poolSize, _poolSize);

			int seed; int initialSeed = 0; bool shouldPingHint;

			for (var i = 0; i < maximumUrls; i++)
			{
				var uri = connectionPool.GetNext(initialSeed, out seed, out shouldPingHint);
				var queue = new ConcurrentQueue<Rest.Client>();
				for (var c = 0; c < maximumConnections; c++)
				{
					var host = uri.Host;
					var port = uri.Port;
					var tsocket = new TSocket(host, port);
					var transport = new TBufferedTransport(tsocket, 1024);
					var protocol = new TBinaryProtocol(transport);
					var client = new Rest.Client(protocol);
					tsocket.Timeout = this._connectionSettings.Timeout;
					tsocket.TcpClient.SendTimeout = this._connectionSettings.Timeout;
					tsocket.TcpClient.ReceiveTimeout = this._connectionSettings.Timeout;
					//tsocket.TcpClient.NoDelay = true;

					queue.Enqueue(client);

					initialSeed = seed;
				}
				_clients.TryAdd(uri, queue);
			}
		}
 public IRequestPipeline Create(IConnectionConfigurationValues configurationValues, IDateTimeProvider dateTimeProvider, IMemoryStreamFactory memorystreamFactory, IRequestParameters requestParameters) =>
 new RequestPipeline(this.Settings, this.DateTimeProvider, this.MemoryStreamFactory, requestParameters ?? new SearchRequestParameters());
 public OpenSearchLowLevelClient(IConnectionConfigurationValues settings) : this(
         new Transport <IConnectionConfigurationValues>(settings ?? new ConnectionConfiguration()))
 {
 }
 internal RollupFieldsIndexCapabilitiesDictionary(IConnectionConfigurationValues c,
                                                  IReadOnlyDictionary <Field, IReadOnlyCollection <RollupFieldsIndexCapabilities> > b
                                                  ) : base(c, b)
 {
 }
Beispiel #29
0
        string IUrlParameter.GetString(IConnectionConfigurationValues settings)
        {
            var nestSettings = (IConnectionSettingsValues)settings;

            return(nestSettings.Inferrer.Id(Document) ?? StringOrLongValue);
        }
Beispiel #30
0
 string IUrlParameter.GetString(IConnectionConfigurationValues settings) => _enumValue.GetStringValue();
Beispiel #31
0
 public string GetString(IConnectionConfigurationValues settings) =>
 string.Join(",", this._scrollIds.Select(s => s.GetString(settings)));
Beispiel #32
0
 string IUrlParameter.GetString(IConnectionConfigurationValues settings) =>
 string.Join(",", Value.Cast <IUrlParameter>().Select(n => n.GetString(settings)));
Beispiel #33
0
 string IUrlParameter.GetString(IConnectionConfigurationValues settings) => Value;
 public BasicallyAuthenticatedHttpConnection(string username, string password, IConnectionConfigurationValues settings)
     : base(settings) {
     this.authorizationHeader = string.Format("Basic {0}", Convert.ToBase64String(Encoding.UTF8.GetBytes(username + ":" + password)));
 }
Beispiel #35
0
 public InMemoryConnection(IConnectionConfigurationValues settings) : base(settings)
 {
     _statusCode = 200;
 }
Beispiel #36
0
 public InMemoryConnection(IConnectionConfigurationValues settings, string fixedResult, int statusCode = 200) : this(settings)
 {
     _fixedResultBytes = Encoding.UTF8.GetBytes(fixedResult);
     _statusCode       = statusCode;
 }
Beispiel #37
0
 public RequestData(HttpMethod method, string path, PostData <object> data, IConnectionConfigurationValues global, IRequestParameters local, IMemoryStreamFactory memoryStreamFactory)
     : this(method, path, data, global, (IRequestConfiguration)local?.RequestConfiguration, memoryStreamFactory)
 {
     this.CustomConverter = local?.DeserializationOverride;
     this.Path            = this.CreatePathWithQueryStrings(path, this.ConnectionSettings, local);
 }
Beispiel #38
0
 public RequestData(HttpMethod method, string path, PostData <object> data, IConnectionConfigurationValues global, IMemoryStreamFactory memoryStreamFactory)
     : this(method, path, data, global, (IRequestConfiguration)null, memoryStreamFactory)
 {
 }
Beispiel #39
0
 public IRequestPipeline Create(IConnectionConfigurationValues configurationValues, IDateTimeProvider dateTimeProvider,
                                IMemoryStreamFactory memoryStreamFactory, IRequestParameters requestParameters
                                ) =>
 new RequestPipeline(configurationValues, dateTimeProvider, memoryStreamFactory, requestParameters);
        public void Write(Stream writableStream, IConnectionConfigurationValues settings)
        {
            var          indent = settings.PrettyJson ? SerializationFormatting.Indented : SerializationFormatting.None;
            MemoryStream ms = null; Stream stream = null;

            switch (Type)
            {
            case PostType.ByteArray:
                ms = new MemoryStream(WrittenBytes);
                break;

            case PostType.LiteralString:
                ms = !string.IsNullOrEmpty(_literalString) ? new MemoryStream(_literalString?.Utf8Bytes()) : null;
                break;

            case PostType.EnumerableOfString:
                ms = _enumurabeOfStrings.HasAny() ? new MemoryStream((string.Join("\n", _enumurabeOfStrings) + "\n").Utf8Bytes()) : null;
                break;

            case PostType.EnumerableOfObject:
                if (!_enumerableOfObject.HasAny())
                {
                    return;
                }

                if (settings.DisableDirectStreaming)
                {
                    ms     = new MemoryStream();
                    stream = ms;
                }
                else
                {
                    stream = writableStream;
                }
                foreach (var o in _enumerableOfObject)
                {
                    settings.Serializer.Serialize(o, stream, indent);
                    stream.Write(new byte[] { (byte)'\n' }, 0, 1);
                }
                break;

            case PostType.Serializable:
                stream = writableStream;
                if (settings.DisableDirectStreaming)
                {
                    ms     = new MemoryStream();
                    stream = ms;
                }
                settings.Serializer.Serialize(this._serializable, stream, indent);
                break;
            }
            if (ms != null)
            {
                ms.Position = 0;
                ms.CopyTo(writableStream, 8096);
            }
            if (this.Type != 0)
            {
                this.WrittenBytes = ms?.ToArray();
            }
        }
Beispiel #41
0
 string IUrlParameter.GetString(IConnectionConfigurationValues settings) => string.Join(",", Value);
Beispiel #42
0
 public string GetString(IConnectionConfigurationValues settings) => _name;
Beispiel #43
0
 string IUrlParameter.GetString(IConnectionConfigurationValues settings) =>
 string.Join(",", ListOfFields.Select(f => ((IUrlParameter)f).GetString(settings)));
		private static async Task PostAssertAsync(PostData<object> postData, byte[] writes, bool storesBytes, IConnectionConfigurationValues settings)
		{
			using (var ms = new MemoryStream())
			{
				await postData.WriteAsync(ms, settings);
				var sentBytes = ms.ToArray();
				sentBytes.Should().Equal(writes);
				if (storesBytes)
					postData.WrittenBytes.Should().NotBeNull();
				else 
					postData.WrittenBytes.Should().BeNull();
			}
		}
Beispiel #45
0
 public string GetString(IConnectionConfigurationValues settings) => string.Join(",", this._actionIds);
Beispiel #46
0
        string IUrlParameter.GetString(IConnectionConfigurationValues settings)
        {
            var nestSettings = settings as IConnectionSettingsValues;

            return(GetString(nestSettings));
        }
        internal static void SerializeUsingWriter <T>(this IElasticsearchSerializer serializer, ref JsonWriter writer, T body, IConnectionConfigurationValues settings, SerializationFormatting formatting)
        {
            if (serializer is IInternalSerializer s && s.TryGetJsonFormatter(out var formatterResolver))
            {
                JsonSerializer.Serialize(ref writer, body, formatterResolver);
                return;
            }

            var memoryStreamFactory = settings.MemoryStreamFactory;
            var bodyBytes           = serializer.SerializeToBytes(body, memoryStreamFactory, formatting);

            writer.WriteRaw(bodyBytes);
        }
Beispiel #48
0
        //hide
        private static async Task PostAssertAsync(PostData postData, byte[] writes, bool storesBytes, IConnectionConfigurationValues settings)
        {
            using (var ms = new MemoryStream())
            {
                await postData.WriteAsync(ms, settings, default(CancellationToken));

                var s1 = Encoding.UTF8.GetString(ms.ToArray());
                var s2 = Encoding.UTF8.GetString(writes);
                s1.Should().Be(s2);

                var sentBytes = ms.ToArray();
                sentBytes.Should().Equal(writes);
                if (storesBytes)
                {
                    postData.WrittenBytes.Should().NotBeNull();
                }
                else
                {
                    postData.WrittenBytes.Should().BeNull();
                }
            }
        }
 internal TypeMappings(IConnectionConfigurationValues connectionSettings, IReadOnlyDictionary <TypeName, TypeMapping> backingDictionary)
     : base(connectionSettings, backingDictionary)
 {
 }
        private RequestData(
            HttpMethod method,
            PostData data,
            IConnectionConfigurationValues global,
            IRequestConfiguration local,
            IMemoryStreamFactory memoryStreamFactory
            )
        {
            ConnectionSettings  = global;
            MemoryStreamFactory = memoryStreamFactory;
            Method   = method;
            PostData = data;

            if (data != null)
            {
                data.DisableDirectStreaming = local?.DisableDirectStreaming ?? global.DisableDirectStreaming;
            }

            Pipelined       = local?.EnableHttpPipelining ?? global.HttpPipeliningEnabled;
            HttpCompression = global.EnableHttpCompression;
            RequestMimeType = local?.ContentType ?? MimeType;
            Accept          = local?.Accept ?? MimeType;

            if (global.Headers != null)
            {
                Headers = new NameValueCollection(global.Headers);
            }

            if (local?.Headers != null)
            {
                Headers ??= new NameValueCollection();
                foreach (var key in local.Headers.AllKeys)
                {
                    Headers[key] = local.Headers[key];
                }
            }

            if (!string.IsNullOrEmpty(local?.OpaqueId))
            {
                Headers ??= new NameValueCollection();
                Headers.Add(OpaqueIdHeader, local.OpaqueId);
            }

            RunAs = local?.RunAs;
            SkipDeserializationForStatusCodes = global?.SkipDeserializationForStatusCodes;
            ThrowExceptions = local?.ThrowExceptions ?? global.ThrowExceptions;

            RequestTimeout = local?.RequestTimeout ?? global.RequestTimeout;
            PingTimeout    =
                local?.PingTimeout
                ?? global.PingTimeout
                ?? (global.ConnectionPool.UsingSsl ? ConnectionConfiguration.DefaultPingTimeoutOnSSL : ConnectionConfiguration.DefaultPingTimeout);

            KeepAliveInterval = (int)(global.KeepAliveInterval?.TotalMilliseconds ?? 2000);
            KeepAliveTime     = (int)(global.KeepAliveTime?.TotalMilliseconds ?? 2000);
            DnsRefreshTimeout = global.DnsRefreshTimeout;

            ProxyAddress  = global.ProxyAddress;
            ProxyUsername = global.ProxyUsername;
            ProxyPassword = global.ProxyPassword;
            DisableAutomaticProxyDetection  = global.DisableAutomaticProxyDetection;
            BasicAuthorizationCredentials   = local?.BasicAuthenticationCredentials ?? global.BasicAuthenticationCredentials;
            ApiKeyAuthenticationCredentials = local?.ApiKeyAuthenticationCredentials ?? global.ApiKeyAuthenticationCredentials;
            AllowedStatusCodes      = local?.AllowedStatusCodes ?? EmptyReadOnly <int> .Collection;
            ClientCertificates      = local?.ClientCertificates ?? global.ClientCertificates;
            UserAgent               = global.UserAgent;
            TransferEncodingChunked = local?.TransferEncodingChunked ?? global.TransferEncodingChunked;
            TcpStats        = local?.EnableTcpStats ?? global.EnableTcpStats;
            ThreadPoolStats = local?.EnableThreadPoolStats ?? global.EnableThreadPoolStats;
        }
Beispiel #51
0
 internal FieldCapabilitiesFields(IConnectionConfigurationValues c, IReadOnlyDictionary <Field, FieldTypes> b) : base(c, b)
 {
 }
Beispiel #52
0
        private async Task AssertOn(IConnectionConfigurationValues settings)
        {
            /**
             * Each of the implicitly converted types behaves _slightly_ differently.
             *
             * For `string`, the UTF-8 bytes are sent in the request and the `WrittenBytes` property is assigned
             * the bytes
             */
            await Post(() => @string, writes : Utf8Bytes(@string), writtenBytesIsSet : true, settings : settings);

            /**
             * Similarly, for `byte[]`, the bytes are sent verbatim and the `WrittenBytes` property is assigned
             * the bytes
             */
            await Post(() => bytes, writes : bytes, writtenBytesIsSet : true, settings : settings);

            /**
             * On platforms that support `ReadOnlyMemory<byte>` you can use `PostData.ReadOnlyMemory` to pass this directly
             */
            await Post(() => PostData.ReadOnlyMemory(bytes.AsMemory()), writes : bytes, writtenBytesIsSet : false, settings : settings);

            /**
             * When passing a collection of `string`, the client assumes that it's a collection of valid serialized json,
             * so joins each with newline feeds, ensuring there is a trailing linefeed. As with `string` and `byte[]`,
             * the `WrittenBytes` property is assigned the UTF-8 bytes of the collection of strings if `DisableDirectStreaming` is set on `ConnectionConfiguration`
             */
            await Post(() => PostData.MultiJson(collectionOfStrings), writes : utf8BytesOfListOfStrings, writtenBytesIsSet : false, settings : settings);

            /**
             * When passing a collection of `object`, the client assumes that it's a collection of objects
             * that needs to be serialized individually to json and joined with newline feeds. As with the collection of strings, the client ensures that
             * there is a trailing linefeed.
             */
            await Post(() => PostData.MultiJson(collectionOfObjects), writes : utf8BytesOfCollectionOfObjects, writtenBytesIsSet : false, settings : settings);

            /** In all other cases, Post data is serialized as is and `WrittenBytes` is not assigned */
            await Post(() => PostData.Serializable(@object), writes : utf8ObjectBytes, writtenBytesIsSet : false, settings : settings);

            /**
             * If you want even more control over how your data is written to the stream consider `PostData.StreamHandler`
             * which allows you to inject your own writer routines
             */
            var streamHandler = PostData.StreamHandler(bytes,
                                                       (b, s) => s.Write(b.AsSpan()),
                                                       async(b, s, ctx) => await s.WriteAsync(b.AsMemory(), ctx)
                                                       );

            await Post(() => streamHandler, writes : bytes, writtenBytesIsSet : false, settings : settings);

            /**
             * ==== Forcing WrittenBytes to be set
             *
             * If you want to maintain a copy of the request that went out, you can set `DisableDirectStreaming`  on `ConnectionConfiguration`.
             * In doing so, the serialized bytes are first written to a private `MemoryStream` so that the client can get hold of the serialized bytes
             */
            settings = new ConnectionConfiguration().DisableDirectStreaming();

            await Post(() => PostData.MultiJson(collectionOfObjects), writes : utf8BytesOfCollectionOfObjects, writtenBytesIsSet : true, settings : settings);

            await Post(() => PostData.MultiJson(collectionOfStrings), writes : utf8BytesOfListOfStrings, writtenBytesIsSet : true, settings : settings);

            await Post(() => PostData.ReadOnlyMemory(bytes.AsMemory()), writes : bytes, writtenBytesIsSet : true, settings : settings);

            await Post(() => streamHandler, writes : bytes, writtenBytesIsSet : true, settings : settings);

            /** This behavior can also be observed when serializing a simple object using `DisableDirectStreaming` enabled
             */
            await Post(() => PostData.Serializable(@object), writes : utf8ObjectBytes, writtenBytesIsSet : true, settings : settings);
        }
		private static async Task Post(Func<PostData<object>> postData, byte[] writes, bool storesBytes, IConnectionConfigurationValues settings)
		{
			PostAssert(postData(), writes, storesBytes, settings);
			await PostAssertAsync(postData(), writes, storesBytes, settings);
		}
Beispiel #54
0
        //hide
        private static async Task Post(Func <PostData> postData, byte[] writes, bool writtenBytesIsSet, IConnectionConfigurationValues settings)
        {
            PostAssert(postData(), writes, writtenBytesIsSet, settings);
            await Task.CompletedTask;

            await PostAssertAsync(postData(), writes, writtenBytesIsSet, settings);
        }
Beispiel #55
0
 string IUrlParameter.GetString(IConnectionConfigurationValues settings) => string.Join(",", _forecastIds ?? Enumerable.Empty <string>());
        string IUrlParameter.GetString(IConnectionConfigurationValues settings)
        {
            var nestSettings = settings as IConnectionSettingsValues;

            return(nestSettings?.Inferrer.PropertyName(this));
        }
		public IRequestPipeline Create(IConnectionConfigurationValues configurationValues, IDateTimeProvider dateTimeProvider, IMemoryStreamFactory memorystreamFactory, IRequestParameters requestParameters) => 
			new RequestPipeline(this.Settings, this.DateTimeProvider, this.MemoryStreamFactory, requestParameters ?? new SearchRequestParameters());
 internal FieldMappingProperties(IConnectionConfigurationValues connectionSettings, IReadOnlyDictionary <Field, FieldMapping> backingDictionary)
     : base(connectionSettings, backingDictionary)
 {
 }
Beispiel #59
0
		public string GetString(IConnectionConfigurationValues settings) => 
			string.Join(",", this._nodeIds);
 public UrlFormatProvider(IConnectionConfigurationValues settings)
 {
     _settings = settings;
 }