//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void terminateLongRunningRestTransactionalEndpointWithCustomTimeoutQuery() throws Exception //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: public virtual void TerminateLongRunningRestTransactionalEndpointWithCustomTimeoutQuery() { GraphDatabaseAPI database = StartDatabaseWithTimeout(); KernelTransactionMonitor timeoutMonitor = database.DependencyResolver.resolveDependency( typeof( KernelTransactionMonitor ) ); OpenEnterpriseNeoServer neoServer = StartNeoServer( ( GraphDatabaseFacade ) database ); long customTimeout = TimeUnit.SECONDS.toMillis( 10 ); HTTP.Response beginResponse = HTTP.withHeaders( HttpHeaderUtils.MAX_EXECUTION_TIME_HEADER, customTimeout.ToString() ).POST(TransactionUri(neoServer), quotedJson("{ 'statements': [ { 'statement': 'CREATE (n)' } ] }")); assertEquals( "Response should be successful.", 201, beginResponse.Status() ); string transactionEndPoint = beginResponse.Location(); _fakeClock.forward( 3, TimeUnit.SECONDS ); HTTP.Response response = HTTP.POST( transactionEndPoint, quotedJson( "{ 'statements': [ { 'statement': 'CREATE (n)' } ] }" ) ); assertEquals( "Response should be successful.", 200, response.Status() ); _fakeClock.forward( 11, TimeUnit.SECONDS ); timeoutMonitor.Run(); response = HTTP.POST( transactionEndPoint, quotedJson( "{ 'statements': [ { 'statement': 'CREATE (n)' } ] }" ) ); assertEquals( "Response should be successful.", 200, response.Status() ); HTTP.Response commitResponse = HTTP.POST( transactionEndPoint + "/commit" ); assertEquals( "Transaction should be already closed and not found.", 404, commitResponse.Status() ); assertEquals( "Transaction should be forcefully closed.", TransactionNotFound.code().serialize(), commitResponse.Get("errors").findValue("code").asText() ); AssertDatabaseDoesNotHaveNodes( database ); }
public static long ExtractTxId(HTTP.Response response) { int lastSlash = response.Location().LastIndexOf('/'); string txIdString = response.Location().Substring(lastSlash + 1); return(long.Parse(txIdString)); }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void shouldReturnCorrectStatusCodeOnDeadlock() throws Exception //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: public virtual void ShouldReturnCorrectStatusCodeOnDeadlock() { // Given using (Transaction tx = Graphdb().beginTx()) { Graphdb().createNode(Label.label("First")); Graphdb().createNode(Label.label("Second")); tx.Success(); } // When I lock node:First HTTP.Response begin = _http.POST("db/data/transaction", quotedJson("{ 'statements': [ { 'statement': 'MATCH (n:First) SET n.prop=1' } ] }")); // and I lock node:Second, and wait for a lock on node:First in another transaction OtherThread.execute(WriteToFirstAndSecond()); // and I wait for those locks to be pending assertTrue(_secondNodeLocked.await(10, TimeUnit.SECONDS)); Thread.Sleep(1000); // and I then try and lock node:Second in the first transaction HTTP.Response deadlock = _http.POST(begin.Location(), quotedJson("{ 'statements': [ { 'statement': 'MATCH (n:Second) SET n.prop=1' } ] }")); // Then assertThat(deadlock.Get("errors").get(0).get("code").TextValue, equalTo(DeadlockDetected.code().serialize())); }
private static HTTP.Response StartTx(HTTP.Builder http) { HTTP.Response tx = http.Post("db/data/transaction"); assertThat(tx.Status(), equalTo(201)); assertThat(tx, containsNoErrors()); return(tx); }
private static HTTP.Response ExecuteUpdateStatement(HTTP.Response tx, long value, HTTP.Builder http) { string updateQuery = "MATCH (n:" + _label + ") SET n." + PROPERTY + "=" + value; HTTP.RawPayload json = quotedJson("{'statements': [{'statement':'" + updateQuery + "'}]}"); return(http.Post(tx.Location(), json)); }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: //ORIGINAL LINE: public void startServerWithConfiguredUser() throws java.io.IOException public virtual void StartServerWithConfiguredUser() { StartServer(true); // Set the password HTTP.Response post = HTTP.withBasicAuth("neo4j", "neo4j").POST(_server.baseUri().resolve("/user/neo4j/password").ToString(), HTTP.RawPayload.quotedJson("{'password':'******'}")); assertEquals(200, post.Status()); }
private static bool AssertElementAtMetaIndex(HTTP.Response response, int[] indexes, string element) { try { IEnumerator <JsonNode> meta = GetJsonNodeWithName(response, "meta").GetEnumerator(); int i = 0; //JAVA TO C# CONVERTER TODO TASK: Java iterators are only converted within the context of 'while' and 'for' loops: for (int metaIndex = 0; meta.hasNext() && i < indexes.Length; metaIndex++) { JsonNode node = meta.Current; if (!node.Null) { string type = node.get("type").TextValue; if (type.Equals(element)) { assertEquals("Expected " + element + " to be at indexes " + Arrays.ToString(indexes) + ", but found it at " + metaIndex, indexes[i], metaIndex); ++i; } else { assertNotEquals("Expected " + element + " at index " + metaIndex + ", but found " + type, indexes[i], metaIndex); } } } return(i == indexes.Length); } catch (JsonParseException) { return(false); } }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void shouldHavePredefinedRoles() throws Exception //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: public virtual void ShouldHavePredefinedRoles() { // Given StartServerWithConfiguredUser(); // When string method = "POST"; string path = "db/data/transaction/commit"; HTTP.RawPayload payload = HTTP.RawPayload.quotedJson("{'statements':[{'statement':'CALL dbms.security.listRoles()'}]}"); HTTP.Response response = HTTP.withBasicAuth("neo4j", "secret").request(method, Server.baseUri().resolve(path).ToString(), payload); // Then assertThat(response.Status(), equalTo(200)); ArrayNode errors = ( ArrayNode )response.Get("errors"); assertThat("Should have no errors", errors.size(), equalTo(0)); ArrayNode results = ( ArrayNode )response.Get("results"); ArrayNode data = ( ArrayNode )results.get(0).get("data"); assertThat("Should have 5 predefined roles", data.size(), equalTo(5)); Stream <string> values = data.findValues("row").Select(row => row.get(0).asText()); assertThat("Expected specific roles", values.collect(Collectors.toList()), hasItems("admin", "architect", "publisher", "editor", "reader")); }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: //ORIGINAL LINE: private void assertQueryGetsValue(ServerControls server, String query, long value) throws Throwable private void AssertQueryGetsValue(ServerControls server, string query, long value) { HTTP.Response response = HTTP.POST(server.HttpURI().resolve("db/data/transaction/commit").ToString(), quotedJson("{ 'statements': [ { 'statement': '" + query + "' } ] }")); assertEquals("[]", response.Get("errors").ToString()); JsonNode result = response.Get("results").get(0); assertEquals("value", result.get("columns").get(0).asText()); assertEquals(value, result.get("data").get(0).get("row").get(0).asLong()); }
private OtherThreadExecutor.WorkerCommand <object, object> WriteToFirstAndSecond() { return(state => { HTTP.Response post = _http.POST("db/data/transaction", quotedJson("{ 'statements': [ { 'statement': 'MATCH (n:Second) SET n.prop=1' } ] }")); _secondNodeLocked.Signal(); _http.POST(post.location(), quotedJson("{ 'statements': [ { 'statement': 'MATCH (n:First) SET n.prop=1' } ] }")); return null; }); }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void cantChangeToCurrentPassword() throws Exception //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: public virtual void CantChangeToCurrentPassword() { // Given StartServer(true); // When HTTP.Response res = HTTP.withBasicAuth("neo4j", "neo4j").POST(_server.baseUri().resolve("/user/neo4j/password").ToString(), HTTP.RawPayload.quotedJson("{'password':'******'}")); // Then assertThat(res.Status(), equalTo(422)); }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void shouldReturnEmptyMapForEmptyProperties() public virtual void ShouldReturnEmptyMapForEmptyProperties() { // Given string node = HTTP.POST(Server().baseUri().resolve("db/data/node").ToString()).location(); string rel = HTTP.POST(node + "/relationships", quotedJson("{'to':'" + node + "', " + "'type':'LOVES'}")).location(); // When HTTP.Response res = HTTP.GET(rel + "/properties"); // Then MatcherAssert.assertThat(res.RawContent(), equalTo("{ }")); }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void shouldGetHelpfulErrorOnProcedureThrowsException() throws Exception //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: public virtual void ShouldGetHelpfulErrorOnProcedureThrowsException() { // When using (ServerControls server = CreateServer(typeof(MyFunctions)).newServer()) { // Then HTTP.Response response = HTTP.POST(server.HttpURI().resolve("db/data/transaction/commit").ToString(), quotedJson("{ 'statements': [ { 'statement': 'RETURN org.neo4j.harness.funcThatThrows()' } ] }")); string error = response.Get("errors").get(0).get("message").asText(); assertEquals("Failed to invoke function `org.neo4j.harness.funcThatThrows`: Caused by: java.lang" + ".RuntimeException: This is an exception", error); } }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void shouldReportCommunityEdition() throws Exception //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: public virtual void ShouldReportCommunityEdition() { // Given string releaseVersion = Server.Database.Graph.DependencyResolver.resolveDependency(typeof(KernelData)).version().ReleaseVersion; // When HTTP.Response res = HTTP.GET(FunctionalTestHelper.managementUri() + "/" + VersionAndEditionService.SERVER_PATH); // Then assertEquals(200, res.Status()); assertThat(res.Get("edition").asText(), equalTo("community")); assertThat(res.Get("version").asText(), equalTo(releaseVersion)); }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void shouldHandleStringFixtures() throws Exception //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: public virtual void ShouldHandleStringFixtures() { // Given two files in the root folder File targetFolder = TestDir.directory(); // When using (ServerControls server = GetServerBuilder(targetFolder).withFixture("CREATE (a:User)").newServer()) { // Then HTTP.Response response = HTTP.POST(server.HttpURI().ToString() + "db/data/transaction/commit", quotedJson("{'statements':[{'statement':'MATCH (n:User) RETURN n'}]}")); assertThat(response.Get("results").get(0).get("data").size(), equalTo(1)); } }
static StackObject *get_Bytes_0(ILIntepreter __intp, StackObject *__esp, IList <object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject *ptr_of_this_method; StackObject *__ret = ILIntepreter.Minus(__esp, 1); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); HTTP.Response instance_of_this_method = (HTTP.Response) typeof(HTTP.Response).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); var result_of_this_method = instance_of_this_method.Bytes; return(ILIntepreter.PushObject(__ret, __mStack, result_of_this_method)); }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void shouldWorkWithInjectableFromKernelExtension() throws Throwable //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: public virtual void ShouldWorkWithInjectableFromKernelExtension() { // When using (ServerControls server = CreateServer(typeof(MyFunctionsUsingMyService)).newServer()) { // Then HTTP.Response response = HTTP.POST(server.HttpURI().resolve("db/data/transaction/commit").ToString(), quotedJson("{ 'statements': [ { 'statement': 'RETURN my.hello() AS result' } ] }")); assertEquals("[]", response.Get("errors").ToString()); JsonNode result = response.Get("results").get(0); assertEquals("result", result.get("columns").get(0).asText()); assertEquals("world", result.get("data").get(0).get("row").get(0).asText()); } }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void shouldIgnoreEmptyFixtureFiles() throws Exception //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: public virtual void ShouldIgnoreEmptyFixtureFiles() { // Given two files in the root folder File targetFolder = TestDir.directory(); FileUtils.writeToFile(new File(targetFolder, "fixture1.cyp"), "CREATE (u:User)\n" + "CREATE (a:OtherUser)", false); FileUtils.writeToFile(new File(targetFolder, "fixture2.cyp"), "", false); // When using (ServerControls server = GetServerBuilder(targetFolder).withFixture(targetFolder).newServer()) { // Then HTTP.Response response = HTTP.POST(server.HttpURI().ToString() + "db/data/transaction/commit", quotedJson("{'statements':[{'statement':'MATCH (n:User) RETURN n'}]}")); assertThat(response.Get("results").get(0).get("data").size(), equalTo(1)); } }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void terminateSingleInstanceRestTransactionThatWaitsForLock() throws Exception //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: public virtual void TerminateSingleInstanceRestTransactionThatWaitsForLock() { ServerControls server = _cleanupRule.add(TestServerBuilders.newInProcessBuilder().withConfig(GraphDatabaseSettings.auth_enabled, Settings.FALSE).withConfig(GraphDatabaseSettings.lock_manager, LockManagerName).withConfig(OnlineBackupSettings.online_backup_enabled, Settings.FALSE).newServer()); GraphDatabaseService db = server.Graph(); HTTP.Builder http = withBaseUri(server.HttpURI()); long value1 = 1L; long value2 = 2L; CreateNode(db); HTTP.Response tx1 = StartTx(http); HTTP.Response tx2 = StartTx(http); AssertNumberOfActiveTransactions(2, db); HTTP.Response update1 = ExecuteUpdateStatement(tx1, value1, http); assertThat(update1.Status(), equalTo(200)); assertThat(update1, containsNoErrors()); System.Threading.CountdownEvent latch = new System.Threading.CountdownEvent(1); //JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET: //ORIGINAL LINE: java.util.concurrent.Future<?> tx2Result = executeInSeparateThread("tx2", () -> Future <object> tx2Result = ExecuteInSeparateThread("tx2", () => { latch.Signal(); Response update2 = ExecuteUpdateStatement(tx2, value2, http); AssertTxWasTerminated(update2); }); Await(latch); SleepForAWhile(); Terminate(tx2, http); Commit(tx1, http); HTTP.Response update3 = ExecuteUpdateStatement(tx2, value2, http); assertThat(update3.Status(), equalTo(404)); tx2Result.get(1, TimeUnit.MINUTES); AssertNodeExists(db, value1); }
public virtual void RollbackAnOpenTransaction() { // Given HTTP.Response firstReq = POST(DataUri + "transaction", HTTP.RawPayload.quotedJson("{ 'statements': [ { 'statement': 'CREATE (n) RETURN id(n)' } ] }")); string location = firstReq.Location(); // Document ResponseEntity response = GenConflict.get().expectedStatus(200).delete(location); // Then IDictionary <string, object> result = jsonToMap(response.Entity()); AssertNoErrors(result); int?id = ResultCell(firstReq, 0, 0); assertThat(GET(getNodeUri(id)).status(), @is(404)); }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Theory public void shouldNotRejectIndexValueThatIsJustSmallerThanConfiguredSize(String uniqueness) public virtual void ShouldNotRejectIndexValueThatIsJustSmallerThanConfiguredSize(string uniqueness) { //Given _server.start(); // When string nodeURI = HTTP.POST(_server.baseUri().ToString() + "db/data/node").header("Location"); Random r = new Random(); string value = ""; for (int i = 0; i < 4_000; i++) { value += ( char )(r.Next(26) + 'a'); } HTTP.Response response = HTTP.POST(_server.baseUri().ToString() + "db/data/index/node/favorites?uniqueness=" + uniqueness, quotedJson("{ 'value': '" + value + " ', 'uri':'" + nodeURI + "', 'key': 'some-key' }")); // Then assertThat(response.Status(), @is(201)); }
private string ParseErrorMessage(HTTP.Response response) { try { JsonNode data = JsonHelper.jsonNode(response.RawContent()); if (data.has("errors") && data.get("errors").has(0)) { JsonNode firstError = data.get("errors").get(0); if (firstError.has("message")) { return(firstError.get("message").asText()); } } } catch (JsonParseException) { fail("Unexpected error parsing Json!"); } return(""); }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void clientErrorShouldRollbackTheTransaction() throws org.neo4j.server.rest.domain.JsonParseException //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: public virtual void ClientErrorShouldRollbackTheTransaction() { // Given HTTP.Response first = POST(TxUri(), quotedJson("{'statements': [{'statement': 'CREATE (n {prop : 1})'}]}")); assertThat(first.Status(), @is(201)); assertThat(first, containsNoErrors()); long txId = ExtractTxId(first); // When HTTP.Response malformed = POST(TxUri(txId), quotedJson("{'statements': [{'statement': '" + Query + "'}]}")); // Then // malformed POST contains expected error assertThat(malformed.Status(), @is(200)); assertThat(malformed, hasErrors(ErrorStatus)); // transaction was rolled back on the previous step and we can't commit it HTTP.Response commit = POST(first.StringFromContent("commit")); assertThat(commit.Status(), @is(404)); }
public override string ExecuteQuery(RESTSubject subject, string call, IDictionary <string, object> @params, System.Action <ResourceIterator <IDictionary <string, object> > > resultConsumer) { HTTP.RawPayload payload = ConstructQuery(call); HTTP.Response response = HTTP.withHeaders(HttpHeaders.AUTHORIZATION, subject.PrincipalCredentials).request(POST, CommitURL(), payload); try { string error = ParseErrorMessage(response); if (error.Length > 0) { return(error); } Consume(resultConsumer, JsonHelper.jsonNode(response.RawContent())); } catch (JsonParseException) { fail("Unexpected error parsing Json!"); } return(""); }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void shouldAllowExecutingEnterpriseBuiltInProceduresWithAuthDisabled() throws Exception //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: public virtual void ShouldAllowExecutingEnterpriseBuiltInProceduresWithAuthDisabled() { // Given StartServerWithAuthDisabled(); // When string method = "POST"; string path = "db/data/transaction/commit"; HTTP.RawPayload payload = HTTP.RawPayload.quotedJson("{'statements':[{'statement':'CALL dbms.listQueries()'}]}"); HTTP.Response response = HTTP.request(method, Server.baseUri().resolve(path).ToString(), payload); // Then assertThat(response.Status(), equalTo(200)); ArrayNode errors = ( ArrayNode )response.Get("errors"); assertThat("Should have no errors", errors.size(), equalTo(0)); ArrayNode results = ( ArrayNode )response.Get("results"); ArrayNode data = ( ArrayNode )results.get(0).get("data"); assertThat("Should see our own query", data.size(), equalTo(1)); }
// The client state machine void Kill() { // Stop the response in its tracks. This will trigger the done // callback, which will similarly kill any reading on the request. // Note that this will actually flow back and cause Kill() to be // executed a second time; this is fine, because both the response // and our Dispose method gracefully handle meing called multiple // times. if (Response != null) { var temp = Response; Response = null; temp.Abort(); } // This will wipe out the socket, stopping any current reading // in its tracks. Dispose(); }
public void Start() { // Set up the state Ready = true; Autoread = true; Request = null; Response = null; Version = HTTP.Version.HTTP1_0; Method = null; Path = null; Headers = null; DataAdapter = null; // If there's already a reader chugging away, simply setting // autoread will take care of it. Otherwise, we need to restart // the reading. Read(); }
public void EndHeaders() { // Now that headers are over, all reading should be manual Autoread = false; // Prep the request DataAdapter = new Core.RequestDataAdapter(async delegate { await ReadAsync(); }); Request = new HTTP.Request(DataAdapter); Request.Headers = Headers; Request.Method = Method; Request.Protocol = Protocol; // Parse out the URI, which ends up being more annoying than it // should be. Stay tuned... var uri = new Uri(Path, UriKind.RelativeOrAbsolute); // Set the path if (uri.IsAbsoluteUri) Request.Path = uri.AbsolutePath; else Request.Path = Path.Split('?')[0]; // Set the host string temp; if (Headers.TryGetValue("host", out temp)) Request.Host = temp; else if (uri.IsAbsoluteUri) Request.Host = uri.Host; else Request.Host = null; // Set the query if (uri.IsAbsoluteUri) { Request.Query = Util.FormUrlEncoding.Parse(uri.Query.Length > 0 ? uri.Query.Substring(1) : ""); } else { var split = Path.Split(QuerySep, 2); Request.Query = Util.FormUrlEncoding.Parse(split.Length > 1 ? split[1] : ""); } // Build the response bool keepAlive = Version == HTTP.Version.HTTP1_1; if (Headers.TryGetValue("connection", out temp)) { temp = temp.ToLower(); if (temp == "close") keepAlive = false; else if (temp == "keep-alive") keepAlive = true; } Response = new HTTP.Response(Version, this, keepAlive, delegate(bool forceDisconnect) { // Now that we're done, we should kill the client if // either the request expects it, or the response // requires it. if (forceDisconnect || !keepAlive) Kill(); else Start(); }); // Since we've set up the request, it'll get scheduled at the END of the current // read call. This prevents issues with overlapping reads, because reads are // guaranteed to have finished before we run any response logic. }