public void Arrange() { _fixture = new Fixture(); _fixture.Behaviors.OfType <ThrowingRecursionBehavior>().ToList().ForEach(b => _fixture.Behaviors.Remove(b)); _fixture.Behaviors.Add(new OmitOnRecursionBehavior()); _syncQueueMock = new Mock <ISyncQueue>(); _repositoryMock = new Mock <IRepository>(); _matcherMock = new Mock <IMatcher>(); _loggerMock = new Mock <ILoggerWrapper>(); _executionContext = new SpiExecutionContext { InternalRequestId = _fixture.Create <Guid>(), ExternalRequestId = _fixture.Create <string>(), }; _executionContextManagerMock = new Mock <ISpiExecutionContextManager>(); _executionContextManagerMock.Setup(cm => cm.SpiExecutionContext) .Returns(_executionContext); _syncManager = new SyncManager( _syncQueueMock.Object, _repositoryMock.Object, _matcherMock.Object, _loggerMock.Object, _executionContextManagerMock.Object); _cancellationToken = new CancellationToken(); }
/// <inheritdoc /> public virtual void SetContext(IHeaderDictionary headerDictionary) { var spiExecutionContext = new SpiExecutionContext(); ReadHeadersIntoContext(headerDictionary, spiExecutionContext); this.spiExecutionContext = spiExecutionContext; }
/// <inheritdoc /> public override void SetInternalRequestId(Guid internalRequestId) { if (this.spiExecutionContext == null) { this.spiExecutionContext = new SpiExecutionContext(); } base.SetInternalRequestId(internalRequestId); }
/// <summary> /// Looks at the input <paramref name="spiExecutionContext" />, and /// uses the values to automatically populate the headers of the /// <paramref name="restRequest" />. /// </summary> /// <param name="restRequest"> /// An instance of <see cref="RestRequest" />. /// </param> /// <param name="spiExecutionContext"> /// An instance of <see cref="SpiExecutionContext" />. /// </param> public static void AppendContext( this RestRequest restRequest, SpiExecutionContext spiExecutionContext) { if (restRequest == null) { throw new ArgumentNullException(nameof(restRequest)); } if (spiExecutionContext == null) { throw new ArgumentNullException(nameof(spiExecutionContext)); } string identityToken = null; if (spiExecutionContext != null) { identityToken = spiExecutionContext.IdentityToken; } if (!string.IsNullOrEmpty(identityToken)) { string authorizationValue = string.Format( CultureInfo.InvariantCulture, BearerAuthorizationFormat, identityToken); restRequest.AddHeader( HeaderNames.Authorization, authorizationValue); // Remember to also add the internal/external request IDs. Guid?internalRequestId = spiExecutionContext.InternalRequestId; string value = null; if (spiExecutionContext.InternalRequestId.HasValue) { value = internalRequestId.Value.ToString(); restRequest.AddHeader( SpiHeaderNames.InternalRequestIdHeaderName, value); } if (!string.IsNullOrEmpty(spiExecutionContext.ExternalRequestId)) { restRequest.AddHeader( SpiHeaderNames.ExternalRequestIdHeaderName, spiExecutionContext.ExternalRequestId); } } }
public void SetContext_HeaderValuesSetInContext_ValuesAsExpected() { // Arrange Guid?expectedInternalRequestId = new Guid("36b3d65b-02af-407d-acd6-d47587f938fe"); Guid?actualInternalRequestId = null; string expectedExternalRequestId = "ed0509b1-16ea-4e1e-88c0-770be6b17081"; string actualExternalRequestId = null; string expectedIdentityToken = "abcOneTwo3"; string actualIdentityToken = null; Dictionary <string, StringValues> store = new Dictionary <string, StringValues>() { { SpiHeaderNames.InternalRequestIdHeaderName, new StringValues(expectedInternalRequestId.ToString()) }, { SpiHeaderNames.ExternalRequestIdHeaderName, new StringValues(expectedExternalRequestId) }, { HeaderNames.Authorization, new StringValues($"BeaRER {expectedIdentityToken}") } }; HeaderDictionary headerDictionary = new HeaderDictionary( store); SpiExecutionContext spiExecutionContext = null; // Act this.httpSpiExecutionContextManager.SetContext(headerDictionary); spiExecutionContext = this.httpSpiExecutionContextManager.SpiExecutionContext; // Assert actualInternalRequestId = spiExecutionContext.InternalRequestId; Assert.AreEqual(expectedInternalRequestId, actualInternalRequestId); actualExternalRequestId = spiExecutionContext.ExternalRequestId; Assert.AreEqual(actualExternalRequestId, expectedExternalRequestId); actualIdentityToken = spiExecutionContext.IdentityToken; Assert.AreEqual(expectedIdentityToken, actualIdentityToken); }
/// <inheritdoc /> public async Task <GetEnumerationMappingsResponse> GetEnumerationMappingsAsync( string enumerationName, string adapterName, CancellationToken cancellationToken) { GetEnumerationMappingsResponse toReturn = null; string getEnumerationValuesPath = string.Format( CultureInfo.InvariantCulture, GetEnumerationValuesPath, enumerationName, adapterName); Uri getEnumerationValuesUri = new Uri( getEnumerationValuesPath, UriKind.Relative); RestRequest restRequest = new RestRequest( getEnumerationValuesUri, Method.GET); SpiExecutionContext spiExecutionContext = this.spiExecutionContextManager.SpiExecutionContext; restRequest.AppendContext(spiExecutionContext); IRestResponse restResponse = await this.restClient.ExecuteTaskAsync( restRequest, cancellationToken) .ConfigureAwait(false); if (!restResponse.IsSuccessful) { this.ParseErrorInformationThrowException(restResponse); } string responseBody = restResponse.Content; toReturn = JsonConvert.DeserializeObject <GetEnumerationMappingsResponse>( responseBody); return(toReturn); }
/// <summary> /// Set properties of context from HTTP headers. /// </summary> /// <param name="headerDictionary">HTTP headers to read from.</param> /// <param name="context">Context to read headers into.</param> /// <exception cref="ArgumentNullException">Thrown if headers or context is null</exception> protected virtual void ReadHeadersIntoContext(IHeaderDictionary headerDictionary, SpiExecutionContext context) { if (headerDictionary == null) { throw new ArgumentNullException(nameof(headerDictionary)); } if (context == null) { throw new ArgumentNullException(nameof(context)); } if (headerDictionary.ContainsKey(SpiHeaderNames.InternalRequestIdHeaderName)) { string internalRequestIdStr = headerDictionary[SpiHeaderNames.InternalRequestIdHeaderName].First(); context.InternalRequestId = Guid.Parse(internalRequestIdStr); } if (headerDictionary.ContainsKey(SpiHeaderNames.ExternalRequestIdHeaderName)) { context.ExternalRequestId = headerDictionary[SpiHeaderNames.ExternalRequestIdHeaderName].First(); } if (headerDictionary.ContainsKey(HeaderNames.Authorization)) { string authorizationValue = headerDictionary[HeaderNames.Authorization].First(); string authorizationValueUpper = authorizationValue.ToUpperInvariant(); if (authorizationValueUpper.StartsWith(BearerAuthorizationPrefix, StringComparison.InvariantCulture)) { context.IdentityToken = authorizationValue.Substring( BearerAuthorizationPrefix.Length, authorizationValue.Length - BearerAuthorizationPrefix.Length); } } }
private async Task <Dictionary <string, Dictionary <string, string[]> > > GetMappingsFromApi(CancellationToken cancellationToken) { var resource = $"adapters/{SourceSystemNames.GetInformationAboutSchools}/mappings"; _logger.Info($"Calling {resource} on translator api"); var request = new RestRequest(resource, Method.GET); SpiExecutionContext spiExecutionContext = _spiExecutionContextManager.SpiExecutionContext; request.AppendContext(spiExecutionContext); // Do we have an OAuth token? // Or is this a server process? string identityToken = spiExecutionContext.IdentityToken; if (string.IsNullOrEmpty(identityToken)) { _logger.Debug( $"No OAuth token present in the " + $"{nameof(SpiExecutionContext)}. The " + $"{nameof(OAuth2ClientCredentialsAuthenticator)} will " + $"be used, and a new token generated."); // The fact we don't have a token means this is probably a // server process. // We need to generate one... _restClient.Authenticator = _oAuth2ClientCredentialsAuthenticator; } else { _logger.Debug( $"OAuth token present in the " + $"{nameof(SpiExecutionContext)}. This will be used in " + $"calling the Translator."); } var response = await _restClient.ExecuteTaskAsync(request, cancellationToken); if (response.StatusCode == HttpStatusCode.NotFound) { return(null); } if (!response.IsSuccessful) { throw new TranslatorApiException( resource, response.StatusCode, response.Content, response.ErrorException); } _logger.Debug($"Received {response.Content}"); var translationResponse = JsonConvert.DeserializeObject <Dictionary <string, TranslationMappingsResult> >(response.Content); return(translationResponse .Select(kvp => new { EnumerationName = kvp.Key, Mappings = kvp.Value.Mappings, }) .ToDictionary( x => x.EnumerationName, x => x.Mappings)); }