Beispiel #1
0
 public BoltTransactionExecutionEnvironment(ExecutionConfiguration executionConfiguration)
 {
     Username          = executionConfiguration.Username;
     Password          = executionConfiguration.Password;
     JsonConverters    = executionConfiguration.JsonConverters;
     ResourceManagerId = executionConfiguration.ResourceManagerId;
 }
        public BoltGraphClient(Uri uri, string username = null, string password = null, string realm = null)
        {
            if ((uri.Scheme == "http") || (uri.Scheme == "https"))
            {
                throw new NotSupportedException($"To use the {nameof(BoltGraphClient)} you need to provide a 'bolt://' scheme, not '{uri.Scheme}'.");
            }

            this.uri      = uri;
            this.username = username;
            this.password = password;
            this.realm    = realm;
            PolicyFactory = new ExecutionPolicyFactory(this);

            JsonConverters = new List <JsonConverter>();
            JsonConverters.AddRange(DefaultJsonConverters);
            JsonContractResolver = DefaultJsonContractResolver;

            ExecutionConfiguration = new ExecutionConfiguration
            {
                UserAgent        = $"Neo4jClient/{GetType().GetTypeInfo().Assembly.GetName().Version}",
                UseJsonStreaming = true,
                JsonConverters   = JsonConverters,
                Username         = username,
                Password         = password,
                Realm            = realm
            };

//            transactionManager = new TransactionManager(this);
        }
        public void ResourceManagerIdDefaultValueIsSet()
        {
            var configuration        = new ExecutionConfiguration();
            var executionEnvironment = new TransactionExecutionEnvironment(configuration);

            Assert.Equal(configuration.ResourceManagerId, executionEnvironment.ResourceManagerId);
        }
Beispiel #4
0
 private static void DoCommit(Uri commitUri, ExecutionConfiguration executionConfiguration, ISerializer serializer, NameValueCollection customHeaders = null)
 {
     Request.With(executionConfiguration, customHeaders)
     .Post(commitUri.AddPath("commit"))
     .WithJsonContent(serializer.Serialize(new CypherStatementList()))
     .WithExpectedStatusCodes(HttpStatusCode.OK)
     .Execute();
 }
Beispiel #5
0
 public TransactionExecutionEnvironment(ExecutionConfiguration executionConfiguration)
 {
     UserAgent        = executionConfiguration.UserAgent;
     UseJsonStreaming = executionConfiguration.UseJsonStreaming;
     Username         = executionConfiguration.Username;
     Password         = executionConfiguration.Password;
     JsonConverters   = executionConfiguration.JsonConverters;
 }
Beispiel #6
0
        internal static async Task <NeoServerConfiguration> GetConfigurationAsync(Uri rootUri, string username, string password, string realm, EncryptionLevel?encryptionLevel, ExecutionConfiguration executionConfiguration)
        {
            if (executionConfiguration == null)
            {
                var httpClient = new HttpClientWrapper(username, password);

                executionConfiguration = new ExecutionConfiguration
                {
                    HttpClient       = httpClient,
                    UserAgent        = $"Neo4jClient/{typeof(NeoServerConfiguration).GetTypeInfo().Assembly.GetName().Version}",
                    UseJsonStreaming = true,
                    JsonConverters   = GraphClient.DefaultJsonConverters,
                    Username         = username,
                    Password         = password,
                    Realm            = realm,
                    EncryptionLevel  = encryptionLevel
                };
            }

            if (!rootUri.AbsoluteUri.EndsWith("/"))
            {
                rootUri = new Uri(rootUri.AbsoluteUri + "/");
            }

            rootUri = new Uri(rootUri, "");

            var result = await Request.With(executionConfiguration)
                         .Get(rootUri)
                         .WithExpectedStatusCodes(HttpStatusCode.OK)
                         .ParseAs <RootApiResponse>()
                         .ExecuteAsync().ConfigureAwait(false);

            if (result == null)
            {
                throw new InvalidOperationException("Couldn't obtain server Root API configuration.");
            }

            var rootUriWithoutUserInfo = rootUri;

            if (!string.IsNullOrEmpty(rootUriWithoutUserInfo.UserInfo))
            {
                rootUriWithoutUserInfo = new UriBuilder(rootUri.AbsoluteUri)
                {
                    UserName = "",
                    Password = ""
                }.Uri;
            }

            result.TrimUriFromProperties(rootUriWithoutUserInfo.AbsoluteUri);

            return(new NeoServerConfiguration(result)
            {
                RootUri = rootUri,
                Username = username,
                Password = password,
                Realm = realm
            });
        }
Beispiel #7
0
 private static void DoRollback(Uri rollbackUri, ExecutionConfiguration executionConfiguration, NameValueCollection customHeaders)
 {
     // not found is ok because it means our transaction either was committed or the timeout was expired
     // and it was rolled back for us
     Request.With(executionConfiguration, customHeaders)
     .Delete(rollbackUri)
     .WithExpectedStatusCodes(HttpStatusCode.OK, HttpStatusCode.NotFound)
     .Execute();
 }
        public void UserCanSetResourceManagerId()
        {
            var resourceManagerId = Guid.NewGuid();
            var configuration     = new ExecutionConfiguration {
                ResourceManagerId = resourceManagerId
            };
            var executionEnvironment = new TransactionExecutionEnvironment(configuration);

            Assert.Equal(resourceManagerId, executionEnvironment.ResourceManagerId);
        }
Beispiel #9
0
        private static Uri DoKeepAlive(
            Uri keepAliveUri,
            ExecutionConfiguration executionConfiguration,
            ISerializer serializer,
            bool newTransaction = false)
        {
            var partialRequest = Request.With(executionConfiguration)
                                 .Post(keepAliveUri)
                                 .WithJsonContent(serializer.Serialize(new CypherStatementList()));

            var response = newTransaction ?
                           partialRequest.WithExpectedStatusCodes(HttpStatusCode.OK, HttpStatusCode.Created).Execute() :
                           partialRequest.WithExpectedStatusCodes(HttpStatusCode.OK).Execute();

            return(response.Headers.Location);
        }
        private static async Task <Uri> DoKeepAlive(
            Uri keepAliveUri,
            ExecutionConfiguration executionConfiguration,
            ISerializer serializer,
            NameValueCollection customHeaders = null,
            bool newTransaction = false)
        {
            var partialRequest = Request.With(executionConfiguration, customHeaders)
                                 .Post(keepAliveUri)
                                 .WithJsonContent(serializer.Serialize(new CypherStatementList()));

            var response = newTransaction ?
                           await partialRequest.WithExpectedStatusCodes(HttpStatusCode.OK, HttpStatusCode.Created).ExecuteAsync().ConfigureAwait(false) :
                           await partialRequest.WithExpectedStatusCodes(HttpStatusCode.OK).ExecuteAsync().ConfigureAwait(false);

            return(response.Headers.Location);
        }
Beispiel #11
0
 public GraphClient(Uri rootUri, IHttpClient httpClient)
 {
     RootUri        = rootUri;
     JsonConverters = new List <JsonConverter>();
     JsonConverters.AddRange(DefaultJsonConverters);
     JsonContractResolver   = DefaultJsonContractResolver;
     ExecutionConfiguration = new ExecutionConfiguration
     {
         HttpClient       = httpClient,
         UserAgent        = $"Neo4jClient/{GetType().GetTypeInfo().Assembly.GetName().Version}",
         UseJsonStreaming = true,
         JsonConverters   = JsonConverters,
         Username         = httpClient?.Username,
         Password         = httpClient?.Password
     };
     UseJsonStreamingIfAvailable = true;
     policyFactory = new ExecutionPolicyFactory(this);
 }
        /// <summary>
        ///     Creates a new instance of the <see cref="BoltGraphClient" />.
        /// </summary>
        /// <param name="uri">
        ///     If the <paramref name="uris" /> parameter is provided, this will be treated as a <em>virtual URI</em>
        ///     , else it will be the URI connected to.
        /// </param>
        /// <param name="uris">
        ///     A collection of <see cref="Uri" /> instances to connect to using an
        ///     <see cref="IServerAddressResolver" />. Leave <c>null</c> (or empty) if you don't want to use it.
        /// </param>
        /// <param name="username">The username to connect to Neo4j with.</param>
        /// <param name="password">The password to connect to Neo4j with.</param>
        /// <param name="realm">The realm to connect to Neo4j with.</param>
        public BoltGraphClient(Uri uri, IEnumerable <Uri> uris, string username = null, string password = null, string realm = null, EncryptionLevel?encryptionLevel = null, bool serializeNullValues = false)
        {
            var localUris = uris?.ToList();

            if (localUris != null && localUris.Any())
            {
                //TODO - const/etc these
                if (!new [] { "neo4j", "neo4j+s", "neo4j+ssc" }.Contains(uri.Scheme.ToLowerInvariant()))
                {
                    throw new NotSupportedException($"To use the {nameof(BoltGraphClient)} with an Address Resolver you need to use the 'neo4j://' scheme, for the 'uri' parameter, not '{uri.Scheme}'.");
                }

                addressResolver = new AddressResolver(uri, localUris);
            }
            else if (!new [] { "neo4j", "neo4j+s", "neo4j+ssc", "bolt", "bolt+s", "bolt+ssc" }.Contains(uri.Scheme.ToLowerInvariant()))
            {
                throw new NotSupportedException($"To use the {nameof(BoltGraphClient)} you need to provide a 'bolt://' or 'neo4j://' scheme, not '{uri.Scheme}'.");
            }

            this.uri             = uri;
            this.username        = username;
            this.password        = password;
            this.realm           = realm;
            this.encryptionLevel = encryptionLevel;
            PolicyFactory        = new ExecutionPolicyFactory(this);

            JsonConverters = new List <JsonConverter>();
            JsonConverters.AddRange(DefaultJsonConverters);
            JsonContractResolver = DefaultJsonContractResolver;

            ExecutionConfiguration = new ExecutionConfiguration
            {
                UserAgent           = $"Neo4jClient/{GetType().GetTypeInfo().Assembly.GetName().Version}",
                UseJsonStreaming    = true,
                JsonConverters      = JsonConverters,
                Username            = username,
                Password            = password,
                Realm               = realm,
                SerializeNullValues = serializeNullValues
            };

            transactionManager = new BoltTransactionManager(this);
        }
Beispiel #13
0
        /// <summary>
        ///     Creates a new instance of the <see cref="BoltGraphClient" />.
        /// </summary>
        /// <param name="uri">
        ///     If the <paramref name="uris" /> parameter is provided, this will be treated as a <em>virtual URI</em>
        ///     , else it will be the URI connected to.
        /// </param>
        /// <param name="uris">
        ///     A collection of <see cref="Uri" /> instances to connect to using an
        ///     <see cref="IServerAddressResolver" />. Leave <c>null</c> (or empty) if you don't want to use it.
        /// </param>
        /// <param name="username">The username to connect to Neo4j with.</param>
        /// <param name="password">The password to connect to Neo4j with.</param>
        /// <param name="realm">The realm to connect to Neo4j with.</param>
        public BoltGraphClient(Uri uri, IEnumerable <Uri> uris, string username = null, string password = null, string realm = null)
        {
            var localUris = uris?.ToList();

            if (localUris != null && localUris.Any())
            {
                if (uri.Scheme.ToLowerInvariant() != "bolt+routing")
                {
                    throw new NotSupportedException($"To use the {nameof(BoltGraphClient)} you need to provide a 'bolt://' scheme, not '{uri.Scheme}'.");
                }

                addressResolver = new AddressResolver(uri, localUris);
            }
            else if (uri.Scheme.ToLowerInvariant() != "bolt" && uri.Scheme.ToLowerInvariant() != "bolt+routing")
            {
                throw new NotSupportedException($"To use the {nameof(BoltGraphClient)} you need to provide a 'bolt://' or 'bolt+routing://' scheme, not '{uri.Scheme}'.");
            }


            this.uri      = uri;
            this.username = username;
            this.password = password;
            this.realm    = realm;
            PolicyFactory = new ExecutionPolicyFactory(this);

            JsonConverters = new List <JsonConverter>();
            JsonConverters.AddRange(DefaultJsonConverters);
            JsonContractResolver = DefaultJsonContractResolver;

            ExecutionConfiguration = new ExecutionConfiguration
            {
                UserAgent        = $"Neo4jClient/{GetType().GetTypeInfo().Assembly.GetName().Version}",
                UseJsonStreaming = true,
                JsonConverters   = JsonConverters,
                Username         = username,
                Password         = password,
                Realm            = realm
            };

            transactionManager = new BoltTransactionManager(this);
        }
Beispiel #14
0
        public async Task ShouldThrowExceptionIfRootApiIsNotDefined()
        {
            using (var testHarness = new RestTestHarness
            {
                { MockRequest.Get("/"), new MockResponse {
                      StatusCode = HttpStatusCode.OK
                  } }
            })
            {
                var httpClient = testHarness.GenerateHttpClient(testHarness.BaseUri);

                var executeConfiguration = new ExecutionConfiguration
                {
                    HttpClient       = httpClient,
                    UserAgent        = $"Neo4jClient/{typeof(NeoServerConfiguration).Assembly.GetName().Version}",
                    UseJsonStreaming = true,
                    JsonConverters   = GraphClient.DefaultJsonConverters
                };

                await Assert.ThrowsAsync <InvalidOperationException>(async() => await NeoServerConfiguration.GetConfigurationAsync(new Uri(testHarness.BaseUri), null, null, null, null, executeConfiguration));
            }
        }
Beispiel #15
0
        public void ShouldThrowExceptionIfRootApiIsNotDefined()
        {
            using (var testHarness = new RestTestHarness
            {
                { MockRequest.Get("/"), new MockResponse {
                      StatusCode = HttpStatusCode.OK
                  } }
            })
            {
                var httpClient = testHarness.GenerateHttpClient(testHarness.BaseUri);

                var executeConfiguration = new ExecutionConfiguration
                {
                    HttpClient = httpClient,
                    UserAgent  =
                        string.Format("Neo4jClient/{0}", typeof(NeoServerConfiguration).Assembly.GetName().Version),
                    UseJsonStreaming = true,
                    JsonConverters   = GraphClient.DefaultJsonConverters
                };

                NeoServerConfiguration.GetConfiguration(new Uri(testHarness.BaseUri), null, null, executeConfiguration);
            }
        }
Beispiel #16
0
        public async Task GraphClientFactoryUseCase()
        {
            const string queryText = @"RETURN d";

            var cypherQuery    = new CypherQuery(queryText, new Dictionary <string, object>(), CypherResultMode.Set, CypherResultFormat.Rest, "neo4j");
            var cypherApiQuery = new CypherStatementList {
                new CypherTransactionStatement(cypherQuery)
            };

            using (var testHarness = new RestTestHarness
            {
                { MockRequest.Get("/"), MockResponse.NeoRoot20() },
                { MockRequest.PostObjectAsJson("/transaction/commit", cypherApiQuery), new MockResponse {
                      StatusCode = HttpStatusCode.OK
                  } }
            })
            {
                var httpClient = testHarness.GenerateHttpClient(testHarness.BaseUri);

                var executeConfiguration = new ExecutionConfiguration
                {
                    HttpClient       = httpClient,
                    UserAgent        = $"Neo4jClient/{typeof(NeoServerConfiguration).Assembly.GetName().Version}",
                    UseJsonStreaming = true,
                    JsonConverters   = GraphClient.DefaultJsonConverters
                };

                var configuration = await NeoServerConfiguration.GetConfigurationAsync(new Uri(testHarness.BaseUri), null, null, null, null, executeConfiguration);

                var factory = new GraphClientFactory(configuration);

                using (var client = await factory.CreateAsync(httpClient))
                {
                    await client.Cypher.Return <object>("d").ExecuteWithoutResultsAsync();
                }
            }
        }
Beispiel #17
0
        public void GraphClientFactoryUseCase()
        {
            const string queryText = @"MATCH (d) RETURN d";

            var cypherQuery    = new CypherQuery(queryText, null, CypherResultMode.Set, CypherResultFormat.Rest);
            var cypherApiQuery = new CypherApiQuery(cypherQuery);

            using (var testHarness = new RestTestHarness
            {
                { MockRequest.Get("/"), MockResponse.NeoRoot() },
                { MockRequest.PostObjectAsJson("/cypher", cypherApiQuery), new MockResponse {
                      StatusCode = HttpStatusCode.OK
                  } }
            })
            {
                var httpClient = testHarness.GenerateHttpClient(testHarness.BaseUri);

                var executeConfiguration = new ExecutionConfiguration
                {
                    HttpClient = httpClient,
                    UserAgent  =
                        string.Format("Neo4jClient/{0}", typeof(NeoServerConfiguration).Assembly.GetName().Version),
                    UseJsonStreaming = true,
                    JsonConverters   = GraphClient.DefaultJsonConverters
                };

                var configuration = NeoServerConfiguration.GetConfiguration(new Uri(testHarness.BaseUri), null, null, executeConfiguration);

                var factory = new GraphClientFactory(configuration);

                using (var client = factory.Create(httpClient))
                {
                    client.Cypher.Match("(d)").Return <object>("d").ExecuteWithoutResults();
                }
            }
        }
Beispiel #18
0
 private Configuration()
 {
     AssetsConfiguration    = new AssetsConfiguration();
     ResearchConfiguration  = new ResearchConfiguration();
     ExecutionConfiguration = new ExecutionConfiguration();
 }
 private string GetAuthorizationHeaderValue(ExecutionConfiguration executionConfig)
 {
     byte[] encoded =
         Encoding.ASCII.GetBytes(string.Format("{0}:{1}", executionConfig.Username, executionConfig.Password));
     return(new AuthenticationHeaderValue("Basic", Convert.ToBase64String(encoded)).ToString());
 }
Beispiel #20
0
 public static IRequestTypeBuilder With(ExecutionConfiguration configuration)
 {
     return new RequestTypeBuilder(configuration);
 }
Beispiel #21
0
 public static IRequestTypeBuilder With(ExecutionConfiguration configuration)
 {
     return(new RequestTypeBuilder(configuration));
 }
        internal static async Task <NeoServerConfiguration> GetConfigurationAsync(Uri rootUri, string username, string password, ExecutionConfiguration executionConfiguration)
        {
            if (executionConfiguration == null)
            {
                var httpClient = new HttpClientWrapper(username, password);

                executionConfiguration = new ExecutionConfiguration
                {
                    HttpClient = httpClient,
                    UserAgent  =
                        string.Format("Neo4jClient/{0}", typeof(NeoServerConfiguration).Assembly.GetName().Version),
                    UseJsonStreaming = true,
                    JsonConverters   = GraphClient.DefaultJsonConverters,
                    Username         = username,
                    Password         = password
                };
            }

            if (!rootUri.AbsoluteUri.EndsWith("/"))
            {
                rootUri = new Uri(rootUri.AbsoluteUri + "/");
            }

            rootUri = new Uri(rootUri, "");

            var result = await Request.With(executionConfiguration)
                         .Get(rootUri)
                         .WithExpectedStatusCodes(HttpStatusCode.OK)
                         .ParseAs <RootApiResponse>()
                         .ExecuteAsync().ConfigureAwait(false);

            if (result == null)
            {
                throw new ApplicationException("Couldn't obtain server Root API configuration.");
            }

            var rootUriWithoutUserInfo = rootUri;

            if (!string.IsNullOrEmpty(rootUriWithoutUserInfo.UserInfo))
            {
                rootUriWithoutUserInfo = new UriBuilder(rootUri.AbsoluteUri)
                {
                    UserName = "",
                    Password = ""
                }.Uri;
            }

            var baseUriLengthToTrim = rootUriWithoutUserInfo.AbsoluteUri.Length - 1;

            result.Batch             = result.Batch.Substring(baseUriLengthToTrim);
            result.Node              = result.Node.Substring(baseUriLengthToTrim);
            result.NodeIndex         = result.NodeIndex.Substring(baseUriLengthToTrim);
            result.Relationship      = "/relationship"; //Doesn't come in on the Service Root
            result.RelationshipIndex = result.RelationshipIndex.Substring(baseUriLengthToTrim);
            result.ExtensionsInfo    = result.ExtensionsInfo.Substring(baseUriLengthToTrim);

            if (!string.IsNullOrEmpty(result.Transaction))
            {
                result.Transaction = result.Transaction.Substring(baseUriLengthToTrim);
            }

            if (result.Extensions != null && result.Extensions.GremlinPlugin != null)
            {
                result.Extensions.GremlinPlugin.ExecuteScript =
                    result.Extensions.GremlinPlugin.ExecuteScript.Substring(baseUriLengthToTrim);
            }

            if (result.Cypher != null)
            {
                result.Cypher = result.Cypher.Substring(baseUriLengthToTrim);
            }

            return(new NeoServerConfiguration(result)
            {
                RootUri = rootUri,
                Username = username,
                Password = password
            });
        }