From cfdedc9a5a442803e0a4f6f8a857175a4fb205fb Mon Sep 17 00:00:00 2001 From: michele Date: Fri, 30 Aug 2019 16:17:12 +0200 Subject: [PATCH 1/4] fixed empty catch blocks in tests --- .../com/arangodb/ArangoCollectionTest.java | 4729 ++++++++--------- src/test/java/com/arangodb/ArangoDBTest.java | 1 - .../java/com/arangodb/ArangoDatabaseTest.java | 2820 +++++----- .../arangodb/ArangoEdgeCollectionTest.java | 762 ++- .../java/com/arangodb/ArangoGraphTest.java | 14 +- .../java/com/arangodb/ArangoSearchTest.java | 810 ++- .../arangodb/ArangoVertexCollectionTest.java | 780 ++- .../java/com/arangodb/ArangoViewTest.java | 109 +- src/test/java/com/arangodb/BaseTest.java | 80 +- .../ConcurrentStreamTransactionsTest.java | 127 +- src/test/java/com/arangodb/DocumentTest.java | 167 +- .../com/arangodb/StreamTransactionTest.java | 1148 ++-- src/test/java/com/arangodb/UserAuthTest.java | 1693 +++--- .../com/arangodb/example/ExampleBase.java | 49 +- ...AqlQueryWithSpecialReturnTypesExample.java | 172 +- .../graph/AQLActorsAndMoviesExample.java | 1046 ++-- .../arangodb/example/graph/BaseGraphTest.java | 146 +- .../velocystream/CommunicationTest.java | 265 +- .../com/arangodb/serde/CustomSerdeTest.java | 3 +- 19 files changed, 7349 insertions(+), 7572 deletions(-) diff --git a/src/test/java/com/arangodb/ArangoCollectionTest.java b/src/test/java/com/arangodb/ArangoCollectionTest.java index dd1c11c6e..80ff8c7f5 100644 --- a/src/test/java/com/arangodb/ArangoCollectionTest.java +++ b/src/test/java/com/arangodb/ArangoCollectionTest.java @@ -54,2392 +54,2347 @@ @RunWith(Parameterized.class) public class ArangoCollectionTest extends BaseTest { - private static final String COLLECTION_NAME = "db_collection_test"; - private static final String EDGE_COLLECTION_NAME = "db_edge_collection_test"; - - public ArangoCollectionTest(final Builder builder) { - super(builder); - try { - db.createCollection(COLLECTION_NAME, null); - } catch (final ArangoDBException e) { - - } - } - - @After - public void teardown() { - try { - db.collection(COLLECTION_NAME).drop(); - } catch (final ArangoDBException e) { - } - ; - try { - db.collection(EDGE_COLLECTION_NAME).drop(); - } catch (final ArangoDBException e) { - } - ; - try { - db.collection(COLLECTION_NAME + "_1").drop(); - } catch (final ArangoDBException e) { - } - ; - } - - @Test - public void create() { - try { - final CollectionEntity result = db.collection(COLLECTION_NAME + "_1").create(); - assertThat(result, is(notNullValue())); - assertThat(result.getId(), is(notNullValue())); - db.collection(COLLECTION_NAME + "_1").drop(); - } catch (final ArangoDBException e) { - throw e; - } - } - - @Test - public void insertDocument() { - final DocumentCreateEntity doc = db.collection(COLLECTION_NAME) - .insertDocument(new BaseDocument(), null); - assertThat(doc, is(notNullValue())); - assertThat(doc.getId(), is(notNullValue())); - assertThat(doc.getKey(), is(notNullValue())); - assertThat(doc.getRev(), is(notNullValue())); - assertThat(doc.getNew(), is(nullValue())); - assertThat(doc.getId(), is(COLLECTION_NAME + "/" + doc.getKey())); - } - - @Test - public void insertDocumentUpdateRev() { - final BaseDocument doc = new BaseDocument(); - final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) - .insertDocument(doc, null); - assertThat(doc.getRevision(), is(createResult.getRev())); - } - - @Test - public void insertDocumentReturnNew() { - final DocumentCreateOptions options = new DocumentCreateOptions().returnNew(true); - final DocumentCreateEntity doc = db.collection(COLLECTION_NAME) - .insertDocument(new BaseDocument(), options); - assertThat(doc, is(notNullValue())); - assertThat(doc.getId(), is(notNullValue())); - assertThat(doc.getKey(), is(notNullValue())); - assertThat(doc.getRev(), is(notNullValue())); - assertThat(doc.getNew(), is(notNullValue())); - } - - @Test - public void insertDocumentOverwriteReturnOld() { - if (!requireVersion(3, 4)) { - return; - } - final BaseDocument doc = new BaseDocument(); - doc.addAttribute("value", "a"); - final DocumentCreateEntity meta = db.collection(COLLECTION_NAME).insertDocument(doc); - doc.addAttribute("value", "b"); - final DocumentCreateEntity repsert = db.collection(COLLECTION_NAME) - .insertDocument(doc, new DocumentCreateOptions().overwrite(true).returnOld(true).returnNew(true)); - assertThat(repsert, is(notNullValue())); - assertThat(repsert.getRev(), is(not(meta.getRev()))); - assertThat(repsert.getOld().getAttribute("value").toString(), is("a")); - assertThat(repsert.getNew().getAttribute("value").toString(), is("b")); - assertThat(db.collection(COLLECTION_NAME).count().getCount(), is(1L)); - } - - @Test - public void insertDocumentWaitForSync() { - final DocumentCreateOptions options = new DocumentCreateOptions().waitForSync(true); - final DocumentCreateEntity doc = db.collection(COLLECTION_NAME) - .insertDocument(new BaseDocument(), options); - assertThat(doc, is(notNullValue())); - assertThat(doc.getId(), is(notNullValue())); - assertThat(doc.getKey(), is(notNullValue())); - assertThat(doc.getRev(), is(notNullValue())); - assertThat(doc.getNew(), is(nullValue())); - } - - @Test - public void insertDocumentAsJson() { - final DocumentCreateEntity doc = db.collection(COLLECTION_NAME) - .insertDocument("{\"_key\":\"docRaw\",\"a\":\"test\"}", null); - assertThat(doc, is(notNullValue())); - assertThat(doc.getId(), is(notNullValue())); - assertThat(doc.getKey(), is(notNullValue())); - assertThat(doc.getRev(), is(notNullValue())); - } - - @Test - public void insertDocumentSilent() { - if (arangoDB.getRole() != ServerRole.SINGLE) { - return; - } - final DocumentCreateEntity meta = db.collection(COLLECTION_NAME) - .insertDocument(new BaseDocument(), new DocumentCreateOptions().silent(true)); - assertThat(meta, is(notNullValue())); - assertThat(meta.getId(), is(nullValue())); - assertThat(meta.getKey(), is(nullValue())); - assertThat(meta.getRev(), is(nullValue())); - } - - @Test - public void insertDocumentSilentDontTouchInstance() { - if (arangoDB.getRole() != ServerRole.SINGLE) { - return; - } - final BaseDocument doc = new BaseDocument(); - final String key = "testkey"; - doc.setKey(key); - final DocumentCreateEntity meta = db.collection(COLLECTION_NAME) - .insertDocument(doc, new DocumentCreateOptions().silent(true)); - assertThat(meta, is(notNullValue())); - assertThat(meta.getKey(), is(nullValue())); - assertThat(doc.getKey(), is(key)); - } - - @Test - public void insertDocumentsSilent() { - if (arangoDB.getRole() != ServerRole.SINGLE) { - return; - } - final MultiDocumentEntity> info = db.collection(COLLECTION_NAME) - .insertDocuments(Arrays.asList(new BaseDocument(), new BaseDocument()), - new DocumentCreateOptions().silent(true)); - assertThat(info, is(notNullValue())); - assertThat(info.getDocuments().isEmpty(), is(true)); - assertThat(info.getDocumentsAndErrors().isEmpty(), is(true)); - assertThat(info.getErrors().isEmpty(), is(true)); - } - - @Test - public void getDocument() { - final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) - .insertDocument(new BaseDocument(), null); - assertThat(createResult.getKey(), is(notNullValue())); - final BaseDocument readResult = db.collection(COLLECTION_NAME) - .getDocument(createResult.getKey(), BaseDocument.class, null); - assertThat(readResult.getKey(), is(createResult.getKey())); - assertThat(readResult.getId(), is(COLLECTION_NAME + "/" + createResult.getKey())); - } - - @Test - public void getDocumentIfMatch() { - final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) - .insertDocument(new BaseDocument(), null); - assertThat(createResult.getKey(), is(notNullValue())); - final DocumentReadOptions options = new DocumentReadOptions().ifMatch(createResult.getRev()); - final BaseDocument readResult = db.collection(COLLECTION_NAME) - .getDocument(createResult.getKey(), BaseDocument.class, options); - assertThat(readResult.getKey(), is(createResult.getKey())); - assertThat(readResult.getId(), is(COLLECTION_NAME + "/" + createResult.getKey())); - } - - @Test - public void getDocumentIfMatchFail() { - final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) - .insertDocument(new BaseDocument(), null); - assertThat(createResult.getKey(), is(notNullValue())); - final DocumentReadOptions options = new DocumentReadOptions().ifMatch("no"); - final BaseDocument document = db.collection(COLLECTION_NAME) - .getDocument(createResult.getKey(), BaseDocument.class, options); - assertThat(document, is(nullValue())); - } - - @Test - public void getDocumentIfNoneMatch() { - final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) - .insertDocument(new BaseDocument(), null); - assertThat(createResult.getKey(), is(notNullValue())); - final DocumentReadOptions options = new DocumentReadOptions().ifNoneMatch("no"); - final BaseDocument readResult = db.collection(COLLECTION_NAME) - .getDocument(createResult.getKey(), BaseDocument.class, options); - assertThat(readResult.getKey(), is(createResult.getKey())); - assertThat(readResult.getId(), is(COLLECTION_NAME + "/" + createResult.getKey())); - } - - @Test - public void getDocumentIfNoneMatchFail() { - final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) - .insertDocument(new BaseDocument(), null); - assertThat(createResult.getKey(), is(notNullValue())); - final DocumentReadOptions options = new DocumentReadOptions().ifNoneMatch(createResult.getRev()); - final BaseDocument document = db.collection(COLLECTION_NAME) - .getDocument(createResult.getKey(), BaseDocument.class, options); - assertThat(document, is(nullValue())); - } - - @Test - public void getDocumentAsJson() { - db.collection(COLLECTION_NAME).insertDocument("{\"_key\":\"docRaw\",\"a\":\"test\"}", null); - final String readResult = db.collection(COLLECTION_NAME).getDocument("docRaw", String.class, null); - assertThat(readResult.contains("\"_key\":\"docRaw\""), is(true)); - assertThat(readResult.contains("\"_id\":\"db_collection_test\\/docRaw\""), is(true)); - } - - @Test - public void getDocumentNotFound() { - final BaseDocument document = db.collection(COLLECTION_NAME).getDocument("no", BaseDocument.class); - assertThat(document, is(nullValue())); - } - - @Test - public void getDocumentNotFoundOptionsDefault() { - final BaseDocument document = db.collection(COLLECTION_NAME) - .getDocument("no", BaseDocument.class, new DocumentReadOptions()); - assertThat(document, is(nullValue())); - } - - @Test - public void getDocumentNotFoundOptionsNull() { - final BaseDocument document = db.collection(COLLECTION_NAME).getDocument("no", BaseDocument.class, null); - assertThat(document, is(nullValue())); - } - - @Test(expected = ArangoDBException.class) - public void getDocumentNotFoundThrowException() { - db.collection(COLLECTION_NAME) - .getDocument("no", BaseDocument.class, new DocumentReadOptions().catchException(false)); - } - - @Test(expected = ArangoDBException.class) - public void getDocumentWrongKey() { - db.collection(COLLECTION_NAME).getDocument("no/no", BaseDocument.class); - } - - public void getDocumentDirtyRead() { - final BaseDocument doc = new BaseDocument(); - db.collection(COLLECTION_NAME).insertDocument(doc); - final VPackSlice document = db.collection(COLLECTION_NAME) - .getDocument(doc.getKey(), VPackSlice.class, new DocumentReadOptions().allowDirtyRead(true)); - assertThat(document, is(notNullValue())); - } - - @Test - public void getDocuments() { - final Collection values = new ArrayList(); - values.add(new BaseDocument("1")); - values.add(new BaseDocument("2")); - values.add(new BaseDocument("3")); - db.collection(COLLECTION_NAME).insertDocuments(values); - final MultiDocumentEntity documents = db.collection(COLLECTION_NAME) - .getDocuments(Arrays.asList("1", "2", "3"), BaseDocument.class); - assertThat(documents, is(notNullValue())); - assertThat(documents.getDocuments().size(), is(3)); - for (final BaseDocument document : documents.getDocuments()) { - assertThat(document.getId(), - isOneOf(COLLECTION_NAME + "/" + "1", COLLECTION_NAME + "/" + "2", COLLECTION_NAME + "/" + "3")); - } - } - - @Test - public void getDocumentsDirtyRead() { - final Collection values = new ArrayList(); - values.add(new BaseDocument("1")); - values.add(new BaseDocument("2")); - values.add(new BaseDocument("3")); - db.collection(COLLECTION_NAME).insertDocuments(values); - final MultiDocumentEntity documents = db.collection(COLLECTION_NAME) - .getDocuments(Arrays.asList("1", "2", "3"), BaseDocument.class, - new DocumentReadOptions().allowDirtyRead(true)); - assertThat(documents, is(notNullValue())); - assertThat(documents.getDocuments().size(), is(3)); - for (final BaseDocument document : documents.getDocuments()) { - assertThat(document.getId(), - isOneOf(COLLECTION_NAME + "/" + "1", COLLECTION_NAME + "/" + "2", COLLECTION_NAME + "/" + "3")); - } - } - - @Test - public void getDocumentsNotFound() { - final MultiDocumentEntity readResult = db.collection(COLLECTION_NAME) - .getDocuments(Collections.singleton("no"), BaseDocument.class); - assertThat(readResult, is(notNullValue())); - assertThat(readResult.getDocuments().size(), is(0)); - assertThat(readResult.getErrors().size(), is(1)); - } - - @Test - public void getDocumentsWrongKey() { - final MultiDocumentEntity readResult = db.collection(COLLECTION_NAME) - .getDocuments(Collections.singleton("no/no"), BaseDocument.class); - assertThat(readResult, is(notNullValue())); - assertThat(readResult.getDocuments().size(), is(0)); - assertThat(readResult.getErrors().size(), is(1)); - } - - @Test - public void updateDocument() { - final BaseDocument doc = new BaseDocument(); - doc.addAttribute("a", "test"); - doc.addAttribute("c", "test"); - final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) - .insertDocument(doc, null); - doc.updateAttribute("a", "test1"); - doc.addAttribute("b", "test"); - doc.updateAttribute("c", null); - final DocumentUpdateEntity updateResult = db.collection(COLLECTION_NAME) - .updateDocument(createResult.getKey(), doc, null); - assertThat(updateResult, is(notNullValue())); - assertThat(updateResult.getId(), is(createResult.getId())); - assertThat(updateResult.getNew(), is(nullValue())); - assertThat(updateResult.getOld(), is(nullValue())); - assertThat(updateResult.getRev(), is(not(updateResult.getOldRev()))); - assertThat(updateResult.getOldRev(), is(createResult.getRev())); - - final BaseDocument readResult = db.collection(COLLECTION_NAME) - .getDocument(createResult.getKey(), BaseDocument.class, null); - assertThat(readResult.getKey(), is(createResult.getKey())); - assertThat(readResult.getAttribute("a"), is(notNullValue())); - assertThat(String.valueOf(readResult.getAttribute("a")), is("test1")); - assertThat(readResult.getAttribute("b"), is(notNullValue())); - assertThat(String.valueOf(readResult.getAttribute("b")), is("test")); - assertThat(readResult.getRevision(), is(updateResult.getRev())); - assertThat(readResult.getProperties().keySet(), hasItem("c")); - } - - @Test - public void updateDocumentUpdateRev() { - final BaseDocument doc = new BaseDocument(); - final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) - .insertDocument(doc, null); - assertThat(doc.getRevision(), is(createResult.getRev())); - final DocumentUpdateEntity updateResult = db.collection(COLLECTION_NAME) - .updateDocument(createResult.getKey(), doc, null); - assertThat(doc.getRevision(), is(updateResult.getRev())); - } - - @Test - public void updateDocumentIfMatch() { - final BaseDocument doc = new BaseDocument(); - doc.addAttribute("a", "test"); - doc.addAttribute("c", "test"); - final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) - .insertDocument(doc, null); - doc.updateAttribute("a", "test1"); - doc.addAttribute("b", "test"); - doc.updateAttribute("c", null); - final DocumentUpdateOptions options = new DocumentUpdateOptions().ifMatch(createResult.getRev()); - final DocumentUpdateEntity updateResult = db.collection(COLLECTION_NAME) - .updateDocument(createResult.getKey(), doc, options); - assertThat(updateResult, is(notNullValue())); - assertThat(updateResult.getId(), is(createResult.getId())); - assertThat(updateResult.getRev(), is(not(updateResult.getOldRev()))); - assertThat(updateResult.getOldRev(), is(createResult.getRev())); - - final BaseDocument readResult = db.collection(COLLECTION_NAME) - .getDocument(createResult.getKey(), BaseDocument.class, null); - assertThat(readResult.getKey(), is(createResult.getKey())); - assertThat(readResult.getAttribute("a"), is(notNullValue())); - assertThat(String.valueOf(readResult.getAttribute("a")), is("test1")); - assertThat(readResult.getAttribute("b"), is(notNullValue())); - assertThat(String.valueOf(readResult.getAttribute("b")), is("test")); - assertThat(readResult.getRevision(), is(updateResult.getRev())); - assertThat(readResult.getProperties().keySet(), hasItem("c")); - } - - @Test - public void updateDocumentIfMatchFail() { - final BaseDocument doc = new BaseDocument(); - doc.addAttribute("a", "test"); - doc.addAttribute("c", "test"); - final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) - .insertDocument(doc, null); - doc.updateAttribute("a", "test1"); - doc.addAttribute("b", "test"); - doc.updateAttribute("c", null); - try { - final DocumentUpdateOptions options = new DocumentUpdateOptions().ifMatch("no"); - db.collection(COLLECTION_NAME).updateDocument(createResult.getKey(), doc, options); - fail(); - } catch (final ArangoDBException e) { - } - } - - @Test - public void updateDocumentReturnNew() { - final BaseDocument doc = new BaseDocument(); - doc.addAttribute("a", "test"); - final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) - .insertDocument(doc, null); - doc.updateAttribute("a", "test1"); - doc.addAttribute("b", "test"); - final DocumentUpdateOptions options = new DocumentUpdateOptions().returnNew(true); - final DocumentUpdateEntity updateResult = db.collection(COLLECTION_NAME) - .updateDocument(createResult.getKey(), doc, options); - assertThat(updateResult, is(notNullValue())); - assertThat(updateResult.getId(), is(createResult.getId())); - assertThat(updateResult.getOldRev(), is(createResult.getRev())); - assertThat(updateResult.getNew(), is(notNullValue())); - assertThat(updateResult.getNew().getKey(), is(createResult.getKey())); - assertThat(updateResult.getNew().getRevision(), is(not(createResult.getRev()))); - assertThat(updateResult.getNew().getAttribute("a"), is(notNullValue())); - assertThat(String.valueOf(updateResult.getNew().getAttribute("a")), is("test1")); - assertThat(updateResult.getNew().getAttribute("b"), is(notNullValue())); - assertThat(String.valueOf(updateResult.getNew().getAttribute("b")), is("test")); - } - - @Test - public void updateDocumentReturnOld() { - final BaseDocument doc = new BaseDocument(); - doc.addAttribute("a", "test"); - final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) - .insertDocument(doc, null); - doc.updateAttribute("a", "test1"); - doc.addAttribute("b", "test"); - final DocumentUpdateOptions options = new DocumentUpdateOptions().returnOld(true); - final DocumentUpdateEntity updateResult = db.collection(COLLECTION_NAME) - .updateDocument(createResult.getKey(), doc, options); - assertThat(updateResult, is(notNullValue())); - assertThat(updateResult.getId(), is(createResult.getId())); - assertThat(updateResult.getOldRev(), is(createResult.getRev())); - assertThat(updateResult.getOld(), is(notNullValue())); - assertThat(updateResult.getOld().getKey(), is(createResult.getKey())); - assertThat(updateResult.getOld().getRevision(), is(createResult.getRev())); - assertThat(updateResult.getOld().getAttribute("a"), is(notNullValue())); - assertThat(String.valueOf(updateResult.getOld().getAttribute("a")), is("test")); - assertThat(updateResult.getOld().getProperties().keySet(), not(hasItem("b"))); - } - - @Test - public void updateDocumentKeepNullTrue() { - final BaseDocument doc = new BaseDocument(); - doc.addAttribute("a", "test"); - final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) - .insertDocument(doc, null); - doc.updateAttribute("a", null); - final DocumentUpdateOptions options = new DocumentUpdateOptions().keepNull(true); - final DocumentUpdateEntity updateResult = db.collection(COLLECTION_NAME) - .updateDocument(createResult.getKey(), doc, options); - assertThat(updateResult, is(notNullValue())); - assertThat(updateResult.getId(), is(createResult.getId())); - assertThat(updateResult.getRev(), is(not(updateResult.getOldRev()))); - assertThat(updateResult.getOldRev(), is(createResult.getRev())); - - final BaseDocument readResult = db.collection(COLLECTION_NAME) - .getDocument(createResult.getKey(), BaseDocument.class, null); - assertThat(readResult.getKey(), is(createResult.getKey())); - assertThat(readResult.getProperties().keySet(), hasItem("a")); - } - - @Test - public void updateDocumentKeepNullFalse() { - final BaseDocument doc = new BaseDocument(); - doc.addAttribute("a", "test"); - final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) - .insertDocument(doc, null); - doc.updateAttribute("a", null); - final DocumentUpdateOptions options = new DocumentUpdateOptions().keepNull(false); - final DocumentUpdateEntity updateResult = db.collection(COLLECTION_NAME) - .updateDocument(createResult.getKey(), doc, options); - assertThat(updateResult, is(notNullValue())); - assertThat(updateResult.getId(), is(createResult.getId())); - assertThat(updateResult.getRev(), is(not(updateResult.getOldRev()))); - assertThat(updateResult.getOldRev(), is(createResult.getRev())); - - final BaseDocument readResult = db.collection(COLLECTION_NAME) - .getDocument(createResult.getKey(), BaseDocument.class, null); - assertThat(readResult.getKey(), is(createResult.getKey())); - assertThat(readResult.getId(), is(createResult.getId())); - assertThat(readResult.getRevision(), is(notNullValue())); - assertThat(readResult.getProperties().keySet(), not(hasItem("a"))); - } - - private static class TestUpdateEntity { - @SuppressWarnings("unused") - private String a, b; - } - - @Test - public void updateDocumentSerializeNullTrue() { - final TestUpdateEntity doc = new TestUpdateEntity(); - doc.a = "foo"; - doc.b = "foo"; - final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME).insertDocument(doc); - final TestUpdateEntity patchDoc = new TestUpdateEntity(); - patchDoc.a = "bar"; - final DocumentUpdateEntity updateResult = db.collection(COLLECTION_NAME) - .updateDocument(createResult.getKey(), patchDoc); - assertThat(updateResult, is(notNullValue())); - assertThat(updateResult.getKey(), is(createResult.getKey())); - - final BaseDocument readResult = db.collection(COLLECTION_NAME) - .getDocument(createResult.getKey(), BaseDocument.class); - assertThat(readResult.getKey(), is(createResult.getKey())); - assertThat(readResult.getProperties().keySet(), hasItem("a")); - assertThat(readResult.getAttribute("a").toString(), is("bar")); - } - - @Test - public void updateDocumentSerializeNullFalse() { - final TestUpdateEntity doc = new TestUpdateEntity(); - doc.a = "foo"; - doc.b = "foo"; - final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME).insertDocument(doc); - final TestUpdateEntity patchDoc = new TestUpdateEntity(); - patchDoc.a = "bar"; - final DocumentUpdateEntity updateResult = db.collection(COLLECTION_NAME) - .updateDocument(createResult.getKey(), patchDoc, new DocumentUpdateOptions().serializeNull(false)); - assertThat(updateResult, is(notNullValue())); - assertThat(updateResult.getKey(), is(createResult.getKey())); - - final BaseDocument readResult = db.collection(COLLECTION_NAME) - .getDocument(createResult.getKey(), BaseDocument.class); - assertThat(readResult.getKey(), is(createResult.getKey())); - assertThat(readResult.getProperties().keySet(), hasItems("a", "b")); - assertThat(readResult.getAttribute("a").toString(), is("bar")); - assertThat(readResult.getAttribute("b").toString(), is("foo")); - } - - @SuppressWarnings("unchecked") - @Test - public void updateDocumentMergeObjectsTrue() { - final BaseDocument doc = new BaseDocument(); - final Map a = new HashMap(); - a.put("a", "test"); - doc.addAttribute("a", a); - final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) - .insertDocument(doc, null); - a.clear(); - a.put("b", "test"); - doc.updateAttribute("a", a); - final DocumentUpdateOptions options = new DocumentUpdateOptions().mergeObjects(true); - final DocumentUpdateEntity updateResult = db.collection(COLLECTION_NAME) - .updateDocument(createResult.getKey(), doc, options); - assertThat(updateResult, is(notNullValue())); - assertThat(updateResult.getId(), is(createResult.getId())); - assertThat(updateResult.getRev(), is(not(updateResult.getOldRev()))); - assertThat(updateResult.getOldRev(), is(createResult.getRev())); - - final BaseDocument readResult = db.collection(COLLECTION_NAME) - .getDocument(createResult.getKey(), BaseDocument.class, null); - assertThat(readResult.getKey(), is(createResult.getKey())); - final Object aResult = readResult.getAttribute("a"); - assertThat(aResult, instanceOf(Map.class)); - final Map aMap = (Map) aResult; - assertThat(aMap.keySet(), hasItem("a")); - assertThat(aMap.keySet(), hasItem("b")); - } - - @SuppressWarnings("unchecked") - @Test - public void updateDocumentMergeObjectsFalse() { - final BaseDocument doc = new BaseDocument(); - final Map a = new HashMap(); - a.put("a", "test"); - doc.addAttribute("a", a); - final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) - .insertDocument(doc, null); - a.clear(); - a.put("b", "test"); - doc.updateAttribute("a", a); - final DocumentUpdateOptions options = new DocumentUpdateOptions().mergeObjects(false); - final DocumentUpdateEntity updateResult = db.collection(COLLECTION_NAME) - .updateDocument(createResult.getKey(), doc, options); - assertThat(updateResult, is(notNullValue())); - assertThat(updateResult.getId(), is(createResult.getId())); - assertThat(updateResult.getRev(), is(not(updateResult.getOldRev()))); - assertThat(updateResult.getOldRev(), is(createResult.getRev())); - - final BaseDocument readResult = db.collection(COLLECTION_NAME) - .getDocument(createResult.getKey(), BaseDocument.class, null); - assertThat(readResult.getKey(), is(createResult.getKey())); - final Object aResult = readResult.getAttribute("a"); - assertThat(aResult, instanceOf(Map.class)); - final Map aMap = (Map) aResult; - assertThat(aMap.keySet(), not(hasItem("a"))); - assertThat(aMap.keySet(), hasItem("b")); - } - - @Test - public void updateDocumentIgnoreRevsFalse() { - final BaseDocument doc = new BaseDocument(); - doc.addAttribute("a", "test"); - final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) - .insertDocument(doc, null); - doc.updateAttribute("a", "test1"); - doc.setRevision("no"); - try { - final DocumentUpdateOptions options = new DocumentUpdateOptions().ignoreRevs(false); - db.collection(COLLECTION_NAME).updateDocument(createResult.getKey(), doc, options); - fail(); - } catch (final ArangoDBException e) { - } - } - - @Test - public void updateDocumentSilent() { - if (arangoDB.getRole() != ServerRole.SINGLE) { - return; - } - final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) - .insertDocument(new BaseDocument()); - final DocumentUpdateEntity meta = db.collection(COLLECTION_NAME) - .updateDocument(createResult.getKey(), new BaseDocument(), new DocumentUpdateOptions().silent(true)); - assertThat(meta, is(notNullValue())); - assertThat(meta.getId(), is(nullValue())); - assertThat(meta.getKey(), is(nullValue())); - assertThat(meta.getRev(), is(nullValue())); - } - - @Test - public void updateDocumentsSilent() { - if (arangoDB.getRole() != ServerRole.SINGLE) { - return; - } - final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) - .insertDocument(new BaseDocument()); - final MultiDocumentEntity> info = db.collection(COLLECTION_NAME) - .updateDocuments(Arrays.asList(new BaseDocument(createResult.getKey())), - new DocumentUpdateOptions().silent(true)); - assertThat(info, is(notNullValue())); - assertThat(info.getDocuments().isEmpty(), is(true)); - assertThat(info.getDocumentsAndErrors().isEmpty(), is(true)); - assertThat(info.getErrors().isEmpty(), is(true)); - } - - @Test - public void updateNonExistingDocument() { - final BaseDocument doc = new BaseDocument("test-" + UUID.randomUUID().toString()); - doc.addAttribute("a", "test"); - doc.addAttribute("c", "test"); - - try { - db.collection(COLLECTION_NAME).updateDocument(doc.getKey(), doc, null); - } catch (ArangoDBException e) { - assertThat(e.getResponseCode(), is(404)); - assertThat(e.getErrorNum(), is(1202)); - } - } - - @Test - public void updateDocumentPreconditionFailed() { - final BaseDocument doc = new BaseDocument("test-" + UUID.randomUUID().toString()); - doc.addAttribute("foo", "a"); - final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) - .insertDocument(doc, null); - - doc.updateAttribute("foo", "b"); - db.collection(COLLECTION_NAME).updateDocument(doc.getKey(), doc, null); - - doc.updateAttribute("foo", "c"); - try { - db.collection(COLLECTION_NAME).updateDocument(doc.getKey(), doc, new DocumentUpdateOptions().ifMatch(createResult.getRev())); - } catch (ArangoDBException e) { - assertThat(e.getResponseCode(), is(412)); - assertThat(e.getErrorNum(), is(1200)); - } - BaseDocument readDocument = db.collection(COLLECTION_NAME).getDocument(doc.getKey(), BaseDocument.class); - assertThat(readDocument.getAttribute("foo"), is("b")); - } - - @Test - public void replaceDocument() { - final BaseDocument doc = new BaseDocument(); - doc.addAttribute("a", "test"); - final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) - .insertDocument(doc, null); - doc.getProperties().clear(); - doc.addAttribute("b", "test"); - final DocumentUpdateEntity replaceResult = db.collection(COLLECTION_NAME) - .replaceDocument(createResult.getKey(), doc, null); - assertThat(replaceResult, is(notNullValue())); - assertThat(replaceResult.getId(), is(createResult.getId())); - assertThat(replaceResult.getNew(), is(nullValue())); - assertThat(replaceResult.getOld(), is(nullValue())); - assertThat(replaceResult.getRev(), is(not(replaceResult.getOldRev()))); - assertThat(replaceResult.getOldRev(), is(createResult.getRev())); - - final BaseDocument readResult = db.collection(COLLECTION_NAME) - .getDocument(createResult.getKey(), BaseDocument.class, null); - assertThat(readResult.getKey(), is(createResult.getKey())); - assertThat(readResult.getRevision(), is(replaceResult.getRev())); - assertThat(readResult.getProperties().keySet(), not(hasItem("a"))); - assertThat(readResult.getAttribute("b"), is(notNullValue())); - assertThat(String.valueOf(readResult.getAttribute("b")), is("test")); - } - - @Test - public void replaceDocumentUpdateRev() { - final BaseDocument doc = new BaseDocument(); - final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) - .insertDocument(doc, null); - assertThat(doc.getRevision(), is(createResult.getRev())); - final DocumentUpdateEntity replaceResult = db.collection(COLLECTION_NAME) - .replaceDocument(createResult.getKey(), doc, null); - assertThat(doc.getRevision(), is(replaceResult.getRev())); - } - - @Test - public void replaceDocumentIfMatch() { - final BaseDocument doc = new BaseDocument(); - doc.addAttribute("a", "test"); - final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) - .insertDocument(doc, null); - doc.getProperties().clear(); - doc.addAttribute("b", "test"); - final DocumentReplaceOptions options = new DocumentReplaceOptions().ifMatch(createResult.getRev()); - final DocumentUpdateEntity replaceResult = db.collection(COLLECTION_NAME) - .replaceDocument(createResult.getKey(), doc, options); - assertThat(replaceResult, is(notNullValue())); - assertThat(replaceResult.getId(), is(createResult.getId())); - assertThat(replaceResult.getRev(), is(not(replaceResult.getOldRev()))); - assertThat(replaceResult.getOldRev(), is(createResult.getRev())); - - final BaseDocument readResult = db.collection(COLLECTION_NAME) - .getDocument(createResult.getKey(), BaseDocument.class, null); - assertThat(readResult.getKey(), is(createResult.getKey())); - assertThat(readResult.getRevision(), is(replaceResult.getRev())); - assertThat(readResult.getProperties().keySet(), not(hasItem("a"))); - assertThat(readResult.getAttribute("b"), is(notNullValue())); - assertThat(String.valueOf(readResult.getAttribute("b")), is("test")); - } - - @Test - public void replaceDocumentIfMatchFail() { - final BaseDocument doc = new BaseDocument(); - doc.addAttribute("a", "test"); - final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) - .insertDocument(doc, null); - doc.getProperties().clear(); - doc.addAttribute("b", "test"); - try { - final DocumentReplaceOptions options = new DocumentReplaceOptions().ifMatch("no"); - db.collection(COLLECTION_NAME).replaceDocument(createResult.getKey(), doc, options); - fail(); - } catch (final ArangoDBException e) { - } - } - - @Test - public void replaceDocumentIgnoreRevsFalse() { - final BaseDocument doc = new BaseDocument(); - doc.addAttribute("a", "test"); - final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) - .insertDocument(doc, null); - doc.getProperties().clear(); - doc.addAttribute("b", "test"); - doc.setRevision("no"); - try { - final DocumentReplaceOptions options = new DocumentReplaceOptions().ignoreRevs(false); - db.collection(COLLECTION_NAME).replaceDocument(createResult.getKey(), doc, options); - fail(); - } catch (final ArangoDBException e) { - } - } - - @Test - public void replaceDocumentReturnNew() { - final BaseDocument doc = new BaseDocument(); - doc.addAttribute("a", "test"); - final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) - .insertDocument(doc, null); - doc.getProperties().clear(); - doc.addAttribute("b", "test"); - final DocumentReplaceOptions options = new DocumentReplaceOptions().returnNew(true); - final DocumentUpdateEntity replaceResult = db.collection(COLLECTION_NAME) - .replaceDocument(createResult.getKey(), doc, options); - assertThat(replaceResult, is(notNullValue())); - assertThat(replaceResult.getId(), is(createResult.getId())); - assertThat(replaceResult.getOldRev(), is(createResult.getRev())); - assertThat(replaceResult.getNew(), is(notNullValue())); - assertThat(replaceResult.getNew().getKey(), is(createResult.getKey())); - assertThat(replaceResult.getNew().getRevision(), is(not(createResult.getRev()))); - assertThat(replaceResult.getNew().getProperties().keySet(), not(hasItem("a"))); - assertThat(replaceResult.getNew().getAttribute("b"), is(notNullValue())); - assertThat(String.valueOf(replaceResult.getNew().getAttribute("b")), is("test")); - } - - @Test - public void replaceDocumentReturnOld() { - final BaseDocument doc = new BaseDocument(); - doc.addAttribute("a", "test"); - final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) - .insertDocument(doc, null); - doc.getProperties().clear(); - doc.addAttribute("b", "test"); - final DocumentReplaceOptions options = new DocumentReplaceOptions().returnOld(true); - final DocumentUpdateEntity replaceResult = db.collection(COLLECTION_NAME) - .replaceDocument(createResult.getKey(), doc, options); - assertThat(replaceResult, is(notNullValue())); - assertThat(replaceResult.getId(), is(createResult.getId())); - assertThat(replaceResult.getOldRev(), is(createResult.getRev())); - assertThat(replaceResult.getOld(), is(notNullValue())); - assertThat(replaceResult.getOld().getKey(), is(createResult.getKey())); - assertThat(replaceResult.getOld().getRevision(), is(createResult.getRev())); - assertThat(replaceResult.getOld().getAttribute("a"), is(notNullValue())); - assertThat(String.valueOf(replaceResult.getOld().getAttribute("a")), is("test")); - assertThat(replaceResult.getOld().getProperties().keySet(), not(hasItem("b"))); - } - - @Test - public void replaceDocumentSilent() { - if (arangoDB.getRole() != ServerRole.SINGLE) { - return; - } - final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) - .insertDocument(new BaseDocument()); - final DocumentUpdateEntity meta = db.collection(COLLECTION_NAME) - .replaceDocument(createResult.getKey(), new BaseDocument(), new DocumentReplaceOptions().silent(true)); - assertThat(meta, is(notNullValue())); - assertThat(meta.getId(), is(nullValue())); - assertThat(meta.getKey(), is(nullValue())); - assertThat(meta.getRev(), is(nullValue())); - } - - @Test - public void replaceDocumentSilentDontTouchInstance() { - if (arangoDB.getRole() != ServerRole.SINGLE) { - return; - } - final BaseDocument doc = new BaseDocument(); - final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME).insertDocument(doc); - final String revision = doc.getRevision(); - assertThat(revision, is(notNullValue())); - final DocumentUpdateEntity meta = db.collection(COLLECTION_NAME) - .replaceDocument(createResult.getKey(), doc, new DocumentReplaceOptions().silent(true)); - assertThat(meta.getRev(), is(nullValue())); - assertThat(doc.getRevision(), is(revision)); - } - - @Test - public void replaceDocumentsSilent() { - if (arangoDB.getRole() != ServerRole.SINGLE) { - return; - } - final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) - .insertDocument(new BaseDocument()); - final MultiDocumentEntity> info = db.collection(COLLECTION_NAME) - .replaceDocuments(Arrays.asList(new BaseDocument(createResult.getKey())), - new DocumentReplaceOptions().silent(true)); - assertThat(info, is(notNullValue())); - assertThat(info.getDocuments().isEmpty(), is(true)); - assertThat(info.getDocumentsAndErrors().isEmpty(), is(true)); - assertThat(info.getErrors().isEmpty(), is(true)); - } - - @Test - public void deleteDocument() { - final BaseDocument doc = new BaseDocument(); - final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) - .insertDocument(doc, null); - db.collection(COLLECTION_NAME).deleteDocument(createResult.getKey(), null, null); - final BaseDocument document = db.collection(COLLECTION_NAME) - .getDocument(createResult.getKey(), BaseDocument.class, null); - assertThat(document, is(nullValue())); - } - - @Test - public void deleteDocumentReturnOld() { - final BaseDocument doc = new BaseDocument(); - doc.addAttribute("a", "test"); - final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) - .insertDocument(doc, null); - final DocumentDeleteOptions options = new DocumentDeleteOptions().returnOld(true); - final DocumentDeleteEntity deleteResult = db.collection(COLLECTION_NAME) - .deleteDocument(createResult.getKey(), BaseDocument.class, options); - assertThat(deleteResult.getOld(), is(notNullValue())); - assertThat(deleteResult.getOld(), instanceOf(BaseDocument.class)); - assertThat(deleteResult.getOld().getAttribute("a"), is(notNullValue())); - assertThat(String.valueOf(deleteResult.getOld().getAttribute("a")), is("test")); - } - - @Test - public void deleteDocumentIfMatch() { - final BaseDocument doc = new BaseDocument(); - final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) - .insertDocument(doc, null); - final DocumentDeleteOptions options = new DocumentDeleteOptions().ifMatch(createResult.getRev()); - db.collection(COLLECTION_NAME).deleteDocument(createResult.getKey(), null, options); - final BaseDocument document = db.collection(COLLECTION_NAME) - .getDocument(createResult.getKey(), BaseDocument.class, null); - assertThat(document, is(nullValue())); - } - - @Test - public void deleteDocumentIfMatchFail() { - final BaseDocument doc = new BaseDocument(); - final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) - .insertDocument(doc, null); - final DocumentDeleteOptions options = new DocumentDeleteOptions().ifMatch("no"); - try { - db.collection(COLLECTION_NAME).deleteDocument(createResult.getKey(), null, options); - fail(); - } catch (final ArangoDBException e) { - } - } - - @Test - public void deleteDocumentSilent() { - if (arangoDB.getRole() != ServerRole.SINGLE) { - return; - } - final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) - .insertDocument(new BaseDocument()); - final DocumentDeleteEntity meta = db.collection(COLLECTION_NAME) - .deleteDocument(createResult.getKey(), BaseDocument.class, new DocumentDeleteOptions().silent(true)); - assertThat(meta, is(notNullValue())); - assertThat(meta.getId(), is(nullValue())); - assertThat(meta.getKey(), is(nullValue())); - assertThat(meta.getRev(), is(nullValue())); - } - - @Test - public void deleteDocumentsSilent() { - if (arangoDB.getRole() != ServerRole.SINGLE) { - return; - } - final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) - .insertDocument(new BaseDocument()); - final MultiDocumentEntity> info = db.collection(COLLECTION_NAME) - .deleteDocuments(Arrays.asList(createResult.getKey()), BaseDocument.class, - new DocumentDeleteOptions().silent(true)); - assertThat(info, is(notNullValue())); - assertThat(info.getDocuments().isEmpty(), is(true)); - assertThat(info.getDocumentsAndErrors().isEmpty(), is(true)); - assertThat(info.getErrors().isEmpty(), is(true)); - } - - @Test - public void getIndex() { - final Collection fields = new ArrayList(); - fields.add("a"); - final IndexEntity createResult = db.collection(COLLECTION_NAME).ensureHashIndex(fields, null); - final IndexEntity readResult = db.collection(COLLECTION_NAME).getIndex(createResult.getId()); - assertThat(readResult.getId(), is(createResult.getId())); - assertThat(readResult.getType(), is(createResult.getType())); - } - - @Test - public void getIndexByKey() { - final Collection fields = new ArrayList(); - fields.add("a"); - final IndexEntity createResult = db.collection(COLLECTION_NAME).ensureHashIndex(fields, null); - final IndexEntity readResult = db.collection(COLLECTION_NAME).getIndex(createResult.getId().split("/")[1]); - assertThat(readResult.getId(), is(createResult.getId())); - assertThat(readResult.getType(), is(createResult.getType())); - } - - @Test - public void deleteIndex() { - final Collection fields = new ArrayList(); - fields.add("a"); - final IndexEntity createResult = db.collection(COLLECTION_NAME).ensureHashIndex(fields, null); - final String id = db.collection(COLLECTION_NAME).deleteIndex(createResult.getId()); - assertThat(id, is(createResult.getId())); - try { - db.getIndex(id); - fail(); - } catch (final ArangoDBException e) { - } - } - - @Test - public void deleteIndexByKey() { - final Collection fields = new ArrayList(); - fields.add("a"); - final IndexEntity createResult = db.collection(COLLECTION_NAME).ensureHashIndex(fields, null); - final String id = db.collection(COLLECTION_NAME).deleteIndex(createResult.getId().split("/")[1]); - assertThat(id, is(createResult.getId())); - try { - db.getIndex(id); - fail(); - } catch (final ArangoDBException e) { - } - } - - @Test - public void createHashIndex() { - final Collection fields = new ArrayList(); - fields.add("a"); - fields.add("b"); - final IndexEntity indexResult = db.collection(COLLECTION_NAME).ensureHashIndex(fields, null); - assertThat(indexResult, is(notNullValue())); - assertThat(indexResult.getConstraint(), is(nullValue())); - assertThat(indexResult.getFields(), hasItem("a")); - assertThat(indexResult.getFields(), hasItem("b")); - assertThat(indexResult.getId(), startsWith(COLLECTION_NAME)); - assertThat(indexResult.getIsNewlyCreated(), is(true)); - assertThat(indexResult.getMinLength(), is(nullValue())); - if (arangoDB.getRole() == ServerRole.SINGLE) { - assertThat(indexResult.getSelectivityEstimate(), is(1.)); - } - assertThat(indexResult.getSparse(), is(false)); - assertThat(indexResult.getType(), is(IndexType.hash)); - assertThat(indexResult.getUnique(), is(false)); - } - - @Test - public void createHashIndexWithOptions() { - if (!requireVersion(3, 5)) { - return; - } - - final HashIndexOptions options = new HashIndexOptions(); - options.name("myHashIndex"); - - final Collection fields = new ArrayList(); - fields.add("a"); - fields.add("b"); - final IndexEntity indexResult = db.collection(COLLECTION_NAME).ensureHashIndex(fields, options); - assertThat(indexResult, is(notNullValue())); - assertThat(indexResult.getConstraint(), is(nullValue())); - assertThat(indexResult.getFields(), hasItem("a")); - assertThat(indexResult.getFields(), hasItem("b")); - assertThat(indexResult.getId(), startsWith(COLLECTION_NAME)); - assertThat(indexResult.getIsNewlyCreated(), is(true)); - assertThat(indexResult.getMinLength(), is(nullValue())); - if (arangoDB.getRole() == ServerRole.SINGLE) { - assertThat(indexResult.getSelectivityEstimate(), is(1.)); - } - assertThat(indexResult.getSparse(), is(false)); - assertThat(indexResult.getType(), is(IndexType.hash)); - assertThat(indexResult.getUnique(), is(false)); - assertThat(indexResult.getName(), is("myHashIndex")); - } - - @Test - public void createGeoIndex() { - final Collection fields = new ArrayList(); - fields.add("a"); - final IndexEntity indexResult = db.collection(COLLECTION_NAME).ensureGeoIndex(fields, null); - assertThat(indexResult, is(notNullValue())); - assertThat(indexResult.getFields(), hasItem("a")); - assertThat(indexResult.getId(), startsWith(COLLECTION_NAME)); - assertThat(indexResult.getIsNewlyCreated(), is(true)); - assertThat(indexResult.getMinLength(), is(nullValue())); - assertThat(indexResult.getSparse(), is(true)); - assertThat(indexResult.getUnique(), is(false)); - if (requireVersion(3, 4)) { - assertThat(indexResult.getType(), is(IndexType.geo)); - } else { - assertThat(indexResult.getType(), is(IndexType.geo1)); - } - } - - @Test - public void createGeoIndexWithOptions() { - if (!requireVersion(3, 5)) { - return; - } - - final GeoIndexOptions options = new GeoIndexOptions(); - options.name("myGeoIndex1"); - - final Collection fields = new ArrayList(); - fields.add("a"); - final IndexEntity indexResult = db.collection(COLLECTION_NAME).ensureGeoIndex(fields, options); - assertThat(indexResult, is(notNullValue())); - assertThat(indexResult.getFields(), hasItem("a")); - assertThat(indexResult.getId(), startsWith(COLLECTION_NAME)); - assertThat(indexResult.getIsNewlyCreated(), is(true)); - assertThat(indexResult.getMinLength(), is(nullValue())); - assertThat(indexResult.getSparse(), is(true)); - assertThat(indexResult.getUnique(), is(false)); - if (requireVersion(3, 4)) { - assertThat(indexResult.getType(), is(IndexType.geo)); - } else { - assertThat(indexResult.getType(), is(IndexType.geo1)); - } - assertThat(indexResult.getName(), is("myGeoIndex1")); - } - - @Test - public void createGeo2Index() { - final Collection fields = new ArrayList(); - fields.add("a"); - fields.add("b"); - final IndexEntity indexResult = db.collection(COLLECTION_NAME).ensureGeoIndex(fields, null); - assertThat(indexResult, is(notNullValue())); - assertThat(indexResult.getFields(), hasItem("a")); - assertThat(indexResult.getFields(), hasItem("b")); - assertThat(indexResult.getId(), startsWith(COLLECTION_NAME)); - assertThat(indexResult.getIsNewlyCreated(), is(true)); - assertThat(indexResult.getMinLength(), is(nullValue())); - assertThat(indexResult.getSparse(), is(true)); - assertThat(indexResult.getUnique(), is(false)); - if (requireVersion(3, 4)) { - assertThat(indexResult.getType(), is(IndexType.geo)); - } else { - assertThat(indexResult.getType(), is(IndexType.geo2)); - } - } - - @Test - public void createGeo2IndexWithOptions() { - if (!requireVersion(3, 5)) { - return; - } - - final GeoIndexOptions options = new GeoIndexOptions(); - options.name("myGeoIndex2"); - - final Collection fields = new ArrayList(); - fields.add("a"); - fields.add("b"); - final IndexEntity indexResult = db.collection(COLLECTION_NAME).ensureGeoIndex(fields, options); - assertThat(indexResult, is(notNullValue())); - assertThat(indexResult.getFields(), hasItem("a")); - assertThat(indexResult.getFields(), hasItem("b")); - assertThat(indexResult.getId(), startsWith(COLLECTION_NAME)); - assertThat(indexResult.getIsNewlyCreated(), is(true)); - assertThat(indexResult.getMinLength(), is(nullValue())); - assertThat(indexResult.getSparse(), is(true)); - assertThat(indexResult.getUnique(), is(false)); - if (requireVersion(3, 4)) { - assertThat(indexResult.getType(), is(IndexType.geo)); - } else { - assertThat(indexResult.getType(), is(IndexType.geo2)); - } - assertThat(indexResult.getName(), is("myGeoIndex2")); - } - - @Test - public void createSkiplistIndex() { - final Collection fields = new ArrayList(); - fields.add("a"); - fields.add("b"); - final IndexEntity indexResult = db.collection(COLLECTION_NAME).ensureSkiplistIndex(fields, null); - assertThat(indexResult, is(notNullValue())); - assertThat(indexResult.getConstraint(), is(nullValue())); - assertThat(indexResult.getFields(), hasItem("a")); - assertThat(indexResult.getFields(), hasItem("b")); - assertThat(indexResult.getId(), startsWith(COLLECTION_NAME)); - assertThat(indexResult.getIsNewlyCreated(), is(true)); - assertThat(indexResult.getMinLength(), is(nullValue())); - assertThat(indexResult.getSparse(), is(false)); - assertThat(indexResult.getType(), is(IndexType.skiplist)); - assertThat(indexResult.getUnique(), is(false)); - } - - @Test - public void createSkiplistIndexWithOptions() { - if (!requireVersion(3, 5)) { - return; - } - - final SkiplistIndexOptions options = new SkiplistIndexOptions(); - options.name("mySkiplistIndex"); - - final Collection fields = new ArrayList(); - fields.add("a"); - fields.add("b"); - final IndexEntity indexResult = db.collection(COLLECTION_NAME).ensureSkiplistIndex(fields, options); - assertThat(indexResult, is(notNullValue())); - assertThat(indexResult.getConstraint(), is(nullValue())); - assertThat(indexResult.getFields(), hasItem("a")); - assertThat(indexResult.getFields(), hasItem("b")); - assertThat(indexResult.getId(), startsWith(COLLECTION_NAME)); - assertThat(indexResult.getIsNewlyCreated(), is(true)); - assertThat(indexResult.getMinLength(), is(nullValue())); - assertThat(indexResult.getSparse(), is(false)); - assertThat(indexResult.getType(), is(IndexType.skiplist)); - assertThat(indexResult.getUnique(), is(false)); - assertThat(indexResult.getName(), is("mySkiplistIndex")); - } - - @Test - public void createPersistentIndex() { - final Collection fields = new ArrayList(); - fields.add("a"); - fields.add("b"); - final IndexEntity indexResult = db.collection(COLLECTION_NAME).ensurePersistentIndex(fields, null); - assertThat(indexResult, is(notNullValue())); - assertThat(indexResult.getConstraint(), is(nullValue())); - assertThat(indexResult.getFields(), hasItem("a")); - assertThat(indexResult.getFields(), hasItem("b")); - assertThat(indexResult.getId(), startsWith(COLLECTION_NAME)); - assertThat(indexResult.getIsNewlyCreated(), is(true)); - assertThat(indexResult.getMinLength(), is(nullValue())); - assertThat(indexResult.getSparse(), is(false)); - assertThat(indexResult.getType(), is(IndexType.persistent)); - assertThat(indexResult.getUnique(), is(false)); - } - - @Test - public void createPersistentIndexWithOptions() { - if (!requireVersion(3, 5)) { - return; - } - - final PersistentIndexOptions options = new PersistentIndexOptions(); - options.name("myPersistentIndex"); - - final Collection fields = new ArrayList(); - fields.add("a"); - fields.add("b"); - final IndexEntity indexResult = db.collection(COLLECTION_NAME).ensurePersistentIndex(fields, options); - assertThat(indexResult, is(notNullValue())); - assertThat(indexResult.getConstraint(), is(nullValue())); - assertThat(indexResult.getFields(), hasItem("a")); - assertThat(indexResult.getFields(), hasItem("b")); - assertThat(indexResult.getId(), startsWith(COLLECTION_NAME)); - assertThat(indexResult.getIsNewlyCreated(), is(true)); - assertThat(indexResult.getMinLength(), is(nullValue())); - assertThat(indexResult.getSparse(), is(false)); - assertThat(indexResult.getType(), is(IndexType.persistent)); - assertThat(indexResult.getUnique(), is(false)); - assertThat(indexResult.getName(), is("myPersistentIndex")); - } - - @Test - public void createFulltextIndex() { - final Collection fields = new ArrayList(); - fields.add("a"); - final IndexEntity indexResult = db.collection(COLLECTION_NAME).ensureFulltextIndex(fields, null); - assertThat(indexResult, is(notNullValue())); - assertThat(indexResult.getConstraint(), is(nullValue())); - assertThat(indexResult.getFields(), hasItem("a")); - assertThat(indexResult.getId(), startsWith(COLLECTION_NAME)); - assertThat(indexResult.getIsNewlyCreated(), is(true)); - assertThat(indexResult.getSparse(), is(true)); - assertThat(indexResult.getType(), is(IndexType.fulltext)); - assertThat(indexResult.getUnique(), is(false)); - } - - @Test - public void createFulltextIndexWithOptions() { - if (!requireVersion(3, 5)) { - return; - } - - final FulltextIndexOptions options = new FulltextIndexOptions(); - options.name("myFulltextIndex"); - - final Collection fields = new ArrayList(); - fields.add("a"); - final IndexEntity indexResult = db.collection(COLLECTION_NAME).ensureFulltextIndex(fields, options); - assertThat(indexResult, is(notNullValue())); - assertThat(indexResult.getConstraint(), is(nullValue())); - assertThat(indexResult.getFields(), hasItem("a")); - assertThat(indexResult.getId(), startsWith(COLLECTION_NAME)); - assertThat(indexResult.getIsNewlyCreated(), is(true)); - assertThat(indexResult.getSparse(), is(true)); - assertThat(indexResult.getType(), is(IndexType.fulltext)); - assertThat(indexResult.getUnique(), is(false)); - assertThat(indexResult.getName(), is("myFulltextIndex")); - } - - @Test - public void createTtlIndexWithoutOptions() { - if (!requireVersion(3, 5)) { - return; - } - final Collection fields = new ArrayList(); - fields.add("a"); - try { - final IndexEntity indexResult = db.collection(COLLECTION_NAME).ensureTtlIndex(fields, null); - } catch (final ArangoDBException e) { - assertThat(e.getResponseCode(), is(400)); - assertThat(e.getErrorNum(), is(10)); - assertThat(e.getMessage(), containsString("expireAfter attribute must be a number")); - } - } - - @Test - public void createTtlIndexWithOptions() { - if (!requireVersion(3, 5)) { - return; - } - final Collection fields = new ArrayList(); - fields.add("a"); - - final TtlIndexOptions options = new TtlIndexOptions(); - options.name("myTtlIndex"); - options.expireAfter(3600); - - final IndexEntity indexResult = db.collection(COLLECTION_NAME).ensureTtlIndex(fields, options); - assertThat(indexResult, is(notNullValue())); - assertThat(indexResult.getFields(), hasItem("a")); - assertThat(indexResult.getId(), startsWith(COLLECTION_NAME)); - assertThat(indexResult.getIsNewlyCreated(), is(true)); - assertThat(indexResult.getType(), is(IndexType.ttl)); - assertThat(indexResult.getExpireAfter(), is(3600)); - assertThat(indexResult.getName(), is("myTtlIndex")); - } - - @Test - public void getIndexes() { - final Collection fields = new ArrayList(); - fields.add("a"); - db.collection(COLLECTION_NAME).ensureHashIndex(fields, null); - final Collection indexes = db.collection(COLLECTION_NAME).getIndexes(); - assertThat(indexes, is(notNullValue())); - assertThat(indexes.size(), is(2)); - for (final IndexEntity i : indexes) { - assertThat(i.getType(), anyOf(is(IndexType.primary), is(IndexType.hash))); - if (i.getType() == IndexType.hash) { - assertThat(i.getFields().size(), is(1)); - assertThat(i.getFields(), hasItem("a")); - } - } - } - - @Test - public void getEdgeIndex() { - try { - db.createCollection(EDGE_COLLECTION_NAME, new CollectionCreateOptions().type(CollectionType.EDGES)); - final Collection indexes = db.collection(EDGE_COLLECTION_NAME).getIndexes(); - assertThat(indexes, is(notNullValue())); - assertThat(indexes.size(), is(2)); - for (final IndexEntity i : indexes) { - assertThat(i.getType(), anyOf(is(IndexType.primary), is(IndexType.edge))); - } - } finally { - try { - db.collection(EDGE_COLLECTION_NAME).drop(); - } catch (final ArangoDBException e) { - } - } - } - - @Test - public void exists() { - assertThat(db.collection(COLLECTION_NAME).exists(), is(true)); - assertThat(db.collection(COLLECTION_NAME + "no").exists(), is(false)); - } - - @Test - public void truncate() { - final BaseDocument doc = new BaseDocument(); - db.collection(COLLECTION_NAME).insertDocument(doc, null); - final BaseDocument readResult = db.collection(COLLECTION_NAME) - .getDocument(doc.getKey(), BaseDocument.class, null); - assertThat(readResult.getKey(), is(doc.getKey())); - final CollectionEntity truncateResult = db.collection(COLLECTION_NAME).truncate(); - assertThat(truncateResult, is(notNullValue())); - assertThat(truncateResult.getId(), is(notNullValue())); - final BaseDocument document = db.collection(COLLECTION_NAME) - .getDocument(doc.getKey(), BaseDocument.class, null); - assertThat(document, is(nullValue())); - } - - @Test - public void getCount() { - final CollectionPropertiesEntity countEmpty = db.collection(COLLECTION_NAME).count(); - assertThat(countEmpty, is(notNullValue())); - assertThat(countEmpty.getCount(), is(0L)); - db.collection(COLLECTION_NAME).insertDocument("{}", null); - final CollectionPropertiesEntity count = db.collection(COLLECTION_NAME).count(); - assertThat(count.getCount(), is(1L)); - } - - @Test - public void documentExists() { - final Boolean existsNot = db.collection(COLLECTION_NAME).documentExists("no", null); - assertThat(existsNot, is(false)); - db.collection(COLLECTION_NAME).insertDocument("{\"_key\":\"abc\"}", null); - final Boolean exists = db.collection(COLLECTION_NAME).documentExists("abc", null); - assertThat(exists, is(true)); - } - - @Test(expected = ArangoDBException.class) - public void documentExistsThrowExcpetion() { - db.collection(COLLECTION_NAME).documentExists("no", new DocumentExistsOptions().catchException(false)); - } - - @Test - public void documentExistsIfMatch() { - final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) - .insertDocument("{\"_key\":\"abc\"}", null); - final DocumentExistsOptions options = new DocumentExistsOptions().ifMatch(createResult.getRev()); - final Boolean exists = db.collection(COLLECTION_NAME).documentExists("abc", options); - assertThat(exists, is(true)); - } - - @Test - public void documentExistsIfMatchFail() { - db.collection(COLLECTION_NAME).insertDocument("{\"_key\":\"abc\"}", null); - final DocumentExistsOptions options = new DocumentExistsOptions().ifMatch("no"); - final Boolean exists = db.collection(COLLECTION_NAME).documentExists("abc", options); - assertThat(exists, is(false)); - } - - @Test - public void documentExistsIfNoneMatch() { - db.collection(COLLECTION_NAME).insertDocument("{\"_key\":\"abc\"}", null); - final DocumentExistsOptions options = new DocumentExistsOptions().ifNoneMatch("no"); - final Boolean exists = db.collection(COLLECTION_NAME).documentExists("abc", options); - assertThat(exists, is(true)); - } - - @Test - public void documentExistsIfNoneMatchFail() { - final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) - .insertDocument("{\"_key\":\"abc\"}", null); - final DocumentExistsOptions options = new DocumentExistsOptions().ifNoneMatch(createResult.getRev()); - final Boolean exists = db.collection(COLLECTION_NAME).documentExists("abc", options); - assertThat(exists, is(false)); - } - - @Test - public void insertDocuments() { - final Collection values = new ArrayList(); - values.add(new BaseDocument()); - values.add(new BaseDocument()); - values.add(new BaseDocument()); - final MultiDocumentEntity> docs = db.collection(COLLECTION_NAME) - .insertDocuments(values, null); - assertThat(docs, is(notNullValue())); - assertThat(docs.getDocuments(), is(notNullValue())); - assertThat(docs.getDocuments().size(), is(3)); - assertThat(docs.getErrors(), is(notNullValue())); - assertThat(docs.getErrors().size(), is(0)); - } - - @Test - public void insertDocumentsOverwrite() { - if (!requireVersion(3, 4)) { - return; - } - final BaseDocument doc1 = new BaseDocument(); - doc1.addAttribute("value", "a"); - final DocumentCreateEntity meta1 = db.collection(COLLECTION_NAME).insertDocument(doc1); - final BaseDocument doc2 = new BaseDocument(); - doc2.addAttribute("value", "a"); - final DocumentCreateEntity meta2 = db.collection(COLLECTION_NAME).insertDocument(doc2); - - doc1.addAttribute("value", "b"); - doc2.addAttribute("value", "b"); - - final MultiDocumentEntity> repsert = db.collection(COLLECTION_NAME) - .insertDocuments(Arrays.asList(doc1, doc2), - new DocumentCreateOptions().overwrite(true).returnOld(true).returnNew(true)); - assertThat(repsert, is(notNullValue())); - assertThat(repsert.getDocuments().size(), is(2)); - assertThat(repsert.getErrors().size(), is(0)); - for (final DocumentCreateEntity documentCreateEntity : repsert.getDocuments()) { - assertThat(documentCreateEntity.getRev(), is(not(meta1.getRev()))); - assertThat(documentCreateEntity.getRev(), is(not(meta2.getRev()))); - assertThat(documentCreateEntity.getOld().getAttribute("value").toString(), is("a")); - assertThat(documentCreateEntity.getNew().getAttribute("value").toString(), is("b")); - } - assertThat(db.collection(COLLECTION_NAME).count().getCount(), is(2L)); - } - - @Test - public void insertDocumentsJson() { - final Collection values = new ArrayList(); - values.add("{}"); - values.add("{}"); - values.add("{}"); - final MultiDocumentEntity> docs = db.collection(COLLECTION_NAME) - .insertDocuments(values); - assertThat(docs, is(notNullValue())); - assertThat(docs.getDocuments(), is(notNullValue())); - assertThat(docs.getDocuments().size(), is(3)); - assertThat(docs.getErrors(), is(notNullValue())); - assertThat(docs.getErrors().size(), is(0)); - } - - @Test - public void insertDocumentsOne() { - final Collection values = new ArrayList(); - values.add(new BaseDocument()); - final MultiDocumentEntity> docs = db.collection(COLLECTION_NAME) - .insertDocuments(values, null); - assertThat(docs, is(notNullValue())); - assertThat(docs.getDocuments(), is(notNullValue())); - assertThat(docs.getDocuments().size(), is(1)); - assertThat(docs.getErrors(), is(notNullValue())); - assertThat(docs.getErrors().size(), is(0)); - } - - @Test - public void insertDocumentsEmpty() { - final Collection values = new ArrayList(); - final MultiDocumentEntity> docs = db.collection(COLLECTION_NAME) - .insertDocuments(values, null); - assertThat(docs, is(notNullValue())); - assertThat(docs.getDocuments(), is(notNullValue())); - assertThat(docs.getDocuments().size(), is(0)); - assertThat(docs.getErrors(), is(notNullValue())); - assertThat(docs.getErrors().size(), is(0)); - } - - @Test - public void insertDocumentsReturnNew() { - final Collection values = new ArrayList(); - values.add(new BaseDocument()); - values.add(new BaseDocument()); - values.add(new BaseDocument()); - final DocumentCreateOptions options = new DocumentCreateOptions().returnNew(true); - final MultiDocumentEntity> docs = db.collection(COLLECTION_NAME) - .insertDocuments(values, options); - assertThat(docs, is(notNullValue())); - assertThat(docs.getDocuments(), is(notNullValue())); - assertThat(docs.getDocuments().size(), is(3)); - assertThat(docs.getErrors(), is(notNullValue())); - assertThat(docs.getErrors().size(), is(0)); - for (final DocumentCreateEntity doc : docs.getDocuments()) { - assertThat(doc.getNew(), is(notNullValue())); - final BaseDocument baseDocument = doc.getNew(); - assertThat(baseDocument.getKey(), is(notNullValue())); - } - - } - - @Test - public void insertDocumentsFail() { - final Collection values = new ArrayList(); - values.add(new BaseDocument("1")); - values.add(new BaseDocument("2")); - values.add(new BaseDocument("2")); - final MultiDocumentEntity> docs = db.collection(COLLECTION_NAME) - .insertDocuments(values); - assertThat(docs, is(notNullValue())); - assertThat(docs.getDocuments(), is(notNullValue())); - assertThat(docs.getDocuments().size(), is(2)); - assertThat(docs.getErrors(), is(notNullValue())); - assertThat(docs.getErrors().size(), is(1)); - assertThat(docs.getErrors().iterator().next().getErrorNum(), is(1210)); - } - - @Test - public void importDocuments() { - final Collection values = new ArrayList(); - values.add(new BaseDocument()); - values.add(new BaseDocument()); - values.add(new BaseDocument()); - final DocumentImportEntity docs = db.collection(COLLECTION_NAME).importDocuments(values); - assertThat(docs, is(notNullValue())); - assertThat(docs.getCreated(), is(values.size())); - assertThat(docs.getEmpty(), is(0)); - assertThat(docs.getErrors(), is(0)); - assertThat(docs.getIgnored(), is(0)); - assertThat(docs.getUpdated(), is(0)); - assertThat(docs.getDetails(), is(empty())); - } - - @Test - public void importDocumentsJsonList() { - final Collection values = new ArrayList(); - values.add("{}"); - values.add("{}"); - values.add("{}"); - final DocumentImportEntity docs = db.collection(COLLECTION_NAME).importDocuments(values); - assertThat(docs, is(notNullValue())); - assertThat(docs.getCreated(), is(values.size())); - assertThat(docs.getEmpty(), is(0)); - assertThat(docs.getErrors(), is(0)); - assertThat(docs.getIgnored(), is(0)); - assertThat(docs.getUpdated(), is(0)); - assertThat(docs.getDetails(), is(empty())); - } - - @Test - public void importDocumentsDuplicateDefaultError() { - final Collection values = new ArrayList(); - values.add(new BaseDocument("1")); - values.add(new BaseDocument("2")); - values.add(new BaseDocument("2")); - final DocumentImportEntity docs = db.collection(COLLECTION_NAME).importDocuments(values); - assertThat(docs, is(notNullValue())); - assertThat(docs.getCreated(), is(2)); - assertThat(docs.getEmpty(), is(0)); - assertThat(docs.getErrors(), is(1)); - assertThat(docs.getIgnored(), is(0)); - assertThat(docs.getUpdated(), is(0)); - assertThat(docs.getDetails(), is(empty())); - } - - @Test - public void importDocumentsDuplicateError() { - final Collection values = new ArrayList(); - values.add(new BaseDocument("1")); - values.add(new BaseDocument("2")); - values.add(new BaseDocument("2")); - final DocumentImportEntity docs = db.collection(COLLECTION_NAME) - .importDocuments(values, new DocumentImportOptions().onDuplicate(OnDuplicate.error)); - assertThat(docs, is(notNullValue())); - assertThat(docs.getCreated(), is(2)); - assertThat(docs.getEmpty(), is(0)); - assertThat(docs.getErrors(), is(1)); - assertThat(docs.getIgnored(), is(0)); - assertThat(docs.getUpdated(), is(0)); - assertThat(docs.getDetails(), is(empty())); - } - - @Test - public void importDocumentsDuplicateIgnore() { - final Collection values = new ArrayList(); - values.add(new BaseDocument("1")); - values.add(new BaseDocument("2")); - values.add(new BaseDocument("2")); - final DocumentImportEntity docs = db.collection(COLLECTION_NAME) - .importDocuments(values, new DocumentImportOptions().onDuplicate(OnDuplicate.ignore)); - assertThat(docs, is(notNullValue())); - assertThat(docs.getCreated(), is(2)); - assertThat(docs.getEmpty(), is(0)); - assertThat(docs.getErrors(), is(0)); - assertThat(docs.getIgnored(), is(1)); - assertThat(docs.getUpdated(), is(0)); - assertThat(docs.getDetails(), is(empty())); - } - - @Test - public void importDocumentsDuplicateReplace() { - final Collection values = new ArrayList(); - values.add(new BaseDocument("1")); - values.add(new BaseDocument("2")); - values.add(new BaseDocument("2")); - final DocumentImportEntity docs = db.collection(COLLECTION_NAME) - .importDocuments(values, new DocumentImportOptions().onDuplicate(OnDuplicate.replace)); - assertThat(docs, is(notNullValue())); - assertThat(docs.getCreated(), is(2)); - assertThat(docs.getEmpty(), is(0)); - assertThat(docs.getErrors(), is(0)); - assertThat(docs.getIgnored(), is(0)); - assertThat(docs.getUpdated(), is(1)); - assertThat(docs.getDetails(), is(empty())); - } - - @Test - public void importDocumentsDuplicateUpdate() { - final Collection values = new ArrayList(); - values.add(new BaseDocument("1")); - values.add(new BaseDocument("2")); - values.add(new BaseDocument("2")); - final DocumentImportEntity docs = db.collection(COLLECTION_NAME) - .importDocuments(values, new DocumentImportOptions().onDuplicate(OnDuplicate.update)); - assertThat(docs, is(notNullValue())); - assertThat(docs.getCreated(), is(2)); - assertThat(docs.getEmpty(), is(0)); - assertThat(docs.getErrors(), is(0)); - assertThat(docs.getIgnored(), is(0)); - assertThat(docs.getUpdated(), is(1)); - assertThat(docs.getDetails(), is(empty())); - } - - @Test - public void importDocumentsCompleteFail() { - final Collection values = new ArrayList(); - values.add(new BaseDocument("1")); - values.add(new BaseDocument("2")); - values.add(new BaseDocument("2")); - try { - db.collection(COLLECTION_NAME).importDocuments(values, new DocumentImportOptions().complete(true)); - fail(); - } catch (final ArangoDBException e) { - assertThat(e.getMessage(), containsString("1210")); - } - } - - @Test - public void importDocumentsDetails() { - final Collection values = new ArrayList(); - values.add(new BaseDocument("1")); - values.add(new BaseDocument("2")); - values.add(new BaseDocument("2")); - final DocumentImportEntity docs = db.collection(COLLECTION_NAME) - .importDocuments(values, new DocumentImportOptions().details(true)); - assertThat(docs, is(notNullValue())); - assertThat(docs.getCreated(), is(2)); - assertThat(docs.getEmpty(), is(0)); - assertThat(docs.getErrors(), is(1)); - assertThat(docs.getIgnored(), is(0)); - assertThat(docs.getUpdated(), is(0)); - assertThat(docs.getDetails().size(), is(1)); - assertThat(docs.getDetails().iterator().next(), containsString("unique constraint violated")); - } - - @Test - public void importDocumentsOverwriteFalse() { - final ArangoCollection collection = db.collection(COLLECTION_NAME); - collection.insertDocument(new BaseDocument()); - assertThat(collection.count().getCount(), is(1L)); - - final Collection values = new ArrayList(); - values.add(new BaseDocument()); - values.add(new BaseDocument()); - collection.importDocuments(values, new DocumentImportOptions().overwrite(false)); - assertThat(collection.count().getCount(), is(3L)); - } - - @Test - public void importDocumentsOverwriteTrue() { - final ArangoCollection collection = db.collection(COLLECTION_NAME); - collection.insertDocument(new BaseDocument()); - assertThat(collection.count().getCount(), is(1L)); - - final Collection values = new ArrayList(); - values.add(new BaseDocument()); - values.add(new BaseDocument()); - collection.importDocuments(values, new DocumentImportOptions().overwrite(true)); - assertThat(collection.count().getCount(), is(2L)); - } - - @Test - public void importDocumentsFromToPrefix() { - db.createCollection(COLLECTION_NAME + "_edge", new CollectionCreateOptions().type(CollectionType.EDGES)); - final ArangoCollection collection = db.collection(COLLECTION_NAME + "_edge"); - try { - final Collection values = new ArrayList(); - final String[] keys = { "1", "2" }; - for (int i = 0; i < keys.length; i++) { - values.add(new BaseEdgeDocument(keys[i], "from", "to")); - } - assertThat(values.size(), is(keys.length)); - - final DocumentImportEntity importResult = collection - .importDocuments(values, new DocumentImportOptions().fromPrefix("foo").toPrefix("bar")); - assertThat(importResult, is(notNullValue())); - assertThat(importResult.getCreated(), is(values.size())); - for (int i = 0; i < keys.length; i++) { - final BaseEdgeDocument doc = collection.getDocument(keys[i], BaseEdgeDocument.class); - assertThat(doc, is(notNullValue())); - assertThat(doc.getFrom(), is("foo/from")); - assertThat(doc.getTo(), is("bar/to")); - } - } finally { - collection.drop(); - } - } - - @Test - public void importDocumentsJson() { - final String values = "[{\"_key\":\"1\"},{\"_key\":\"2\"}]"; - final DocumentImportEntity docs = db.collection(COLLECTION_NAME).importDocuments(values); - assertThat(docs, is(notNullValue())); - assertThat(docs.getCreated(), is(2)); - assertThat(docs.getEmpty(), is(0)); - assertThat(docs.getErrors(), is(0)); - assertThat(docs.getIgnored(), is(0)); - assertThat(docs.getUpdated(), is(0)); - assertThat(docs.getDetails(), is(empty())); - } - - @Test - public void importDocumentsJsonDuplicateDefaultError() { - final String values = "[{\"_key\":\"1\"},{\"_key\":\"2\"},{\"_key\":\"2\"}]"; - final DocumentImportEntity docs = db.collection(COLLECTION_NAME).importDocuments(values); - assertThat(docs, is(notNullValue())); - assertThat(docs.getCreated(), is(2)); - assertThat(docs.getEmpty(), is(0)); - assertThat(docs.getErrors(), is(1)); - assertThat(docs.getIgnored(), is(0)); - assertThat(docs.getUpdated(), is(0)); - assertThat(docs.getDetails(), is(empty())); - } - - @Test - public void importDocumentsJsonDuplicateError() { - final String values = "[{\"_key\":\"1\"},{\"_key\":\"2\"},{\"_key\":\"2\"}]"; - final DocumentImportEntity docs = db.collection(COLLECTION_NAME) - .importDocuments(values, new DocumentImportOptions().onDuplicate(OnDuplicate.error)); - assertThat(docs, is(notNullValue())); - assertThat(docs.getCreated(), is(2)); - assertThat(docs.getEmpty(), is(0)); - assertThat(docs.getErrors(), is(1)); - assertThat(docs.getIgnored(), is(0)); - assertThat(docs.getUpdated(), is(0)); - assertThat(docs.getDetails(), is(empty())); - } - - @Test - public void importDocumentsJsonDuplicateIgnore() { - final String values = "[{\"_key\":\"1\"},{\"_key\":\"2\"},{\"_key\":\"2\"}]"; - final DocumentImportEntity docs = db.collection(COLLECTION_NAME) - .importDocuments(values, new DocumentImportOptions().onDuplicate(OnDuplicate.ignore)); - assertThat(docs, is(notNullValue())); - assertThat(docs.getCreated(), is(2)); - assertThat(docs.getEmpty(), is(0)); - assertThat(docs.getErrors(), is(0)); - assertThat(docs.getIgnored(), is(1)); - assertThat(docs.getUpdated(), is(0)); - assertThat(docs.getDetails(), is(empty())); - } - - @Test - public void importDocumentsJsonDuplicateReplace() { - final String values = "[{\"_key\":\"1\"},{\"_key\":\"2\"},{\"_key\":\"2\"}]"; - final DocumentImportEntity docs = db.collection(COLLECTION_NAME) - .importDocuments(values, new DocumentImportOptions().onDuplicate(OnDuplicate.replace)); - assertThat(docs, is(notNullValue())); - assertThat(docs.getCreated(), is(2)); - assertThat(docs.getEmpty(), is(0)); - assertThat(docs.getErrors(), is(0)); - assertThat(docs.getIgnored(), is(0)); - assertThat(docs.getUpdated(), is(1)); - assertThat(docs.getDetails(), is(empty())); - } - - @Test - public void importDocumentsJsonDuplicateUpdate() { - final String values = "[{\"_key\":\"1\"},{\"_key\":\"2\"},{\"_key\":\"2\"}]"; - final DocumentImportEntity docs = db.collection(COLLECTION_NAME) - .importDocuments(values, new DocumentImportOptions().onDuplicate(OnDuplicate.update)); - assertThat(docs, is(notNullValue())); - assertThat(docs.getCreated(), is(2)); - assertThat(docs.getEmpty(), is(0)); - assertThat(docs.getErrors(), is(0)); - assertThat(docs.getIgnored(), is(0)); - assertThat(docs.getUpdated(), is(1)); - assertThat(docs.getDetails(), is(empty())); - } - - @Test - public void importDocumentsJsonCompleteFail() { - final String values = "[{\"_key\":\"1\"},{\"_key\":\"2\"},{\"_key\":\"2\"}]"; - try { - db.collection(COLLECTION_NAME).importDocuments(values, new DocumentImportOptions().complete(true)); - fail(); - } catch (final ArangoDBException e) { - assertThat(e.getMessage(), containsString("1210")); - } - } - - @Test - public void importDocumentsJsonDetails() { - final String values = "[{\"_key\":\"1\"},{\"_key\":\"2\"},{\"_key\":\"2\"}]"; - final DocumentImportEntity docs = db.collection(COLLECTION_NAME) - .importDocuments(values, new DocumentImportOptions().details(true)); - assertThat(docs, is(notNullValue())); - assertThat(docs.getCreated(), is(2)); - assertThat(docs.getEmpty(), is(0)); - assertThat(docs.getErrors(), is(1)); - assertThat(docs.getIgnored(), is(0)); - assertThat(docs.getUpdated(), is(0)); - assertThat(docs.getDetails().size(), is(1)); - assertThat(docs.getDetails().iterator().next(), containsString("unique constraint violated")); - } - - @Test - public void importDocumentsJsonOverwriteFalse() { - final ArangoCollection collection = db.collection(COLLECTION_NAME); - collection.insertDocument(new BaseDocument()); - assertThat(collection.count().getCount(), is(1L)); - - final String values = "[{\"_key\":\"1\"},{\"_key\":\"2\"}]"; - collection.importDocuments(values, new DocumentImportOptions().overwrite(false)); - assertThat(collection.count().getCount(), is(3L)); - } - - @Test - public void importDocumentsJsonOverwriteTrue() { - final ArangoCollection collection = db.collection(COLLECTION_NAME); - collection.insertDocument(new BaseDocument()); - assertThat(collection.count().getCount(), is(1L)); - - final String values = "[{\"_key\":\"1\"},{\"_key\":\"2\"}]"; - collection.importDocuments(values, new DocumentImportOptions().overwrite(true)); - assertThat(collection.count().getCount(), is(2L)); - } - - @Test - public void importDocumentsJsonFromToPrefix() { - db.createCollection(COLLECTION_NAME + "_edge", new CollectionCreateOptions().type(CollectionType.EDGES)); - final ArangoCollection collection = db.collection(COLLECTION_NAME + "_edge"); - try { - final String[] keys = { "1", "2" }; - final String values = "[{\"_key\":\"1\",\"_from\":\"from\",\"_to\":\"to\"},{\"_key\":\"2\",\"_from\":\"from\",\"_to\":\"to\"}]"; - - final DocumentImportEntity importResult = collection - .importDocuments(values, new DocumentImportOptions().fromPrefix("foo").toPrefix("bar")); - assertThat(importResult, is(notNullValue())); - assertThat(importResult.getCreated(), is(2)); - for (int i = 0; i < keys.length; i++) { - final BaseEdgeDocument doc = collection.getDocument(keys[i], BaseEdgeDocument.class); - assertThat(doc, is(notNullValue())); - assertThat(doc.getFrom(), is("foo/from")); - assertThat(doc.getTo(), is("bar/to")); - } - } finally { - collection.drop(); - } - } - - @Test - public void deleteDocumentsByKey() { - final Collection values = new ArrayList(); - { - final BaseDocument e = new BaseDocument(); - e.setKey("1"); - values.add(e); - } - { - final BaseDocument e = new BaseDocument(); - e.setKey("2"); - values.add(e); - } - db.collection(COLLECTION_NAME).insertDocuments(values, null); - final Collection keys = new ArrayList(); - keys.add("1"); - keys.add("2"); - final MultiDocumentEntity> deleteResult = db.collection(COLLECTION_NAME) - .deleteDocuments(keys, null, null); - assertThat(deleteResult, is(notNullValue())); - assertThat(deleteResult.getDocuments().size(), is(2)); - for (final DocumentDeleteEntity i : deleteResult.getDocuments()) { - assertThat(i.getKey(), anyOf(is("1"), is("2"))); - } - assertThat(deleteResult.getErrors().size(), is(0)); - } - - @Test - public void deleteDocumentsByDocuments() { - final Collection values = new ArrayList(); - { - final BaseDocument e = new BaseDocument(); - e.setKey("1"); - values.add(e); - } - { - final BaseDocument e = new BaseDocument(); - e.setKey("2"); - values.add(e); - } - db.collection(COLLECTION_NAME).insertDocuments(values, null); - final MultiDocumentEntity> deleteResult = db.collection(COLLECTION_NAME) - .deleteDocuments(values, null, null); - assertThat(deleteResult, is(notNullValue())); - assertThat(deleteResult.getDocuments().size(), is(2)); - for (final DocumentDeleteEntity i : deleteResult.getDocuments()) { - assertThat(i.getKey(), anyOf(is("1"), is("2"))); - } - assertThat(deleteResult.getErrors().size(), is(0)); - } - - @Test - public void deleteDocumentsByKeyOne() { - final Collection values = new ArrayList(); - { - final BaseDocument e = new BaseDocument(); - e.setKey("1"); - values.add(e); - } - db.collection(COLLECTION_NAME).insertDocuments(values, null); - final Collection keys = new ArrayList(); - keys.add("1"); - final MultiDocumentEntity> deleteResult = db.collection(COLLECTION_NAME) - .deleteDocuments(keys, null, null); - assertThat(deleteResult, is(notNullValue())); - assertThat(deleteResult.getDocuments().size(), is(1)); - for (final DocumentDeleteEntity i : deleteResult.getDocuments()) { - assertThat(i.getKey(), is("1")); - } - assertThat(deleteResult.getErrors().size(), is(0)); - } - - @Test - public void deleteDocumentsByDocumentOne() { - final Collection values = new ArrayList(); - { - final BaseDocument e = new BaseDocument(); - e.setKey("1"); - values.add(e); - } - db.collection(COLLECTION_NAME).insertDocuments(values, null); - final MultiDocumentEntity> deleteResult = db.collection(COLLECTION_NAME) - .deleteDocuments(values, null, null); - assertThat(deleteResult, is(notNullValue())); - assertThat(deleteResult.getDocuments().size(), is(1)); - for (final DocumentDeleteEntity i : deleteResult.getDocuments()) { - assertThat(i.getKey(), is("1")); - } - assertThat(deleteResult.getErrors().size(), is(0)); - } - - @Test - public void deleteDocumentsEmpty() { - final Collection values = new ArrayList(); - db.collection(COLLECTION_NAME).insertDocuments(values, null); - final Collection keys = new ArrayList(); - final MultiDocumentEntity> deleteResult = db.collection(COLLECTION_NAME) - .deleteDocuments(keys, null, null); - assertThat(deleteResult, is(notNullValue())); - assertThat(deleteResult.getDocuments().size(), is(0)); - assertThat(deleteResult.getErrors().size(), is(0)); - } - - @Test - public void deleteDocumentsByKeyNotExisting() { - final Collection values = new ArrayList(); - db.collection(COLLECTION_NAME).insertDocuments(values, null); - final Collection keys = new ArrayList(); - keys.add("1"); - keys.add("2"); - final MultiDocumentEntity> deleteResult = db.collection(COLLECTION_NAME) - .deleteDocuments(keys, null, null); - assertThat(deleteResult, is(notNullValue())); - assertThat(deleteResult.getDocuments().size(), is(0)); - assertThat(deleteResult.getErrors().size(), is(2)); - } - - @Test - public void deleteDocumentsByDocumentsNotExisting() { - final Collection values = new ArrayList(); - { - final BaseDocument e = new BaseDocument(); - e.setKey("1"); - values.add(e); - } - { - final BaseDocument e = new BaseDocument(); - e.setKey("2"); - values.add(e); - } - final MultiDocumentEntity> deleteResult = db.collection(COLLECTION_NAME) - .deleteDocuments(values, null, null); - assertThat(deleteResult, is(notNullValue())); - assertThat(deleteResult.getDocuments().size(), is(0)); - assertThat(deleteResult.getErrors().size(), is(2)); - } - - @Test - public void updateDocuments() { - final Collection values = new ArrayList(); - { - final BaseDocument e = new BaseDocument(); - e.setKey("1"); - values.add(e); - } - { - final BaseDocument e = new BaseDocument(); - e.setKey("2"); - values.add(e); - } - db.collection(COLLECTION_NAME).insertDocuments(values, null); - final Collection updatedValues = new ArrayList(); - for (final BaseDocument i : values) { - i.addAttribute("a", "test"); - updatedValues.add(i); - } - final MultiDocumentEntity> updateResult = db.collection(COLLECTION_NAME) - .updateDocuments(updatedValues, null); - assertThat(updateResult.getDocuments().size(), is(2)); - assertThat(updateResult.getErrors().size(), is(0)); - } - - @Test - public void updateDocumentsOne() { - final Collection values = new ArrayList(); - { - final BaseDocument e = new BaseDocument(); - e.setKey("1"); - values.add(e); - } - db.collection(COLLECTION_NAME).insertDocuments(values, null); - final Collection updatedValues = new ArrayList(); - final BaseDocument first = values.iterator().next(); - first.addAttribute("a", "test"); - updatedValues.add(first); - final MultiDocumentEntity> updateResult = db.collection(COLLECTION_NAME) - .updateDocuments(updatedValues, null); - assertThat(updateResult.getDocuments().size(), is(1)); - assertThat(updateResult.getErrors().size(), is(0)); - } - - @Test - public void updateDocumentsEmpty() { - final Collection values = new ArrayList(); - final MultiDocumentEntity> updateResult = db.collection(COLLECTION_NAME) - .updateDocuments(values, null); - assertThat(updateResult.getDocuments().size(), is(0)); - assertThat(updateResult.getErrors().size(), is(0)); - } - - @Test - public void updateDocumentsWithoutKey() { - final Collection values = new ArrayList(); - { - values.add(new BaseDocument("1")); - } - db.collection(COLLECTION_NAME).insertDocuments(values, null); - final Collection updatedValues = new ArrayList(); - for (final BaseDocument i : values) { - i.addAttribute("a", "test"); - updatedValues.add(i); - } - updatedValues.add(new BaseDocument()); - final MultiDocumentEntity> updateResult = db.collection(COLLECTION_NAME) - .updateDocuments(updatedValues, null); - assertThat(updateResult.getDocuments().size(), is(1)); - assertThat(updateResult.getErrors().size(), is(1)); - } - - @Test - public void updateDocumentsJson() { - final Collection values = new ArrayList(); - values.add("{\"_key\":\"1\"}"); - values.add("{\"_key\":\"2\"}"); - db.collection(COLLECTION_NAME).insertDocuments(values); - - final Collection updatedValues = new ArrayList(); - updatedValues.add("{\"_key\":\"1\", \"foo\":\"bar\"}"); - updatedValues.add("{\"_key\":\"2\", \"foo\":\"bar\"}"); - final MultiDocumentEntity> updateResult = db.collection(COLLECTION_NAME) - .updateDocuments(updatedValues); - assertThat(updateResult.getDocuments().size(), is(2)); - assertThat(updateResult.getErrors().size(), is(0)); - } - - @Test - public void replaceDocuments() { - final Collection values = new ArrayList(); - { - values.add(new BaseDocument("1")); - values.add(new BaseDocument("2")); - } - db.collection(COLLECTION_NAME).insertDocuments(values, null); - final Collection updatedValues = new ArrayList(); - for (final BaseDocument i : values) { - i.addAttribute("a", "test"); - updatedValues.add(i); - } - final MultiDocumentEntity> updateResult = db.collection(COLLECTION_NAME) - .replaceDocuments(updatedValues, null); - assertThat(updateResult.getDocuments().size(), is(2)); - assertThat(updateResult.getErrors().size(), is(0)); - } - - @Test - public void replaceDocumentsOne() { - final Collection values = new ArrayList(); - { - final BaseDocument e = new BaseDocument(); - e.setKey("1"); - values.add(e); - } - db.collection(COLLECTION_NAME).insertDocuments(values, null); - final Collection updatedValues = new ArrayList(); - final BaseDocument first = values.iterator().next(); - first.addAttribute("a", "test"); - updatedValues.add(first); - final MultiDocumentEntity> updateResult = db.collection(COLLECTION_NAME) - .updateDocuments(updatedValues, null); - assertThat(updateResult.getDocuments().size(), is(1)); - assertThat(updateResult.getErrors().size(), is(0)); - } - - @Test - public void replaceDocumentsEmpty() { - final Collection values = new ArrayList(); - final MultiDocumentEntity> updateResult = db.collection(COLLECTION_NAME) - .updateDocuments(values, null); - assertThat(updateResult.getDocuments().size(), is(0)); - assertThat(updateResult.getErrors().size(), is(0)); - } - - @Test - public void replaceDocumentsWithoutKey() { - final Collection values = new ArrayList(); - { - values.add(new BaseDocument("1")); - } - db.collection(COLLECTION_NAME).insertDocuments(values, null); - final Collection updatedValues = new ArrayList(); - for (final BaseDocument i : values) { - i.addAttribute("a", "test"); - updatedValues.add(i); - } - updatedValues.add(new BaseDocument()); - final MultiDocumentEntity> updateResult = db.collection(COLLECTION_NAME) - .updateDocuments(updatedValues, null); - assertThat(updateResult.getDocuments().size(), is(1)); - assertThat(updateResult.getErrors().size(), is(1)); - } - - @Test - public void replaceDocumentsJson() { - final Collection values = new ArrayList(); - values.add("{\"_key\":\"1\"}"); - values.add("{\"_key\":\"2\"}"); - db.collection(COLLECTION_NAME).insertDocuments(values); - - final Collection updatedValues = new ArrayList(); - updatedValues.add("{\"_key\":\"1\", \"foo\":\"bar\"}"); - updatedValues.add("{\"_key\":\"2\", \"foo\":\"bar\"}"); - final MultiDocumentEntity> updateResult = db.collection(COLLECTION_NAME) - .replaceDocuments(updatedValues); - assertThat(updateResult.getDocuments().size(), is(2)); - assertThat(updateResult.getErrors().size(), is(0)); - } - - @Test - public void load() { - final CollectionEntity result = db.collection(COLLECTION_NAME).load(); - assertThat(result.getName(), is(COLLECTION_NAME)); - } - - @Test - public void unload() { - final CollectionEntity result = db.collection(COLLECTION_NAME).unload(); - assertThat(result.getName(), is(COLLECTION_NAME)); - } - - @Test - public void getInfo() { - final CollectionEntity result = db.collection(COLLECTION_NAME).getInfo(); - assertThat(result.getName(), is(COLLECTION_NAME)); - } - - @Test - public void getPropeties() { - final CollectionPropertiesEntity result = db.collection(COLLECTION_NAME).getProperties(); - assertThat(result.getName(), is(COLLECTION_NAME)); - assertThat(result.getCount(), is(nullValue())); - } - - @Test - public void changeProperties() { - final String collection = COLLECTION_NAME + "_prop"; - try { - db.createCollection(collection); - final CollectionPropertiesEntity properties = db.collection(collection).getProperties(); - assertThat(properties.getWaitForSync(), is(notNullValue())); - final CollectionPropertiesOptions options = new CollectionPropertiesOptions(); - options.waitForSync(!properties.getWaitForSync()); - options.journalSize(2000000L); - final CollectionPropertiesEntity changedProperties = db.collection(collection).changeProperties(options); - assertThat(changedProperties.getWaitForSync(), is(notNullValue())); - assertThat(changedProperties.getWaitForSync(), is(not(properties.getWaitForSync()))); - } finally { - db.collection(collection).drop(); - } - } - - @Test - public void rename() { - if (arangoDB.getRole() != ServerRole.SINGLE) { - return; - } - try { - final CollectionEntity result = db.collection(COLLECTION_NAME).rename(COLLECTION_NAME + "1"); - assertThat(result, is(notNullValue())); - assertThat(result.getName(), is(COLLECTION_NAME + "1")); - final CollectionEntity info = db.collection(COLLECTION_NAME + "1").getInfo(); - assertThat(info.getName(), is(COLLECTION_NAME + "1")); - try { - db.collection(COLLECTION_NAME).getInfo(); - fail(); - } catch (final ArangoDBException e) { - } - } finally { - db.collection(COLLECTION_NAME + "1").rename(COLLECTION_NAME); - } - } - - @Test - public void responsibleShard() { - if (arangoDB.getRole() != ServerRole.COORDINATOR) { - return; - } - if (!requireVersion(3, 5)) { - return; - } - ShardEntity shard = db.collection(COLLECTION_NAME).getResponsibleShard(new BaseDocument("testKey")); - assertThat(shard, is(notNullValue())); - assertThat(shard.getShardId(), is(notNullValue())); - } - - @Test - public void renameDontBreaksCollectionHandler() { - if (arangoDB.getRole() != ServerRole.SINGLE) { - return; - } - try { - final ArangoCollection collection = db.collection(COLLECTION_NAME); - collection.rename(COLLECTION_NAME + "1"); - assertThat(collection.getInfo(), is(notNullValue())); - } finally { - db.collection(COLLECTION_NAME + "1").rename(COLLECTION_NAME); - } - } - - @Test - public void getRevision() { - final CollectionRevisionEntity result = db.collection(COLLECTION_NAME).getRevision(); - assertThat(result, is(notNullValue())); - assertThat(result.getName(), is(COLLECTION_NAME)); - assertThat(result.getRevision(), is(notNullValue())); - } - - @Test - public void keyWithSpecialCharacter() { - final String key = "myKey_-:.@()+,=;$!*'%"; - db.collection(COLLECTION_NAME).insertDocument(new BaseDocument(key)); - final BaseDocument doc = db.collection(COLLECTION_NAME).getDocument(key, BaseDocument.class); - assertThat(doc, is(notNullValue())); - assertThat(doc.getKey(), is(key)); - } - - @Test - public void alreadyUrlEncodedkey() { - final String key = "http%3A%2F%2Fexample.com%2F"; - db.collection(COLLECTION_NAME).insertDocument(new BaseDocument(key)); - final BaseDocument doc = db.collection(COLLECTION_NAME).getDocument(key, BaseDocument.class); - assertThat(doc, is(notNullValue())); - assertThat(doc.getKey(), is(key)); - } - - @Test - public void grantAccessRW() { - try { - arangoDB.createUser("user1", "1234", null); - db.collection(COLLECTION_NAME).grantAccess("user1", Permissions.RW); - } finally { - arangoDB.deleteUser("user1"); - } - } - - @Test - public void grantAccessRO() { - try { - arangoDB.createUser("user1", "1234", null); - db.collection(COLLECTION_NAME).grantAccess("user1", Permissions.RO); - } finally { - arangoDB.deleteUser("user1"); - } - } - - @Test - public void grantAccessNONE() { - try { - arangoDB.createUser("user1", "1234", null); - db.collection(COLLECTION_NAME).grantAccess("user1", Permissions.NONE); - } finally { - arangoDB.deleteUser("user1"); - } - } - - @Test(expected = ArangoDBException.class) - public void grantAccessUserNotFound() { - db.collection(COLLECTION_NAME).grantAccess("user1", Permissions.RW); - } - - @Test - public void revokeAccess() { - try { - arangoDB.createUser("user1", "1234", null); - db.collection(COLLECTION_NAME).grantAccess("user1", Permissions.NONE); - } finally { - arangoDB.deleteUser("user1"); - } - } - - @Test(expected = ArangoDBException.class) - public void revokeAccessUserNotFound() { - db.collection(COLLECTION_NAME).grantAccess("user1", Permissions.NONE); - } - - @Test - public void resetAccess() { - try { - arangoDB.createUser("user1", "1234", null); - db.collection(COLLECTION_NAME).resetAccess("user1"); - } finally { - arangoDB.deleteUser("user1"); - } - } - - @Test(expected = ArangoDBException.class) - public void resetAccessUserNotFound() { - db.collection(COLLECTION_NAME).resetAccess("user1"); - } - - @Test - public void getPermissions() { - assertThat(Permissions.RW, is(db.collection(COLLECTION_NAME).getPermissions("root"))); - } + private static final String COLLECTION_NAME = "db_collection_test"; + private static final String EDGE_COLLECTION_NAME = "db_edge_collection_test"; + + public ArangoCollectionTest(final Builder builder) { + super(builder); + if (!db.collection(COLLECTION_NAME).exists()) + db.createCollection(COLLECTION_NAME, null); + } + + @After + public void teardown() { + if (db.collection(COLLECTION_NAME).exists()) + db.collection(COLLECTION_NAME).drop(); + if (db.collection(EDGE_COLLECTION_NAME).exists()) + db.collection(EDGE_COLLECTION_NAME).drop(); + if (db.collection(EDGE_COLLECTION_NAME + "_1").exists()) + db.collection(COLLECTION_NAME + "_1").drop(); + } + + @Test + public void create() { + final CollectionEntity result = db.collection(COLLECTION_NAME + "_1").create(); + assertThat(result, is(notNullValue())); + assertThat(result.getId(), is(notNullValue())); + db.collection(COLLECTION_NAME + "_1").drop(); + } + + @Test + public void insertDocument() { + final DocumentCreateEntity doc = db.collection(COLLECTION_NAME) + .insertDocument(new BaseDocument(), null); + assertThat(doc, is(notNullValue())); + assertThat(doc.getId(), is(notNullValue())); + assertThat(doc.getKey(), is(notNullValue())); + assertThat(doc.getRev(), is(notNullValue())); + assertThat(doc.getNew(), is(nullValue())); + assertThat(doc.getId(), is(COLLECTION_NAME + "/" + doc.getKey())); + } + + @Test + public void insertDocumentUpdateRev() { + final BaseDocument doc = new BaseDocument(); + final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) + .insertDocument(doc, null); + assertThat(doc.getRevision(), is(createResult.getRev())); + } + + @Test + public void insertDocumentReturnNew() { + final DocumentCreateOptions options = new DocumentCreateOptions().returnNew(true); + final DocumentCreateEntity doc = db.collection(COLLECTION_NAME) + .insertDocument(new BaseDocument(), options); + assertThat(doc, is(notNullValue())); + assertThat(doc.getId(), is(notNullValue())); + assertThat(doc.getKey(), is(notNullValue())); + assertThat(doc.getRev(), is(notNullValue())); + assertThat(doc.getNew(), is(notNullValue())); + } + + @Test + public void insertDocumentOverwriteReturnOld() { + if (!requireVersion(3, 4)) { + return; + } + final BaseDocument doc = new BaseDocument(); + doc.addAttribute("value", "a"); + final DocumentCreateEntity meta = db.collection(COLLECTION_NAME).insertDocument(doc); + doc.addAttribute("value", "b"); + final DocumentCreateEntity repsert = db.collection(COLLECTION_NAME) + .insertDocument(doc, new DocumentCreateOptions().overwrite(true).returnOld(true).returnNew(true)); + assertThat(repsert, is(notNullValue())); + assertThat(repsert.getRev(), is(not(meta.getRev()))); + assertThat(repsert.getOld().getAttribute("value").toString(), is("a")); + assertThat(repsert.getNew().getAttribute("value").toString(), is("b")); + assertThat(db.collection(COLLECTION_NAME).count().getCount(), is(1L)); + } + + @Test + public void insertDocumentWaitForSync() { + final DocumentCreateOptions options = new DocumentCreateOptions().waitForSync(true); + final DocumentCreateEntity doc = db.collection(COLLECTION_NAME) + .insertDocument(new BaseDocument(), options); + assertThat(doc, is(notNullValue())); + assertThat(doc.getId(), is(notNullValue())); + assertThat(doc.getKey(), is(notNullValue())); + assertThat(doc.getRev(), is(notNullValue())); + assertThat(doc.getNew(), is(nullValue())); + } + + @Test + public void insertDocumentAsJson() { + final DocumentCreateEntity doc = db.collection(COLLECTION_NAME) + .insertDocument("{\"_key\":\"docRaw\",\"a\":\"test\"}", null); + assertThat(doc, is(notNullValue())); + assertThat(doc.getId(), is(notNullValue())); + assertThat(doc.getKey(), is(notNullValue())); + assertThat(doc.getRev(), is(notNullValue())); + } + + @Test + public void insertDocumentSilent() { + if (arangoDB.getRole() != ServerRole.SINGLE) { + return; + } + final DocumentCreateEntity meta = db.collection(COLLECTION_NAME) + .insertDocument(new BaseDocument(), new DocumentCreateOptions().silent(true)); + assertThat(meta, is(notNullValue())); + assertThat(meta.getId(), is(nullValue())); + assertThat(meta.getKey(), is(nullValue())); + assertThat(meta.getRev(), is(nullValue())); + } + + @Test + public void insertDocumentSilentDontTouchInstance() { + if (arangoDB.getRole() != ServerRole.SINGLE) { + return; + } + final BaseDocument doc = new BaseDocument(); + final String key = "testkey"; + doc.setKey(key); + final DocumentCreateEntity meta = db.collection(COLLECTION_NAME) + .insertDocument(doc, new DocumentCreateOptions().silent(true)); + assertThat(meta, is(notNullValue())); + assertThat(meta.getKey(), is(nullValue())); + assertThat(doc.getKey(), is(key)); + } + + @Test + public void insertDocumentsSilent() { + if (arangoDB.getRole() != ServerRole.SINGLE) { + return; + } + final MultiDocumentEntity> info = db.collection(COLLECTION_NAME) + .insertDocuments(Arrays.asList(new BaseDocument(), new BaseDocument()), + new DocumentCreateOptions().silent(true)); + assertThat(info, is(notNullValue())); + assertThat(info.getDocuments().isEmpty(), is(true)); + assertThat(info.getDocumentsAndErrors().isEmpty(), is(true)); + assertThat(info.getErrors().isEmpty(), is(true)); + } + + @Test + public void getDocument() { + final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) + .insertDocument(new BaseDocument(), null); + assertThat(createResult.getKey(), is(notNullValue())); + final BaseDocument readResult = db.collection(COLLECTION_NAME) + .getDocument(createResult.getKey(), BaseDocument.class, null); + assertThat(readResult.getKey(), is(createResult.getKey())); + assertThat(readResult.getId(), is(COLLECTION_NAME + "/" + createResult.getKey())); + } + + @Test + public void getDocumentIfMatch() { + final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) + .insertDocument(new BaseDocument(), null); + assertThat(createResult.getKey(), is(notNullValue())); + final DocumentReadOptions options = new DocumentReadOptions().ifMatch(createResult.getRev()); + final BaseDocument readResult = db.collection(COLLECTION_NAME) + .getDocument(createResult.getKey(), BaseDocument.class, options); + assertThat(readResult.getKey(), is(createResult.getKey())); + assertThat(readResult.getId(), is(COLLECTION_NAME + "/" + createResult.getKey())); + } + + @Test + public void getDocumentIfMatchFail() { + final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) + .insertDocument(new BaseDocument(), null); + assertThat(createResult.getKey(), is(notNullValue())); + final DocumentReadOptions options = new DocumentReadOptions().ifMatch("no"); + final BaseDocument document = db.collection(COLLECTION_NAME) + .getDocument(createResult.getKey(), BaseDocument.class, options); + assertThat(document, is(nullValue())); + } + + @Test + public void getDocumentIfNoneMatch() { + final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) + .insertDocument(new BaseDocument(), null); + assertThat(createResult.getKey(), is(notNullValue())); + final DocumentReadOptions options = new DocumentReadOptions().ifNoneMatch("no"); + final BaseDocument readResult = db.collection(COLLECTION_NAME) + .getDocument(createResult.getKey(), BaseDocument.class, options); + assertThat(readResult.getKey(), is(createResult.getKey())); + assertThat(readResult.getId(), is(COLLECTION_NAME + "/" + createResult.getKey())); + } + + @Test + public void getDocumentIfNoneMatchFail() { + final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) + .insertDocument(new BaseDocument(), null); + assertThat(createResult.getKey(), is(notNullValue())); + final DocumentReadOptions options = new DocumentReadOptions().ifNoneMatch(createResult.getRev()); + final BaseDocument document = db.collection(COLLECTION_NAME) + .getDocument(createResult.getKey(), BaseDocument.class, options); + assertThat(document, is(nullValue())); + } + + @Test + public void getDocumentAsJson() { + db.collection(COLLECTION_NAME).insertDocument("{\"_key\":\"docRaw\",\"a\":\"test\"}", null); + final String readResult = db.collection(COLLECTION_NAME).getDocument("docRaw", String.class, null); + assertThat(readResult.contains("\"_key\":\"docRaw\""), is(true)); + assertThat(readResult.contains("\"_id\":\"db_collection_test\\/docRaw\""), is(true)); + } + + @Test + public void getDocumentNotFound() { + final BaseDocument document = db.collection(COLLECTION_NAME).getDocument("no", BaseDocument.class); + assertThat(document, is(nullValue())); + } + + @Test + public void getDocumentNotFoundOptionsDefault() { + final BaseDocument document = db.collection(COLLECTION_NAME) + .getDocument("no", BaseDocument.class, new DocumentReadOptions()); + assertThat(document, is(nullValue())); + } + + @Test + public void getDocumentNotFoundOptionsNull() { + final BaseDocument document = db.collection(COLLECTION_NAME).getDocument("no", BaseDocument.class, null); + assertThat(document, is(nullValue())); + } + + @Test(expected = ArangoDBException.class) + public void getDocumentNotFoundThrowException() { + db.collection(COLLECTION_NAME) + .getDocument("no", BaseDocument.class, new DocumentReadOptions().catchException(false)); + } + + @Test(expected = ArangoDBException.class) + public void getDocumentWrongKey() { + db.collection(COLLECTION_NAME).getDocument("no/no", BaseDocument.class); + } + + public void getDocumentDirtyRead() { + final BaseDocument doc = new BaseDocument(); + db.collection(COLLECTION_NAME).insertDocument(doc); + final VPackSlice document = db.collection(COLLECTION_NAME) + .getDocument(doc.getKey(), VPackSlice.class, new DocumentReadOptions().allowDirtyRead(true)); + assertThat(document, is(notNullValue())); + } + + @Test + public void getDocuments() { + final Collection values = new ArrayList(); + values.add(new BaseDocument("1")); + values.add(new BaseDocument("2")); + values.add(new BaseDocument("3")); + db.collection(COLLECTION_NAME).insertDocuments(values); + final MultiDocumentEntity documents = db.collection(COLLECTION_NAME) + .getDocuments(Arrays.asList("1", "2", "3"), BaseDocument.class); + assertThat(documents, is(notNullValue())); + assertThat(documents.getDocuments().size(), is(3)); + for (final BaseDocument document : documents.getDocuments()) { + assertThat(document.getId(), + isOneOf(COLLECTION_NAME + "/" + "1", COLLECTION_NAME + "/" + "2", COLLECTION_NAME + "/" + "3")); + } + } + + @Test + public void getDocumentsDirtyRead() { + final Collection values = new ArrayList(); + values.add(new BaseDocument("1")); + values.add(new BaseDocument("2")); + values.add(new BaseDocument("3")); + db.collection(COLLECTION_NAME).insertDocuments(values); + final MultiDocumentEntity documents = db.collection(COLLECTION_NAME) + .getDocuments(Arrays.asList("1", "2", "3"), BaseDocument.class, + new DocumentReadOptions().allowDirtyRead(true)); + assertThat(documents, is(notNullValue())); + assertThat(documents.getDocuments().size(), is(3)); + for (final BaseDocument document : documents.getDocuments()) { + assertThat(document.getId(), + isOneOf(COLLECTION_NAME + "/" + "1", COLLECTION_NAME + "/" + "2", COLLECTION_NAME + "/" + "3")); + } + } + + @Test + public void getDocumentsNotFound() { + final MultiDocumentEntity readResult = db.collection(COLLECTION_NAME) + .getDocuments(Collections.singleton("no"), BaseDocument.class); + assertThat(readResult, is(notNullValue())); + assertThat(readResult.getDocuments().size(), is(0)); + assertThat(readResult.getErrors().size(), is(1)); + } + + @Test + public void getDocumentsWrongKey() { + final MultiDocumentEntity readResult = db.collection(COLLECTION_NAME) + .getDocuments(Collections.singleton("no/no"), BaseDocument.class); + assertThat(readResult, is(notNullValue())); + assertThat(readResult.getDocuments().size(), is(0)); + assertThat(readResult.getErrors().size(), is(1)); + } + + @Test + public void updateDocument() { + final BaseDocument doc = new BaseDocument(); + doc.addAttribute("a", "test"); + doc.addAttribute("c", "test"); + final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) + .insertDocument(doc, null); + doc.updateAttribute("a", "test1"); + doc.addAttribute("b", "test"); + doc.updateAttribute("c", null); + final DocumentUpdateEntity updateResult = db.collection(COLLECTION_NAME) + .updateDocument(createResult.getKey(), doc, null); + assertThat(updateResult, is(notNullValue())); + assertThat(updateResult.getId(), is(createResult.getId())); + assertThat(updateResult.getNew(), is(nullValue())); + assertThat(updateResult.getOld(), is(nullValue())); + assertThat(updateResult.getRev(), is(not(updateResult.getOldRev()))); + assertThat(updateResult.getOldRev(), is(createResult.getRev())); + + final BaseDocument readResult = db.collection(COLLECTION_NAME) + .getDocument(createResult.getKey(), BaseDocument.class, null); + assertThat(readResult.getKey(), is(createResult.getKey())); + assertThat(readResult.getAttribute("a"), is(notNullValue())); + assertThat(String.valueOf(readResult.getAttribute("a")), is("test1")); + assertThat(readResult.getAttribute("b"), is(notNullValue())); + assertThat(String.valueOf(readResult.getAttribute("b")), is("test")); + assertThat(readResult.getRevision(), is(updateResult.getRev())); + assertThat(readResult.getProperties().keySet(), hasItem("c")); + } + + @Test + public void updateDocumentUpdateRev() { + final BaseDocument doc = new BaseDocument(); + final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) + .insertDocument(doc, null); + assertThat(doc.getRevision(), is(createResult.getRev())); + final DocumentUpdateEntity updateResult = db.collection(COLLECTION_NAME) + .updateDocument(createResult.getKey(), doc, null); + assertThat(doc.getRevision(), is(updateResult.getRev())); + } + + @Test + public void updateDocumentIfMatch() { + final BaseDocument doc = new BaseDocument(); + doc.addAttribute("a", "test"); + doc.addAttribute("c", "test"); + final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) + .insertDocument(doc, null); + doc.updateAttribute("a", "test1"); + doc.addAttribute("b", "test"); + doc.updateAttribute("c", null); + final DocumentUpdateOptions options = new DocumentUpdateOptions().ifMatch(createResult.getRev()); + final DocumentUpdateEntity updateResult = db.collection(COLLECTION_NAME) + .updateDocument(createResult.getKey(), doc, options); + assertThat(updateResult, is(notNullValue())); + assertThat(updateResult.getId(), is(createResult.getId())); + assertThat(updateResult.getRev(), is(not(updateResult.getOldRev()))); + assertThat(updateResult.getOldRev(), is(createResult.getRev())); + + final BaseDocument readResult = db.collection(COLLECTION_NAME) + .getDocument(createResult.getKey(), BaseDocument.class, null); + assertThat(readResult.getKey(), is(createResult.getKey())); + assertThat(readResult.getAttribute("a"), is(notNullValue())); + assertThat(String.valueOf(readResult.getAttribute("a")), is("test1")); + assertThat(readResult.getAttribute("b"), is(notNullValue())); + assertThat(String.valueOf(readResult.getAttribute("b")), is("test")); + assertThat(readResult.getRevision(), is(updateResult.getRev())); + assertThat(readResult.getProperties().keySet(), hasItem("c")); + } + + @Test(expected = ArangoDBException.class) + public void updateDocumentIfMatchFail() { + final BaseDocument doc = new BaseDocument(); + doc.addAttribute("a", "test"); + doc.addAttribute("c", "test"); + final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) + .insertDocument(doc, null); + doc.updateAttribute("a", "test1"); + doc.addAttribute("b", "test"); + doc.updateAttribute("c", null); + + final DocumentUpdateOptions options = new DocumentUpdateOptions().ifMatch("no"); + db.collection(COLLECTION_NAME).updateDocument(createResult.getKey(), doc, options); + } + + @Test + public void updateDocumentReturnNew() { + final BaseDocument doc = new BaseDocument(); + doc.addAttribute("a", "test"); + final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) + .insertDocument(doc, null); + doc.updateAttribute("a", "test1"); + doc.addAttribute("b", "test"); + final DocumentUpdateOptions options = new DocumentUpdateOptions().returnNew(true); + final DocumentUpdateEntity updateResult = db.collection(COLLECTION_NAME) + .updateDocument(createResult.getKey(), doc, options); + assertThat(updateResult, is(notNullValue())); + assertThat(updateResult.getId(), is(createResult.getId())); + assertThat(updateResult.getOldRev(), is(createResult.getRev())); + assertThat(updateResult.getNew(), is(notNullValue())); + assertThat(updateResult.getNew().getKey(), is(createResult.getKey())); + assertThat(updateResult.getNew().getRevision(), is(not(createResult.getRev()))); + assertThat(updateResult.getNew().getAttribute("a"), is(notNullValue())); + assertThat(String.valueOf(updateResult.getNew().getAttribute("a")), is("test1")); + assertThat(updateResult.getNew().getAttribute("b"), is(notNullValue())); + assertThat(String.valueOf(updateResult.getNew().getAttribute("b")), is("test")); + } + + @Test + public void updateDocumentReturnOld() { + final BaseDocument doc = new BaseDocument(); + doc.addAttribute("a", "test"); + final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) + .insertDocument(doc, null); + doc.updateAttribute("a", "test1"); + doc.addAttribute("b", "test"); + final DocumentUpdateOptions options = new DocumentUpdateOptions().returnOld(true); + final DocumentUpdateEntity updateResult = db.collection(COLLECTION_NAME) + .updateDocument(createResult.getKey(), doc, options); + assertThat(updateResult, is(notNullValue())); + assertThat(updateResult.getId(), is(createResult.getId())); + assertThat(updateResult.getOldRev(), is(createResult.getRev())); + assertThat(updateResult.getOld(), is(notNullValue())); + assertThat(updateResult.getOld().getKey(), is(createResult.getKey())); + assertThat(updateResult.getOld().getRevision(), is(createResult.getRev())); + assertThat(updateResult.getOld().getAttribute("a"), is(notNullValue())); + assertThat(String.valueOf(updateResult.getOld().getAttribute("a")), is("test")); + assertThat(updateResult.getOld().getProperties().keySet(), not(hasItem("b"))); + } + + @Test + public void updateDocumentKeepNullTrue() { + final BaseDocument doc = new BaseDocument(); + doc.addAttribute("a", "test"); + final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) + .insertDocument(doc, null); + doc.updateAttribute("a", null); + final DocumentUpdateOptions options = new DocumentUpdateOptions().keepNull(true); + final DocumentUpdateEntity updateResult = db.collection(COLLECTION_NAME) + .updateDocument(createResult.getKey(), doc, options); + assertThat(updateResult, is(notNullValue())); + assertThat(updateResult.getId(), is(createResult.getId())); + assertThat(updateResult.getRev(), is(not(updateResult.getOldRev()))); + assertThat(updateResult.getOldRev(), is(createResult.getRev())); + + final BaseDocument readResult = db.collection(COLLECTION_NAME) + .getDocument(createResult.getKey(), BaseDocument.class, null); + assertThat(readResult.getKey(), is(createResult.getKey())); + assertThat(readResult.getProperties().keySet(), hasItem("a")); + } + + @Test + public void updateDocumentKeepNullFalse() { + final BaseDocument doc = new BaseDocument(); + doc.addAttribute("a", "test"); + final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) + .insertDocument(doc, null); + doc.updateAttribute("a", null); + final DocumentUpdateOptions options = new DocumentUpdateOptions().keepNull(false); + final DocumentUpdateEntity updateResult = db.collection(COLLECTION_NAME) + .updateDocument(createResult.getKey(), doc, options); + assertThat(updateResult, is(notNullValue())); + assertThat(updateResult.getId(), is(createResult.getId())); + assertThat(updateResult.getRev(), is(not(updateResult.getOldRev()))); + assertThat(updateResult.getOldRev(), is(createResult.getRev())); + + final BaseDocument readResult = db.collection(COLLECTION_NAME) + .getDocument(createResult.getKey(), BaseDocument.class, null); + assertThat(readResult.getKey(), is(createResult.getKey())); + assertThat(readResult.getId(), is(createResult.getId())); + assertThat(readResult.getRevision(), is(notNullValue())); + assertThat(readResult.getProperties().keySet(), not(hasItem("a"))); + } + + private static class TestUpdateEntity { + @SuppressWarnings("unused") + private String a, b; + } + + @Test + public void updateDocumentSerializeNullTrue() { + final TestUpdateEntity doc = new TestUpdateEntity(); + doc.a = "foo"; + doc.b = "foo"; + final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME).insertDocument(doc); + final TestUpdateEntity patchDoc = new TestUpdateEntity(); + patchDoc.a = "bar"; + final DocumentUpdateEntity updateResult = db.collection(COLLECTION_NAME) + .updateDocument(createResult.getKey(), patchDoc); + assertThat(updateResult, is(notNullValue())); + assertThat(updateResult.getKey(), is(createResult.getKey())); + + final BaseDocument readResult = db.collection(COLLECTION_NAME) + .getDocument(createResult.getKey(), BaseDocument.class); + assertThat(readResult.getKey(), is(createResult.getKey())); + assertThat(readResult.getProperties().keySet(), hasItem("a")); + assertThat(readResult.getAttribute("a").toString(), is("bar")); + } + + @Test + public void updateDocumentSerializeNullFalse() { + final TestUpdateEntity doc = new TestUpdateEntity(); + doc.a = "foo"; + doc.b = "foo"; + final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME).insertDocument(doc); + final TestUpdateEntity patchDoc = new TestUpdateEntity(); + patchDoc.a = "bar"; + final DocumentUpdateEntity updateResult = db.collection(COLLECTION_NAME) + .updateDocument(createResult.getKey(), patchDoc, new DocumentUpdateOptions().serializeNull(false)); + assertThat(updateResult, is(notNullValue())); + assertThat(updateResult.getKey(), is(createResult.getKey())); + + final BaseDocument readResult = db.collection(COLLECTION_NAME) + .getDocument(createResult.getKey(), BaseDocument.class); + assertThat(readResult.getKey(), is(createResult.getKey())); + assertThat(readResult.getProperties().keySet(), hasItems("a", "b")); + assertThat(readResult.getAttribute("a").toString(), is("bar")); + assertThat(readResult.getAttribute("b").toString(), is("foo")); + } + + @SuppressWarnings("unchecked") + @Test + public void updateDocumentMergeObjectsTrue() { + final BaseDocument doc = new BaseDocument(); + final Map a = new HashMap(); + a.put("a", "test"); + doc.addAttribute("a", a); + final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) + .insertDocument(doc, null); + a.clear(); + a.put("b", "test"); + doc.updateAttribute("a", a); + final DocumentUpdateOptions options = new DocumentUpdateOptions().mergeObjects(true); + final DocumentUpdateEntity updateResult = db.collection(COLLECTION_NAME) + .updateDocument(createResult.getKey(), doc, options); + assertThat(updateResult, is(notNullValue())); + assertThat(updateResult.getId(), is(createResult.getId())); + assertThat(updateResult.getRev(), is(not(updateResult.getOldRev()))); + assertThat(updateResult.getOldRev(), is(createResult.getRev())); + + final BaseDocument readResult = db.collection(COLLECTION_NAME) + .getDocument(createResult.getKey(), BaseDocument.class, null); + assertThat(readResult.getKey(), is(createResult.getKey())); + final Object aResult = readResult.getAttribute("a"); + assertThat(aResult, instanceOf(Map.class)); + final Map aMap = (Map) aResult; + assertThat(aMap.keySet(), hasItem("a")); + assertThat(aMap.keySet(), hasItem("b")); + } + + @SuppressWarnings("unchecked") + @Test + public void updateDocumentMergeObjectsFalse() { + final BaseDocument doc = new BaseDocument(); + final Map a = new HashMap(); + a.put("a", "test"); + doc.addAttribute("a", a); + final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) + .insertDocument(doc, null); + a.clear(); + a.put("b", "test"); + doc.updateAttribute("a", a); + final DocumentUpdateOptions options = new DocumentUpdateOptions().mergeObjects(false); + final DocumentUpdateEntity updateResult = db.collection(COLLECTION_NAME) + .updateDocument(createResult.getKey(), doc, options); + assertThat(updateResult, is(notNullValue())); + assertThat(updateResult.getId(), is(createResult.getId())); + assertThat(updateResult.getRev(), is(not(updateResult.getOldRev()))); + assertThat(updateResult.getOldRev(), is(createResult.getRev())); + + final BaseDocument readResult = db.collection(COLLECTION_NAME) + .getDocument(createResult.getKey(), BaseDocument.class, null); + assertThat(readResult.getKey(), is(createResult.getKey())); + final Object aResult = readResult.getAttribute("a"); + assertThat(aResult, instanceOf(Map.class)); + final Map aMap = (Map) aResult; + assertThat(aMap.keySet(), not(hasItem("a"))); + assertThat(aMap.keySet(), hasItem("b")); + } + + @Test(expected = ArangoDBException.class) + public void updateDocumentIgnoreRevsFalse() { + final BaseDocument doc = new BaseDocument(); + doc.addAttribute("a", "test"); + final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) + .insertDocument(doc, null); + doc.updateAttribute("a", "test1"); + doc.setRevision("no"); + + final DocumentUpdateOptions options = new DocumentUpdateOptions().ignoreRevs(false); + db.collection(COLLECTION_NAME).updateDocument(createResult.getKey(), doc, options); + } + + @Test + public void updateDocumentSilent() { + if (arangoDB.getRole() != ServerRole.SINGLE) { + return; + } + final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) + .insertDocument(new BaseDocument()); + final DocumentUpdateEntity meta = db.collection(COLLECTION_NAME) + .updateDocument(createResult.getKey(), new BaseDocument(), new DocumentUpdateOptions().silent(true)); + assertThat(meta, is(notNullValue())); + assertThat(meta.getId(), is(nullValue())); + assertThat(meta.getKey(), is(nullValue())); + assertThat(meta.getRev(), is(nullValue())); + } + + @Test + public void updateDocumentsSilent() { + if (arangoDB.getRole() != ServerRole.SINGLE) { + return; + } + final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) + .insertDocument(new BaseDocument()); + final MultiDocumentEntity> info = db.collection(COLLECTION_NAME) + .updateDocuments(Arrays.asList(new BaseDocument(createResult.getKey())), + new DocumentUpdateOptions().silent(true)); + assertThat(info, is(notNullValue())); + assertThat(info.getDocuments().isEmpty(), is(true)); + assertThat(info.getDocumentsAndErrors().isEmpty(), is(true)); + assertThat(info.getErrors().isEmpty(), is(true)); + } + + @Test + public void updateNonExistingDocument() { + final BaseDocument doc = new BaseDocument("test-" + UUID.randomUUID().toString()); + doc.addAttribute("a", "test"); + doc.addAttribute("c", "test"); + + try { + db.collection(COLLECTION_NAME).updateDocument(doc.getKey(), doc, null); + fail(); + } catch (ArangoDBException e) { + assertThat(e.getResponseCode(), is(404)); + assertThat(e.getErrorNum(), is(1202)); + } + } + + @Test + public void updateDocumentPreconditionFailed() { + final BaseDocument doc = new BaseDocument("test-" + UUID.randomUUID().toString()); + doc.addAttribute("foo", "a"); + final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) + .insertDocument(doc, null); + + doc.updateAttribute("foo", "b"); + db.collection(COLLECTION_NAME).updateDocument(doc.getKey(), doc, null); + + doc.updateAttribute("foo", "c"); + try { + db.collection(COLLECTION_NAME).updateDocument(doc.getKey(), doc, new DocumentUpdateOptions().ifMatch(createResult.getRev())); + fail(); + } catch (ArangoDBException e) { + assertThat(e.getResponseCode(), is(412)); + assertThat(e.getErrorNum(), is(1200)); + } + BaseDocument readDocument = db.collection(COLLECTION_NAME).getDocument(doc.getKey(), BaseDocument.class); + assertThat(readDocument.getAttribute("foo"), is("b")); + } + + @Test + public void replaceDocument() { + final BaseDocument doc = new BaseDocument(); + doc.addAttribute("a", "test"); + final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) + .insertDocument(doc, null); + doc.getProperties().clear(); + doc.addAttribute("b", "test"); + final DocumentUpdateEntity replaceResult = db.collection(COLLECTION_NAME) + .replaceDocument(createResult.getKey(), doc, null); + assertThat(replaceResult, is(notNullValue())); + assertThat(replaceResult.getId(), is(createResult.getId())); + assertThat(replaceResult.getNew(), is(nullValue())); + assertThat(replaceResult.getOld(), is(nullValue())); + assertThat(replaceResult.getRev(), is(not(replaceResult.getOldRev()))); + assertThat(replaceResult.getOldRev(), is(createResult.getRev())); + + final BaseDocument readResult = db.collection(COLLECTION_NAME) + .getDocument(createResult.getKey(), BaseDocument.class, null); + assertThat(readResult.getKey(), is(createResult.getKey())); + assertThat(readResult.getRevision(), is(replaceResult.getRev())); + assertThat(readResult.getProperties().keySet(), not(hasItem("a"))); + assertThat(readResult.getAttribute("b"), is(notNullValue())); + assertThat(String.valueOf(readResult.getAttribute("b")), is("test")); + } + + @Test + public void replaceDocumentUpdateRev() { + final BaseDocument doc = new BaseDocument(); + final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) + .insertDocument(doc, null); + assertThat(doc.getRevision(), is(createResult.getRev())); + final DocumentUpdateEntity replaceResult = db.collection(COLLECTION_NAME) + .replaceDocument(createResult.getKey(), doc, null); + assertThat(doc.getRevision(), is(replaceResult.getRev())); + } + + @Test + public void replaceDocumentIfMatch() { + final BaseDocument doc = new BaseDocument(); + doc.addAttribute("a", "test"); + final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) + .insertDocument(doc, null); + doc.getProperties().clear(); + doc.addAttribute("b", "test"); + final DocumentReplaceOptions options = new DocumentReplaceOptions().ifMatch(createResult.getRev()); + final DocumentUpdateEntity replaceResult = db.collection(COLLECTION_NAME) + .replaceDocument(createResult.getKey(), doc, options); + assertThat(replaceResult, is(notNullValue())); + assertThat(replaceResult.getId(), is(createResult.getId())); + assertThat(replaceResult.getRev(), is(not(replaceResult.getOldRev()))); + assertThat(replaceResult.getOldRev(), is(createResult.getRev())); + + final BaseDocument readResult = db.collection(COLLECTION_NAME) + .getDocument(createResult.getKey(), BaseDocument.class, null); + assertThat(readResult.getKey(), is(createResult.getKey())); + assertThat(readResult.getRevision(), is(replaceResult.getRev())); + assertThat(readResult.getProperties().keySet(), not(hasItem("a"))); + assertThat(readResult.getAttribute("b"), is(notNullValue())); + assertThat(String.valueOf(readResult.getAttribute("b")), is("test")); + } + + @Test(expected = ArangoDBException.class) + public void replaceDocumentIfMatchFail() { + final BaseDocument doc = new BaseDocument(); + doc.addAttribute("a", "test"); + final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) + .insertDocument(doc, null); + doc.getProperties().clear(); + doc.addAttribute("b", "test"); + + final DocumentReplaceOptions options = new DocumentReplaceOptions().ifMatch("no"); + db.collection(COLLECTION_NAME).replaceDocument(createResult.getKey(), doc, options); + } + + @Test(expected = ArangoDBException.class) + public void replaceDocumentIgnoreRevsFalse() { + final BaseDocument doc = new BaseDocument(); + doc.addAttribute("a", "test"); + final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) + .insertDocument(doc, null); + doc.getProperties().clear(); + doc.addAttribute("b", "test"); + doc.setRevision("no"); + + final DocumentReplaceOptions options = new DocumentReplaceOptions().ignoreRevs(false); + db.collection(COLLECTION_NAME).replaceDocument(createResult.getKey(), doc, options); + } + + @Test + public void replaceDocumentReturnNew() { + final BaseDocument doc = new BaseDocument(); + doc.addAttribute("a", "test"); + final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) + .insertDocument(doc, null); + doc.getProperties().clear(); + doc.addAttribute("b", "test"); + final DocumentReplaceOptions options = new DocumentReplaceOptions().returnNew(true); + final DocumentUpdateEntity replaceResult = db.collection(COLLECTION_NAME) + .replaceDocument(createResult.getKey(), doc, options); + assertThat(replaceResult, is(notNullValue())); + assertThat(replaceResult.getId(), is(createResult.getId())); + assertThat(replaceResult.getOldRev(), is(createResult.getRev())); + assertThat(replaceResult.getNew(), is(notNullValue())); + assertThat(replaceResult.getNew().getKey(), is(createResult.getKey())); + assertThat(replaceResult.getNew().getRevision(), is(not(createResult.getRev()))); + assertThat(replaceResult.getNew().getProperties().keySet(), not(hasItem("a"))); + assertThat(replaceResult.getNew().getAttribute("b"), is(notNullValue())); + assertThat(String.valueOf(replaceResult.getNew().getAttribute("b")), is("test")); + } + + @Test + public void replaceDocumentReturnOld() { + final BaseDocument doc = new BaseDocument(); + doc.addAttribute("a", "test"); + final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) + .insertDocument(doc, null); + doc.getProperties().clear(); + doc.addAttribute("b", "test"); + final DocumentReplaceOptions options = new DocumentReplaceOptions().returnOld(true); + final DocumentUpdateEntity replaceResult = db.collection(COLLECTION_NAME) + .replaceDocument(createResult.getKey(), doc, options); + assertThat(replaceResult, is(notNullValue())); + assertThat(replaceResult.getId(), is(createResult.getId())); + assertThat(replaceResult.getOldRev(), is(createResult.getRev())); + assertThat(replaceResult.getOld(), is(notNullValue())); + assertThat(replaceResult.getOld().getKey(), is(createResult.getKey())); + assertThat(replaceResult.getOld().getRevision(), is(createResult.getRev())); + assertThat(replaceResult.getOld().getAttribute("a"), is(notNullValue())); + assertThat(String.valueOf(replaceResult.getOld().getAttribute("a")), is("test")); + assertThat(replaceResult.getOld().getProperties().keySet(), not(hasItem("b"))); + } + + @Test + public void replaceDocumentSilent() { + if (arangoDB.getRole() != ServerRole.SINGLE) { + return; + } + final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) + .insertDocument(new BaseDocument()); + final DocumentUpdateEntity meta = db.collection(COLLECTION_NAME) + .replaceDocument(createResult.getKey(), new BaseDocument(), new DocumentReplaceOptions().silent(true)); + assertThat(meta, is(notNullValue())); + assertThat(meta.getId(), is(nullValue())); + assertThat(meta.getKey(), is(nullValue())); + assertThat(meta.getRev(), is(nullValue())); + } + + @Test + public void replaceDocumentSilentDontTouchInstance() { + if (arangoDB.getRole() != ServerRole.SINGLE) { + return; + } + final BaseDocument doc = new BaseDocument(); + final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME).insertDocument(doc); + final String revision = doc.getRevision(); + assertThat(revision, is(notNullValue())); + final DocumentUpdateEntity meta = db.collection(COLLECTION_NAME) + .replaceDocument(createResult.getKey(), doc, new DocumentReplaceOptions().silent(true)); + assertThat(meta.getRev(), is(nullValue())); + assertThat(doc.getRevision(), is(revision)); + } + + @Test + public void replaceDocumentsSilent() { + if (arangoDB.getRole() != ServerRole.SINGLE) { + return; + } + final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) + .insertDocument(new BaseDocument()); + final MultiDocumentEntity> info = db.collection(COLLECTION_NAME) + .replaceDocuments(Arrays.asList(new BaseDocument(createResult.getKey())), + new DocumentReplaceOptions().silent(true)); + assertThat(info, is(notNullValue())); + assertThat(info.getDocuments().isEmpty(), is(true)); + assertThat(info.getDocumentsAndErrors().isEmpty(), is(true)); + assertThat(info.getErrors().isEmpty(), is(true)); + } + + @Test + public void deleteDocument() { + final BaseDocument doc = new BaseDocument(); + final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) + .insertDocument(doc, null); + db.collection(COLLECTION_NAME).deleteDocument(createResult.getKey(), null, null); + final BaseDocument document = db.collection(COLLECTION_NAME) + .getDocument(createResult.getKey(), BaseDocument.class, null); + assertThat(document, is(nullValue())); + } + + @Test + public void deleteDocumentReturnOld() { + final BaseDocument doc = new BaseDocument(); + doc.addAttribute("a", "test"); + final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) + .insertDocument(doc, null); + final DocumentDeleteOptions options = new DocumentDeleteOptions().returnOld(true); + final DocumentDeleteEntity deleteResult = db.collection(COLLECTION_NAME) + .deleteDocument(createResult.getKey(), BaseDocument.class, options); + assertThat(deleteResult.getOld(), is(notNullValue())); + assertThat(deleteResult.getOld(), instanceOf(BaseDocument.class)); + assertThat(deleteResult.getOld().getAttribute("a"), is(notNullValue())); + assertThat(String.valueOf(deleteResult.getOld().getAttribute("a")), is("test")); + } + + @Test + public void deleteDocumentIfMatch() { + final BaseDocument doc = new BaseDocument(); + final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) + .insertDocument(doc, null); + final DocumentDeleteOptions options = new DocumentDeleteOptions().ifMatch(createResult.getRev()); + db.collection(COLLECTION_NAME).deleteDocument(createResult.getKey(), null, options); + final BaseDocument document = db.collection(COLLECTION_NAME) + .getDocument(createResult.getKey(), BaseDocument.class, null); + assertThat(document, is(nullValue())); + } + + @Test(expected = ArangoDBException.class) + public void deleteDocumentIfMatchFail() { + final BaseDocument doc = new BaseDocument(); + final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) + .insertDocument(doc, null); + final DocumentDeleteOptions options = new DocumentDeleteOptions().ifMatch("no"); + db.collection(COLLECTION_NAME).deleteDocument(createResult.getKey(), null, options); + } + + @Test + public void deleteDocumentSilent() { + if (arangoDB.getRole() != ServerRole.SINGLE) { + return; + } + final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) + .insertDocument(new BaseDocument()); + final DocumentDeleteEntity meta = db.collection(COLLECTION_NAME) + .deleteDocument(createResult.getKey(), BaseDocument.class, new DocumentDeleteOptions().silent(true)); + assertThat(meta, is(notNullValue())); + assertThat(meta.getId(), is(nullValue())); + assertThat(meta.getKey(), is(nullValue())); + assertThat(meta.getRev(), is(nullValue())); + } + + @Test + public void deleteDocumentsSilent() { + if (arangoDB.getRole() != ServerRole.SINGLE) { + return; + } + final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) + .insertDocument(new BaseDocument()); + final MultiDocumentEntity> info = db.collection(COLLECTION_NAME) + .deleteDocuments(Arrays.asList(createResult.getKey()), BaseDocument.class, + new DocumentDeleteOptions().silent(true)); + assertThat(info, is(notNullValue())); + assertThat(info.getDocuments().isEmpty(), is(true)); + assertThat(info.getDocumentsAndErrors().isEmpty(), is(true)); + assertThat(info.getErrors().isEmpty(), is(true)); + } + + @Test + public void getIndex() { + final Collection fields = new ArrayList(); + fields.add("a"); + final IndexEntity createResult = db.collection(COLLECTION_NAME).ensureHashIndex(fields, null); + final IndexEntity readResult = db.collection(COLLECTION_NAME).getIndex(createResult.getId()); + assertThat(readResult.getId(), is(createResult.getId())); + assertThat(readResult.getType(), is(createResult.getType())); + } + + @Test + public void getIndexByKey() { + final Collection fields = new ArrayList(); + fields.add("a"); + final IndexEntity createResult = db.collection(COLLECTION_NAME).ensureHashIndex(fields, null); + final IndexEntity readResult = db.collection(COLLECTION_NAME).getIndex(createResult.getId().split("/")[1]); + assertThat(readResult.getId(), is(createResult.getId())); + assertThat(readResult.getType(), is(createResult.getType())); + } + + @Test(expected = ArangoDBException.class) + public void deleteIndex() { + final Collection fields = new ArrayList(); + fields.add("a"); + final IndexEntity createResult = db.collection(COLLECTION_NAME).ensureHashIndex(fields, null); + final String id = db.collection(COLLECTION_NAME).deleteIndex(createResult.getId()); + assertThat(id, is(createResult.getId())); + db.getIndex(id); + } + + @Test(expected = ArangoDBException.class) + public void deleteIndexByKey() { + final Collection fields = new ArrayList(); + fields.add("a"); + final IndexEntity createResult = db.collection(COLLECTION_NAME).ensureHashIndex(fields, null); + final String id = db.collection(COLLECTION_NAME).deleteIndex(createResult.getId().split("/")[1]); + assertThat(id, is(createResult.getId())); + db.getIndex(id); + } + + @Test + public void createHashIndex() { + final Collection fields = new ArrayList(); + fields.add("a"); + fields.add("b"); + final IndexEntity indexResult = db.collection(COLLECTION_NAME).ensureHashIndex(fields, null); + assertThat(indexResult, is(notNullValue())); + assertThat(indexResult.getConstraint(), is(nullValue())); + assertThat(indexResult.getFields(), hasItem("a")); + assertThat(indexResult.getFields(), hasItem("b")); + assertThat(indexResult.getId(), startsWith(COLLECTION_NAME)); + assertThat(indexResult.getIsNewlyCreated(), is(true)); + assertThat(indexResult.getMinLength(), is(nullValue())); + if (arangoDB.getRole() == ServerRole.SINGLE) { + assertThat(indexResult.getSelectivityEstimate(), is(1.)); + } + assertThat(indexResult.getSparse(), is(false)); + assertThat(indexResult.getType(), is(IndexType.hash)); + assertThat(indexResult.getUnique(), is(false)); + } + + @Test + public void createHashIndexWithOptions() { + if (!requireVersion(3, 5)) { + return; + } + + final HashIndexOptions options = new HashIndexOptions(); + options.name("myHashIndex"); + + final Collection fields = new ArrayList(); + fields.add("a"); + fields.add("b"); + final IndexEntity indexResult = db.collection(COLLECTION_NAME).ensureHashIndex(fields, options); + assertThat(indexResult, is(notNullValue())); + assertThat(indexResult.getConstraint(), is(nullValue())); + assertThat(indexResult.getFields(), hasItem("a")); + assertThat(indexResult.getFields(), hasItem("b")); + assertThat(indexResult.getId(), startsWith(COLLECTION_NAME)); + assertThat(indexResult.getIsNewlyCreated(), is(true)); + assertThat(indexResult.getMinLength(), is(nullValue())); + if (arangoDB.getRole() == ServerRole.SINGLE) { + assertThat(indexResult.getSelectivityEstimate(), is(1.)); + } + assertThat(indexResult.getSparse(), is(false)); + assertThat(indexResult.getType(), is(IndexType.hash)); + assertThat(indexResult.getUnique(), is(false)); + assertThat(indexResult.getName(), is("myHashIndex")); + } + + @Test + public void createGeoIndex() { + final Collection fields = new ArrayList(); + fields.add("a"); + final IndexEntity indexResult = db.collection(COLLECTION_NAME).ensureGeoIndex(fields, null); + assertThat(indexResult, is(notNullValue())); + assertThat(indexResult.getFields(), hasItem("a")); + assertThat(indexResult.getId(), startsWith(COLLECTION_NAME)); + assertThat(indexResult.getIsNewlyCreated(), is(true)); + assertThat(indexResult.getMinLength(), is(nullValue())); + assertThat(indexResult.getSparse(), is(true)); + assertThat(indexResult.getUnique(), is(false)); + if (requireVersion(3, 4)) { + assertThat(indexResult.getType(), is(IndexType.geo)); + } else { + assertThat(indexResult.getType(), is(IndexType.geo1)); + } + } + + @Test + public void createGeoIndexWithOptions() { + if (!requireVersion(3, 5)) { + return; + } + + final GeoIndexOptions options = new GeoIndexOptions(); + options.name("myGeoIndex1"); + + final Collection fields = new ArrayList(); + fields.add("a"); + final IndexEntity indexResult = db.collection(COLLECTION_NAME).ensureGeoIndex(fields, options); + assertThat(indexResult, is(notNullValue())); + assertThat(indexResult.getFields(), hasItem("a")); + assertThat(indexResult.getId(), startsWith(COLLECTION_NAME)); + assertThat(indexResult.getIsNewlyCreated(), is(true)); + assertThat(indexResult.getMinLength(), is(nullValue())); + assertThat(indexResult.getSparse(), is(true)); + assertThat(indexResult.getUnique(), is(false)); + if (requireVersion(3, 4)) { + assertThat(indexResult.getType(), is(IndexType.geo)); + } else { + assertThat(indexResult.getType(), is(IndexType.geo1)); + } + assertThat(indexResult.getName(), is("myGeoIndex1")); + } + + @Test + public void createGeo2Index() { + final Collection fields = new ArrayList(); + fields.add("a"); + fields.add("b"); + final IndexEntity indexResult = db.collection(COLLECTION_NAME).ensureGeoIndex(fields, null); + assertThat(indexResult, is(notNullValue())); + assertThat(indexResult.getFields(), hasItem("a")); + assertThat(indexResult.getFields(), hasItem("b")); + assertThat(indexResult.getId(), startsWith(COLLECTION_NAME)); + assertThat(indexResult.getIsNewlyCreated(), is(true)); + assertThat(indexResult.getMinLength(), is(nullValue())); + assertThat(indexResult.getSparse(), is(true)); + assertThat(indexResult.getUnique(), is(false)); + if (requireVersion(3, 4)) { + assertThat(indexResult.getType(), is(IndexType.geo)); + } else { + assertThat(indexResult.getType(), is(IndexType.geo2)); + } + } + + @Test + public void createGeo2IndexWithOptions() { + if (!requireVersion(3, 5)) { + return; + } + + final GeoIndexOptions options = new GeoIndexOptions(); + options.name("myGeoIndex2"); + + final Collection fields = new ArrayList(); + fields.add("a"); + fields.add("b"); + final IndexEntity indexResult = db.collection(COLLECTION_NAME).ensureGeoIndex(fields, options); + assertThat(indexResult, is(notNullValue())); + assertThat(indexResult.getFields(), hasItem("a")); + assertThat(indexResult.getFields(), hasItem("b")); + assertThat(indexResult.getId(), startsWith(COLLECTION_NAME)); + assertThat(indexResult.getIsNewlyCreated(), is(true)); + assertThat(indexResult.getMinLength(), is(nullValue())); + assertThat(indexResult.getSparse(), is(true)); + assertThat(indexResult.getUnique(), is(false)); + if (requireVersion(3, 4)) { + assertThat(indexResult.getType(), is(IndexType.geo)); + } else { + assertThat(indexResult.getType(), is(IndexType.geo2)); + } + assertThat(indexResult.getName(), is("myGeoIndex2")); + } + + @Test + public void createSkiplistIndex() { + final Collection fields = new ArrayList(); + fields.add("a"); + fields.add("b"); + final IndexEntity indexResult = db.collection(COLLECTION_NAME).ensureSkiplistIndex(fields, null); + assertThat(indexResult, is(notNullValue())); + assertThat(indexResult.getConstraint(), is(nullValue())); + assertThat(indexResult.getFields(), hasItem("a")); + assertThat(indexResult.getFields(), hasItem("b")); + assertThat(indexResult.getId(), startsWith(COLLECTION_NAME)); + assertThat(indexResult.getIsNewlyCreated(), is(true)); + assertThat(indexResult.getMinLength(), is(nullValue())); + assertThat(indexResult.getSparse(), is(false)); + assertThat(indexResult.getType(), is(IndexType.skiplist)); + assertThat(indexResult.getUnique(), is(false)); + } + + @Test + public void createSkiplistIndexWithOptions() { + if (!requireVersion(3, 5)) { + return; + } + + final SkiplistIndexOptions options = new SkiplistIndexOptions(); + options.name("mySkiplistIndex"); + + final Collection fields = new ArrayList(); + fields.add("a"); + fields.add("b"); + final IndexEntity indexResult = db.collection(COLLECTION_NAME).ensureSkiplistIndex(fields, options); + assertThat(indexResult, is(notNullValue())); + assertThat(indexResult.getConstraint(), is(nullValue())); + assertThat(indexResult.getFields(), hasItem("a")); + assertThat(indexResult.getFields(), hasItem("b")); + assertThat(indexResult.getId(), startsWith(COLLECTION_NAME)); + assertThat(indexResult.getIsNewlyCreated(), is(true)); + assertThat(indexResult.getMinLength(), is(nullValue())); + assertThat(indexResult.getSparse(), is(false)); + assertThat(indexResult.getType(), is(IndexType.skiplist)); + assertThat(indexResult.getUnique(), is(false)); + assertThat(indexResult.getName(), is("mySkiplistIndex")); + } + + @Test + public void createPersistentIndex() { + final Collection fields = new ArrayList(); + fields.add("a"); + fields.add("b"); + final IndexEntity indexResult = db.collection(COLLECTION_NAME).ensurePersistentIndex(fields, null); + assertThat(indexResult, is(notNullValue())); + assertThat(indexResult.getConstraint(), is(nullValue())); + assertThat(indexResult.getFields(), hasItem("a")); + assertThat(indexResult.getFields(), hasItem("b")); + assertThat(indexResult.getId(), startsWith(COLLECTION_NAME)); + assertThat(indexResult.getIsNewlyCreated(), is(true)); + assertThat(indexResult.getMinLength(), is(nullValue())); + assertThat(indexResult.getSparse(), is(false)); + assertThat(indexResult.getType(), is(IndexType.persistent)); + assertThat(indexResult.getUnique(), is(false)); + } + + @Test + public void createPersistentIndexWithOptions() { + if (!requireVersion(3, 5)) { + return; + } + + final PersistentIndexOptions options = new PersistentIndexOptions(); + options.name("myPersistentIndex"); + + final Collection fields = new ArrayList(); + fields.add("a"); + fields.add("b"); + final IndexEntity indexResult = db.collection(COLLECTION_NAME).ensurePersistentIndex(fields, options); + assertThat(indexResult, is(notNullValue())); + assertThat(indexResult.getConstraint(), is(nullValue())); + assertThat(indexResult.getFields(), hasItem("a")); + assertThat(indexResult.getFields(), hasItem("b")); + assertThat(indexResult.getId(), startsWith(COLLECTION_NAME)); + assertThat(indexResult.getIsNewlyCreated(), is(true)); + assertThat(indexResult.getMinLength(), is(nullValue())); + assertThat(indexResult.getSparse(), is(false)); + assertThat(indexResult.getType(), is(IndexType.persistent)); + assertThat(indexResult.getUnique(), is(false)); + assertThat(indexResult.getName(), is("myPersistentIndex")); + } + + @Test + public void createFulltextIndex() { + final Collection fields = new ArrayList(); + fields.add("a"); + final IndexEntity indexResult = db.collection(COLLECTION_NAME).ensureFulltextIndex(fields, null); + assertThat(indexResult, is(notNullValue())); + assertThat(indexResult.getConstraint(), is(nullValue())); + assertThat(indexResult.getFields(), hasItem("a")); + assertThat(indexResult.getId(), startsWith(COLLECTION_NAME)); + assertThat(indexResult.getIsNewlyCreated(), is(true)); + assertThat(indexResult.getSparse(), is(true)); + assertThat(indexResult.getType(), is(IndexType.fulltext)); + assertThat(indexResult.getUnique(), is(false)); + } + + @Test + public void createFulltextIndexWithOptions() { + if (!requireVersion(3, 5)) { + return; + } + + final FulltextIndexOptions options = new FulltextIndexOptions(); + options.name("myFulltextIndex"); + + final Collection fields = new ArrayList(); + fields.add("a"); + final IndexEntity indexResult = db.collection(COLLECTION_NAME).ensureFulltextIndex(fields, options); + assertThat(indexResult, is(notNullValue())); + assertThat(indexResult.getConstraint(), is(nullValue())); + assertThat(indexResult.getFields(), hasItem("a")); + assertThat(indexResult.getId(), startsWith(COLLECTION_NAME)); + assertThat(indexResult.getIsNewlyCreated(), is(true)); + assertThat(indexResult.getSparse(), is(true)); + assertThat(indexResult.getType(), is(IndexType.fulltext)); + assertThat(indexResult.getUnique(), is(false)); + assertThat(indexResult.getName(), is("myFulltextIndex")); + } + + @Test + public void createTtlIndexWithoutOptions() { + if (!requireVersion(3, 5)) { + return; + } + final Collection fields = new ArrayList(); + fields.add("a"); + try { + db.collection(COLLECTION_NAME).ensureTtlIndex(fields, null); + fail(); + } catch (final ArangoDBException e) { + assertThat(e.getResponseCode(), is(400)); + assertThat(e.getErrorNum(), is(10)); + assertThat(e.getMessage(), containsString("expireAfter attribute must be a number")); + } + } + + @Test + public void createTtlIndexWithOptions() { + if (!requireVersion(3, 5)) { + return; + } + final Collection fields = new ArrayList(); + fields.add("a"); + + final TtlIndexOptions options = new TtlIndexOptions(); + options.name("myTtlIndex"); + options.expireAfter(3600); + + final IndexEntity indexResult = db.collection(COLLECTION_NAME).ensureTtlIndex(fields, options); + assertThat(indexResult, is(notNullValue())); + assertThat(indexResult.getFields(), hasItem("a")); + assertThat(indexResult.getId(), startsWith(COLLECTION_NAME)); + assertThat(indexResult.getIsNewlyCreated(), is(true)); + assertThat(indexResult.getType(), is(IndexType.ttl)); + assertThat(indexResult.getExpireAfter(), is(3600)); + assertThat(indexResult.getName(), is("myTtlIndex")); + } + + @Test + public void getIndexes() { + final Collection fields = new ArrayList(); + fields.add("a"); + db.collection(COLLECTION_NAME).ensureHashIndex(fields, null); + final Collection indexes = db.collection(COLLECTION_NAME).getIndexes(); + assertThat(indexes, is(notNullValue())); + assertThat(indexes.size(), is(2)); + for (final IndexEntity i : indexes) { + assertThat(i.getType(), anyOf(is(IndexType.primary), is(IndexType.hash))); + if (i.getType() == IndexType.hash) { + assertThat(i.getFields().size(), is(1)); + assertThat(i.getFields(), hasItem("a")); + } + } + } + + @Test + public void getEdgeIndex() { + db.createCollection(EDGE_COLLECTION_NAME, new CollectionCreateOptions().type(CollectionType.EDGES)); + final Collection indexes = db.collection(EDGE_COLLECTION_NAME).getIndexes(); + assertThat(indexes, is(notNullValue())); + assertThat(indexes.size(), is(2)); + for (final IndexEntity i : indexes) { + assertThat(i.getType(), anyOf(is(IndexType.primary), is(IndexType.edge))); + } + db.collection(EDGE_COLLECTION_NAME).drop(); + } + + @Test + public void exists() { + assertThat(db.collection(COLLECTION_NAME).exists(), is(true)); + assertThat(db.collection(COLLECTION_NAME + "no").exists(), is(false)); + } + + @Test + public void truncate() { + final BaseDocument doc = new BaseDocument(); + db.collection(COLLECTION_NAME).insertDocument(doc, null); + final BaseDocument readResult = db.collection(COLLECTION_NAME) + .getDocument(doc.getKey(), BaseDocument.class, null); + assertThat(readResult.getKey(), is(doc.getKey())); + final CollectionEntity truncateResult = db.collection(COLLECTION_NAME).truncate(); + assertThat(truncateResult, is(notNullValue())); + assertThat(truncateResult.getId(), is(notNullValue())); + final BaseDocument document = db.collection(COLLECTION_NAME) + .getDocument(doc.getKey(), BaseDocument.class, null); + assertThat(document, is(nullValue())); + } + + @Test + public void getCount() { + final CollectionPropertiesEntity countEmpty = db.collection(COLLECTION_NAME).count(); + assertThat(countEmpty, is(notNullValue())); + assertThat(countEmpty.getCount(), is(0L)); + db.collection(COLLECTION_NAME).insertDocument("{}", null); + final CollectionPropertiesEntity count = db.collection(COLLECTION_NAME).count(); + assertThat(count.getCount(), is(1L)); + } + + @Test + public void documentExists() { + final Boolean existsNot = db.collection(COLLECTION_NAME).documentExists("no", null); + assertThat(existsNot, is(false)); + db.collection(COLLECTION_NAME).insertDocument("{\"_key\":\"abc\"}", null); + final Boolean exists = db.collection(COLLECTION_NAME).documentExists("abc", null); + assertThat(exists, is(true)); + } + + @Test(expected = ArangoDBException.class) + public void documentExistsThrowExcpetion() { + db.collection(COLLECTION_NAME).documentExists("no", new DocumentExistsOptions().catchException(false)); + } + + @Test + public void documentExistsIfMatch() { + final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) + .insertDocument("{\"_key\":\"abc\"}", null); + final DocumentExistsOptions options = new DocumentExistsOptions().ifMatch(createResult.getRev()); + final Boolean exists = db.collection(COLLECTION_NAME).documentExists("abc", options); + assertThat(exists, is(true)); + } + + @Test + public void documentExistsIfMatchFail() { + db.collection(COLLECTION_NAME).insertDocument("{\"_key\":\"abc\"}", null); + final DocumentExistsOptions options = new DocumentExistsOptions().ifMatch("no"); + final Boolean exists = db.collection(COLLECTION_NAME).documentExists("abc", options); + assertThat(exists, is(false)); + } + + @Test + public void documentExistsIfNoneMatch() { + db.collection(COLLECTION_NAME).insertDocument("{\"_key\":\"abc\"}", null); + final DocumentExistsOptions options = new DocumentExistsOptions().ifNoneMatch("no"); + final Boolean exists = db.collection(COLLECTION_NAME).documentExists("abc", options); + assertThat(exists, is(true)); + } + + @Test + public void documentExistsIfNoneMatchFail() { + final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) + .insertDocument("{\"_key\":\"abc\"}", null); + final DocumentExistsOptions options = new DocumentExistsOptions().ifNoneMatch(createResult.getRev()); + final Boolean exists = db.collection(COLLECTION_NAME).documentExists("abc", options); + assertThat(exists, is(false)); + } + + @Test + public void insertDocuments() { + final Collection values = new ArrayList(); + values.add(new BaseDocument()); + values.add(new BaseDocument()); + values.add(new BaseDocument()); + final MultiDocumentEntity> docs = db.collection(COLLECTION_NAME) + .insertDocuments(values, null); + assertThat(docs, is(notNullValue())); + assertThat(docs.getDocuments(), is(notNullValue())); + assertThat(docs.getDocuments().size(), is(3)); + assertThat(docs.getErrors(), is(notNullValue())); + assertThat(docs.getErrors().size(), is(0)); + } + + @Test + public void insertDocumentsOverwrite() { + if (!requireVersion(3, 4)) { + return; + } + final BaseDocument doc1 = new BaseDocument(); + doc1.addAttribute("value", "a"); + final DocumentCreateEntity meta1 = db.collection(COLLECTION_NAME).insertDocument(doc1); + final BaseDocument doc2 = new BaseDocument(); + doc2.addAttribute("value", "a"); + final DocumentCreateEntity meta2 = db.collection(COLLECTION_NAME).insertDocument(doc2); + + doc1.addAttribute("value", "b"); + doc2.addAttribute("value", "b"); + + final MultiDocumentEntity> repsert = db.collection(COLLECTION_NAME) + .insertDocuments(Arrays.asList(doc1, doc2), + new DocumentCreateOptions().overwrite(true).returnOld(true).returnNew(true)); + assertThat(repsert, is(notNullValue())); + assertThat(repsert.getDocuments().size(), is(2)); + assertThat(repsert.getErrors().size(), is(0)); + for (final DocumentCreateEntity documentCreateEntity : repsert.getDocuments()) { + assertThat(documentCreateEntity.getRev(), is(not(meta1.getRev()))); + assertThat(documentCreateEntity.getRev(), is(not(meta2.getRev()))); + assertThat(documentCreateEntity.getOld().getAttribute("value").toString(), is("a")); + assertThat(documentCreateEntity.getNew().getAttribute("value").toString(), is("b")); + } + assertThat(db.collection(COLLECTION_NAME).count().getCount(), is(2L)); + } + + @Test + public void insertDocumentsJson() { + final Collection values = new ArrayList(); + values.add("{}"); + values.add("{}"); + values.add("{}"); + final MultiDocumentEntity> docs = db.collection(COLLECTION_NAME) + .insertDocuments(values); + assertThat(docs, is(notNullValue())); + assertThat(docs.getDocuments(), is(notNullValue())); + assertThat(docs.getDocuments().size(), is(3)); + assertThat(docs.getErrors(), is(notNullValue())); + assertThat(docs.getErrors().size(), is(0)); + } + + @Test + public void insertDocumentsOne() { + final Collection values = new ArrayList(); + values.add(new BaseDocument()); + final MultiDocumentEntity> docs = db.collection(COLLECTION_NAME) + .insertDocuments(values, null); + assertThat(docs, is(notNullValue())); + assertThat(docs.getDocuments(), is(notNullValue())); + assertThat(docs.getDocuments().size(), is(1)); + assertThat(docs.getErrors(), is(notNullValue())); + assertThat(docs.getErrors().size(), is(0)); + } + + @Test + public void insertDocumentsEmpty() { + final Collection values = new ArrayList(); + final MultiDocumentEntity> docs = db.collection(COLLECTION_NAME) + .insertDocuments(values, null); + assertThat(docs, is(notNullValue())); + assertThat(docs.getDocuments(), is(notNullValue())); + assertThat(docs.getDocuments().size(), is(0)); + assertThat(docs.getErrors(), is(notNullValue())); + assertThat(docs.getErrors().size(), is(0)); + } + + @Test + public void insertDocumentsReturnNew() { + final Collection values = new ArrayList(); + values.add(new BaseDocument()); + values.add(new BaseDocument()); + values.add(new BaseDocument()); + final DocumentCreateOptions options = new DocumentCreateOptions().returnNew(true); + final MultiDocumentEntity> docs = db.collection(COLLECTION_NAME) + .insertDocuments(values, options); + assertThat(docs, is(notNullValue())); + assertThat(docs.getDocuments(), is(notNullValue())); + assertThat(docs.getDocuments().size(), is(3)); + assertThat(docs.getErrors(), is(notNullValue())); + assertThat(docs.getErrors().size(), is(0)); + for (final DocumentCreateEntity doc : docs.getDocuments()) { + assertThat(doc.getNew(), is(notNullValue())); + final BaseDocument baseDocument = doc.getNew(); + assertThat(baseDocument.getKey(), is(notNullValue())); + } + + } + + @Test + public void insertDocumentsFail() { + final Collection values = new ArrayList(); + values.add(new BaseDocument("1")); + values.add(new BaseDocument("2")); + values.add(new BaseDocument("2")); + final MultiDocumentEntity> docs = db.collection(COLLECTION_NAME) + .insertDocuments(values); + assertThat(docs, is(notNullValue())); + assertThat(docs.getDocuments(), is(notNullValue())); + assertThat(docs.getDocuments().size(), is(2)); + assertThat(docs.getErrors(), is(notNullValue())); + assertThat(docs.getErrors().size(), is(1)); + assertThat(docs.getErrors().iterator().next().getErrorNum(), is(1210)); + } + + @Test + public void importDocuments() { + final Collection values = new ArrayList(); + values.add(new BaseDocument()); + values.add(new BaseDocument()); + values.add(new BaseDocument()); + final DocumentImportEntity docs = db.collection(COLLECTION_NAME).importDocuments(values); + assertThat(docs, is(notNullValue())); + assertThat(docs.getCreated(), is(values.size())); + assertThat(docs.getEmpty(), is(0)); + assertThat(docs.getErrors(), is(0)); + assertThat(docs.getIgnored(), is(0)); + assertThat(docs.getUpdated(), is(0)); + assertThat(docs.getDetails(), is(empty())); + } + + @Test + public void importDocumentsJsonList() { + final Collection values = new ArrayList(); + values.add("{}"); + values.add("{}"); + values.add("{}"); + final DocumentImportEntity docs = db.collection(COLLECTION_NAME).importDocuments(values); + assertThat(docs, is(notNullValue())); + assertThat(docs.getCreated(), is(values.size())); + assertThat(docs.getEmpty(), is(0)); + assertThat(docs.getErrors(), is(0)); + assertThat(docs.getIgnored(), is(0)); + assertThat(docs.getUpdated(), is(0)); + assertThat(docs.getDetails(), is(empty())); + } + + @Test + public void importDocumentsDuplicateDefaultError() { + final Collection values = new ArrayList(); + values.add(new BaseDocument("1")); + values.add(new BaseDocument("2")); + values.add(new BaseDocument("2")); + final DocumentImportEntity docs = db.collection(COLLECTION_NAME).importDocuments(values); + assertThat(docs, is(notNullValue())); + assertThat(docs.getCreated(), is(2)); + assertThat(docs.getEmpty(), is(0)); + assertThat(docs.getErrors(), is(1)); + assertThat(docs.getIgnored(), is(0)); + assertThat(docs.getUpdated(), is(0)); + assertThat(docs.getDetails(), is(empty())); + } + + @Test + public void importDocumentsDuplicateError() { + final Collection values = new ArrayList(); + values.add(new BaseDocument("1")); + values.add(new BaseDocument("2")); + values.add(new BaseDocument("2")); + final DocumentImportEntity docs = db.collection(COLLECTION_NAME) + .importDocuments(values, new DocumentImportOptions().onDuplicate(OnDuplicate.error)); + assertThat(docs, is(notNullValue())); + assertThat(docs.getCreated(), is(2)); + assertThat(docs.getEmpty(), is(0)); + assertThat(docs.getErrors(), is(1)); + assertThat(docs.getIgnored(), is(0)); + assertThat(docs.getUpdated(), is(0)); + assertThat(docs.getDetails(), is(empty())); + } + + @Test + public void importDocumentsDuplicateIgnore() { + final Collection values = new ArrayList(); + values.add(new BaseDocument("1")); + values.add(new BaseDocument("2")); + values.add(new BaseDocument("2")); + final DocumentImportEntity docs = db.collection(COLLECTION_NAME) + .importDocuments(values, new DocumentImportOptions().onDuplicate(OnDuplicate.ignore)); + assertThat(docs, is(notNullValue())); + assertThat(docs.getCreated(), is(2)); + assertThat(docs.getEmpty(), is(0)); + assertThat(docs.getErrors(), is(0)); + assertThat(docs.getIgnored(), is(1)); + assertThat(docs.getUpdated(), is(0)); + assertThat(docs.getDetails(), is(empty())); + } + + @Test + public void importDocumentsDuplicateReplace() { + final Collection values = new ArrayList(); + values.add(new BaseDocument("1")); + values.add(new BaseDocument("2")); + values.add(new BaseDocument("2")); + final DocumentImportEntity docs = db.collection(COLLECTION_NAME) + .importDocuments(values, new DocumentImportOptions().onDuplicate(OnDuplicate.replace)); + assertThat(docs, is(notNullValue())); + assertThat(docs.getCreated(), is(2)); + assertThat(docs.getEmpty(), is(0)); + assertThat(docs.getErrors(), is(0)); + assertThat(docs.getIgnored(), is(0)); + assertThat(docs.getUpdated(), is(1)); + assertThat(docs.getDetails(), is(empty())); + } + + @Test + public void importDocumentsDuplicateUpdate() { + final Collection values = new ArrayList(); + values.add(new BaseDocument("1")); + values.add(new BaseDocument("2")); + values.add(new BaseDocument("2")); + final DocumentImportEntity docs = db.collection(COLLECTION_NAME) + .importDocuments(values, new DocumentImportOptions().onDuplicate(OnDuplicate.update)); + assertThat(docs, is(notNullValue())); + assertThat(docs.getCreated(), is(2)); + assertThat(docs.getEmpty(), is(0)); + assertThat(docs.getErrors(), is(0)); + assertThat(docs.getIgnored(), is(0)); + assertThat(docs.getUpdated(), is(1)); + assertThat(docs.getDetails(), is(empty())); + } + + @Test + public void importDocumentsCompleteFail() { + final Collection values = new ArrayList(); + values.add(new BaseDocument("1")); + values.add(new BaseDocument("2")); + values.add(new BaseDocument("2")); + try { + db.collection(COLLECTION_NAME).importDocuments(values, new DocumentImportOptions().complete(true)); + fail(); + } catch (final ArangoDBException e) { + assertThat(e.getErrorNum(), is(1210)); + } + } + + @Test + public void importDocumentsDetails() { + final Collection values = new ArrayList(); + values.add(new BaseDocument("1")); + values.add(new BaseDocument("2")); + values.add(new BaseDocument("2")); + final DocumentImportEntity docs = db.collection(COLLECTION_NAME) + .importDocuments(values, new DocumentImportOptions().details(true)); + assertThat(docs, is(notNullValue())); + assertThat(docs.getCreated(), is(2)); + assertThat(docs.getEmpty(), is(0)); + assertThat(docs.getErrors(), is(1)); + assertThat(docs.getIgnored(), is(0)); + assertThat(docs.getUpdated(), is(0)); + assertThat(docs.getDetails().size(), is(1)); + assertThat(docs.getDetails().iterator().next(), containsString("unique constraint violated")); + } + + @Test + public void importDocumentsOverwriteFalse() { + final ArangoCollection collection = db.collection(COLLECTION_NAME); + collection.insertDocument(new BaseDocument()); + assertThat(collection.count().getCount(), is(1L)); + + final Collection values = new ArrayList(); + values.add(new BaseDocument()); + values.add(new BaseDocument()); + collection.importDocuments(values, new DocumentImportOptions().overwrite(false)); + assertThat(collection.count().getCount(), is(3L)); + } + + @Test + public void importDocumentsOverwriteTrue() { + final ArangoCollection collection = db.collection(COLLECTION_NAME); + collection.insertDocument(new BaseDocument()); + assertThat(collection.count().getCount(), is(1L)); + + final Collection values = new ArrayList(); + values.add(new BaseDocument()); + values.add(new BaseDocument()); + collection.importDocuments(values, new DocumentImportOptions().overwrite(true)); + assertThat(collection.count().getCount(), is(2L)); + } + + @Test + public void importDocumentsFromToPrefix() { + db.createCollection(COLLECTION_NAME + "_edge", new CollectionCreateOptions().type(CollectionType.EDGES)); + final ArangoCollection collection = db.collection(COLLECTION_NAME + "_edge"); + try { + final Collection values = new ArrayList(); + final String[] keys = {"1", "2"}; + for (int i = 0; i < keys.length; i++) { + values.add(new BaseEdgeDocument(keys[i], "from", "to")); + } + assertThat(values.size(), is(keys.length)); + + final DocumentImportEntity importResult = collection + .importDocuments(values, new DocumentImportOptions().fromPrefix("foo").toPrefix("bar")); + assertThat(importResult, is(notNullValue())); + assertThat(importResult.getCreated(), is(values.size())); + for (int i = 0; i < keys.length; i++) { + final BaseEdgeDocument doc = collection.getDocument(keys[i], BaseEdgeDocument.class); + assertThat(doc, is(notNullValue())); + assertThat(doc.getFrom(), is("foo/from")); + assertThat(doc.getTo(), is("bar/to")); + } + } finally { + collection.drop(); + } + } + + @Test + public void importDocumentsJson() { + final String values = "[{\"_key\":\"1\"},{\"_key\":\"2\"}]"; + final DocumentImportEntity docs = db.collection(COLLECTION_NAME).importDocuments(values); + assertThat(docs, is(notNullValue())); + assertThat(docs.getCreated(), is(2)); + assertThat(docs.getEmpty(), is(0)); + assertThat(docs.getErrors(), is(0)); + assertThat(docs.getIgnored(), is(0)); + assertThat(docs.getUpdated(), is(0)); + assertThat(docs.getDetails(), is(empty())); + } + + @Test + public void importDocumentsJsonDuplicateDefaultError() { + final String values = "[{\"_key\":\"1\"},{\"_key\":\"2\"},{\"_key\":\"2\"}]"; + final DocumentImportEntity docs = db.collection(COLLECTION_NAME).importDocuments(values); + assertThat(docs, is(notNullValue())); + assertThat(docs.getCreated(), is(2)); + assertThat(docs.getEmpty(), is(0)); + assertThat(docs.getErrors(), is(1)); + assertThat(docs.getIgnored(), is(0)); + assertThat(docs.getUpdated(), is(0)); + assertThat(docs.getDetails(), is(empty())); + } + + @Test + public void importDocumentsJsonDuplicateError() { + final String values = "[{\"_key\":\"1\"},{\"_key\":\"2\"},{\"_key\":\"2\"}]"; + final DocumentImportEntity docs = db.collection(COLLECTION_NAME) + .importDocuments(values, new DocumentImportOptions().onDuplicate(OnDuplicate.error)); + assertThat(docs, is(notNullValue())); + assertThat(docs.getCreated(), is(2)); + assertThat(docs.getEmpty(), is(0)); + assertThat(docs.getErrors(), is(1)); + assertThat(docs.getIgnored(), is(0)); + assertThat(docs.getUpdated(), is(0)); + assertThat(docs.getDetails(), is(empty())); + } + + @Test + public void importDocumentsJsonDuplicateIgnore() { + final String values = "[{\"_key\":\"1\"},{\"_key\":\"2\"},{\"_key\":\"2\"}]"; + final DocumentImportEntity docs = db.collection(COLLECTION_NAME) + .importDocuments(values, new DocumentImportOptions().onDuplicate(OnDuplicate.ignore)); + assertThat(docs, is(notNullValue())); + assertThat(docs.getCreated(), is(2)); + assertThat(docs.getEmpty(), is(0)); + assertThat(docs.getErrors(), is(0)); + assertThat(docs.getIgnored(), is(1)); + assertThat(docs.getUpdated(), is(0)); + assertThat(docs.getDetails(), is(empty())); + } + + @Test + public void importDocumentsJsonDuplicateReplace() { + final String values = "[{\"_key\":\"1\"},{\"_key\":\"2\"},{\"_key\":\"2\"}]"; + final DocumentImportEntity docs = db.collection(COLLECTION_NAME) + .importDocuments(values, new DocumentImportOptions().onDuplicate(OnDuplicate.replace)); + assertThat(docs, is(notNullValue())); + assertThat(docs.getCreated(), is(2)); + assertThat(docs.getEmpty(), is(0)); + assertThat(docs.getErrors(), is(0)); + assertThat(docs.getIgnored(), is(0)); + assertThat(docs.getUpdated(), is(1)); + assertThat(docs.getDetails(), is(empty())); + } + + @Test + public void importDocumentsJsonDuplicateUpdate() { + final String values = "[{\"_key\":\"1\"},{\"_key\":\"2\"},{\"_key\":\"2\"}]"; + final DocumentImportEntity docs = db.collection(COLLECTION_NAME) + .importDocuments(values, new DocumentImportOptions().onDuplicate(OnDuplicate.update)); + assertThat(docs, is(notNullValue())); + assertThat(docs.getCreated(), is(2)); + assertThat(docs.getEmpty(), is(0)); + assertThat(docs.getErrors(), is(0)); + assertThat(docs.getIgnored(), is(0)); + assertThat(docs.getUpdated(), is(1)); + assertThat(docs.getDetails(), is(empty())); + } + + @Test + public void importDocumentsJsonCompleteFail() { + final String values = "[{\"_key\":\"1\"},{\"_key\":\"2\"},{\"_key\":\"2\"}]"; + try { + db.collection(COLLECTION_NAME).importDocuments(values, new DocumentImportOptions().complete(true)); + fail(); + } catch (final ArangoDBException e) { + assertThat(e.getErrorNum(), is(1210)); + } + } + + @Test + public void importDocumentsJsonDetails() { + final String values = "[{\"_key\":\"1\"},{\"_key\":\"2\"},{\"_key\":\"2\"}]"; + final DocumentImportEntity docs = db.collection(COLLECTION_NAME) + .importDocuments(values, new DocumentImportOptions().details(true)); + assertThat(docs, is(notNullValue())); + assertThat(docs.getCreated(), is(2)); + assertThat(docs.getEmpty(), is(0)); + assertThat(docs.getErrors(), is(1)); + assertThat(docs.getIgnored(), is(0)); + assertThat(docs.getUpdated(), is(0)); + assertThat(docs.getDetails().size(), is(1)); + assertThat(docs.getDetails().iterator().next(), containsString("unique constraint violated")); + } + + @Test + public void importDocumentsJsonOverwriteFalse() { + final ArangoCollection collection = db.collection(COLLECTION_NAME); + collection.insertDocument(new BaseDocument()); + assertThat(collection.count().getCount(), is(1L)); + + final String values = "[{\"_key\":\"1\"},{\"_key\":\"2\"}]"; + collection.importDocuments(values, new DocumentImportOptions().overwrite(false)); + assertThat(collection.count().getCount(), is(3L)); + } + + @Test + public void importDocumentsJsonOverwriteTrue() { + final ArangoCollection collection = db.collection(COLLECTION_NAME); + collection.insertDocument(new BaseDocument()); + assertThat(collection.count().getCount(), is(1L)); + + final String values = "[{\"_key\":\"1\"},{\"_key\":\"2\"}]"; + collection.importDocuments(values, new DocumentImportOptions().overwrite(true)); + assertThat(collection.count().getCount(), is(2L)); + } + + @Test + public void importDocumentsJsonFromToPrefix() { + db.createCollection(COLLECTION_NAME + "_edge", new CollectionCreateOptions().type(CollectionType.EDGES)); + final ArangoCollection collection = db.collection(COLLECTION_NAME + "_edge"); + try { + final String[] keys = {"1", "2"}; + final String values = "[{\"_key\":\"1\",\"_from\":\"from\",\"_to\":\"to\"},{\"_key\":\"2\",\"_from\":\"from\",\"_to\":\"to\"}]"; + + final DocumentImportEntity importResult = collection + .importDocuments(values, new DocumentImportOptions().fromPrefix("foo").toPrefix("bar")); + assertThat(importResult, is(notNullValue())); + assertThat(importResult.getCreated(), is(2)); + for (int i = 0; i < keys.length; i++) { + final BaseEdgeDocument doc = collection.getDocument(keys[i], BaseEdgeDocument.class); + assertThat(doc, is(notNullValue())); + assertThat(doc.getFrom(), is("foo/from")); + assertThat(doc.getTo(), is("bar/to")); + } + } finally { + collection.drop(); + } + } + + @Test + public void deleteDocumentsByKey() { + final Collection values = new ArrayList(); + { + final BaseDocument e = new BaseDocument(); + e.setKey("1"); + values.add(e); + } + { + final BaseDocument e = new BaseDocument(); + e.setKey("2"); + values.add(e); + } + db.collection(COLLECTION_NAME).insertDocuments(values, null); + final Collection keys = new ArrayList(); + keys.add("1"); + keys.add("2"); + final MultiDocumentEntity> deleteResult = db.collection(COLLECTION_NAME) + .deleteDocuments(keys, null, null); + assertThat(deleteResult, is(notNullValue())); + assertThat(deleteResult.getDocuments().size(), is(2)); + for (final DocumentDeleteEntity i : deleteResult.getDocuments()) { + assertThat(i.getKey(), anyOf(is("1"), is("2"))); + } + assertThat(deleteResult.getErrors().size(), is(0)); + } + + @Test + public void deleteDocumentsByDocuments() { + final Collection values = new ArrayList(); + { + final BaseDocument e = new BaseDocument(); + e.setKey("1"); + values.add(e); + } + { + final BaseDocument e = new BaseDocument(); + e.setKey("2"); + values.add(e); + } + db.collection(COLLECTION_NAME).insertDocuments(values, null); + final MultiDocumentEntity> deleteResult = db.collection(COLLECTION_NAME) + .deleteDocuments(values, null, null); + assertThat(deleteResult, is(notNullValue())); + assertThat(deleteResult.getDocuments().size(), is(2)); + for (final DocumentDeleteEntity i : deleteResult.getDocuments()) { + assertThat(i.getKey(), anyOf(is("1"), is("2"))); + } + assertThat(deleteResult.getErrors().size(), is(0)); + } + + @Test + public void deleteDocumentsByKeyOne() { + final Collection values = new ArrayList(); + { + final BaseDocument e = new BaseDocument(); + e.setKey("1"); + values.add(e); + } + db.collection(COLLECTION_NAME).insertDocuments(values, null); + final Collection keys = new ArrayList(); + keys.add("1"); + final MultiDocumentEntity> deleteResult = db.collection(COLLECTION_NAME) + .deleteDocuments(keys, null, null); + assertThat(deleteResult, is(notNullValue())); + assertThat(deleteResult.getDocuments().size(), is(1)); + for (final DocumentDeleteEntity i : deleteResult.getDocuments()) { + assertThat(i.getKey(), is("1")); + } + assertThat(deleteResult.getErrors().size(), is(0)); + } + + @Test + public void deleteDocumentsByDocumentOne() { + final Collection values = new ArrayList(); + { + final BaseDocument e = new BaseDocument(); + e.setKey("1"); + values.add(e); + } + db.collection(COLLECTION_NAME).insertDocuments(values, null); + final MultiDocumentEntity> deleteResult = db.collection(COLLECTION_NAME) + .deleteDocuments(values, null, null); + assertThat(deleteResult, is(notNullValue())); + assertThat(deleteResult.getDocuments().size(), is(1)); + for (final DocumentDeleteEntity i : deleteResult.getDocuments()) { + assertThat(i.getKey(), is("1")); + } + assertThat(deleteResult.getErrors().size(), is(0)); + } + + @Test + public void deleteDocumentsEmpty() { + final Collection values = new ArrayList(); + db.collection(COLLECTION_NAME).insertDocuments(values, null); + final Collection keys = new ArrayList(); + final MultiDocumentEntity> deleteResult = db.collection(COLLECTION_NAME) + .deleteDocuments(keys, null, null); + assertThat(deleteResult, is(notNullValue())); + assertThat(deleteResult.getDocuments().size(), is(0)); + assertThat(deleteResult.getErrors().size(), is(0)); + } + + @Test + public void deleteDocumentsByKeyNotExisting() { + final Collection values = new ArrayList(); + db.collection(COLLECTION_NAME).insertDocuments(values, null); + final Collection keys = new ArrayList(); + keys.add("1"); + keys.add("2"); + final MultiDocumentEntity> deleteResult = db.collection(COLLECTION_NAME) + .deleteDocuments(keys, null, null); + assertThat(deleteResult, is(notNullValue())); + assertThat(deleteResult.getDocuments().size(), is(0)); + assertThat(deleteResult.getErrors().size(), is(2)); + } + + @Test + public void deleteDocumentsByDocumentsNotExisting() { + final Collection values = new ArrayList(); + { + final BaseDocument e = new BaseDocument(); + e.setKey("1"); + values.add(e); + } + { + final BaseDocument e = new BaseDocument(); + e.setKey("2"); + values.add(e); + } + final MultiDocumentEntity> deleteResult = db.collection(COLLECTION_NAME) + .deleteDocuments(values, null, null); + assertThat(deleteResult, is(notNullValue())); + assertThat(deleteResult.getDocuments().size(), is(0)); + assertThat(deleteResult.getErrors().size(), is(2)); + } + + @Test + public void updateDocuments() { + final Collection values = new ArrayList(); + { + final BaseDocument e = new BaseDocument(); + e.setKey("1"); + values.add(e); + } + { + final BaseDocument e = new BaseDocument(); + e.setKey("2"); + values.add(e); + } + db.collection(COLLECTION_NAME).insertDocuments(values, null); + final Collection updatedValues = new ArrayList(); + for (final BaseDocument i : values) { + i.addAttribute("a", "test"); + updatedValues.add(i); + } + final MultiDocumentEntity> updateResult = db.collection(COLLECTION_NAME) + .updateDocuments(updatedValues, null); + assertThat(updateResult.getDocuments().size(), is(2)); + assertThat(updateResult.getErrors().size(), is(0)); + } + + @Test + public void updateDocumentsOne() { + final Collection values = new ArrayList(); + { + final BaseDocument e = new BaseDocument(); + e.setKey("1"); + values.add(e); + } + db.collection(COLLECTION_NAME).insertDocuments(values, null); + final Collection updatedValues = new ArrayList(); + final BaseDocument first = values.iterator().next(); + first.addAttribute("a", "test"); + updatedValues.add(first); + final MultiDocumentEntity> updateResult = db.collection(COLLECTION_NAME) + .updateDocuments(updatedValues, null); + assertThat(updateResult.getDocuments().size(), is(1)); + assertThat(updateResult.getErrors().size(), is(0)); + } + + @Test + public void updateDocumentsEmpty() { + final Collection values = new ArrayList(); + final MultiDocumentEntity> updateResult = db.collection(COLLECTION_NAME) + .updateDocuments(values, null); + assertThat(updateResult.getDocuments().size(), is(0)); + assertThat(updateResult.getErrors().size(), is(0)); + } + + @Test + public void updateDocumentsWithoutKey() { + final Collection values = new ArrayList(); + { + values.add(new BaseDocument("1")); + } + db.collection(COLLECTION_NAME).insertDocuments(values, null); + final Collection updatedValues = new ArrayList(); + for (final BaseDocument i : values) { + i.addAttribute("a", "test"); + updatedValues.add(i); + } + updatedValues.add(new BaseDocument()); + final MultiDocumentEntity> updateResult = db.collection(COLLECTION_NAME) + .updateDocuments(updatedValues, null); + assertThat(updateResult.getDocuments().size(), is(1)); + assertThat(updateResult.getErrors().size(), is(1)); + } + + @Test + public void updateDocumentsJson() { + final Collection values = new ArrayList(); + values.add("{\"_key\":\"1\"}"); + values.add("{\"_key\":\"2\"}"); + db.collection(COLLECTION_NAME).insertDocuments(values); + + final Collection updatedValues = new ArrayList(); + updatedValues.add("{\"_key\":\"1\", \"foo\":\"bar\"}"); + updatedValues.add("{\"_key\":\"2\", \"foo\":\"bar\"}"); + final MultiDocumentEntity> updateResult = db.collection(COLLECTION_NAME) + .updateDocuments(updatedValues); + assertThat(updateResult.getDocuments().size(), is(2)); + assertThat(updateResult.getErrors().size(), is(0)); + } + + @Test + public void replaceDocuments() { + final Collection values = new ArrayList(); + { + values.add(new BaseDocument("1")); + values.add(new BaseDocument("2")); + } + db.collection(COLLECTION_NAME).insertDocuments(values, null); + final Collection updatedValues = new ArrayList(); + for (final BaseDocument i : values) { + i.addAttribute("a", "test"); + updatedValues.add(i); + } + final MultiDocumentEntity> updateResult = db.collection(COLLECTION_NAME) + .replaceDocuments(updatedValues, null); + assertThat(updateResult.getDocuments().size(), is(2)); + assertThat(updateResult.getErrors().size(), is(0)); + } + + @Test + public void replaceDocumentsOne() { + final Collection values = new ArrayList(); + { + final BaseDocument e = new BaseDocument(); + e.setKey("1"); + values.add(e); + } + db.collection(COLLECTION_NAME).insertDocuments(values, null); + final Collection updatedValues = new ArrayList(); + final BaseDocument first = values.iterator().next(); + first.addAttribute("a", "test"); + updatedValues.add(first); + final MultiDocumentEntity> updateResult = db.collection(COLLECTION_NAME) + .updateDocuments(updatedValues, null); + assertThat(updateResult.getDocuments().size(), is(1)); + assertThat(updateResult.getErrors().size(), is(0)); + } + + @Test + public void replaceDocumentsEmpty() { + final Collection values = new ArrayList(); + final MultiDocumentEntity> updateResult = db.collection(COLLECTION_NAME) + .updateDocuments(values, null); + assertThat(updateResult.getDocuments().size(), is(0)); + assertThat(updateResult.getErrors().size(), is(0)); + } + + @Test + public void replaceDocumentsWithoutKey() { + final Collection values = new ArrayList(); + { + values.add(new BaseDocument("1")); + } + db.collection(COLLECTION_NAME).insertDocuments(values, null); + final Collection updatedValues = new ArrayList(); + for (final BaseDocument i : values) { + i.addAttribute("a", "test"); + updatedValues.add(i); + } + updatedValues.add(new BaseDocument()); + final MultiDocumentEntity> updateResult = db.collection(COLLECTION_NAME) + .updateDocuments(updatedValues, null); + assertThat(updateResult.getDocuments().size(), is(1)); + assertThat(updateResult.getErrors().size(), is(1)); + } + + @Test + public void replaceDocumentsJson() { + final Collection values = new ArrayList(); + values.add("{\"_key\":\"1\"}"); + values.add("{\"_key\":\"2\"}"); + db.collection(COLLECTION_NAME).insertDocuments(values); + + final Collection updatedValues = new ArrayList(); + updatedValues.add("{\"_key\":\"1\", \"foo\":\"bar\"}"); + updatedValues.add("{\"_key\":\"2\", \"foo\":\"bar\"}"); + final MultiDocumentEntity> updateResult = db.collection(COLLECTION_NAME) + .replaceDocuments(updatedValues); + assertThat(updateResult.getDocuments().size(), is(2)); + assertThat(updateResult.getErrors().size(), is(0)); + } + + @Test + public void load() { + final CollectionEntity result = db.collection(COLLECTION_NAME).load(); + assertThat(result.getName(), is(COLLECTION_NAME)); + } + + @Test + public void unload() { + final CollectionEntity result = db.collection(COLLECTION_NAME).unload(); + assertThat(result.getName(), is(COLLECTION_NAME)); + } + + @Test + public void getInfo() { + final CollectionEntity result = db.collection(COLLECTION_NAME).getInfo(); + assertThat(result.getName(), is(COLLECTION_NAME)); + } + + @Test + public void getPropeties() { + final CollectionPropertiesEntity result = db.collection(COLLECTION_NAME).getProperties(); + assertThat(result.getName(), is(COLLECTION_NAME)); + assertThat(result.getCount(), is(nullValue())); + } + + @Test + public void changeProperties() { + final String collection = COLLECTION_NAME + "_prop"; + try { + db.createCollection(collection); + final CollectionPropertiesEntity properties = db.collection(collection).getProperties(); + assertThat(properties.getWaitForSync(), is(notNullValue())); + final CollectionPropertiesOptions options = new CollectionPropertiesOptions(); + options.waitForSync(!properties.getWaitForSync()); + options.journalSize(2000000L); + final CollectionPropertiesEntity changedProperties = db.collection(collection).changeProperties(options); + assertThat(changedProperties.getWaitForSync(), is(notNullValue())); + assertThat(changedProperties.getWaitForSync(), is(not(properties.getWaitForSync()))); + } finally { + db.collection(collection).drop(); + } + } + + @Test + public void rename() { + if (arangoDB.getRole() != ServerRole.SINGLE) { + return; + } + final CollectionEntity result = db.collection(COLLECTION_NAME).rename(COLLECTION_NAME + "1"); + assertThat(result, is(notNullValue())); + assertThat(result.getName(), is(COLLECTION_NAME + "1")); + final CollectionEntity info = db.collection(COLLECTION_NAME + "1").getInfo(); + assertThat(info.getName(), is(COLLECTION_NAME + "1")); + try { + db.collection(COLLECTION_NAME).getInfo(); + fail(); + } catch (final ArangoDBException e) { + assertThat(e.getResponseCode(), is(404)); + } + db.collection(COLLECTION_NAME + "1").rename(COLLECTION_NAME); + } + + @Test + public void responsibleShard() { + if (arangoDB.getRole() != ServerRole.COORDINATOR) { + return; + } + if (!requireVersion(3, 5)) { + return; + } + ShardEntity shard = db.collection(COLLECTION_NAME).getResponsibleShard(new BaseDocument("testKey")); + assertThat(shard, is(notNullValue())); + assertThat(shard.getShardId(), is(notNullValue())); + } + + @Test + public void renameDontBreaksCollectionHandler() { + if (arangoDB.getRole() != ServerRole.SINGLE) { + return; + } + try { + final ArangoCollection collection = db.collection(COLLECTION_NAME); + collection.rename(COLLECTION_NAME + "1"); + assertThat(collection.getInfo(), is(notNullValue())); + } finally { + db.collection(COLLECTION_NAME + "1").rename(COLLECTION_NAME); + } + } + + @Test + public void getRevision() { + final CollectionRevisionEntity result = db.collection(COLLECTION_NAME).getRevision(); + assertThat(result, is(notNullValue())); + assertThat(result.getName(), is(COLLECTION_NAME)); + assertThat(result.getRevision(), is(notNullValue())); + } + + @Test + public void keyWithSpecialCharacter() { + final String key = "myKey_-:.@()+,=;$!*'%"; + db.collection(COLLECTION_NAME).insertDocument(new BaseDocument(key)); + final BaseDocument doc = db.collection(COLLECTION_NAME).getDocument(key, BaseDocument.class); + assertThat(doc, is(notNullValue())); + assertThat(doc.getKey(), is(key)); + } + + @Test + public void alreadyUrlEncodedkey() { + final String key = "http%3A%2F%2Fexample.com%2F"; + db.collection(COLLECTION_NAME).insertDocument(new BaseDocument(key)); + final BaseDocument doc = db.collection(COLLECTION_NAME).getDocument(key, BaseDocument.class); + assertThat(doc, is(notNullValue())); + assertThat(doc.getKey(), is(key)); + } + + @Test + public void grantAccessRW() { + try { + arangoDB.createUser("user1", "1234", null); + db.collection(COLLECTION_NAME).grantAccess("user1", Permissions.RW); + } finally { + arangoDB.deleteUser("user1"); + } + } + + @Test + public void grantAccessRO() { + try { + arangoDB.createUser("user1", "1234", null); + db.collection(COLLECTION_NAME).grantAccess("user1", Permissions.RO); + } finally { + arangoDB.deleteUser("user1"); + } + } + + @Test + public void grantAccessNONE() { + try { + arangoDB.createUser("user1", "1234", null); + db.collection(COLLECTION_NAME).grantAccess("user1", Permissions.NONE); + } finally { + arangoDB.deleteUser("user1"); + } + } + + @Test(expected = ArangoDBException.class) + public void grantAccessUserNotFound() { + db.collection(COLLECTION_NAME).grantAccess("user1", Permissions.RW); + } + + @Test + public void revokeAccess() { + try { + arangoDB.createUser("user1", "1234", null); + db.collection(COLLECTION_NAME).grantAccess("user1", Permissions.NONE); + } finally { + arangoDB.deleteUser("user1"); + } + } + + @Test(expected = ArangoDBException.class) + public void revokeAccessUserNotFound() { + db.collection(COLLECTION_NAME).grantAccess("user1", Permissions.NONE); + } + + @Test + public void resetAccess() { + try { + arangoDB.createUser("user1", "1234", null); + db.collection(COLLECTION_NAME).resetAccess("user1"); + } finally { + arangoDB.deleteUser("user1"); + } + } + + @Test(expected = ArangoDBException.class) + public void resetAccessUserNotFound() { + db.collection(COLLECTION_NAME).resetAccess("user1"); + } + + @Test + public void getPermissions() { + assertThat(Permissions.RW, is(db.collection(COLLECTION_NAME).getPermissions("root"))); + } } diff --git a/src/test/java/com/arangodb/ArangoDBTest.java b/src/test/java/com/arangodb/ArangoDBTest.java index a956dd2c7..8852ce25f 100644 --- a/src/test/java/com/arangodb/ArangoDBTest.java +++ b/src/test/java/com/arangodb/ArangoDBTest.java @@ -415,7 +415,6 @@ public void arangoDBException() { } catch (final ArangoDBException e) { assertThat(e.getResponseCode(), is(404)); assertThat(e.getErrorNum(), is(1228)); - assertThat(e.getErrorMessage(), is("database not found")); } } diff --git a/src/test/java/com/arangodb/ArangoDatabaseTest.java b/src/test/java/com/arangodb/ArangoDatabaseTest.java index 47b20050b..dbc5ab9d7 100644 --- a/src/test/java/com/arangodb/ArangoDatabaseTest.java +++ b/src/test/java/com/arangodb/ArangoDatabaseTest.java @@ -57,1463 +57,1385 @@ @RunWith(Parameterized.class) public class ArangoDatabaseTest extends BaseTest { - Logger LOG = LoggerFactory.getLogger(ArangoDatabaseTest.class); - - private static final String COLLECTION_NAME = "db_test"; - private static final String GRAPH_NAME = "graph_test"; - - public ArangoDatabaseTest(final Builder builder) { - super(builder); - } - - @Before - public void setUp() { - try { - ArangoCollection c = db.collection(COLLECTION_NAME); - c.drop(); - } catch (final ArangoDBException e) { - } - - try { - ArangoCollection c = db.collection(COLLECTION_NAME + "1"); - c.drop(); - } catch (final ArangoDBException e) { - } - - try { - ArangoCollection c = db.collection(COLLECTION_NAME + "2"); - c.drop(); - } catch (final ArangoDBException e) { - } - - try { - ArangoCollection c = db.collection(COLLECTION_NAME + "edge"); - c.drop(); - } catch (final ArangoDBException e) { - } - - try { - ArangoCollection c = db.collection(COLLECTION_NAME + "from"); - c.drop(); - } catch (final ArangoDBException e) { - } - - try { - ArangoCollection c = db.collection(COLLECTION_NAME + "to"); - c.drop(); - } catch (final ArangoDBException e) { - } - } - - @Test - public void create() { - try { - final Boolean result = arangoDB.db(BaseTest.TEST_DB + "_1").create(); - assertThat(result, is(true)); - } finally { - try { - arangoDB.db(BaseTest.TEST_DB + "_1").drop(); - } catch (final ArangoDBException e) { - } - } - } - - @Test - public void getVersion() { - final ArangoDBVersion version = db.getVersion(); - assertThat(version, is(notNullValue())); - assertThat(version.getServer(), is(notNullValue())); - assertThat(version.getVersion(), is(notNullValue())); - } - - @Test - public void getEngine() { - final ArangoDBEngine engine = db.getEngine(); - assertThat(engine, is(notNullValue())); - assertThat(engine.getName(), is(notNullValue())); - } - - @Test - public void exists() { - assertThat(db.exists(), is(true)); - assertThat(arangoDB.db("no").exists(), is(false)); - } - - @Test - public void getAccessibleDatabases() { - final Collection dbs = db.getAccessibleDatabases(); - assertThat(dbs, is(notNullValue())); - assertThat(dbs.size(), greaterThan(0)); - assertThat(dbs, hasItem("_system")); - } - - @Test - public void createCollection() { - try { - final CollectionEntity result = db.createCollection(COLLECTION_NAME, null); - assertThat(result, is(notNullValue())); - assertThat(result.getId(), is(notNullValue())); - } finally { - db.collection(COLLECTION_NAME).drop(); - } - } - - @Test - public void createCollectionWithReplicationFactor() { - if (arangoDB.getRole() == ServerRole.SINGLE) { - return; - } - try { - final CollectionEntity result = db - .createCollection(COLLECTION_NAME, new CollectionCreateOptions().replicationFactor(2)); - assertThat(result, is(notNullValue())); - assertThat(result.getId(), is(notNullValue())); - assertThat(db.collection(COLLECTION_NAME).getProperties().getReplicationFactor(), is(2)); - assertThat(db.collection(COLLECTION_NAME).getProperties().getSatellite(), is(nullValue())); - } catch (final ArangoDBException e) { - e.printStackTrace(); - } finally { - db.collection(COLLECTION_NAME).drop(); - } - - } - - @Test - public void createCollectionWithMinReplicationFactor() { - - // if we do not have version at least 3.5+ => exit - if (!requireVersion(3, 5)) { - LOG.info("Skip Test 'createCollectionWithMinReplicationFactor' because feature not implemented yet."); - return; - } - - // if we do not have a cluster => exit - if (arangoDB.getRole() == ServerRole.SINGLE) { - return; - } - - try { - final CollectionEntity result = db.createCollection(COLLECTION_NAME, - new CollectionCreateOptions().replicationFactor(2).minReplicationFactor(2)); - assertThat(result, is(notNullValue())); - assertThat(result.getId(), is(notNullValue())); - assertThat(db.collection(COLLECTION_NAME).getProperties().getReplicationFactor(), is(2)); - assertThat(db.collection(COLLECTION_NAME).getProperties().getMinReplicationFactor(), is(2)); - assertThat(db.collection(COLLECTION_NAME).getProperties().getSatellite(), is(nullValue())); - db.collection(COLLECTION_NAME).drop(); - } catch (final ArangoDBException e) { - e.printStackTrace(); - } - - } - - @Test - public void createSatelliteCollection() { - if (arangoDB.getVersion().getLicense() == License.COMMUNITY) { - LOG.info("Skip Test 'createSatelliteCollection' on COMMUNITY VERSION"); - return; - } - - if (arangoDB.getRole() == ServerRole.SINGLE) { - LOG.info("Skip Test 'createSatelliteCollection' on SINGLE SERVER"); - return; - } - - try { - - final CollectionEntity result = db - .createCollection(COLLECTION_NAME, new CollectionCreateOptions().satellite(true)); - - assertThat(result, is(notNullValue())); - assertThat(result.getId(), is(notNullValue())); - assertThat(db.collection(COLLECTION_NAME).getProperties().getReplicationFactor(), is(nullValue())); - assertThat(db.collection(COLLECTION_NAME).getProperties().getSatellite(), is(true)); - - } finally { - db.collection(COLLECTION_NAME).drop(); - } - } - - @Test - public void createCollectionWithNumberOfShards() { - if (arangoDB.getRole() == ServerRole.SINGLE) { - return; - } - - try { - - final CollectionEntity result = db - .createCollection(COLLECTION_NAME, new CollectionCreateOptions().numberOfShards(2)); - - assertThat(result, is(notNullValue())); - assertThat(result.getId(), is(notNullValue())); - assertThat(db.collection(COLLECTION_NAME).getProperties().getNumberOfShards(), is(2)); - - } finally { - db.collection(COLLECTION_NAME).drop(); - } - } - - @Test - public void createCollectionWithShardingStrategys() { - if (!requireVersion(3, 4)) { - LOG.info("Skip Test 'createCollectionWithShardingStrategys' because feature not implemented yet."); - return; - } - - if (arangoDB.getRole() == ServerRole.SINGLE) { - LOG.info("Skip Test 'createCollectionWithShardingStrategys' on SINGLE SERVER"); - return; - } - - try { - final CollectionEntity result = db.createCollection(COLLECTION_NAME, new CollectionCreateOptions() - .shardingStrategy(ShardingStrategy.COMMUNITY_COMPAT.getInternalName())); - - assertThat(result, is(notNullValue())); - assertThat(result.getId(), is(notNullValue())); - assertThat(db.collection(COLLECTION_NAME).getProperties().getShardingStrategy(), - is(ShardingStrategy.COMMUNITY_COMPAT.getInternalName())); - - } catch (ArangoDBException e) { - System.out.println(e); - assertTrue(false); - } finally { - db.collection(COLLECTION_NAME).drop(); - } - } - - @Test - public void createCollectionWithSmartJoinAttribute() { - if (!requireVersion(3, 5)) { - LOG.info("Skip Test 'createCollectionWithSmartJoinAttribute' because feature not implemented yet."); - return; - } - - if (arangoDB.getVersion().getLicense() == License.COMMUNITY) { - LOG.info("Skip Test 'createCollectionWithSmartJoinAttribute' on COMMUNITY SERVER"); - return; - } - - if (arangoDB.getRole() == ServerRole.SINGLE) { - LOG.info("Skip Test 'createCollectionWithSmartJoinAttribute' on SINGLE SERVER"); - return; - } - - try { - final CollectionEntity result = db.createCollection(COLLECTION_NAME, - new CollectionCreateOptions().smartJoinAttribute("test123").shardKeys("_key:")); - assertThat(result, is(notNullValue())); - assertThat(result.getId(), is(notNullValue())); - assertThat(db.collection(COLLECTION_NAME).getProperties().getSmartJoinAttribute(), is("test123")); - - } catch (Exception e) { - System.out.println(e); - assertTrue(false); - } finally { - try { - db.collection(COLLECTION_NAME).drop(); - } catch (Exception e) { - System.out.println(e); - } - } - } - - @Test - public void createCollectionWithSmartJoinAttributeWrong() { - if (!requireVersion(3, 5)) { - LOG.info("Skip Test 'createCollectionWithSmartJoinAttributeWrong' because feature not implemented yet."); - return; - } - - if (arangoDB.getVersion().getLicense() == License.COMMUNITY) { - LOG.info("Skip Test 'createCollectionWithSmartJoinAttributeWrong' on COMMUNITY SERVER"); - return; - } - - if (arangoDB.getRole() == ServerRole.SINGLE) { - LOG.info("Skip Test 'createCollectionWithSmartJoinAttributeWrong' on SINGLE SERVER"); - return; - } - - try { - db.createCollection(COLLECTION_NAME, new CollectionCreateOptions().smartJoinAttribute("test123")); - } catch (ArangoDBException e) { - assertThat(e.getErrorNum(), is(4006)); - // TODO: - // at the moment older server versions reply with response code 500, which is a misbehavior - // when the fix has been backported to all the supported db versions uncomment the following: - // assertThat(e.getResponseCode(), is(400)); - } finally { - try { - db.collection(COLLECTION_NAME).drop(); - assertTrue(false); - } catch (Exception e) { - System.out.println(e); - } - } - } - - @Test - public void createCollectionWithNumberOfShardsAndShardKey() { - if (arangoDB.getRole() == ServerRole.SINGLE) { - LOG.info("Skip Test 'createCollectionWithNumberOfShardsAndShardKey' on SINGLE SERVER"); - return; - } - - try { - final CollectionEntity result = db - .createCollection(COLLECTION_NAME, new CollectionCreateOptions().numberOfShards(2).shardKeys("a")); - assertThat(result, is(notNullValue())); - assertThat(result.getId(), is(notNullValue())); - final CollectionPropertiesEntity properties = db.collection(COLLECTION_NAME).getProperties(); - assertThat(properties.getNumberOfShards(), is(2)); - assertThat(properties.getShardKeys().size(), is(1)); - } finally { - db.collection(COLLECTION_NAME).drop(); - } - } - - @Test - public void createCollectionWithNumberOfShardsAndShardKeys() { - if (arangoDB.getRole() == ServerRole.SINGLE) { - LOG.info("Skip Test 'createCollectionWithNumberOfShardsAndShardKeys' on SINGLE SERVER"); - return; - } - - try { - final CollectionEntity result = db.createCollection(COLLECTION_NAME, - new CollectionCreateOptions().numberOfShards(2).shardKeys("a", "b")); - assertThat(result, is(notNullValue())); - assertThat(result.getId(), is(notNullValue())); - final CollectionPropertiesEntity properties = db.collection(COLLECTION_NAME).getProperties(); - assertThat(properties.getNumberOfShards(), is(2)); - assertThat(properties.getShardKeys().size(), is(2)); - } finally { - db.collection(COLLECTION_NAME).drop(); - } - } - - @Test - public void createCollectionWithDistributeShardsLike() { - - if (arangoDB.getVersion().getLicense() == License.ENTERPRISE && arangoDB.getRole() != ServerRole.SINGLE) { - - final Integer numberOfShards = 3; - - db.createCollection(COLLECTION_NAME, new CollectionCreateOptions().numberOfShards(numberOfShards)); - db.createCollection(COLLECTION_NAME + "2", - new CollectionCreateOptions().distributeShardsLike(COLLECTION_NAME)); - - assertThat(db.collection(COLLECTION_NAME).getProperties().getNumberOfShards(), is(numberOfShards)); - assertThat(db.collection(COLLECTION_NAME + "2").getProperties().getNumberOfShards(), is(numberOfShards)); - } - - } - - @Test - public void deleteCollection() { - db.createCollection(COLLECTION_NAME, null); - db.collection(COLLECTION_NAME).drop(); - try { - db.collection(COLLECTION_NAME).getInfo(); - fail(); - } catch (final ArangoDBException e) { - } - } - - @Test - public void deleteSystemCollection() { - - if (arangoDB.getRole() != ServerRole.SINGLE) { - return; - } - - final String name = "_system_test"; - db.createCollection(name, new CollectionCreateOptions().isSystem(true)); - db.collection(name).drop(true); - try { - db.collection(name).getInfo(); - fail(); - } catch (final ArangoDBException e) { - } - } - - @Test - public void deleteSystemCollectionFail() { - if (arangoDB.getRole() != ServerRole.SINGLE) { - return; - } - final String name = "_system_test"; - db.createCollection(name, new CollectionCreateOptions().isSystem(true)); - try { - db.collection(name).drop(); - fail(); - } catch (final ArangoDBException e) { - } - db.collection(name).drop(true); - try { - db.collection(name).getInfo(); - fail(); - } catch (final ArangoDBException e) { - } - } - - @Test - public void getIndex() { - try { - db.createCollection(COLLECTION_NAME, null); - final Collection fields = new ArrayList(); - fields.add("a"); - final IndexEntity createResult = db.collection(COLLECTION_NAME).ensureHashIndex(fields, null); - final IndexEntity readResult = db.getIndex(createResult.getId()); - assertThat(readResult.getId(), is(createResult.getId())); - assertThat(readResult.getType(), is(createResult.getType())); - } finally { - db.collection(COLLECTION_NAME).drop(); - } - } - - @Test - public void deleteIndex() { - try { - db.createCollection(COLLECTION_NAME, null); - final Collection fields = new ArrayList(); - fields.add("a"); - final IndexEntity createResult = db.collection(COLLECTION_NAME).ensureHashIndex(fields, null); - final String id = db.deleteIndex(createResult.getId()); - assertThat(id, is(createResult.getId())); - try { - db.getIndex(id); - fail(); - } catch (final ArangoDBException e) { - } - } finally { - db.collection(COLLECTION_NAME).drop(); - } - } - - @Test - public void getCollections() { - try { - final Collection systemCollections = db.getCollections(null); - db.createCollection(COLLECTION_NAME + "1", null); - db.createCollection(COLLECTION_NAME + "2", null); - final Collection collections = db.getCollections(null); - assertThat(collections.size(), is(2 + systemCollections.size())); - assertThat(collections, is(notNullValue())); - } finally { - db.collection(COLLECTION_NAME + "1").drop(); - db.collection(COLLECTION_NAME + "2").drop(); - } - } - - @Test - public void getCollectionsExcludeSystem() { - try { - final CollectionsReadOptions options = new CollectionsReadOptions().excludeSystem(true); - final Collection nonSystemCollections = db.getCollections(options); - - assertThat(nonSystemCollections.size(), is(0)); - db.createCollection(COLLECTION_NAME + "1", null); - db.createCollection(COLLECTION_NAME + "2", null); - final Collection newCollections = db.getCollections(options); - assertThat(newCollections.size(), is(2)); - assertThat(newCollections, is(notNullValue())); - } catch (final ArangoDBException e) { - System.out.println(e.getErrorMessage()); - } finally { - try { - db.collection(COLLECTION_NAME + "1").drop(); - db.collection(COLLECTION_NAME + "2").drop(); - } catch (final ArangoDBException e) { - } - } - } - - @Test - public void grantAccess() { - try { - arangoDB.createUser("user1", "1234", null); - db.grantAccess("user1"); - } finally { - arangoDB.deleteUser("user1"); - } - } - - @Test - public void grantAccessRW() { - try { - arangoDB.createUser("user1", "1234", null); - db.grantAccess("user1", Permissions.RW); - } finally { - arangoDB.deleteUser("user1"); - } - } - - @Test - public void grantAccessRO() { - try { - arangoDB.createUser("user1", "1234", null); - db.grantAccess("user1", Permissions.RO); - } finally { - arangoDB.deleteUser("user1"); - } - } - - @Test - public void grantAccessNONE() { - try { - arangoDB.createUser("user1", "1234", null); - db.grantAccess("user1", Permissions.NONE); - } finally { - arangoDB.deleteUser("user1"); - } - } - - @Test(expected = ArangoDBException.class) - public void grantAccessUserNotFound() { - db.grantAccess("user1", Permissions.RW); - } - - @Test - public void revokeAccess() { - try { - arangoDB.createUser("user1", "1234", null); - db.revokeAccess("user1"); - } finally { - arangoDB.deleteUser("user1"); - } - } - - @Test(expected = ArangoDBException.class) - public void revokeAccessUserNotFound() { - db.revokeAccess("user1"); - } - - @Test - public void resetAccess() { - try { - arangoDB.createUser("user1", "1234", null); - db.resetAccess("user1"); - } finally { - arangoDB.deleteUser("user1"); - } - } - - @Test(expected = ArangoDBException.class) - public void resetAccessUserNotFound() { - db.resetAccess("user1"); - } - - @Test - public void grantDefaultCollectionAccess() { - try { - arangoDB.createUser("user1", "1234"); - db.grantDefaultCollectionAccess("user1", Permissions.RW); - } finally { - arangoDB.deleteUser("user1"); - } - } - - @Test - public void getPermissions() { - assertThat(Permissions.RW, is(db.getPermissions("root"))); - } - - @Test - public void query() { - try { - db.createCollection(COLLECTION_NAME, null); - for (int i = 0; i < 10; i++) { - db.collection(COLLECTION_NAME).insertDocument(new BaseDocument(), null); - } - final ArangoCursor cursor = db.query("for i in db_test return i._id", null, null, String.class); - assertThat(cursor, is(notNullValue())); - for (int i = 0; i < 10; i++, cursor.next()) { - assertThat(cursor.hasNext(), is(i != 10)); - } - } finally { - db.collection(COLLECTION_NAME).drop(); - } - } - - @Test - public void queryForEach() { - try { - db.createCollection(COLLECTION_NAME, null); - for (int i = 0; i < 10; i++) { - db.collection(COLLECTION_NAME).insertDocument(new BaseDocument(), null); - } - final ArangoCursor cursor = db.query("for i in db_test return i._id", null, null, String.class); - assertThat(cursor, is(notNullValue())); - final AtomicInteger i = new AtomicInteger(0); - for (; cursor.hasNext(); cursor.next()) { - i.incrementAndGet(); - } - assertThat(i.get(), is(10)); - } finally { - db.collection(COLLECTION_NAME).drop(); - } - } - - @Test - public void queryIterate() { - try { - db.createCollection(COLLECTION_NAME, null); - for (int i = 0; i < 10; i++) { - db.collection(COLLECTION_NAME).insertDocument(new BaseDocument(), null); - } - final ArangoCursor cursor = db.query("for i in db_test return i._id", null, null, String.class); - assertThat(cursor, is(notNullValue())); - final AtomicInteger i = new AtomicInteger(0); - for (; cursor.hasNext(); cursor.next()) { - i.incrementAndGet(); - } - assertThat(i.get(), is(10)); - } finally { - db.collection(COLLECTION_NAME).drop(); - } - } - - @Test - public void queryWithCount() { - try { - db.createCollection(COLLECTION_NAME, null); - for (int i = 0; i < 10; i++) { - db.collection(COLLECTION_NAME).insertDocument(new BaseDocument(), null); - } - - final ArangoCursor cursor = db - .query("for i in db_test Limit 6 return i._id", null, new AqlQueryOptions().count(true), - String.class); - assertThat(cursor, is(notNullValue())); - for (int i = 0; i < 6; i++, cursor.next()) { - assertThat(cursor.hasNext(), is(i != 6)); - } - assertThat(cursor.getCount(), is(6)); - - } finally { - db.collection(COLLECTION_NAME).drop(); - } - } - - @Test - public void queryWithLimitAndFullCount() { - try { - db.createCollection(COLLECTION_NAME, null); - for (int i = 0; i < 10; i++) { - db.collection(COLLECTION_NAME).insertDocument(new BaseDocument(), null); - } - - final ArangoCursor cursor = db - .query("for i in db_test Limit 5 return i._id", null, new AqlQueryOptions().fullCount(true), - String.class); - assertThat(cursor, is(notNullValue())); - for (int i = 0; i < 5; i++, cursor.next()) { - assertThat(cursor.hasNext(), is(i != 5)); - } - assertThat(cursor.getStats(), is(notNullValue())); - assertThat(cursor.getStats().getFullCount(), is(10L)); - - } finally { - db.collection(COLLECTION_NAME).drop(); - } - } - - @Test - public void queryWithBatchSize() { - try { - db.createCollection(COLLECTION_NAME, null); - for (int i = 0; i < 10; i++) { - db.collection(COLLECTION_NAME).insertDocument(new BaseDocument(), null); - } - - final ArangoCursor cursor = db - .query("for i in db_test return i._id", null, new AqlQueryOptions().batchSize(5).count(true), - String.class); - - assertThat(cursor, is(notNullValue())); - for (int i = 0; i < 10; i++, cursor.next()) { - assertThat(cursor.hasNext(), is(i != 10)); - } - } catch (final ArangoDBException e) { - System.out.println(e.getErrorMessage()); - System.out.println(e.getErrorNum()); - } finally { - db.collection(COLLECTION_NAME).drop(); - } - } - - @Test - public void queryIterateWithBatchSize() { - try { - db.createCollection(COLLECTION_NAME, null); - for (int i = 0; i < 10; i++) { - db.collection(COLLECTION_NAME).insertDocument(new BaseDocument(), null); - } - - final ArangoCursor cursor = db - .query("for i in db_test return i._id", null, new AqlQueryOptions().batchSize(5).count(true), - String.class); - - assertThat(cursor, is(notNullValue())); - final AtomicInteger i = new AtomicInteger(0); - for (; cursor.hasNext(); cursor.next()) { - i.incrementAndGet(); - } - assertThat(i.get(), is(10)); - } finally { - db.collection(COLLECTION_NAME).drop(); - } - } - - /** - * ignored. takes to long - */ - @Test - @Ignore - public void queryWithTTL() throws InterruptedException { - // set TTL to 1 seconds and get the second batch after 2 seconds! - final int ttl = 1; - final int wait = 2; - try { - db.createCollection(COLLECTION_NAME, null); - for (int i = 0; i < 10; i++) { - db.collection(COLLECTION_NAME).insertDocument(new BaseDocument(), null); - } - - final ArangoCursor cursor = db - .query("for i in db_test return i._id", null, new AqlQueryOptions().batchSize(5).ttl(ttl), - String.class); - - assertThat(cursor, is(notNullValue())); - - for (int i = 0; i < 10; i++, cursor.next()) { - assertThat(cursor.hasNext(), is(i != 10)); - if (i == 1) { - Thread.sleep(wait * 1000); - } - } - fail("this should fail"); - } catch (final ArangoDBException ex) { - assertThat(ex.getMessage(), is("Response: 404, Error: 1600 - cursor not found")); - } finally { - db.collection(COLLECTION_NAME).drop(); - } - } - - @Test - public void changeQueryCache() { - try { - QueryCachePropertiesEntity properties = db.getQueryCacheProperties(); - assertThat(properties, is(notNullValue())); - assertThat(properties.getMode(), is(CacheMode.off)); - assertThat(properties.getMaxResults(), greaterThan(0L)); - - properties.setMode(CacheMode.on); - properties = db.setQueryCacheProperties(properties); - assertThat(properties, is(notNullValue())); - assertThat(properties.getMode(), is(CacheMode.on)); - - properties = db.getQueryCacheProperties(); - assertThat(properties.getMode(), is(CacheMode.on)); - } finally { - final QueryCachePropertiesEntity properties = new QueryCachePropertiesEntity(); - properties.setMode(CacheMode.off); - db.setQueryCacheProperties(properties); - } - } - - @Test - public void queryWithCache() throws InterruptedException { - if (arangoDB.getRole() != ServerRole.SINGLE) { - return; - } - try { - db.createCollection(COLLECTION_NAME, null); - for (int i = 0; i < 10; i++) { - db.collection(COLLECTION_NAME).insertDocument(new BaseDocument(), null); - } - - final QueryCachePropertiesEntity properties = new QueryCachePropertiesEntity(); - properties.setMode(CacheMode.on); - db.setQueryCacheProperties(properties); - - final ArangoCursor cursor = db - .query("FOR t IN db_test FILTER t.age >= 10 SORT t.age RETURN t._id", null, - new AqlQueryOptions().cache(true), String.class); - - assertThat(cursor, is(notNullValue())); - assertThat(cursor.isCached(), is(false)); - - final ArangoCursor cachedCursor = db - .query("FOR t IN db_test FILTER t.age >= 10 SORT t.age RETURN t._id", null, - new AqlQueryOptions().cache(true), String.class); - - assertThat(cachedCursor, is(notNullValue())); - assertThat(cachedCursor.isCached(), is(true)); - - } finally { - db.collection(COLLECTION_NAME).drop(); - final QueryCachePropertiesEntity properties = new QueryCachePropertiesEntity(); - properties.setMode(CacheMode.off); - db.setQueryCacheProperties(properties); - } - } - - @Test - public void queryWithMemoryLimit() { - try { - db.query("RETURN 'bla'", null, new AqlQueryOptions().memoryLimit(1L), String.class); - fail(); - } catch (final ArangoDBException e) { - assertThat(e.getErrorNum(), is(32)); - } - } - - @Test(expected = ArangoDBException.class) - public void queryWithFailOnWarningTrue() { - db.query("RETURN 1 / 0", null, new AqlQueryOptions().failOnWarning(true), String.class); - } - - @Test - public void queryWithFailOnWarningFalse() { - final ArangoCursor cursor = db - .query("RETURN 1 / 0", null, new AqlQueryOptions().failOnWarning(false), String.class); - assertThat(cursor.next(), is("null")); - } - - @Test - public void queryWithMaxWarningCount() { - final ArangoCursor cursorWithWarnings = db - .query("RETURN 1 / 0", null, new AqlQueryOptions(), String.class); - assertThat(cursorWithWarnings.getWarnings().size(), is(1)); - final ArangoCursor cursorWithLimitedWarnings = db - .query("RETURN 1 / 0", null, new AqlQueryOptions().maxWarningCount(0L), String.class); - final Collection warnings = cursorWithLimitedWarnings.getWarnings(); - if (warnings != null) { - assertThat(warnings.size(), is(0)); - } - } - - @Test - public void queryCursor() { - try { - db.createCollection(COLLECTION_NAME, null); - final int numbDocs = 10; - for (int i = 0; i < numbDocs; i++) { - db.collection(COLLECTION_NAME).insertDocument(new BaseDocument(), null); - } - - final int batchSize = 5; - final ArangoCursor cursor = db.query("for i in db_test return i._id", null, - new AqlQueryOptions().batchSize(batchSize).count(true), String.class); - assertThat(cursor, is(notNullValue())); - assertThat(cursor.getCount(), is(numbDocs)); - - final ArangoCursor cursor2 = db.cursor(cursor.getId(), String.class); - assertThat(cursor2, is(notNullValue())); - assertThat(cursor2.getCount(), is(numbDocs)); - assertThat(cursor2.hasNext(), is(true)); - - for (int i = 0; i < batchSize; i++, cursor.next()) { - assertThat(cursor.hasNext(), is(i != batchSize)); - } - } finally { - db.collection(COLLECTION_NAME).drop(); - } - } - - @Test - public void changeQueryTrackingProperties() { - try { - QueryTrackingPropertiesEntity properties = db.getQueryTrackingProperties(); - assertThat(properties, is(notNullValue())); - assertThat(properties.getEnabled(), is(true)); - assertThat(properties.getTrackSlowQueries(), is(true)); - assertThat(properties.getMaxQueryStringLength(), greaterThan(0L)); - assertThat(properties.getMaxSlowQueries(), greaterThan(0L)); - assertThat(properties.getSlowQueryThreshold(), greaterThan(0L)); - properties.setEnabled(false); - properties = db.setQueryTrackingProperties(properties); - assertThat(properties, is(notNullValue())); - assertThat(properties.getEnabled(), is(false)); - properties = db.getQueryTrackingProperties(); - assertThat(properties.getEnabled(), is(false)); - } finally { - final QueryTrackingPropertiesEntity properties = new QueryTrackingPropertiesEntity(); - properties.setEnabled(true); - db.setQueryTrackingProperties(properties); - } - } - - @Test - public void queryWithBindVars() throws InterruptedException { - try { - db.createCollection(COLLECTION_NAME, null); - for (int i = 0; i < 10; i++) { - final BaseDocument baseDocument = new BaseDocument(); - baseDocument.addAttribute("age", 20 + i); - db.collection(COLLECTION_NAME).insertDocument(baseDocument, null); - } - final Map bindVars = new HashMap(); - bindVars.put("@coll", COLLECTION_NAME); - bindVars.put("age", 25); - - final ArangoCursor cursor = db - .query("FOR t IN @@coll FILTER t.age >= @age SORT t.age RETURN t._id", bindVars, null, - String.class); - - assertThat(cursor, is(notNullValue())); - - for (int i = 0; i < 5; i++, cursor.next()) { - assertThat(cursor.hasNext(), is(i != 5)); - } - - } finally { - db.collection(COLLECTION_NAME).drop(); - } - } - - @Test - public void queryWithWarning() { - final ArangoCursor cursor = arangoDB.db().query("return 1/0", null, null, String.class); - - assertThat(cursor, is(notNullValue())); - assertThat(cursor.getWarnings(), is(notNullValue())); - } - - @Test - public void queryStream() { - if (requireVersion(3, 4)) { - final ArangoCursor cursor = db - .query("FOR i IN 1..2 RETURN i", null, new AqlQueryOptions().stream(true).count(true), - VPackSlice.class); - assertThat(cursor, is(notNullValue())); - assertThat(cursor.getCount(), is(nullValue())); - } - } - - @Test - public void queryClose() throws IOException { - final ArangoCursor cursor = arangoDB.db() - .query("for i in 1..2 return i", null, new AqlQueryOptions().batchSize(1), String.class); - cursor.close(); - int count = 0; - try { - for (; cursor.hasNext(); cursor.next(), count++) { - } - fail(); - } catch (final ArangoDBException e) { - assertThat(count, is(1)); - } - - } - - @Test - public void queryNoResults() throws IOException { - try { - db.createCollection(COLLECTION_NAME); - final ArangoCursor cursor = db - .query("FOR i IN @@col RETURN i", new MapBuilder().put("@col", COLLECTION_NAME).get(), null, - BaseDocument.class); - cursor.close(); - } finally { - db.collection(COLLECTION_NAME).drop(); - } - } - - @Test - public void queryWithNullBindParam() throws IOException { - try { - db.createCollection(COLLECTION_NAME); - final ArangoCursor cursor = db.query("FOR i IN @@col FILTER i.test == @test RETURN i", - new MapBuilder().put("@col", COLLECTION_NAME).put("test", null).get(), null, BaseDocument.class); - cursor.close(); - } finally { - db.collection(COLLECTION_NAME).drop(); - } - } - - @Test - public void queryAllowDirtyRead() throws IOException { - try { - db.createCollection(COLLECTION_NAME); - final ArangoCursor cursor = db.query("FOR i IN @@col FILTER i.test == @test RETURN i", - new MapBuilder().put("@col", COLLECTION_NAME).put("test", null).get(), - new AqlQueryOptions().allowDirtyRead(true), BaseDocument.class); - cursor.close(); - } catch (ArangoDBException e) { - System.out.println(e); - } finally { - db.collection(COLLECTION_NAME).drop(); - } - } - - @Test - public void explainQuery() { - final AqlExecutionExplainEntity explain = arangoDB.db().explainQuery("for i in 1..1 return i", null, null); - assertThat(explain, is(notNullValue())); - assertThat(explain.getPlan(), is(notNullValue())); - assertThat(explain.getPlans(), is(nullValue())); - final ExecutionPlan plan = explain.getPlan(); - assertThat(plan.getCollections().size(), is(0)); - assertThat(plan.getEstimatedCost(), greaterThan(0)); - assertThat(plan.getEstimatedNrItems(), greaterThan(0)); - assertThat(plan.getVariables().size(), is(2)); - assertThat(plan.getNodes().size(), is(greaterThan(0))); - } - - @Test - public void parseQuery() { - final AqlParseEntity parse = arangoDB.db().parseQuery("for i in 1..1 return i"); - assertThat(parse, is(notNullValue())); - assertThat(parse.getBindVars(), is(empty())); - assertThat(parse.getCollections().size(), is(0)); - assertThat(parse.getAst().size(), is(1)); - } - - @Test - @Ignore - public void getCurrentlyRunningQueries() throws InterruptedException, ExecutionException { - final Thread t = new Thread() { - @Override - public void run() { - super.run(); - db.query("return sleep(0.2)", null, null, Void.class); - } - }; - t.start(); - Thread.sleep(100); - try { - final Collection currentlyRunningQueries = db.getCurrentlyRunningQueries(); - assertThat(currentlyRunningQueries, is(notNullValue())); - assertThat(currentlyRunningQueries.size(), is(1)); - final QueryEntity queryEntity = currentlyRunningQueries.iterator().next(); - assertThat(queryEntity.getQuery(), is("return sleep(0.2)")); - assertThat(queryEntity.getState(), is(QueryExecutionState.EXECUTING)); - } finally { - t.join(); - } - } - - @Test - @Ignore - public void getAndClearSlowQueries() throws InterruptedException, ExecutionException { - final QueryTrackingPropertiesEntity properties = db.getQueryTrackingProperties(); - final Long slowQueryThreshold = properties.getSlowQueryThreshold(); - try { - properties.setSlowQueryThreshold(1L); - db.setQueryTrackingProperties(properties); - - db.query("return sleep(1.1)", null, null, Void.class); - final Collection slowQueries = db.getSlowQueries(); - assertThat(slowQueries, is(notNullValue())); - assertThat(slowQueries.size(), is(1)); - final QueryEntity queryEntity = slowQueries.iterator().next(); - assertThat(queryEntity.getQuery(), is("return sleep(1.1)")); - - db.clearSlowQueries(); - assertThat(db.getSlowQueries().size(), is(0)); - } finally { - properties.setSlowQueryThreshold(slowQueryThreshold); - db.setQueryTrackingProperties(properties); - } - } - - @Test - @Ignore - public void killQuery() throws InterruptedException, ExecutionException { - final Thread t = new Thread() { - @Override - public void run() { - super.run(); - try { - db.query("return sleep(0.2)", null, null, Void.class); - fail(); - } catch (final ArangoDBException e) { - } - } - }; - t.start(); - Thread.sleep(100); - final Collection currentlyRunningQueries = db.getCurrentlyRunningQueries(); - assertThat(currentlyRunningQueries, is(notNullValue())); - assertThat(currentlyRunningQueries.size(), is(1)); - - final QueryEntity queryEntity = currentlyRunningQueries.iterator().next(); - db.killQuery(queryEntity.getId()); - } - - @Test - public void createGetDeleteAqlFunction() { - final Collection aqlFunctionsInitial = db.getAqlFunctions(null); - assertThat(aqlFunctionsInitial, is(empty())); - try { - db.createAqlFunction("myfunctions::temperature::celsiustofahrenheit", - "function (celsius) { return celsius * 1.8 + 32; }", null); - - final Collection aqlFunctions = db.getAqlFunctions(null); - assertThat(aqlFunctions.size(), is(greaterThan(aqlFunctionsInitial.size()))); - } finally { - final Integer deleteCount = db.deleteAqlFunction("myfunctions::temperature::celsiustofahrenheit", null); - // compatibility with ArangoDB < 3.4 - if (requireVersion(3, 4)) { - assertThat(deleteCount, is(1)); - } else { - assertThat(deleteCount, is(nullValue())); - } - final Collection aqlFunctions = db.getAqlFunctions(null); - assertThat(aqlFunctions.size(), is(aqlFunctionsInitial.size())); - } - } - - @Test - public void createGetDeleteAqlFunctionWithNamespace() { - final Collection aqlFunctionsInitial = db.getAqlFunctions(null); - assertThat(aqlFunctionsInitial, is(empty())); - try { - db.createAqlFunction("myfunctions::temperature::celsiustofahrenheit1", - "function (celsius) { return celsius * 1.8 + 32; }", null); - db.createAqlFunction("myfunctions::temperature::celsiustofahrenheit2", - "function (celsius) { return celsius * 1.8 + 32; }", null); - - } finally { - final Integer deleteCount = db - .deleteAqlFunction("myfunctions::temperature", new AqlFunctionDeleteOptions().group(true)); - // compatibility with ArangoDB < 3.4 - if (requireVersion(3, 4)) { - assertThat(deleteCount, is(2)); - } else { - assertThat(deleteCount, is(nullValue())); - } - final Collection aqlFunctions = db.getAqlFunctions(null); - assertThat(aqlFunctions.size(), is(aqlFunctionsInitial.size())); - } - } - - @Test - public void createGraph() { - try { - final GraphEntity result = db.createGraph(GRAPH_NAME, null, null); - assertThat(result, is(notNullValue())); - assertThat(result.getName(), is(GRAPH_NAME)); - } finally { - db.graph(GRAPH_NAME).drop(); - } - } - - @Test - public void createGraphReplicationFaktor() { - if (arangoDB.getRole() == ServerRole.SINGLE) { - return; - } - try { - final String edgeCollection = COLLECTION_NAME + "edge"; - final String fromCollection = COLLECTION_NAME + "from"; - final String toCollection = COLLECTION_NAME + "to"; - final Collection edgeDefinitions = Arrays - .asList(new EdgeDefinition().collection(edgeCollection).from(fromCollection).to(toCollection)); - final GraphEntity result = db - .createGraph(GRAPH_NAME, edgeDefinitions, new GraphCreateOptions().replicationFactor(2)); - assertThat(result, is(notNullValue())); - for (final String collection : Arrays.asList(edgeCollection, fromCollection, toCollection)) { - final CollectionPropertiesEntity properties = db.collection(collection).getProperties(); - assertThat(properties.getReplicationFactor(), is(2)); - } - } finally { - db.graph(GRAPH_NAME).drop(); - } - } - - @Test - public void createGraphNumberOfShards() { - if (arangoDB.getRole() == ServerRole.SINGLE) { - return; - } - try { - final String edgeCollection = COLLECTION_NAME + "edge"; - final String fromCollection = COLLECTION_NAME + "from"; - final String toCollection = COLLECTION_NAME + "to"; - final Collection edgeDefinitions = Arrays - .asList(new EdgeDefinition().collection(edgeCollection).from(fromCollection).to(toCollection)); - final GraphEntity result = db - .createGraph(GRAPH_NAME, edgeDefinitions, new GraphCreateOptions().numberOfShards(2)); - assertThat(result, is(notNullValue())); - for (final String collection : Arrays.asList(edgeCollection, fromCollection, toCollection)) { - final CollectionPropertiesEntity properties = db.collection(collection).getProperties(); - assertThat(properties.getNumberOfShards(), is(2)); - } - } finally { - db.graph(GRAPH_NAME).drop(); - } - } - - @Test - public void getGraphs() { - try { - db.createGraph(GRAPH_NAME, null, null); - final Collection graphs = db.getGraphs(); - assertThat(graphs, is(notNullValue())); - assertThat(graphs.size(), is(1)); - assertThat(graphs.iterator().next().getName(), is(GRAPH_NAME)); - } finally { - db.graph(GRAPH_NAME).drop(); - } - } - - @Test - public void transactionString() { - final TransactionOptions options = new TransactionOptions().params("test"); - final String result = db.transaction("function (params) {return params;}", String.class, options); - assertThat(result, is("test")); - } - - @Test - public void transactionNumber() { - final TransactionOptions options = new TransactionOptions().params(5); - final Integer result = db.transaction("function (params) {return params;}", Integer.class, options); - assertThat(result, is(5)); - } - - @Test - public void transactionVPack() throws VPackException { - final TransactionOptions options = new TransactionOptions().params(new VPackBuilder().add("test").slice()); - final VPackSlice result = db.transaction("function (params) {return params;}", VPackSlice.class, options); - assertThat(result.isString(), is(true)); - assertThat(result.getAsString(), is("test")); - } - - @Test - public void transactionVPackObject() throws VPackException { - final VPackSlice params = new VPackBuilder().add(ValueType.OBJECT).add("foo", "hello").add("bar", "world") - .close().slice(); - final TransactionOptions options = new TransactionOptions().params(params); - final String result = db - .transaction("function (params) { return params['foo'] + ' ' + params['bar'];}", String.class, options); - assertThat(result, is("hello world")); - } - - @Test - public void transactionVPackArray() throws VPackException { - final VPackSlice params = new VPackBuilder().add(ValueType.ARRAY).add("hello").add("world").close().slice(); - final TransactionOptions options = new TransactionOptions().params(params); - final String result = db - .transaction("function (params) { return params[0] + ' ' + params[1];}", String.class, options); - assertThat(result, is("hello world")); - } - - @Test - public void transactionMap() { - final Map params = new MapBuilder().put("foo", "hello").put("bar", "world").get(); - final TransactionOptions options = new TransactionOptions().params(params); - final String result = db - .transaction("function (params) { return params['foo'] + ' ' + params['bar'];}", String.class, options); - assertThat(result, is("hello world")); - } - - @Test - public void transactionArray() { - final String[] params = new String[] { "hello", "world" }; - final TransactionOptions options = new TransactionOptions().params(params); - final String result = db - .transaction("function (params) { return params[0] + ' ' + params[1];}", String.class, options); - assertThat(result, is("hello world")); - } - - @Test - public void transactionCollection() { - final Collection params = new ArrayList(); - params.add("hello"); - params.add("world"); - final TransactionOptions options = new TransactionOptions().params(params); - final String result = db - .transaction("function (params) { return params[0] + ' ' + params[1];}", String.class, options); - assertThat(result, is("hello world")); - } - - @Test - public void transactionInsertJson() { - try { - db.createCollection(COLLECTION_NAME); - final TransactionOptions options = new TransactionOptions().params("{\"_key\":\"0\"}") - .writeCollections(COLLECTION_NAME); - //@formatter:off + Logger LOG = LoggerFactory.getLogger(ArangoDatabaseTest.class); + + private static final String COLLECTION_NAME = "db_test"; + private static final String GRAPH_NAME = "graph_test"; + + public ArangoDatabaseTest(final Builder builder) { + super(builder); + } + + @Before + public void setUp() { + if (db.collection(COLLECTION_NAME + "2").exists()) + db.collection(COLLECTION_NAME + "2").drop(); + if (db.collection(COLLECTION_NAME + "1").exists()) + db.collection(COLLECTION_NAME + "1").drop(); + if (db.collection(COLLECTION_NAME).exists()) + db.collection(COLLECTION_NAME).drop(); + if (db.collection(COLLECTION_NAME + "edge").exists()) + db.collection(COLLECTION_NAME + "edge").drop(); + if (db.collection(COLLECTION_NAME + "from").exists()) + db.collection(COLLECTION_NAME + "from").drop(); + if (db.collection(COLLECTION_NAME + "to").exists()) + db.collection(COLLECTION_NAME + "to").drop(); + } + + @Test + public void create() { + final Boolean result = arangoDB.db(BaseTest.TEST_DB + "_1").create(); + assertThat(result, is(true)); + arangoDB.db(BaseTest.TEST_DB + "_1").drop(); + } + + @Test + public void getVersion() { + final ArangoDBVersion version = db.getVersion(); + assertThat(version, is(notNullValue())); + assertThat(version.getServer(), is(notNullValue())); + assertThat(version.getVersion(), is(notNullValue())); + } + + @Test + public void getEngine() { + final ArangoDBEngine engine = db.getEngine(); + assertThat(engine, is(notNullValue())); + assertThat(engine.getName(), is(notNullValue())); + } + + @Test + public void exists() { + assertThat(db.exists(), is(true)); + assertThat(arangoDB.db("no").exists(), is(false)); + } + + @Test + public void getAccessibleDatabases() { + final Collection dbs = db.getAccessibleDatabases(); + assertThat(dbs, is(notNullValue())); + assertThat(dbs.size(), greaterThan(0)); + assertThat(dbs, hasItem("_system")); + } + + @Test + public void createCollection() { + try { + final CollectionEntity result = db.createCollection(COLLECTION_NAME, null); + assertThat(result, is(notNullValue())); + assertThat(result.getId(), is(notNullValue())); + } finally { + db.collection(COLLECTION_NAME).drop(); + } + } + + @Test + public void createCollectionWithReplicationFactor() { + if (arangoDB.getRole() == ServerRole.SINGLE) { + return; + } + final CollectionEntity result = db + .createCollection(COLLECTION_NAME, new CollectionCreateOptions().replicationFactor(2)); + assertThat(result, is(notNullValue())); + assertThat(result.getId(), is(notNullValue())); + assertThat(db.collection(COLLECTION_NAME).getProperties().getReplicationFactor(), is(2)); + assertThat(db.collection(COLLECTION_NAME).getProperties().getSatellite(), is(nullValue())); + db.collection(COLLECTION_NAME).drop(); + } + + @Test + public void createCollectionWithMinReplicationFactor() { + + // if we do not have version at least 3.5+ => exit + if (!requireVersion(3, 5)) { + LOG.info("Skip Test 'createCollectionWithMinReplicationFactor' because feature not implemented yet."); + return; + } + + // if we do not have a cluster => exit + if (arangoDB.getRole() == ServerRole.SINGLE) { + return; + } + + final CollectionEntity result = db.createCollection(COLLECTION_NAME, + new CollectionCreateOptions().replicationFactor(2).minReplicationFactor(2)); + assertThat(result, is(notNullValue())); + assertThat(result.getId(), is(notNullValue())); + assertThat(db.collection(COLLECTION_NAME).getProperties().getReplicationFactor(), is(2)); + assertThat(db.collection(COLLECTION_NAME).getProperties().getMinReplicationFactor(), is(2)); + assertThat(db.collection(COLLECTION_NAME).getProperties().getSatellite(), is(nullValue())); + db.collection(COLLECTION_NAME).drop(); + } + + @Test + public void createSatelliteCollection() { + if (arangoDB.getVersion().getLicense() == License.COMMUNITY) { + LOG.info("Skip Test 'createSatelliteCollection' on COMMUNITY VERSION"); + return; + } + + if (arangoDB.getRole() == ServerRole.SINGLE) { + LOG.info("Skip Test 'createSatelliteCollection' on SINGLE SERVER"); + return; + } + + try { + + final CollectionEntity result = db + .createCollection(COLLECTION_NAME, new CollectionCreateOptions().satellite(true)); + + assertThat(result, is(notNullValue())); + assertThat(result.getId(), is(notNullValue())); + assertThat(db.collection(COLLECTION_NAME).getProperties().getReplicationFactor(), is(nullValue())); + assertThat(db.collection(COLLECTION_NAME).getProperties().getSatellite(), is(true)); + + } finally { + db.collection(COLLECTION_NAME).drop(); + } + } + + @Test + public void createCollectionWithNumberOfShards() { + if (arangoDB.getRole() == ServerRole.SINGLE) { + return; + } + + try { + + final CollectionEntity result = db + .createCollection(COLLECTION_NAME, new CollectionCreateOptions().numberOfShards(2)); + + assertThat(result, is(notNullValue())); + assertThat(result.getId(), is(notNullValue())); + assertThat(db.collection(COLLECTION_NAME).getProperties().getNumberOfShards(), is(2)); + + } finally { + db.collection(COLLECTION_NAME).drop(); + } + } + + @Test + public void createCollectionWithShardingStrategys() { + if (!requireVersion(3, 4)) { + LOG.info("Skip Test 'createCollectionWithShardingStrategys' because feature not implemented yet."); + return; + } + + if (arangoDB.getRole() == ServerRole.SINGLE) { + LOG.info("Skip Test 'createCollectionWithShardingStrategys' on SINGLE SERVER"); + return; + } + + final CollectionEntity result = db.createCollection(COLLECTION_NAME, new CollectionCreateOptions() + .shardingStrategy(ShardingStrategy.COMMUNITY_COMPAT.getInternalName())); + + assertThat(result, is(notNullValue())); + assertThat(result.getId(), is(notNullValue())); + assertThat(db.collection(COLLECTION_NAME).getProperties().getShardingStrategy(), + is(ShardingStrategy.COMMUNITY_COMPAT.getInternalName())); + db.collection(COLLECTION_NAME).drop(); + } + + @Test + public void createCollectionWithSmartJoinAttribute() { + if (!requireVersion(3, 5)) { + LOG.info("Skip Test 'createCollectionWithSmartJoinAttribute' because feature not implemented yet."); + return; + } + + if (arangoDB.getVersion().getLicense() == License.COMMUNITY) { + LOG.info("Skip Test 'createCollectionWithSmartJoinAttribute' on COMMUNITY SERVER"); + return; + } + + if (arangoDB.getRole() == ServerRole.SINGLE) { + LOG.info("Skip Test 'createCollectionWithSmartJoinAttribute' on SINGLE SERVER"); + return; + } + + final CollectionEntity result = db.createCollection(COLLECTION_NAME, + new CollectionCreateOptions().smartJoinAttribute("test123").shardKeys("_key:")); + assertThat(result, is(notNullValue())); + assertThat(result.getId(), is(notNullValue())); + assertThat(db.collection(COLLECTION_NAME).getProperties().getSmartJoinAttribute(), is("test123")); + db.collection(COLLECTION_NAME).drop(); + } + + @Test + public void createCollectionWithSmartJoinAttributeWrong() { + if (!requireVersion(3, 5)) { + LOG.info("Skip Test 'createCollectionWithSmartJoinAttributeWrong' because feature not implemented yet."); + return; + } + + if (arangoDB.getVersion().getLicense() == License.COMMUNITY) { + LOG.info("Skip Test 'createCollectionWithSmartJoinAttributeWrong' on COMMUNITY SERVER"); + return; + } + + if (arangoDB.getRole() == ServerRole.SINGLE) { + LOG.info("Skip Test 'createCollectionWithSmartJoinAttributeWrong' on SINGLE SERVER"); + return; + } + + try { + db.createCollection(COLLECTION_NAME, new CollectionCreateOptions().smartJoinAttribute("test123")); + } catch (ArangoDBException e) { + assertThat(e.getErrorNum(), is(4006)); + // TODO: + // at the moment older server versions reply with response code 500, which is a misbehavior + // when the fix has been backported to all the supported db versions uncomment the following: + // assertThat(e.getResponseCode(), is(400)); + } + } + + @Test + public void createCollectionWithNumberOfShardsAndShardKey() { + if (arangoDB.getRole() == ServerRole.SINGLE) { + LOG.info("Skip Test 'createCollectionWithNumberOfShardsAndShardKey' on SINGLE SERVER"); + return; + } + + try { + final CollectionEntity result = db + .createCollection(COLLECTION_NAME, new CollectionCreateOptions().numberOfShards(2).shardKeys("a")); + assertThat(result, is(notNullValue())); + assertThat(result.getId(), is(notNullValue())); + final CollectionPropertiesEntity properties = db.collection(COLLECTION_NAME).getProperties(); + assertThat(properties.getNumberOfShards(), is(2)); + assertThat(properties.getShardKeys().size(), is(1)); + } finally { + db.collection(COLLECTION_NAME).drop(); + } + } + + @Test + public void createCollectionWithNumberOfShardsAndShardKeys() { + if (arangoDB.getRole() == ServerRole.SINGLE) { + LOG.info("Skip Test 'createCollectionWithNumberOfShardsAndShardKeys' on SINGLE SERVER"); + return; + } + + try { + final CollectionEntity result = db.createCollection(COLLECTION_NAME, + new CollectionCreateOptions().numberOfShards(2).shardKeys("a", "b")); + assertThat(result, is(notNullValue())); + assertThat(result.getId(), is(notNullValue())); + final CollectionPropertiesEntity properties = db.collection(COLLECTION_NAME).getProperties(); + assertThat(properties.getNumberOfShards(), is(2)); + assertThat(properties.getShardKeys().size(), is(2)); + } finally { + db.collection(COLLECTION_NAME).drop(); + } + } + + @Test + public void createCollectionWithDistributeShardsLike() { + + if (arangoDB.getVersion().getLicense() == License.ENTERPRISE && arangoDB.getRole() != ServerRole.SINGLE) { + + final Integer numberOfShards = 3; + + db.createCollection(COLLECTION_NAME, new CollectionCreateOptions().numberOfShards(numberOfShards)); + db.createCollection(COLLECTION_NAME + "2", + new CollectionCreateOptions().distributeShardsLike(COLLECTION_NAME)); + + assertThat(db.collection(COLLECTION_NAME).getProperties().getNumberOfShards(), is(numberOfShards)); + assertThat(db.collection(COLLECTION_NAME + "2").getProperties().getNumberOfShards(), is(numberOfShards)); + } + + } + + @Test(expected = ArangoDBException.class) + public void deleteCollection() { + db.createCollection(COLLECTION_NAME, null); + db.collection(COLLECTION_NAME).drop(); + db.collection(COLLECTION_NAME).getInfo(); + } + + @Test + public void deleteSystemCollection() { + + if (arangoDB.getRole() != ServerRole.SINGLE) { + return; + } + + final String name = "_system_test"; + db.createCollection(name, new CollectionCreateOptions().isSystem(true)); + db.collection(name).drop(true); + try { + db.collection(name).getInfo(); + fail(); + } catch (final ArangoDBException e) { + } + } + + @Test + public void deleteSystemCollectionFail() { + if (arangoDB.getRole() != ServerRole.SINGLE) { + return; + } + final String name = "_system_test"; + db.createCollection(name, new CollectionCreateOptions().isSystem(true)); + try { + db.collection(name).drop(); + fail(); + } catch (final ArangoDBException e) { + } + db.collection(name).drop(true); + try { + db.collection(name).getInfo(); + fail(); + } catch (final ArangoDBException e) { + } + } + + @Test + public void getIndex() { + try { + db.createCollection(COLLECTION_NAME, null); + final Collection fields = new ArrayList(); + fields.add("a"); + final IndexEntity createResult = db.collection(COLLECTION_NAME).ensureHashIndex(fields, null); + final IndexEntity readResult = db.getIndex(createResult.getId()); + assertThat(readResult.getId(), is(createResult.getId())); + assertThat(readResult.getType(), is(createResult.getType())); + } finally { + db.collection(COLLECTION_NAME).drop(); + } + } + + @Test + public void deleteIndex() { + db.createCollection(COLLECTION_NAME, null); + final Collection fields = new ArrayList(); + fields.add("a"); + final IndexEntity createResult = db.collection(COLLECTION_NAME).ensureHashIndex(fields, null); + final String id = db.deleteIndex(createResult.getId()); + assertThat(id, is(createResult.getId())); + try { + db.getIndex(id); + fail(); + } catch (final ArangoDBException e) { + } + db.collection(COLLECTION_NAME).drop(); + } + + @Test + public void getCollections() { + try { + final Collection systemCollections = db.getCollections(null); + db.createCollection(COLLECTION_NAME + "1", null); + db.createCollection(COLLECTION_NAME + "2", null); + final Collection collections = db.getCollections(null); + assertThat(collections.size(), is(2 + systemCollections.size())); + assertThat(collections, is(notNullValue())); + } finally { + db.collection(COLLECTION_NAME + "1").drop(); + db.collection(COLLECTION_NAME + "2").drop(); + } + } + + @Test + public void getCollectionsExcludeSystem() { + try { + final CollectionsReadOptions options = new CollectionsReadOptions().excludeSystem(true); + final Collection nonSystemCollections = db.getCollections(options); + + assertThat(nonSystemCollections.size(), is(0)); + db.createCollection(COLLECTION_NAME + "1", null); + db.createCollection(COLLECTION_NAME + "2", null); + final Collection newCollections = db.getCollections(options); + assertThat(newCollections.size(), is(2)); + assertThat(newCollections, is(notNullValue())); + } catch (final ArangoDBException e) { + System.out.println(e.getErrorMessage()); + } finally { + db.collection(COLLECTION_NAME + "1").drop(); + db.collection(COLLECTION_NAME + "2").drop(); + } + } + + @Test + public void grantAccess() { + try { + arangoDB.createUser("user1", "1234", null); + db.grantAccess("user1"); + } finally { + arangoDB.deleteUser("user1"); + } + } + + @Test + public void grantAccessRW() { + try { + arangoDB.createUser("user1", "1234", null); + db.grantAccess("user1", Permissions.RW); + } finally { + arangoDB.deleteUser("user1"); + } + } + + @Test + public void grantAccessRO() { + try { + arangoDB.createUser("user1", "1234", null); + db.grantAccess("user1", Permissions.RO); + } finally { + arangoDB.deleteUser("user1"); + } + } + + @Test + public void grantAccessNONE() { + try { + arangoDB.createUser("user1", "1234", null); + db.grantAccess("user1", Permissions.NONE); + } finally { + arangoDB.deleteUser("user1"); + } + } + + @Test(expected = ArangoDBException.class) + public void grantAccessUserNotFound() { + db.grantAccess("user1", Permissions.RW); + } + + @Test + public void revokeAccess() { + try { + arangoDB.createUser("user1", "1234", null); + db.revokeAccess("user1"); + } finally { + arangoDB.deleteUser("user1"); + } + } + + @Test(expected = ArangoDBException.class) + public void revokeAccessUserNotFound() { + db.revokeAccess("user1"); + } + + @Test + public void resetAccess() { + try { + arangoDB.createUser("user1", "1234", null); + db.resetAccess("user1"); + } finally { + arangoDB.deleteUser("user1"); + } + } + + @Test(expected = ArangoDBException.class) + public void resetAccessUserNotFound() { + db.resetAccess("user1"); + } + + @Test + public void grantDefaultCollectionAccess() { + try { + arangoDB.createUser("user1", "1234"); + db.grantDefaultCollectionAccess("user1", Permissions.RW); + } finally { + arangoDB.deleteUser("user1"); + } + } + + @Test + public void getPermissions() { + assertThat(Permissions.RW, is(db.getPermissions("root"))); + } + + @Test + public void query() { + try { + db.createCollection(COLLECTION_NAME, null); + for (int i = 0; i < 10; i++) { + db.collection(COLLECTION_NAME).insertDocument(new BaseDocument(), null); + } + final ArangoCursor cursor = db.query("for i in db_test return i._id", null, null, String.class); + assertThat(cursor, is(notNullValue())); + for (int i = 0; i < 10; i++, cursor.next()) { + assertThat(cursor.hasNext(), is(i != 10)); + } + } finally { + db.collection(COLLECTION_NAME).drop(); + } + } + + @Test + public void queryForEach() { + try { + db.createCollection(COLLECTION_NAME, null); + for (int i = 0; i < 10; i++) { + db.collection(COLLECTION_NAME).insertDocument(new BaseDocument(), null); + } + final ArangoCursor cursor = db.query("for i in db_test return i._id", null, null, String.class); + assertThat(cursor, is(notNullValue())); + final AtomicInteger i = new AtomicInteger(0); + for (; cursor.hasNext(); cursor.next()) { + i.incrementAndGet(); + } + assertThat(i.get(), is(10)); + } finally { + db.collection(COLLECTION_NAME).drop(); + } + } + + @Test + public void queryIterate() { + try { + db.createCollection(COLLECTION_NAME, null); + for (int i = 0; i < 10; i++) { + db.collection(COLLECTION_NAME).insertDocument(new BaseDocument(), null); + } + final ArangoCursor cursor = db.query("for i in db_test return i._id", null, null, String.class); + assertThat(cursor, is(notNullValue())); + final AtomicInteger i = new AtomicInteger(0); + for (; cursor.hasNext(); cursor.next()) { + i.incrementAndGet(); + } + assertThat(i.get(), is(10)); + } finally { + db.collection(COLLECTION_NAME).drop(); + } + } + + @Test + public void queryWithCount() { + try { + db.createCollection(COLLECTION_NAME, null); + for (int i = 0; i < 10; i++) { + db.collection(COLLECTION_NAME).insertDocument(new BaseDocument(), null); + } + + final ArangoCursor cursor = db + .query("for i in db_test Limit 6 return i._id", null, new AqlQueryOptions().count(true), + String.class); + assertThat(cursor, is(notNullValue())); + for (int i = 0; i < 6; i++, cursor.next()) { + assertThat(cursor.hasNext(), is(i != 6)); + } + assertThat(cursor.getCount(), is(6)); + + } finally { + db.collection(COLLECTION_NAME).drop(); + } + } + + @Test + public void queryWithLimitAndFullCount() { + try { + db.createCollection(COLLECTION_NAME, null); + for (int i = 0; i < 10; i++) { + db.collection(COLLECTION_NAME).insertDocument(new BaseDocument(), null); + } + + final ArangoCursor cursor = db + .query("for i in db_test Limit 5 return i._id", null, new AqlQueryOptions().fullCount(true), + String.class); + assertThat(cursor, is(notNullValue())); + for (int i = 0; i < 5; i++, cursor.next()) { + assertThat(cursor.hasNext(), is(i != 5)); + } + assertThat(cursor.getStats(), is(notNullValue())); + assertThat(cursor.getStats().getFullCount(), is(10L)); + + } finally { + db.collection(COLLECTION_NAME).drop(); + } + } + + @Test + public void queryWithBatchSize() { + try { + db.createCollection(COLLECTION_NAME, null); + for (int i = 0; i < 10; i++) { + db.collection(COLLECTION_NAME).insertDocument(new BaseDocument(), null); + } + + final ArangoCursor cursor = db + .query("for i in db_test return i._id", null, new AqlQueryOptions().batchSize(5).count(true), + String.class); + + assertThat(cursor, is(notNullValue())); + for (int i = 0; i < 10; i++, cursor.next()) { + assertThat(cursor.hasNext(), is(i != 10)); + } + } catch (final ArangoDBException e) { + System.out.println(e.getErrorMessage()); + System.out.println(e.getErrorNum()); + } finally { + db.collection(COLLECTION_NAME).drop(); + } + } + + @Test + public void queryIterateWithBatchSize() { + try { + db.createCollection(COLLECTION_NAME, null); + for (int i = 0; i < 10; i++) { + db.collection(COLLECTION_NAME).insertDocument(new BaseDocument(), null); + } + + final ArangoCursor cursor = db + .query("for i in db_test return i._id", null, new AqlQueryOptions().batchSize(5).count(true), + String.class); + + assertThat(cursor, is(notNullValue())); + final AtomicInteger i = new AtomicInteger(0); + for (; cursor.hasNext(); cursor.next()) { + i.incrementAndGet(); + } + assertThat(i.get(), is(10)); + } finally { + db.collection(COLLECTION_NAME).drop(); + } + } + + /** + * ignored. takes to long + */ + @Test + @Ignore + public void queryWithTTL() throws InterruptedException { + // set TTL to 1 seconds and get the second batch after 2 seconds! + final int ttl = 1; + final int wait = 2; + try { + db.createCollection(COLLECTION_NAME, null); + for (int i = 0; i < 10; i++) { + db.collection(COLLECTION_NAME).insertDocument(new BaseDocument(), null); + } + + final ArangoCursor cursor = db + .query("for i in db_test return i._id", null, new AqlQueryOptions().batchSize(5).ttl(ttl), + String.class); + + assertThat(cursor, is(notNullValue())); + + for (int i = 0; i < 10; i++, cursor.next()) { + assertThat(cursor.hasNext(), is(i != 10)); + if (i == 1) { + Thread.sleep(wait * 1000); + } + } + fail("this should fail"); + } catch (final ArangoDBException ex) { + assertThat(ex.getMessage(), is("Response: 404, Error: 1600 - cursor not found")); + } finally { + db.collection(COLLECTION_NAME).drop(); + } + } + + @Test + public void changeQueryCache() { + try { + QueryCachePropertiesEntity properties = db.getQueryCacheProperties(); + assertThat(properties, is(notNullValue())); + assertThat(properties.getMode(), is(CacheMode.off)); + assertThat(properties.getMaxResults(), greaterThan(0L)); + + properties.setMode(CacheMode.on); + properties = db.setQueryCacheProperties(properties); + assertThat(properties, is(notNullValue())); + assertThat(properties.getMode(), is(CacheMode.on)); + + properties = db.getQueryCacheProperties(); + assertThat(properties.getMode(), is(CacheMode.on)); + } finally { + final QueryCachePropertiesEntity properties = new QueryCachePropertiesEntity(); + properties.setMode(CacheMode.off); + db.setQueryCacheProperties(properties); + } + } + + @Test + public void queryWithCache() throws InterruptedException { + if (arangoDB.getRole() != ServerRole.SINGLE) { + return; + } + try { + db.createCollection(COLLECTION_NAME, null); + for (int i = 0; i < 10; i++) { + db.collection(COLLECTION_NAME).insertDocument(new BaseDocument(), null); + } + + final QueryCachePropertiesEntity properties = new QueryCachePropertiesEntity(); + properties.setMode(CacheMode.on); + db.setQueryCacheProperties(properties); + + final ArangoCursor cursor = db + .query("FOR t IN db_test FILTER t.age >= 10 SORT t.age RETURN t._id", null, + new AqlQueryOptions().cache(true), String.class); + + assertThat(cursor, is(notNullValue())); + assertThat(cursor.isCached(), is(false)); + + final ArangoCursor cachedCursor = db + .query("FOR t IN db_test FILTER t.age >= 10 SORT t.age RETURN t._id", null, + new AqlQueryOptions().cache(true), String.class); + + assertThat(cachedCursor, is(notNullValue())); + assertThat(cachedCursor.isCached(), is(true)); + + } finally { + db.collection(COLLECTION_NAME).drop(); + final QueryCachePropertiesEntity properties = new QueryCachePropertiesEntity(); + properties.setMode(CacheMode.off); + db.setQueryCacheProperties(properties); + } + } + + @Test + public void queryWithMemoryLimit() { + try { + db.query("RETURN 'bla'", null, new AqlQueryOptions().memoryLimit(1L), String.class); + fail(); + } catch (final ArangoDBException e) { + assertThat(e.getErrorNum(), is(32)); + } + } + + @Test(expected = ArangoDBException.class) + public void queryWithFailOnWarningTrue() { + db.query("RETURN 1 / 0", null, new AqlQueryOptions().failOnWarning(true), String.class); + } + + @Test + public void queryWithFailOnWarningFalse() { + final ArangoCursor cursor = db + .query("RETURN 1 / 0", null, new AqlQueryOptions().failOnWarning(false), String.class); + assertThat(cursor.next(), is("null")); + } + + @Test + public void queryWithMaxWarningCount() { + final ArangoCursor cursorWithWarnings = db + .query("RETURN 1 / 0", null, new AqlQueryOptions(), String.class); + assertThat(cursorWithWarnings.getWarnings().size(), is(1)); + final ArangoCursor cursorWithLimitedWarnings = db + .query("RETURN 1 / 0", null, new AqlQueryOptions().maxWarningCount(0L), String.class); + final Collection warnings = cursorWithLimitedWarnings.getWarnings(); + if (warnings != null) { + assertThat(warnings.size(), is(0)); + } + } + + @Test + public void queryCursor() { + try { + db.createCollection(COLLECTION_NAME, null); + final int numbDocs = 10; + for (int i = 0; i < numbDocs; i++) { + db.collection(COLLECTION_NAME).insertDocument(new BaseDocument(), null); + } + + final int batchSize = 5; + final ArangoCursor cursor = db.query("for i in db_test return i._id", null, + new AqlQueryOptions().batchSize(batchSize).count(true), String.class); + assertThat(cursor, is(notNullValue())); + assertThat(cursor.getCount(), is(numbDocs)); + + final ArangoCursor cursor2 = db.cursor(cursor.getId(), String.class); + assertThat(cursor2, is(notNullValue())); + assertThat(cursor2.getCount(), is(numbDocs)); + assertThat(cursor2.hasNext(), is(true)); + + for (int i = 0; i < batchSize; i++, cursor.next()) { + assertThat(cursor.hasNext(), is(i != batchSize)); + } + } finally { + db.collection(COLLECTION_NAME).drop(); + } + } + + @Test + public void changeQueryTrackingProperties() { + try { + QueryTrackingPropertiesEntity properties = db.getQueryTrackingProperties(); + assertThat(properties, is(notNullValue())); + assertThat(properties.getEnabled(), is(true)); + assertThat(properties.getTrackSlowQueries(), is(true)); + assertThat(properties.getMaxQueryStringLength(), greaterThan(0L)); + assertThat(properties.getMaxSlowQueries(), greaterThan(0L)); + assertThat(properties.getSlowQueryThreshold(), greaterThan(0L)); + properties.setEnabled(false); + properties = db.setQueryTrackingProperties(properties); + assertThat(properties, is(notNullValue())); + assertThat(properties.getEnabled(), is(false)); + properties = db.getQueryTrackingProperties(); + assertThat(properties.getEnabled(), is(false)); + } finally { + final QueryTrackingPropertiesEntity properties = new QueryTrackingPropertiesEntity(); + properties.setEnabled(true); + db.setQueryTrackingProperties(properties); + } + } + + @Test + public void queryWithBindVars() throws InterruptedException { + try { + db.createCollection(COLLECTION_NAME, null); + for (int i = 0; i < 10; i++) { + final BaseDocument baseDocument = new BaseDocument(); + baseDocument.addAttribute("age", 20 + i); + db.collection(COLLECTION_NAME).insertDocument(baseDocument, null); + } + final Map bindVars = new HashMap(); + bindVars.put("@coll", COLLECTION_NAME); + bindVars.put("age", 25); + + final ArangoCursor cursor = db + .query("FOR t IN @@coll FILTER t.age >= @age SORT t.age RETURN t._id", bindVars, null, + String.class); + + assertThat(cursor, is(notNullValue())); + + for (int i = 0; i < 5; i++, cursor.next()) { + assertThat(cursor.hasNext(), is(i != 5)); + } + + } finally { + db.collection(COLLECTION_NAME).drop(); + } + } + + @Test + public void queryWithWarning() { + final ArangoCursor cursor = arangoDB.db().query("return 1/0", null, null, String.class); + + assertThat(cursor, is(notNullValue())); + assertThat(cursor.getWarnings(), is(notNullValue())); + } + + @Test + public void queryStream() { + if (requireVersion(3, 4)) { + final ArangoCursor cursor = db + .query("FOR i IN 1..2 RETURN i", null, new AqlQueryOptions().stream(true).count(true), + VPackSlice.class); + assertThat(cursor, is(notNullValue())); + assertThat(cursor.getCount(), is(nullValue())); + } + } + + @Test + public void queryClose() throws IOException { + final ArangoCursor cursor = arangoDB.db() + .query("for i in 1..2 return i", null, new AqlQueryOptions().batchSize(1), String.class); + cursor.close(); + int count = 0; + try { + for (; cursor.hasNext(); cursor.next(), count++) { + } + fail(); + } catch (final ArangoDBException e) { + assertThat(count, is(1)); + } + + } + + @Test + public void queryNoResults() throws IOException { + try { + db.createCollection(COLLECTION_NAME); + final ArangoCursor cursor = db + .query("FOR i IN @@col RETURN i", new MapBuilder().put("@col", COLLECTION_NAME).get(), null, + BaseDocument.class); + cursor.close(); + } finally { + db.collection(COLLECTION_NAME).drop(); + } + } + + @Test + public void queryWithNullBindParam() throws IOException { + try { + db.createCollection(COLLECTION_NAME); + final ArangoCursor cursor = db.query("FOR i IN @@col FILTER i.test == @test RETURN i", + new MapBuilder().put("@col", COLLECTION_NAME).put("test", null).get(), null, BaseDocument.class); + cursor.close(); + } finally { + db.collection(COLLECTION_NAME).drop(); + } + } + + @Test + public void queryAllowDirtyRead() throws IOException { + try { + db.createCollection(COLLECTION_NAME); + final ArangoCursor cursor = db.query("FOR i IN @@col FILTER i.test == @test RETURN i", + new MapBuilder().put("@col", COLLECTION_NAME).put("test", null).get(), + new AqlQueryOptions().allowDirtyRead(true), BaseDocument.class); + cursor.close(); + } catch (ArangoDBException e) { + System.out.println(e); + } finally { + db.collection(COLLECTION_NAME).drop(); + } + } + + @Test + public void explainQuery() { + final AqlExecutionExplainEntity explain = arangoDB.db().explainQuery("for i in 1..1 return i", null, null); + assertThat(explain, is(notNullValue())); + assertThat(explain.getPlan(), is(notNullValue())); + assertThat(explain.getPlans(), is(nullValue())); + final ExecutionPlan plan = explain.getPlan(); + assertThat(plan.getCollections().size(), is(0)); + assertThat(plan.getEstimatedCost(), greaterThan(0)); + assertThat(plan.getEstimatedNrItems(), greaterThan(0)); + assertThat(plan.getVariables().size(), is(2)); + assertThat(plan.getNodes().size(), is(greaterThan(0))); + } + + @Test + public void parseQuery() { + final AqlParseEntity parse = arangoDB.db().parseQuery("for i in 1..1 return i"); + assertThat(parse, is(notNullValue())); + assertThat(parse.getBindVars(), is(empty())); + assertThat(parse.getCollections().size(), is(0)); + assertThat(parse.getAst().size(), is(1)); + } + + @Test + @Ignore + public void getCurrentlyRunningQueries() throws InterruptedException, ExecutionException { + final Thread t = new Thread() { + @Override + public void run() { + super.run(); + db.query("return sleep(0.2)", null, null, Void.class); + } + }; + t.start(); + Thread.sleep(100); + try { + final Collection currentlyRunningQueries = db.getCurrentlyRunningQueries(); + assertThat(currentlyRunningQueries, is(notNullValue())); + assertThat(currentlyRunningQueries.size(), is(1)); + final QueryEntity queryEntity = currentlyRunningQueries.iterator().next(); + assertThat(queryEntity.getQuery(), is("return sleep(0.2)")); + assertThat(queryEntity.getState(), is(QueryExecutionState.EXECUTING)); + } finally { + t.join(); + } + } + + @Test + @Ignore + public void getAndClearSlowQueries() throws InterruptedException, ExecutionException { + final QueryTrackingPropertiesEntity properties = db.getQueryTrackingProperties(); + final Long slowQueryThreshold = properties.getSlowQueryThreshold(); + try { + properties.setSlowQueryThreshold(1L); + db.setQueryTrackingProperties(properties); + + db.query("return sleep(1.1)", null, null, Void.class); + final Collection slowQueries = db.getSlowQueries(); + assertThat(slowQueries, is(notNullValue())); + assertThat(slowQueries.size(), is(1)); + final QueryEntity queryEntity = slowQueries.iterator().next(); + assertThat(queryEntity.getQuery(), is("return sleep(1.1)")); + + db.clearSlowQueries(); + assertThat(db.getSlowQueries().size(), is(0)); + } finally { + properties.setSlowQueryThreshold(slowQueryThreshold); + db.setQueryTrackingProperties(properties); + } + } + + @Test + @Ignore + public void killQuery() throws InterruptedException, ExecutionException { + final Thread t = new Thread() { + @Override + public void run() { + super.run(); + try { + db.query("return sleep(0.2)", null, null, Void.class); + fail(); + } catch (final ArangoDBException e) { + } + } + }; + t.start(); + Thread.sleep(100); + final Collection currentlyRunningQueries = db.getCurrentlyRunningQueries(); + assertThat(currentlyRunningQueries, is(notNullValue())); + assertThat(currentlyRunningQueries.size(), is(1)); + + final QueryEntity queryEntity = currentlyRunningQueries.iterator().next(); + db.killQuery(queryEntity.getId()); + } + + @Test + public void createGetDeleteAqlFunction() { + final Collection aqlFunctionsInitial = db.getAqlFunctions(null); + assertThat(aqlFunctionsInitial, is(empty())); + try { + db.createAqlFunction("myfunctions::temperature::celsiustofahrenheit", + "function (celsius) { return celsius * 1.8 + 32; }", null); + + final Collection aqlFunctions = db.getAqlFunctions(null); + assertThat(aqlFunctions.size(), is(greaterThan(aqlFunctionsInitial.size()))); + } finally { + final Integer deleteCount = db.deleteAqlFunction("myfunctions::temperature::celsiustofahrenheit", null); + // compatibility with ArangoDB < 3.4 + if (requireVersion(3, 4)) { + assertThat(deleteCount, is(1)); + } else { + assertThat(deleteCount, is(nullValue())); + } + final Collection aqlFunctions = db.getAqlFunctions(null); + assertThat(aqlFunctions.size(), is(aqlFunctionsInitial.size())); + } + } + + @Test + public void createGetDeleteAqlFunctionWithNamespace() { + final Collection aqlFunctionsInitial = db.getAqlFunctions(null); + assertThat(aqlFunctionsInitial, is(empty())); + try { + db.createAqlFunction("myfunctions::temperature::celsiustofahrenheit1", + "function (celsius) { return celsius * 1.8 + 32; }", null); + db.createAqlFunction("myfunctions::temperature::celsiustofahrenheit2", + "function (celsius) { return celsius * 1.8 + 32; }", null); + + } finally { + final Integer deleteCount = db + .deleteAqlFunction("myfunctions::temperature", new AqlFunctionDeleteOptions().group(true)); + // compatibility with ArangoDB < 3.4 + if (requireVersion(3, 4)) { + assertThat(deleteCount, is(2)); + } else { + assertThat(deleteCount, is(nullValue())); + } + final Collection aqlFunctions = db.getAqlFunctions(null); + assertThat(aqlFunctions.size(), is(aqlFunctionsInitial.size())); + } + } + + @Test + public void createGraph() { + try { + final GraphEntity result = db.createGraph(GRAPH_NAME, null, null); + assertThat(result, is(notNullValue())); + assertThat(result.getName(), is(GRAPH_NAME)); + } finally { + db.graph(GRAPH_NAME).drop(); + } + } + + @Test + public void createGraphReplicationFaktor() { + if (arangoDB.getRole() == ServerRole.SINGLE) { + return; + } + try { + final String edgeCollection = COLLECTION_NAME + "edge"; + final String fromCollection = COLLECTION_NAME + "from"; + final String toCollection = COLLECTION_NAME + "to"; + final Collection edgeDefinitions = Arrays + .asList(new EdgeDefinition().collection(edgeCollection).from(fromCollection).to(toCollection)); + final GraphEntity result = db + .createGraph(GRAPH_NAME, edgeDefinitions, new GraphCreateOptions().replicationFactor(2)); + assertThat(result, is(notNullValue())); + for (final String collection : Arrays.asList(edgeCollection, fromCollection, toCollection)) { + final CollectionPropertiesEntity properties = db.collection(collection).getProperties(); + assertThat(properties.getReplicationFactor(), is(2)); + } + } finally { + db.graph(GRAPH_NAME).drop(); + } + } + + @Test + public void createGraphNumberOfShards() { + if (arangoDB.getRole() == ServerRole.SINGLE) { + return; + } + try { + final String edgeCollection = COLLECTION_NAME + "edge"; + final String fromCollection = COLLECTION_NAME + "from"; + final String toCollection = COLLECTION_NAME + "to"; + final Collection edgeDefinitions = Arrays + .asList(new EdgeDefinition().collection(edgeCollection).from(fromCollection).to(toCollection)); + final GraphEntity result = db + .createGraph(GRAPH_NAME, edgeDefinitions, new GraphCreateOptions().numberOfShards(2)); + assertThat(result, is(notNullValue())); + for (final String collection : Arrays.asList(edgeCollection, fromCollection, toCollection)) { + final CollectionPropertiesEntity properties = db.collection(collection).getProperties(); + assertThat(properties.getNumberOfShards(), is(2)); + } + } finally { + db.graph(GRAPH_NAME).drop(); + } + } + + @Test + public void getGraphs() { + try { + db.createGraph(GRAPH_NAME, null, null); + final Collection graphs = db.getGraphs(); + assertThat(graphs, is(notNullValue())); + assertThat(graphs.size(), is(1)); + assertThat(graphs.iterator().next().getName(), is(GRAPH_NAME)); + } finally { + db.graph(GRAPH_NAME).drop(); + } + } + + @Test + public void transactionString() { + final TransactionOptions options = new TransactionOptions().params("test"); + final String result = db.transaction("function (params) {return params;}", String.class, options); + assertThat(result, is("test")); + } + + @Test + public void transactionNumber() { + final TransactionOptions options = new TransactionOptions().params(5); + final Integer result = db.transaction("function (params) {return params;}", Integer.class, options); + assertThat(result, is(5)); + } + + @Test + public void transactionVPack() throws VPackException { + final TransactionOptions options = new TransactionOptions().params(new VPackBuilder().add("test").slice()); + final VPackSlice result = db.transaction("function (params) {return params;}", VPackSlice.class, options); + assertThat(result.isString(), is(true)); + assertThat(result.getAsString(), is("test")); + } + + @Test + public void transactionVPackObject() throws VPackException { + final VPackSlice params = new VPackBuilder().add(ValueType.OBJECT).add("foo", "hello").add("bar", "world") + .close().slice(); + final TransactionOptions options = new TransactionOptions().params(params); + final String result = db + .transaction("function (params) { return params['foo'] + ' ' + params['bar'];}", String.class, options); + assertThat(result, is("hello world")); + } + + @Test + public void transactionVPackArray() throws VPackException { + final VPackSlice params = new VPackBuilder().add(ValueType.ARRAY).add("hello").add("world").close().slice(); + final TransactionOptions options = new TransactionOptions().params(params); + final String result = db + .transaction("function (params) { return params[0] + ' ' + params[1];}", String.class, options); + assertThat(result, is("hello world")); + } + + @Test + public void transactionMap() { + final Map params = new MapBuilder().put("foo", "hello").put("bar", "world").get(); + final TransactionOptions options = new TransactionOptions().params(params); + final String result = db + .transaction("function (params) { return params['foo'] + ' ' + params['bar'];}", String.class, options); + assertThat(result, is("hello world")); + } + + @Test + public void transactionArray() { + final String[] params = new String[]{"hello", "world"}; + final TransactionOptions options = new TransactionOptions().params(params); + final String result = db + .transaction("function (params) { return params[0] + ' ' + params[1];}", String.class, options); + assertThat(result, is("hello world")); + } + + @Test + public void transactionCollection() { + final Collection params = new ArrayList(); + params.add("hello"); + params.add("world"); + final TransactionOptions options = new TransactionOptions().params(params); + final String result = db + .transaction("function (params) { return params[0] + ' ' + params[1];}", String.class, options); + assertThat(result, is("hello world")); + } + + @Test + public void transactionInsertJson() { + try { + db.createCollection(COLLECTION_NAME); + final TransactionOptions options = new TransactionOptions().params("{\"_key\":\"0\"}") + .writeCollections(COLLECTION_NAME); + //@formatter:off db.transaction("function (params) { " + "var db = require('internal').db;" + "db." + COLLECTION_NAME + ".save(JSON.parse(params));" + "}", Void.class, options); //@formatter:on - assertThat(db.collection(COLLECTION_NAME).count().getCount(), is(1L)); - assertThat(db.collection(COLLECTION_NAME).getDocument("0", String.class), is(notNullValue())); - } finally { - db.collection(COLLECTION_NAME).drop(); - } - } - - @Test - public void transactionExclusiveWrite() { - if (!requireVersion(3, 4)) { - return; - } - try { - db.createCollection(COLLECTION_NAME); - final TransactionOptions options = new TransactionOptions().params("{\"_key\":\"0\"}") - .exclusiveCollections(COLLECTION_NAME); - //@formatter:off + assertThat(db.collection(COLLECTION_NAME).count().getCount(), is(1L)); + assertThat(db.collection(COLLECTION_NAME).getDocument("0", String.class), is(notNullValue())); + } finally { + db.collection(COLLECTION_NAME).drop(); + } + } + + @Test + public void transactionExclusiveWrite() { + if (!requireVersion(3, 4)) { + return; + } + try { + db.createCollection(COLLECTION_NAME); + final TransactionOptions options = new TransactionOptions().params("{\"_key\":\"0\"}") + .exclusiveCollections(COLLECTION_NAME); + //@formatter:off db.transaction("function (params) { " + "var db = require('internal').db;" + "db." + COLLECTION_NAME + ".save(JSON.parse(params));" + "}", Void.class, options); //@formatter:on - assertThat(db.collection(COLLECTION_NAME).count().getCount(), is(1L)); - assertThat(db.collection(COLLECTION_NAME).getDocument("0", String.class), is(notNullValue())); - } finally { - db.collection(COLLECTION_NAME).drop(); - } - } - - @Test - public void transactionEmpty() { - db.transaction("function () {}", null, null); - } - - @Test - public void transactionallowImplicit() { - try { - db.createCollection("someCollection", null); - db.createCollection("someOtherCollection", null); - final String action = "function (params) {" + "var db = require('internal').db;" - + "return {'a':db.someCollection.all().toArray()[0], 'b':db.someOtherCollection.all().toArray()[0]};" - + "}"; - final TransactionOptions options = new TransactionOptions().readCollections("someCollection"); - db.transaction(action, VPackSlice.class, options); - try { - options.allowImplicit(false); - db.transaction(action, VPackSlice.class, options); - fail(); - } catch (final ArangoDBException e) { - } - } finally { - db.collection("someCollection").drop(); - db.collection("someOtherCollection").drop(); - } - } - - protected static class TransactionTestEntity { - private String value; - - public TransactionTestEntity() { - super(); - } - } - - @Test - public void transactionPojoReturn() { - final String action = "function() { return {'value':'hello world'}; }"; - final TransactionTestEntity res = db.transaction(action, TransactionTestEntity.class, new TransactionOptions()); - assertThat(res, is(notNullValue())); - assertThat(res.value, is("hello world")); - } - - @Test - public void getInfo() { - final DatabaseEntity info = db.getInfo(); - assertThat(info, is(notNullValue())); - assertThat(info.getId(), is(notNullValue())); - assertThat(info.getName(), is(TEST_DB)); - assertThat(info.getPath(), is(notNullValue())); - assertThat(info.getIsSystem(), is(false)); - } - - @Test - public void executeTraversal() { - try { - db.createCollection("person", null); - db.createCollection("knows", new CollectionCreateOptions().type(CollectionType.EDGES)); - for (final String e : new String[] { "Alice", "Bob", "Charlie", "Dave", "Eve" }) { - final BaseDocument doc = new BaseDocument(); - doc.setKey(e); - db.collection("person").insertDocument(doc, null); - } - for (final String[] e : new String[][] { new String[] { "Alice", "Bob" }, new String[] { "Bob", "Charlie" }, - new String[] { "Bob", "Dave" }, new String[] { "Eve", "Alice" }, new String[] { "Eve", "Bob" } }) { - final BaseEdgeDocument edge = new BaseEdgeDocument(); - edge.setKey(e[0] + "_knows_" + e[1]); - edge.setFrom("person/" + e[0]); - edge.setTo("person/" + e[1]); - db.collection("knows").insertDocument(edge, null); - } - final TraversalOptions options = new TraversalOptions().edgeCollection("knows").startVertex("person/Alice") - .direction(Direction.outbound); - final TraversalEntity traversal = db - .executeTraversal(BaseDocument.class, BaseEdgeDocument.class, options); - - assertThat(traversal, is(notNullValue())); - - final Collection vertices = traversal.getVertices(); - assertThat(vertices, is(notNullValue())); - assertThat(vertices.size(), is(4)); - - final Iterator verticesIterator = vertices.iterator(); - final Collection v = Arrays.asList(new String[] { "Alice", "Bob", "Charlie", "Dave" }); - for (; verticesIterator.hasNext(); ) { - assertThat(v.contains(verticesIterator.next().getKey()), is(true)); - } - - final Collection> paths = traversal.getPaths(); - assertThat(paths, is(notNullValue())); - assertThat(paths.size(), is(4)); - - assertThat(paths.iterator().hasNext(), is(true)); - final PathEntity first = paths.iterator().next(); - assertThat(first, is(notNullValue())); - assertThat(first.getEdges().size(), is(0)); - assertThat(first.getVertices().size(), is(1)); - assertThat(first.getVertices().iterator().next().getKey(), is("Alice")); - } finally { - db.collection("person").drop(); - db.collection("knows").drop(); - } - } - - @Test - public void getDocument() { - try { - db.createCollection(COLLECTION_NAME); - final BaseDocument value = new BaseDocument(); - value.setKey("123"); - db.collection(COLLECTION_NAME).insertDocument(value); - final BaseDocument document = db.getDocument(COLLECTION_NAME + "/123", BaseDocument.class); - assertThat(document, is(notNullValue())); - assertThat(document.getKey(), is("123")); - } finally { - db.collection(COLLECTION_NAME).drop(); - } - } - - @Test - public void shouldIncludeExceptionMessage() { - if (!requireVersion(3, 2)) { - final String exceptionMessage = "My error context"; - final String action = "function (params) {" + "throw '" + exceptionMessage + "';" + "}"; - try { - db.transaction(action, VPackSlice.class, null); - fail(); - } catch (final ArangoDBException e) { - assertTrue(e.getException().contains(exceptionMessage)); - } - } - } - - @Test(expected = ArangoDBException.class) - public void getDocumentWrongId() { - db.getDocument("123", BaseDocument.class); - } - - @Test - public void reloadRouting() { - db.reloadRouting(); - } + assertThat(db.collection(COLLECTION_NAME).count().getCount(), is(1L)); + assertThat(db.collection(COLLECTION_NAME).getDocument("0", String.class), is(notNullValue())); + } finally { + db.collection(COLLECTION_NAME).drop(); + } + } + + @Test + public void transactionEmpty() { + db.transaction("function () {}", null, null); + } + + @Test + public void transactionallowImplicit() { + db.createCollection("someCollection", null); + db.createCollection("someOtherCollection", null); + final String action = "function (params) {" + "var db = require('internal').db;" + + "return {'a':db.someCollection.all().toArray()[0], 'b':db.someOtherCollection.all().toArray()[0]};" + + "}"; + final TransactionOptions options = new TransactionOptions().readCollections("someCollection"); + db.transaction(action, VPackSlice.class, options); + try { + options.allowImplicit(false); + db.transaction(action, VPackSlice.class, options); + fail(); + } catch (final ArangoDBException e) { + } + db.collection("someCollection").drop(); + db.collection("someOtherCollection").drop(); + } + + protected static class TransactionTestEntity { + private String value; + + public TransactionTestEntity() { + super(); + } + } + + @Test + public void transactionPojoReturn() { + final String action = "function() { return {'value':'hello world'}; }"; + final TransactionTestEntity res = db.transaction(action, TransactionTestEntity.class, new TransactionOptions()); + assertThat(res, is(notNullValue())); + assertThat(res.value, is("hello world")); + } + + @Test + public void getInfo() { + final DatabaseEntity info = db.getInfo(); + assertThat(info, is(notNullValue())); + assertThat(info.getId(), is(notNullValue())); + assertThat(info.getName(), is(TEST_DB)); + assertThat(info.getPath(), is(notNullValue())); + assertThat(info.getIsSystem(), is(false)); + } + + @Test + public void executeTraversal() { + try { + db.createCollection("person", null); + db.createCollection("knows", new CollectionCreateOptions().type(CollectionType.EDGES)); + for (final String e : new String[]{"Alice", "Bob", "Charlie", "Dave", "Eve"}) { + final BaseDocument doc = new BaseDocument(); + doc.setKey(e); + db.collection("person").insertDocument(doc, null); + } + for (final String[] e : new String[][]{new String[]{"Alice", "Bob"}, new String[]{"Bob", "Charlie"}, + new String[]{"Bob", "Dave"}, new String[]{"Eve", "Alice"}, new String[]{"Eve", "Bob"}}) { + final BaseEdgeDocument edge = new BaseEdgeDocument(); + edge.setKey(e[0] + "_knows_" + e[1]); + edge.setFrom("person/" + e[0]); + edge.setTo("person/" + e[1]); + db.collection("knows").insertDocument(edge, null); + } + final TraversalOptions options = new TraversalOptions().edgeCollection("knows").startVertex("person/Alice") + .direction(Direction.outbound); + final TraversalEntity traversal = db + .executeTraversal(BaseDocument.class, BaseEdgeDocument.class, options); + + assertThat(traversal, is(notNullValue())); + + final Collection vertices = traversal.getVertices(); + assertThat(vertices, is(notNullValue())); + assertThat(vertices.size(), is(4)); + + final Iterator verticesIterator = vertices.iterator(); + final Collection v = Arrays.asList(new String[]{"Alice", "Bob", "Charlie", "Dave"}); + for (; verticesIterator.hasNext(); ) { + assertThat(v.contains(verticesIterator.next().getKey()), is(true)); + } + + final Collection> paths = traversal.getPaths(); + assertThat(paths, is(notNullValue())); + assertThat(paths.size(), is(4)); + + assertThat(paths.iterator().hasNext(), is(true)); + final PathEntity first = paths.iterator().next(); + assertThat(first, is(notNullValue())); + assertThat(first.getEdges().size(), is(0)); + assertThat(first.getVertices().size(), is(1)); + assertThat(first.getVertices().iterator().next().getKey(), is("Alice")); + } finally { + db.collection("person").drop(); + db.collection("knows").drop(); + } + } + + @Test + public void getDocument() { + try { + db.createCollection(COLLECTION_NAME); + final BaseDocument value = new BaseDocument(); + value.setKey("123"); + db.collection(COLLECTION_NAME).insertDocument(value); + final BaseDocument document = db.getDocument(COLLECTION_NAME + "/123", BaseDocument.class); + assertThat(document, is(notNullValue())); + assertThat(document.getKey(), is("123")); + } finally { + db.collection(COLLECTION_NAME).drop(); + } + } + + @Test + public void shouldIncludeExceptionMessage() { + if (!requireVersion(3, 2)) { + final String exceptionMessage = "My error context"; + final String action = "function (params) {" + "throw '" + exceptionMessage + "';" + "}"; + try { + db.transaction(action, VPackSlice.class, null); + fail(); + } catch (final ArangoDBException e) { + assertTrue(e.getException().contains(exceptionMessage)); + } + } + } + + @Test(expected = ArangoDBException.class) + public void getDocumentWrongId() { + db.getDocument("123", BaseDocument.class); + } + + @Test + public void reloadRouting() { + db.reloadRouting(); + } } diff --git a/src/test/java/com/arangodb/ArangoEdgeCollectionTest.java b/src/test/java/com/arangodb/ArangoEdgeCollectionTest.java index c12782c27..e95625542 100644 --- a/src/test/java/com/arangodb/ArangoEdgeCollectionTest.java +++ b/src/test/java/com/arangodb/ArangoEdgeCollectionTest.java @@ -51,393 +51,385 @@ /** * @author Mark Vollmary - * */ @RunWith(Parameterized.class) public class ArangoEdgeCollectionTest extends BaseTest { - private static final String GRAPH_NAME = "db_collection_test"; - private static final String EDGE_COLLECTION_NAME = "db_edge_collection_test"; - private static final String VERTEX_COLLECTION_NAME = "db_vertex_collection_test"; - - public ArangoEdgeCollectionTest(final Builder builder) { - super(builder); - } - - @Before - public void setup() { - try { - db.graph(GRAPH_NAME).drop(true); - } catch (final ArangoDBException e) { - } - - try { - db.createCollection(VERTEX_COLLECTION_NAME, null); - } catch (final ArangoDBException e) { - } - - try { - db.createCollection(EDGE_COLLECTION_NAME, new CollectionCreateOptions().type(CollectionType.EDGES)); - } catch (final ArangoDBException e) { - } - - final Collection edgeDefinitions = new ArrayList(); - edgeDefinitions.add(new EdgeDefinition().collection(EDGE_COLLECTION_NAME).from(VERTEX_COLLECTION_NAME) - .to(VERTEX_COLLECTION_NAME)); - db.createGraph(GRAPH_NAME, edgeDefinitions, null); - } - - @After - public void teardown() { - for (final String collection : new String[] { VERTEX_COLLECTION_NAME, EDGE_COLLECTION_NAME }) { - db.collection(collection).truncate(); - } - - try { - db.graph(GRAPH_NAME).drop(true); - } catch (final ArangoDBException e) {} - } - - private BaseEdgeDocument createEdgeValue() { - final VertexEntity v1 = db.graph(GRAPH_NAME).vertexCollection(VERTEX_COLLECTION_NAME) - .insertVertex(new BaseDocument(), null); - final VertexEntity v2 = db.graph(GRAPH_NAME).vertexCollection(VERTEX_COLLECTION_NAME) - .insertVertex(new BaseDocument(), null); - - final BaseEdgeDocument value = new BaseEdgeDocument(); - value.setFrom(v1.getId()); - value.setTo(v2.getId()); - return value; - } - - @Test - public void insertEdge() { - final BaseEdgeDocument value = createEdgeValue(); - final EdgeEntity edge = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).insertEdge(value, null); - assertThat(edge, is(notNullValue())); - final BaseEdgeDocument document = db.collection(EDGE_COLLECTION_NAME).getDocument(edge.getKey(), - BaseEdgeDocument.class, null); - assertThat(document, is(notNullValue())); - assertThat(document.getKey(), is(edge.getKey())); - assertThat(document.getFrom(), is(notNullValue())); - assertThat(document.getTo(), is(notNullValue())); - } - - @Test - public void insertEdgeUpdateRev() { - final BaseEdgeDocument value = createEdgeValue(); - final EdgeEntity edge = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).insertEdge(value, null); - assertThat(value.getRevision(), is(edge.getRev())); - } - - @Test - public void insertEdgeViolatingUniqueConstraint() { - // FIXME: remove once fix is backported to 3.4 - assumeTrue(requireVersion(3, 5)); - - db.collection(EDGE_COLLECTION_NAME) - .ensureSkiplistIndex(Arrays.asList("_from", "_to"), new SkiplistIndexOptions().unique(true)); - - final VertexEntity v1 = db.graph(GRAPH_NAME).vertexCollection(VERTEX_COLLECTION_NAME) - .insertVertex(new BaseDocument("v1"), null); - final VertexEntity v2 = db.graph(GRAPH_NAME).vertexCollection(VERTEX_COLLECTION_NAME) - .insertVertex(new BaseDocument("v2"), null); - - BaseEdgeDocument edge = new BaseEdgeDocument(); - edge.setFrom(v1.getId()); - edge.setTo(v2.getId()); - - db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).insertEdge(edge, null); - - try { - db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).insertEdge(edge, null); - } catch (ArangoDBException e) { - assertThat(e.getResponseCode(), is(409)); - assertThat(e.getErrorNum(), is(1210)); - } - } - - @Test - public void getEdge() { - final BaseEdgeDocument value = createEdgeValue(); - final EdgeEntity edge = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).insertEdge(value, null); - final BaseEdgeDocument document = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME) - .getEdge(edge.getKey(), BaseEdgeDocument.class, null); - assertThat(document, is(notNullValue())); - assertThat(document.getKey(), is(edge.getKey())); - assertThat(document.getFrom(), is(notNullValue())); - assertThat(document.getTo(), is(notNullValue())); - } - - @Test - public void getEdgeIfMatch() { - final BaseEdgeDocument value = createEdgeValue(); - final EdgeEntity edge = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).insertEdge(value, null); - final GraphDocumentReadOptions options = new GraphDocumentReadOptions().ifMatch(edge.getRev()); - final BaseDocument document = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).getEdge(edge.getKey(), - BaseDocument.class, options); - assertThat(document, is(notNullValue())); - assertThat(document.getKey(), is(edge.getKey())); - } - - @Test - public void getEdgeIfMatchFail() { - final BaseEdgeDocument value = createEdgeValue(); - final EdgeEntity edge = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).insertEdge(value, null); - final GraphDocumentReadOptions options = new GraphDocumentReadOptions().ifMatch("no"); - final BaseEdgeDocument edge2 = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).getEdge(edge.getKey(), - BaseEdgeDocument.class, options); - assertThat(edge2, is(nullValue())); - } - - @Test - public void getEdgeIfNoneMatch() { - final BaseEdgeDocument value = createEdgeValue(); - final EdgeEntity edge = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).insertEdge(value, null); - final GraphDocumentReadOptions options = new GraphDocumentReadOptions().ifNoneMatch("no"); - final BaseDocument document = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).getEdge(edge.getKey(), - BaseDocument.class, options); - assertThat(document, is(notNullValue())); - assertThat(document.getKey(), is(edge.getKey())); - } - - @Test - public void getEdgeIfNoneMatchFail() { - final BaseEdgeDocument value = createEdgeValue(); - final EdgeEntity edge = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).insertEdge(value, null); - final GraphDocumentReadOptions options = new GraphDocumentReadOptions().ifNoneMatch(edge.getRev()); - final BaseEdgeDocument edge2 = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).getEdge(edge.getKey(), - BaseEdgeDocument.class, options); - assertThat(edge2, is(nullValue())); - } - - @Test - public void replaceEdge() { - final BaseEdgeDocument doc = createEdgeValue(); - doc.addAttribute("a", "test"); - final EdgeEntity createResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).insertEdge(doc, null); - doc.getProperties().clear(); - doc.addAttribute("b", "test"); - final EdgeUpdateEntity replaceResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME) - .replaceEdge(createResult.getKey(), doc, null); - assertThat(replaceResult, is(notNullValue())); - assertThat(replaceResult.getId(), is(createResult.getId())); - assertThat(replaceResult.getRev(), is(not(replaceResult.getOldRev()))); - assertThat(replaceResult.getOldRev(), is(createResult.getRev())); - - final BaseEdgeDocument readResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME) - .getEdge(createResult.getKey(), BaseEdgeDocument.class, null); - assertThat(readResult.getKey(), is(createResult.getKey())); - assertThat(readResult.getRevision(), is(replaceResult.getRev())); - assertThat(readResult.getProperties().keySet(), not(hasItem("a"))); - assertThat(readResult.getAttribute("b"), is(notNullValue())); - assertThat(String.valueOf(readResult.getAttribute("b")), is("test")); - } - - @Test - public void replaceEdgeUpdateRev() { - final BaseEdgeDocument doc = createEdgeValue(); - final EdgeEntity createResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).insertEdge(doc, null); - assertThat(doc.getRevision(), is(createResult.getRev())); - final EdgeUpdateEntity replaceResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME) - .replaceEdge(createResult.getKey(), doc, null); - assertThat(doc.getRevision(), is(replaceResult.getRev())); - } - - @Test - public void replaceEdgeIfMatch() { - final BaseEdgeDocument doc = createEdgeValue(); - doc.addAttribute("a", "test"); - final EdgeEntity createResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).insertEdge(doc, null); - doc.getProperties().clear(); - doc.addAttribute("b", "test"); - final EdgeReplaceOptions options = new EdgeReplaceOptions().ifMatch(createResult.getRev()); - final EdgeUpdateEntity replaceResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME) - .replaceEdge(createResult.getKey(), doc, options); - assertThat(replaceResult, is(notNullValue())); - assertThat(replaceResult.getId(), is(createResult.getId())); - assertThat(replaceResult.getRev(), is(not(replaceResult.getOldRev()))); - assertThat(replaceResult.getOldRev(), is(createResult.getRev())); - - final BaseEdgeDocument readResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME) - .getEdge(createResult.getKey(), BaseEdgeDocument.class, null); - assertThat(readResult.getKey(), is(createResult.getKey())); - assertThat(readResult.getRevision(), is(replaceResult.getRev())); - assertThat(readResult.getProperties().keySet(), not(hasItem("a"))); - assertThat(readResult.getAttribute("b"), is(notNullValue())); - assertThat(String.valueOf(readResult.getAttribute("b")), is("test")); - } - - @Test - public void replaceEdgeIfMatchFail() { - final BaseEdgeDocument doc = createEdgeValue(); - doc.addAttribute("a", "test"); - final EdgeEntity createResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).insertEdge(doc, null); - doc.getProperties().clear(); - doc.addAttribute("b", "test"); - try { - final EdgeReplaceOptions options = new EdgeReplaceOptions().ifMatch("no"); - db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).replaceEdge(createResult.getKey(), doc, options); - fail(); - } catch (final ArangoDBException e) { - } - } - - @Test - public void updateEdge() { - final BaseEdgeDocument doc = createEdgeValue(); - doc.addAttribute("a", "test"); - doc.addAttribute("c", "test"); - final EdgeEntity createResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).insertEdge(doc, null); - doc.updateAttribute("a", "test1"); - doc.addAttribute("b", "test"); - doc.updateAttribute("c", null); - final EdgeUpdateEntity updateResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME) - .updateEdge(createResult.getKey(), doc, null); - assertThat(updateResult, is(notNullValue())); - assertThat(updateResult.getId(), is(createResult.getId())); - assertThat(updateResult.getRev(), is(not(updateResult.getOldRev()))); - assertThat(updateResult.getOldRev(), is(createResult.getRev())); - - final BaseEdgeDocument readResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME) - .getEdge(createResult.getKey(), BaseEdgeDocument.class, null); - assertThat(readResult.getKey(), is(createResult.getKey())); - assertThat(readResult.getAttribute("a"), is(notNullValue())); - assertThat(String.valueOf(readResult.getAttribute("a")), is("test1")); - assertThat(readResult.getAttribute("b"), is(notNullValue())); - assertThat(String.valueOf(readResult.getAttribute("b")), is("test")); - assertThat(readResult.getRevision(), is(updateResult.getRev())); - assertThat(readResult.getProperties().keySet(), hasItem("c")); - } - - @Test - public void updateEdgeUpdateRev() { - final BaseEdgeDocument doc = createEdgeValue(); - final EdgeEntity createResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).insertEdge(doc, null); - assertThat(doc.getRevision(), is(createResult.getRev())); - final EdgeUpdateEntity updateResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME) - .updateEdge(createResult.getKey(), doc, null); - assertThat(doc.getRevision(), is(updateResult.getRev())); - } - - @Test - public void updateEdgeIfMatch() { - final BaseEdgeDocument doc = createEdgeValue(); - doc.addAttribute("a", "test"); - doc.addAttribute("c", "test"); - final EdgeEntity createResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).insertEdge(doc, null); - doc.updateAttribute("a", "test1"); - doc.addAttribute("b", "test"); - doc.updateAttribute("c", null); - final EdgeUpdateOptions options = new EdgeUpdateOptions().ifMatch(createResult.getRev()); - final EdgeUpdateEntity updateResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME) - .updateEdge(createResult.getKey(), doc, options); - assertThat(updateResult, is(notNullValue())); - assertThat(updateResult.getId(), is(createResult.getId())); - assertThat(updateResult.getRev(), is(not(updateResult.getOldRev()))); - assertThat(updateResult.getOldRev(), is(createResult.getRev())); - - final BaseEdgeDocument readResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME) - .getEdge(createResult.getKey(), BaseEdgeDocument.class, null); - assertThat(readResult.getKey(), is(createResult.getKey())); - assertThat(readResult.getAttribute("a"), is(notNullValue())); - assertThat(String.valueOf(readResult.getAttribute("a")), is("test1")); - assertThat(readResult.getAttribute("b"), is(notNullValue())); - assertThat(String.valueOf(readResult.getAttribute("b")), is("test")); - assertThat(readResult.getRevision(), is(updateResult.getRev())); - assertThat(readResult.getProperties().keySet(), hasItem("c")); - } - - @Test - public void updateEdgeIfMatchFail() { - final BaseEdgeDocument doc = createEdgeValue(); - doc.addAttribute("a", "test"); - doc.addAttribute("c", "test"); - final EdgeEntity createResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).insertEdge(doc, null); - doc.updateAttribute("a", "test1"); - doc.addAttribute("b", "test"); - doc.updateAttribute("c", null); - try { - final EdgeUpdateOptions options = new EdgeUpdateOptions().ifMatch("no"); - db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).updateEdge(createResult.getKey(), doc, options); - fail(); - } catch (final ArangoDBException e) { - } - } - - @Test - public void updateEdgeKeepNullTrue() { - final BaseEdgeDocument doc = createEdgeValue(); - doc.addAttribute("a", "test"); - final EdgeEntity createResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).insertEdge(doc, null); - doc.updateAttribute("a", null); - final EdgeUpdateOptions options = new EdgeUpdateOptions().keepNull(true); - final EdgeUpdateEntity updateResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME) - .updateEdge(createResult.getKey(), doc, options); - assertThat(updateResult, is(notNullValue())); - assertThat(updateResult.getId(), is(createResult.getId())); - assertThat(updateResult.getRev(), is(not(updateResult.getOldRev()))); - assertThat(updateResult.getOldRev(), is(createResult.getRev())); - - final BaseEdgeDocument readResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME) - .getEdge(createResult.getKey(), BaseEdgeDocument.class, null); - assertThat(readResult.getKey(), is(createResult.getKey())); - assertThat(readResult.getProperties().keySet().size(), is(1)); - assertThat(readResult.getProperties().keySet(), hasItem("a")); - } - - @Test - public void updateEdgeKeepNullFalse() { - final BaseEdgeDocument doc = createEdgeValue(); - doc.addAttribute("a", "test"); - final EdgeEntity createResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).insertEdge(doc, null); - doc.updateAttribute("a", null); - final EdgeUpdateOptions options = new EdgeUpdateOptions().keepNull(false); - final EdgeUpdateEntity updateResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME) - .updateEdge(createResult.getKey(), doc, options); - assertThat(updateResult, is(notNullValue())); - assertThat(updateResult.getId(), is(createResult.getId())); - assertThat(updateResult.getRev(), is(not(updateResult.getOldRev()))); - assertThat(updateResult.getOldRev(), is(createResult.getRev())); - - final BaseEdgeDocument readResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME) - .getEdge(createResult.getKey(), BaseEdgeDocument.class, null); - assertThat(readResult.getKey(), is(createResult.getKey())); - assertThat(readResult.getId(), is(createResult.getId())); - assertThat(readResult.getRevision(), is(notNullValue())); - assertThat(readResult.getProperties().keySet(), not(hasItem("a"))); - } - - @Test - public void deleteEdge() { - final BaseEdgeDocument doc = createEdgeValue(); - final EdgeEntity createResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).insertEdge(doc, null); - db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).deleteEdge(createResult.getKey(), null); - final BaseEdgeDocument edge = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME) - .getEdge(createResult.getKey(), BaseEdgeDocument.class, null); - assertThat(edge, is(nullValue())); - } - - @Test - public void deleteEdgeIfMatch() { - final BaseEdgeDocument doc = createEdgeValue(); - final EdgeEntity createResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).insertEdge(doc, null); - final EdgeDeleteOptions options = new EdgeDeleteOptions().ifMatch(createResult.getRev()); - db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).deleteEdge(createResult.getKey(), options); - final BaseEdgeDocument edge = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME) - .getEdge(createResult.getKey(), BaseEdgeDocument.class, null); - assertThat(edge, is(nullValue())); - } - - @Test - public void deleteEdgeIfMatchFail() { - final BaseEdgeDocument doc = createEdgeValue(); - final EdgeEntity createResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).insertEdge(doc, null); - final EdgeDeleteOptions options = new EdgeDeleteOptions().ifMatch("no"); - try { - db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).deleteEdge(createResult.getKey(), options); - fail(); - } catch (final ArangoDBException e) { - } - } + private static final String GRAPH_NAME = "db_collection_test"; + private static final String EDGE_COLLECTION_NAME = "db_edge_collection_test"; + private static final String VERTEX_COLLECTION_NAME = "db_vertex_collection_test"; + + public ArangoEdgeCollectionTest(final Builder builder) { + super(builder); + } + + @Before + public void setup() { + if (db.graph(GRAPH_NAME).exists()) + db.graph(GRAPH_NAME).drop(true); + + if (!db.collection(VERTEX_COLLECTION_NAME).exists()) + db.createCollection(VERTEX_COLLECTION_NAME, null); + + if (!db.collection(EDGE_COLLECTION_NAME).exists()) + db.createCollection(EDGE_COLLECTION_NAME, new CollectionCreateOptions().type(CollectionType.EDGES)); + + final Collection edgeDefinitions = new ArrayList(); + edgeDefinitions.add(new EdgeDefinition().collection(EDGE_COLLECTION_NAME).from(VERTEX_COLLECTION_NAME) + .to(VERTEX_COLLECTION_NAME)); + db.createGraph(GRAPH_NAME, edgeDefinitions, null); + } + + @After + public void teardown() { + for (final String collection : new String[]{VERTEX_COLLECTION_NAME, EDGE_COLLECTION_NAME}) { + db.collection(collection).truncate(); + } + + if (db.graph(GRAPH_NAME).exists()) + db.graph(GRAPH_NAME).drop(true); + } + + private BaseEdgeDocument createEdgeValue() { + final VertexEntity v1 = db.graph(GRAPH_NAME).vertexCollection(VERTEX_COLLECTION_NAME) + .insertVertex(new BaseDocument(), null); + final VertexEntity v2 = db.graph(GRAPH_NAME).vertexCollection(VERTEX_COLLECTION_NAME) + .insertVertex(new BaseDocument(), null); + + final BaseEdgeDocument value = new BaseEdgeDocument(); + value.setFrom(v1.getId()); + value.setTo(v2.getId()); + return value; + } + + @Test + public void insertEdge() { + final BaseEdgeDocument value = createEdgeValue(); + final EdgeEntity edge = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).insertEdge(value, null); + assertThat(edge, is(notNullValue())); + final BaseEdgeDocument document = db.collection(EDGE_COLLECTION_NAME).getDocument(edge.getKey(), + BaseEdgeDocument.class, null); + assertThat(document, is(notNullValue())); + assertThat(document.getKey(), is(edge.getKey())); + assertThat(document.getFrom(), is(notNullValue())); + assertThat(document.getTo(), is(notNullValue())); + } + + @Test + public void insertEdgeUpdateRev() { + final BaseEdgeDocument value = createEdgeValue(); + final EdgeEntity edge = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).insertEdge(value, null); + assertThat(value.getRevision(), is(edge.getRev())); + } + + @Test + public void insertEdgeViolatingUniqueConstraint() { + // FIXME: remove once fix is backported to 3.4 + assumeTrue(requireVersion(3, 5)); + + db.collection(EDGE_COLLECTION_NAME) + .ensureSkiplistIndex(Arrays.asList("_from", "_to"), new SkiplistIndexOptions().unique(true)); + + final VertexEntity v1 = db.graph(GRAPH_NAME).vertexCollection(VERTEX_COLLECTION_NAME) + .insertVertex(new BaseDocument("v1"), null); + final VertexEntity v2 = db.graph(GRAPH_NAME).vertexCollection(VERTEX_COLLECTION_NAME) + .insertVertex(new BaseDocument("v2"), null); + + BaseEdgeDocument edge = new BaseEdgeDocument(); + edge.setFrom(v1.getId()); + edge.setTo(v2.getId()); + + db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).insertEdge(edge, null); + + try { + db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).insertEdge(edge, null); + } catch (ArangoDBException e) { + assertThat(e.getResponseCode(), is(409)); + assertThat(e.getErrorNum(), is(1210)); + } + } + + @Test + public void getEdge() { + final BaseEdgeDocument value = createEdgeValue(); + final EdgeEntity edge = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).insertEdge(value, null); + final BaseEdgeDocument document = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME) + .getEdge(edge.getKey(), BaseEdgeDocument.class, null); + assertThat(document, is(notNullValue())); + assertThat(document.getKey(), is(edge.getKey())); + assertThat(document.getFrom(), is(notNullValue())); + assertThat(document.getTo(), is(notNullValue())); + } + + @Test + public void getEdgeIfMatch() { + final BaseEdgeDocument value = createEdgeValue(); + final EdgeEntity edge = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).insertEdge(value, null); + final GraphDocumentReadOptions options = new GraphDocumentReadOptions().ifMatch(edge.getRev()); + final BaseDocument document = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).getEdge(edge.getKey(), + BaseDocument.class, options); + assertThat(document, is(notNullValue())); + assertThat(document.getKey(), is(edge.getKey())); + } + + @Test + public void getEdgeIfMatchFail() { + final BaseEdgeDocument value = createEdgeValue(); + final EdgeEntity edge = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).insertEdge(value, null); + final GraphDocumentReadOptions options = new GraphDocumentReadOptions().ifMatch("no"); + final BaseEdgeDocument edge2 = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).getEdge(edge.getKey(), + BaseEdgeDocument.class, options); + assertThat(edge2, is(nullValue())); + } + + @Test + public void getEdgeIfNoneMatch() { + final BaseEdgeDocument value = createEdgeValue(); + final EdgeEntity edge = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).insertEdge(value, null); + final GraphDocumentReadOptions options = new GraphDocumentReadOptions().ifNoneMatch("no"); + final BaseDocument document = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).getEdge(edge.getKey(), + BaseDocument.class, options); + assertThat(document, is(notNullValue())); + assertThat(document.getKey(), is(edge.getKey())); + } + + @Test + public void getEdgeIfNoneMatchFail() { + final BaseEdgeDocument value = createEdgeValue(); + final EdgeEntity edge = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).insertEdge(value, null); + final GraphDocumentReadOptions options = new GraphDocumentReadOptions().ifNoneMatch(edge.getRev()); + final BaseEdgeDocument edge2 = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).getEdge(edge.getKey(), + BaseEdgeDocument.class, options); + assertThat(edge2, is(nullValue())); + } + + @Test + public void replaceEdge() { + final BaseEdgeDocument doc = createEdgeValue(); + doc.addAttribute("a", "test"); + final EdgeEntity createResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).insertEdge(doc, null); + doc.getProperties().clear(); + doc.addAttribute("b", "test"); + final EdgeUpdateEntity replaceResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME) + .replaceEdge(createResult.getKey(), doc, null); + assertThat(replaceResult, is(notNullValue())); + assertThat(replaceResult.getId(), is(createResult.getId())); + assertThat(replaceResult.getRev(), is(not(replaceResult.getOldRev()))); + assertThat(replaceResult.getOldRev(), is(createResult.getRev())); + + final BaseEdgeDocument readResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME) + .getEdge(createResult.getKey(), BaseEdgeDocument.class, null); + assertThat(readResult.getKey(), is(createResult.getKey())); + assertThat(readResult.getRevision(), is(replaceResult.getRev())); + assertThat(readResult.getProperties().keySet(), not(hasItem("a"))); + assertThat(readResult.getAttribute("b"), is(notNullValue())); + assertThat(String.valueOf(readResult.getAttribute("b")), is("test")); + } + + @Test + public void replaceEdgeUpdateRev() { + final BaseEdgeDocument doc = createEdgeValue(); + final EdgeEntity createResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).insertEdge(doc, null); + assertThat(doc.getRevision(), is(createResult.getRev())); + final EdgeUpdateEntity replaceResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME) + .replaceEdge(createResult.getKey(), doc, null); + assertThat(doc.getRevision(), is(replaceResult.getRev())); + } + + @Test + public void replaceEdgeIfMatch() { + final BaseEdgeDocument doc = createEdgeValue(); + doc.addAttribute("a", "test"); + final EdgeEntity createResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).insertEdge(doc, null); + doc.getProperties().clear(); + doc.addAttribute("b", "test"); + final EdgeReplaceOptions options = new EdgeReplaceOptions().ifMatch(createResult.getRev()); + final EdgeUpdateEntity replaceResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME) + .replaceEdge(createResult.getKey(), doc, options); + assertThat(replaceResult, is(notNullValue())); + assertThat(replaceResult.getId(), is(createResult.getId())); + assertThat(replaceResult.getRev(), is(not(replaceResult.getOldRev()))); + assertThat(replaceResult.getOldRev(), is(createResult.getRev())); + + final BaseEdgeDocument readResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME) + .getEdge(createResult.getKey(), BaseEdgeDocument.class, null); + assertThat(readResult.getKey(), is(createResult.getKey())); + assertThat(readResult.getRevision(), is(replaceResult.getRev())); + assertThat(readResult.getProperties().keySet(), not(hasItem("a"))); + assertThat(readResult.getAttribute("b"), is(notNullValue())); + assertThat(String.valueOf(readResult.getAttribute("b")), is("test")); + } + + @Test + public void replaceEdgeIfMatchFail() { + final BaseEdgeDocument doc = createEdgeValue(); + doc.addAttribute("a", "test"); + final EdgeEntity createResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).insertEdge(doc, null); + doc.getProperties().clear(); + doc.addAttribute("b", "test"); + try { + final EdgeReplaceOptions options = new EdgeReplaceOptions().ifMatch("no"); + db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).replaceEdge(createResult.getKey(), doc, options); + fail(); + } catch (final ArangoDBException e) { + } + } + + @Test + public void updateEdge() { + final BaseEdgeDocument doc = createEdgeValue(); + doc.addAttribute("a", "test"); + doc.addAttribute("c", "test"); + final EdgeEntity createResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).insertEdge(doc, null); + doc.updateAttribute("a", "test1"); + doc.addAttribute("b", "test"); + doc.updateAttribute("c", null); + final EdgeUpdateEntity updateResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME) + .updateEdge(createResult.getKey(), doc, null); + assertThat(updateResult, is(notNullValue())); + assertThat(updateResult.getId(), is(createResult.getId())); + assertThat(updateResult.getRev(), is(not(updateResult.getOldRev()))); + assertThat(updateResult.getOldRev(), is(createResult.getRev())); + + final BaseEdgeDocument readResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME) + .getEdge(createResult.getKey(), BaseEdgeDocument.class, null); + assertThat(readResult.getKey(), is(createResult.getKey())); + assertThat(readResult.getAttribute("a"), is(notNullValue())); + assertThat(String.valueOf(readResult.getAttribute("a")), is("test1")); + assertThat(readResult.getAttribute("b"), is(notNullValue())); + assertThat(String.valueOf(readResult.getAttribute("b")), is("test")); + assertThat(readResult.getRevision(), is(updateResult.getRev())); + assertThat(readResult.getProperties().keySet(), hasItem("c")); + } + + @Test + public void updateEdgeUpdateRev() { + final BaseEdgeDocument doc = createEdgeValue(); + final EdgeEntity createResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).insertEdge(doc, null); + assertThat(doc.getRevision(), is(createResult.getRev())); + final EdgeUpdateEntity updateResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME) + .updateEdge(createResult.getKey(), doc, null); + assertThat(doc.getRevision(), is(updateResult.getRev())); + } + + @Test + public void updateEdgeIfMatch() { + final BaseEdgeDocument doc = createEdgeValue(); + doc.addAttribute("a", "test"); + doc.addAttribute("c", "test"); + final EdgeEntity createResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).insertEdge(doc, null); + doc.updateAttribute("a", "test1"); + doc.addAttribute("b", "test"); + doc.updateAttribute("c", null); + final EdgeUpdateOptions options = new EdgeUpdateOptions().ifMatch(createResult.getRev()); + final EdgeUpdateEntity updateResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME) + .updateEdge(createResult.getKey(), doc, options); + assertThat(updateResult, is(notNullValue())); + assertThat(updateResult.getId(), is(createResult.getId())); + assertThat(updateResult.getRev(), is(not(updateResult.getOldRev()))); + assertThat(updateResult.getOldRev(), is(createResult.getRev())); + + final BaseEdgeDocument readResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME) + .getEdge(createResult.getKey(), BaseEdgeDocument.class, null); + assertThat(readResult.getKey(), is(createResult.getKey())); + assertThat(readResult.getAttribute("a"), is(notNullValue())); + assertThat(String.valueOf(readResult.getAttribute("a")), is("test1")); + assertThat(readResult.getAttribute("b"), is(notNullValue())); + assertThat(String.valueOf(readResult.getAttribute("b")), is("test")); + assertThat(readResult.getRevision(), is(updateResult.getRev())); + assertThat(readResult.getProperties().keySet(), hasItem("c")); + } + + @Test + public void updateEdgeIfMatchFail() { + final BaseEdgeDocument doc = createEdgeValue(); + doc.addAttribute("a", "test"); + doc.addAttribute("c", "test"); + final EdgeEntity createResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).insertEdge(doc, null); + doc.updateAttribute("a", "test1"); + doc.addAttribute("b", "test"); + doc.updateAttribute("c", null); + try { + final EdgeUpdateOptions options = new EdgeUpdateOptions().ifMatch("no"); + db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).updateEdge(createResult.getKey(), doc, options); + fail(); + } catch (final ArangoDBException e) { + } + } + + @Test + public void updateEdgeKeepNullTrue() { + final BaseEdgeDocument doc = createEdgeValue(); + doc.addAttribute("a", "test"); + final EdgeEntity createResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).insertEdge(doc, null); + doc.updateAttribute("a", null); + final EdgeUpdateOptions options = new EdgeUpdateOptions().keepNull(true); + final EdgeUpdateEntity updateResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME) + .updateEdge(createResult.getKey(), doc, options); + assertThat(updateResult, is(notNullValue())); + assertThat(updateResult.getId(), is(createResult.getId())); + assertThat(updateResult.getRev(), is(not(updateResult.getOldRev()))); + assertThat(updateResult.getOldRev(), is(createResult.getRev())); + + final BaseEdgeDocument readResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME) + .getEdge(createResult.getKey(), BaseEdgeDocument.class, null); + assertThat(readResult.getKey(), is(createResult.getKey())); + assertThat(readResult.getProperties().keySet().size(), is(1)); + assertThat(readResult.getProperties().keySet(), hasItem("a")); + } + + @Test + public void updateEdgeKeepNullFalse() { + final BaseEdgeDocument doc = createEdgeValue(); + doc.addAttribute("a", "test"); + final EdgeEntity createResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).insertEdge(doc, null); + doc.updateAttribute("a", null); + final EdgeUpdateOptions options = new EdgeUpdateOptions().keepNull(false); + final EdgeUpdateEntity updateResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME) + .updateEdge(createResult.getKey(), doc, options); + assertThat(updateResult, is(notNullValue())); + assertThat(updateResult.getId(), is(createResult.getId())); + assertThat(updateResult.getRev(), is(not(updateResult.getOldRev()))); + assertThat(updateResult.getOldRev(), is(createResult.getRev())); + + final BaseEdgeDocument readResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME) + .getEdge(createResult.getKey(), BaseEdgeDocument.class, null); + assertThat(readResult.getKey(), is(createResult.getKey())); + assertThat(readResult.getId(), is(createResult.getId())); + assertThat(readResult.getRevision(), is(notNullValue())); + assertThat(readResult.getProperties().keySet(), not(hasItem("a"))); + } + + @Test + public void deleteEdge() { + final BaseEdgeDocument doc = createEdgeValue(); + final EdgeEntity createResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).insertEdge(doc, null); + db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).deleteEdge(createResult.getKey(), null); + final BaseEdgeDocument edge = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME) + .getEdge(createResult.getKey(), BaseEdgeDocument.class, null); + assertThat(edge, is(nullValue())); + } + + @Test + public void deleteEdgeIfMatch() { + final BaseEdgeDocument doc = createEdgeValue(); + final EdgeEntity createResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).insertEdge(doc, null); + final EdgeDeleteOptions options = new EdgeDeleteOptions().ifMatch(createResult.getRev()); + db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).deleteEdge(createResult.getKey(), options); + final BaseEdgeDocument edge = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME) + .getEdge(createResult.getKey(), BaseEdgeDocument.class, null); + assertThat(edge, is(nullValue())); + } + + @Test + public void deleteEdgeIfMatchFail() { + final BaseEdgeDocument doc = createEdgeValue(); + final EdgeEntity createResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).insertEdge(doc, null); + final EdgeDeleteOptions options = new EdgeDeleteOptions().ifMatch("no"); + try { + db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).deleteEdge(createResult.getKey(), options); + fail(); + } catch (final ArangoDBException e) { + } + } } diff --git a/src/test/java/com/arangodb/ArangoGraphTest.java b/src/test/java/com/arangodb/ArangoGraphTest.java index 1b5698e2d..a970ba005 100644 --- a/src/test/java/com/arangodb/ArangoGraphTest.java +++ b/src/test/java/com/arangodb/ArangoGraphTest.java @@ -70,10 +70,8 @@ public ArangoGraphTest(final Builder builder) { @Before public void setup() { - try { + if (db.graph(GRAPH_NAME).exists()) db.graph(GRAPH_NAME).drop(true); - } catch (final ArangoDBException e1) { - } final Collection edgeDefinitions = new ArrayList(); edgeDefinitions.add(new EdgeDefinition().collection(EDGE_COL_1).from(VERTEX_COL_1).to(VERTEX_COL_2)); edgeDefinitions @@ -260,16 +258,12 @@ public void smartGraph() { if (arangoDB.getVersion().getLicense() == License.ENTERPRISE) { for (final String collection : new String[]{EDGE_COL_1, EDGE_COL_2, VERTEX_COL_1, VERTEX_COL_2, VERTEX_COL_3, VERTEX_COL_4}) { - try { + if (db.collection(collection).exists()) db.collection(collection).drop(); - } catch (final ArangoDBException e) { - - } } - try { + + if (db.graph(GRAPH_NAME).exists()) db.graph(GRAPH_NAME).drop(); - } catch (final ArangoDBException e) { - } final Collection edgeDefinitions = new ArrayList(); diff --git a/src/test/java/com/arangodb/ArangoSearchTest.java b/src/test/java/com/arangodb/ArangoSearchTest.java index dab180661..a7f26ae52 100644 --- a/src/test/java/com/arangodb/ArangoSearchTest.java +++ b/src/test/java/com/arangodb/ArangoSearchTest.java @@ -37,6 +37,7 @@ import static org.hamcrest.Matchers.*; import static org.junit.Assert.assertThat; +import static org.junit.Assert.fail; /** * @author Mark Vollmary @@ -44,416 +45,405 @@ @RunWith(Parameterized.class) public class ArangoSearchTest extends BaseTest { - private static final String VIEW_NAME = "view_test"; - - public ArangoSearchTest(final Builder builder) { - super(builder); - } - - @After - public void teardown() { - try { - ArangoCollection c = db.collection("view_update_prop_test_collection"); - c.drop(); - } catch (final ArangoDBException e) { - } - - try { - ArangoCollection c = db.collection("view_replace_prop_test_collection"); - c.drop(); - } catch (final ArangoDBException e) { - } - - try { - db.view(VIEW_NAME).drop(); - } catch (final ArangoDBException e) { - } - } - - @Test - public void exists() { - if (!requireVersion(3, 4)) { - return; - } - db.createArangoSearch(VIEW_NAME, new ArangoSearchCreateOptions()); - assertThat(db.arangoSearch(VIEW_NAME).exists(), is(true)); - } - - @Test - public void getInfo() { - if (!requireVersion(3, 4)) { - return; - } - db.createArangoSearch(VIEW_NAME, new ArangoSearchCreateOptions()); - final ViewEntity info = db.arangoSearch(VIEW_NAME).getInfo(); - assertThat(info, is(not(nullValue()))); - assertThat(info.getId(), is(not(nullValue()))); - assertThat(info.getName(), is(VIEW_NAME)); - assertThat(info.getType(), is(ViewType.ARANGO_SEARCH)); - } - - @Test - public void drop() { - if (!requireVersion(3, 4)) { - return; - } - db.createArangoSearch(VIEW_NAME, new ArangoSearchCreateOptions()); - final ArangoView view = db.arangoSearch(VIEW_NAME); - view.drop(); - assertThat(view.exists(), is(false)); - } - - @Test - public void rename() { - if (arangoDB.getRole() != ServerRole.SINGLE) { - return; - } - if (!requireVersion(3, 4)) { - return; - } - final String name = VIEW_NAME + "_new"; - db.createArangoSearch(name, new ArangoSearchCreateOptions()); - db.arangoSearch(name).rename(VIEW_NAME); - assertThat(db.arangoSearch(name).exists(), is(false)); - assertThat(db.arangoSearch(VIEW_NAME).exists(), is(true)); - } - - @Test - public void create() { - if (!requireVersion(3, 4)) { - return; - } - final ViewEntity info = db.arangoSearch(VIEW_NAME).create(); - assertThat(info, is(not(nullValue()))); - assertThat(info.getId(), is(not(nullValue()))); - assertThat(info.getName(), is(VIEW_NAME)); - assertThat(info.getType(), is(ViewType.ARANGO_SEARCH)); - assertThat(db.arangoSearch(VIEW_NAME).exists(), is(true)); - } - - @Test - public void createWithOptions() { - if (!requireVersion(3, 4)) { - return; - } - final ArangoSearchCreateOptions options = new ArangoSearchCreateOptions(); - final ViewEntity info = db.arangoSearch(VIEW_NAME).create(options); - assertThat(info, is(not(nullValue()))); - assertThat(info.getId(), is(not(nullValue()))); - assertThat(info.getName(), is(VIEW_NAME)); - assertThat(info.getType(), is(ViewType.ARANGO_SEARCH)); - assertThat(db.arangoSearch(VIEW_NAME).exists(), is(true)); - } - - @Test - public void createWithPrimarySort() { - if (!requireVersion(3, 5)) { - return; - } - final ArangoSearchCreateOptions options = new ArangoSearchCreateOptions(); - - final PrimarySort primarySort = PrimarySort.on("myFieldName"); - primarySort.ascending(true); - options.primarySort(primarySort); - options.consolidationIntervalMsec(666666L); - - final ViewEntity info = db.arangoSearch(VIEW_NAME).create(options); - assertThat(info, is(not(nullValue()))); - assertThat(info.getId(), is(not(nullValue()))); - assertThat(info.getName(), is(VIEW_NAME)); - assertThat(info.getType(), is(ViewType.ARANGO_SEARCH)); - assertThat(db.arangoSearch(VIEW_NAME).exists(), is(true)); - } - - @Test - public void createWithCommitIntervalMsec() { - if (!requireVersion(3, 5)) { - return; - } - final ArangoSearchCreateOptions options = new ArangoSearchCreateOptions(); - options.commitIntervalMsec(666666L); - - final ViewEntity info = db.arangoSearch(VIEW_NAME).create(options); - assertThat(info, is(not(nullValue()))); - assertThat(info.getId(), is(not(nullValue()))); - assertThat(info.getName(), is(VIEW_NAME)); - assertThat(info.getType(), is(ViewType.ARANGO_SEARCH)); - assertThat(db.arangoSearch(VIEW_NAME).exists(), is(true)); - - // check commit interval msec property - final ArangoSearch view = db.arangoSearch(VIEW_NAME); - final ArangoSearchPropertiesEntity properties = view.getProperties(); - assertThat(properties.getCommitIntervalMsec(), is(666666L)); - } - - @Test - public void getProperties() { - if (!requireVersion(3, 4)) { - return; - } - final ArangoSearch view = db.arangoSearch(VIEW_NAME); - view.create(new ArangoSearchCreateOptions()); - final ArangoSearchPropertiesEntity properties = view.getProperties(); - assertThat(properties, is(not(nullValue()))); - assertThat(properties.getId(), is(not(nullValue()))); - assertThat(properties.getName(), is(VIEW_NAME)); - assertThat(properties.getType(), is(ViewType.ARANGO_SEARCH)); - assertThat(properties.getConsolidationIntervalMsec(), is(not(nullValue()))); - assertThat(properties.getCleanupIntervalStep(), is(not(nullValue()))); - final ConsolidationPolicy consolidate = properties.getConsolidationPolicy(); - assertThat(consolidate, is(is(not(nullValue())))); - final Collection links = properties.getLinks(); - assertThat(links.isEmpty(), is(true)); - } - - @Test - public void updateProperties() { - if (!requireVersion(3, 4)) { - return; - } - db.createCollection("view_update_prop_test_collection"); - final ArangoSearch view = db.arangoSearch(VIEW_NAME); - view.create(new ArangoSearchCreateOptions()); - final ArangoSearchPropertiesOptions options = new ArangoSearchPropertiesOptions(); - options.cleanupIntervalStep(15L); - options.consolidationIntervalMsec(65000L); - options.consolidationPolicy(ConsolidationPolicy.of(ConsolidationType.BYTES_ACCUM).threshold(1.)); - options.link(CollectionLink.on("view_update_prop_test_collection") - .fields(FieldLink.on("value").analyzers("identity").trackListPositions(true).includeAllFields(true) - .storeValues(StoreValuesType.ID))); - final ArangoSearchPropertiesEntity properties = view.updateProperties(options); - assertThat(properties, is(not(nullValue()))); - assertThat(properties.getCleanupIntervalStep(), is(15L)); - assertThat(properties.getConsolidationIntervalMsec(), is(65000L)); - final ConsolidationPolicy consolidate = properties.getConsolidationPolicy(); - assertThat(consolidate, is(not(nullValue()))); - assertThat(consolidate.getType(), is(ConsolidationType.BYTES_ACCUM)); - assertThat(consolidate.getThreshold(), is(1.)); - assertThat(properties.getLinks().size(), is(1)); - final CollectionLink link = properties.getLinks().iterator().next(); - assertThat(link.getName(), is("view_update_prop_test_collection")); - assertThat(link.getFields().size(), is(1)); - final FieldLink next = link.getFields().iterator().next(); - assertThat(next.getName(), is("value")); - assertThat(next.getIncludeAllFields(), is(true)); - assertThat(next.getTrackListPositions(), is(true)); - assertThat(next.getStoreValues(), is(StoreValuesType.ID)); - } - - @Test - public void replaceProperties() { - if (!requireVersion(3, 4)) { - return; - } - - db.createCollection("view_replace_prop_test_collection"); - final ArangoSearch view = db.arangoSearch(VIEW_NAME); - view.create(new ArangoSearchCreateOptions()); - final ArangoSearchPropertiesOptions options = new ArangoSearchPropertiesOptions(); - options.link(CollectionLink.on("view_replace_prop_test_collection") - .fields(FieldLink.on("value").analyzers("identity"))); - final ArangoSearchPropertiesEntity properties = view.replaceProperties(options); - assertThat(properties, is(not(nullValue()))); - assertThat(properties.getLinks().size(), is(1)); - final CollectionLink link = properties.getLinks().iterator().next(); - assertThat(link.getName(), is("view_replace_prop_test_collection")); - assertThat(link.getFields().size(), is(1)); - assertThat(link.getFields().iterator().next().getName(), is("value")); - } - - private void createGetAndDeleteAnalyzer(AnalyzerEntity options){ - - String fullyQualifiedName = db.name() + "::" + options.getName(); - - // createAnalyzer - AnalyzerEntity createdAnalyzer = db.createAnalyzer(options); - - assertThat(createdAnalyzer.getName(), is(fullyQualifiedName)); - assertThat(createdAnalyzer.getType(), is(options.getType())); - assertThat(createdAnalyzer.getFeatures(), is(options.getFeatures())); - assertThat(createdAnalyzer.getProperties(), is(options.getProperties())); - - // getAnalyzer - AnalyzerEntity gotAnalyzer = db.getAnalyzer(options.getName()); - assertThat(gotAnalyzer.getName(), is(fullyQualifiedName)); - assertThat(gotAnalyzer.getType(), is(options.getType())); - assertThat(gotAnalyzer.getFeatures(), is(options.getFeatures())); - assertThat(gotAnalyzer.getProperties(), is(options.getProperties())); - - // getAnalyzers - @SuppressWarnings("OptionalGetWithoutIsPresent") - AnalyzerEntity foundAnalyzer = db.getAnalyzers().stream().filter(it -> it.getName().equals(fullyQualifiedName)) - .findFirst().get(); - - assertThat(foundAnalyzer.getName(), is(fullyQualifiedName)); - assertThat(foundAnalyzer.getType(), is(options.getType())); - assertThat(foundAnalyzer.getFeatures(), is(options.getFeatures())); - assertThat(foundAnalyzer.getProperties(), is(options.getProperties())); - - AnalyzerDeleteOptions deleteOptions = new AnalyzerDeleteOptions(); - deleteOptions.setForce(true); - - // deleteAnalyzer - db.deleteAnalyzer(options.getName(), deleteOptions); - - try { - db.getAnalyzer(options.getName()); - throw new RuntimeException("deleted analyzer should not be found!"); - } catch (ArangoDBException e) { - // ok - } - - } - - @Test - public void identityAnalyzer() { - if (!requireVersion(3, 5)) { - return; - } - - String name = "test-" + UUID.randomUUID().toString(); - - Set features = new HashSet<>(); - features.add(AnalyzerFeature.frequency); - features.add(AnalyzerFeature.norm); - features.add(AnalyzerFeature.position); - - AnalyzerEntity options = new AnalyzerEntity(); - options.setFeatures(features); - options.setName(name); - options.setType(AnalyzerType.identity); - options.setProperties(Collections.emptyMap()); - - createGetAndDeleteAnalyzer(options); - } - - @Test - public void delimiterAnalyzer() { - if (!requireVersion(3, 5)) { - return; - } - - String name = "test-" + UUID.randomUUID().toString(); - - Set features = new HashSet<>(); - features.add(AnalyzerFeature.frequency); - features.add(AnalyzerFeature.norm); - features.add(AnalyzerFeature.position); - - AnalyzerEntity options = new AnalyzerEntity(); - options.setFeatures(features); - options.setName(name); - options.setType(AnalyzerType.delimiter); - options.setProperties(Collections.singletonMap("delimiter", "-")); - - createGetAndDeleteAnalyzer(options); - } - - @Test - public void stemAnalyzer() { - if (!requireVersion(3, 5)) { - return; - } - - String name = "test-" + UUID.randomUUID().toString(); - - Set features = new HashSet<>(); - features.add(AnalyzerFeature.frequency); - features.add(AnalyzerFeature.norm); - features.add(AnalyzerFeature.position); - - AnalyzerEntity options = new AnalyzerEntity(); - options.setFeatures(features); - options.setName(name); - options.setType(AnalyzerType.stem); - options.setProperties(Collections.singletonMap("locale", "ru.utf-8")); - - createGetAndDeleteAnalyzer(options); - } - - @Test - public void normAnalyzer() { - if (!requireVersion(3, 5)) { - return; - } - - String name = "test-" + UUID.randomUUID().toString(); - - Set features = new HashSet<>(); - features.add(AnalyzerFeature.frequency); - features.add(AnalyzerFeature.norm); - features.add(AnalyzerFeature.position); - - Map properties = new HashMap<>(); - properties.put("locale", "ru.utf-8"); - properties.put("case", "lower"); - properties.put("accent", true); - - AnalyzerEntity options = new AnalyzerEntity(); - options.setFeatures(features); - options.setName(name); - options.setType(AnalyzerType.norm); - options.setProperties(properties); - - createGetAndDeleteAnalyzer(options); - } - - @Test - public void ngramAnalyzer() { - if (!requireVersion(3, 5)) { - return; - } - - String name = "test-" + UUID.randomUUID().toString(); - - Set features = new HashSet<>(); - features.add(AnalyzerFeature.frequency); - features.add(AnalyzerFeature.norm); - features.add(AnalyzerFeature.position); - - Map properties = new HashMap<>(); - properties.put("max", 6L); - properties.put("min", 3L); - properties.put("preserveOriginal", true); - - AnalyzerEntity options = new AnalyzerEntity(); - options.setFeatures(features); - options.setName(name); - options.setType(AnalyzerType.ngram); - options.setProperties(properties); - - createGetAndDeleteAnalyzer(options); - } - - @Test - public void textAnalyzer() { - if (!requireVersion(3, 5)) { - return; - } - - String name = "test-" + UUID.randomUUID().toString(); - - Set features = new HashSet<>(); - features.add(AnalyzerFeature.frequency); - features.add(AnalyzerFeature.norm); - features.add(AnalyzerFeature.position); - - Map properties = new HashMap<>(); - properties.put("locale", "ru.utf-8"); - properties.put("case", "lower"); - properties.put("stopwords", Collections.emptyList()); - properties.put("accent", true); - properties.put("stemming", true); - - AnalyzerEntity options = new AnalyzerEntity(); - options.setFeatures(features); - options.setName(name); - options.setType(AnalyzerType.text); - options.setProperties(properties); - - createGetAndDeleteAnalyzer(options); - } - + private static final String VIEW_NAME = "view_test"; + + public ArangoSearchTest(final Builder builder) { + super(builder); + } + + @After + public void teardown() { + if (db.collection("view_update_prop_test_collection").exists()) + db.collection("view_update_prop_test_collection").drop(); + if (db.collection("view_replace_prop_test_collection").exists()) + db.collection("view_replace_prop_test_collection").drop(); + if (db.view(VIEW_NAME).exists()) + db.view(VIEW_NAME).drop(); + } + + @Test + public void exists() { + if (!requireVersion(3, 4)) { + return; + } + db.createArangoSearch(VIEW_NAME, new ArangoSearchCreateOptions()); + assertThat(db.arangoSearch(VIEW_NAME).exists(), is(true)); + } + + @Test + public void getInfo() { + if (!requireVersion(3, 4)) { + return; + } + db.createArangoSearch(VIEW_NAME, new ArangoSearchCreateOptions()); + final ViewEntity info = db.arangoSearch(VIEW_NAME).getInfo(); + assertThat(info, is(not(nullValue()))); + assertThat(info.getId(), is(not(nullValue()))); + assertThat(info.getName(), is(VIEW_NAME)); + assertThat(info.getType(), is(ViewType.ARANGO_SEARCH)); + } + + @Test + public void drop() { + if (!requireVersion(3, 4)) { + return; + } + db.createArangoSearch(VIEW_NAME, new ArangoSearchCreateOptions()); + final ArangoView view = db.arangoSearch(VIEW_NAME); + view.drop(); + assertThat(view.exists(), is(false)); + } + + @Test + public void rename() { + if (arangoDB.getRole() != ServerRole.SINGLE) { + return; + } + if (!requireVersion(3, 4)) { + return; + } + final String name = VIEW_NAME + "_new"; + db.createArangoSearch(name, new ArangoSearchCreateOptions()); + db.arangoSearch(name).rename(VIEW_NAME); + assertThat(db.arangoSearch(name).exists(), is(false)); + assertThat(db.arangoSearch(VIEW_NAME).exists(), is(true)); + } + + @Test + public void create() { + if (!requireVersion(3, 4)) { + return; + } + final ViewEntity info = db.arangoSearch(VIEW_NAME).create(); + assertThat(info, is(not(nullValue()))); + assertThat(info.getId(), is(not(nullValue()))); + assertThat(info.getName(), is(VIEW_NAME)); + assertThat(info.getType(), is(ViewType.ARANGO_SEARCH)); + assertThat(db.arangoSearch(VIEW_NAME).exists(), is(true)); + } + + @Test + public void createWithOptions() { + if (!requireVersion(3, 4)) { + return; + } + final ArangoSearchCreateOptions options = new ArangoSearchCreateOptions(); + final ViewEntity info = db.arangoSearch(VIEW_NAME).create(options); + assertThat(info, is(not(nullValue()))); + assertThat(info.getId(), is(not(nullValue()))); + assertThat(info.getName(), is(VIEW_NAME)); + assertThat(info.getType(), is(ViewType.ARANGO_SEARCH)); + assertThat(db.arangoSearch(VIEW_NAME).exists(), is(true)); + } + + @Test + public void createWithPrimarySort() { + if (!requireVersion(3, 5)) { + return; + } + final ArangoSearchCreateOptions options = new ArangoSearchCreateOptions(); + + final PrimarySort primarySort = PrimarySort.on("myFieldName"); + primarySort.ascending(true); + options.primarySort(primarySort); + options.consolidationIntervalMsec(666666L); + + final ViewEntity info = db.arangoSearch(VIEW_NAME).create(options); + assertThat(info, is(not(nullValue()))); + assertThat(info.getId(), is(not(nullValue()))); + assertThat(info.getName(), is(VIEW_NAME)); + assertThat(info.getType(), is(ViewType.ARANGO_SEARCH)); + assertThat(db.arangoSearch(VIEW_NAME).exists(), is(true)); + } + + @Test + public void createWithCommitIntervalMsec() { + if (!requireVersion(3, 5)) { + return; + } + final ArangoSearchCreateOptions options = new ArangoSearchCreateOptions(); + options.commitIntervalMsec(666666L); + + final ViewEntity info = db.arangoSearch(VIEW_NAME).create(options); + assertThat(info, is(not(nullValue()))); + assertThat(info.getId(), is(not(nullValue()))); + assertThat(info.getName(), is(VIEW_NAME)); + assertThat(info.getType(), is(ViewType.ARANGO_SEARCH)); + assertThat(db.arangoSearch(VIEW_NAME).exists(), is(true)); + + // check commit interval msec property + final ArangoSearch view = db.arangoSearch(VIEW_NAME); + final ArangoSearchPropertiesEntity properties = view.getProperties(); + assertThat(properties.getCommitIntervalMsec(), is(666666L)); + } + + @Test + public void getProperties() { + if (!requireVersion(3, 4)) { + return; + } + final ArangoSearch view = db.arangoSearch(VIEW_NAME); + view.create(new ArangoSearchCreateOptions()); + final ArangoSearchPropertiesEntity properties = view.getProperties(); + assertThat(properties, is(not(nullValue()))); + assertThat(properties.getId(), is(not(nullValue()))); + assertThat(properties.getName(), is(VIEW_NAME)); + assertThat(properties.getType(), is(ViewType.ARANGO_SEARCH)); + assertThat(properties.getConsolidationIntervalMsec(), is(not(nullValue()))); + assertThat(properties.getCleanupIntervalStep(), is(not(nullValue()))); + final ConsolidationPolicy consolidate = properties.getConsolidationPolicy(); + assertThat(consolidate, is(is(not(nullValue())))); + final Collection links = properties.getLinks(); + assertThat(links.isEmpty(), is(true)); + } + + @Test + public void updateProperties() { + if (!requireVersion(3, 4)) { + return; + } + db.createCollection("view_update_prop_test_collection"); + final ArangoSearch view = db.arangoSearch(VIEW_NAME); + view.create(new ArangoSearchCreateOptions()); + final ArangoSearchPropertiesOptions options = new ArangoSearchPropertiesOptions(); + options.cleanupIntervalStep(15L); + options.consolidationIntervalMsec(65000L); + options.consolidationPolicy(ConsolidationPolicy.of(ConsolidationType.BYTES_ACCUM).threshold(1.)); + options.link(CollectionLink.on("view_update_prop_test_collection") + .fields(FieldLink.on("value").analyzers("identity").trackListPositions(true).includeAllFields(true) + .storeValues(StoreValuesType.ID))); + final ArangoSearchPropertiesEntity properties = view.updateProperties(options); + assertThat(properties, is(not(nullValue()))); + assertThat(properties.getCleanupIntervalStep(), is(15L)); + assertThat(properties.getConsolidationIntervalMsec(), is(65000L)); + final ConsolidationPolicy consolidate = properties.getConsolidationPolicy(); + assertThat(consolidate, is(not(nullValue()))); + assertThat(consolidate.getType(), is(ConsolidationType.BYTES_ACCUM)); + assertThat(consolidate.getThreshold(), is(1.)); + assertThat(properties.getLinks().size(), is(1)); + final CollectionLink link = properties.getLinks().iterator().next(); + assertThat(link.getName(), is("view_update_prop_test_collection")); + assertThat(link.getFields().size(), is(1)); + final FieldLink next = link.getFields().iterator().next(); + assertThat(next.getName(), is("value")); + assertThat(next.getIncludeAllFields(), is(true)); + assertThat(next.getTrackListPositions(), is(true)); + assertThat(next.getStoreValues(), is(StoreValuesType.ID)); + } + + @Test + public void replaceProperties() { + if (!requireVersion(3, 4)) { + return; + } + + db.createCollection("view_replace_prop_test_collection"); + final ArangoSearch view = db.arangoSearch(VIEW_NAME); + view.create(new ArangoSearchCreateOptions()); + final ArangoSearchPropertiesOptions options = new ArangoSearchPropertiesOptions(); + options.link(CollectionLink.on("view_replace_prop_test_collection") + .fields(FieldLink.on("value").analyzers("identity"))); + final ArangoSearchPropertiesEntity properties = view.replaceProperties(options); + assertThat(properties, is(not(nullValue()))); + assertThat(properties.getLinks().size(), is(1)); + final CollectionLink link = properties.getLinks().iterator().next(); + assertThat(link.getName(), is("view_replace_prop_test_collection")); + assertThat(link.getFields().size(), is(1)); + assertThat(link.getFields().iterator().next().getName(), is("value")); + } + + private void createGetAndDeleteAnalyzer(AnalyzerEntity options) { + + String fullyQualifiedName = db.name() + "::" + options.getName(); + + // createAnalyzer + AnalyzerEntity createdAnalyzer = db.createAnalyzer(options); + + assertThat(createdAnalyzer.getName(), is(fullyQualifiedName)); + assertThat(createdAnalyzer.getType(), is(options.getType())); + assertThat(createdAnalyzer.getFeatures(), is(options.getFeatures())); + assertThat(createdAnalyzer.getProperties(), is(options.getProperties())); + + // getAnalyzer + AnalyzerEntity gotAnalyzer = db.getAnalyzer(options.getName()); + assertThat(gotAnalyzer.getName(), is(fullyQualifiedName)); + assertThat(gotAnalyzer.getType(), is(options.getType())); + assertThat(gotAnalyzer.getFeatures(), is(options.getFeatures())); + assertThat(gotAnalyzer.getProperties(), is(options.getProperties())); + + // getAnalyzers + @SuppressWarnings("OptionalGetWithoutIsPresent") + AnalyzerEntity foundAnalyzer = db.getAnalyzers().stream().filter(it -> it.getName().equals(fullyQualifiedName)) + .findFirst().get(); + + assertThat(foundAnalyzer.getName(), is(fullyQualifiedName)); + assertThat(foundAnalyzer.getType(), is(options.getType())); + assertThat(foundAnalyzer.getFeatures(), is(options.getFeatures())); + assertThat(foundAnalyzer.getProperties(), is(options.getProperties())); + + AnalyzerDeleteOptions deleteOptions = new AnalyzerDeleteOptions(); + deleteOptions.setForce(true); + + // deleteAnalyzer + db.deleteAnalyzer(options.getName(), deleteOptions); + + try { + db.getAnalyzer(options.getName()); + fail("deleted analyzer should not be found!"); + } catch (ArangoDBException e) { + // ok + } + + } + + @Test + public void identityAnalyzer() { + if (!requireVersion(3, 5)) { + return; + } + + String name = "test-" + UUID.randomUUID().toString(); + + Set features = new HashSet<>(); + features.add(AnalyzerFeature.frequency); + features.add(AnalyzerFeature.norm); + features.add(AnalyzerFeature.position); + + AnalyzerEntity options = new AnalyzerEntity(); + options.setFeatures(features); + options.setName(name); + options.setType(AnalyzerType.identity); + options.setProperties(Collections.emptyMap()); + + createGetAndDeleteAnalyzer(options); + } + + @Test + public void delimiterAnalyzer() { + if (!requireVersion(3, 5)) { + return; + } + + String name = "test-" + UUID.randomUUID().toString(); + + Set features = new HashSet<>(); + features.add(AnalyzerFeature.frequency); + features.add(AnalyzerFeature.norm); + features.add(AnalyzerFeature.position); + + AnalyzerEntity options = new AnalyzerEntity(); + options.setFeatures(features); + options.setName(name); + options.setType(AnalyzerType.delimiter); + options.setProperties(Collections.singletonMap("delimiter", "-")); + + createGetAndDeleteAnalyzer(options); + } + + @Test + public void stemAnalyzer() { + if (!requireVersion(3, 5)) { + return; + } + + String name = "test-" + UUID.randomUUID().toString(); + + Set features = new HashSet<>(); + features.add(AnalyzerFeature.frequency); + features.add(AnalyzerFeature.norm); + features.add(AnalyzerFeature.position); + + AnalyzerEntity options = new AnalyzerEntity(); + options.setFeatures(features); + options.setName(name); + options.setType(AnalyzerType.stem); + options.setProperties(Collections.singletonMap("locale", "ru.utf-8")); + + createGetAndDeleteAnalyzer(options); + } + + @Test + public void normAnalyzer() { + if (!requireVersion(3, 5)) { + return; + } + + String name = "test-" + UUID.randomUUID().toString(); + + Set features = new HashSet<>(); + features.add(AnalyzerFeature.frequency); + features.add(AnalyzerFeature.norm); + features.add(AnalyzerFeature.position); + + Map properties = new HashMap<>(); + properties.put("locale", "ru.utf-8"); + properties.put("case", "lower"); + properties.put("accent", true); + + AnalyzerEntity options = new AnalyzerEntity(); + options.setFeatures(features); + options.setName(name); + options.setType(AnalyzerType.norm); + options.setProperties(properties); + + createGetAndDeleteAnalyzer(options); + } + + @Test + public void ngramAnalyzer() { + if (!requireVersion(3, 5)) { + return; + } + + String name = "test-" + UUID.randomUUID().toString(); + + Set features = new HashSet<>(); + features.add(AnalyzerFeature.frequency); + features.add(AnalyzerFeature.norm); + features.add(AnalyzerFeature.position); + + Map properties = new HashMap<>(); + properties.put("max", 6L); + properties.put("min", 3L); + properties.put("preserveOriginal", true); + + AnalyzerEntity options = new AnalyzerEntity(); + options.setFeatures(features); + options.setName(name); + options.setType(AnalyzerType.ngram); + options.setProperties(properties); + + createGetAndDeleteAnalyzer(options); + } + + @Test + public void textAnalyzer() { + if (!requireVersion(3, 5)) { + return; + } + + String name = "test-" + UUID.randomUUID().toString(); + + Set features = new HashSet<>(); + features.add(AnalyzerFeature.frequency); + features.add(AnalyzerFeature.norm); + features.add(AnalyzerFeature.position); + + Map properties = new HashMap<>(); + properties.put("locale", "ru.utf-8"); + properties.put("case", "lower"); + properties.put("stopwords", Collections.emptyList()); + properties.put("accent", true); + properties.put("stemming", true); + + AnalyzerEntity options = new AnalyzerEntity(); + options.setFeatures(features); + options.setName(name); + options.setType(AnalyzerType.text); + options.setProperties(properties); + + createGetAndDeleteAnalyzer(options); + } } diff --git a/src/test/java/com/arangodb/ArangoVertexCollectionTest.java b/src/test/java/com/arangodb/ArangoVertexCollectionTest.java index 4c22d8508..0e60eda2c 100644 --- a/src/test/java/com/arangodb/ArangoVertexCollectionTest.java +++ b/src/test/java/com/arangodb/ArangoVertexCollectionTest.java @@ -45,399 +45,389 @@ @RunWith(Parameterized.class) public class ArangoVertexCollectionTest extends BaseTest { - private static final String GRAPH_NAME = "db_collection_test"; - private static final String COLLECTION_NAME = "db_vertex_collection_test"; - - public ArangoVertexCollectionTest(final Builder builder) { - super(builder); - setup(); - } - - public void setup() { - try { - db.createCollection(COLLECTION_NAME, null); - } catch (final ArangoDBException e) { - } - final GraphCreateOptions options = new GraphCreateOptions().orphanCollections(COLLECTION_NAME); - try { - db.createGraph(GRAPH_NAME, null, options); - } catch (final ArangoDBException e) { - } - - } - - @After - public void teardown() { - try { - db.graph(GRAPH_NAME).drop(); - } catch (final ArangoDBException e) { - } - try { - db.collection(COLLECTION_NAME).drop(); - } catch (final ArangoDBException e) { - } - - } - - @Test - public void dropVertexCollection() { - db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME).drop(); - final Collection vertexCollections = db.graph(GRAPH_NAME).getVertexCollections(); - assertThat(vertexCollections, not(hasItem(COLLECTION_NAME))); - } - - @Test - public void insertVertex() { - final VertexEntity vertex = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) - .insertVertex(new BaseDocument(), null); - assertThat(vertex, is(notNullValue())); - final BaseDocument document = db.collection(COLLECTION_NAME) - .getDocument(vertex.getKey(), BaseDocument.class, null); - assertThat(document, is(notNullValue())); - assertThat(document.getKey(), is(vertex.getKey())); - } - - @Test - public void insertVertexViolatingUniqueConstraint() { - // FIXME: remove once fix is backported to 3.4 - assumeTrue(requireVersion(3, 5)); - - db.collection(COLLECTION_NAME) - .ensureSkiplistIndex(Collections.singletonList("properties"), new SkiplistIndexOptions().unique(true)); - - db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME).insertVertex(new BaseDocument(), null); - - try { - db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME).insertVertex(new BaseDocument(), null); - } catch (ArangoDBException e) { - assertThat(e.getResponseCode(), is(409)); - assertThat(e.getErrorNum(), is(1210)); - } - } - - @Test - public void duplicateInsertSameObjectVertex() { - - final ArangoVertexCollection vertexCollection = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME); - - // ######################################################### - // Create a new BaseDocument - // ######################################################### - - UUID uuid = UUID.randomUUID(); - BaseDocument bd = new BaseDocument(); - bd.setKey(uuid.toString()); - bd.addAttribute("name", "Paul"); - - vertexCollection.insertVertex(bd); - - UUID uuid2 = UUID.randomUUID(); - BaseDocument bd2 = new BaseDocument(); - bd2.setKey(uuid2.toString()); - bd2.addAttribute("name", "Paul"); - - vertexCollection.insertVertex(bd2); - } - - @Test - public void insertVertexUpdateRev() { - final BaseDocument doc = new BaseDocument(); - final VertexEntity vertex = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME).insertVertex(doc, null); - assertThat(doc.getRevision(), is(vertex.getRev())); - } - - @Test - public void getVertex() { - final VertexEntity vertex = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) - .insertVertex(new BaseDocument(), null); - final BaseDocument document = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) - .getVertex(vertex.getKey(), BaseDocument.class, null); - assertThat(document, is(notNullValue())); - assertThat(document.getKey(), is(vertex.getKey())); - } - - @Test - public void getVertexIfMatch() { - final VertexEntity vertex = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) - .insertVertex(new BaseDocument(), null); - final GraphDocumentReadOptions options = new GraphDocumentReadOptions().ifMatch(vertex.getRev()); - final BaseDocument document = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) - .getVertex(vertex.getKey(), BaseDocument.class, options); - assertThat(document, is(notNullValue())); - assertThat(document.getKey(), is(vertex.getKey())); - } - - @Test - public void getVertexIfMatchFail() { - final VertexEntity vertex = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) - .insertVertex(new BaseDocument(), null); - final GraphDocumentReadOptions options = new GraphDocumentReadOptions().ifMatch("no"); - final BaseDocument vertex2 = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) - .getVertex(vertex.getKey(), BaseDocument.class, options); - assertThat(vertex2, is(nullValue())); - } - - @Test - public void getVertexIfNoneMatch() { - final VertexEntity vertex = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) - .insertVertex(new BaseDocument(), null); - final GraphDocumentReadOptions options = new GraphDocumentReadOptions().ifNoneMatch("no"); - final BaseDocument document = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) - .getVertex(vertex.getKey(), BaseDocument.class, options); - assertThat(document, is(notNullValue())); - assertThat(document.getKey(), is(vertex.getKey())); - } - - @Test - public void getVertexIfNoneMatchFail() { - final VertexEntity vertex = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) - .insertVertex(new BaseDocument(), null); - final GraphDocumentReadOptions options = new GraphDocumentReadOptions().ifNoneMatch(vertex.getRev()); - final BaseDocument vertex2 = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) - .getVertex(vertex.getKey(), BaseDocument.class, options); - assertThat(vertex2, is(nullValue())); - } - - @Test - public void replaceVertex() { - final BaseDocument doc = new BaseDocument(); - doc.addAttribute("a", "test"); - final VertexEntity createResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) - .insertVertex(doc, null); - doc.getProperties().clear(); - doc.addAttribute("b", "test"); - final VertexUpdateEntity replaceResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) - .replaceVertex(createResult.getKey(), doc, null); - assertThat(replaceResult, is(notNullValue())); - assertThat(replaceResult.getId(), is(createResult.getId())); - assertThat(replaceResult.getRev(), is(not(replaceResult.getOldRev()))); - assertThat(replaceResult.getOldRev(), is(createResult.getRev())); - - final BaseDocument readResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) - .getVertex(createResult.getKey(), BaseDocument.class, null); - assertThat(readResult.getKey(), is(createResult.getKey())); - assertThat(readResult.getRevision(), is(replaceResult.getRev())); - assertThat(readResult.getProperties().keySet(), not(hasItem("a"))); - assertThat(readResult.getAttribute("b"), is(notNullValue())); - assertThat(String.valueOf(readResult.getAttribute("b")), is("test")); - } - - @Test - public void replaceVertexUpdateRev() { - final BaseDocument doc = new BaseDocument(); - final VertexEntity createResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) - .insertVertex(doc, null); - assertThat(doc.getRevision(), is(createResult.getRev())); - final VertexUpdateEntity replaceResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) - .replaceVertex(createResult.getKey(), doc, null); - assertThat(doc.getRevision(), is(replaceResult.getRev())); - } - - @Test - public void replaceVertexIfMatch() { - final BaseDocument doc = new BaseDocument(); - doc.addAttribute("a", "test"); - final VertexEntity createResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) - .insertVertex(doc, null); - doc.getProperties().clear(); - doc.addAttribute("b", "test"); - final VertexReplaceOptions options = new VertexReplaceOptions().ifMatch(createResult.getRev()); - final VertexUpdateEntity replaceResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) - .replaceVertex(createResult.getKey(), doc, options); - assertThat(replaceResult, is(notNullValue())); - assertThat(replaceResult.getId(), is(createResult.getId())); - assertThat(replaceResult.getRev(), is(not(replaceResult.getOldRev()))); - assertThat(replaceResult.getOldRev(), is(createResult.getRev())); - - final BaseDocument readResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) - .getVertex(createResult.getKey(), BaseDocument.class, null); - assertThat(readResult.getKey(), is(createResult.getKey())); - assertThat(readResult.getRevision(), is(replaceResult.getRev())); - assertThat(readResult.getProperties().keySet(), not(hasItem("a"))); - assertThat(readResult.getAttribute("b"), is(notNullValue())); - assertThat(String.valueOf(readResult.getAttribute("b")), is("test")); - } - - @Test - public void replaceVertexIfMatchFail() { - final BaseDocument doc = new BaseDocument(); - doc.addAttribute("a", "test"); - final VertexEntity createResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) - .insertVertex(doc, null); - doc.getProperties().clear(); - doc.addAttribute("b", "test"); - try { - final VertexReplaceOptions options = new VertexReplaceOptions().ifMatch("no"); - db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME).replaceVertex(createResult.getKey(), doc, options); - fail(); - } catch (final ArangoDBException e) { - } - } - - @Test - public void updateVertex() { - final BaseDocument doc = new BaseDocument(); - doc.addAttribute("a", "test"); - doc.addAttribute("c", "test"); - final VertexEntity createResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) - .insertVertex(doc, null); - doc.updateAttribute("a", "test1"); - doc.addAttribute("b", "test"); - doc.updateAttribute("c", null); - final VertexUpdateEntity updateResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) - .updateVertex(createResult.getKey(), doc, null); - assertThat(updateResult, is(notNullValue())); - assertThat(updateResult.getId(), is(createResult.getId())); - assertThat(updateResult.getRev(), is(not(updateResult.getOldRev()))); - assertThat(updateResult.getOldRev(), is(createResult.getRev())); - - final BaseDocument readResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) - .getVertex(createResult.getKey(), BaseDocument.class, null); - assertThat(readResult.getKey(), is(createResult.getKey())); - assertThat(readResult.getAttribute("a"), is(notNullValue())); - assertThat(String.valueOf(readResult.getAttribute("a")), is("test1")); - assertThat(readResult.getAttribute("b"), is(notNullValue())); - assertThat(String.valueOf(readResult.getAttribute("b")), is("test")); - assertThat(readResult.getRevision(), is(updateResult.getRev())); - assertThat(readResult.getProperties().keySet(), hasItem("c")); - } - - @Test - public void updateVertexUpdateRev() { - final BaseDocument doc = new BaseDocument(); - final VertexEntity createResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) - .insertVertex(doc, null); - assertThat(doc.getRevision(), is(createResult.getRev())); - final VertexUpdateEntity updateResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) - .updateVertex(createResult.getKey(), doc, null); - assertThat(doc.getRevision(), is(updateResult.getRev())); - } - - @Test - public void updateVertexIfMatch() { - final BaseDocument doc = new BaseDocument(); - doc.addAttribute("a", "test"); - doc.addAttribute("c", "test"); - final VertexEntity createResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) - .insertVertex(doc, null); - doc.updateAttribute("a", "test1"); - doc.addAttribute("b", "test"); - doc.updateAttribute("c", null); - final VertexUpdateOptions options = new VertexUpdateOptions().ifMatch(createResult.getRev()); - final VertexUpdateEntity updateResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) - .updateVertex(createResult.getKey(), doc, options); - assertThat(updateResult, is(notNullValue())); - assertThat(updateResult.getId(), is(createResult.getId())); - assertThat(updateResult.getRev(), is(not(updateResult.getOldRev()))); - assertThat(updateResult.getOldRev(), is(createResult.getRev())); - - final BaseDocument readResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) - .getVertex(createResult.getKey(), BaseDocument.class, null); - assertThat(readResult.getKey(), is(createResult.getKey())); - assertThat(readResult.getAttribute("a"), is(notNullValue())); - assertThat(String.valueOf(readResult.getAttribute("a")), is("test1")); - assertThat(readResult.getAttribute("b"), is(notNullValue())); - assertThat(String.valueOf(readResult.getAttribute("b")), is("test")); - assertThat(readResult.getRevision(), is(updateResult.getRev())); - assertThat(readResult.getProperties().keySet(), hasItem("c")); - } - - @Test - public void updateVertexIfMatchFail() { - final BaseDocument doc = new BaseDocument(); - doc.addAttribute("a", "test"); - doc.addAttribute("c", "test"); - final VertexEntity createResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) - .insertVertex(doc, null); - doc.updateAttribute("a", "test1"); - doc.addAttribute("b", "test"); - doc.updateAttribute("c", null); - try { - final VertexUpdateOptions options = new VertexUpdateOptions().ifMatch("no"); - db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME).updateVertex(createResult.getKey(), doc, options); - fail(); - } catch (final ArangoDBException e) { - } - } - - @Test - public void updateVertexKeepNullTrue() { - final BaseDocument doc = new BaseDocument(); - doc.addAttribute("a", "test"); - final VertexEntity createResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) - .insertVertex(doc, null); - doc.updateAttribute("a", null); - final VertexUpdateOptions options = new VertexUpdateOptions().keepNull(true); - final VertexUpdateEntity updateResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) - .updateVertex(createResult.getKey(), doc, options); - assertThat(updateResult, is(notNullValue())); - assertThat(updateResult.getId(), is(createResult.getId())); - assertThat(updateResult.getRev(), is(not(updateResult.getOldRev()))); - assertThat(updateResult.getOldRev(), is(createResult.getRev())); - - final BaseDocument readResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) - .getVertex(createResult.getKey(), BaseDocument.class, null); - assertThat(readResult.getKey(), is(createResult.getKey())); - assertThat(readResult.getProperties().keySet().size(), is(1)); - assertThat(readResult.getProperties().keySet(), hasItem("a")); - } - - @Test - public void updateVertexKeepNullFalse() { - final BaseDocument doc = new BaseDocument(); - doc.addAttribute("a", "test"); - final VertexEntity createResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) - .insertVertex(doc, null); - doc.updateAttribute("a", null); - final VertexUpdateOptions options = new VertexUpdateOptions().keepNull(false); - final VertexUpdateEntity updateResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) - .updateVertex(createResult.getKey(), doc, options); - assertThat(updateResult, is(notNullValue())); - assertThat(updateResult.getId(), is(createResult.getId())); - assertThat(updateResult.getRev(), is(not(updateResult.getOldRev()))); - assertThat(updateResult.getOldRev(), is(createResult.getRev())); - - final BaseDocument readResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) - .getVertex(createResult.getKey(), BaseDocument.class, null); - assertThat(readResult.getKey(), is(createResult.getKey())); - assertThat(readResult.getId(), is(createResult.getId())); - assertThat(readResult.getRevision(), is(notNullValue())); - assertThat(readResult.getProperties().keySet(), not(hasItem("a"))); - } - - @Test - public void deleteVertex() { - final BaseDocument doc = new BaseDocument(); - final VertexEntity createResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) - .insertVertex(doc, null); - db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME).deleteVertex(createResult.getKey(), null); - final BaseDocument vertex = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) - .getVertex(createResult.getKey(), BaseDocument.class, null); - assertThat(vertex, is(nullValue())); - } - - @Test - public void deleteVertexIfMatch() { - final BaseDocument doc = new BaseDocument(); - final VertexEntity createResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) - .insertVertex(doc, null); - final VertexDeleteOptions options = new VertexDeleteOptions().ifMatch(createResult.getRev()); - db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME).deleteVertex(createResult.getKey(), options); - final BaseDocument vertex = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) - .getVertex(createResult.getKey(), BaseDocument.class, null); - assertThat(vertex, is(nullValue())); - } - - @Test - public void deleteVertexIfMatchFail() { - final BaseDocument doc = new BaseDocument(); - final VertexEntity createResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) - .insertVertex(doc, null); - final VertexDeleteOptions options = new VertexDeleteOptions().ifMatch("no"); - try { - db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME).deleteVertex(createResult.getKey(), options); - fail(); - } catch (final ArangoDBException e) { - } - } + private static final String GRAPH_NAME = "db_collection_test"; + private static final String COLLECTION_NAME = "db_vertex_collection_test"; + + public ArangoVertexCollectionTest(final Builder builder) { + super(builder); + setup(); + } + + public void setup() { + if (!db.collection(COLLECTION_NAME).exists()) + db.createCollection(COLLECTION_NAME, null); + + if (!db.graph(GRAPH_NAME).exists()) + db.createGraph(GRAPH_NAME, null, new GraphCreateOptions().orphanCollections(COLLECTION_NAME)); + } + + @After + public void teardown() { + if (db.graph(GRAPH_NAME).exists()) + db.graph(GRAPH_NAME).drop(); + if (db.collection(COLLECTION_NAME).exists()) + db.collection(COLLECTION_NAME).drop(); + } + + @Test + public void dropVertexCollection() { + db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME).drop(); + final Collection vertexCollections = db.graph(GRAPH_NAME).getVertexCollections(); + assertThat(vertexCollections, not(hasItem(COLLECTION_NAME))); + } + + @Test + public void insertVertex() { + final VertexEntity vertex = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) + .insertVertex(new BaseDocument(), null); + assertThat(vertex, is(notNullValue())); + final BaseDocument document = db.collection(COLLECTION_NAME) + .getDocument(vertex.getKey(), BaseDocument.class, null); + assertThat(document, is(notNullValue())); + assertThat(document.getKey(), is(vertex.getKey())); + } + + @Test + public void insertVertexViolatingUniqueConstraint() { + // FIXME: remove once fix is backported to 3.4 + assumeTrue(requireVersion(3, 5)); + + db.collection(COLLECTION_NAME) + .ensureSkiplistIndex(Collections.singletonList("properties"), new SkiplistIndexOptions().unique(true)); + + db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME).insertVertex(new BaseDocument(), null); + + try { + db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME).insertVertex(new BaseDocument(), null); + } catch (ArangoDBException e) { + assertThat(e.getResponseCode(), is(409)); + assertThat(e.getErrorNum(), is(1210)); + } + } + + @Test + public void duplicateInsertSameObjectVertex() { + + final ArangoVertexCollection vertexCollection = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME); + + // ######################################################### + // Create a new BaseDocument + // ######################################################### + + UUID uuid = UUID.randomUUID(); + BaseDocument bd = new BaseDocument(); + bd.setKey(uuid.toString()); + bd.addAttribute("name", "Paul"); + + vertexCollection.insertVertex(bd); + + UUID uuid2 = UUID.randomUUID(); + BaseDocument bd2 = new BaseDocument(); + bd2.setKey(uuid2.toString()); + bd2.addAttribute("name", "Paul"); + + vertexCollection.insertVertex(bd2); + } + + @Test + public void insertVertexUpdateRev() { + final BaseDocument doc = new BaseDocument(); + final VertexEntity vertex = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME).insertVertex(doc, null); + assertThat(doc.getRevision(), is(vertex.getRev())); + } + + @Test + public void getVertex() { + final VertexEntity vertex = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) + .insertVertex(new BaseDocument(), null); + final BaseDocument document = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) + .getVertex(vertex.getKey(), BaseDocument.class, null); + assertThat(document, is(notNullValue())); + assertThat(document.getKey(), is(vertex.getKey())); + } + + @Test + public void getVertexIfMatch() { + final VertexEntity vertex = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) + .insertVertex(new BaseDocument(), null); + final GraphDocumentReadOptions options = new GraphDocumentReadOptions().ifMatch(vertex.getRev()); + final BaseDocument document = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) + .getVertex(vertex.getKey(), BaseDocument.class, options); + assertThat(document, is(notNullValue())); + assertThat(document.getKey(), is(vertex.getKey())); + } + + @Test + public void getVertexIfMatchFail() { + final VertexEntity vertex = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) + .insertVertex(new BaseDocument(), null); + final GraphDocumentReadOptions options = new GraphDocumentReadOptions().ifMatch("no"); + final BaseDocument vertex2 = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) + .getVertex(vertex.getKey(), BaseDocument.class, options); + assertThat(vertex2, is(nullValue())); + } + + @Test + public void getVertexIfNoneMatch() { + final VertexEntity vertex = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) + .insertVertex(new BaseDocument(), null); + final GraphDocumentReadOptions options = new GraphDocumentReadOptions().ifNoneMatch("no"); + final BaseDocument document = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) + .getVertex(vertex.getKey(), BaseDocument.class, options); + assertThat(document, is(notNullValue())); + assertThat(document.getKey(), is(vertex.getKey())); + } + + @Test + public void getVertexIfNoneMatchFail() { + final VertexEntity vertex = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) + .insertVertex(new BaseDocument(), null); + final GraphDocumentReadOptions options = new GraphDocumentReadOptions().ifNoneMatch(vertex.getRev()); + final BaseDocument vertex2 = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) + .getVertex(vertex.getKey(), BaseDocument.class, options); + assertThat(vertex2, is(nullValue())); + } + + @Test + public void replaceVertex() { + final BaseDocument doc = new BaseDocument(); + doc.addAttribute("a", "test"); + final VertexEntity createResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) + .insertVertex(doc, null); + doc.getProperties().clear(); + doc.addAttribute("b", "test"); + final VertexUpdateEntity replaceResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) + .replaceVertex(createResult.getKey(), doc, null); + assertThat(replaceResult, is(notNullValue())); + assertThat(replaceResult.getId(), is(createResult.getId())); + assertThat(replaceResult.getRev(), is(not(replaceResult.getOldRev()))); + assertThat(replaceResult.getOldRev(), is(createResult.getRev())); + + final BaseDocument readResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) + .getVertex(createResult.getKey(), BaseDocument.class, null); + assertThat(readResult.getKey(), is(createResult.getKey())); + assertThat(readResult.getRevision(), is(replaceResult.getRev())); + assertThat(readResult.getProperties().keySet(), not(hasItem("a"))); + assertThat(readResult.getAttribute("b"), is(notNullValue())); + assertThat(String.valueOf(readResult.getAttribute("b")), is("test")); + } + + @Test + public void replaceVertexUpdateRev() { + final BaseDocument doc = new BaseDocument(); + final VertexEntity createResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) + .insertVertex(doc, null); + assertThat(doc.getRevision(), is(createResult.getRev())); + final VertexUpdateEntity replaceResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) + .replaceVertex(createResult.getKey(), doc, null); + assertThat(doc.getRevision(), is(replaceResult.getRev())); + } + + @Test + public void replaceVertexIfMatch() { + final BaseDocument doc = new BaseDocument(); + doc.addAttribute("a", "test"); + final VertexEntity createResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) + .insertVertex(doc, null); + doc.getProperties().clear(); + doc.addAttribute("b", "test"); + final VertexReplaceOptions options = new VertexReplaceOptions().ifMatch(createResult.getRev()); + final VertexUpdateEntity replaceResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) + .replaceVertex(createResult.getKey(), doc, options); + assertThat(replaceResult, is(notNullValue())); + assertThat(replaceResult.getId(), is(createResult.getId())); + assertThat(replaceResult.getRev(), is(not(replaceResult.getOldRev()))); + assertThat(replaceResult.getOldRev(), is(createResult.getRev())); + + final BaseDocument readResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) + .getVertex(createResult.getKey(), BaseDocument.class, null); + assertThat(readResult.getKey(), is(createResult.getKey())); + assertThat(readResult.getRevision(), is(replaceResult.getRev())); + assertThat(readResult.getProperties().keySet(), not(hasItem("a"))); + assertThat(readResult.getAttribute("b"), is(notNullValue())); + assertThat(String.valueOf(readResult.getAttribute("b")), is("test")); + } + + @Test + public void replaceVertexIfMatchFail() { + final BaseDocument doc = new BaseDocument(); + doc.addAttribute("a", "test"); + final VertexEntity createResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) + .insertVertex(doc, null); + doc.getProperties().clear(); + doc.addAttribute("b", "test"); + try { + final VertexReplaceOptions options = new VertexReplaceOptions().ifMatch("no"); + db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME).replaceVertex(createResult.getKey(), doc, options); + fail(); + } catch (final ArangoDBException e) { + } + } + + @Test + public void updateVertex() { + final BaseDocument doc = new BaseDocument(); + doc.addAttribute("a", "test"); + doc.addAttribute("c", "test"); + final VertexEntity createResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) + .insertVertex(doc, null); + doc.updateAttribute("a", "test1"); + doc.addAttribute("b", "test"); + doc.updateAttribute("c", null); + final VertexUpdateEntity updateResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) + .updateVertex(createResult.getKey(), doc, null); + assertThat(updateResult, is(notNullValue())); + assertThat(updateResult.getId(), is(createResult.getId())); + assertThat(updateResult.getRev(), is(not(updateResult.getOldRev()))); + assertThat(updateResult.getOldRev(), is(createResult.getRev())); + + final BaseDocument readResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) + .getVertex(createResult.getKey(), BaseDocument.class, null); + assertThat(readResult.getKey(), is(createResult.getKey())); + assertThat(readResult.getAttribute("a"), is(notNullValue())); + assertThat(String.valueOf(readResult.getAttribute("a")), is("test1")); + assertThat(readResult.getAttribute("b"), is(notNullValue())); + assertThat(String.valueOf(readResult.getAttribute("b")), is("test")); + assertThat(readResult.getRevision(), is(updateResult.getRev())); + assertThat(readResult.getProperties().keySet(), hasItem("c")); + } + + @Test + public void updateVertexUpdateRev() { + final BaseDocument doc = new BaseDocument(); + final VertexEntity createResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) + .insertVertex(doc, null); + assertThat(doc.getRevision(), is(createResult.getRev())); + final VertexUpdateEntity updateResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) + .updateVertex(createResult.getKey(), doc, null); + assertThat(doc.getRevision(), is(updateResult.getRev())); + } + + @Test + public void updateVertexIfMatch() { + final BaseDocument doc = new BaseDocument(); + doc.addAttribute("a", "test"); + doc.addAttribute("c", "test"); + final VertexEntity createResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) + .insertVertex(doc, null); + doc.updateAttribute("a", "test1"); + doc.addAttribute("b", "test"); + doc.updateAttribute("c", null); + final VertexUpdateOptions options = new VertexUpdateOptions().ifMatch(createResult.getRev()); + final VertexUpdateEntity updateResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) + .updateVertex(createResult.getKey(), doc, options); + assertThat(updateResult, is(notNullValue())); + assertThat(updateResult.getId(), is(createResult.getId())); + assertThat(updateResult.getRev(), is(not(updateResult.getOldRev()))); + assertThat(updateResult.getOldRev(), is(createResult.getRev())); + + final BaseDocument readResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) + .getVertex(createResult.getKey(), BaseDocument.class, null); + assertThat(readResult.getKey(), is(createResult.getKey())); + assertThat(readResult.getAttribute("a"), is(notNullValue())); + assertThat(String.valueOf(readResult.getAttribute("a")), is("test1")); + assertThat(readResult.getAttribute("b"), is(notNullValue())); + assertThat(String.valueOf(readResult.getAttribute("b")), is("test")); + assertThat(readResult.getRevision(), is(updateResult.getRev())); + assertThat(readResult.getProperties().keySet(), hasItem("c")); + } + + @Test + public void updateVertexIfMatchFail() { + final BaseDocument doc = new BaseDocument(); + doc.addAttribute("a", "test"); + doc.addAttribute("c", "test"); + final VertexEntity createResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) + .insertVertex(doc, null); + doc.updateAttribute("a", "test1"); + doc.addAttribute("b", "test"); + doc.updateAttribute("c", null); + try { + final VertexUpdateOptions options = new VertexUpdateOptions().ifMatch("no"); + db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME).updateVertex(createResult.getKey(), doc, options); + fail(); + } catch (final ArangoDBException e) { + } + } + + @Test + public void updateVertexKeepNullTrue() { + final BaseDocument doc = new BaseDocument(); + doc.addAttribute("a", "test"); + final VertexEntity createResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) + .insertVertex(doc, null); + doc.updateAttribute("a", null); + final VertexUpdateOptions options = new VertexUpdateOptions().keepNull(true); + final VertexUpdateEntity updateResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) + .updateVertex(createResult.getKey(), doc, options); + assertThat(updateResult, is(notNullValue())); + assertThat(updateResult.getId(), is(createResult.getId())); + assertThat(updateResult.getRev(), is(not(updateResult.getOldRev()))); + assertThat(updateResult.getOldRev(), is(createResult.getRev())); + + final BaseDocument readResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) + .getVertex(createResult.getKey(), BaseDocument.class, null); + assertThat(readResult.getKey(), is(createResult.getKey())); + assertThat(readResult.getProperties().keySet().size(), is(1)); + assertThat(readResult.getProperties().keySet(), hasItem("a")); + } + + @Test + public void updateVertexKeepNullFalse() { + final BaseDocument doc = new BaseDocument(); + doc.addAttribute("a", "test"); + final VertexEntity createResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) + .insertVertex(doc, null); + doc.updateAttribute("a", null); + final VertexUpdateOptions options = new VertexUpdateOptions().keepNull(false); + final VertexUpdateEntity updateResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) + .updateVertex(createResult.getKey(), doc, options); + assertThat(updateResult, is(notNullValue())); + assertThat(updateResult.getId(), is(createResult.getId())); + assertThat(updateResult.getRev(), is(not(updateResult.getOldRev()))); + assertThat(updateResult.getOldRev(), is(createResult.getRev())); + + final BaseDocument readResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) + .getVertex(createResult.getKey(), BaseDocument.class, null); + assertThat(readResult.getKey(), is(createResult.getKey())); + assertThat(readResult.getId(), is(createResult.getId())); + assertThat(readResult.getRevision(), is(notNullValue())); + assertThat(readResult.getProperties().keySet(), not(hasItem("a"))); + } + + @Test + public void deleteVertex() { + final BaseDocument doc = new BaseDocument(); + final VertexEntity createResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) + .insertVertex(doc, null); + db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME).deleteVertex(createResult.getKey(), null); + final BaseDocument vertex = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) + .getVertex(createResult.getKey(), BaseDocument.class, null); + assertThat(vertex, is(nullValue())); + } + + @Test + public void deleteVertexIfMatch() { + final BaseDocument doc = new BaseDocument(); + final VertexEntity createResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) + .insertVertex(doc, null); + final VertexDeleteOptions options = new VertexDeleteOptions().ifMatch(createResult.getRev()); + db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME).deleteVertex(createResult.getKey(), options); + final BaseDocument vertex = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) + .getVertex(createResult.getKey(), BaseDocument.class, null); + assertThat(vertex, is(nullValue())); + } + + @Test + public void deleteVertexIfMatchFail() { + final BaseDocument doc = new BaseDocument(); + final VertexEntity createResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) + .insertVertex(doc, null); + final VertexDeleteOptions options = new VertexDeleteOptions().ifMatch("no"); + try { + db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME).deleteVertex(createResult.getKey(), options); + fail(); + } catch (final ArangoDBException e) { + } + } } diff --git a/src/test/java/com/arangodb/ArangoViewTest.java b/src/test/java/com/arangodb/ArangoViewTest.java index 7c8e44f1c..3dc388533 100644 --- a/src/test/java/com/arangodb/ArangoViewTest.java +++ b/src/test/java/com/arangodb/ArangoViewTest.java @@ -37,71 +37,68 @@ /** * @author Mark Vollmary - * */ @RunWith(Parameterized.class) public class ArangoViewTest extends BaseTest { - private static final String VIEW_NAME = "view_test"; + private static final String VIEW_NAME = "view_test"; - public ArangoViewTest(final Builder builder) { - super(builder); - } + public ArangoViewTest(final Builder builder) { + super(builder); + } - @After - public void teardown() { - try { - db.view(VIEW_NAME).drop(); - } catch (final ArangoDBException e) { - } - } + @After + public void teardown() { + if (db.view(VIEW_NAME).exists()) + db.view(VIEW_NAME).drop(); + } - @Test - public void exists() { - if (!requireVersion(3, 4)) { - return; - } - db.createView(VIEW_NAME, ViewType.ARANGO_SEARCH); - assertThat(db.view(VIEW_NAME).exists(), is(true)); - } + @Test + public void exists() { + if (!requireVersion(3, 4)) { + return; + } + db.createView(VIEW_NAME, ViewType.ARANGO_SEARCH); + assertThat(db.view(VIEW_NAME).exists(), is(true)); + } - @Test - public void getInfo() { - if (!requireVersion(3, 4)) { - return; - } - db.createView(VIEW_NAME, ViewType.ARANGO_SEARCH); - final ViewEntity info = db.view(VIEW_NAME).getInfo(); - assertThat(info, is(not(nullValue()))); - assertThat(info.getId(), is(not(nullValue()))); - assertThat(info.getName(), is(VIEW_NAME)); - assertThat(info.getType(), is(ViewType.ARANGO_SEARCH)); - } + @Test + public void getInfo() { + if (!requireVersion(3, 4)) { + return; + } + db.createView(VIEW_NAME, ViewType.ARANGO_SEARCH); + final ViewEntity info = db.view(VIEW_NAME).getInfo(); + assertThat(info, is(not(nullValue()))); + assertThat(info.getId(), is(not(nullValue()))); + assertThat(info.getName(), is(VIEW_NAME)); + assertThat(info.getType(), is(ViewType.ARANGO_SEARCH)); + } - @Test - public void drop() { - if (!requireVersion(3, 4)) { - return; - } - db.createView(VIEW_NAME, ViewType.ARANGO_SEARCH); - final ArangoView view = db.view(VIEW_NAME); - view.drop(); - assertThat(view.exists(), is(false)); - } + @Test + public void drop() { + if (!requireVersion(3, 4)) { + return; + } + db.createView(VIEW_NAME, ViewType.ARANGO_SEARCH); + final ArangoView view = db.view(VIEW_NAME); + view.drop(); + assertThat(view.exists(), is(false)); + } - @Test - public void rename() { - if (arangoDB.getRole() != ServerRole.SINGLE) { - return; - } - if (!requireVersion(3, 4)) { - return; - } - final String name = VIEW_NAME + "_new"; - db.createView(name, ViewType.ARANGO_SEARCH); - db.view(name).rename(VIEW_NAME); - assertThat(db.view(name).exists(), is(false)); - assertThat(db.view(VIEW_NAME).exists(), is(true)); - } + @Test + public void rename() { + if (arangoDB.getRole() != ServerRole.SINGLE) { + return; + } + if (!requireVersion(3, 4)) { + return; + } + final String name = VIEW_NAME + "_new"; + db.createView(name, ViewType.ARANGO_SEARCH); + db.view(name).rename(VIEW_NAME); + assertThat(db.view(name).exists(), is(false)); + assertThat(db.view(VIEW_NAME).exists(), is(true)); + } } diff --git a/src/test/java/com/arangodb/BaseTest.java b/src/test/java/com/arangodb/BaseTest.java index 1aa769fda..0567c1afa 100644 --- a/src/test/java/com/arangodb/BaseTest.java +++ b/src/test/java/com/arangodb/BaseTest.java @@ -34,55 +34,49 @@ */ public abstract class BaseTest { - @Parameters - public static Collection builders() { - return Arrays.asList(// - new ArangoDB.Builder().useProtocol(Protocol.VST), // - new ArangoDB.Builder().useProtocol(Protocol.HTTP_JSON), // - new ArangoDB.Builder().useProtocol(Protocol.HTTP_VPACK) // - ); - } + @Parameters + public static Collection builders() { + return Arrays.asList(// + new ArangoDB.Builder().useProtocol(Protocol.VST), // + new ArangoDB.Builder().useProtocol(Protocol.HTTP_JSON), // + new ArangoDB.Builder().useProtocol(Protocol.HTTP_VPACK) // + ); + } - protected static final String TEST_DB = "java_driver_test_db"; - protected static final String TEST_DB_CUSTOM = "java_driver_test_db_custom"; - protected static ArangoDB arangoDB; - protected static ArangoDatabase db; + protected static final String TEST_DB = "java_driver_test_db"; + protected static final String TEST_DB_CUSTOM = "java_driver_test_db_custom"; + protected static ArangoDB arangoDB; + protected static ArangoDatabase db; - public BaseTest(final ArangoDB.Builder builder) { - super(); - if (arangoDB != null) { - shutdown(); - } - arangoDB = builder.build(); - db = arangoDB.db(TEST_DB); + public BaseTest(final ArangoDB.Builder builder) { + super(); + if (arangoDB != null) { + shutdown(); + } + arangoDB = builder.build(); + db = arangoDB.db(TEST_DB); - // only create the database if not existing - try { - db.getVersion().getVersion(); - } catch (final ArangoDBException e) { - if (e.getErrorNum() == 1228) { // DATABASE NOT FOUND - arangoDB.createDatabase(TEST_DB); - } - } - } + if (!db.exists()) + db.create(); + } - @AfterClass - public static void shutdown() { - arangoDB.shutdown(); - arangoDB = null; - } + @AfterClass + public static void shutdown() { + arangoDB.shutdown(); + arangoDB = null; + } - protected boolean requireVersion(final int major, final int minor) { - final String[] split = arangoDB.getVersion().getVersion().split("\\."); - return Integer.valueOf(split[0]) >= major && Integer.valueOf(split[1]) >= minor; - } + protected boolean requireVersion(final int major, final int minor) { + final String[] split = arangoDB.getVersion().getVersion().split("\\."); + return Integer.valueOf(split[0]) >= major && Integer.valueOf(split[1]) >= minor; + } - protected boolean requireStorageEngine(ArangoDBEngine.StorageEngineName name) { - return name.equals(arangoDB.getEngine().getName()); - } + protected boolean requireStorageEngine(ArangoDBEngine.StorageEngineName name) { + return name.equals(arangoDB.getEngine().getName()); + } - protected boolean requireSingleServer() { - return (arangoDB.getRole() == ServerRole.SINGLE); - } + protected boolean requireSingleServer() { + return (arangoDB.getRole() == ServerRole.SINGLE); + } } diff --git a/src/test/java/com/arangodb/ConcurrentStreamTransactionsTest.java b/src/test/java/com/arangodb/ConcurrentStreamTransactionsTest.java index 5d1d464d4..416ef8a69 100644 --- a/src/test/java/com/arangodb/ConcurrentStreamTransactionsTest.java +++ b/src/test/java/com/arangodb/ConcurrentStreamTransactionsTest.java @@ -41,90 +41,85 @@ @RunWith(Parameterized.class) public class ConcurrentStreamTransactionsTest extends BaseTest { - private static final String COLLECTION_NAME = "db_concurrent_stream_transactions_test"; + private static final String COLLECTION_NAME = "db_concurrent_stream_transactions_test"; - public ConcurrentStreamTransactionsTest(final Builder builder) { - super(builder); - try { - if (db.collection(COLLECTION_NAME).exists()) - db.collection(COLLECTION_NAME).drop(); + public ConcurrentStreamTransactionsTest(final Builder builder) { + super(builder); + if (db.collection(COLLECTION_NAME).exists()) + db.collection(COLLECTION_NAME).drop(); - db.createCollection(COLLECTION_NAME, null); - } catch (final ArangoDBException e) { + db.createCollection(COLLECTION_NAME, null); + } - } - } + @After + public void teardown() { + if (db.collection(COLLECTION_NAME).exists()) + db.collection(COLLECTION_NAME).drop(); + } - @After - public void teardown() { - try { - db.collection(COLLECTION_NAME).drop(); - } catch (final ArangoDBException e) { - } - } + @Test + public void conflictOnInsertDocumentWithNotYetCommittedTx() { + assumeTrue(requireSingleServer()); + assumeTrue(requireVersion(3, 5)); + assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); - @Test - public void conflictOnInsertDocumentWithNotYetCommittedTx() { - assumeTrue(requireSingleServer()); - assumeTrue(requireVersion(3, 5)); - assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); + StreamTransactionEntity tx1 = db.beginStreamTransaction( + new StreamTransactionOptions().readCollections(COLLECTION_NAME).writeCollections(COLLECTION_NAME)); - StreamTransactionEntity tx1 = db.beginStreamTransaction( - new StreamTransactionOptions().readCollections(COLLECTION_NAME).writeCollections(COLLECTION_NAME)); + StreamTransactionEntity tx2 = db.beginStreamTransaction( + new StreamTransactionOptions().readCollections(COLLECTION_NAME).writeCollections(COLLECTION_NAME)); - StreamTransactionEntity tx2 = db.beginStreamTransaction( - new StreamTransactionOptions().readCollections(COLLECTION_NAME).writeCollections(COLLECTION_NAME)); + String key = UUID.randomUUID().toString(); - String key = UUID.randomUUID().toString(); + // insert a document from within tx1 + db.collection(COLLECTION_NAME) + .insertDocument(new BaseDocument(key), new DocumentCreateOptions().streamTransactionId(tx1.getId())); - // insert a document from within tx1 - db.collection(COLLECTION_NAME) - .insertDocument(new BaseDocument(key), new DocumentCreateOptions().streamTransactionId(tx1.getId())); + try { + // insert conflicting document from within tx2 + db.collection(COLLECTION_NAME).insertDocument(new BaseDocument(key), + new DocumentCreateOptions().streamTransactionId(tx2.getId())); - try { - // insert conflicting document from within tx2 - db.collection(COLLECTION_NAME).insertDocument(new BaseDocument(key), - new DocumentCreateOptions().streamTransactionId(tx2.getId())); + throw new RuntimeException("This should never be thrown"); + } catch (ArangoDBException e) { + e.printStackTrace(); + } - throw new RuntimeException("This should never be thrown"); - } catch (ArangoDBException e) { - e.printStackTrace(); - } + db.abortStreamTransaction(tx1.getId()); + db.abortStreamTransaction(tx2.getId()); + } - db.abortStreamTransaction(tx1.getId()); - db.abortStreamTransaction(tx2.getId()); - } + @Test + public void conflictOnInsertDocumentWithAlreadyCommittedTx() { + assumeTrue(requireSingleServer()); + assumeTrue(requireVersion(3, 5)); + assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); - @Test - public void conflictOnInsertDocumentWithAlreadyCommittedTx() { - assumeTrue(requireSingleServer()); - assumeTrue(requireVersion(3, 5)); - assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); + StreamTransactionEntity tx1 = db.beginStreamTransaction( + new StreamTransactionOptions().readCollections(COLLECTION_NAME).writeCollections(COLLECTION_NAME)); - StreamTransactionEntity tx1 = db.beginStreamTransaction( - new StreamTransactionOptions().readCollections(COLLECTION_NAME).writeCollections(COLLECTION_NAME)); + StreamTransactionEntity tx2 = db.beginStreamTransaction( + new StreamTransactionOptions().readCollections(COLLECTION_NAME).writeCollections(COLLECTION_NAME)); - StreamTransactionEntity tx2 = db.beginStreamTransaction( - new StreamTransactionOptions().readCollections(COLLECTION_NAME).writeCollections(COLLECTION_NAME)); + String key = UUID.randomUUID().toString(); - String key = UUID.randomUUID().toString(); + // insert a document from within tx1 + db.collection(COLLECTION_NAME) + .insertDocument(new BaseDocument(key), new DocumentCreateOptions().streamTransactionId(tx1.getId())); - // insert a document from within tx1 - db.collection(COLLECTION_NAME) - .insertDocument(new BaseDocument(key), new DocumentCreateOptions().streamTransactionId(tx1.getId())); + // commit tx1 + db.commitStreamTransaction(tx1.getId()); - // commit tx1 - db.commitStreamTransaction(tx1.getId()); + try { + // insert conflicting document from within tx2 + db.collection(COLLECTION_NAME).insertDocument(new BaseDocument(key), + new DocumentCreateOptions().streamTransactionId(tx2.getId())); - try { - // insert conflicting document from within tx2 - db.collection(COLLECTION_NAME).insertDocument(new BaseDocument(key), - new DocumentCreateOptions().streamTransactionId(tx2.getId())); + throw new RuntimeException("This should never be thrown"); + } catch (ArangoDBException e) { + e.printStackTrace(); + } - throw new RuntimeException("This should never be thrown"); - } catch (ArangoDBException e) { - e.printStackTrace(); - db.abortStreamTransaction(tx2.getId()); - } - } + db.abortStreamTransaction(tx2.getId()); + } } diff --git a/src/test/java/com/arangodb/DocumentTest.java b/src/test/java/com/arangodb/DocumentTest.java index ad18a8677..4d44ccbc2 100644 --- a/src/test/java/com/arangodb/DocumentTest.java +++ b/src/test/java/com/arangodb/DocumentTest.java @@ -37,100 +37,95 @@ /** * @author Mark Vollmary - * */ @RunWith(Parameterized.class) public class DocumentTest extends BaseTest { - private static final String COLLECTION_NAME = "collection_test"; - private ArangoCollection collection; + private static final String COLLECTION_NAME = "collection_test"; + private ArangoCollection collection; - public DocumentTest(final Builder builder) { - super(builder); - setup(); - } + public DocumentTest(final Builder builder) { + super(builder); + setup(); + } - public void setup() { - db.createCollection(COLLECTION_NAME); - collection = db.collection(COLLECTION_NAME); - } + public void setup() { + db.createCollection(COLLECTION_NAME); + collection = db.collection(COLLECTION_NAME); + } - @After - public void teardown() { - collection.truncate(); - try { - db.collection(COLLECTION_NAME).drop(); - } catch (final ArangoDBException e) { - - } - } + @After + public void teardown() { + if (db.collection(COLLECTION_NAME).exists()) + db.collection(COLLECTION_NAME).drop(); + } - @SuppressWarnings("unchecked") - @Test - public void insertAsJson() { - //@formatter:off - final String json = - "{" - + "\"article\": {" - + "\"artist\": \"PREGARDIEN/RHEINISCHE KANTOREI/DAS\"," - + "\"releaseDate\": \"1970-01-01\"," - + "\"composer\": \"BACH\"," - + "\"format\": \"CD\"," - + "\"vat\": \"H\"," - + "\"carriers\": 1," - + "\"label\": \"CAPRICCIO\"," - + "\"title\": \"BACH ST MATTHEW PASSION BWV244\"," - + "\"barcode\": [" - + "\"4006408600466\"" - + "]," - + "\"conductor\": \"MAX, H.\"" - + "}," - + "\"stock\": {" - + "\"status\": \"RMV\"," - + "\"lastUpdate\": \"2016-11-01 00:00\"" - + "}" - + "}"; - //@formatter:on - final DocumentCreateEntity createResult = collection.insertDocument(json); - final BaseDocument doc = collection.getDocument(createResult.getKey(), BaseDocument.class); - assertThat(doc, is(notNullValue())); - final Object article = doc.getAttribute("article"); - assertThat(article, is(notNullValue())); - final Object artist = ((Map) article).get("artist"); - assertThat(artist, is(notNullValue())); - assertThat(artist.toString(), is("PREGARDIEN/RHEINISCHE KANTOREI/DAS")); - } + @SuppressWarnings("unchecked") + @Test + public void insertAsJson() { + //@formatter:off + final String json = + "{" + + "\"article\": {" + + "\"artist\": \"PREGARDIEN/RHEINISCHE KANTOREI/DAS\"," + + "\"releaseDate\": \"1970-01-01\"," + + "\"composer\": \"BACH\"," + + "\"format\": \"CD\"," + + "\"vat\": \"H\"," + + "\"carriers\": 1," + + "\"label\": \"CAPRICCIO\"," + + "\"title\": \"BACH ST MATTHEW PASSION BWV244\"," + + "\"barcode\": [" + + "\"4006408600466\"" + + "]," + + "\"conductor\": \"MAX, H.\"" + + "}," + + "\"stock\": {" + + "\"status\": \"RMV\"," + + "\"lastUpdate\": \"2016-11-01 00:00\"" + + "}" + + "}"; + //@formatter:on + final DocumentCreateEntity createResult = collection.insertDocument(json); + final BaseDocument doc = collection.getDocument(createResult.getKey(), BaseDocument.class); + assertThat(doc, is(notNullValue())); + final Object article = doc.getAttribute("article"); + assertThat(article, is(notNullValue())); + final Object artist = ((Map) article).get("artist"); + assertThat(artist, is(notNullValue())); + assertThat(artist.toString(), is("PREGARDIEN/RHEINISCHE KANTOREI/DAS")); + } - @SuppressWarnings("unchecked") - @Test - public void insertAsBaseDocument() { - final BaseDocument document = new BaseDocument(); - { - final BaseDocument article = new BaseDocument(); - document.addAttribute("article", article); - article.addAttribute("artist", "PREGARDIEN/RHEINISCHE KANTOREI/DAS"); - article.addAttribute("releaseDate", "1970-01-01"); - article.addAttribute("composer", "BACH"); - article.addAttribute("format", "CD"); - article.addAttribute("vat", "H"); - article.addAttribute("carriers", 1); - article.addAttribute("label", "CAPRICCIO"); - article.addAttribute("title", "BACH ST MATTHEW PASSION BWV244"); - article.addAttribute("barcode", new String[] { "4006408600466" }); - article.addAttribute("conductor", "MAX, H."); - final BaseDocument stock = new BaseDocument(); - document.addAttribute("stock", stock); - stock.addAttribute("status", "RMV"); - stock.addAttribute("lastUpdate", "2016-11-01 00:00"); - } - final DocumentCreateEntity createResult = collection.insertDocument(document); - final BaseDocument doc = collection.getDocument(createResult.getKey(), BaseDocument.class); - assertThat(doc, is(notNullValue())); - final Object article = doc.getAttribute("article"); - assertThat(article, is(notNullValue())); - final Object artist = ((Map) article).get("artist"); - assertThat(artist, is(notNullValue())); - assertThat(artist.toString(), is("PREGARDIEN/RHEINISCHE KANTOREI/DAS")); - } + @SuppressWarnings("unchecked") + @Test + public void insertAsBaseDocument() { + final BaseDocument document = new BaseDocument(); + { + final BaseDocument article = new BaseDocument(); + document.addAttribute("article", article); + article.addAttribute("artist", "PREGARDIEN/RHEINISCHE KANTOREI/DAS"); + article.addAttribute("releaseDate", "1970-01-01"); + article.addAttribute("composer", "BACH"); + article.addAttribute("format", "CD"); + article.addAttribute("vat", "H"); + article.addAttribute("carriers", 1); + article.addAttribute("label", "CAPRICCIO"); + article.addAttribute("title", "BACH ST MATTHEW PASSION BWV244"); + article.addAttribute("barcode", new String[]{"4006408600466"}); + article.addAttribute("conductor", "MAX, H."); + final BaseDocument stock = new BaseDocument(); + document.addAttribute("stock", stock); + stock.addAttribute("status", "RMV"); + stock.addAttribute("lastUpdate", "2016-11-01 00:00"); + } + final DocumentCreateEntity createResult = collection.insertDocument(document); + final BaseDocument doc = collection.getDocument(createResult.getKey(), BaseDocument.class); + assertThat(doc, is(notNullValue())); + final Object article = doc.getAttribute("article"); + assertThat(article, is(notNullValue())); + final Object artist = ((Map) article).get("artist"); + assertThat(artist, is(notNullValue())); + assertThat(artist.toString(), is("PREGARDIEN/RHEINISCHE KANTOREI/DAS")); + } } diff --git a/src/test/java/com/arangodb/StreamTransactionTest.java b/src/test/java/com/arangodb/StreamTransactionTest.java index 55e326cde..d3fa6369f 100644 --- a/src/test/java/com/arangodb/StreamTransactionTest.java +++ b/src/test/java/com/arangodb/StreamTransactionTest.java @@ -43,687 +43,681 @@ @RunWith(Parameterized.class) public class StreamTransactionTest extends BaseTest { - private static final String COLLECTION_NAME = "db_stream_transaction_test"; - - public StreamTransactionTest(final Builder builder) { - super(builder); - try { - if (db.collection(COLLECTION_NAME).exists()) - db.collection(COLLECTION_NAME).drop(); - - db.createCollection(COLLECTION_NAME, null); - } catch (final ArangoDBException e) { - - } - } - - @After - public void teardown() { - try { - db.collection(COLLECTION_NAME).drop(); - } catch (final ArangoDBException e) { - } - } - - @Test - public void beginStreamTransaction() { - assumeTrue(requireSingleServer()); - assumeTrue(requireVersion(3, 5)); - assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); - - StreamTransactionEntity tx = db.beginStreamTransaction(null); - assertThat(tx.getId(), is(notNullValue())); - assertThat(tx.getStatus(), is(StreamTransactionStatus.running)); - db.abortStreamTransaction(tx.getId()); - } - - @Test(expected = ArangoDBException.class) - public void beginStreamTransactionWithNonExistingCollectionsShouldThrow() { - assumeTrue(requireSingleServer()); - assumeTrue(requireVersion(3, 5)); - assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); - - db.beginStreamTransaction(new StreamTransactionOptions().writeCollections("notExistingCollection")); - } - - @Test - public void abortStreamTransaction() { - assumeTrue(requireSingleServer()); - assumeTrue(requireVersion(3, 5)); - assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); - - StreamTransactionEntity begunTx = db.beginStreamTransaction(null); - StreamTransactionEntity abortedTx = db.abortStreamTransaction(begunTx.getId()); - - assertThat(abortedTx.getId(), is(notNullValue())); - assertThat(abortedTx.getId(), is(begunTx.getId())); - assertThat(abortedTx.getStatus(), is(StreamTransactionStatus.aborted)); - } - - @Test - public void abortStreamTransactionTwice() { - assumeTrue(requireSingleServer()); - assumeTrue(requireVersion(3, 5)); - assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); - - StreamTransactionEntity begunTx = db.beginStreamTransaction(null); - db.abortStreamTransaction(begunTx.getId()); - db.abortStreamTransaction(begunTx.getId()); - } - - @Test(expected = ArangoDBException.class) - public void abortStreamTransactionWhenTransactionIdDoesNotExistsShouldThrow() { - assumeTrue(requireSingleServer()); - assumeTrue(requireVersion(3, 5)); - assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); - - db.abortStreamTransaction("000000"); - } - - @Test(expected = ArangoDBException.class) - public void abortStreamTransactionWithInvalidTransactionIdShouldThrow() { - assumeTrue(requireSingleServer()); - assumeTrue(requireVersion(3, 5)); - assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); - - db.abortStreamTransaction("invalidTransactionId"); - } - - @Test(expected = ArangoDBException.class) - public void abortCommittedStreamTransactionShouldThrow() { - assumeTrue(requireSingleServer()); - assumeTrue(requireVersion(3, 5)); - assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); - - StreamTransactionEntity createdTx = db.beginStreamTransaction(null); - db.commitStreamTransaction(createdTx.getId()); - db.abortStreamTransaction(createdTx.getId()); - } - - @Test - public void getStreamTransaction() { - assumeTrue(requireSingleServer()); - assumeTrue(requireVersion(3, 5)); - assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); - - StreamTransactionEntity createdTx = db.beginStreamTransaction(null); - StreamTransactionEntity gotTx = db.getStreamTransaction(createdTx.getId()); - - assertThat(gotTx.getId(), is(notNullValue())); - assertThat(gotTx.getId(), is(createdTx.getId())); - assertThat(gotTx.getStatus(), is(StreamTransactionStatus.running)); - - db.abortStreamTransaction(createdTx.getId()); - } - - @Test(expected = ArangoDBException.class) - public void getStreamTransactionWhenTransactionIdDoesNotExistsShouldThrow() { - assumeTrue(requireSingleServer()); - assumeTrue(requireVersion(3, 5)); - assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); - - db.getStreamTransaction("000000"); - } - - @Test(expected = ArangoDBException.class) - public void getStreamTransactionWithInvalidTransactionIdShouldThrow() { - assumeTrue(requireSingleServer()); - assumeTrue(requireVersion(3, 5)); - assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); - - db.getStreamTransaction("invalidTransactionId"); - } - - @Test - public void commitStreamTransaction() { - assumeTrue(requireSingleServer()); - assumeTrue(requireVersion(3, 5)); - assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); - - StreamTransactionEntity createdTx = db.beginStreamTransaction(null); - StreamTransactionEntity committedTx = db.commitStreamTransaction(createdTx.getId()); - - assertThat(committedTx.getId(), is(notNullValue())); - assertThat(committedTx.getId(), is(createdTx.getId())); - assertThat(committedTx.getStatus(), is(StreamTransactionStatus.committed)); - } - - @Test - public void commitStreamTransactionTwice() { - assumeTrue(requireSingleServer()); - assumeTrue(requireVersion(3, 5)); - assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); - - StreamTransactionEntity createdTx = db.beginStreamTransaction(null); - db.commitStreamTransaction(createdTx.getId()); - db.commitStreamTransaction(createdTx.getId()); - } - - @Test(expected = ArangoDBException.class) - public void commitStreamTransactionWhenTransactionIdDoesNotExistsShouldThrow() { - assumeTrue(requireSingleServer()); - assumeTrue(requireVersion(3, 5)); - assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); - - db.commitStreamTransaction("000000"); - } - - @Test(expected = ArangoDBException.class) - public void commitStreamTransactionWithInvalidTransactionIdShouldThrow() { - assumeTrue(requireSingleServer()); - assumeTrue(requireVersion(3, 5)); - assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); - - db.commitStreamTransaction("invalidTransactionId"); - } - - @Test(expected = ArangoDBException.class) - public void commitAbortedStreamTransactionShouldThrow() { - assumeTrue(requireSingleServer()); - assumeTrue(requireVersion(3, 5)); - assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); - - StreamTransactionEntity createdTx = db.beginStreamTransaction(null); - db.abortStreamTransaction(createdTx.getId()); - db.commitStreamTransaction(createdTx.getId()); - } - - @Test - public void getDocument() { - assumeTrue(requireSingleServer()); - assumeTrue(requireVersion(3, 5)); - assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); - - StreamTransactionEntity tx = db - .beginStreamTransaction(new StreamTransactionOptions().readCollections(COLLECTION_NAME)); - - // insert a document from outside the tx - DocumentCreateEntity externalDoc = db.collection(COLLECTION_NAME) - .insertDocument(new BaseDocument(), null); - - // assert that the document is not found from within the tx - assertThat(db.collection(COLLECTION_NAME).getDocument(externalDoc.getKey(), BaseDocument.class, - new DocumentReadOptions().streamTransactionId(tx.getId())), is(nullValue())); - - db.abortStreamTransaction(tx.getId()); - } - - @Test(expected = ArangoDBException.class) - public void getDocumentWithNonExistingTransactionIdShouldThrow() { - assumeTrue(requireSingleServer()); - assumeTrue(requireVersion(3, 5)); - assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); - - db.collection(COLLECTION_NAME) - .getDocument("docId", BaseDocument.class, new DocumentReadOptions().streamTransactionId("123456")); - } - - @Test(expected = ArangoDBException.class) - public void getDocumentWithInvalidTransactionIdShouldThrow() { - assumeTrue(requireSingleServer()); - assumeTrue(requireVersion(3, 5)); - assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); - - db.collection(COLLECTION_NAME) - .getDocument("docId", BaseDocument.class, new DocumentReadOptions().streamTransactionId("abcde")); - } - - @Test - public void getDocuments() { - assumeTrue(requireSingleServer()); - assumeTrue(requireVersion(3, 5)); - assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); - - StreamTransactionEntity tx = db - .beginStreamTransaction(new StreamTransactionOptions().readCollections(COLLECTION_NAME)); - - // insert documents from outside the tx - DocumentCreateEntity externalDoc1 = db.collection(COLLECTION_NAME) - .insertDocument(new BaseDocument(), null); - - DocumentCreateEntity externalDoc2 = db.collection(COLLECTION_NAME) - .insertDocument(new BaseDocument(), null); - - // assert that the documents are not found from within the tx - MultiDocumentEntity documents = db.collection(COLLECTION_NAME) - .getDocuments(Arrays.asList(externalDoc1.getId(), externalDoc2.getId()), BaseDocument.class, - new DocumentReadOptions().streamTransactionId(tx.getId())); - - assertThat(documents.getDocuments(), is(empty())); - - db.abortStreamTransaction(tx.getId()); - } - - @Test - public void insertDocument() { - assumeTrue(requireSingleServer()); - assumeTrue(requireVersion(3, 5)); - assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); - - StreamTransactionEntity tx = db.beginStreamTransaction( - new StreamTransactionOptions().readCollections(COLLECTION_NAME).writeCollections(COLLECTION_NAME)); - - // insert a document from within the tx - DocumentCreateEntity txDoc = db.collection(COLLECTION_NAME) - .insertDocument(new BaseDocument(), new DocumentCreateOptions().streamTransactionId(tx.getId())); + private static final String COLLECTION_NAME = "db_stream_transaction_test"; + + public StreamTransactionTest(final Builder builder) { + super(builder); + if (db.collection(COLLECTION_NAME).exists()) + db.collection(COLLECTION_NAME).drop(); + + db.createCollection(COLLECTION_NAME, null); + } + + @After + public void teardown() { + if (db.collection(COLLECTION_NAME).exists()) + db.collection(COLLECTION_NAME).drop(); + } + + @Test + public void beginStreamTransaction() { + assumeTrue(requireSingleServer()); + assumeTrue(requireVersion(3, 5)); + assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); + + StreamTransactionEntity tx = db.beginStreamTransaction(null); + assertThat(tx.getId(), is(notNullValue())); + assertThat(tx.getStatus(), is(StreamTransactionStatus.running)); + db.abortStreamTransaction(tx.getId()); + } + + @Test(expected = ArangoDBException.class) + public void beginStreamTransactionWithNonExistingCollectionsShouldThrow() { + assumeTrue(requireSingleServer()); + assumeTrue(requireVersion(3, 5)); + assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); + + db.beginStreamTransaction(new StreamTransactionOptions().writeCollections("notExistingCollection")); + } + + @Test + public void abortStreamTransaction() { + assumeTrue(requireSingleServer()); + assumeTrue(requireVersion(3, 5)); + assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); + + StreamTransactionEntity begunTx = db.beginStreamTransaction(null); + StreamTransactionEntity abortedTx = db.abortStreamTransaction(begunTx.getId()); + + assertThat(abortedTx.getId(), is(notNullValue())); + assertThat(abortedTx.getId(), is(begunTx.getId())); + assertThat(abortedTx.getStatus(), is(StreamTransactionStatus.aborted)); + } + + @Test + public void abortStreamTransactionTwice() { + assumeTrue(requireSingleServer()); + assumeTrue(requireVersion(3, 5)); + assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); + + StreamTransactionEntity begunTx = db.beginStreamTransaction(null); + db.abortStreamTransaction(begunTx.getId()); + db.abortStreamTransaction(begunTx.getId()); + } + + @Test(expected = ArangoDBException.class) + public void abortStreamTransactionWhenTransactionIdDoesNotExistsShouldThrow() { + assumeTrue(requireSingleServer()); + assumeTrue(requireVersion(3, 5)); + assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); + + db.abortStreamTransaction("000000"); + } + + @Test(expected = ArangoDBException.class) + public void abortStreamTransactionWithInvalidTransactionIdShouldThrow() { + assumeTrue(requireSingleServer()); + assumeTrue(requireVersion(3, 5)); + assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); + + db.abortStreamTransaction("invalidTransactionId"); + } + + @Test(expected = ArangoDBException.class) + public void abortCommittedStreamTransactionShouldThrow() { + assumeTrue(requireSingleServer()); + assumeTrue(requireVersion(3, 5)); + assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); + + StreamTransactionEntity createdTx = db.beginStreamTransaction(null); + db.commitStreamTransaction(createdTx.getId()); + db.abortStreamTransaction(createdTx.getId()); + } + + @Test + public void getStreamTransaction() { + assumeTrue(requireSingleServer()); + assumeTrue(requireVersion(3, 5)); + assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); + + StreamTransactionEntity createdTx = db.beginStreamTransaction(null); + StreamTransactionEntity gotTx = db.getStreamTransaction(createdTx.getId()); + + assertThat(gotTx.getId(), is(notNullValue())); + assertThat(gotTx.getId(), is(createdTx.getId())); + assertThat(gotTx.getStatus(), is(StreamTransactionStatus.running)); + + db.abortStreamTransaction(createdTx.getId()); + } + + @Test(expected = ArangoDBException.class) + public void getStreamTransactionWhenTransactionIdDoesNotExistsShouldThrow() { + assumeTrue(requireSingleServer()); + assumeTrue(requireVersion(3, 5)); + assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); + + db.getStreamTransaction("000000"); + } + + @Test(expected = ArangoDBException.class) + public void getStreamTransactionWithInvalidTransactionIdShouldThrow() { + assumeTrue(requireSingleServer()); + assumeTrue(requireVersion(3, 5)); + assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); + + db.getStreamTransaction("invalidTransactionId"); + } + + @Test + public void commitStreamTransaction() { + assumeTrue(requireSingleServer()); + assumeTrue(requireVersion(3, 5)); + assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); + + StreamTransactionEntity createdTx = db.beginStreamTransaction(null); + StreamTransactionEntity committedTx = db.commitStreamTransaction(createdTx.getId()); + + assertThat(committedTx.getId(), is(notNullValue())); + assertThat(committedTx.getId(), is(createdTx.getId())); + assertThat(committedTx.getStatus(), is(StreamTransactionStatus.committed)); + } + + @Test + public void commitStreamTransactionTwice() { + assumeTrue(requireSingleServer()); + assumeTrue(requireVersion(3, 5)); + assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); + + StreamTransactionEntity createdTx = db.beginStreamTransaction(null); + db.commitStreamTransaction(createdTx.getId()); + db.commitStreamTransaction(createdTx.getId()); + } + + @Test(expected = ArangoDBException.class) + public void commitStreamTransactionWhenTransactionIdDoesNotExistsShouldThrow() { + assumeTrue(requireSingleServer()); + assumeTrue(requireVersion(3, 5)); + assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); + + db.commitStreamTransaction("000000"); + } + + @Test(expected = ArangoDBException.class) + public void commitStreamTransactionWithInvalidTransactionIdShouldThrow() { + assumeTrue(requireSingleServer()); + assumeTrue(requireVersion(3, 5)); + assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); + + db.commitStreamTransaction("invalidTransactionId"); + } + + @Test(expected = ArangoDBException.class) + public void commitAbortedStreamTransactionShouldThrow() { + assumeTrue(requireSingleServer()); + assumeTrue(requireVersion(3, 5)); + assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); + + StreamTransactionEntity createdTx = db.beginStreamTransaction(null); + db.abortStreamTransaction(createdTx.getId()); + db.commitStreamTransaction(createdTx.getId()); + } + + @Test + public void getDocument() { + assumeTrue(requireSingleServer()); + assumeTrue(requireVersion(3, 5)); + assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); + + StreamTransactionEntity tx = db + .beginStreamTransaction(new StreamTransactionOptions().readCollections(COLLECTION_NAME)); + + // insert a document from outside the tx + DocumentCreateEntity externalDoc = db.collection(COLLECTION_NAME) + .insertDocument(new BaseDocument(), null); + + // assert that the document is not found from within the tx + assertThat(db.collection(COLLECTION_NAME).getDocument(externalDoc.getKey(), BaseDocument.class, + new DocumentReadOptions().streamTransactionId(tx.getId())), is(nullValue())); + + db.abortStreamTransaction(tx.getId()); + } + + @Test(expected = ArangoDBException.class) + public void getDocumentWithNonExistingTransactionIdShouldThrow() { + assumeTrue(requireSingleServer()); + assumeTrue(requireVersion(3, 5)); + assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); + + db.collection(COLLECTION_NAME) + .getDocument("docId", BaseDocument.class, new DocumentReadOptions().streamTransactionId("123456")); + } + + @Test(expected = ArangoDBException.class) + public void getDocumentWithInvalidTransactionIdShouldThrow() { + assumeTrue(requireSingleServer()); + assumeTrue(requireVersion(3, 5)); + assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); + + db.collection(COLLECTION_NAME) + .getDocument("docId", BaseDocument.class, new DocumentReadOptions().streamTransactionId("abcde")); + } + + @Test + public void getDocuments() { + assumeTrue(requireSingleServer()); + assumeTrue(requireVersion(3, 5)); + assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); + + StreamTransactionEntity tx = db + .beginStreamTransaction(new StreamTransactionOptions().readCollections(COLLECTION_NAME)); + + // insert documents from outside the tx + DocumentCreateEntity externalDoc1 = db.collection(COLLECTION_NAME) + .insertDocument(new BaseDocument(), null); + + DocumentCreateEntity externalDoc2 = db.collection(COLLECTION_NAME) + .insertDocument(new BaseDocument(), null); + + // assert that the documents are not found from within the tx + MultiDocumentEntity documents = db.collection(COLLECTION_NAME) + .getDocuments(Arrays.asList(externalDoc1.getId(), externalDoc2.getId()), BaseDocument.class, + new DocumentReadOptions().streamTransactionId(tx.getId())); + + assertThat(documents.getDocuments(), is(empty())); + + db.abortStreamTransaction(tx.getId()); + } + + @Test + public void insertDocument() { + assumeTrue(requireSingleServer()); + assumeTrue(requireVersion(3, 5)); + assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); + + StreamTransactionEntity tx = db.beginStreamTransaction( + new StreamTransactionOptions().readCollections(COLLECTION_NAME).writeCollections(COLLECTION_NAME)); + + // insert a document from within the tx + DocumentCreateEntity txDoc = db.collection(COLLECTION_NAME) + .insertDocument(new BaseDocument(), new DocumentCreateOptions().streamTransactionId(tx.getId())); - // assert that the document is not found from outside the tx - assertThat(db.collection(COLLECTION_NAME).getDocument(txDoc.getKey(), BaseDocument.class, null), - is(nullValue())); - - // assert that the document is found from within the tx - assertThat(db.collection(COLLECTION_NAME).getDocument(txDoc.getKey(), BaseDocument.class, - new DocumentReadOptions().streamTransactionId(tx.getId())), is(notNullValue())); - - db.commitStreamTransaction(tx.getId()); + // assert that the document is not found from outside the tx + assertThat(db.collection(COLLECTION_NAME).getDocument(txDoc.getKey(), BaseDocument.class, null), + is(nullValue())); + + // assert that the document is found from within the tx + assertThat(db.collection(COLLECTION_NAME).getDocument(txDoc.getKey(), BaseDocument.class, + new DocumentReadOptions().streamTransactionId(tx.getId())), is(notNullValue())); + + db.commitStreamTransaction(tx.getId()); - // assert that the document is found after commit - assertThat(db.collection(COLLECTION_NAME).getDocument(txDoc.getKey(), BaseDocument.class, null), - is(notNullValue())); - } + // assert that the document is found after commit + assertThat(db.collection(COLLECTION_NAME).getDocument(txDoc.getKey(), BaseDocument.class, null), + is(notNullValue())); + } - @Test - public void insertDocuments() { - assumeTrue(requireSingleServer()); - assumeTrue(requireVersion(3, 5)); - assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); + @Test + public void insertDocuments() { + assumeTrue(requireSingleServer()); + assumeTrue(requireVersion(3, 5)); + assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); - StreamTransactionEntity tx = db.beginStreamTransaction( - new StreamTransactionOptions().readCollections(COLLECTION_NAME).writeCollections(COLLECTION_NAME)); + StreamTransactionEntity tx = db.beginStreamTransaction( + new StreamTransactionOptions().readCollections(COLLECTION_NAME).writeCollections(COLLECTION_NAME)); - // insert documents from within the tx - MultiDocumentEntity> txDocs = db.collection(COLLECTION_NAME) - .insertDocuments(Arrays.asList(new BaseDocument(), new BaseDocument(), new BaseDocument()), - new DocumentCreateOptions().streamTransactionId(tx.getId())); + // insert documents from within the tx + MultiDocumentEntity> txDocs = db.collection(COLLECTION_NAME) + .insertDocuments(Arrays.asList(new BaseDocument(), new BaseDocument(), new BaseDocument()), + new DocumentCreateOptions().streamTransactionId(tx.getId())); - List keys = txDocs.getDocuments().stream().map(DocumentEntity::getKey).collect(Collectors.toList()); - - // assert that the documents are not found from outside the tx - assertThat(db.collection(COLLECTION_NAME).getDocuments(keys, BaseDocument.class, null).getDocuments(), - is(empty())); + List keys = txDocs.getDocuments().stream().map(DocumentEntity::getKey).collect(Collectors.toList()); + + // assert that the documents are not found from outside the tx + assertThat(db.collection(COLLECTION_NAME).getDocuments(keys, BaseDocument.class, null).getDocuments(), + is(empty())); - // assert that the documents are found from within the tx - assertThat(db.collection(COLLECTION_NAME) - .getDocuments(keys, BaseDocument.class, new DocumentReadOptions().streamTransactionId(tx.getId())) - .getDocuments(), hasSize(keys.size())); + // assert that the documents are found from within the tx + assertThat(db.collection(COLLECTION_NAME) + .getDocuments(keys, BaseDocument.class, new DocumentReadOptions().streamTransactionId(tx.getId())) + .getDocuments(), hasSize(keys.size())); - db.commitStreamTransaction(tx.getId()); + db.commitStreamTransaction(tx.getId()); - // assert that the document is found after commit - assertThat(db.collection(COLLECTION_NAME).getDocuments(keys, BaseDocument.class, null).getDocuments(), - hasSize(keys.size())); - } + // assert that the document is found after commit + assertThat(db.collection(COLLECTION_NAME).getDocuments(keys, BaseDocument.class, null).getDocuments(), + hasSize(keys.size())); + } - @Test - public void replaceDocument() { - assumeTrue(requireSingleServer()); - assumeTrue(requireVersion(3, 5)); - assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); + @Test + public void replaceDocument() { + assumeTrue(requireSingleServer()); + assumeTrue(requireVersion(3, 5)); + assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); - BaseDocument doc = new BaseDocument(); - doc.addAttribute("test", "foo"); + BaseDocument doc = new BaseDocument(); + doc.addAttribute("test", "foo"); - DocumentCreateEntity createdDoc = db.collection(COLLECTION_NAME).insertDocument(doc, null); + DocumentCreateEntity createdDoc = db.collection(COLLECTION_NAME).insertDocument(doc, null); - StreamTransactionEntity tx = db.beginStreamTransaction( - new StreamTransactionOptions().readCollections(COLLECTION_NAME).writeCollections(COLLECTION_NAME)); + StreamTransactionEntity tx = db.beginStreamTransaction( + new StreamTransactionOptions().readCollections(COLLECTION_NAME).writeCollections(COLLECTION_NAME)); - // replace document from within the tx - doc.getProperties().clear(); - doc.addAttribute("test", "bar"); - db.collection(COLLECTION_NAME).replaceDocument(createdDoc.getKey(), doc, - new DocumentReplaceOptions().streamTransactionId(tx.getId())); + // replace document from within the tx + doc.getProperties().clear(); + doc.addAttribute("test", "bar"); + db.collection(COLLECTION_NAME).replaceDocument(createdDoc.getKey(), doc, + new DocumentReplaceOptions().streamTransactionId(tx.getId())); - // assert that the document has not been replaced from outside the tx - assertThat(db.collection(COLLECTION_NAME).getDocument(createdDoc.getKey(), BaseDocument.class, null) - .getProperties().get("test"), is("foo")); + // assert that the document has not been replaced from outside the tx + assertThat(db.collection(COLLECTION_NAME).getDocument(createdDoc.getKey(), BaseDocument.class, null) + .getProperties().get("test"), is("foo")); - // assert that the document has been replaced from within the tx - assertThat(db.collection(COLLECTION_NAME).getDocument(createdDoc.getKey(), BaseDocument.class, - new DocumentReadOptions().streamTransactionId(tx.getId())).getProperties().get("test"), is("bar")); + // assert that the document has been replaced from within the tx + assertThat(db.collection(COLLECTION_NAME).getDocument(createdDoc.getKey(), BaseDocument.class, + new DocumentReadOptions().streamTransactionId(tx.getId())).getProperties().get("test"), is("bar")); - db.commitStreamTransaction(tx.getId()); + db.commitStreamTransaction(tx.getId()); - // assert that the document has been replaced after commit - assertThat(db.collection(COLLECTION_NAME).getDocument(createdDoc.getKey(), BaseDocument.class, null) - .getProperties().get("test"), is("bar")); - } + // assert that the document has been replaced after commit + assertThat(db.collection(COLLECTION_NAME).getDocument(createdDoc.getKey(), BaseDocument.class, null) + .getProperties().get("test"), is("bar")); + } - @Test - public void replaceDocuments() { - assumeTrue(requireSingleServer()); - assumeTrue(requireVersion(3, 5)); - assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); + @Test + public void replaceDocuments() { + assumeTrue(requireSingleServer()); + assumeTrue(requireVersion(3, 5)); + assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); - List docs = IntStream.range(0, 3).mapToObj(it -> new BaseDocument()) - .peek(doc -> doc.addAttribute("test", "foo")).collect(Collectors.toList()); + List docs = IntStream.range(0, 3).mapToObj(it -> new BaseDocument()) + .peek(doc -> doc.addAttribute("test", "foo")).collect(Collectors.toList()); - List createdDocs = db.collection(COLLECTION_NAME) - .insertDocuments(docs, new DocumentCreateOptions().returnNew(true)).getDocuments().stream() - .map(DocumentCreateEntity::getNew).collect(Collectors.toList()); + List createdDocs = db.collection(COLLECTION_NAME) + .insertDocuments(docs, new DocumentCreateOptions().returnNew(true)).getDocuments().stream() + .map(DocumentCreateEntity::getNew).collect(Collectors.toList()); - List keys = createdDocs.stream().map(BaseDocument::getKey).collect(Collectors.toList()); + List keys = createdDocs.stream().map(BaseDocument::getKey).collect(Collectors.toList()); - StreamTransactionEntity tx = db.beginStreamTransaction( - new StreamTransactionOptions().readCollections(COLLECTION_NAME).writeCollections(COLLECTION_NAME)); + StreamTransactionEntity tx = db.beginStreamTransaction( + new StreamTransactionOptions().readCollections(COLLECTION_NAME).writeCollections(COLLECTION_NAME)); - List modifiedDocs = createdDocs.stream().peek(doc -> { - doc.getProperties().clear(); - doc.addAttribute("test", "bar"); - }).collect(Collectors.toList()); + List modifiedDocs = createdDocs.stream().peek(doc -> { + doc.getProperties().clear(); + doc.addAttribute("test", "bar"); + }).collect(Collectors.toList()); - // replace document from within the tx - db.collection(COLLECTION_NAME) - .replaceDocuments(modifiedDocs, new DocumentReplaceOptions().streamTransactionId(tx.getId())); + // replace document from within the tx + db.collection(COLLECTION_NAME) + .replaceDocuments(modifiedDocs, new DocumentReplaceOptions().streamTransactionId(tx.getId())); - // assert that the documents has not been replaced from outside the tx - assertThat(db.collection(COLLECTION_NAME).getDocuments(keys, BaseDocument.class, null).getDocuments().stream() - .map(it -> ((String) it.getAttribute("test"))).collect(Collectors.toList()), everyItem(is("foo"))); + // assert that the documents has not been replaced from outside the tx + assertThat(db.collection(COLLECTION_NAME).getDocuments(keys, BaseDocument.class, null).getDocuments().stream() + .map(it -> ((String) it.getAttribute("test"))).collect(Collectors.toList()), everyItem(is("foo"))); - // assert that the document has been replaced from within the tx - assertThat(db.collection(COLLECTION_NAME) - .getDocuments(keys, BaseDocument.class, new DocumentReadOptions().streamTransactionId(tx.getId())) - .getDocuments().stream().map(it -> ((String) it.getAttribute("test"))).collect(Collectors.toList()), - everyItem(is("bar"))); + // assert that the document has been replaced from within the tx + assertThat(db.collection(COLLECTION_NAME) + .getDocuments(keys, BaseDocument.class, new DocumentReadOptions().streamTransactionId(tx.getId())) + .getDocuments().stream().map(it -> ((String) it.getAttribute("test"))).collect(Collectors.toList()), + everyItem(is("bar"))); - db.commitStreamTransaction(tx.getId()); + db.commitStreamTransaction(tx.getId()); - // assert that the document has been replaced after commit - assertThat(db.collection(COLLECTION_NAME).getDocuments(keys, BaseDocument.class, null).getDocuments().stream() - .map(it -> ((String) it.getAttribute("test"))).collect(Collectors.toList()), everyItem(is("bar"))); - } + // assert that the document has been replaced after commit + assertThat(db.collection(COLLECTION_NAME).getDocuments(keys, BaseDocument.class, null).getDocuments().stream() + .map(it -> ((String) it.getAttribute("test"))).collect(Collectors.toList()), everyItem(is("bar"))); + } - @Test - public void updateDocument() { - assumeTrue(requireSingleServer()); - assumeTrue(requireVersion(3, 5)); - assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); + @Test + public void updateDocument() { + assumeTrue(requireSingleServer()); + assumeTrue(requireVersion(3, 5)); + assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); - BaseDocument doc = new BaseDocument(); - doc.addAttribute("test", "foo"); + BaseDocument doc = new BaseDocument(); + doc.addAttribute("test", "foo"); - DocumentCreateEntity createdDoc = db.collection(COLLECTION_NAME).insertDocument(doc, null); + DocumentCreateEntity createdDoc = db.collection(COLLECTION_NAME).insertDocument(doc, null); - StreamTransactionEntity tx = db.beginStreamTransaction( - new StreamTransactionOptions().readCollections(COLLECTION_NAME).writeCollections(COLLECTION_NAME)); + StreamTransactionEntity tx = db.beginStreamTransaction( + new StreamTransactionOptions().readCollections(COLLECTION_NAME).writeCollections(COLLECTION_NAME)); - // update document from within the tx - doc.getProperties().clear(); - doc.addAttribute("test", "bar"); - db.collection(COLLECTION_NAME) - .updateDocument(createdDoc.getKey(), doc, new DocumentUpdateOptions().streamTransactionId(tx.getId())); + // update document from within the tx + doc.getProperties().clear(); + doc.addAttribute("test", "bar"); + db.collection(COLLECTION_NAME) + .updateDocument(createdDoc.getKey(), doc, new DocumentUpdateOptions().streamTransactionId(tx.getId())); - // assert that the document has not been updated from outside the tx - assertThat(db.collection(COLLECTION_NAME).getDocument(createdDoc.getKey(), BaseDocument.class, null) - .getProperties().get("test"), is("foo")); + // assert that the document has not been updated from outside the tx + assertThat(db.collection(COLLECTION_NAME).getDocument(createdDoc.getKey(), BaseDocument.class, null) + .getProperties().get("test"), is("foo")); - // assert that the document has been updated from within the tx - assertThat(db.collection(COLLECTION_NAME).getDocument(createdDoc.getKey(), BaseDocument.class, - new DocumentReadOptions().streamTransactionId(tx.getId())).getProperties().get("test"), is("bar")); + // assert that the document has been updated from within the tx + assertThat(db.collection(COLLECTION_NAME).getDocument(createdDoc.getKey(), BaseDocument.class, + new DocumentReadOptions().streamTransactionId(tx.getId())).getProperties().get("test"), is("bar")); - db.commitStreamTransaction(tx.getId()); + db.commitStreamTransaction(tx.getId()); - // assert that the document has been updated after commit - assertThat(db.collection(COLLECTION_NAME).getDocument(createdDoc.getKey(), BaseDocument.class, null) - .getProperties().get("test"), is("bar")); + // assert that the document has been updated after commit + assertThat(db.collection(COLLECTION_NAME).getDocument(createdDoc.getKey(), BaseDocument.class, null) + .getProperties().get("test"), is("bar")); - } + } - @Test - public void updateDocuments() { - assumeTrue(requireSingleServer()); - assumeTrue(requireVersion(3, 5)); - assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); + @Test + public void updateDocuments() { + assumeTrue(requireSingleServer()); + assumeTrue(requireVersion(3, 5)); + assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); - List docs = IntStream.range(0, 3).mapToObj(it -> new BaseDocument()) - .peek(doc -> doc.addAttribute("test", "foo")).collect(Collectors.toList()); + List docs = IntStream.range(0, 3).mapToObj(it -> new BaseDocument()) + .peek(doc -> doc.addAttribute("test", "foo")).collect(Collectors.toList()); - List createdDocs = db.collection(COLLECTION_NAME) - .insertDocuments(docs, new DocumentCreateOptions().returnNew(true)).getDocuments().stream() - .map(DocumentCreateEntity::getNew).collect(Collectors.toList()); + List createdDocs = db.collection(COLLECTION_NAME) + .insertDocuments(docs, new DocumentCreateOptions().returnNew(true)).getDocuments().stream() + .map(DocumentCreateEntity::getNew).collect(Collectors.toList()); - List keys = createdDocs.stream().map(BaseDocument::getKey).collect(Collectors.toList()); + List keys = createdDocs.stream().map(BaseDocument::getKey).collect(Collectors.toList()); - StreamTransactionEntity tx = db.beginStreamTransaction( - new StreamTransactionOptions().readCollections(COLLECTION_NAME).writeCollections(COLLECTION_NAME)); + StreamTransactionEntity tx = db.beginStreamTransaction( + new StreamTransactionOptions().readCollections(COLLECTION_NAME).writeCollections(COLLECTION_NAME)); - List modifiedDocs = createdDocs.stream().peek(doc -> { - doc.getProperties().clear(); - doc.addAttribute("test", "bar"); - }).collect(Collectors.toList()); + List modifiedDocs = createdDocs.stream().peek(doc -> { + doc.getProperties().clear(); + doc.addAttribute("test", "bar"); + }).collect(Collectors.toList()); - // update documents from within the tx - db.collection(COLLECTION_NAME) - .updateDocuments(modifiedDocs, new DocumentUpdateOptions().streamTransactionId(tx.getId())); + // update documents from within the tx + db.collection(COLLECTION_NAME) + .updateDocuments(modifiedDocs, new DocumentUpdateOptions().streamTransactionId(tx.getId())); - // assert that the documents have not been updated from outside the tx - assertThat(db.collection(COLLECTION_NAME).getDocuments(keys, BaseDocument.class, null).getDocuments().stream() - .map(it -> ((String) it.getAttribute("test"))).collect(Collectors.toList()), everyItem(is("foo"))); + // assert that the documents have not been updated from outside the tx + assertThat(db.collection(COLLECTION_NAME).getDocuments(keys, BaseDocument.class, null).getDocuments().stream() + .map(it -> ((String) it.getAttribute("test"))).collect(Collectors.toList()), everyItem(is("foo"))); - // assert that the documents have been updated from within the tx - List values = db.collection(COLLECTION_NAME) - .getDocuments(keys, BaseDocument.class, new DocumentReadOptions().streamTransactionId(tx.getId())) - .getDocuments().stream().map(it -> ((String) it.getAttribute("test"))).collect(Collectors.toList()); - assertThat(values, everyItem(is("bar"))); + // assert that the documents have been updated from within the tx + List values = db.collection(COLLECTION_NAME) + .getDocuments(keys, BaseDocument.class, new DocumentReadOptions().streamTransactionId(tx.getId())) + .getDocuments().stream().map(it -> ((String) it.getAttribute("test"))).collect(Collectors.toList()); + assertThat(values, everyItem(is("bar"))); - db.commitStreamTransaction(tx.getId()); + db.commitStreamTransaction(tx.getId()); - // assert that the document has been updated after commit - assertThat(db.collection(COLLECTION_NAME).getDocuments(keys, BaseDocument.class, null).getDocuments().stream() - .map(it -> ((String) it.getAttribute("test"))).collect(Collectors.toList()), everyItem(is("bar"))); - } + // assert that the document has been updated after commit + assertThat(db.collection(COLLECTION_NAME).getDocuments(keys, BaseDocument.class, null).getDocuments().stream() + .map(it -> ((String) it.getAttribute("test"))).collect(Collectors.toList()), everyItem(is("bar"))); + } - @Test - public void deleteDocument() { - assumeTrue(requireSingleServer()); - assumeTrue(requireVersion(3, 5)); - assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); + @Test + public void deleteDocument() { + assumeTrue(requireSingleServer()); + assumeTrue(requireVersion(3, 5)); + assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); - DocumentCreateEntity createdDoc = db.collection(COLLECTION_NAME) - .insertDocument(new BaseDocument(), null); + DocumentCreateEntity createdDoc = db.collection(COLLECTION_NAME) + .insertDocument(new BaseDocument(), null); - StreamTransactionEntity tx = db.beginStreamTransaction( - new StreamTransactionOptions().readCollections(COLLECTION_NAME).writeCollections(COLLECTION_NAME)); + StreamTransactionEntity tx = db.beginStreamTransaction( + new StreamTransactionOptions().readCollections(COLLECTION_NAME).writeCollections(COLLECTION_NAME)); - // delete document from within the tx - db.collection(COLLECTION_NAME) - .deleteDocument(createdDoc.getKey(), null, new DocumentDeleteOptions().streamTransactionId(tx.getId())); + // delete document from within the tx + db.collection(COLLECTION_NAME) + .deleteDocument(createdDoc.getKey(), null, new DocumentDeleteOptions().streamTransactionId(tx.getId())); - // assert that the document has not been deleted from outside the tx - assertThat(db.collection(COLLECTION_NAME).getDocument(createdDoc.getKey(), BaseDocument.class, null), - is(notNullValue())); + // assert that the document has not been deleted from outside the tx + assertThat(db.collection(COLLECTION_NAME).getDocument(createdDoc.getKey(), BaseDocument.class, null), + is(notNullValue())); - // assert that the document has been deleted from within the tx - assertThat(db.collection(COLLECTION_NAME).getDocument(createdDoc.getKey(), BaseDocument.class, - new DocumentReadOptions().streamTransactionId(tx.getId())), is(nullValue())); + // assert that the document has been deleted from within the tx + assertThat(db.collection(COLLECTION_NAME).getDocument(createdDoc.getKey(), BaseDocument.class, + new DocumentReadOptions().streamTransactionId(tx.getId())), is(nullValue())); - db.commitStreamTransaction(tx.getId()); + db.commitStreamTransaction(tx.getId()); - // assert that the document has been deleted after commit - assertThat(db.collection(COLLECTION_NAME).getDocument(createdDoc.getKey(), BaseDocument.class, null), - is(nullValue())); - } + // assert that the document has been deleted after commit + assertThat(db.collection(COLLECTION_NAME).getDocument(createdDoc.getKey(), BaseDocument.class, null), + is(nullValue())); + } - @Test - public void deleteDocuments() { - assumeTrue(requireSingleServer()); - assumeTrue(requireVersion(3, 5)); - assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); + @Test + public void deleteDocuments() { + assumeTrue(requireSingleServer()); + assumeTrue(requireVersion(3, 5)); + assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); - List keys = db.collection(COLLECTION_NAME) - .insertDocuments(Arrays.asList(new BaseDocument(), new BaseDocument(), new BaseDocument()), null) - .getDocuments().stream().map(DocumentEntity::getKey).collect(Collectors.toList()); + List keys = db.collection(COLLECTION_NAME) + .insertDocuments(Arrays.asList(new BaseDocument(), new BaseDocument(), new BaseDocument()), null) + .getDocuments().stream().map(DocumentEntity::getKey).collect(Collectors.toList()); - StreamTransactionEntity tx = db.beginStreamTransaction( - new StreamTransactionOptions().readCollections(COLLECTION_NAME).writeCollections(COLLECTION_NAME)); + StreamTransactionEntity tx = db.beginStreamTransaction( + new StreamTransactionOptions().readCollections(COLLECTION_NAME).writeCollections(COLLECTION_NAME)); - // delete document from within the tx - db.collection(COLLECTION_NAME) - .deleteDocuments(keys, null, new DocumentDeleteOptions().streamTransactionId(tx.getId())); + // delete document from within the tx + db.collection(COLLECTION_NAME) + .deleteDocuments(keys, null, new DocumentDeleteOptions().streamTransactionId(tx.getId())); - // assert that the documents has not been deleted from outside the tx - assertThat(db.collection(COLLECTION_NAME).getDocuments(keys, BaseDocument.class, null).getDocuments(), - hasSize(keys.size())); + // assert that the documents has not been deleted from outside the tx + assertThat(db.collection(COLLECTION_NAME).getDocuments(keys, BaseDocument.class, null).getDocuments(), + hasSize(keys.size())); - // assert that the document has been deleted from within the tx - assertThat(db.collection(COLLECTION_NAME) - .getDocuments(keys, BaseDocument.class, new DocumentReadOptions().streamTransactionId(tx.getId())) - .getDocuments(), is(empty())); + // assert that the document has been deleted from within the tx + assertThat(db.collection(COLLECTION_NAME) + .getDocuments(keys, BaseDocument.class, new DocumentReadOptions().streamTransactionId(tx.getId())) + .getDocuments(), is(empty())); - db.commitStreamTransaction(tx.getId()); + db.commitStreamTransaction(tx.getId()); - // assert that the document has been deleted after commit - assertThat(db.collection(COLLECTION_NAME).getDocuments(keys, BaseDocument.class, null).getDocuments(), - is(empty())); - } + // assert that the document has been deleted after commit + assertThat(db.collection(COLLECTION_NAME).getDocuments(keys, BaseDocument.class, null).getDocuments(), + is(empty())); + } - @Test - public void documentExists() { - assumeTrue(requireSingleServer()); - assumeTrue(requireVersion(3, 5)); - assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); + @Test + public void documentExists() { + assumeTrue(requireSingleServer()); + assumeTrue(requireVersion(3, 5)); + assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); - StreamTransactionEntity tx = db - .beginStreamTransaction(new StreamTransactionOptions().readCollections(COLLECTION_NAME)); + StreamTransactionEntity tx = db + .beginStreamTransaction(new StreamTransactionOptions().readCollections(COLLECTION_NAME)); - // insert a document from outside the tx - DocumentCreateEntity externalDoc = db.collection(COLLECTION_NAME) - .insertDocument(new BaseDocument(), null); + // insert a document from outside the tx + DocumentCreateEntity externalDoc = db.collection(COLLECTION_NAME) + .insertDocument(new BaseDocument(), null); - // assert that the document is not found from within the tx - assertThat(db.collection(COLLECTION_NAME) - .documentExists(externalDoc.getKey(), new DocumentExistsOptions().streamTransactionId(tx.getId())), - is(false)); + // assert that the document is not found from within the tx + assertThat(db.collection(COLLECTION_NAME) + .documentExists(externalDoc.getKey(), new DocumentExistsOptions().streamTransactionId(tx.getId())), + is(false)); - db.abortStreamTransaction(tx.getId()); - } + db.abortStreamTransaction(tx.getId()); + } - @Test - public void count() { - assumeTrue(requireSingleServer()); - assumeTrue(requireVersion(3, 5)); - assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); + @Test + public void count() { + assumeTrue(requireSingleServer()); + assumeTrue(requireVersion(3, 5)); + assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); - Long initialCount = db.collection(COLLECTION_NAME).count().getCount(); + Long initialCount = db.collection(COLLECTION_NAME).count().getCount(); - StreamTransactionEntity tx = db - .beginStreamTransaction(new StreamTransactionOptions().readCollections(COLLECTION_NAME)); + StreamTransactionEntity tx = db + .beginStreamTransaction(new StreamTransactionOptions().readCollections(COLLECTION_NAME)); - // insert a document from outside the tx - db.collection(COLLECTION_NAME).insertDocument(new BaseDocument(), null); + // insert a document from outside the tx + db.collection(COLLECTION_NAME).insertDocument(new BaseDocument(), null); - // assert that the document is not counted from within the tx - assertThat(db.collection(COLLECTION_NAME).count(new CollectionCountOptions().streamTransactionId(tx.getId())) - .getCount(), is(initialCount)); + // assert that the document is not counted from within the tx + assertThat(db.collection(COLLECTION_NAME).count(new CollectionCountOptions().streamTransactionId(tx.getId())) + .getCount(), is(initialCount)); - db.abortStreamTransaction(tx.getId()); - } + db.abortStreamTransaction(tx.getId()); + } - @Test - public void truncate() { - assumeTrue(requireSingleServer()); - assumeTrue(requireVersion(3, 5)); - assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); + @Test + public void truncate() { + assumeTrue(requireSingleServer()); + assumeTrue(requireVersion(3, 5)); + assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); - db.collection(COLLECTION_NAME).insertDocument(new BaseDocument(), null); + db.collection(COLLECTION_NAME).insertDocument(new BaseDocument(), null); - StreamTransactionEntity tx = db.beginStreamTransaction( - new StreamTransactionOptions().readCollections(COLLECTION_NAME).writeCollections(COLLECTION_NAME)); + StreamTransactionEntity tx = db.beginStreamTransaction( + new StreamTransactionOptions().readCollections(COLLECTION_NAME).writeCollections(COLLECTION_NAME)); - // truncate document from within the tx - db.collection(COLLECTION_NAME).truncate(new CollectionTruncateOptions().streamTransactionId(tx.getId())); + // truncate document from within the tx + db.collection(COLLECTION_NAME).truncate(new CollectionTruncateOptions().streamTransactionId(tx.getId())); - // assert that the collection has not been truncated from outside the tx - assertThat(db.collection(COLLECTION_NAME).count().getCount(), is(greaterThan(0L))); + // assert that the collection has not been truncated from outside the tx + assertThat(db.collection(COLLECTION_NAME).count().getCount(), is(greaterThan(0L))); - // assert that the collection has been truncated from within the tx - assertThat(db.collection(COLLECTION_NAME).count(new CollectionCountOptions().streamTransactionId(tx.getId())) - .getCount(), is(0L)); + // assert that the collection has been truncated from within the tx + assertThat(db.collection(COLLECTION_NAME).count(new CollectionCountOptions().streamTransactionId(tx.getId())) + .getCount(), is(0L)); - db.commitStreamTransaction(tx.getId()); + db.commitStreamTransaction(tx.getId()); - // assert that the collection has been truncated after commit - assertThat(db.collection(COLLECTION_NAME).count().getCount(), is(0L)); - } + // assert that the collection has been truncated after commit + assertThat(db.collection(COLLECTION_NAME).count().getCount(), is(0L)); + } - @Test - public void createCursor() { - assumeTrue(requireSingleServer()); - assumeTrue(requireVersion(3, 5)); - assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); + @Test + public void createCursor() { + assumeTrue(requireSingleServer()); + assumeTrue(requireVersion(3, 5)); + assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); - StreamTransactionEntity tx = db - .beginStreamTransaction(new StreamTransactionOptions().readCollections(COLLECTION_NAME)); + StreamTransactionEntity tx = db + .beginStreamTransaction(new StreamTransactionOptions().readCollections(COLLECTION_NAME)); - // insert a document from outside the tx - DocumentCreateEntity externalDoc = db.collection(COLLECTION_NAME) - .insertDocument(new BaseDocument(), null); + // insert a document from outside the tx + DocumentCreateEntity externalDoc = db.collection(COLLECTION_NAME) + .insertDocument(new BaseDocument(), null); - final Map bindVars = new HashMap<>(); - bindVars.put("@collection", COLLECTION_NAME); - bindVars.put("key", externalDoc.getKey()); + final Map bindVars = new HashMap<>(); + bindVars.put("@collection", COLLECTION_NAME); + bindVars.put("key", externalDoc.getKey()); - ArangoCursor cursor = db - .query("FOR doc IN @@collection FILTER doc._key == @key RETURN doc", bindVars, - new AqlQueryOptions().streamTransactionId(tx.getId()), BaseDocument.class); + ArangoCursor cursor = db + .query("FOR doc IN @@collection FILTER doc._key == @key RETURN doc", bindVars, + new AqlQueryOptions().streamTransactionId(tx.getId()), BaseDocument.class); - // assert that the document is not found from within the tx - assertThat(cursor.hasNext(), is(false)); + // assert that the document is not found from within the tx + assertThat(cursor.hasNext(), is(false)); - db.abortStreamTransaction(tx.getId()); - } + db.abortStreamTransaction(tx.getId()); + } - @Test - public void nextCursor() { - assumeTrue(requireSingleServer()); - assumeTrue(requireVersion(3, 5)); - assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); + @Test + public void nextCursor() { + assumeTrue(requireSingleServer()); + assumeTrue(requireVersion(3, 5)); + assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); - StreamTransactionEntity tx = db.beginStreamTransaction( - new StreamTransactionOptions().readCollections(COLLECTION_NAME).writeCollections(COLLECTION_NAME)); + StreamTransactionEntity tx = db.beginStreamTransaction( + new StreamTransactionOptions().readCollections(COLLECTION_NAME).writeCollections(COLLECTION_NAME)); - // insert documents from within the tx - List keys = db.collection(COLLECTION_NAME) - .insertDocuments(IntStream.range(0, 10).mapToObj(it -> new BaseDocument()).collect(Collectors.toList()), - new DocumentCreateOptions().streamTransactionId(tx.getId())).getDocuments().stream() - .map(DocumentEntity::getKey).collect(Collectors.toList()); + // insert documents from within the tx + List keys = db.collection(COLLECTION_NAME) + .insertDocuments(IntStream.range(0, 10).mapToObj(it -> new BaseDocument()).collect(Collectors.toList()), + new DocumentCreateOptions().streamTransactionId(tx.getId())).getDocuments().stream() + .map(DocumentEntity::getKey).collect(Collectors.toList()); - final Map bindVars = new HashMap<>(); - bindVars.put("@collection", COLLECTION_NAME); - bindVars.put("keys", keys); + final Map bindVars = new HashMap<>(); + bindVars.put("@collection", COLLECTION_NAME); + bindVars.put("keys", keys); - ArangoCursor cursor = db - .query("FOR doc IN @@collection FILTER CONTAINS_ARRAY(@keys, doc._key) RETURN doc", bindVars, - new AqlQueryOptions().streamTransactionId(tx.getId()).batchSize(2), BaseDocument.class); + ArangoCursor cursor = db + .query("FOR doc IN @@collection FILTER CONTAINS_ARRAY(@keys, doc._key) RETURN doc", bindVars, + new AqlQueryOptions().streamTransactionId(tx.getId()).batchSize(2), BaseDocument.class); - List docs = cursor.asListRemaining(); + List docs = cursor.asListRemaining(); - // assert that all the keys are returned from the query - assertThat(docs.stream().map(BaseDocument::getKey).collect(Collectors.toList()), - containsInAnyOrder(keys.toArray())); + // assert that all the keys are returned from the query + assertThat(docs.stream().map(BaseDocument::getKey).collect(Collectors.toList()), + containsInAnyOrder(keys.toArray())); - db.abortStreamTransaction(tx.getId()); - } + db.abortStreamTransaction(tx.getId()); + } - @Test - public void getStreamTransactions() { - assumeTrue(requireSingleServer()); - assumeTrue(requireVersion(3, 5)); - assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); + @Test + public void getStreamTransactions() { + assumeTrue(requireSingleServer()); + assumeTrue(requireVersion(3, 5)); + assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); - StreamTransactionEntity tx1 = db.beginStreamTransaction(null); - StreamTransactionEntity tx2 = db.beginStreamTransaction(null); + StreamTransactionEntity tx1 = db.beginStreamTransaction(null); + StreamTransactionEntity tx2 = db.beginStreamTransaction(null); - List createdIds = Arrays.asList(tx1.getId(), tx2.getId()); - Set gotTxs = db.getStreamTransactions().stream(). - filter(it -> createdIds.contains(it.getId())).collect(Collectors.toSet()); + List createdIds = Arrays.asList(tx1.getId(), tx2.getId()); + Set gotTxs = db.getStreamTransactions().stream(). + filter(it -> createdIds.contains(it.getId())).collect(Collectors.toSet()); - assertThat(gotTxs.size(), is(createdIds.size())); - assertThat(gotTxs.stream() - .allMatch(it -> it.getStatus() == StreamTransactionStatus.running), is(true)); + assertThat(gotTxs.size(), is(createdIds.size())); + assertThat(gotTxs.stream() + .allMatch(it -> it.getStatus() == StreamTransactionStatus.running), is(true)); - db.abortStreamTransaction(tx1.getId()); - db.abortStreamTransaction(tx2.getId()); - } + db.abortStreamTransaction(tx1.getId()); + db.abortStreamTransaction(tx2.getId()); + } } diff --git a/src/test/java/com/arangodb/UserAuthTest.java b/src/test/java/com/arangodb/UserAuthTest.java index 7d068ed8b..85aaffd76 100644 --- a/src/test/java/com/arangodb/UserAuthTest.java +++ b/src/test/java/com/arangodb/UserAuthTest.java @@ -51,858 +51,855 @@ /** * @author Mark Vollmary - * */ @RunWith(Parameterized.class) @Ignore public class UserAuthTest { - private static final String DB_NAME = "AuthUnitTestDB"; - private static final String DB_NAME_NEW = DB_NAME + "new"; - private static final String COLLECTION_NAME = "AuthUnitTestCollection"; - private static final String COLLECTION_NAME_NEW = COLLECTION_NAME + "new"; - private static final String USER_NAME = "AuthUnitTestUser"; - private static final String USER_NAME_NEW = USER_NAME + "new"; - - public static class UserAuthParam { - Protocol protocol; - Permissions systemPermission; - Permissions dbPermission; - Permissions colPermission; - - public UserAuthParam(final Protocol protocol, final Permissions systemPermission, - final Permissions dbPermission, final Permissions colPermission) { - super(); - this.protocol = protocol; - this.systemPermission = systemPermission; - this.dbPermission = dbPermission; - this.colPermission = colPermission; - } - - } - - @Parameters - public static Collection params() { - final Collection params = new ArrayList(); - final Permissions[] permissions = new Permissions[] { Permissions.RW, Permissions.RO, Permissions.NONE }; - for (final Protocol protocol : new Protocol[] { Protocol.VST, Protocol.HTTP_JSON, Protocol.HTTP_VPACK }) { - for (final Permissions systemPermission : permissions) { - for (final Permissions dbPermission : permissions) { - for (final Permissions colPermission : permissions) { - params.add(new UserAuthParam(protocol, systemPermission, dbPermission, colPermission)); - } - } - } - } - return params; - } - - private static ArangoDB arangoDB; - private static ArangoDB arangoDBRoot; - private final UserAuthParam param; - private final String details; - - public UserAuthTest(final UserAuthParam param) { - super(); - this.param = param; - if (arangoDB != null || arangoDBRoot != null) { - shutdown(); - } - arangoDBRoot = new ArangoDB.Builder().useProtocol(param.protocol).build(); - arangoDBRoot.createUser(USER_NAME, ""); - arangoDB = new ArangoDB.Builder().useProtocol(param.protocol).user(USER_NAME).build(); - arangoDBRoot.createDatabase(DB_NAME); - arangoDBRoot.db(DB_NAME).createCollection(COLLECTION_NAME); - arangoDBRoot.db().grantAccess(USER_NAME, param.systemPermission); - arangoDBRoot.db(DB_NAME).grantAccess(USER_NAME, param.dbPermission); - arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME).grantAccess(USER_NAME, param.colPermission); - details = new StringBuffer().append(param.protocol).append("_").append(param.systemPermission).append("_") - .append(param.dbPermission).append("_").append(param.colPermission).toString(); - } - - @AfterClass - public static void shutdown() { - arangoDBRoot.deleteUser(USER_NAME); - try { - arangoDBRoot.db(DB_NAME).drop(); - } catch (final ArangoDBException e) { - } - if (arangoDB != null) { - arangoDB.shutdown(); - } - arangoDBRoot.shutdown(); - arangoDB = null; - arangoDBRoot = null; - } - - @Test - public void createDatabase() { - try { - if (Permissions.RW.equals(param.systemPermission)) { - try { - assertThat(details, arangoDB.createDatabase(DB_NAME_NEW), is(true)); - } catch (final ArangoDBException e) { - fail(details); - } - assertThat(details, arangoDBRoot.getDatabases(), hasItem(DB_NAME_NEW)); - } else { - try { - arangoDB.createDatabase(DB_NAME_NEW); - fail(details); - } catch (final ArangoDBException e) { - } - assertThat(details, arangoDBRoot.getDatabases(), not(hasItem(DB_NAME_NEW))); - } - } finally { - try { - arangoDBRoot.db(DB_NAME_NEW).drop(); - } catch (final ArangoDBException e) { - } - } - } - - @Test - public void dropDatabase() { - try { - arangoDBRoot.createDatabase(DB_NAME_NEW); - if (Permissions.RW.equals(param.systemPermission)) { - try { - assertThat(details, arangoDB.db(DB_NAME).drop(), is(true)); - } catch (final ArangoDBException e) { - fail(details); - } - assertThat(details, arangoDBRoot.getDatabases(), not(hasItem(DB_NAME))); - } else { - try { - arangoDB.db(DB_NAME).drop(); - fail(details); - } catch (final ArangoDBException e) { - } - assertThat(details, arangoDBRoot.getDatabases(), hasItem(DB_NAME)); - } - } finally { - try { - arangoDBRoot.db(DB_NAME_NEW).drop(); - } catch (final ArangoDBException e) { - } - } - } - - @Test - public void createUser() { - try { - if (Permissions.RW.equals(param.systemPermission)) { - try { - arangoDB.createUser(USER_NAME_NEW, ""); - } catch (final ArangoDBException e) { - fail(details); - } - assertThat(details, arangoDBRoot.getUsers(), is(notNullValue())); - } else { - try { - arangoDB.createUser(USER_NAME_NEW, ""); - fail(details); - } catch (final ArangoDBException e) { - } - try { - arangoDBRoot.getUser(USER_NAME_NEW); - fail(details); - } catch (final ArangoDBException e) { - } - } - } finally { - try { - arangoDBRoot.deleteUser(USER_NAME_NEW); - } catch (final ArangoDBException e) { - } - } - } - - @Test - public void deleteUser() { - try { - arangoDBRoot.createUser(USER_NAME_NEW, ""); - if (Permissions.RW.equals(param.systemPermission)) { - try { - arangoDB.deleteUser(USER_NAME_NEW); - } catch (final ArangoDBException e) { - fail(details); - } - try { - arangoDBRoot.getUser(USER_NAME_NEW); - fail(details); - } catch (final ArangoDBException e) { - } - } else { - try { - arangoDB.deleteUser(USER_NAME_NEW); - fail(details); - } catch (final ArangoDBException e) { - } - assertThat(details, arangoDBRoot.getUsers(), is(notNullValue())); - } - } finally { - try { - arangoDBRoot.deleteUser(USER_NAME_NEW); - } catch (final ArangoDBException e) { - } - } - } - - @Test - public void updateUser() { - try { - arangoDBRoot.createUser(USER_NAME_NEW, ""); - if (Permissions.RW.equals(param.systemPermission)) { - try { - arangoDB.updateUser(USER_NAME_NEW, new UserUpdateOptions().active(false)); - } catch (final ArangoDBException e) { - fail(details); - } - assertThat(details, arangoDBRoot.getUser(USER_NAME_NEW).getActive(), is(false)); - } else { - try { - arangoDB.updateUser(USER_NAME_NEW, new UserUpdateOptions().active(false)); - fail(details); - } catch (final ArangoDBException e) { - } - assertThat(details, arangoDBRoot.getUser(USER_NAME_NEW).getActive(), is(true)); - } - } finally { - try { - arangoDBRoot.deleteUser(USER_NAME_NEW); - } catch (final ArangoDBException e) { - } - } - } - - @Test - public void grantUserDBAccess() { - try { - arangoDBRoot.createUser(USER_NAME_NEW, ""); - if (Permissions.RW.equals(param.systemPermission)) { - try { - arangoDB.db().grantAccess(USER_NAME_NEW); - } catch (final ArangoDBException e) { - fail(details); - } - } else { - try { - arangoDB.db().grantAccess(USER_NAME_NEW); - fail(details); - } catch (final ArangoDBException e) { - } - } - } finally { - try { - arangoDBRoot.deleteUser(USER_NAME_NEW); - } catch (final ArangoDBException e) { - } - } - } - - @Test - public void resetUserDBAccess() { - try { - arangoDBRoot.createUser(USER_NAME_NEW, ""); - arangoDBRoot.db().grantAccess(USER_NAME_NEW); - if (Permissions.RW.equals(param.systemPermission)) { - try { - arangoDB.db(DB_NAME).resetAccess(USER_NAME_NEW); - } catch (final ArangoDBException e) { - fail(details); - } - } else { - try { - arangoDB.db(DB_NAME).resetAccess(USER_NAME_NEW); - fail(details); - } catch (final ArangoDBException e) { - } - } - } finally { - try { - arangoDBRoot.deleteUser(USER_NAME_NEW); - } catch (final ArangoDBException e) { - } - } - } - - @Test - public void grantUserCollcetionAccess() { - try { - arangoDBRoot.createUser(USER_NAME_NEW, ""); - if (Permissions.RW.equals(param.systemPermission)) { - try { - arangoDB.db(DB_NAME).collection(COLLECTION_NAME).grantAccess(USER_NAME_NEW, Permissions.RW); - } catch (final ArangoDBException e) { - fail(details); - } - } else { - try { - arangoDB.db(DB_NAME).collection(COLLECTION_NAME).grantAccess(USER_NAME_NEW, Permissions.RW); - fail(details); - } catch (final ArangoDBException e) { - } - } - } finally { - try { - arangoDBRoot.deleteUser(USER_NAME_NEW); - } catch (final ArangoDBException e) { - } - } - } - - @Test - public void resetUserCollectionAccess() { - try { - arangoDBRoot.createUser(USER_NAME_NEW, ""); - arangoDBRoot.db().grantAccess(USER_NAME_NEW); - if (Permissions.RW.equals(param.systemPermission)) { - try { - arangoDB.db(DB_NAME).collection(COLLECTION_NAME).resetAccess(USER_NAME_NEW); - } catch (final ArangoDBException e) { - fail(details); - } - } else { - try { - arangoDB.db(DB_NAME).collection(COLLECTION_NAME).resetAccess(USER_NAME_NEW); - fail(details); - } catch (final ArangoDBException e) { - } - } - } finally { - try { - arangoDBRoot.deleteUser(USER_NAME_NEW); - } catch (final ArangoDBException e) { - } - } - } - - @Test - public void updateUserDefaultDatabaseAccess() { - try { - arangoDBRoot.createUser(USER_NAME_NEW, ""); - arangoDBRoot.db().grantAccess(USER_NAME_NEW); - if (Permissions.RW.equals(param.systemPermission)) { - try { - arangoDB.grantDefaultDatabaseAccess(USER_NAME_NEW, Permissions.RW); - } catch (final ArangoDBException e) { - fail(details); - } - } else { - try { - arangoDB.grantDefaultDatabaseAccess(USER_NAME_NEW, Permissions.RW); - fail(details); - } catch (final ArangoDBException e) { - } - } - } finally { - try { - arangoDBRoot.deleteUser(USER_NAME_NEW); - } catch (final ArangoDBException e) { - } - } - } - - @Test - public void updateUserDefaultCollectionAccess() { - try { - arangoDBRoot.createUser(USER_NAME_NEW, ""); - arangoDBRoot.db().grantAccess(USER_NAME_NEW); - if (Permissions.RW.equals(param.systemPermission)) { - try { - arangoDB.grantDefaultCollectionAccess(USER_NAME_NEW, Permissions.RW); - } catch (final ArangoDBException e) { - fail(details); - } - } else { - try { - arangoDB.grantDefaultCollectionAccess(USER_NAME_NEW, Permissions.RW); - fail(details); - } catch (final ArangoDBException e) { - } - } - } finally { - try { - arangoDBRoot.deleteUser(USER_NAME_NEW); - } catch (final ArangoDBException e) { - } - } - } - - @Test - public void createCollection() { - try { - if (Permissions.RW.equals(param.dbPermission)) { - try { - arangoDB.db(DB_NAME).createCollection(COLLECTION_NAME_NEW); - } catch (final ArangoDBException e) { - fail(details); - } - assertThat(details, arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME_NEW).getInfo(), - is(notNullValue())); - } else { - try { - arangoDB.db(DB_NAME).createCollection(COLLECTION_NAME_NEW); - fail(details); - } catch (final ArangoDBException e) { - } - try { - arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME_NEW).getInfo(); - fail(details); - } catch (final ArangoDBException e) { - } - } - } finally { - try { - arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME_NEW).drop(); - } catch (final ArangoDBException e) { - } - } - } - - @Test - public void dropCollection() { - try { - arangoDBRoot.db(DB_NAME).createCollection(COLLECTION_NAME_NEW); - arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME_NEW).grantAccess(USER_NAME, param.colPermission); - if (Permissions.RW.equals(param.dbPermission) && Permissions.RW.equals(param.colPermission)) { - try { - arangoDB.db(DB_NAME).collection(COLLECTION_NAME_NEW).drop(); - } catch (final ArangoDBException e) { - fail(details); - } - try { - arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME_NEW).getInfo(); - fail(details); - } catch (final ArangoDBException e) { - } - } else { - try { - arangoDB.db(DB_NAME).collection(COLLECTION_NAME_NEW).drop(); - fail(details); - } catch (final ArangoDBException e) { - } - assertThat(details, arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME_NEW).getInfo(), - is(notNullValue())); - } - } finally { - try { - arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME_NEW).drop(); - } catch (final ArangoDBException e) { - } - } - } - - @Test - public void seeCollection() { - if ((Permissions.RW.equals(param.dbPermission) || Permissions.RO.equals(param.dbPermission)) - && (Permissions.RW.equals(param.colPermission) || Permissions.RO.equals(param.colPermission))) { - try { - final Collection collections = arangoDB.db(DB_NAME).getCollections(); - boolean found = false; - for (final CollectionEntity collection : collections) { - if (collection.getName().equals(COLLECTION_NAME)) { - found = true; - break; - } - } - assertThat(details, found, is(true)); - } catch (final ArangoDBException e) { - fail(details); - } - } else if (Permissions.RW.equals(param.dbPermission) || Permissions.RO.equals(param.dbPermission)) { - final Collection collections = arangoDB.db(DB_NAME).getCollections(); - boolean found = false; - for (final CollectionEntity collection : collections) { - if (collection.getName().equals(COLLECTION_NAME)) { - found = true; - break; - } - } - assertThat(details, found, is(false)); - } - } - - @Test - public void readCollectionInfo() { - if ((Permissions.RW.equals(param.dbPermission) || Permissions.RO.equals(param.dbPermission)) - && (Permissions.RW.equals(param.colPermission) || Permissions.RO.equals(param.colPermission))) { - try { - assertThat(details, arangoDB.db(DB_NAME).collection(COLLECTION_NAME).getInfo(), is(notNullValue())); - } catch (final ArangoDBException e) { - fail(details); - } - } else { - try { - arangoDB.db(DB_NAME).collection(COLLECTION_NAME).getInfo(); - fail(details); - } catch (final ArangoDBException e) { - } - } - } - - @Test - public void readCollectionProperties() { - if ((Permissions.RW.equals(param.dbPermission) || Permissions.RO.equals(param.dbPermission)) - && (Permissions.RW.equals(param.colPermission) || Permissions.RO.equals(param.colPermission))) { - try { - assertThat(details, arangoDB.db(DB_NAME).collection(COLLECTION_NAME).getProperties(), - is(notNullValue())); - } catch (final ArangoDBException e) { - fail(details); - } - } else { - try { - arangoDB.db(DB_NAME).collection(COLLECTION_NAME).getProperties(); - fail(details); - } catch (final ArangoDBException e) { - } - } - } - - @Test - public void writeCollectionProperties() { - if (Permissions.RW.equals(param.dbPermission) && Permissions.RW.equals(param.colPermission)) { - try { - assertThat(details, arangoDB.db(DB_NAME).collection(COLLECTION_NAME) - .changeProperties(new CollectionPropertiesOptions().waitForSync(true)), - is(notNullValue())); - } catch (final ArangoDBException e) { - fail(details); - } - assertThat(details, arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME).getProperties().getWaitForSync(), - is(true)); - } else { - try { - arangoDB.db(DB_NAME).collection(COLLECTION_NAME) - .changeProperties(new CollectionPropertiesOptions().waitForSync(true)); - fail(details); - } catch (final ArangoDBException e) { - } - assertThat(details, arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME).getProperties().getWaitForSync(), - is(false)); - } - } - - @Test - public void readCollectionIndexes() { - if ((Permissions.RW.equals(param.dbPermission) || Permissions.RO.equals(param.dbPermission)) - && (Permissions.RW.equals(param.colPermission) || Permissions.RO.equals(param.colPermission))) { - try { - assertThat(details, arangoDB.db(DB_NAME).collection(COLLECTION_NAME).getIndexes(), is(notNullValue())); - } catch (final ArangoDBException e) { - fail(details); - } - } else { - try { - arangoDB.db(DB_NAME).collection(COLLECTION_NAME).getIndexes(); - fail(details); - } catch (final ArangoDBException e) { - } - } - } - - @Test - public void createCollectionIndex() { - String id = null; - try { - if (Permissions.RW.equals(param.dbPermission) && Permissions.RW.equals(param.colPermission)) { - try { - final IndexEntity createHashIndex = arangoDB.db(DB_NAME).collection(COLLECTION_NAME) - .ensureHashIndex(Arrays.asList("a"), new HashIndexOptions()); - assertThat(details, createHashIndex, is(notNullValue())); - id = createHashIndex.getId(); - } catch (final ArangoDBException e) { - fail(details); - } - assertThat(details, arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME).getIndexes().size(), is(2)); - } else { - try { - final IndexEntity createHashIndex = arangoDB.db(DB_NAME).collection(COLLECTION_NAME) - .ensureHashIndex(Arrays.asList("a"), new HashIndexOptions()); - id = createHashIndex.getId(); - fail(details); - } catch (final ArangoDBException e) { - } - assertThat(details, arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME).getIndexes().size(), is(1)); - } - } finally { - if (id != null) { - arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME).deleteIndex(id); - } - } - } - - @Test - public void dropCollectionIndex() { - final String id = arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME) - .ensureHashIndex(Arrays.asList("a"), new HashIndexOptions()).getId(); - try { - if (Permissions.RW.equals(param.dbPermission) && Permissions.RW.equals(param.colPermission)) { - try { - arangoDB.db(DB_NAME).collection(COLLECTION_NAME).deleteIndex(id); - } catch (final ArangoDBException e) { - fail(details); - } - assertThat(details, arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME).getIndexes().size(), is(1)); - } else { - try { - arangoDB.db(DB_NAME).collection(COLLECTION_NAME).deleteIndex(id); - fail(details); - } catch (final ArangoDBException e) { - } - assertThat(details, arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME).getIndexes().size(), is(2)); - } - } finally { - if (id != null) { - try { - arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME).deleteIndex(id); - } catch (final ArangoDBException e) { - } - } - } - } - - @Test - public void truncateCollection() { - try { - arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME).insertDocument(new BaseDocument("123")); - if ((Permissions.RW.equals(param.dbPermission) || Permissions.RO.equals(param.dbPermission)) - && Permissions.RW.equals(param.colPermission)) { - try { - arangoDB.db(DB_NAME).collection(COLLECTION_NAME).truncate(); - } catch (final ArangoDBException e) { - fail(details); - } - assertThat(details, arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME).documentExists("123"), - is(false)); - } else { - try { - arangoDB.db(DB_NAME).collection(COLLECTION_NAME).truncate(); - fail(details); - } catch (final ArangoDBException e) { - } - assertThat(details, arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME).documentExists("123"), - is(true)); - } - } finally { - try { - arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME).truncate(); - } catch (final ArangoDBException e) { - } - } - } - - @Test - public void readDocumentByKey() { - try { - arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME).insertDocument(new BaseDocument("123")); - if ((Permissions.RW.equals(param.dbPermission) || Permissions.RO.equals(param.dbPermission)) - && (Permissions.RW.equals(param.colPermission) || Permissions.RO.equals(param.colPermission))) { - assertThat(details, - arangoDB.db(DB_NAME).collection(COLLECTION_NAME).getDocument("123", BaseDocument.class), - is(notNullValue())); - } else { - assertThat(details, - arangoDB.db(DB_NAME).collection(COLLECTION_NAME).getDocument("123", BaseDocument.class), - is(nullValue())); - } - } finally { - try { - arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME).deleteDocument("123"); - } catch (final ArangoDBException e) { - } - } - } - - @Test - public void readDocumentByAql() { - try { - arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME).insertDocument(new BaseDocument("123")); - if ((Permissions.RW.equals(param.dbPermission) || Permissions.RO.equals(param.dbPermission)) - && (Permissions.RW.equals(param.colPermission) || Permissions.RO.equals(param.colPermission))) { - assertThat(details, - arangoDB.db(DB_NAME).query("FOR i IN @@col RETURN i", - new MapBuilder().put("@col", COLLECTION_NAME).get(), new AqlQueryOptions(), BaseDocument.class) - .asListRemaining().size(), - is(1)); - } else { - assertThat(details, - arangoDB.db(DB_NAME).collection(COLLECTION_NAME).getDocument("123", BaseDocument.class), - is(nullValue())); - } - } finally { - try { - arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME).deleteDocument("123"); - } catch (final ArangoDBException e) { - } - } - } - - @Test - public void insertDocument() { - try { - if ((Permissions.RW.equals(param.dbPermission) || Permissions.RO.equals(param.dbPermission)) - && Permissions.RW.equals(param.colPermission)) { - try { - arangoDB.db(DB_NAME).collection(COLLECTION_NAME).insertDocument(new BaseDocument("123")); - } catch (final ArangoDBException e) { - fail(details); - } - assertThat(details, arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME).documentExists("123"), - is(true)); - } else { - try { - arangoDB.db(DB_NAME).collection(COLLECTION_NAME).insertDocument(new BaseDocument("123")); - fail(details); - } catch (final ArangoDBException e) { - } - assertThat(details, arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME).documentExists("123"), - is(false)); - } - } finally { - try { - arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME).deleteDocument("123"); - } catch (final ArangoDBException e) { - } - } - } - - @Test - public void updateDocumentByKey() { - try { - arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME).insertDocument(new BaseDocument("123")); - if ((Permissions.RW.equals(param.dbPermission) || Permissions.RO.equals(param.dbPermission)) - && Permissions.RW.equals(param.colPermission)) { - try { - arangoDB.db(DB_NAME).collection(COLLECTION_NAME).updateDocument("123", - new BaseDocument(new MapBuilder().put("test", "test").get())); - } catch (final ArangoDBException e) { - fail(details); - } - assertThat(details, arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME) - .getDocument("123", BaseDocument.class).getAttribute("test").toString(), - is("test")); - } else { - try { - arangoDB.db(DB_NAME).collection(COLLECTION_NAME).updateDocument("123", - new BaseDocument(new MapBuilder().put("test", "test").get())); - fail(details); - } catch (final ArangoDBException e) { - } - assertThat(details, arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME) - .getDocument("123", BaseDocument.class).getAttribute("test"), - is(nullValue())); - } - } finally { - try { - arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME).deleteDocument("123"); - } catch (final ArangoDBException e) { - } - } - } - - @Test - public void updateDocumentByAql() { - try { - arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME).insertDocument(new BaseDocument("123")); - if ((Permissions.RW.equals(param.dbPermission) || Permissions.RO.equals(param.dbPermission)) - && Permissions.RW.equals(param.colPermission)) { - try { - arangoDB.db(DB_NAME).query("FOR i IN @@col UPDATE i WITH @newDoc IN @@col", - new MapBuilder().put("@col", COLLECTION_NAME) - .put("newDoc", new BaseDocument(new MapBuilder().put("test", "test").get())).get(), - new AqlQueryOptions(), Void.class); - } catch (final ArangoDBException e) { - fail(details); - } - assertThat(details, arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME) - .getDocument("123", BaseDocument.class).getAttribute("test").toString(), - is("test")); - } else { - try { - arangoDB.db(DB_NAME).query("FOR i IN @@col UPDATE i WITH @newDoc IN @@col", - new MapBuilder().put("@col", COLLECTION_NAME) - .put("newDoc", new BaseDocument(new MapBuilder().put("test", "test").get())).get(), - new AqlQueryOptions(), Void.class); - fail(details); - } catch (final ArangoDBException e) { - } - assertThat(details, arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME) - .getDocument("123", BaseDocument.class).getAttribute("test"), - is(nullValue())); - } - } finally { - try { - arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME).deleteDocument("123"); - } catch (final ArangoDBException e) { - } - } - } - - @Test - public void deleteDocumentByKey() { - try { - arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME).insertDocument(new BaseDocument("123")); - if ((Permissions.RW.equals(param.dbPermission) || Permissions.RO.equals(param.dbPermission)) - && Permissions.RW.equals(param.colPermission)) { - try { - arangoDB.db(DB_NAME).collection(COLLECTION_NAME).deleteDocument("123"); - } catch (final ArangoDBException e) { - fail(details); - } - assertThat(details, arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME).documentExists("123"), - is(false)); - } else { - try { - arangoDB.db(DB_NAME).collection(COLLECTION_NAME).deleteDocument("123"); - fail(details); - } catch (final ArangoDBException e) { - } - assertThat(details, arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME).documentExists("123"), - is(true)); - } - } finally { - try { - arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME).deleteDocument("123"); - } catch (final ArangoDBException e) { - } - } - } - - @Test - public void deleteDocumentByAql() { - try { - arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME).insertDocument(new BaseDocument("123")); - if ((Permissions.RW.equals(param.dbPermission) || Permissions.RO.equals(param.dbPermission)) - && Permissions.RW.equals(param.colPermission)) { - try { - arangoDB.db(DB_NAME).query("REMOVE @key IN @@col", - new MapBuilder().put("key", "123").put("@col", COLLECTION_NAME).get(), new AqlQueryOptions(), - Void.class); - } catch (final ArangoDBException e) { - fail(details); - } - assertThat(details, arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME).documentExists("123"), - is(false)); - } else { - try { - arangoDB.db(DB_NAME).query("REMOVE @key IN @@col", - new MapBuilder().put("key", "123").put("@col", COLLECTION_NAME).get(), new AqlQueryOptions(), - Void.class); - fail(details); - } catch (final ArangoDBException e) { - } - assertThat(details, arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME).documentExists("123"), - is(true)); - } - } finally { - try { - arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME).deleteDocument("123"); - } catch (final ArangoDBException e) { - } - } - } + private static final String DB_NAME = "AuthUnitTestDB"; + private static final String DB_NAME_NEW = DB_NAME + "new"; + private static final String COLLECTION_NAME = "AuthUnitTestCollection"; + private static final String COLLECTION_NAME_NEW = COLLECTION_NAME + "new"; + private static final String USER_NAME = "AuthUnitTestUser"; + private static final String USER_NAME_NEW = USER_NAME + "new"; + + public static class UserAuthParam { + Protocol protocol; + Permissions systemPermission; + Permissions dbPermission; + Permissions colPermission; + + public UserAuthParam(final Protocol protocol, final Permissions systemPermission, + final Permissions dbPermission, final Permissions colPermission) { + super(); + this.protocol = protocol; + this.systemPermission = systemPermission; + this.dbPermission = dbPermission; + this.colPermission = colPermission; + } + + } + + @Parameters + public static Collection params() { + final Collection params = new ArrayList(); + final Permissions[] permissions = new Permissions[]{Permissions.RW, Permissions.RO, Permissions.NONE}; + for (final Protocol protocol : new Protocol[]{Protocol.VST, Protocol.HTTP_JSON, Protocol.HTTP_VPACK}) { + for (final Permissions systemPermission : permissions) { + for (final Permissions dbPermission : permissions) { + for (final Permissions colPermission : permissions) { + params.add(new UserAuthParam(protocol, systemPermission, dbPermission, colPermission)); + } + } + } + } + return params; + } + + private static ArangoDB arangoDB; + private static ArangoDB arangoDBRoot; + private final UserAuthParam param; + private final String details; + + public UserAuthTest(final UserAuthParam param) { + super(); + this.param = param; + if (arangoDB != null || arangoDBRoot != null) { + shutdown(); + } + arangoDBRoot = new ArangoDB.Builder().useProtocol(param.protocol).build(); + arangoDBRoot.createUser(USER_NAME, ""); + arangoDB = new ArangoDB.Builder().useProtocol(param.protocol).user(USER_NAME).build(); + arangoDBRoot.createDatabase(DB_NAME); + arangoDBRoot.db(DB_NAME).createCollection(COLLECTION_NAME); + arangoDBRoot.db().grantAccess(USER_NAME, param.systemPermission); + arangoDBRoot.db(DB_NAME).grantAccess(USER_NAME, param.dbPermission); + arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME).grantAccess(USER_NAME, param.colPermission); + details = new StringBuffer().append(param.protocol).append("_").append(param.systemPermission).append("_") + .append(param.dbPermission).append("_").append(param.colPermission).toString(); + } + + @AfterClass + public static void shutdown() { + arangoDBRoot.deleteUser(USER_NAME); + if (arangoDBRoot.db(DB_NAME).exists()) + arangoDBRoot.db(DB_NAME).drop(); + if (arangoDB != null) { + arangoDB.shutdown(); + } + arangoDBRoot.shutdown(); + arangoDB = null; + arangoDBRoot = null; + } + + @Test + public void createDatabase() { + try { + if (Permissions.RW.equals(param.systemPermission)) { + try { + assertThat(details, arangoDB.createDatabase(DB_NAME_NEW), is(true)); + } catch (final ArangoDBException e) { + fail(details); + } + assertThat(details, arangoDBRoot.getDatabases(), hasItem(DB_NAME_NEW)); + } else { + try { + arangoDB.createDatabase(DB_NAME_NEW); + fail(details); + } catch (final ArangoDBException e) { + } + assertThat(details, arangoDBRoot.getDatabases(), not(hasItem(DB_NAME_NEW))); + } + } finally { + try { + arangoDBRoot.db(DB_NAME_NEW).drop(); + } catch (final ArangoDBException e) { + } + } + } + + @Test + public void dropDatabase() { + try { + arangoDBRoot.createDatabase(DB_NAME_NEW); + if (Permissions.RW.equals(param.systemPermission)) { + try { + assertThat(details, arangoDB.db(DB_NAME).drop(), is(true)); + } catch (final ArangoDBException e) { + fail(details); + } + assertThat(details, arangoDBRoot.getDatabases(), not(hasItem(DB_NAME))); + } else { + try { + arangoDB.db(DB_NAME).drop(); + fail(details); + } catch (final ArangoDBException e) { + } + assertThat(details, arangoDBRoot.getDatabases(), hasItem(DB_NAME)); + } + } finally { + try { + arangoDBRoot.db(DB_NAME_NEW).drop(); + } catch (final ArangoDBException e) { + } + } + } + + @Test + public void createUser() { + try { + if (Permissions.RW.equals(param.systemPermission)) { + try { + arangoDB.createUser(USER_NAME_NEW, ""); + } catch (final ArangoDBException e) { + fail(details); + } + assertThat(details, arangoDBRoot.getUsers(), is(notNullValue())); + } else { + try { + arangoDB.createUser(USER_NAME_NEW, ""); + fail(details); + } catch (final ArangoDBException e) { + } + try { + arangoDBRoot.getUser(USER_NAME_NEW); + fail(details); + } catch (final ArangoDBException e) { + } + } + } finally { + try { + arangoDBRoot.deleteUser(USER_NAME_NEW); + } catch (final ArangoDBException e) { + } + } + } + + @Test + public void deleteUser() { + try { + arangoDBRoot.createUser(USER_NAME_NEW, ""); + if (Permissions.RW.equals(param.systemPermission)) { + try { + arangoDB.deleteUser(USER_NAME_NEW); + } catch (final ArangoDBException e) { + fail(details); + } + try { + arangoDBRoot.getUser(USER_NAME_NEW); + fail(details); + } catch (final ArangoDBException e) { + } + } else { + try { + arangoDB.deleteUser(USER_NAME_NEW); + fail(details); + } catch (final ArangoDBException e) { + } + assertThat(details, arangoDBRoot.getUsers(), is(notNullValue())); + } + } finally { + try { + arangoDBRoot.deleteUser(USER_NAME_NEW); + } catch (final ArangoDBException e) { + } + } + } + + @Test + public void updateUser() { + try { + arangoDBRoot.createUser(USER_NAME_NEW, ""); + if (Permissions.RW.equals(param.systemPermission)) { + try { + arangoDB.updateUser(USER_NAME_NEW, new UserUpdateOptions().active(false)); + } catch (final ArangoDBException e) { + fail(details); + } + assertThat(details, arangoDBRoot.getUser(USER_NAME_NEW).getActive(), is(false)); + } else { + try { + arangoDB.updateUser(USER_NAME_NEW, new UserUpdateOptions().active(false)); + fail(details); + } catch (final ArangoDBException e) { + } + assertThat(details, arangoDBRoot.getUser(USER_NAME_NEW).getActive(), is(true)); + } + } finally { + try { + arangoDBRoot.deleteUser(USER_NAME_NEW); + } catch (final ArangoDBException e) { + } + } + } + + @Test + public void grantUserDBAccess() { + try { + arangoDBRoot.createUser(USER_NAME_NEW, ""); + if (Permissions.RW.equals(param.systemPermission)) { + try { + arangoDB.db().grantAccess(USER_NAME_NEW); + } catch (final ArangoDBException e) { + fail(details); + } + } else { + try { + arangoDB.db().grantAccess(USER_NAME_NEW); + fail(details); + } catch (final ArangoDBException e) { + } + } + } finally { + try { + arangoDBRoot.deleteUser(USER_NAME_NEW); + } catch (final ArangoDBException e) { + } + } + } + + @Test + public void resetUserDBAccess() { + try { + arangoDBRoot.createUser(USER_NAME_NEW, ""); + arangoDBRoot.db().grantAccess(USER_NAME_NEW); + if (Permissions.RW.equals(param.systemPermission)) { + try { + arangoDB.db(DB_NAME).resetAccess(USER_NAME_NEW); + } catch (final ArangoDBException e) { + fail(details); + } + } else { + try { + arangoDB.db(DB_NAME).resetAccess(USER_NAME_NEW); + fail(details); + } catch (final ArangoDBException e) { + } + } + } finally { + try { + arangoDBRoot.deleteUser(USER_NAME_NEW); + } catch (final ArangoDBException e) { + } + } + } + + @Test + public void grantUserCollcetionAccess() { + try { + arangoDBRoot.createUser(USER_NAME_NEW, ""); + if (Permissions.RW.equals(param.systemPermission)) { + try { + arangoDB.db(DB_NAME).collection(COLLECTION_NAME).grantAccess(USER_NAME_NEW, Permissions.RW); + } catch (final ArangoDBException e) { + fail(details); + } + } else { + try { + arangoDB.db(DB_NAME).collection(COLLECTION_NAME).grantAccess(USER_NAME_NEW, Permissions.RW); + fail(details); + } catch (final ArangoDBException e) { + } + } + } finally { + try { + arangoDBRoot.deleteUser(USER_NAME_NEW); + } catch (final ArangoDBException e) { + } + } + } + + @Test + public void resetUserCollectionAccess() { + try { + arangoDBRoot.createUser(USER_NAME_NEW, ""); + arangoDBRoot.db().grantAccess(USER_NAME_NEW); + if (Permissions.RW.equals(param.systemPermission)) { + try { + arangoDB.db(DB_NAME).collection(COLLECTION_NAME).resetAccess(USER_NAME_NEW); + } catch (final ArangoDBException e) { + fail(details); + } + } else { + try { + arangoDB.db(DB_NAME).collection(COLLECTION_NAME).resetAccess(USER_NAME_NEW); + fail(details); + } catch (final ArangoDBException e) { + } + } + } finally { + try { + arangoDBRoot.deleteUser(USER_NAME_NEW); + } catch (final ArangoDBException e) { + } + } + } + + @Test + public void updateUserDefaultDatabaseAccess() { + try { + arangoDBRoot.createUser(USER_NAME_NEW, ""); + arangoDBRoot.db().grantAccess(USER_NAME_NEW); + if (Permissions.RW.equals(param.systemPermission)) { + try { + arangoDB.grantDefaultDatabaseAccess(USER_NAME_NEW, Permissions.RW); + } catch (final ArangoDBException e) { + fail(details); + } + } else { + try { + arangoDB.grantDefaultDatabaseAccess(USER_NAME_NEW, Permissions.RW); + fail(details); + } catch (final ArangoDBException e) { + } + } + } finally { + try { + arangoDBRoot.deleteUser(USER_NAME_NEW); + } catch (final ArangoDBException e) { + } + } + } + + @Test + public void updateUserDefaultCollectionAccess() { + try { + arangoDBRoot.createUser(USER_NAME_NEW, ""); + arangoDBRoot.db().grantAccess(USER_NAME_NEW); + if (Permissions.RW.equals(param.systemPermission)) { + try { + arangoDB.grantDefaultCollectionAccess(USER_NAME_NEW, Permissions.RW); + } catch (final ArangoDBException e) { + fail(details); + } + } else { + try { + arangoDB.grantDefaultCollectionAccess(USER_NAME_NEW, Permissions.RW); + fail(details); + } catch (final ArangoDBException e) { + } + } + } finally { + try { + arangoDBRoot.deleteUser(USER_NAME_NEW); + } catch (final ArangoDBException e) { + } + } + } + + @Test + public void createCollection() { + try { + if (Permissions.RW.equals(param.dbPermission)) { + try { + arangoDB.db(DB_NAME).createCollection(COLLECTION_NAME_NEW); + } catch (final ArangoDBException e) { + fail(details); + } + assertThat(details, arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME_NEW).getInfo(), + is(notNullValue())); + } else { + try { + arangoDB.db(DB_NAME).createCollection(COLLECTION_NAME_NEW); + fail(details); + } catch (final ArangoDBException e) { + } + try { + arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME_NEW).getInfo(); + fail(details); + } catch (final ArangoDBException e) { + } + } + } finally { + try { + arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME_NEW).drop(); + } catch (final ArangoDBException e) { + } + } + } + + @Test + public void dropCollection() { + try { + arangoDBRoot.db(DB_NAME).createCollection(COLLECTION_NAME_NEW); + arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME_NEW).grantAccess(USER_NAME, param.colPermission); + if (Permissions.RW.equals(param.dbPermission) && Permissions.RW.equals(param.colPermission)) { + try { + arangoDB.db(DB_NAME).collection(COLLECTION_NAME_NEW).drop(); + } catch (final ArangoDBException e) { + fail(details); + } + try { + arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME_NEW).getInfo(); + fail(details); + } catch (final ArangoDBException e) { + } + } else { + try { + arangoDB.db(DB_NAME).collection(COLLECTION_NAME_NEW).drop(); + fail(details); + } catch (final ArangoDBException e) { + } + assertThat(details, arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME_NEW).getInfo(), + is(notNullValue())); + } + } finally { + try { + arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME_NEW).drop(); + } catch (final ArangoDBException e) { + } + } + } + + @Test + public void seeCollection() { + if ((Permissions.RW.equals(param.dbPermission) || Permissions.RO.equals(param.dbPermission)) + && (Permissions.RW.equals(param.colPermission) || Permissions.RO.equals(param.colPermission))) { + try { + final Collection collections = arangoDB.db(DB_NAME).getCollections(); + boolean found = false; + for (final CollectionEntity collection : collections) { + if (collection.getName().equals(COLLECTION_NAME)) { + found = true; + break; + } + } + assertThat(details, found, is(true)); + } catch (final ArangoDBException e) { + fail(details); + } + } else if (Permissions.RW.equals(param.dbPermission) || Permissions.RO.equals(param.dbPermission)) { + final Collection collections = arangoDB.db(DB_NAME).getCollections(); + boolean found = false; + for (final CollectionEntity collection : collections) { + if (collection.getName().equals(COLLECTION_NAME)) { + found = true; + break; + } + } + assertThat(details, found, is(false)); + } + } + + @Test + public void readCollectionInfo() { + if ((Permissions.RW.equals(param.dbPermission) || Permissions.RO.equals(param.dbPermission)) + && (Permissions.RW.equals(param.colPermission) || Permissions.RO.equals(param.colPermission))) { + try { + assertThat(details, arangoDB.db(DB_NAME).collection(COLLECTION_NAME).getInfo(), is(notNullValue())); + } catch (final ArangoDBException e) { + fail(details); + } + } else { + try { + arangoDB.db(DB_NAME).collection(COLLECTION_NAME).getInfo(); + fail(details); + } catch (final ArangoDBException e) { + } + } + } + + @Test + public void readCollectionProperties() { + if ((Permissions.RW.equals(param.dbPermission) || Permissions.RO.equals(param.dbPermission)) + && (Permissions.RW.equals(param.colPermission) || Permissions.RO.equals(param.colPermission))) { + try { + assertThat(details, arangoDB.db(DB_NAME).collection(COLLECTION_NAME).getProperties(), + is(notNullValue())); + } catch (final ArangoDBException e) { + fail(details); + } + } else { + try { + arangoDB.db(DB_NAME).collection(COLLECTION_NAME).getProperties(); + fail(details); + } catch (final ArangoDBException e) { + } + } + } + + @Test + public void writeCollectionProperties() { + if (Permissions.RW.equals(param.dbPermission) && Permissions.RW.equals(param.colPermission)) { + try { + assertThat(details, arangoDB.db(DB_NAME).collection(COLLECTION_NAME) + .changeProperties(new CollectionPropertiesOptions().waitForSync(true)), + is(notNullValue())); + } catch (final ArangoDBException e) { + fail(details); + } + assertThat(details, arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME).getProperties().getWaitForSync(), + is(true)); + } else { + try { + arangoDB.db(DB_NAME).collection(COLLECTION_NAME) + .changeProperties(new CollectionPropertiesOptions().waitForSync(true)); + fail(details); + } catch (final ArangoDBException e) { + } + assertThat(details, arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME).getProperties().getWaitForSync(), + is(false)); + } + } + + @Test + public void readCollectionIndexes() { + if ((Permissions.RW.equals(param.dbPermission) || Permissions.RO.equals(param.dbPermission)) + && (Permissions.RW.equals(param.colPermission) || Permissions.RO.equals(param.colPermission))) { + try { + assertThat(details, arangoDB.db(DB_NAME).collection(COLLECTION_NAME).getIndexes(), is(notNullValue())); + } catch (final ArangoDBException e) { + fail(details); + } + } else { + try { + arangoDB.db(DB_NAME).collection(COLLECTION_NAME).getIndexes(); + fail(details); + } catch (final ArangoDBException e) { + } + } + } + + @Test + public void createCollectionIndex() { + String id = null; + try { + if (Permissions.RW.equals(param.dbPermission) && Permissions.RW.equals(param.colPermission)) { + try { + final IndexEntity createHashIndex = arangoDB.db(DB_NAME).collection(COLLECTION_NAME) + .ensureHashIndex(Arrays.asList("a"), new HashIndexOptions()); + assertThat(details, createHashIndex, is(notNullValue())); + id = createHashIndex.getId(); + } catch (final ArangoDBException e) { + fail(details); + } + assertThat(details, arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME).getIndexes().size(), is(2)); + } else { + try { + final IndexEntity createHashIndex = arangoDB.db(DB_NAME).collection(COLLECTION_NAME) + .ensureHashIndex(Arrays.asList("a"), new HashIndexOptions()); + id = createHashIndex.getId(); + fail(details); + } catch (final ArangoDBException e) { + } + assertThat(details, arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME).getIndexes().size(), is(1)); + } + } finally { + if (id != null) { + arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME).deleteIndex(id); + } + } + } + + @Test + public void dropCollectionIndex() { + final String id = arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME) + .ensureHashIndex(Arrays.asList("a"), new HashIndexOptions()).getId(); + try { + if (Permissions.RW.equals(param.dbPermission) && Permissions.RW.equals(param.colPermission)) { + try { + arangoDB.db(DB_NAME).collection(COLLECTION_NAME).deleteIndex(id); + } catch (final ArangoDBException e) { + fail(details); + } + assertThat(details, arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME).getIndexes().size(), is(1)); + } else { + try { + arangoDB.db(DB_NAME).collection(COLLECTION_NAME).deleteIndex(id); + fail(details); + } catch (final ArangoDBException e) { + } + assertThat(details, arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME).getIndexes().size(), is(2)); + } + } finally { + if (id != null) { + try { + arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME).deleteIndex(id); + } catch (final ArangoDBException e) { + } + } + } + } + + @Test + public void truncateCollection() { + try { + arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME).insertDocument(new BaseDocument("123")); + if ((Permissions.RW.equals(param.dbPermission) || Permissions.RO.equals(param.dbPermission)) + && Permissions.RW.equals(param.colPermission)) { + try { + arangoDB.db(DB_NAME).collection(COLLECTION_NAME).truncate(); + } catch (final ArangoDBException e) { + fail(details); + } + assertThat(details, arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME).documentExists("123"), + is(false)); + } else { + try { + arangoDB.db(DB_NAME).collection(COLLECTION_NAME).truncate(); + fail(details); + } catch (final ArangoDBException e) { + } + assertThat(details, arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME).documentExists("123"), + is(true)); + } + } finally { + try { + arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME).truncate(); + } catch (final ArangoDBException e) { + } + } + } + + @Test + public void readDocumentByKey() { + try { + arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME).insertDocument(new BaseDocument("123")); + if ((Permissions.RW.equals(param.dbPermission) || Permissions.RO.equals(param.dbPermission)) + && (Permissions.RW.equals(param.colPermission) || Permissions.RO.equals(param.colPermission))) { + assertThat(details, + arangoDB.db(DB_NAME).collection(COLLECTION_NAME).getDocument("123", BaseDocument.class), + is(notNullValue())); + } else { + assertThat(details, + arangoDB.db(DB_NAME).collection(COLLECTION_NAME).getDocument("123", BaseDocument.class), + is(nullValue())); + } + } finally { + try { + arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME).deleteDocument("123"); + } catch (final ArangoDBException e) { + } + } + } + + @Test + public void readDocumentByAql() { + try { + arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME).insertDocument(new BaseDocument("123")); + if ((Permissions.RW.equals(param.dbPermission) || Permissions.RO.equals(param.dbPermission)) + && (Permissions.RW.equals(param.colPermission) || Permissions.RO.equals(param.colPermission))) { + assertThat(details, + arangoDB.db(DB_NAME).query("FOR i IN @@col RETURN i", + new MapBuilder().put("@col", COLLECTION_NAME).get(), new AqlQueryOptions(), BaseDocument.class) + .asListRemaining().size(), + is(1)); + } else { + assertThat(details, + arangoDB.db(DB_NAME).collection(COLLECTION_NAME).getDocument("123", BaseDocument.class), + is(nullValue())); + } + } finally { + try { + arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME).deleteDocument("123"); + } catch (final ArangoDBException e) { + } + } + } + + @Test + public void insertDocument() { + try { + if ((Permissions.RW.equals(param.dbPermission) || Permissions.RO.equals(param.dbPermission)) + && Permissions.RW.equals(param.colPermission)) { + try { + arangoDB.db(DB_NAME).collection(COLLECTION_NAME).insertDocument(new BaseDocument("123")); + } catch (final ArangoDBException e) { + fail(details); + } + assertThat(details, arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME).documentExists("123"), + is(true)); + } else { + try { + arangoDB.db(DB_NAME).collection(COLLECTION_NAME).insertDocument(new BaseDocument("123")); + fail(details); + } catch (final ArangoDBException e) { + } + assertThat(details, arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME).documentExists("123"), + is(false)); + } + } finally { + try { + arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME).deleteDocument("123"); + } catch (final ArangoDBException e) { + } + } + } + + @Test + public void updateDocumentByKey() { + try { + arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME).insertDocument(new BaseDocument("123")); + if ((Permissions.RW.equals(param.dbPermission) || Permissions.RO.equals(param.dbPermission)) + && Permissions.RW.equals(param.colPermission)) { + try { + arangoDB.db(DB_NAME).collection(COLLECTION_NAME).updateDocument("123", + new BaseDocument(new MapBuilder().put("test", "test").get())); + } catch (final ArangoDBException e) { + fail(details); + } + assertThat(details, arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME) + .getDocument("123", BaseDocument.class).getAttribute("test").toString(), + is("test")); + } else { + try { + arangoDB.db(DB_NAME).collection(COLLECTION_NAME).updateDocument("123", + new BaseDocument(new MapBuilder().put("test", "test").get())); + fail(details); + } catch (final ArangoDBException e) { + } + assertThat(details, arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME) + .getDocument("123", BaseDocument.class).getAttribute("test"), + is(nullValue())); + } + } finally { + try { + arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME).deleteDocument("123"); + } catch (final ArangoDBException e) { + } + } + } + + @Test + public void updateDocumentByAql() { + try { + arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME).insertDocument(new BaseDocument("123")); + if ((Permissions.RW.equals(param.dbPermission) || Permissions.RO.equals(param.dbPermission)) + && Permissions.RW.equals(param.colPermission)) { + try { + arangoDB.db(DB_NAME).query("FOR i IN @@col UPDATE i WITH @newDoc IN @@col", + new MapBuilder().put("@col", COLLECTION_NAME) + .put("newDoc", new BaseDocument(new MapBuilder().put("test", "test").get())).get(), + new AqlQueryOptions(), Void.class); + } catch (final ArangoDBException e) { + fail(details); + } + assertThat(details, arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME) + .getDocument("123", BaseDocument.class).getAttribute("test").toString(), + is("test")); + } else { + try { + arangoDB.db(DB_NAME).query("FOR i IN @@col UPDATE i WITH @newDoc IN @@col", + new MapBuilder().put("@col", COLLECTION_NAME) + .put("newDoc", new BaseDocument(new MapBuilder().put("test", "test").get())).get(), + new AqlQueryOptions(), Void.class); + fail(details); + } catch (final ArangoDBException e) { + } + assertThat(details, arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME) + .getDocument("123", BaseDocument.class).getAttribute("test"), + is(nullValue())); + } + } finally { + try { + arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME).deleteDocument("123"); + } catch (final ArangoDBException e) { + } + } + } + + @Test + public void deleteDocumentByKey() { + try { + arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME).insertDocument(new BaseDocument("123")); + if ((Permissions.RW.equals(param.dbPermission) || Permissions.RO.equals(param.dbPermission)) + && Permissions.RW.equals(param.colPermission)) { + try { + arangoDB.db(DB_NAME).collection(COLLECTION_NAME).deleteDocument("123"); + } catch (final ArangoDBException e) { + fail(details); + } + assertThat(details, arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME).documentExists("123"), + is(false)); + } else { + try { + arangoDB.db(DB_NAME).collection(COLLECTION_NAME).deleteDocument("123"); + fail(details); + } catch (final ArangoDBException e) { + } + assertThat(details, arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME).documentExists("123"), + is(true)); + } + } finally { + try { + arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME).deleteDocument("123"); + } catch (final ArangoDBException e) { + } + } + } + + @Test + public void deleteDocumentByAql() { + try { + arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME).insertDocument(new BaseDocument("123")); + if ((Permissions.RW.equals(param.dbPermission) || Permissions.RO.equals(param.dbPermission)) + && Permissions.RW.equals(param.colPermission)) { + try { + arangoDB.db(DB_NAME).query("REMOVE @key IN @@col", + new MapBuilder().put("key", "123").put("@col", COLLECTION_NAME).get(), new AqlQueryOptions(), + Void.class); + } catch (final ArangoDBException e) { + fail(details); + } + assertThat(details, arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME).documentExists("123"), + is(false)); + } else { + try { + arangoDB.db(DB_NAME).query("REMOVE @key IN @@col", + new MapBuilder().put("key", "123").put("@col", COLLECTION_NAME).get(), new AqlQueryOptions(), + Void.class); + fail(details); + } catch (final ArangoDBException e) { + } + assertThat(details, arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME).documentExists("123"), + is(true)); + } + } finally { + try { + arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME).deleteDocument("123"); + } catch (final ArangoDBException e) { + } + } + } } diff --git a/src/test/java/com/arangodb/example/ExampleBase.java b/src/test/java/com/arangodb/example/ExampleBase.java index f3bb8cb76..49d89d40d 100644 --- a/src/test/java/com/arangodb/example/ExampleBase.java +++ b/src/test/java/com/arangodb/example/ExampleBase.java @@ -30,34 +30,31 @@ /** * @author Mark Vollmary - * */ public class ExampleBase { - protected static final String DB_NAME = "json_example_db"; - protected static final String COLLECTION_NAME = "json_example_collection"; - - protected static ArangoDB arangoDB; - protected static ArangoDatabase db; - protected static ArangoCollection collection; - - @BeforeClass - public static void setUp() { - arangoDB = new ArangoDB.Builder().build(); - try { - arangoDB.db(DB_NAME).drop(); - } catch (final ArangoDBException e) { - } - arangoDB.createDatabase(DB_NAME); - db = arangoDB.db(DB_NAME); - db.createCollection(COLLECTION_NAME); - collection = db.collection(COLLECTION_NAME); - } - - @AfterClass - public static void tearDown() { - db.drop(); - arangoDB.shutdown(); - } + protected static final String DB_NAME = "json_example_db"; + protected static final String COLLECTION_NAME = "json_example_collection"; + + protected static ArangoDB arangoDB; + protected static ArangoDatabase db; + protected static ArangoCollection collection; + + @BeforeClass + public static void setUp() { + arangoDB = new ArangoDB.Builder().build(); + if (arangoDB.db(DB_NAME).exists()) + arangoDB.db(DB_NAME).drop(); + arangoDB.createDatabase(DB_NAME); + db = arangoDB.db(DB_NAME); + db.createCollection(COLLECTION_NAME); + collection = db.collection(COLLECTION_NAME); + } + + @AfterClass + public static void tearDown() { + db.drop(); + arangoDB.shutdown(); + } } diff --git a/src/test/java/com/arangodb/example/document/AqlQueryWithSpecialReturnTypesExample.java b/src/test/java/com/arangodb/example/document/AqlQueryWithSpecialReturnTypesExample.java index 331a4226f..f35602cb2 100644 --- a/src/test/java/com/arangodb/example/document/AqlQueryWithSpecialReturnTypesExample.java +++ b/src/test/java/com/arangodb/example/document/AqlQueryWithSpecialReturnTypesExample.java @@ -40,101 +40,97 @@ /** * @author Mark Vollmary - * */ public class AqlQueryWithSpecialReturnTypesExample extends ExampleBase { - @BeforeClass - public static void before() { - createExamples(); - } + @BeforeClass + public static void before() { + createExamples(); + } - public enum Gender { - MALE, FEMALE - } + public enum Gender { + MALE, FEMALE + } - private static void createExamples() { - for (int i = 0; i < 100; i++) { - final BaseDocument value = new BaseDocument(); - value.addAttribute("name", "TestUser" + i); - value.addAttribute("gender", (i % 2) == 0 ? Gender.MALE : Gender.FEMALE); - value.addAttribute("age", i + 10); - db.collection(COLLECTION_NAME).insertDocument(value); - } - } + private static void createExamples() { + for (int i = 0; i < 100; i++) { + final BaseDocument value = new BaseDocument(); + value.addAttribute("name", "TestUser" + i); + value.addAttribute("gender", (i % 2) == 0 ? Gender.MALE : Gender.FEMALE); + value.addAttribute("age", i + 10); + db.collection(COLLECTION_NAME).insertDocument(value); + } + } - @Test - public void aqlWithLimitQueryAsVPackObject() { - final String query = "FOR t IN " + COLLECTION_NAME - + " FILTER t.age >= 20 && t.age < 30 && t.gender == @gender RETURN t"; - final Map bindVars = new MapBuilder().put("gender", Gender.FEMALE).get(); - final ArangoCursor cursor = db.query(query, bindVars, null, VPackSlice.class); - assertThat(cursor, is(notNullValue())); - for (; cursor.hasNext();) { - final VPackSlice vpack = cursor.next(); - try { - assertThat(vpack.get("name").getAsString(), - isOneOf("TestUser11", "TestUser13", "TestUser15", "TestUser17", "TestUser19")); - assertThat(vpack.get("gender").getAsString(), is(Gender.FEMALE.name())); - assertThat(vpack.get("age").getAsInt(), isOneOf(21, 23, 25, 27, 29)); - } catch (final VPackException e) { - } - } - } + @Test + public void aqlWithLimitQueryAsVPackObject() { + final String query = "FOR t IN " + COLLECTION_NAME + + " FILTER t.age >= 20 && t.age < 30 && t.gender == @gender RETURN t"; + final Map bindVars = new MapBuilder().put("gender", Gender.FEMALE).get(); + final ArangoCursor cursor = db.query(query, bindVars, null, VPackSlice.class); + assertThat(cursor, is(notNullValue())); + for (; cursor.hasNext(); ) { + final VPackSlice vpack = cursor.next(); + assertThat(vpack.get("name").getAsString(), + isOneOf("TestUser11", "TestUser13", "TestUser15", "TestUser17", "TestUser19")); + assertThat(vpack.get("gender").getAsString(), is(Gender.FEMALE.name())); + assertThat(vpack.get("age").getAsInt(), isOneOf(21, 23, 25, 27, 29)); + } + } - @Test - public void aqlWithLimitQueryAsVPackArray() { - final String query = "FOR t IN " + COLLECTION_NAME - + " FILTER t.age >= 20 && t.age < 30 && t.gender == @gender RETURN [t.name, t.gender, t.age]"; - final Map bindVars = new MapBuilder().put("gender", Gender.FEMALE).get(); - final ArangoCursor cursor = db.query(query, bindVars, null, VPackSlice.class); - assertThat(cursor, is(notNullValue())); - for (; cursor.hasNext();) { - final VPackSlice vpack = cursor.next(); - assertThat(vpack.get(0).getAsString(), - isOneOf("TestUser11", "TestUser13", "TestUser15", "TestUser17", "TestUser19")); - assertThat(vpack.get(1).getAsString(), is(Gender.FEMALE.name())); - assertThat(vpack.get(2).getAsInt(), isOneOf(21, 23, 25, 27, 29)); - } - } + @Test + public void aqlWithLimitQueryAsVPackArray() { + final String query = "FOR t IN " + COLLECTION_NAME + + " FILTER t.age >= 20 && t.age < 30 && t.gender == @gender RETURN [t.name, t.gender, t.age]"; + final Map bindVars = new MapBuilder().put("gender", Gender.FEMALE).get(); + final ArangoCursor cursor = db.query(query, bindVars, null, VPackSlice.class); + assertThat(cursor, is(notNullValue())); + for (; cursor.hasNext(); ) { + final VPackSlice vpack = cursor.next(); + assertThat(vpack.get(0).getAsString(), + isOneOf("TestUser11", "TestUser13", "TestUser15", "TestUser17", "TestUser19")); + assertThat(vpack.get(1).getAsString(), is(Gender.FEMALE.name())); + assertThat(vpack.get(2).getAsInt(), isOneOf(21, 23, 25, 27, 29)); + } + } - @Test - @SuppressWarnings("rawtypes") - public void aqlWithLimitQueryAsMap() { - final String query = "FOR t IN " + COLLECTION_NAME - + " FILTER t.age >= 20 && t.age < 30 && t.gender == @gender RETURN t"; - final Map bindVars = new MapBuilder().put("gender", Gender.FEMALE).get(); - final ArangoCursor cursor = db.query(query, bindVars, null, Map.class); - assertThat(cursor, is(notNullValue())); - for (; cursor.hasNext();) { - final Map map = cursor.next(); - assertThat(map.get("name"), is(notNullValue())); - assertThat(String.valueOf(map.get("name")), - isOneOf("TestUser11", "TestUser13", "TestUser15", "TestUser17", "TestUser19")); - assertThat(map.get("gender"), is(notNullValue())); - assertThat(String.valueOf(map.get("gender")), is(Gender.FEMALE.name())); - assertThat(map.get("age"), is(notNullValue())); - assertThat(Long.valueOf(map.get("age").toString()), isOneOf(21L, 23L, 25L, 27L, 29L)); - } - } + @Test + @SuppressWarnings("rawtypes") + public void aqlWithLimitQueryAsMap() { + final String query = "FOR t IN " + COLLECTION_NAME + + " FILTER t.age >= 20 && t.age < 30 && t.gender == @gender RETURN t"; + final Map bindVars = new MapBuilder().put("gender", Gender.FEMALE).get(); + final ArangoCursor cursor = db.query(query, bindVars, null, Map.class); + assertThat(cursor, is(notNullValue())); + for (; cursor.hasNext(); ) { + final Map map = cursor.next(); + assertThat(map.get("name"), is(notNullValue())); + assertThat(String.valueOf(map.get("name")), + isOneOf("TestUser11", "TestUser13", "TestUser15", "TestUser17", "TestUser19")); + assertThat(map.get("gender"), is(notNullValue())); + assertThat(String.valueOf(map.get("gender")), is(Gender.FEMALE.name())); + assertThat(map.get("age"), is(notNullValue())); + assertThat(Long.valueOf(map.get("age").toString()), isOneOf(21L, 23L, 25L, 27L, 29L)); + } + } - @Test - @SuppressWarnings("rawtypes") - public void aqlWithLimitQueryAsList() { - final String query = "FOR t IN " + COLLECTION_NAME - + " FILTER t.age >= 20 && t.age < 30 && t.gender == @gender RETURN [t.name, t.gender, t.age]"; - final Map bindVars = new MapBuilder().put("gender", Gender.FEMALE).get(); - final ArangoCursor cursor = db.query(query, bindVars, null, List.class); - assertThat(cursor, is(notNullValue())); - for (; cursor.hasNext();) { - final List list = cursor.next(); - assertThat(list.get(0), is(notNullValue())); - assertThat(String.valueOf(list.get(0)), - isOneOf("TestUser11", "TestUser13", "TestUser15", "TestUser17", "TestUser19")); - assertThat(list.get(1), is(notNullValue())); - assertThat(Gender.valueOf(String.valueOf(list.get(1))), is(Gender.FEMALE)); - assertThat(list.get(2), is(notNullValue())); - assertThat(Long.valueOf(String.valueOf(list.get(2))), isOneOf(21L, 23L, 25L, 27L, 29L)); - } - } + @Test + @SuppressWarnings("rawtypes") + public void aqlWithLimitQueryAsList() { + final String query = "FOR t IN " + COLLECTION_NAME + + " FILTER t.age >= 20 && t.age < 30 && t.gender == @gender RETURN [t.name, t.gender, t.age]"; + final Map bindVars = new MapBuilder().put("gender", Gender.FEMALE).get(); + final ArangoCursor cursor = db.query(query, bindVars, null, List.class); + assertThat(cursor, is(notNullValue())); + for (; cursor.hasNext(); ) { + final List list = cursor.next(); + assertThat(list.get(0), is(notNullValue())); + assertThat(String.valueOf(list.get(0)), + isOneOf("TestUser11", "TestUser13", "TestUser15", "TestUser17", "TestUser19")); + assertThat(list.get(1), is(notNullValue())); + assertThat(Gender.valueOf(String.valueOf(list.get(1))), is(Gender.FEMALE)); + assertThat(list.get(2), is(notNullValue())); + assertThat(Long.valueOf(String.valueOf(list.get(2))), isOneOf(21L, 23L, 25L, 27L, 29L)); + } + } } diff --git a/src/test/java/com/arangodb/example/graph/AQLActorsAndMoviesExample.java b/src/test/java/com/arangodb/example/graph/AQLActorsAndMoviesExample.java index 79ef27823..ef6aa46f9 100644 --- a/src/test/java/com/arangodb/example/graph/AQLActorsAndMoviesExample.java +++ b/src/test/java/com/arangodb/example/graph/AQLActorsAndMoviesExample.java @@ -40,534 +40,530 @@ /** * @author Mark Vollmary - * * @see AQL Example Queries on an - * Actors and Movies Database - * + * Actors and Movies Database */ public class AQLActorsAndMoviesExample { - private static final String TEST_DB = "actors_movies_test_db"; - private static ArangoDB arangoDB; - private static ArangoDatabase db; - - @BeforeClass - public static void setUp() { - arangoDB = new ArangoDB.Builder().build(); - try { - arangoDB.db(TEST_DB).drop(); - } catch (final ArangoDBException e) { - } - arangoDB.createDatabase(TEST_DB); - db = arangoDB.db(TEST_DB); - createData(); - } - - @AfterClass - public static void tearDown() { - db.drop(); - arangoDB.shutdown(); - } - - /** - * @see AQL - * Example Queries on an Actors and Movies Database - */ - @Test - public void allActorsActsInMovie1or2() { - final ArangoCursor cursor = db.query( - "WITH actors FOR x IN ANY 'movies/TheMatrix' actsIn OPTIONS {bfs: true, uniqueVertices: 'global'} RETURN x._id", - null, null, String.class); - assertThat(cursor.asListRemaining(), - hasItems("actors/Keanu", "actors/Hugo", "actors/Emil", "actors/Carrie", "actors/Laurence")); - } - - /** - * @see AQL - * Example Queries on an Actors and Movies Database - */ - @Test - public void allActorsActsInMovie1or2UnionDistinct() { - final ArangoCursor cursor = db.query( - "WITH actors FOR x IN UNION_DISTINCT ((FOR y IN ANY 'movies/TheMatrix' actsIn OPTIONS {bfs: true, uniqueVertices: 'global'} RETURN y._id), (FOR y IN ANY 'movies/TheDevilsAdvocate' actsIn OPTIONS {bfs: true, uniqueVertices: 'global'} RETURN y._id)) RETURN x", - null, null, String.class); - assertThat(cursor.asListRemaining(), hasItems("actors/Emil", "actors/Hugo", "actors/Carrie", "actors/Laurence", - "actors/Keanu", "actors/Al", "actors/Charlize")); - } - - /** - * @see AQL - * Example Queries on an Actors and Movies Database - */ - @Test - public void allActorsActsInMovie1and2() { - final ArangoCursor cursor = db.query( - "WITH actors FOR x IN INTERSECTION ((FOR y IN ANY 'movies/TheMatrix' actsIn OPTIONS {bfs: true, uniqueVertices: 'global'} RETURN y._id), (FOR y IN ANY 'movies/TheDevilsAdvocate' actsIn OPTIONS {bfs: true, uniqueVertices: 'global'} RETURN y._id)) RETURN x", - null, null, String.class); - assertThat(cursor.asListRemaining(), hasItems("actors/Keanu")); - } - - /** - * @see AQL - * Example Queries on an Actors and Movies Database - */ - @Test - public void allMoviesBetweenActor1andActor2() { - final ArangoCursor cursor = db.query( - "WITH movies FOR x IN INTERSECTION ((FOR y IN ANY 'actors/Hugo' actsIn OPTIONS {bfs: true, uniqueVertices: 'global'} RETURN y._id), (FOR y IN ANY 'actors/Keanu' actsIn OPTIONS {bfs: true, uniqueVertices: 'global'} RETURN y._id)) RETURN x", - null, null, String.class); - assertThat(cursor.asListRemaining(), - hasItems("movies/TheMatrixRevolutions", "movies/TheMatrixReloaded", "movies/TheMatrix")); - } - - /** - * @see AQL - * Example Queries on an Actors and Movies Database - */ - @Test - public void allActorsWhoActedIn3orMoreMovies() { - final ArangoCursor cursor = db.query( - "FOR x IN actsIn COLLECT actor = x._from WITH COUNT INTO counter FILTER counter >= 3 RETURN {actor: actor, movies: counter}", - null, null, Actor.class); - assertThat(cursor.asListRemaining(), - hasItems(new Actor("actors/Carrie", 3), new Actor("actors/CubaG", 4), new Actor("actors/Hugo", 3), - new Actor("actors/Keanu", 4), new Actor("actors/Laurence", 3), new Actor("actors/MegR", 5), - new Actor("actors/TomC", 3), new Actor("actors/TomH", 3))); - } - - /** - * @see AQL - * Example Queries on an Actors and Movies Database - */ - @Test - public void allMoviesWhereExactly6ActorsActedIn() { - final ArangoCursor cursor = db.query( - "FOR x IN actsIn COLLECT movie = x._to WITH COUNT INTO counter FILTER counter == 6 RETURN movie", null, - null, String.class); - assertThat(cursor.asListRemaining(), - hasItems("movies/SleeplessInSeattle", "movies/TopGun", "movies/YouveGotMail")); - } - - /** - * @see AQL - * Example Queries on an Actors and Movies Database - */ - @Test - public void theNumberOfActorsByMovie() { - final ArangoCursor cursor = db.query( - "FOR x IN actsIn COLLECT movie = x._to WITH COUNT INTO counter RETURN {movie: movie, actors: counter}", - null, null, Movie.class); - assertThat(cursor.asListRemaining(), - hasItems(new Movie("movies/AFewGoodMen", 11), new Movie("movies/AsGoodAsItGets", 4), - new Movie("movies/JerryMaguire", 9), new Movie("movies/JoeVersustheVolcano", 3), - new Movie("movies/SleeplessInSeattle", 6), new Movie("movies/SnowFallingonCedars", 4), - new Movie("movies/StandByMe", 7), new Movie("movies/TheDevilsAdvocate", 3), - new Movie("movies/TheMatrix", 5), new Movie("movies/TheMatrixReloaded", 4), - new Movie("movies/TheMatrixRevolutions", 4), new Movie("movies/TopGun", 6), - new Movie("movies/WhatDreamsMayCome", 5), new Movie("movies/WhenHarryMetSally", 4), - new Movie("movies/YouveGotMail", 6))); - } - - /** - * @see AQL - * Example Queries on an Actors and Movies Database - */ - @Test - public void theNumberOfMoviesByActor() { - final ArangoCursor cursor = db.query( - "FOR x IN actsIn COLLECT actor = x._from WITH COUNT INTO counter RETURN {actor: actor, movies: counter}", - null, null, Actor.class); - assertThat(cursor.asListRemaining(), - hasItems(new Actor("actors/Al", 1), new Actor("actors/AnnabellaS", 1), new Actor("actors/AnthonyE", 1), - new Actor("actors/BillPull", 1), new Actor("actors/BillyC", 1), new Actor("actors/BonnieH", 1), - new Actor("actors/BrunoK", 1), new Actor("actors/Carrie", 3), new Actor("actors/CarrieF", 1), - new Actor("actors/Charlize", 1), new Actor("actors/ChristopherG", 1), new Actor("actors/CoreyF", 1), - new Actor("actors/CubaG", 4), new Actor("actors/DaveC", 1), new Actor("actors/DemiM", 1), - new Actor("actors/Emil", 1), new Actor("actors/EthanH", 1), new Actor("actors/GregK", 2), - new Actor("actors/HelenH", 1), new Actor("actors/Hugo", 3), new Actor("actors/JackN", 2), - new Actor("actors/JamesC", 1), new Actor("actors/JamesM", 1), new Actor("actors/JayM", 1), - new Actor("actors/JerryO", 2), new Actor("actors/JohnC", 1), new Actor("actors/JonathanL", 1), - new Actor("actors/JTW", 1), new Actor("actors/Keanu", 4), new Actor("actors/KellyM", 1), - new Actor("actors/KellyP", 1), new Actor("actors/KevinB", 1), new Actor("actors/KevinP", 1), - new Actor("actors/KieferS", 2), new Actor("actors/Laurence", 3), new Actor("actors/MarshallB", 1), - new Actor("actors/MaxS", 2), new Actor("actors/MegR", 5), new Actor("actors/Nathan", 1), - new Actor("actors/NoahW", 1), new Actor("actors/ParkerP", 1), new Actor("actors/ReginaK", 1), - new Actor("actors/ReneeZ", 1), new Actor("actors/RickY", 1), new Actor("actors/RitaW", 1), - new Actor("actors/RiverP", 1), new Actor("actors/Robin", 1), new Actor("actors/RosieO", 1), - new Actor("actors/SteveZ", 1), new Actor("actors/TomC", 3), new Actor("actors/TomH", 3), - new Actor("actors/TomS", 1), new Actor("actors/ValK", 1), new Actor("actors/VictorG", 1), - new Actor("actors/WernerH", 1), new Actor("actors/WilW", 1))); - } - - /** - * @see AQL - * Example Queries on an Actors and Movies Database - */ - @Test - public void theNumberOfMoviesActedInBetween2005and2010byActor() { - final ArangoCursor cursor = db.query( - "FOR x IN actsIn FILTER x.year >= 1990 && x.year <= 1995 COLLECT actor = x._from WITH COUNT INTO counter RETURN {actor: actor, movies: counter}", - null, null, Actor.class); - assertThat(cursor.asListRemaining(), - hasItems(new Actor("actors/BillPull", 1), new Actor("actors/ChristopherG", 1), new Actor("actors/CubaG", 1), - new Actor("actors/DemiM", 1), new Actor("actors/JackN", 1), new Actor("actors/JamesM", 1), - new Actor("actors/JTW", 1), new Actor("actors/KevinB", 1), new Actor("actors/KieferS", 1), - new Actor("actors/MegR", 2), new Actor("actors/Nathan", 1), new Actor("actors/NoahW", 1), - new Actor("actors/RitaW", 1), new Actor("actors/RosieO", 1), new Actor("actors/TomC", 1), - new Actor("actors/TomH", 2), new Actor("actors/VictorG", 1))); - } - - public static class Actor { - private String actor; - private Integer movies; - - public Actor() { - super(); - } - - public Actor(final String actor, final Integer movies) { - super(); - this.actor = actor; - this.movies = movies; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((actor == null) ? 0 : actor.hashCode()); - result = prime * result + ((movies == null) ? 0 : movies.hashCode()); - return result; - } - - @Override - public boolean equals(final Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final Actor other = (Actor) obj; - if (actor == null) { - if (other.actor != null) { - return false; - } - } else if (!actor.equals(other.actor)) { - return false; - } - if (movies == null) { - if (other.movies != null) { - return false; - } - } else if (!movies.equals(other.movies)) { - return false; - } - return true; - } - - } - - public static class Movie { - private String movie; - private Integer actors; - - public Movie() { - super(); - } - - public Movie(final String movie, final Integer actors) { - super(); - this.movie = movie; - this.actors = actors; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((actors == null) ? 0 : actors.hashCode()); - result = prime * result + ((movie == null) ? 0 : movie.hashCode()); - return result; - } - - @Override - public boolean equals(final Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final Movie other = (Movie) obj; - if (actors == null) { - if (other.actors != null) { - return false; - } - } else if (!actors.equals(other.actors)) { - return false; - } - if (movie == null) { - if (other.movie != null) { - return false; - } - } else if (!movie.equals(other.movie)) { - return false; - } - return true; - } - - } - - private static DocumentCreateEntity saveMovie( - final ArangoCollection movies, - final String key, - final String title, - final int released, - final String tagline) { - final BaseDocument value = new BaseDocument(); - value.setKey(key); - value.addAttribute("title", title); - value.addAttribute("released", released); - value.addAttribute("tagline", tagline); - return movies.insertDocument(value); - } - - private static DocumentCreateEntity saveActor( - final ArangoCollection actors, - final String key, - final String name, - final int born) { - final BaseDocument value = new BaseDocument(); - value.setKey(key); - value.addAttribute("name", name); - value.addAttribute("born", born); - return actors.insertDocument(value); - } - - private static DocumentCreateEntity saveActsIn( - final ArangoCollection actsIn, - final String actor, - final String movie, - final String[] roles, - final int year) { - final BaseEdgeDocument value = new BaseEdgeDocument(); - value.setFrom(actor); - value.setTo(movie); - value.addAttribute("roles", roles); - value.addAttribute("year", year); - return actsIn.insertDocument(value); - } - - private static void createData() { - db.createCollection("actors"); - final ArangoCollection actors = db.collection("actors"); - db.createCollection("movies"); - final ArangoCollection movies = db.collection("movies"); - db.createCollection("actsIn", new CollectionCreateOptions().type(CollectionType.EDGES)); - final ArangoCollection actsIn = db.collection("actsIn"); - - final String theMatrix = saveMovie(movies, "TheMatrix", "The Matrix", 1999, "Welcome to the Real World") - .getId(); - final String keanu = saveActor(actors, "Keanu", "Keanu Reeves", 1964).getId(); - final String carrie = saveActor(actors, "Carrie", "Carrie-Anne Moss", 1967).getId(); - final String laurence = saveActor(actors, "Laurence", "Laurence Fishburne", 1961).getId(); - final String hugo = saveActor(actors, "Hugo", "Hugo Weaving", 1960).getId(); - final String emil = saveActor(actors, "Emil", "Emil Eifrem", 1978).getId(); - - saveActsIn(actsIn, keanu, theMatrix, new String[] { "Neo" }, 1999); - saveActsIn(actsIn, carrie, theMatrix, new String[] { "Trinity" }, 1999); - saveActsIn(actsIn, laurence, theMatrix, new String[] { "Morpheus" }, 1999); - saveActsIn(actsIn, hugo, theMatrix, new String[] { "Agent Smith" }, 1999); - saveActsIn(actsIn, emil, theMatrix, new String[] { "Emil" }, 1999); - - final String theMatrixReloaded = saveMovie(movies, "TheMatrixReloaded", "The Matrix Reloaded", 2003, - "Free your mind").getId(); - saveActsIn(actsIn, keanu, theMatrixReloaded, new String[] { "Neo" }, 2003); - saveActsIn(actsIn, carrie, theMatrixReloaded, new String[] { "Trinity" }, 2003); - saveActsIn(actsIn, laurence, theMatrixReloaded, new String[] { "Morpheus" }, 2003); - saveActsIn(actsIn, hugo, theMatrixReloaded, new String[] { "Agent Smith" }, 2003); - - final String theMatrixRevolutions = saveMovie(movies, "TheMatrixRevolutions", "The Matrix Revolutions", 2003, - "Everything that has a beginning has an end").getId(); - saveActsIn(actsIn, keanu, theMatrixRevolutions, new String[] { "Neo" }, 2003); - saveActsIn(actsIn, carrie, theMatrixRevolutions, new String[] { "Trinity" }, 2003); - saveActsIn(actsIn, laurence, theMatrixRevolutions, new String[] { "Morpheus" }, 2003); - saveActsIn(actsIn, hugo, theMatrixRevolutions, new String[] { "Agent Smith" }, 2003); - - final String theDevilsAdvocate = saveMovie(movies, "TheDevilsAdvocate", "The Devil's Advocate", 1997, - "Evil has its winning ways").getId(); - final String charlize = saveActor(actors, "Charlize", "Charlize Theron", 1975).getId(); - final String al = saveActor(actors, "Al", "Al Pacino", 1940).getId(); - saveActsIn(actsIn, keanu, theDevilsAdvocate, new String[] { "Kevin Lomax" }, 1997); - saveActsIn(actsIn, charlize, theDevilsAdvocate, new String[] { "Mary Ann Lomax" }, 1997); - saveActsIn(actsIn, al, theDevilsAdvocate, new String[] { "John Milton" }, 1997); - - final String AFewGoodMen = saveMovie(movies, "AFewGoodMen", "A Few Good Men", 1992, - "In the heart of the nation's capital, in a courthouse of the U.S. government, one man will stop at nothing to keep his honor, and one will stop at nothing to find the truth.") - .getId(); - final String tomC = saveActor(actors, "TomC", "Tom Cruise", 1962).getId(); - final String jackN = saveActor(actors, "JackN", "Jack Nicholson", 1937).getId(); - final String demiM = saveActor(actors, "DemiM", "Demi Moore", 1962).getId(); - final String kevinB = saveActor(actors, "KevinB", "Kevin Bacon", 1958).getId(); - final String kieferS = saveActor(actors, "KieferS", "Kiefer Sutherland", 1966).getId(); - final String noahW = saveActor(actors, "NoahW", "Noah Wyle", 1971).getId(); - final String cubaG = saveActor(actors, "CubaG", "Cuba Gooding Jr.", 1968).getId(); - final String kevinP = saveActor(actors, "KevinP", "Kevin Pollak", 1957).getId(); - final String jTW = saveActor(actors, "JTW", "J.T. Walsh", 1943).getId(); - final String jamesM = saveActor(actors, "JamesM", "James Marshall", 1967).getId(); - final String christopherG = saveActor(actors, "ChristopherG", "Christopher Guest", 1948).getId(); - saveActsIn(actsIn, tomC, AFewGoodMen, new String[] { "Lt. Daniel Kaffee" }, 1992); - saveActsIn(actsIn, jackN, AFewGoodMen, new String[] { "Col. Nathan R. Jessup" }, 1992); - saveActsIn(actsIn, demiM, AFewGoodMen, new String[] { "Lt. Cdr. JoAnne Galloway" }, 1992); - saveActsIn(actsIn, kevinB, AFewGoodMen, new String[] { "Capt. Jack Ross" }, 1992); - saveActsIn(actsIn, kieferS, AFewGoodMen, new String[] { "Lt. Jonathan Kendrick" }, 1992); - saveActsIn(actsIn, noahW, AFewGoodMen, new String[] { "Cpl. Jeffrey Barnes" }, 1992); - saveActsIn(actsIn, cubaG, AFewGoodMen, new String[] { "Cpl. Carl Hammaker" }, 1992); - saveActsIn(actsIn, kevinP, AFewGoodMen, new String[] { "Lt. Sam Weinberg" }, 1992); - saveActsIn(actsIn, jTW, AFewGoodMen, new String[] { "Lt. Col. Matthew Andrew Markinson" }, 1992); - saveActsIn(actsIn, jamesM, AFewGoodMen, new String[] { "Pfc. Louden Downey" }, 1992); - saveActsIn(actsIn, christopherG, AFewGoodMen, new String[] { "Dr. Stone" }, 1992); - - final String topGun = saveMovie(movies, "TopGun", "Top Gun", 1986, "I feel the need, the need for speed.") - .getId(); - final String kellyM = saveActor(actors, "KellyM", "Kelly McGillis", 1957).getId(); - final String valK = saveActor(actors, "ValK", "Val Kilmer", 1959).getId(); - final String anthonyE = saveActor(actors, "AnthonyE", "Anthony Edwards", 1962).getId(); - final String tomS = saveActor(actors, "TomS", "Tom Skerritt", 1933).getId(); - final String megR = saveActor(actors, "MegR", "Meg Ryan", 1961).getId(); - saveActsIn(actsIn, tomC, topGun, new String[] { "Maverick" }, 1986); - saveActsIn(actsIn, kellyM, topGun, new String[] { "Charlie" }, 1986); - saveActsIn(actsIn, valK, topGun, new String[] { "Iceman" }, 1986); - saveActsIn(actsIn, anthonyE, topGun, new String[] { "Goose" }, 1986); - saveActsIn(actsIn, tomS, topGun, new String[] { "Viper" }, 1986); - saveActsIn(actsIn, megR, topGun, new String[] { "Carole" }, 1986); - - final String jerryMaguire = saveMovie(movies, "JerryMaguire", "Jerry Maguire", 2000, - "The rest of his life begins now.").getId(); - final String reneeZ = saveActor(actors, "ReneeZ", "Renee Zellweger", 1969).getId(); - final String kellyP = saveActor(actors, "KellyP", "Kelly Preston", 1962).getId(); - final String jerryO = saveActor(actors, "JerryO", "Jerry O'Connell", 1974).getId(); - final String jayM = saveActor(actors, "JayM", "Jay Mohr", 1970).getId(); - final String bonnieH = saveActor(actors, "BonnieH", "Bonnie Hunt", 1961).getId(); - final String reginaK = saveActor(actors, "ReginaK", "Regina King", 1971).getId(); - final String jonathanL = saveActor(actors, "JonathanL", "Jonathan Lipnicki", 1996).getId(); - saveActsIn(actsIn, tomC, jerryMaguire, new String[] { "Jerry Maguire" }, 2000); - saveActsIn(actsIn, cubaG, jerryMaguire, new String[] { "Rod Tidwell" }, 2000); - saveActsIn(actsIn, reneeZ, jerryMaguire, new String[] { "Dorothy Boyd" }, 2000); - saveActsIn(actsIn, kellyP, jerryMaguire, new String[] { "Avery Bishop" }, 2000); - saveActsIn(actsIn, jerryO, jerryMaguire, new String[] { "Frank Cushman" }, 2000); - saveActsIn(actsIn, jayM, jerryMaguire, new String[] { "Bob Sugar" }, 2000); - saveActsIn(actsIn, bonnieH, jerryMaguire, new String[] { "Laurel Boyd" }, 2000); - saveActsIn(actsIn, reginaK, jerryMaguire, new String[] { "Marcee Tidwell" }, 2000); - saveActsIn(actsIn, jonathanL, jerryMaguire, new String[] { "Ray Boyd" }, 2000); - - final String standByMe = saveMovie(movies, "StandByMe", "Stand By Me", 1986, - "For some, it's the last real taste of innocence, and the first real taste of life. But for everyone, it's the time that memories are made of.") - .getId(); - final String riverP = saveActor(actors, "RiverP", "River Phoenix", 1970).getId(); - final String coreyF = saveActor(actors, "CoreyF", "Corey Feldman", 1971).getId(); - final String wilW = saveActor(actors, "WilW", "Wil Wheaton", 1972).getId(); - final String johnC = saveActor(actors, "JohnC", "John Cusack", 1966).getId(); - final String marshallB = saveActor(actors, "MarshallB", "Marshall Bell", 1942).getId(); - saveActsIn(actsIn, wilW, standByMe, new String[] { "Gordie Lachance" }, 1986); - saveActsIn(actsIn, riverP, standByMe, new String[] { "Chris Chambers" }, 1986); - saveActsIn(actsIn, jerryO, standByMe, new String[] { "Vern Tessio" }, 1986); - saveActsIn(actsIn, coreyF, standByMe, new String[] { "Teddy Duchamp" }, 1986); - saveActsIn(actsIn, johnC, standByMe, new String[] { "Denny Lachance" }, 1986); - saveActsIn(actsIn, kieferS, standByMe, new String[] { "Ace Merrill" }, 1986); - saveActsIn(actsIn, marshallB, standByMe, new String[] { "Mr. Lachance" }, 1986); - - final String asGoodAsItGets = saveMovie(movies, "AsGoodAsItGets", "As Good as It Gets", 1997, - "A comedy from the heart that goes for the throat.").getId(); - final String helenH = saveActor(actors, "HelenH", "Helen Hunt", 1963).getId(); - final String gregK = saveActor(actors, "GregK", "Greg Kinnear", 1963).getId(); - saveActsIn(actsIn, jackN, asGoodAsItGets, new String[] { "Melvin Udall" }, 1997); - saveActsIn(actsIn, helenH, asGoodAsItGets, new String[] { "Carol Connelly" }, 1997); - saveActsIn(actsIn, gregK, asGoodAsItGets, new String[] { "Simon Bishop" }, 1997); - saveActsIn(actsIn, cubaG, asGoodAsItGets, new String[] { "Frank Sachs" }, 1997); - - final String whatDreamsMayCome = saveMovie(movies, "WhatDreamsMayCome", "What Dreams May Come", 1998, - "After life there is more. The end is just the beginning.").getId(); - final String annabellaS = saveActor(actors, "AnnabellaS", "Annabella Sciorra", 1960).getId(); - final String maxS = saveActor(actors, "MaxS", "Max von Sydow", 1929).getId(); - final String wernerH = saveActor(actors, "WernerH", "Werner Herzog", 1942).getId(); - final String robin = saveActor(actors, "Robin", "Robin Williams", 1951).getId(); - saveActsIn(actsIn, robin, whatDreamsMayCome, new String[] { "Chris Nielsen" }, 1998); - saveActsIn(actsIn, cubaG, whatDreamsMayCome, new String[] { "Albert Lewis" }, 1998); - saveActsIn(actsIn, annabellaS, whatDreamsMayCome, new String[] { "Annie Collins-Nielsen" }, 1998); - saveActsIn(actsIn, maxS, whatDreamsMayCome, new String[] { "The Tracker" }, 1998); - saveActsIn(actsIn, wernerH, whatDreamsMayCome, new String[] { "The Face" }, 1998); - - final String snowFallingonCedars = saveMovie(movies, "SnowFallingonCedars", "Snow Falling on Cedars", 1999, - "First loves last. Forever.").getId(); - final String ethanH = saveActor(actors, "EthanH", "Ethan Hawke", 1970).getId(); - final String rickY = saveActor(actors, "RickY", "Rick Yune", 1971).getId(); - final String jamesC = saveActor(actors, "JamesC", "James Cromwell", 1940).getId(); - saveActsIn(actsIn, ethanH, snowFallingonCedars, new String[] { "Ishmael Chambers" }, 1999); - saveActsIn(actsIn, rickY, snowFallingonCedars, new String[] { "Kazuo Miyamoto" }, 1999); - saveActsIn(actsIn, maxS, snowFallingonCedars, new String[] { "Nels Gudmundsson" }, 1999); - saveActsIn(actsIn, jamesC, snowFallingonCedars, new String[] { "Judge Fielding" }, 1999); - - final String youveGotMail = saveMovie(movies, "YouveGotMail", "You've Got Mail", 1998, - "At odds in life... in love on-line.").getId(); - final String parkerP = saveActor(actors, "ParkerP", "Parker Posey", 1968).getId(); - final String daveC = saveActor(actors, "DaveC", "Dave Chappelle", 1973).getId(); - final String steveZ = saveActor(actors, "SteveZ", "Steve Zahn", 1967).getId(); - final String tomH = saveActor(actors, "TomH", "Tom Hanks", 1956).getId(); - saveActsIn(actsIn, tomH, youveGotMail, new String[] { "Joe Fox" }, 1998); - saveActsIn(actsIn, megR, youveGotMail, new String[] { "Kathleen Kelly" }, 1998); - saveActsIn(actsIn, gregK, youveGotMail, new String[] { "Frank Navasky" }, 1998); - saveActsIn(actsIn, parkerP, youveGotMail, new String[] { "Patricia Eden" }, 1998); - saveActsIn(actsIn, daveC, youveGotMail, new String[] { "Kevin Jackson" }, 1998); - saveActsIn(actsIn, steveZ, youveGotMail, new String[] { "George Pappas" }, 1998); - - final String sleeplessInSeattle = saveMovie(movies, "SleeplessInSeattle", "Sleepless in Seattle", 1993, - "What if someone you never met, someone you never saw, someone you never knew was the only someone for you?") - .getId(); - final String ritaW = saveActor(actors, "RitaW", "Rita Wilson", 1956).getId(); - final String billPull = saveActor(actors, "BillPull", "Bill Pullman", 1953).getId(); - final String victorG = saveActor(actors, "VictorG", "Victor Garber", 1949).getId(); - final String rosieO = saveActor(actors, "RosieO", "Rosie O'Donnell", 1962).getId(); - saveActsIn(actsIn, tomH, sleeplessInSeattle, new String[] { "Sam Baldwin" }, 1993); - saveActsIn(actsIn, megR, sleeplessInSeattle, new String[] { "Annie Reed" }, 1993); - saveActsIn(actsIn, ritaW, sleeplessInSeattle, new String[] { "Suzy" }, 1993); - saveActsIn(actsIn, billPull, sleeplessInSeattle, new String[] { "Walter" }, 1993); - saveActsIn(actsIn, victorG, sleeplessInSeattle, new String[] { "Greg" }, 1993); - saveActsIn(actsIn, rosieO, sleeplessInSeattle, new String[] { "Becky" }, 1993); - - final String joeVersustheVolcano = saveMovie(movies, "JoeVersustheVolcano", "Joe Versus the Volcano", 1990, - "A story of love, lava and burning desire.").getId(); - final String nathan = saveActor(actors, "Nathan", "Nathan Lane", 1956).getId(); - saveActsIn(actsIn, tomH, joeVersustheVolcano, new String[] { "Joe Banks" }, 1990); - saveActsIn(actsIn, megR, joeVersustheVolcano, - new String[] { "DeDe', 'Angelica Graynamore', 'Patricia Graynamore" }, 1990); - saveActsIn(actsIn, nathan, joeVersustheVolcano, new String[] { "Baw" }, 1990); - - final String whenHarryMetSally = saveMovie(movies, "WhenHarryMetSally", "When Harry Met Sally", 1998, - "At odds in life... in love on-line.").getId(); - final String billyC = saveActor(actors, "BillyC", "Billy Crystal", 1948).getId(); - final String carrieF = saveActor(actors, "CarrieF", "Carrie Fisher", 1956).getId(); - final String brunoK = saveActor(actors, "BrunoK", "Bruno Kirby", 1949).getId(); - saveActsIn(actsIn, billyC, whenHarryMetSally, new String[] { "Harry Burns" }, 1998); - saveActsIn(actsIn, megR, whenHarryMetSally, new String[] { "Sally Albright" }, 1998); - saveActsIn(actsIn, carrieF, whenHarryMetSally, new String[] { "Marie" }, 1998); - saveActsIn(actsIn, brunoK, whenHarryMetSally, new String[] { "Jess" }, 1998); - } + private static final String TEST_DB = "actors_movies_test_db"; + private static ArangoDB arangoDB; + private static ArangoDatabase db; + + @BeforeClass + public static void setUp() { + arangoDB = new ArangoDB.Builder().build(); + if (arangoDB.db(TEST_DB).exists()) + arangoDB.db(TEST_DB).drop(); + arangoDB.createDatabase(TEST_DB); + db = arangoDB.db(TEST_DB); + createData(); + } + + @AfterClass + public static void tearDown() { + db.drop(); + arangoDB.shutdown(); + } + + /** + * @see AQL + * Example Queries on an Actors and Movies Database + */ + @Test + public void allActorsActsInMovie1or2() { + final ArangoCursor cursor = db.query( + "WITH actors FOR x IN ANY 'movies/TheMatrix' actsIn OPTIONS {bfs: true, uniqueVertices: 'global'} RETURN x._id", + null, null, String.class); + assertThat(cursor.asListRemaining(), + hasItems("actors/Keanu", "actors/Hugo", "actors/Emil", "actors/Carrie", "actors/Laurence")); + } + + /** + * @see AQL + * Example Queries on an Actors and Movies Database + */ + @Test + public void allActorsActsInMovie1or2UnionDistinct() { + final ArangoCursor cursor = db.query( + "WITH actors FOR x IN UNION_DISTINCT ((FOR y IN ANY 'movies/TheMatrix' actsIn OPTIONS {bfs: true, uniqueVertices: 'global'} RETURN y._id), (FOR y IN ANY 'movies/TheDevilsAdvocate' actsIn OPTIONS {bfs: true, uniqueVertices: 'global'} RETURN y._id)) RETURN x", + null, null, String.class); + assertThat(cursor.asListRemaining(), hasItems("actors/Emil", "actors/Hugo", "actors/Carrie", "actors/Laurence", + "actors/Keanu", "actors/Al", "actors/Charlize")); + } + + /** + * @see AQL + * Example Queries on an Actors and Movies Database + */ + @Test + public void allActorsActsInMovie1and2() { + final ArangoCursor cursor = db.query( + "WITH actors FOR x IN INTERSECTION ((FOR y IN ANY 'movies/TheMatrix' actsIn OPTIONS {bfs: true, uniqueVertices: 'global'} RETURN y._id), (FOR y IN ANY 'movies/TheDevilsAdvocate' actsIn OPTIONS {bfs: true, uniqueVertices: 'global'} RETURN y._id)) RETURN x", + null, null, String.class); + assertThat(cursor.asListRemaining(), hasItems("actors/Keanu")); + } + + /** + * @see AQL + * Example Queries on an Actors and Movies Database + */ + @Test + public void allMoviesBetweenActor1andActor2() { + final ArangoCursor cursor = db.query( + "WITH movies FOR x IN INTERSECTION ((FOR y IN ANY 'actors/Hugo' actsIn OPTIONS {bfs: true, uniqueVertices: 'global'} RETURN y._id), (FOR y IN ANY 'actors/Keanu' actsIn OPTIONS {bfs: true, uniqueVertices: 'global'} RETURN y._id)) RETURN x", + null, null, String.class); + assertThat(cursor.asListRemaining(), + hasItems("movies/TheMatrixRevolutions", "movies/TheMatrixReloaded", "movies/TheMatrix")); + } + + /** + * @see AQL + * Example Queries on an Actors and Movies Database + */ + @Test + public void allActorsWhoActedIn3orMoreMovies() { + final ArangoCursor cursor = db.query( + "FOR x IN actsIn COLLECT actor = x._from WITH COUNT INTO counter FILTER counter >= 3 RETURN {actor: actor, movies: counter}", + null, null, Actor.class); + assertThat(cursor.asListRemaining(), + hasItems(new Actor("actors/Carrie", 3), new Actor("actors/CubaG", 4), new Actor("actors/Hugo", 3), + new Actor("actors/Keanu", 4), new Actor("actors/Laurence", 3), new Actor("actors/MegR", 5), + new Actor("actors/TomC", 3), new Actor("actors/TomH", 3))); + } + + /** + * @see AQL + * Example Queries on an Actors and Movies Database + */ + @Test + public void allMoviesWhereExactly6ActorsActedIn() { + final ArangoCursor cursor = db.query( + "FOR x IN actsIn COLLECT movie = x._to WITH COUNT INTO counter FILTER counter == 6 RETURN movie", null, + null, String.class); + assertThat(cursor.asListRemaining(), + hasItems("movies/SleeplessInSeattle", "movies/TopGun", "movies/YouveGotMail")); + } + + /** + * @see AQL + * Example Queries on an Actors and Movies Database + */ + @Test + public void theNumberOfActorsByMovie() { + final ArangoCursor cursor = db.query( + "FOR x IN actsIn COLLECT movie = x._to WITH COUNT INTO counter RETURN {movie: movie, actors: counter}", + null, null, Movie.class); + assertThat(cursor.asListRemaining(), + hasItems(new Movie("movies/AFewGoodMen", 11), new Movie("movies/AsGoodAsItGets", 4), + new Movie("movies/JerryMaguire", 9), new Movie("movies/JoeVersustheVolcano", 3), + new Movie("movies/SleeplessInSeattle", 6), new Movie("movies/SnowFallingonCedars", 4), + new Movie("movies/StandByMe", 7), new Movie("movies/TheDevilsAdvocate", 3), + new Movie("movies/TheMatrix", 5), new Movie("movies/TheMatrixReloaded", 4), + new Movie("movies/TheMatrixRevolutions", 4), new Movie("movies/TopGun", 6), + new Movie("movies/WhatDreamsMayCome", 5), new Movie("movies/WhenHarryMetSally", 4), + new Movie("movies/YouveGotMail", 6))); + } + + /** + * @see AQL + * Example Queries on an Actors and Movies Database + */ + @Test + public void theNumberOfMoviesByActor() { + final ArangoCursor cursor = db.query( + "FOR x IN actsIn COLLECT actor = x._from WITH COUNT INTO counter RETURN {actor: actor, movies: counter}", + null, null, Actor.class); + assertThat(cursor.asListRemaining(), + hasItems(new Actor("actors/Al", 1), new Actor("actors/AnnabellaS", 1), new Actor("actors/AnthonyE", 1), + new Actor("actors/BillPull", 1), new Actor("actors/BillyC", 1), new Actor("actors/BonnieH", 1), + new Actor("actors/BrunoK", 1), new Actor("actors/Carrie", 3), new Actor("actors/CarrieF", 1), + new Actor("actors/Charlize", 1), new Actor("actors/ChristopherG", 1), new Actor("actors/CoreyF", 1), + new Actor("actors/CubaG", 4), new Actor("actors/DaveC", 1), new Actor("actors/DemiM", 1), + new Actor("actors/Emil", 1), new Actor("actors/EthanH", 1), new Actor("actors/GregK", 2), + new Actor("actors/HelenH", 1), new Actor("actors/Hugo", 3), new Actor("actors/JackN", 2), + new Actor("actors/JamesC", 1), new Actor("actors/JamesM", 1), new Actor("actors/JayM", 1), + new Actor("actors/JerryO", 2), new Actor("actors/JohnC", 1), new Actor("actors/JonathanL", 1), + new Actor("actors/JTW", 1), new Actor("actors/Keanu", 4), new Actor("actors/KellyM", 1), + new Actor("actors/KellyP", 1), new Actor("actors/KevinB", 1), new Actor("actors/KevinP", 1), + new Actor("actors/KieferS", 2), new Actor("actors/Laurence", 3), new Actor("actors/MarshallB", 1), + new Actor("actors/MaxS", 2), new Actor("actors/MegR", 5), new Actor("actors/Nathan", 1), + new Actor("actors/NoahW", 1), new Actor("actors/ParkerP", 1), new Actor("actors/ReginaK", 1), + new Actor("actors/ReneeZ", 1), new Actor("actors/RickY", 1), new Actor("actors/RitaW", 1), + new Actor("actors/RiverP", 1), new Actor("actors/Robin", 1), new Actor("actors/RosieO", 1), + new Actor("actors/SteveZ", 1), new Actor("actors/TomC", 3), new Actor("actors/TomH", 3), + new Actor("actors/TomS", 1), new Actor("actors/ValK", 1), new Actor("actors/VictorG", 1), + new Actor("actors/WernerH", 1), new Actor("actors/WilW", 1))); + } + + /** + * @see AQL + * Example Queries on an Actors and Movies Database + */ + @Test + public void theNumberOfMoviesActedInBetween2005and2010byActor() { + final ArangoCursor cursor = db.query( + "FOR x IN actsIn FILTER x.year >= 1990 && x.year <= 1995 COLLECT actor = x._from WITH COUNT INTO counter RETURN {actor: actor, movies: counter}", + null, null, Actor.class); + assertThat(cursor.asListRemaining(), + hasItems(new Actor("actors/BillPull", 1), new Actor("actors/ChristopherG", 1), new Actor("actors/CubaG", 1), + new Actor("actors/DemiM", 1), new Actor("actors/JackN", 1), new Actor("actors/JamesM", 1), + new Actor("actors/JTW", 1), new Actor("actors/KevinB", 1), new Actor("actors/KieferS", 1), + new Actor("actors/MegR", 2), new Actor("actors/Nathan", 1), new Actor("actors/NoahW", 1), + new Actor("actors/RitaW", 1), new Actor("actors/RosieO", 1), new Actor("actors/TomC", 1), + new Actor("actors/TomH", 2), new Actor("actors/VictorG", 1))); + } + + public static class Actor { + private String actor; + private Integer movies; + + public Actor() { + super(); + } + + public Actor(final String actor, final Integer movies) { + super(); + this.actor = actor; + this.movies = movies; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((actor == null) ? 0 : actor.hashCode()); + result = prime * result + ((movies == null) ? 0 : movies.hashCode()); + return result; + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final Actor other = (Actor) obj; + if (actor == null) { + if (other.actor != null) { + return false; + } + } else if (!actor.equals(other.actor)) { + return false; + } + if (movies == null) { + if (other.movies != null) { + return false; + } + } else if (!movies.equals(other.movies)) { + return false; + } + return true; + } + + } + + public static class Movie { + private String movie; + private Integer actors; + + public Movie() { + super(); + } + + public Movie(final String movie, final Integer actors) { + super(); + this.movie = movie; + this.actors = actors; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((actors == null) ? 0 : actors.hashCode()); + result = prime * result + ((movie == null) ? 0 : movie.hashCode()); + return result; + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final Movie other = (Movie) obj; + if (actors == null) { + if (other.actors != null) { + return false; + } + } else if (!actors.equals(other.actors)) { + return false; + } + if (movie == null) { + if (other.movie != null) { + return false; + } + } else if (!movie.equals(other.movie)) { + return false; + } + return true; + } + + } + + private static DocumentCreateEntity saveMovie( + final ArangoCollection movies, + final String key, + final String title, + final int released, + final String tagline) { + final BaseDocument value = new BaseDocument(); + value.setKey(key); + value.addAttribute("title", title); + value.addAttribute("released", released); + value.addAttribute("tagline", tagline); + return movies.insertDocument(value); + } + + private static DocumentCreateEntity saveActor( + final ArangoCollection actors, + final String key, + final String name, + final int born) { + final BaseDocument value = new BaseDocument(); + value.setKey(key); + value.addAttribute("name", name); + value.addAttribute("born", born); + return actors.insertDocument(value); + } + + private static DocumentCreateEntity saveActsIn( + final ArangoCollection actsIn, + final String actor, + final String movie, + final String[] roles, + final int year) { + final BaseEdgeDocument value = new BaseEdgeDocument(); + value.setFrom(actor); + value.setTo(movie); + value.addAttribute("roles", roles); + value.addAttribute("year", year); + return actsIn.insertDocument(value); + } + + private static void createData() { + db.createCollection("actors"); + final ArangoCollection actors = db.collection("actors"); + db.createCollection("movies"); + final ArangoCollection movies = db.collection("movies"); + db.createCollection("actsIn", new CollectionCreateOptions().type(CollectionType.EDGES)); + final ArangoCollection actsIn = db.collection("actsIn"); + + final String theMatrix = saveMovie(movies, "TheMatrix", "The Matrix", 1999, "Welcome to the Real World") + .getId(); + final String keanu = saveActor(actors, "Keanu", "Keanu Reeves", 1964).getId(); + final String carrie = saveActor(actors, "Carrie", "Carrie-Anne Moss", 1967).getId(); + final String laurence = saveActor(actors, "Laurence", "Laurence Fishburne", 1961).getId(); + final String hugo = saveActor(actors, "Hugo", "Hugo Weaving", 1960).getId(); + final String emil = saveActor(actors, "Emil", "Emil Eifrem", 1978).getId(); + + saveActsIn(actsIn, keanu, theMatrix, new String[]{"Neo"}, 1999); + saveActsIn(actsIn, carrie, theMatrix, new String[]{"Trinity"}, 1999); + saveActsIn(actsIn, laurence, theMatrix, new String[]{"Morpheus"}, 1999); + saveActsIn(actsIn, hugo, theMatrix, new String[]{"Agent Smith"}, 1999); + saveActsIn(actsIn, emil, theMatrix, new String[]{"Emil"}, 1999); + + final String theMatrixReloaded = saveMovie(movies, "TheMatrixReloaded", "The Matrix Reloaded", 2003, + "Free your mind").getId(); + saveActsIn(actsIn, keanu, theMatrixReloaded, new String[]{"Neo"}, 2003); + saveActsIn(actsIn, carrie, theMatrixReloaded, new String[]{"Trinity"}, 2003); + saveActsIn(actsIn, laurence, theMatrixReloaded, new String[]{"Morpheus"}, 2003); + saveActsIn(actsIn, hugo, theMatrixReloaded, new String[]{"Agent Smith"}, 2003); + + final String theMatrixRevolutions = saveMovie(movies, "TheMatrixRevolutions", "The Matrix Revolutions", 2003, + "Everything that has a beginning has an end").getId(); + saveActsIn(actsIn, keanu, theMatrixRevolutions, new String[]{"Neo"}, 2003); + saveActsIn(actsIn, carrie, theMatrixRevolutions, new String[]{"Trinity"}, 2003); + saveActsIn(actsIn, laurence, theMatrixRevolutions, new String[]{"Morpheus"}, 2003); + saveActsIn(actsIn, hugo, theMatrixRevolutions, new String[]{"Agent Smith"}, 2003); + + final String theDevilsAdvocate = saveMovie(movies, "TheDevilsAdvocate", "The Devil's Advocate", 1997, + "Evil has its winning ways").getId(); + final String charlize = saveActor(actors, "Charlize", "Charlize Theron", 1975).getId(); + final String al = saveActor(actors, "Al", "Al Pacino", 1940).getId(); + saveActsIn(actsIn, keanu, theDevilsAdvocate, new String[]{"Kevin Lomax"}, 1997); + saveActsIn(actsIn, charlize, theDevilsAdvocate, new String[]{"Mary Ann Lomax"}, 1997); + saveActsIn(actsIn, al, theDevilsAdvocate, new String[]{"John Milton"}, 1997); + + final String AFewGoodMen = saveMovie(movies, "AFewGoodMen", "A Few Good Men", 1992, + "In the heart of the nation's capital, in a courthouse of the U.S. government, one man will stop at nothing to keep his honor, and one will stop at nothing to find the truth.") + .getId(); + final String tomC = saveActor(actors, "TomC", "Tom Cruise", 1962).getId(); + final String jackN = saveActor(actors, "JackN", "Jack Nicholson", 1937).getId(); + final String demiM = saveActor(actors, "DemiM", "Demi Moore", 1962).getId(); + final String kevinB = saveActor(actors, "KevinB", "Kevin Bacon", 1958).getId(); + final String kieferS = saveActor(actors, "KieferS", "Kiefer Sutherland", 1966).getId(); + final String noahW = saveActor(actors, "NoahW", "Noah Wyle", 1971).getId(); + final String cubaG = saveActor(actors, "CubaG", "Cuba Gooding Jr.", 1968).getId(); + final String kevinP = saveActor(actors, "KevinP", "Kevin Pollak", 1957).getId(); + final String jTW = saveActor(actors, "JTW", "J.T. Walsh", 1943).getId(); + final String jamesM = saveActor(actors, "JamesM", "James Marshall", 1967).getId(); + final String christopherG = saveActor(actors, "ChristopherG", "Christopher Guest", 1948).getId(); + saveActsIn(actsIn, tomC, AFewGoodMen, new String[]{"Lt. Daniel Kaffee"}, 1992); + saveActsIn(actsIn, jackN, AFewGoodMen, new String[]{"Col. Nathan R. Jessup"}, 1992); + saveActsIn(actsIn, demiM, AFewGoodMen, new String[]{"Lt. Cdr. JoAnne Galloway"}, 1992); + saveActsIn(actsIn, kevinB, AFewGoodMen, new String[]{"Capt. Jack Ross"}, 1992); + saveActsIn(actsIn, kieferS, AFewGoodMen, new String[]{"Lt. Jonathan Kendrick"}, 1992); + saveActsIn(actsIn, noahW, AFewGoodMen, new String[]{"Cpl. Jeffrey Barnes"}, 1992); + saveActsIn(actsIn, cubaG, AFewGoodMen, new String[]{"Cpl. Carl Hammaker"}, 1992); + saveActsIn(actsIn, kevinP, AFewGoodMen, new String[]{"Lt. Sam Weinberg"}, 1992); + saveActsIn(actsIn, jTW, AFewGoodMen, new String[]{"Lt. Col. Matthew Andrew Markinson"}, 1992); + saveActsIn(actsIn, jamesM, AFewGoodMen, new String[]{"Pfc. Louden Downey"}, 1992); + saveActsIn(actsIn, christopherG, AFewGoodMen, new String[]{"Dr. Stone"}, 1992); + + final String topGun = saveMovie(movies, "TopGun", "Top Gun", 1986, "I feel the need, the need for speed.") + .getId(); + final String kellyM = saveActor(actors, "KellyM", "Kelly McGillis", 1957).getId(); + final String valK = saveActor(actors, "ValK", "Val Kilmer", 1959).getId(); + final String anthonyE = saveActor(actors, "AnthonyE", "Anthony Edwards", 1962).getId(); + final String tomS = saveActor(actors, "TomS", "Tom Skerritt", 1933).getId(); + final String megR = saveActor(actors, "MegR", "Meg Ryan", 1961).getId(); + saveActsIn(actsIn, tomC, topGun, new String[]{"Maverick"}, 1986); + saveActsIn(actsIn, kellyM, topGun, new String[]{"Charlie"}, 1986); + saveActsIn(actsIn, valK, topGun, new String[]{"Iceman"}, 1986); + saveActsIn(actsIn, anthonyE, topGun, new String[]{"Goose"}, 1986); + saveActsIn(actsIn, tomS, topGun, new String[]{"Viper"}, 1986); + saveActsIn(actsIn, megR, topGun, new String[]{"Carole"}, 1986); + + final String jerryMaguire = saveMovie(movies, "JerryMaguire", "Jerry Maguire", 2000, + "The rest of his life begins now.").getId(); + final String reneeZ = saveActor(actors, "ReneeZ", "Renee Zellweger", 1969).getId(); + final String kellyP = saveActor(actors, "KellyP", "Kelly Preston", 1962).getId(); + final String jerryO = saveActor(actors, "JerryO", "Jerry O'Connell", 1974).getId(); + final String jayM = saveActor(actors, "JayM", "Jay Mohr", 1970).getId(); + final String bonnieH = saveActor(actors, "BonnieH", "Bonnie Hunt", 1961).getId(); + final String reginaK = saveActor(actors, "ReginaK", "Regina King", 1971).getId(); + final String jonathanL = saveActor(actors, "JonathanL", "Jonathan Lipnicki", 1996).getId(); + saveActsIn(actsIn, tomC, jerryMaguire, new String[]{"Jerry Maguire"}, 2000); + saveActsIn(actsIn, cubaG, jerryMaguire, new String[]{"Rod Tidwell"}, 2000); + saveActsIn(actsIn, reneeZ, jerryMaguire, new String[]{"Dorothy Boyd"}, 2000); + saveActsIn(actsIn, kellyP, jerryMaguire, new String[]{"Avery Bishop"}, 2000); + saveActsIn(actsIn, jerryO, jerryMaguire, new String[]{"Frank Cushman"}, 2000); + saveActsIn(actsIn, jayM, jerryMaguire, new String[]{"Bob Sugar"}, 2000); + saveActsIn(actsIn, bonnieH, jerryMaguire, new String[]{"Laurel Boyd"}, 2000); + saveActsIn(actsIn, reginaK, jerryMaguire, new String[]{"Marcee Tidwell"}, 2000); + saveActsIn(actsIn, jonathanL, jerryMaguire, new String[]{"Ray Boyd"}, 2000); + + final String standByMe = saveMovie(movies, "StandByMe", "Stand By Me", 1986, + "For some, it's the last real taste of innocence, and the first real taste of life. But for everyone, it's the time that memories are made of.") + .getId(); + final String riverP = saveActor(actors, "RiverP", "River Phoenix", 1970).getId(); + final String coreyF = saveActor(actors, "CoreyF", "Corey Feldman", 1971).getId(); + final String wilW = saveActor(actors, "WilW", "Wil Wheaton", 1972).getId(); + final String johnC = saveActor(actors, "JohnC", "John Cusack", 1966).getId(); + final String marshallB = saveActor(actors, "MarshallB", "Marshall Bell", 1942).getId(); + saveActsIn(actsIn, wilW, standByMe, new String[]{"Gordie Lachance"}, 1986); + saveActsIn(actsIn, riverP, standByMe, new String[]{"Chris Chambers"}, 1986); + saveActsIn(actsIn, jerryO, standByMe, new String[]{"Vern Tessio"}, 1986); + saveActsIn(actsIn, coreyF, standByMe, new String[]{"Teddy Duchamp"}, 1986); + saveActsIn(actsIn, johnC, standByMe, new String[]{"Denny Lachance"}, 1986); + saveActsIn(actsIn, kieferS, standByMe, new String[]{"Ace Merrill"}, 1986); + saveActsIn(actsIn, marshallB, standByMe, new String[]{"Mr. Lachance"}, 1986); + + final String asGoodAsItGets = saveMovie(movies, "AsGoodAsItGets", "As Good as It Gets", 1997, + "A comedy from the heart that goes for the throat.").getId(); + final String helenH = saveActor(actors, "HelenH", "Helen Hunt", 1963).getId(); + final String gregK = saveActor(actors, "GregK", "Greg Kinnear", 1963).getId(); + saveActsIn(actsIn, jackN, asGoodAsItGets, new String[]{"Melvin Udall"}, 1997); + saveActsIn(actsIn, helenH, asGoodAsItGets, new String[]{"Carol Connelly"}, 1997); + saveActsIn(actsIn, gregK, asGoodAsItGets, new String[]{"Simon Bishop"}, 1997); + saveActsIn(actsIn, cubaG, asGoodAsItGets, new String[]{"Frank Sachs"}, 1997); + + final String whatDreamsMayCome = saveMovie(movies, "WhatDreamsMayCome", "What Dreams May Come", 1998, + "After life there is more. The end is just the beginning.").getId(); + final String annabellaS = saveActor(actors, "AnnabellaS", "Annabella Sciorra", 1960).getId(); + final String maxS = saveActor(actors, "MaxS", "Max von Sydow", 1929).getId(); + final String wernerH = saveActor(actors, "WernerH", "Werner Herzog", 1942).getId(); + final String robin = saveActor(actors, "Robin", "Robin Williams", 1951).getId(); + saveActsIn(actsIn, robin, whatDreamsMayCome, new String[]{"Chris Nielsen"}, 1998); + saveActsIn(actsIn, cubaG, whatDreamsMayCome, new String[]{"Albert Lewis"}, 1998); + saveActsIn(actsIn, annabellaS, whatDreamsMayCome, new String[]{"Annie Collins-Nielsen"}, 1998); + saveActsIn(actsIn, maxS, whatDreamsMayCome, new String[]{"The Tracker"}, 1998); + saveActsIn(actsIn, wernerH, whatDreamsMayCome, new String[]{"The Face"}, 1998); + + final String snowFallingonCedars = saveMovie(movies, "SnowFallingonCedars", "Snow Falling on Cedars", 1999, + "First loves last. Forever.").getId(); + final String ethanH = saveActor(actors, "EthanH", "Ethan Hawke", 1970).getId(); + final String rickY = saveActor(actors, "RickY", "Rick Yune", 1971).getId(); + final String jamesC = saveActor(actors, "JamesC", "James Cromwell", 1940).getId(); + saveActsIn(actsIn, ethanH, snowFallingonCedars, new String[]{"Ishmael Chambers"}, 1999); + saveActsIn(actsIn, rickY, snowFallingonCedars, new String[]{"Kazuo Miyamoto"}, 1999); + saveActsIn(actsIn, maxS, snowFallingonCedars, new String[]{"Nels Gudmundsson"}, 1999); + saveActsIn(actsIn, jamesC, snowFallingonCedars, new String[]{"Judge Fielding"}, 1999); + + final String youveGotMail = saveMovie(movies, "YouveGotMail", "You've Got Mail", 1998, + "At odds in life... in love on-line.").getId(); + final String parkerP = saveActor(actors, "ParkerP", "Parker Posey", 1968).getId(); + final String daveC = saveActor(actors, "DaveC", "Dave Chappelle", 1973).getId(); + final String steveZ = saveActor(actors, "SteveZ", "Steve Zahn", 1967).getId(); + final String tomH = saveActor(actors, "TomH", "Tom Hanks", 1956).getId(); + saveActsIn(actsIn, tomH, youveGotMail, new String[]{"Joe Fox"}, 1998); + saveActsIn(actsIn, megR, youveGotMail, new String[]{"Kathleen Kelly"}, 1998); + saveActsIn(actsIn, gregK, youveGotMail, new String[]{"Frank Navasky"}, 1998); + saveActsIn(actsIn, parkerP, youveGotMail, new String[]{"Patricia Eden"}, 1998); + saveActsIn(actsIn, daveC, youveGotMail, new String[]{"Kevin Jackson"}, 1998); + saveActsIn(actsIn, steveZ, youveGotMail, new String[]{"George Pappas"}, 1998); + + final String sleeplessInSeattle = saveMovie(movies, "SleeplessInSeattle", "Sleepless in Seattle", 1993, + "What if someone you never met, someone you never saw, someone you never knew was the only someone for you?") + .getId(); + final String ritaW = saveActor(actors, "RitaW", "Rita Wilson", 1956).getId(); + final String billPull = saveActor(actors, "BillPull", "Bill Pullman", 1953).getId(); + final String victorG = saveActor(actors, "VictorG", "Victor Garber", 1949).getId(); + final String rosieO = saveActor(actors, "RosieO", "Rosie O'Donnell", 1962).getId(); + saveActsIn(actsIn, tomH, sleeplessInSeattle, new String[]{"Sam Baldwin"}, 1993); + saveActsIn(actsIn, megR, sleeplessInSeattle, new String[]{"Annie Reed"}, 1993); + saveActsIn(actsIn, ritaW, sleeplessInSeattle, new String[]{"Suzy"}, 1993); + saveActsIn(actsIn, billPull, sleeplessInSeattle, new String[]{"Walter"}, 1993); + saveActsIn(actsIn, victorG, sleeplessInSeattle, new String[]{"Greg"}, 1993); + saveActsIn(actsIn, rosieO, sleeplessInSeattle, new String[]{"Becky"}, 1993); + + final String joeVersustheVolcano = saveMovie(movies, "JoeVersustheVolcano", "Joe Versus the Volcano", 1990, + "A story of love, lava and burning desire.").getId(); + final String nathan = saveActor(actors, "Nathan", "Nathan Lane", 1956).getId(); + saveActsIn(actsIn, tomH, joeVersustheVolcano, new String[]{"Joe Banks"}, 1990); + saveActsIn(actsIn, megR, joeVersustheVolcano, + new String[]{"DeDe', 'Angelica Graynamore', 'Patricia Graynamore"}, 1990); + saveActsIn(actsIn, nathan, joeVersustheVolcano, new String[]{"Baw"}, 1990); + + final String whenHarryMetSally = saveMovie(movies, "WhenHarryMetSally", "When Harry Met Sally", 1998, + "At odds in life... in love on-line.").getId(); + final String billyC = saveActor(actors, "BillyC", "Billy Crystal", 1948).getId(); + final String carrieF = saveActor(actors, "CarrieF", "Carrie Fisher", 1956).getId(); + final String brunoK = saveActor(actors, "BrunoK", "Bruno Kirby", 1949).getId(); + saveActsIn(actsIn, billyC, whenHarryMetSally, new String[]{"Harry Burns"}, 1998); + saveActsIn(actsIn, megR, whenHarryMetSally, new String[]{"Sally Albright"}, 1998); + saveActsIn(actsIn, carrieF, whenHarryMetSally, new String[]{"Marie"}, 1998); + saveActsIn(actsIn, brunoK, whenHarryMetSally, new String[]{"Jess"}, 1998); + } } diff --git a/src/test/java/com/arangodb/example/graph/BaseGraphTest.java b/src/test/java/com/arangodb/example/graph/BaseGraphTest.java index 69c2912fc..0c488aef7 100644 --- a/src/test/java/com/arangodb/example/graph/BaseGraphTest.java +++ b/src/test/java/com/arangodb/example/graph/BaseGraphTest.java @@ -35,84 +35,78 @@ /** * @author Mark Vollmary - * */ public abstract class BaseGraphTest { - protected static final String TEST_DB = "java_driver_graph_test_db"; - protected static ArangoDB arangoDB; - protected static ArangoDatabase db; - protected static final String GRAPH_NAME = "traversalGraph"; - protected static final String EDGE_COLLECTION_NAME = "edges"; - protected static final String VERTEXT_COLLECTION_NAME = "circles"; - - @BeforeClass - public static void init() { - if (arangoDB == null) { - arangoDB = new ArangoDB.Builder().build(); - } - try { - arangoDB.db(TEST_DB).drop(); - } catch (final ArangoDBException e) { - } - arangoDB.createDatabase(TEST_DB); - BaseGraphTest.db = arangoDB.db(TEST_DB); - - final Collection edgeDefinitions = new ArrayList(); - final EdgeDefinition edgeDefinition = new EdgeDefinition().collection(EDGE_COLLECTION_NAME) - .from(VERTEXT_COLLECTION_NAME).to(VERTEXT_COLLECTION_NAME); - edgeDefinitions.add(edgeDefinition); - try { - db.createGraph(GRAPH_NAME, edgeDefinitions, null); - addExampleElements(); - } catch (final ArangoDBException ex) { - - } - } - - @AfterClass - public static void shutdown() { - arangoDB.db(TEST_DB).drop(); - arangoDB.shutdown(); - arangoDB = null; - } - - private static void addExampleElements() throws ArangoDBException { - - // Add circle circles - final VertexEntity vA = createVertex(new Circle("A", "1")); - final VertexEntity vB = createVertex(new Circle("B", "2")); - final VertexEntity vC = createVertex(new Circle("C", "3")); - final VertexEntity vD = createVertex(new Circle("D", "4")); - final VertexEntity vE = createVertex(new Circle("E", "5")); - final VertexEntity vF = createVertex(new Circle("F", "6")); - final VertexEntity vG = createVertex(new Circle("G", "7")); - final VertexEntity vH = createVertex(new Circle("H", "8")); - final VertexEntity vI = createVertex(new Circle("I", "9")); - final VertexEntity vJ = createVertex(new Circle("J", "10")); - final VertexEntity vK = createVertex(new Circle("K", "11")); - - // Add relevant edges - left branch: - saveEdge(new CircleEdge(vA.getId(), vB.getId(), false, true, "left_bar")); - saveEdge(new CircleEdge(vB.getId(), vC.getId(), false, true, "left_blarg")); - saveEdge(new CircleEdge(vC.getId(), vD.getId(), false, true, "left_blorg")); - saveEdge(new CircleEdge(vB.getId(), vE.getId(), false, true, "left_blub")); - saveEdge(new CircleEdge(vE.getId(), vF.getId(), false, true, "left_schubi")); - - // Add relevant edges - right branch: - saveEdge(new CircleEdge(vA.getId(), vG.getId(), false, true, "right_foo")); - saveEdge(new CircleEdge(vG.getId(), vH.getId(), false, true, "right_blob")); - saveEdge(new CircleEdge(vH.getId(), vI.getId(), false, true, "right_blub")); - saveEdge(new CircleEdge(vG.getId(), vJ.getId(), false, true, "right_zip")); - saveEdge(new CircleEdge(vJ.getId(), vK.getId(), false, true, "right_zup")); - } - - private static EdgeEntity saveEdge(final CircleEdge edge) throws ArangoDBException { - return db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).insertEdge(edge); - } - - private static VertexEntity createVertex(final Circle vertex) throws ArangoDBException { - return db.graph(GRAPH_NAME).vertexCollection(VERTEXT_COLLECTION_NAME).insertVertex(vertex); - } + protected static final String TEST_DB = "java_driver_graph_test_db"; + protected static ArangoDB arangoDB; + protected static ArangoDatabase db; + protected static final String GRAPH_NAME = "traversalGraph"; + protected static final String EDGE_COLLECTION_NAME = "edges"; + protected static final String VERTEXT_COLLECTION_NAME = "circles"; + + @BeforeClass + public static void init() { + if (arangoDB == null) { + arangoDB = new ArangoDB.Builder().build(); + } + if (arangoDB.db(TEST_DB).exists()) + arangoDB.db(TEST_DB).drop(); + arangoDB.createDatabase(TEST_DB); + BaseGraphTest.db = arangoDB.db(TEST_DB); + + final Collection edgeDefinitions = new ArrayList(); + final EdgeDefinition edgeDefinition = new EdgeDefinition().collection(EDGE_COLLECTION_NAME) + .from(VERTEXT_COLLECTION_NAME).to(VERTEXT_COLLECTION_NAME); + edgeDefinitions.add(edgeDefinition); + if (!db.graph(GRAPH_NAME).exists()) + db.createGraph(GRAPH_NAME, edgeDefinitions, null); + addExampleElements(); + } + + @AfterClass + public static void shutdown() { + arangoDB.db(TEST_DB).drop(); + arangoDB.shutdown(); + arangoDB = null; + } + + private static void addExampleElements() throws ArangoDBException { + + // Add circle circles + final VertexEntity vA = createVertex(new Circle("A", "1")); + final VertexEntity vB = createVertex(new Circle("B", "2")); + final VertexEntity vC = createVertex(new Circle("C", "3")); + final VertexEntity vD = createVertex(new Circle("D", "4")); + final VertexEntity vE = createVertex(new Circle("E", "5")); + final VertexEntity vF = createVertex(new Circle("F", "6")); + final VertexEntity vG = createVertex(new Circle("G", "7")); + final VertexEntity vH = createVertex(new Circle("H", "8")); + final VertexEntity vI = createVertex(new Circle("I", "9")); + final VertexEntity vJ = createVertex(new Circle("J", "10")); + final VertexEntity vK = createVertex(new Circle("K", "11")); + + // Add relevant edges - left branch: + saveEdge(new CircleEdge(vA.getId(), vB.getId(), false, true, "left_bar")); + saveEdge(new CircleEdge(vB.getId(), vC.getId(), false, true, "left_blarg")); + saveEdge(new CircleEdge(vC.getId(), vD.getId(), false, true, "left_blorg")); + saveEdge(new CircleEdge(vB.getId(), vE.getId(), false, true, "left_blub")); + saveEdge(new CircleEdge(vE.getId(), vF.getId(), false, true, "left_schubi")); + + // Add relevant edges - right branch: + saveEdge(new CircleEdge(vA.getId(), vG.getId(), false, true, "right_foo")); + saveEdge(new CircleEdge(vG.getId(), vH.getId(), false, true, "right_blob")); + saveEdge(new CircleEdge(vH.getId(), vI.getId(), false, true, "right_blub")); + saveEdge(new CircleEdge(vG.getId(), vJ.getId(), false, true, "right_zip")); + saveEdge(new CircleEdge(vJ.getId(), vK.getId(), false, true, "right_zup")); + } + + private static EdgeEntity saveEdge(final CircleEdge edge) throws ArangoDBException { + return db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).insertEdge(edge); + } + + private static VertexEntity createVertex(final Circle vertex) throws ArangoDBException { + return db.graph(GRAPH_NAME).vertexCollection(VERTEXT_COLLECTION_NAME).insertVertex(vertex); + } } diff --git a/src/test/java/com/arangodb/internal/velocystream/CommunicationTest.java b/src/test/java/com/arangodb/internal/velocystream/CommunicationTest.java index 50a263923..1bd233568 100644 --- a/src/test/java/com/arangodb/internal/velocystream/CommunicationTest.java +++ b/src/test/java/com/arangodb/internal/velocystream/CommunicationTest.java @@ -37,150 +37,129 @@ /** * @author Mark Vollmary - * */ public class CommunicationTest { - private static final String FAST = "fast"; - private static final String SLOW = "slow"; - - @Test - public void chunkSizeSmall() { - final ArangoDB arangoDB = new ArangoDB.Builder().chunksize(20).build(); - final ArangoDBVersion version = arangoDB.getVersion(); - assertThat(version, is(notNullValue())); - } - - @Test - public void multiThread() throws Exception { - final ArangoDB arangoDB = new ArangoDB.Builder().build(); - arangoDB.getVersion();// authentication - - final Collection result = new ConcurrentLinkedQueue(); - final Thread fast = new Thread() { - @Override - public void run() { - try { - arangoDB.db().query("return sleep(1)", null, null, null); - result.add(FAST); - } catch (final ArangoDBException e) { - } - } - }; - final Thread slow = new Thread() { - @Override - public void run() { - try { - arangoDB.db().query("return sleep(4)", null, null, null); - result.add(SLOW); - } catch (final ArangoDBException e) { - } - } - }; - slow.start(); - Thread.sleep(1000); - fast.start(); - - slow.join(); - fast.join(); - - assertThat(result.size(), is(2)); - final Iterator iterator = result.iterator(); - assertThat(iterator.next(), is(FAST)); - assertThat(iterator.next(), is(SLOW)); - } - - @Test - public void multiThreadSameDatabases() throws Exception { - final ArangoDB arangoDB = new ArangoDB.Builder().build(); - arangoDB.getVersion();// authentication - - final ArangoDatabase db = arangoDB.db(); - - final Collection result = new ConcurrentLinkedQueue(); - final Thread t1 = new Thread() { - @Override - public void run() { - try { - db.query("return sleep(1)", null, null, null); - result.add("1"); - } catch (final ArangoDBException e) { - e.printStackTrace(System.err); - } - } - }; - final Thread t2 = new Thread() { - @Override - public void run() { - try { - db.query("return sleep(1)", null, null, null); - result.add("1"); - } catch (final ArangoDBException e) { - e.printStackTrace(System.err); - } - } - }; - t2.start(); - t1.start(); - t2.join(); - t1.join(); - assertThat(result.size(), is(2)); - } - - @Test - public void multiThreadMultiDatabases() throws Exception { - final ArangoDB arangoDB = new ArangoDB.Builder().build(); - arangoDB.getVersion();// authentication - - try { - arangoDB.createDatabase("db1"); - arangoDB.createDatabase("db2"); - final ArangoDatabase db1 = arangoDB.db("db1"); - final ArangoDatabase db2 = arangoDB.db("db2"); - - final Collection result = new ConcurrentLinkedQueue(); - final Thread t1 = new Thread() { - @Override - public void run() { - try { - db1.query("return sleep(1)", null, null, null); - result.add("1"); - } catch (final ArangoDBException e) { - } - } - }; - final Thread t2 = new Thread() { - @Override - public void run() { - try { - db2.query("return sleep(1)", null, null, null); - result.add("1"); - } catch (final ArangoDBException e) { - } - } - }; - t2.start(); - t1.start(); - t2.join(); - t1.join(); - assertThat(result.size(), is(2)); - } finally { - arangoDB.db("db1").drop(); - arangoDB.db("db2").drop(); - } - } - - @Test - public void minOneConnection() { - final ArangoDB arangoDB = new ArangoDB.Builder().maxConnections(0).build(); - final ArangoDBVersion version = arangoDB.getVersion(); - assertThat(version, is(notNullValue())); - } - - @Test - public void defaultMaxConnection() { - final ArangoDB arangoDB = new ArangoDB.Builder().maxConnections(null).build(); - final ArangoDBVersion version = arangoDB.getVersion(); - assertThat(version, is(notNullValue())); - } + private static final String FAST = "fast"; + private static final String SLOW = "slow"; + + @Test + public void chunkSizeSmall() { + final ArangoDB arangoDB = new ArangoDB.Builder().chunksize(20).build(); + final ArangoDBVersion version = arangoDB.getVersion(); + assertThat(version, is(notNullValue())); + } + + @Test + public void multiThread() throws Exception { + final ArangoDB arangoDB = new ArangoDB.Builder().build(); + arangoDB.getVersion();// authentication + + final Collection result = new ConcurrentLinkedQueue(); + final Thread fast = new Thread() { + @Override + public void run() { + arangoDB.db().query("return sleep(1)", null, null, null); + result.add(FAST); + } + }; + final Thread slow = new Thread() { + @Override + public void run() { + arangoDB.db().query("return sleep(4)", null, null, null); + result.add(SLOW); + } + }; + slow.start(); + Thread.sleep(1000); + fast.start(); + + slow.join(); + fast.join(); + + assertThat(result.size(), is(2)); + final Iterator iterator = result.iterator(); + assertThat(iterator.next(), is(FAST)); + assertThat(iterator.next(), is(SLOW)); + } + + @Test + public void multiThreadSameDatabases() throws Exception { + final ArangoDB arangoDB = new ArangoDB.Builder().build(); + arangoDB.getVersion();// authentication + + final ArangoDatabase db = arangoDB.db(); + + final Collection result = new ConcurrentLinkedQueue(); + final Thread t1 = new Thread() { + @Override + public void run() { + db.query("return sleep(1)", null, null, null); + result.add("1"); + } + }; + final Thread t2 = new Thread() { + @Override + public void run() { + db.query("return sleep(1)", null, null, null); + result.add("1"); + } + }; + t2.start(); + t1.start(); + t2.join(); + t1.join(); + assertThat(result.size(), is(2)); + } + + @Test + public void multiThreadMultiDatabases() throws Exception { + final ArangoDB arangoDB = new ArangoDB.Builder().build(); + arangoDB.getVersion();// authentication + + try { + arangoDB.createDatabase("db1"); + arangoDB.createDatabase("db2"); + final ArangoDatabase db1 = arangoDB.db("db1"); + final ArangoDatabase db2 = arangoDB.db("db2"); + + final Collection result = new ConcurrentLinkedQueue(); + final Thread t1 = new Thread() { + @Override + public void run() { + db1.query("return sleep(1)", null, null, null); + result.add("1"); + } + }; + final Thread t2 = new Thread() { + @Override + public void run() { + db2.query("return sleep(1)", null, null, null); + result.add("1"); + } + }; + t2.start(); + t1.start(); + t2.join(); + t1.join(); + assertThat(result.size(), is(2)); + } finally { + arangoDB.db("db1").drop(); + arangoDB.db("db2").drop(); + } + } + + @Test + public void minOneConnection() { + final ArangoDB arangoDB = new ArangoDB.Builder().maxConnections(0).build(); + final ArangoDBVersion version = arangoDB.getVersion(); + assertThat(version, is(notNullValue())); + } + + @Test + public void defaultMaxConnection() { + final ArangoDB arangoDB = new ArangoDB.Builder().maxConnections(null).build(); + final ArangoDBVersion version = arangoDB.getVersion(); + assertThat(version, is(notNullValue())); + } } diff --git a/src/test/java/com/arangodb/serde/CustomSerdeTest.java b/src/test/java/com/arangodb/serde/CustomSerdeTest.java index 5549be407..a83271395 100644 --- a/src/test/java/com/arangodb/serde/CustomSerdeTest.java +++ b/src/test/java/com/arangodb/serde/CustomSerdeTest.java @@ -75,7 +75,8 @@ public void init() { @After public void shutdown() { - db.drop(); + if (db.exists()) + db.drop(); } @Test From b5ac20a90636220f5e6fb4b709a50e7f41c194f6 Mon Sep 17 00:00:00 2001 From: michele Date: Mon, 2 Sep 2019 12:27:30 +0200 Subject: [PATCH 2/4] tests code analysis fixes --- .../com/arangodb/ArangoCollectionTest.java | 159 ++++++------ .../java/com/arangodb/ArangoCursorTest.java | 243 ++---------------- src/test/java/com/arangodb/ArangoDBTest.java | 10 +- .../java/com/arangodb/ArangoDatabaseTest.java | 139 +++++----- .../arangodb/ArangoEdgeCollectionTest.java | 5 +- .../java/com/arangodb/ArangoGraphTest.java | 6 +- src/test/java/com/arangodb/ArangoSslTest.java | 2 +- .../arangodb/ArangoVertexCollectionTest.java | 5 +- src/test/java/com/arangodb/BaseTest.java | 23 +- src/test/java/com/arangodb/DocumentTest.java | 2 +- src/test/java/com/arangodb/UserAuthTest.java | 31 +-- .../com/arangodb/example/ExampleBase.java | 5 +- ...AqlQueryWithSpecialReturnTypesExample.java | 1 - .../arangodb/example/document/TestEntity.java | 1 + .../graph/AQLActorsAndMoviesExample.java | 25 +- .../arangodb/example/graph/BaseGraphTest.java | 19 +- .../com/arangodb/example/graph/Circle.java | 3 +- .../arangodb/example/graph/CircleEdge.java | 3 +- .../graph/ShortestPathInAQLExample.java | 9 +- .../arangodb/internal/DocumentCacheTest.java | 7 +- .../velocystream/CommunicationTest.java | 73 ++---- .../com/arangodb/serde/CustomSerdeTest.java | 2 +- .../util/ArangoSerializationTest.java | 4 +- 23 files changed, 271 insertions(+), 506 deletions(-) diff --git a/src/test/java/com/arangodb/ArangoCollectionTest.java b/src/test/java/com/arangodb/ArangoCollectionTest.java index 80ff8c7f5..9b8c64a70 100644 --- a/src/test/java/com/arangodb/ArangoCollectionTest.java +++ b/src/test/java/com/arangodb/ArangoCollectionTest.java @@ -290,6 +290,7 @@ public void getDocumentWrongKey() { db.collection(COLLECTION_NAME).getDocument("no/no", BaseDocument.class); } + @Test public void getDocumentDirtyRead() { final BaseDocument doc = new BaseDocument(); db.collection(COLLECTION_NAME).insertDocument(doc); @@ -300,7 +301,7 @@ public void getDocumentDirtyRead() { @Test public void getDocuments() { - final Collection values = new ArrayList(); + final Collection values = new ArrayList<>(); values.add(new BaseDocument("1")); values.add(new BaseDocument("2")); values.add(new BaseDocument("3")); @@ -317,7 +318,7 @@ public void getDocuments() { @Test public void getDocumentsDirtyRead() { - final Collection values = new ArrayList(); + final Collection values = new ArrayList<>(); values.add(new BaseDocument("1")); values.add(new BaseDocument("2")); values.add(new BaseDocument("3")); @@ -575,7 +576,7 @@ public void updateDocumentSerializeNullFalse() { @Test public void updateDocumentMergeObjectsTrue() { final BaseDocument doc = new BaseDocument(); - final Map a = new HashMap(); + final Map a = new HashMap<>(); a.put("a", "test"); doc.addAttribute("a", a); final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) @@ -605,7 +606,7 @@ public void updateDocumentMergeObjectsTrue() { @Test public void updateDocumentMergeObjectsFalse() { final BaseDocument doc = new BaseDocument(); - final Map a = new HashMap(); + final Map a = new HashMap<>(); a.put("a", "test"); doc.addAttribute("a", a); final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) @@ -667,7 +668,7 @@ public void updateDocumentsSilent() { final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) .insertDocument(new BaseDocument()); final MultiDocumentEntity> info = db.collection(COLLECTION_NAME) - .updateDocuments(Arrays.asList(new BaseDocument(createResult.getKey())), + .updateDocuments(Collections.singletonList(new BaseDocument(createResult.getKey())), new DocumentUpdateOptions().silent(true)); assertThat(info, is(notNullValue())); assertThat(info.getDocuments().isEmpty(), is(true)); @@ -883,7 +884,7 @@ public void replaceDocumentsSilent() { final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) .insertDocument(new BaseDocument()); final MultiDocumentEntity> info = db.collection(COLLECTION_NAME) - .replaceDocuments(Arrays.asList(new BaseDocument(createResult.getKey())), + .replaceDocuments(Collections.singletonList(new BaseDocument(createResult.getKey())), new DocumentReplaceOptions().silent(true)); assertThat(info, is(notNullValue())); assertThat(info.getDocuments().isEmpty(), is(true)); @@ -961,7 +962,7 @@ public void deleteDocumentsSilent() { final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) .insertDocument(new BaseDocument()); final MultiDocumentEntity> info = db.collection(COLLECTION_NAME) - .deleteDocuments(Arrays.asList(createResult.getKey()), BaseDocument.class, + .deleteDocuments(Collections.singletonList(createResult.getKey()), BaseDocument.class, new DocumentDeleteOptions().silent(true)); assertThat(info, is(notNullValue())); assertThat(info.getDocuments().isEmpty(), is(true)); @@ -971,7 +972,7 @@ public void deleteDocumentsSilent() { @Test public void getIndex() { - final Collection fields = new ArrayList(); + final Collection fields = new ArrayList<>(); fields.add("a"); final IndexEntity createResult = db.collection(COLLECTION_NAME).ensureHashIndex(fields, null); final IndexEntity readResult = db.collection(COLLECTION_NAME).getIndex(createResult.getId()); @@ -981,7 +982,7 @@ public void getIndex() { @Test public void getIndexByKey() { - final Collection fields = new ArrayList(); + final Collection fields = new ArrayList<>(); fields.add("a"); final IndexEntity createResult = db.collection(COLLECTION_NAME).ensureHashIndex(fields, null); final IndexEntity readResult = db.collection(COLLECTION_NAME).getIndex(createResult.getId().split("/")[1]); @@ -991,7 +992,7 @@ public void getIndexByKey() { @Test(expected = ArangoDBException.class) public void deleteIndex() { - final Collection fields = new ArrayList(); + final Collection fields = new ArrayList<>(); fields.add("a"); final IndexEntity createResult = db.collection(COLLECTION_NAME).ensureHashIndex(fields, null); final String id = db.collection(COLLECTION_NAME).deleteIndex(createResult.getId()); @@ -1001,7 +1002,7 @@ public void deleteIndex() { @Test(expected = ArangoDBException.class) public void deleteIndexByKey() { - final Collection fields = new ArrayList(); + final Collection fields = new ArrayList<>(); fields.add("a"); final IndexEntity createResult = db.collection(COLLECTION_NAME).ensureHashIndex(fields, null); final String id = db.collection(COLLECTION_NAME).deleteIndex(createResult.getId().split("/")[1]); @@ -1011,7 +1012,7 @@ public void deleteIndexByKey() { @Test public void createHashIndex() { - final Collection fields = new ArrayList(); + final Collection fields = new ArrayList<>(); fields.add("a"); fields.add("b"); final IndexEntity indexResult = db.collection(COLLECTION_NAME).ensureHashIndex(fields, null); @@ -1039,7 +1040,7 @@ public void createHashIndexWithOptions() { final HashIndexOptions options = new HashIndexOptions(); options.name("myHashIndex"); - final Collection fields = new ArrayList(); + final Collection fields = new ArrayList<>(); fields.add("a"); fields.add("b"); final IndexEntity indexResult = db.collection(COLLECTION_NAME).ensureHashIndex(fields, options); @@ -1061,7 +1062,7 @@ public void createHashIndexWithOptions() { @Test public void createGeoIndex() { - final Collection fields = new ArrayList(); + final Collection fields = new ArrayList<>(); fields.add("a"); final IndexEntity indexResult = db.collection(COLLECTION_NAME).ensureGeoIndex(fields, null); assertThat(indexResult, is(notNullValue())); @@ -1087,7 +1088,7 @@ public void createGeoIndexWithOptions() { final GeoIndexOptions options = new GeoIndexOptions(); options.name("myGeoIndex1"); - final Collection fields = new ArrayList(); + final Collection fields = new ArrayList<>(); fields.add("a"); final IndexEntity indexResult = db.collection(COLLECTION_NAME).ensureGeoIndex(fields, options); assertThat(indexResult, is(notNullValue())); @@ -1107,7 +1108,7 @@ public void createGeoIndexWithOptions() { @Test public void createGeo2Index() { - final Collection fields = new ArrayList(); + final Collection fields = new ArrayList<>(); fields.add("a"); fields.add("b"); final IndexEntity indexResult = db.collection(COLLECTION_NAME).ensureGeoIndex(fields, null); @@ -1135,7 +1136,7 @@ public void createGeo2IndexWithOptions() { final GeoIndexOptions options = new GeoIndexOptions(); options.name("myGeoIndex2"); - final Collection fields = new ArrayList(); + final Collection fields = new ArrayList<>(); fields.add("a"); fields.add("b"); final IndexEntity indexResult = db.collection(COLLECTION_NAME).ensureGeoIndex(fields, options); @@ -1157,7 +1158,7 @@ public void createGeo2IndexWithOptions() { @Test public void createSkiplistIndex() { - final Collection fields = new ArrayList(); + final Collection fields = new ArrayList<>(); fields.add("a"); fields.add("b"); final IndexEntity indexResult = db.collection(COLLECTION_NAME).ensureSkiplistIndex(fields, null); @@ -1182,7 +1183,7 @@ public void createSkiplistIndexWithOptions() { final SkiplistIndexOptions options = new SkiplistIndexOptions(); options.name("mySkiplistIndex"); - final Collection fields = new ArrayList(); + final Collection fields = new ArrayList<>(); fields.add("a"); fields.add("b"); final IndexEntity indexResult = db.collection(COLLECTION_NAME).ensureSkiplistIndex(fields, options); @@ -1201,7 +1202,7 @@ public void createSkiplistIndexWithOptions() { @Test public void createPersistentIndex() { - final Collection fields = new ArrayList(); + final Collection fields = new ArrayList<>(); fields.add("a"); fields.add("b"); final IndexEntity indexResult = db.collection(COLLECTION_NAME).ensurePersistentIndex(fields, null); @@ -1226,7 +1227,7 @@ public void createPersistentIndexWithOptions() { final PersistentIndexOptions options = new PersistentIndexOptions(); options.name("myPersistentIndex"); - final Collection fields = new ArrayList(); + final Collection fields = new ArrayList<>(); fields.add("a"); fields.add("b"); final IndexEntity indexResult = db.collection(COLLECTION_NAME).ensurePersistentIndex(fields, options); @@ -1245,7 +1246,7 @@ public void createPersistentIndexWithOptions() { @Test public void createFulltextIndex() { - final Collection fields = new ArrayList(); + final Collection fields = new ArrayList<>(); fields.add("a"); final IndexEntity indexResult = db.collection(COLLECTION_NAME).ensureFulltextIndex(fields, null); assertThat(indexResult, is(notNullValue())); @@ -1267,7 +1268,7 @@ public void createFulltextIndexWithOptions() { final FulltextIndexOptions options = new FulltextIndexOptions(); options.name("myFulltextIndex"); - final Collection fields = new ArrayList(); + final Collection fields = new ArrayList<>(); fields.add("a"); final IndexEntity indexResult = db.collection(COLLECTION_NAME).ensureFulltextIndex(fields, options); assertThat(indexResult, is(notNullValue())); @@ -1286,7 +1287,7 @@ public void createTtlIndexWithoutOptions() { if (!requireVersion(3, 5)) { return; } - final Collection fields = new ArrayList(); + final Collection fields = new ArrayList<>(); fields.add("a"); try { db.collection(COLLECTION_NAME).ensureTtlIndex(fields, null); @@ -1303,7 +1304,7 @@ public void createTtlIndexWithOptions() { if (!requireVersion(3, 5)) { return; } - final Collection fields = new ArrayList(); + final Collection fields = new ArrayList<>(); fields.add("a"); final TtlIndexOptions options = new TtlIndexOptions(); @@ -1322,7 +1323,7 @@ public void createTtlIndexWithOptions() { @Test public void getIndexes() { - final Collection fields = new ArrayList(); + final Collection fields = new ArrayList<>(); fields.add("a"); db.collection(COLLECTION_NAME).ensureHashIndex(fields, null); final Collection indexes = db.collection(COLLECTION_NAME).getIndexes(); @@ -1430,7 +1431,7 @@ public void documentExistsIfNoneMatchFail() { @Test public void insertDocuments() { - final Collection values = new ArrayList(); + final Collection values = new ArrayList<>(); values.add(new BaseDocument()); values.add(new BaseDocument()); values.add(new BaseDocument()); @@ -1475,7 +1476,7 @@ public void insertDocumentsOverwrite() { @Test public void insertDocumentsJson() { - final Collection values = new ArrayList(); + final Collection values = new ArrayList<>(); values.add("{}"); values.add("{}"); values.add("{}"); @@ -1490,7 +1491,7 @@ public void insertDocumentsJson() { @Test public void insertDocumentsOne() { - final Collection values = new ArrayList(); + final Collection values = new ArrayList<>(); values.add(new BaseDocument()); final MultiDocumentEntity> docs = db.collection(COLLECTION_NAME) .insertDocuments(values, null); @@ -1503,7 +1504,7 @@ public void insertDocumentsOne() { @Test public void insertDocumentsEmpty() { - final Collection values = new ArrayList(); + final Collection values = new ArrayList<>(); final MultiDocumentEntity> docs = db.collection(COLLECTION_NAME) .insertDocuments(values, null); assertThat(docs, is(notNullValue())); @@ -1515,7 +1516,7 @@ public void insertDocumentsEmpty() { @Test public void insertDocumentsReturnNew() { - final Collection values = new ArrayList(); + final Collection values = new ArrayList<>(); values.add(new BaseDocument()); values.add(new BaseDocument()); values.add(new BaseDocument()); @@ -1537,7 +1538,7 @@ public void insertDocumentsReturnNew() { @Test public void insertDocumentsFail() { - final Collection values = new ArrayList(); + final Collection values = new ArrayList<>(); values.add(new BaseDocument("1")); values.add(new BaseDocument("2")); values.add(new BaseDocument("2")); @@ -1553,7 +1554,7 @@ public void insertDocumentsFail() { @Test public void importDocuments() { - final Collection values = new ArrayList(); + final Collection values = new ArrayList<>(); values.add(new BaseDocument()); values.add(new BaseDocument()); values.add(new BaseDocument()); @@ -1569,7 +1570,7 @@ public void importDocuments() { @Test public void importDocumentsJsonList() { - final Collection values = new ArrayList(); + final Collection values = new ArrayList<>(); values.add("{}"); values.add("{}"); values.add("{}"); @@ -1585,7 +1586,7 @@ public void importDocumentsJsonList() { @Test public void importDocumentsDuplicateDefaultError() { - final Collection values = new ArrayList(); + final Collection values = new ArrayList<>(); values.add(new BaseDocument("1")); values.add(new BaseDocument("2")); values.add(new BaseDocument("2")); @@ -1601,7 +1602,7 @@ public void importDocumentsDuplicateDefaultError() { @Test public void importDocumentsDuplicateError() { - final Collection values = new ArrayList(); + final Collection values = new ArrayList<>(); values.add(new BaseDocument("1")); values.add(new BaseDocument("2")); values.add(new BaseDocument("2")); @@ -1618,7 +1619,7 @@ public void importDocumentsDuplicateError() { @Test public void importDocumentsDuplicateIgnore() { - final Collection values = new ArrayList(); + final Collection values = new ArrayList<>(); values.add(new BaseDocument("1")); values.add(new BaseDocument("2")); values.add(new BaseDocument("2")); @@ -1635,7 +1636,7 @@ public void importDocumentsDuplicateIgnore() { @Test public void importDocumentsDuplicateReplace() { - final Collection values = new ArrayList(); + final Collection values = new ArrayList<>(); values.add(new BaseDocument("1")); values.add(new BaseDocument("2")); values.add(new BaseDocument("2")); @@ -1652,7 +1653,7 @@ public void importDocumentsDuplicateReplace() { @Test public void importDocumentsDuplicateUpdate() { - final Collection values = new ArrayList(); + final Collection values = new ArrayList<>(); values.add(new BaseDocument("1")); values.add(new BaseDocument("2")); values.add(new BaseDocument("2")); @@ -1669,7 +1670,7 @@ public void importDocumentsDuplicateUpdate() { @Test public void importDocumentsCompleteFail() { - final Collection values = new ArrayList(); + final Collection values = new ArrayList<>(); values.add(new BaseDocument("1")); values.add(new BaseDocument("2")); values.add(new BaseDocument("2")); @@ -1683,7 +1684,7 @@ public void importDocumentsCompleteFail() { @Test public void importDocumentsDetails() { - final Collection values = new ArrayList(); + final Collection values = new ArrayList<>(); values.add(new BaseDocument("1")); values.add(new BaseDocument("2")); values.add(new BaseDocument("2")); @@ -1705,7 +1706,7 @@ public void importDocumentsOverwriteFalse() { collection.insertDocument(new BaseDocument()); assertThat(collection.count().getCount(), is(1L)); - final Collection values = new ArrayList(); + final Collection values = new ArrayList<>(); values.add(new BaseDocument()); values.add(new BaseDocument()); collection.importDocuments(values, new DocumentImportOptions().overwrite(false)); @@ -1718,7 +1719,7 @@ public void importDocumentsOverwriteTrue() { collection.insertDocument(new BaseDocument()); assertThat(collection.count().getCount(), is(1L)); - final Collection values = new ArrayList(); + final Collection values = new ArrayList<>(); values.add(new BaseDocument()); values.add(new BaseDocument()); collection.importDocuments(values, new DocumentImportOptions().overwrite(true)); @@ -1730,10 +1731,10 @@ public void importDocumentsFromToPrefix() { db.createCollection(COLLECTION_NAME + "_edge", new CollectionCreateOptions().type(CollectionType.EDGES)); final ArangoCollection collection = db.collection(COLLECTION_NAME + "_edge"); try { - final Collection values = new ArrayList(); + final Collection values = new ArrayList<>(); final String[] keys = {"1", "2"}; - for (int i = 0; i < keys.length; i++) { - values.add(new BaseEdgeDocument(keys[i], "from", "to")); + for (String s : keys) { + values.add(new BaseEdgeDocument(s, "from", "to")); } assertThat(values.size(), is(keys.length)); @@ -1741,8 +1742,8 @@ public void importDocumentsFromToPrefix() { .importDocuments(values, new DocumentImportOptions().fromPrefix("foo").toPrefix("bar")); assertThat(importResult, is(notNullValue())); assertThat(importResult.getCreated(), is(values.size())); - for (int i = 0; i < keys.length; i++) { - final BaseEdgeDocument doc = collection.getDocument(keys[i], BaseEdgeDocument.class); + for (String key : keys) { + final BaseEdgeDocument doc = collection.getDocument(key, BaseEdgeDocument.class); assertThat(doc, is(notNullValue())); assertThat(doc.getFrom(), is("foo/from")); assertThat(doc.getTo(), is("bar/to")); @@ -1894,8 +1895,8 @@ public void importDocumentsJsonFromToPrefix() { .importDocuments(values, new DocumentImportOptions().fromPrefix("foo").toPrefix("bar")); assertThat(importResult, is(notNullValue())); assertThat(importResult.getCreated(), is(2)); - for (int i = 0; i < keys.length; i++) { - final BaseEdgeDocument doc = collection.getDocument(keys[i], BaseEdgeDocument.class); + for (String key : keys) { + final BaseEdgeDocument doc = collection.getDocument(key, BaseEdgeDocument.class); assertThat(doc, is(notNullValue())); assertThat(doc.getFrom(), is("foo/from")); assertThat(doc.getTo(), is("bar/to")); @@ -1907,7 +1908,7 @@ public void importDocumentsJsonFromToPrefix() { @Test public void deleteDocumentsByKey() { - final Collection values = new ArrayList(); + final Collection values = new ArrayList<>(); { final BaseDocument e = new BaseDocument(); e.setKey("1"); @@ -1919,7 +1920,7 @@ public void deleteDocumentsByKey() { values.add(e); } db.collection(COLLECTION_NAME).insertDocuments(values, null); - final Collection keys = new ArrayList(); + final Collection keys = new ArrayList<>(); keys.add("1"); keys.add("2"); final MultiDocumentEntity> deleteResult = db.collection(COLLECTION_NAME) @@ -1934,7 +1935,7 @@ public void deleteDocumentsByKey() { @Test public void deleteDocumentsByDocuments() { - final Collection values = new ArrayList(); + final Collection values = new ArrayList<>(); { final BaseDocument e = new BaseDocument(); e.setKey("1"); @@ -1958,14 +1959,14 @@ public void deleteDocumentsByDocuments() { @Test public void deleteDocumentsByKeyOne() { - final Collection values = new ArrayList(); + final Collection values = new ArrayList<>(); { final BaseDocument e = new BaseDocument(); e.setKey("1"); values.add(e); } db.collection(COLLECTION_NAME).insertDocuments(values, null); - final Collection keys = new ArrayList(); + final Collection keys = new ArrayList<>(); keys.add("1"); final MultiDocumentEntity> deleteResult = db.collection(COLLECTION_NAME) .deleteDocuments(keys, null, null); @@ -1979,7 +1980,7 @@ public void deleteDocumentsByKeyOne() { @Test public void deleteDocumentsByDocumentOne() { - final Collection values = new ArrayList(); + final Collection values = new ArrayList<>(); { final BaseDocument e = new BaseDocument(); e.setKey("1"); @@ -1998,9 +1999,9 @@ public void deleteDocumentsByDocumentOne() { @Test public void deleteDocumentsEmpty() { - final Collection values = new ArrayList(); + final Collection values = new ArrayList<>(); db.collection(COLLECTION_NAME).insertDocuments(values, null); - final Collection keys = new ArrayList(); + final Collection keys = new ArrayList<>(); final MultiDocumentEntity> deleteResult = db.collection(COLLECTION_NAME) .deleteDocuments(keys, null, null); assertThat(deleteResult, is(notNullValue())); @@ -2010,9 +2011,9 @@ public void deleteDocumentsEmpty() { @Test public void deleteDocumentsByKeyNotExisting() { - final Collection values = new ArrayList(); + final Collection values = new ArrayList<>(); db.collection(COLLECTION_NAME).insertDocuments(values, null); - final Collection keys = new ArrayList(); + final Collection keys = new ArrayList<>(); keys.add("1"); keys.add("2"); final MultiDocumentEntity> deleteResult = db.collection(COLLECTION_NAME) @@ -2024,7 +2025,7 @@ public void deleteDocumentsByKeyNotExisting() { @Test public void deleteDocumentsByDocumentsNotExisting() { - final Collection values = new ArrayList(); + final Collection values = new ArrayList<>(); { final BaseDocument e = new BaseDocument(); e.setKey("1"); @@ -2044,7 +2045,7 @@ public void deleteDocumentsByDocumentsNotExisting() { @Test public void updateDocuments() { - final Collection values = new ArrayList(); + final Collection values = new ArrayList<>(); { final BaseDocument e = new BaseDocument(); e.setKey("1"); @@ -2056,7 +2057,7 @@ public void updateDocuments() { values.add(e); } db.collection(COLLECTION_NAME).insertDocuments(values, null); - final Collection updatedValues = new ArrayList(); + final Collection updatedValues = new ArrayList<>(); for (final BaseDocument i : values) { i.addAttribute("a", "test"); updatedValues.add(i); @@ -2069,14 +2070,14 @@ public void updateDocuments() { @Test public void updateDocumentsOne() { - final Collection values = new ArrayList(); + final Collection values = new ArrayList<>(); { final BaseDocument e = new BaseDocument(); e.setKey("1"); values.add(e); } db.collection(COLLECTION_NAME).insertDocuments(values, null); - final Collection updatedValues = new ArrayList(); + final Collection updatedValues = new ArrayList<>(); final BaseDocument first = values.iterator().next(); first.addAttribute("a", "test"); updatedValues.add(first); @@ -2088,7 +2089,7 @@ public void updateDocumentsOne() { @Test public void updateDocumentsEmpty() { - final Collection values = new ArrayList(); + final Collection values = new ArrayList<>(); final MultiDocumentEntity> updateResult = db.collection(COLLECTION_NAME) .updateDocuments(values, null); assertThat(updateResult.getDocuments().size(), is(0)); @@ -2097,12 +2098,12 @@ public void updateDocumentsEmpty() { @Test public void updateDocumentsWithoutKey() { - final Collection values = new ArrayList(); + final Collection values = new ArrayList<>(); { values.add(new BaseDocument("1")); } db.collection(COLLECTION_NAME).insertDocuments(values, null); - final Collection updatedValues = new ArrayList(); + final Collection updatedValues = new ArrayList<>(); for (final BaseDocument i : values) { i.addAttribute("a", "test"); updatedValues.add(i); @@ -2116,12 +2117,12 @@ public void updateDocumentsWithoutKey() { @Test public void updateDocumentsJson() { - final Collection values = new ArrayList(); + final Collection values = new ArrayList<>(); values.add("{\"_key\":\"1\"}"); values.add("{\"_key\":\"2\"}"); db.collection(COLLECTION_NAME).insertDocuments(values); - final Collection updatedValues = new ArrayList(); + final Collection updatedValues = new ArrayList<>(); updatedValues.add("{\"_key\":\"1\", \"foo\":\"bar\"}"); updatedValues.add("{\"_key\":\"2\", \"foo\":\"bar\"}"); final MultiDocumentEntity> updateResult = db.collection(COLLECTION_NAME) @@ -2132,13 +2133,13 @@ public void updateDocumentsJson() { @Test public void replaceDocuments() { - final Collection values = new ArrayList(); + final Collection values = new ArrayList<>(); { values.add(new BaseDocument("1")); values.add(new BaseDocument("2")); } db.collection(COLLECTION_NAME).insertDocuments(values, null); - final Collection updatedValues = new ArrayList(); + final Collection updatedValues = new ArrayList<>(); for (final BaseDocument i : values) { i.addAttribute("a", "test"); updatedValues.add(i); @@ -2151,14 +2152,14 @@ public void replaceDocuments() { @Test public void replaceDocumentsOne() { - final Collection values = new ArrayList(); + final Collection values = new ArrayList<>(); { final BaseDocument e = new BaseDocument(); e.setKey("1"); values.add(e); } db.collection(COLLECTION_NAME).insertDocuments(values, null); - final Collection updatedValues = new ArrayList(); + final Collection updatedValues = new ArrayList<>(); final BaseDocument first = values.iterator().next(); first.addAttribute("a", "test"); updatedValues.add(first); @@ -2170,7 +2171,7 @@ public void replaceDocumentsOne() { @Test public void replaceDocumentsEmpty() { - final Collection values = new ArrayList(); + final Collection values = new ArrayList<>(); final MultiDocumentEntity> updateResult = db.collection(COLLECTION_NAME) .updateDocuments(values, null); assertThat(updateResult.getDocuments().size(), is(0)); @@ -2179,12 +2180,12 @@ public void replaceDocumentsEmpty() { @Test public void replaceDocumentsWithoutKey() { - final Collection values = new ArrayList(); + final Collection values = new ArrayList<>(); { values.add(new BaseDocument("1")); } db.collection(COLLECTION_NAME).insertDocuments(values, null); - final Collection updatedValues = new ArrayList(); + final Collection updatedValues = new ArrayList<>(); for (final BaseDocument i : values) { i.addAttribute("a", "test"); updatedValues.add(i); @@ -2198,12 +2199,12 @@ public void replaceDocumentsWithoutKey() { @Test public void replaceDocumentsJson() { - final Collection values = new ArrayList(); + final Collection values = new ArrayList<>(); values.add("{\"_key\":\"1\"}"); values.add("{\"_key\":\"2\"}"); db.collection(COLLECTION_NAME).insertDocuments(values); - final Collection updatedValues = new ArrayList(); + final Collection updatedValues = new ArrayList<>(); updatedValues.add("{\"_key\":\"1\", \"foo\":\"bar\"}"); updatedValues.add("{\"_key\":\"2\", \"foo\":\"bar\"}"); final MultiDocumentEntity> updateResult = db.collection(COLLECTION_NAME) diff --git a/src/test/java/com/arangodb/ArangoCursorTest.java b/src/test/java/com/arangodb/ArangoCursorTest.java index a8de88f9a..e4288fc48 100644 --- a/src/test/java/com/arangodb/ArangoCursorTest.java +++ b/src/test/java/com/arangodb/ArangoCursorTest.java @@ -73,117 +73,42 @@ public void next() { @Test public void mapFilterCount() { final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); - final long count = cursor.map(new Function() { - @Override - public Long apply(final VPackSlice t) { - return t.getAsLong(); - } - }).filter(new Predicate() { - @Override - public boolean test(final Long t) { - return t < 50; - } - }).count(); + final long count = cursor.map(VPackSlice::getAsLong).filter(t -> t < 50).count(); assertThat(count, is(50L)); } @Test public void mapMapFilterCount() { final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); - final long count = cursor.map(new Function() { - @Override - public Long apply(final VPackSlice t) { - return t.getAsLong(); - } - }).map(new Function() { - @Override - public Long apply(final Long t) { - return t * 10; - } - }).filter(new Predicate() { - @Override - public boolean test(final Long t) { - return t < 500; - } - }).count(); + final long count = cursor.map(VPackSlice::getAsLong).map(t -> t * 10).filter(t -> t < 500).count(); assertThat(count, is(50L)); } @Test public void mapMapFilterFilterCount() { final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); - final long count = cursor.map(new Function() { - @Override - public Long apply(final VPackSlice t) { - return t.getAsLong(); - } - }).map(new Function() { - @Override - public Long apply(final Long t) { - return t * 10; - } - }).filter(new Predicate() { - @Override - public boolean test(final Long t) { - return t < 500; - } - }).filter(new Predicate() { - @Override - public boolean test(final Long t) { - return t < 250; - } - }).count(); + final long count = cursor.map(VPackSlice::getAsLong).map(t -> t * 10).filter(t -> t < 500).filter(t -> t < 250).count(); assertThat(count, is(25L)); } @Test public void mapFilterNext() { final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); - final long count = cursor.map(new Function() { - @Override - public Long apply(final VPackSlice t) { - return t.getAsLong(); - } - }).filter(new Predicate() { - @Override - public boolean test(final Long t) { - return t < 50; - } - }).iterator().next(); + final long count = cursor.map(VPackSlice::getAsLong).filter(t -> t < 50).iterator().next(); assertThat(count, is(0L)); } @Test public void mapFilterFirst() { final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); - final long count = cursor.map(new Function() { - @Override - public Long apply(final VPackSlice t) { - return t.getAsLong(); - } - }).filter(new Predicate() { - @Override - public boolean test(final Long t) { - return t < 50; - } - }).first(); + final long count = cursor.map(VPackSlice::getAsLong).filter(t -> t < 50).first(); assertThat(count, is(0L)); } @Test public void mapFilterCollectIntoList() { final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); - final List target = cursor.map(new Function() { - @Override - public Long apply(final VPackSlice t) { - return t.getAsLong(); - } - }).filter(new Predicate() { - @Override - public boolean test(final Long t) { - return t < 50; - } - }).collectInto(new ArrayList()); + final List target = cursor.map(VPackSlice::getAsLong).filter(t -> t < 50).collectInto(new ArrayList<>()); assertThat(target, is(not(nullValue()))); assertThat(target.size(), is(50)); } @@ -191,17 +116,7 @@ public boolean test(final Long t) { @Test public void mapFilterCollectIntoSet() { final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); - final Set target = cursor.map(new Function() { - @Override - public Long apply(final VPackSlice t) { - return t.getAsLong(); - } - }).filter(new Predicate() { - @Override - public boolean test(final Long t) { - return t < 50; - } - }).collectInto(new HashSet()); + final Set target = cursor.map(VPackSlice::getAsLong).filter(t -> t < 50).collectInto(new HashSet<>()); assertThat(target, is(not(nullValue()))); assertThat(target.size(), is(50)); } @@ -210,203 +125,83 @@ public boolean test(final Long t) { public void foreach() { final AtomicLong i = new AtomicLong(0L); final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); - cursor.foreach(new Consumer() { - @Override - public void accept(final VPackSlice t) { - assertThat(t.getAsLong(), is(i.getAndIncrement())); - } - }); + cursor.foreach(t -> assertThat(t.getAsLong(), is(i.getAndIncrement()))); } @Test public void mapForeach() { final AtomicLong i = new AtomicLong(0L); final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); - cursor.map(new Function() { - @Override - public Long apply(final VPackSlice t) { - return t.getAsLong(); - } - }).foreach(new Consumer() { - @Override - public void accept(final Long t) { - assertThat(t, is(i.getAndIncrement())); - } - }); + cursor.map(VPackSlice::getAsLong).foreach(t -> assertThat(t, is(i.getAndIncrement()))); } @Test public void mapFilterForeach() { final AtomicLong i = new AtomicLong(0L); final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); - cursor.map(new Function() { - @Override - public Long apply(final VPackSlice t) { - return t.getAsLong(); - } - }).filter(new Predicate() { - @Override - public boolean test(final Long t) { - return t < 50; - } - }).foreach(new Consumer() { - @Override - public void accept(final Long t) { - assertThat(t, is(i.getAndIncrement())); - } - }); + cursor.map(VPackSlice::getAsLong).filter(t -> t < 50).foreach(t -> assertThat(t, is(i.getAndIncrement()))); } @Test public void anyMatch() { final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); - final boolean match = cursor.anyMatch(new Predicate() { - @Override - public boolean test(final VPackSlice t) { - return t.getAsLong() == 50L; - } - }); + final boolean match = cursor.anyMatch(t -> t.getAsLong() == 50L); assertThat(match, is(true)); } @Test public void mapAnyMatch() { final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); - final boolean match = cursor.map(new Function() { - @Override - public Long apply(final VPackSlice t) { - return t.getAsLong(); - } - }).anyMatch(new Predicate() { - @Override - public boolean test(final Long t) { - return t == 50L; - } - }); + final boolean match = cursor.map(VPackSlice::getAsLong).anyMatch(t -> t == 50L); assertThat(match, is(true)); } @Test public void mapFilterAnyMatch() { final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); - final boolean match = cursor.map(new Function() { - @Override - public Long apply(final VPackSlice t) { - return t.getAsLong(); - } - }).filter(new Predicate() { - @Override - public boolean test(final Long t) { - return t < 50; - } - }).anyMatch(new Predicate() { - @Override - public boolean test(final Long t) { - return t == 25L; - } - }); + final boolean match = cursor.map(VPackSlice::getAsLong).filter(t -> t < 50).anyMatch(t -> t == 25L); assertThat(match, is(true)); } @Test public void noneMatch() { final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); - final boolean match = cursor.noneMatch(new Predicate() { - @Override - public boolean test(final VPackSlice t) { - return t.getAsLong() == 100L; - } - }); + final boolean match = cursor.noneMatch(t -> t.getAsLong() == 100L); assertThat(match, is(true)); } @Test public void mapNoneMatch() { final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); - final boolean match = cursor.map(new Function() { - @Override - public Long apply(final VPackSlice t) { - return t.getAsLong(); - } - }).noneMatch(new Predicate() { - @Override - public boolean test(final Long t) { - return t == 100L; - } - }); + final boolean match = cursor.map(VPackSlice::getAsLong).noneMatch(t -> t == 100L); assertThat(match, is(true)); } @Test public void mapFilterNoneMatch() { final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); - final boolean match = cursor.map(new Function() { - @Override - public Long apply(final VPackSlice t) { - return t.getAsLong(); - } - }).filter(new Predicate() { - @Override - public boolean test(final Long t) { - return t < 50; - } - }).noneMatch(new Predicate() { - @Override - public boolean test(final Long t) { - return t == 50L; - } - }); + final boolean match = cursor.map(VPackSlice::getAsLong).filter(t -> t < 50).noneMatch(t -> t == 50L); assertThat(match, is(true)); } @Test public void allMatch() { final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); - final boolean match = cursor.allMatch(new Predicate() { - @Override - public boolean test(final VPackSlice t) { - return t.getAsLong() < 100L; - } - }); + final boolean match = cursor.allMatch(t -> t.getAsLong() < 100L); assertThat(match, is(true)); } @Test public void mapAllMatch() { final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); - final boolean match = cursor.map(new Function() { - @Override - public Long apply(final VPackSlice t) { - return t.getAsLong(); - } - }).allMatch(new Predicate() { - @Override - public boolean test(final Long t) { - return t < 100; - } - }); + final boolean match = cursor.map(VPackSlice::getAsLong).allMatch(t -> t < 100); assertThat(match, is(true)); } @Test public void mapFilterAllMatch() { final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); - final boolean match = cursor.map(new Function() { - @Override - public Long apply(final VPackSlice t) { - return t.getAsLong(); - } - }).filter(new Predicate() { - @Override - public boolean test(final Long t) { - return t < 50; - } - }).allMatch(new Predicate() { - @Override - public boolean test(final Long t) { - return t < 50; - } - }); + final boolean match = cursor.map(VPackSlice::getAsLong).filter(t -> t < 50).allMatch(t -> t < 50); assertThat(match, is(true)); } } diff --git a/src/test/java/com/arangodb/ArangoDBTest.java b/src/test/java/com/arangodb/ArangoDBTest.java index 8852ce25f..65bf889aa 100644 --- a/src/test/java/com/arangodb/ArangoDBTest.java +++ b/src/test/java/com/arangodb/ArangoDBTest.java @@ -185,7 +185,7 @@ public void getUsers() { assertThat(users, is(notNullValue())); assertThat(users.size(), is(initialUsers.size() + 1)); - final List> matchers = new ArrayList>(users.size()); + final List> matchers = new ArrayList<>(users.size()); // Add initial users, including root: for (final UserEntity userEntity : initialUsers) { matchers.add(is(userEntity.getUser())); @@ -214,7 +214,7 @@ public void updateUserNoOptions() { @Test public void updateUser() { try { - final Map extra = new HashMap(); + final Map extra = new HashMap<>(); extra.put("hund", false); arangoDB.createUser(USER, PW, new UserCreateOptions().extra(extra)); extra.put("hund", true); @@ -236,7 +236,7 @@ public void updateUser() { @Test public void replaceUser() { try { - final Map extra = new HashMap(); + final Map extra = new HashMap<>(); extra.put("hund", false); arangoDB.createUser(USER, PW, new UserCreateOptions().extra(extra)); extra.remove("hund"); @@ -282,7 +282,7 @@ public void authenticationFailPassword() { arangoDB.getVersion(); fail(); } catch (final ArangoDBException e) { - + assertThat(e.getResponseCode(), is(401)); } } @@ -293,7 +293,7 @@ public void authenticationFailUser() { arangoDB.getVersion(); fail(); } catch (final ArangoDBException e) { - + assertThat(e.getResponseCode(), is(401)); } } diff --git a/src/test/java/com/arangodb/ArangoDatabaseTest.java b/src/test/java/com/arangodb/ArangoDatabaseTest.java index dbc5ab9d7..7a9a2fb8a 100644 --- a/src/test/java/com/arangodb/ArangoDatabaseTest.java +++ b/src/test/java/com/arangodb/ArangoDatabaseTest.java @@ -42,7 +42,6 @@ import java.io.IOException; import java.util.*; -import java.util.concurrent.ExecutionException; import java.util.concurrent.atomic.AtomicInteger; import static org.hamcrest.CoreMatchers.notNullValue; @@ -57,7 +56,7 @@ @RunWith(Parameterized.class) public class ArangoDatabaseTest extends BaseTest { - Logger LOG = LoggerFactory.getLogger(ArangoDatabaseTest.class); + private final Logger LOG = LoggerFactory.getLogger(ArangoDatabaseTest.class); private static final String COLLECTION_NAME = "db_test"; private static final String GRAPH_NAME = "graph_test"; @@ -367,6 +366,7 @@ public void deleteSystemCollection() { db.collection(name).getInfo(); fail(); } catch (final ArangoDBException e) { + assertThat(e.getResponseCode(), is(404)); } } @@ -376,17 +376,23 @@ public void deleteSystemCollectionFail() { return; } final String name = "_system_test"; + ArangoCollection collection = db.collection(name); + if (collection.exists()) + collection.drop(true); + db.createCollection(name, new CollectionCreateOptions().isSystem(true)); try { - db.collection(name).drop(); + collection.drop(); fail(); } catch (final ArangoDBException e) { + assertThat(e.getResponseCode(), is(403)); } - db.collection(name).drop(true); + collection.drop(true); try { - db.collection(name).getInfo(); + collection.getInfo(); fail(); } catch (final ArangoDBException e) { + assertThat(e.getResponseCode(), is(404)); } } @@ -394,7 +400,7 @@ public void deleteSystemCollectionFail() { public void getIndex() { try { db.createCollection(COLLECTION_NAME, null); - final Collection fields = new ArrayList(); + final Collection fields = new ArrayList<>(); fields.add("a"); final IndexEntity createResult = db.collection(COLLECTION_NAME).ensureHashIndex(fields, null); final IndexEntity readResult = db.getIndex(createResult.getId()); @@ -408,7 +414,7 @@ public void getIndex() { @Test public void deleteIndex() { db.createCollection(COLLECTION_NAME, null); - final Collection fields = new ArrayList(); + final Collection fields = new ArrayList<>(); fields.add("a"); final IndexEntity createResult = db.collection(COLLECTION_NAME).ensureHashIndex(fields, null); final String id = db.deleteIndex(createResult.getId()); @@ -417,6 +423,7 @@ public void deleteIndex() { db.getIndex(id); fail(); } catch (final ArangoDBException e) { + assertThat(e.getResponseCode(), is(404)); } db.collection(COLLECTION_NAME).drop(); } @@ -438,22 +445,18 @@ public void getCollections() { @Test public void getCollectionsExcludeSystem() { - try { - final CollectionsReadOptions options = new CollectionsReadOptions().excludeSystem(true); - final Collection nonSystemCollections = db.getCollections(options); + final CollectionsReadOptions options = new CollectionsReadOptions().excludeSystem(true); + final Collection nonSystemCollections = db.getCollections(options); - assertThat(nonSystemCollections.size(), is(0)); - db.createCollection(COLLECTION_NAME + "1", null); - db.createCollection(COLLECTION_NAME + "2", null); - final Collection newCollections = db.getCollections(options); - assertThat(newCollections.size(), is(2)); - assertThat(newCollections, is(notNullValue())); - } catch (final ArangoDBException e) { - System.out.println(e.getErrorMessage()); - } finally { - db.collection(COLLECTION_NAME + "1").drop(); - db.collection(COLLECTION_NAME + "2").drop(); - } + assertThat(nonSystemCollections.size(), is(0)); + db.createCollection(COLLECTION_NAME + "1", null); + db.createCollection(COLLECTION_NAME + "2", null); + final Collection newCollections = db.getCollections(options); + assertThat(newCollections.size(), is(2)); + assertThat(newCollections, is(notNullValue())); + + db.collection(COLLECTION_NAME + "1").drop(); + db.collection(COLLECTION_NAME + "2").drop(); } @Test @@ -556,7 +559,7 @@ public void query() { final ArangoCursor cursor = db.query("for i in db_test return i._id", null, null, String.class); assertThat(cursor, is(notNullValue())); for (int i = 0; i < 10; i++, cursor.next()) { - assertThat(cursor.hasNext(), is(i != 10)); + assertThat(cursor.hasNext(), is(true)); } } finally { db.collection(COLLECTION_NAME).drop(); @@ -614,7 +617,7 @@ public void queryWithCount() { String.class); assertThat(cursor, is(notNullValue())); for (int i = 0; i < 6; i++, cursor.next()) { - assertThat(cursor.hasNext(), is(i != 6)); + assertThat(cursor.hasNext(), is(true)); } assertThat(cursor.getCount(), is(6)); @@ -636,7 +639,7 @@ public void queryWithLimitAndFullCount() { String.class); assertThat(cursor, is(notNullValue())); for (int i = 0; i < 5; i++, cursor.next()) { - assertThat(cursor.hasNext(), is(i != 5)); + assertThat(cursor.hasNext(), is(true)); } assertThat(cursor.getStats(), is(notNullValue())); assertThat(cursor.getStats().getFullCount(), is(10L)); @@ -660,7 +663,7 @@ public void queryWithBatchSize() { assertThat(cursor, is(notNullValue())); for (int i = 0; i < 10; i++, cursor.next()) { - assertThat(cursor.hasNext(), is(i != 10)); + assertThat(cursor.hasNext(), is(true)); } } catch (final ArangoDBException e) { System.out.println(e.getErrorMessage()); @@ -715,7 +718,7 @@ public void queryWithTTL() throws InterruptedException { assertThat(cursor, is(notNullValue())); for (int i = 0; i < 10; i++, cursor.next()) { - assertThat(cursor.hasNext(), is(i != 10)); + assertThat(cursor.hasNext(), is(true)); if (i == 1) { Thread.sleep(wait * 1000); } @@ -751,7 +754,7 @@ public void changeQueryCache() { } @Test - public void queryWithCache() throws InterruptedException { + public void queryWithCache() { if (arangoDB.getRole() != ServerRole.SINGLE) { return; } @@ -843,7 +846,7 @@ public void queryCursor() { assertThat(cursor2.hasNext(), is(true)); for (int i = 0; i < batchSize; i++, cursor.next()) { - assertThat(cursor.hasNext(), is(i != batchSize)); + assertThat(cursor.hasNext(), is(true)); } } finally { db.collection(COLLECTION_NAME).drop(); @@ -874,7 +877,7 @@ public void changeQueryTrackingProperties() { } @Test - public void queryWithBindVars() throws InterruptedException { + public void queryWithBindVars() { try { db.createCollection(COLLECTION_NAME, null); for (int i = 0; i < 10; i++) { @@ -882,7 +885,7 @@ public void queryWithBindVars() throws InterruptedException { baseDocument.addAttribute("age", 20 + i); db.collection(COLLECTION_NAME).insertDocument(baseDocument, null); } - final Map bindVars = new HashMap(); + final Map bindVars = new HashMap<>(); bindVars.put("@coll", COLLECTION_NAME); bindVars.put("age", 25); @@ -893,7 +896,7 @@ public void queryWithBindVars() throws InterruptedException { assertThat(cursor, is(notNullValue())); for (int i = 0; i < 5; i++, cursor.next()) { - assertThat(cursor.hasNext(), is(i != 5)); + assertThat(cursor.hasNext(), is(true)); } } finally { @@ -963,17 +966,12 @@ public void queryWithNullBindParam() throws IOException { @Test public void queryAllowDirtyRead() throws IOException { - try { - db.createCollection(COLLECTION_NAME); - final ArangoCursor cursor = db.query("FOR i IN @@col FILTER i.test == @test RETURN i", - new MapBuilder().put("@col", COLLECTION_NAME).put("test", null).get(), - new AqlQueryOptions().allowDirtyRead(true), BaseDocument.class); - cursor.close(); - } catch (ArangoDBException e) { - System.out.println(e); - } finally { - db.collection(COLLECTION_NAME).drop(); - } + db.createCollection(COLLECTION_NAME); + final ArangoCursor cursor = db.query("FOR i IN @@col FILTER i.test == @test RETURN i", + new MapBuilder().put("@col", COLLECTION_NAME).put("test", null).get(), + new AqlQueryOptions().allowDirtyRead(true), BaseDocument.class); + cursor.close(); + db.collection(COLLECTION_NAME).drop(); } @Test @@ -1001,7 +999,7 @@ public void parseQuery() { @Test @Ignore - public void getCurrentlyRunningQueries() throws InterruptedException, ExecutionException { + public void getCurrentlyRunningQueries() throws InterruptedException { final Thread t = new Thread() { @Override public void run() { @@ -1024,47 +1022,40 @@ public void run() { } @Test - @Ignore - public void getAndClearSlowQueries() throws InterruptedException, ExecutionException { + public void getAndClearSlowQueries() { final QueryTrackingPropertiesEntity properties = db.getQueryTrackingProperties(); final Long slowQueryThreshold = properties.getSlowQueryThreshold(); - try { - properties.setSlowQueryThreshold(1L); - db.setQueryTrackingProperties(properties); + properties.setSlowQueryThreshold(1L); + db.setQueryTrackingProperties(properties); - db.query("return sleep(1.1)", null, null, Void.class); - final Collection slowQueries = db.getSlowQueries(); - assertThat(slowQueries, is(notNullValue())); - assertThat(slowQueries.size(), is(1)); - final QueryEntity queryEntity = slowQueries.iterator().next(); - assertThat(queryEntity.getQuery(), is("return sleep(1.1)")); + db.query("return sleep(1.1)", null, null, Void.class); + final Collection slowQueries = db.getSlowQueries(); + assertThat(slowQueries, is(notNullValue())); + assertThat(slowQueries.size(), is(1)); + final QueryEntity queryEntity = slowQueries.iterator().next(); + assertThat(queryEntity.getQuery(), is("return sleep(1.1)")); - db.clearSlowQueries(); - assertThat(db.getSlowQueries().size(), is(0)); - } finally { - properties.setSlowQueryThreshold(slowQueryThreshold); - db.setQueryTrackingProperties(properties); - } + db.clearSlowQueries(); + assertThat(db.getSlowQueries().size(), is(0)); + properties.setSlowQueryThreshold(slowQueryThreshold); + db.setQueryTrackingProperties(properties); } @Test @Ignore - public void killQuery() throws InterruptedException, ExecutionException { + public void killQuery() throws InterruptedException { final Thread t = new Thread() { @Override public void run() { super.run(); - try { - db.query("return sleep(0.2)", null, null, Void.class); - fail(); - } catch (final ArangoDBException e) { - } + db.query("return sleep(0.2)", null, null, Void.class); + fail(); } }; t.start(); Thread.sleep(100); + final Collection currentlyRunningQueries = db.getCurrentlyRunningQueries(); - assertThat(currentlyRunningQueries, is(notNullValue())); assertThat(currentlyRunningQueries.size(), is(1)); final QueryEntity queryEntity = currentlyRunningQueries.iterator().next(); @@ -1138,8 +1129,7 @@ public void createGraphReplicationFaktor() { final String edgeCollection = COLLECTION_NAME + "edge"; final String fromCollection = COLLECTION_NAME + "from"; final String toCollection = COLLECTION_NAME + "to"; - final Collection edgeDefinitions = Arrays - .asList(new EdgeDefinition().collection(edgeCollection).from(fromCollection).to(toCollection)); + final Collection edgeDefinitions = Collections.singletonList(new EdgeDefinition().collection(edgeCollection).from(fromCollection).to(toCollection)); final GraphEntity result = db .createGraph(GRAPH_NAME, edgeDefinitions, new GraphCreateOptions().replicationFactor(2)); assertThat(result, is(notNullValue())); @@ -1161,8 +1151,7 @@ public void createGraphNumberOfShards() { final String edgeCollection = COLLECTION_NAME + "edge"; final String fromCollection = COLLECTION_NAME + "from"; final String toCollection = COLLECTION_NAME + "to"; - final Collection edgeDefinitions = Arrays - .asList(new EdgeDefinition().collection(edgeCollection).from(fromCollection).to(toCollection)); + final Collection edgeDefinitions = Collections.singletonList(new EdgeDefinition().collection(edgeCollection).from(fromCollection).to(toCollection)); final GraphEntity result = db .createGraph(GRAPH_NAME, edgeDefinitions, new GraphCreateOptions().numberOfShards(2)); assertThat(result, is(notNullValue())); @@ -1249,7 +1238,7 @@ public void transactionArray() { @Test public void transactionCollection() { - final Collection params = new ArrayList(); + final Collection params = new ArrayList<>(); params.add("hello"); params.add("world"); final TransactionOptions options = new TransactionOptions().params(params); @@ -1318,11 +1307,13 @@ public void transactionallowImplicit() { db.transaction(action, VPackSlice.class, options); fail(); } catch (final ArangoDBException e) { + assertThat(e.getResponseCode(), is(400)); } db.collection("someCollection").drop(); db.collection("someOtherCollection").drop(); } + @SuppressWarnings({"WeakerAccess", "unused"}) protected static class TransactionTestEntity { private String value; @@ -1379,7 +1370,7 @@ public void executeTraversal() { assertThat(vertices.size(), is(4)); final Iterator verticesIterator = vertices.iterator(); - final Collection v = Arrays.asList(new String[]{"Alice", "Bob", "Charlie", "Dave"}); + final Collection v = Arrays.asList("Alice", "Bob", "Charlie", "Dave"); for (; verticesIterator.hasNext(); ) { assertThat(v.contains(verticesIterator.next().getKey()), is(true)); } diff --git a/src/test/java/com/arangodb/ArangoEdgeCollectionTest.java b/src/test/java/com/arangodb/ArangoEdgeCollectionTest.java index e95625542..07289527e 100644 --- a/src/test/java/com/arangodb/ArangoEdgeCollectionTest.java +++ b/src/test/java/com/arangodb/ArangoEdgeCollectionTest.java @@ -74,7 +74,7 @@ public void setup() { if (!db.collection(EDGE_COLLECTION_NAME).exists()) db.createCollection(EDGE_COLLECTION_NAME, new CollectionCreateOptions().type(CollectionType.EDGES)); - final Collection edgeDefinitions = new ArrayList(); + final Collection edgeDefinitions = new ArrayList<>(); edgeDefinitions.add(new EdgeDefinition().collection(EDGE_COLLECTION_NAME).from(VERTEX_COLLECTION_NAME) .to(VERTEX_COLLECTION_NAME)); db.createGraph(GRAPH_NAME, edgeDefinitions, null); @@ -272,6 +272,7 @@ public void replaceEdgeIfMatchFail() { db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).replaceEdge(createResult.getKey(), doc, options); fail(); } catch (final ArangoDBException e) { + assertThat(e.getResponseCode(), is(412)); } } @@ -354,6 +355,7 @@ public void updateEdgeIfMatchFail() { db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).updateEdge(createResult.getKey(), doc, options); fail(); } catch (final ArangoDBException e) { + assertThat(e.getResponseCode(), is(412)); } } @@ -430,6 +432,7 @@ public void deleteEdgeIfMatchFail() { db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).deleteEdge(createResult.getKey(), options); fail(); } catch (final ArangoDBException e) { + assertThat(e.getResponseCode(), is(412)); } } } diff --git a/src/test/java/com/arangodb/ArangoGraphTest.java b/src/test/java/com/arangodb/ArangoGraphTest.java index a970ba005..7bd4d2977 100644 --- a/src/test/java/com/arangodb/ArangoGraphTest.java +++ b/src/test/java/com/arangodb/ArangoGraphTest.java @@ -72,7 +72,7 @@ public ArangoGraphTest(final Builder builder) { public void setup() { if (db.graph(GRAPH_NAME).exists()) db.graph(GRAPH_NAME).drop(true); - final Collection edgeDefinitions = new ArrayList(); + final Collection edgeDefinitions = new ArrayList<>(); edgeDefinitions.add(new EdgeDefinition().collection(EDGE_COL_1).from(VERTEX_COL_1).to(VERTEX_COL_2)); edgeDefinitions .add(new EdgeDefinition().collection(EDGE_COL_2).from(VERTEX_COL_2).to(VERTEX_COL_1, VERTEX_COL_3)); @@ -123,7 +123,7 @@ public void createWithReplicationAndMinReplicationFactor() { } try { - final Collection edgeDefinitions = new ArrayList(); + final Collection edgeDefinitions = new ArrayList<>(); final GraphEntity graph = db.createGraph(GRAPH_NAME + "_1", edgeDefinitions, new GraphCreateOptions().isSmart(true).replicationFactor(2).minReplicationFactor(2)); assertThat(graph, is(notNullValue())); assertThat(graph.getName(), is(GRAPH_NAME + "_1")); @@ -265,7 +265,7 @@ public void smartGraph() { if (db.graph(GRAPH_NAME).exists()) db.graph(GRAPH_NAME).drop(); - final Collection edgeDefinitions = new ArrayList(); + final Collection edgeDefinitions = new ArrayList<>(); edgeDefinitions.add(new EdgeDefinition().collection(EDGE_COL_1).from(VERTEX_COL_1).to(VERTEX_COL_2)); edgeDefinitions.add(new EdgeDefinition().collection(EDGE_COL_2).from(VERTEX_COL_2).to(VERTEX_COL_1, VERTEX_COL_3)); diff --git a/src/test/java/com/arangodb/ArangoSslTest.java b/src/test/java/com/arangodb/ArangoSslTest.java index 795f7592d..50ad138b4 100644 --- a/src/test/java/com/arangodb/ArangoSslTest.java +++ b/src/test/java/com/arangodb/ArangoSslTest.java @@ -79,7 +79,7 @@ public void connect() throws Exception { @Test @Ignore - public void connectWithoutValidSslContext() throws Exception { + public void connectWithoutValidSslContext() { try { final ArangoDB arangoDB = new ArangoDB.Builder() .loadProperties(ArangoSslTest.class.getResourceAsStream("/arangodb-ssl.properties")).useSsl(true) diff --git a/src/test/java/com/arangodb/ArangoVertexCollectionTest.java b/src/test/java/com/arangodb/ArangoVertexCollectionTest.java index 0e60eda2c..992d8e05a 100644 --- a/src/test/java/com/arangodb/ArangoVertexCollectionTest.java +++ b/src/test/java/com/arangodb/ArangoVertexCollectionTest.java @@ -53,7 +53,7 @@ public ArangoVertexCollectionTest(final Builder builder) { setup(); } - public void setup() { + private void setup() { if (!db.collection(COLLECTION_NAME).exists()) db.createCollection(COLLECTION_NAME, null); @@ -261,6 +261,7 @@ public void replaceVertexIfMatchFail() { db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME).replaceVertex(createResult.getKey(), doc, options); fail(); } catch (final ArangoDBException e) { + assertThat(e.getResponseCode(), is(412)); } } @@ -347,6 +348,7 @@ public void updateVertexIfMatchFail() { db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME).updateVertex(createResult.getKey(), doc, options); fail(); } catch (final ArangoDBException e) { + assertThat(e.getResponseCode(), is(412)); } } @@ -428,6 +430,7 @@ public void deleteVertexIfMatchFail() { db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME).deleteVertex(createResult.getKey(), options); fail(); } catch (final ArangoDBException e) { + assertThat(e.getResponseCode(), is(412)); } } } diff --git a/src/test/java/com/arangodb/BaseTest.java b/src/test/java/com/arangodb/BaseTest.java index 0567c1afa..075584726 100644 --- a/src/test/java/com/arangodb/BaseTest.java +++ b/src/test/java/com/arangodb/BaseTest.java @@ -20,14 +20,14 @@ package com.arangodb; -import java.util.Arrays; -import java.util.Collection; - import com.arangodb.entity.ArangoDBEngine; import com.arangodb.entity.ServerRole; import org.junit.AfterClass; import org.junit.runners.Parameterized.Parameters; +import java.util.Arrays; +import java.util.Collection; + /** * @author Mark Vollmary * @author Michele Rastelli @@ -43,12 +43,11 @@ public static Collection builders() { ); } - protected static final String TEST_DB = "java_driver_test_db"; - protected static final String TEST_DB_CUSTOM = "java_driver_test_db_custom"; - protected static ArangoDB arangoDB; - protected static ArangoDatabase db; + static final String TEST_DB = "java_driver_test_db"; + static ArangoDB arangoDB; + static ArangoDatabase db; - public BaseTest(final ArangoDB.Builder builder) { + BaseTest(final ArangoDB.Builder builder) { super(); if (arangoDB != null) { shutdown(); @@ -66,16 +65,16 @@ public static void shutdown() { arangoDB = null; } - protected boolean requireVersion(final int major, final int minor) { + boolean requireVersion(final int major, final int minor) { final String[] split = arangoDB.getVersion().getVersion().split("\\."); - return Integer.valueOf(split[0]) >= major && Integer.valueOf(split[1]) >= minor; + return Integer.parseInt(split[0]) >= major && Integer.parseInt(split[1]) >= minor; } - protected boolean requireStorageEngine(ArangoDBEngine.StorageEngineName name) { + boolean requireStorageEngine(ArangoDBEngine.StorageEngineName name) { return name.equals(arangoDB.getEngine().getName()); } - protected boolean requireSingleServer() { + boolean requireSingleServer() { return (arangoDB.getRole() == ServerRole.SINGLE); } diff --git a/src/test/java/com/arangodb/DocumentTest.java b/src/test/java/com/arangodb/DocumentTest.java index 4d44ccbc2..5a70b8611 100644 --- a/src/test/java/com/arangodb/DocumentTest.java +++ b/src/test/java/com/arangodb/DocumentTest.java @@ -49,7 +49,7 @@ public DocumentTest(final Builder builder) { setup(); } - public void setup() { + private void setup() { db.createCollection(COLLECTION_NAME); collection = db.collection(COLLECTION_NAME); } diff --git a/src/test/java/com/arangodb/UserAuthTest.java b/src/test/java/com/arangodb/UserAuthTest.java index 85aaffd76..43042f55e 100644 --- a/src/test/java/com/arangodb/UserAuthTest.java +++ b/src/test/java/com/arangodb/UserAuthTest.java @@ -29,8 +29,8 @@ import static org.junit.Assert.fail; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collection; +import java.util.Collections; import org.junit.AfterClass; import org.junit.Ignore; @@ -52,6 +52,7 @@ /** * @author Mark Vollmary */ +@SuppressWarnings("CatchMayIgnoreException") @RunWith(Parameterized.class) @Ignore public class UserAuthTest { @@ -63,14 +64,14 @@ public class UserAuthTest { private static final String USER_NAME = "AuthUnitTestUser"; private static final String USER_NAME_NEW = USER_NAME + "new"; - public static class UserAuthParam { - Protocol protocol; - Permissions systemPermission; - Permissions dbPermission; - Permissions colPermission; + static class UserAuthParam { + final Protocol protocol; + final Permissions systemPermission; + final Permissions dbPermission; + final Permissions colPermission; - public UserAuthParam(final Protocol protocol, final Permissions systemPermission, - final Permissions dbPermission, final Permissions colPermission) { + UserAuthParam(final Protocol protocol, final Permissions systemPermission, + final Permissions dbPermission, final Permissions colPermission) { super(); this.protocol = protocol; this.systemPermission = systemPermission; @@ -82,7 +83,7 @@ public UserAuthParam(final Protocol protocol, final Permissions systemPermission @Parameters public static Collection params() { - final Collection params = new ArrayList(); + final Collection params = new ArrayList<>(); final Permissions[] permissions = new Permissions[]{Permissions.RW, Permissions.RO, Permissions.NONE}; for (final Protocol protocol : new Protocol[]{Protocol.VST, Protocol.HTTP_JSON, Protocol.HTTP_VPACK}) { for (final Permissions systemPermission : permissions) { @@ -115,8 +116,8 @@ public UserAuthTest(final UserAuthParam param) { arangoDBRoot.db().grantAccess(USER_NAME, param.systemPermission); arangoDBRoot.db(DB_NAME).grantAccess(USER_NAME, param.dbPermission); arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME).grantAccess(USER_NAME, param.colPermission); - details = new StringBuffer().append(param.protocol).append("_").append(param.systemPermission).append("_") - .append(param.dbPermission).append("_").append(param.colPermission).toString(); + details = param.protocol + "_" + param.systemPermission + "_" + + param.dbPermission + "_" + param.colPermission; } @AfterClass @@ -508,7 +509,7 @@ public void seeCollection() { } catch (final ArangoDBException e) { fail(details); } - } else if (Permissions.RW.equals(param.dbPermission) || Permissions.RO.equals(param.dbPermission)) { + } else if ((Permissions.RW.equals(param.dbPermission) || Permissions.RO.equals(param.dbPermission))) { final Collection collections = arangoDB.db(DB_NAME).getCollections(); boolean found = false; for (final CollectionEntity collection : collections) { @@ -607,7 +608,7 @@ public void createCollectionIndex() { if (Permissions.RW.equals(param.dbPermission) && Permissions.RW.equals(param.colPermission)) { try { final IndexEntity createHashIndex = arangoDB.db(DB_NAME).collection(COLLECTION_NAME) - .ensureHashIndex(Arrays.asList("a"), new HashIndexOptions()); + .ensureHashIndex(Collections.singletonList("a"), new HashIndexOptions()); assertThat(details, createHashIndex, is(notNullValue())); id = createHashIndex.getId(); } catch (final ArangoDBException e) { @@ -617,7 +618,7 @@ public void createCollectionIndex() { } else { try { final IndexEntity createHashIndex = arangoDB.db(DB_NAME).collection(COLLECTION_NAME) - .ensureHashIndex(Arrays.asList("a"), new HashIndexOptions()); + .ensureHashIndex(Collections.singletonList("a"), new HashIndexOptions()); id = createHashIndex.getId(); fail(details); } catch (final ArangoDBException e) { @@ -634,7 +635,7 @@ public void createCollectionIndex() { @Test public void dropCollectionIndex() { final String id = arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME) - .ensureHashIndex(Arrays.asList("a"), new HashIndexOptions()).getId(); + .ensureHashIndex(Collections.singletonList("a"), new HashIndexOptions()).getId(); try { if (Permissions.RW.equals(param.dbPermission) && Permissions.RW.equals(param.colPermission)) { try { diff --git a/src/test/java/com/arangodb/example/ExampleBase.java b/src/test/java/com/arangodb/example/ExampleBase.java index 49d89d40d..9f0b611c7 100644 --- a/src/test/java/com/arangodb/example/ExampleBase.java +++ b/src/test/java/com/arangodb/example/ExampleBase.java @@ -25,7 +25,6 @@ import com.arangodb.ArangoCollection; import com.arangodb.ArangoDB; -import com.arangodb.ArangoDBException; import com.arangodb.ArangoDatabase; /** @@ -33,10 +32,10 @@ */ public class ExampleBase { - protected static final String DB_NAME = "json_example_db"; + private static final String DB_NAME = "json_example_db"; protected static final String COLLECTION_NAME = "json_example_collection"; - protected static ArangoDB arangoDB; + private static ArangoDB arangoDB; protected static ArangoDatabase db; protected static ArangoCollection collection; diff --git a/src/test/java/com/arangodb/example/document/AqlQueryWithSpecialReturnTypesExample.java b/src/test/java/com/arangodb/example/document/AqlQueryWithSpecialReturnTypesExample.java index f35602cb2..fc5c66fb8 100644 --- a/src/test/java/com/arangodb/example/document/AqlQueryWithSpecialReturnTypesExample.java +++ b/src/test/java/com/arangodb/example/document/AqlQueryWithSpecialReturnTypesExample.java @@ -36,7 +36,6 @@ import com.arangodb.example.ExampleBase; import com.arangodb.util.MapBuilder; import com.arangodb.velocypack.VPackSlice; -import com.arangodb.velocypack.exception.VPackException; /** * @author Mark Vollmary diff --git a/src/test/java/com/arangodb/example/document/TestEntity.java b/src/test/java/com/arangodb/example/document/TestEntity.java index 774aef2be..ee9bebaa3 100644 --- a/src/test/java/com/arangodb/example/document/TestEntity.java +++ b/src/test/java/com/arangodb/example/document/TestEntity.java @@ -24,6 +24,7 @@ * @author Mark Vollmary * */ +@SuppressWarnings({"WeakerAccess", "unused"}) public class TestEntity { private String foo; diff --git a/src/test/java/com/arangodb/example/graph/AQLActorsAndMoviesExample.java b/src/test/java/com/arangodb/example/graph/AQLActorsAndMoviesExample.java index ef6aa46f9..7d140217d 100644 --- a/src/test/java/com/arangodb/example/graph/AQLActorsAndMoviesExample.java +++ b/src/test/java/com/arangodb/example/graph/AQLActorsAndMoviesExample.java @@ -30,7 +30,6 @@ import com.arangodb.ArangoCollection; import com.arangodb.ArangoCursor; import com.arangodb.ArangoDB; -import com.arangodb.ArangoDBException; import com.arangodb.ArangoDatabase; import com.arangodb.entity.BaseDocument; import com.arangodb.entity.BaseEdgeDocument; @@ -222,6 +221,7 @@ public void theNumberOfMoviesActedInBetween2005and2010byActor() { new Actor("actors/TomH", 2), new Actor("actors/VictorG", 1))); } + @SuppressWarnings("WeakerAccess") public static class Actor { private String actor; private Integer movies; @@ -265,17 +265,13 @@ public boolean equals(final Object obj) { return false; } if (movies == null) { - if (other.movies != null) { - return false; - } - } else if (!movies.equals(other.movies)) { - return false; - } - return true; + return other.movies == null; + } else return movies.equals(other.movies); } } + @SuppressWarnings("WeakerAccess") public static class Movie { private String movie; private Integer actors; @@ -319,13 +315,8 @@ public boolean equals(final Object obj) { return false; } if (movie == null) { - if (other.movie != null) { - return false; - } - } else if (!movie.equals(other.movie)) { - return false; - } - return true; + return other.movie == null; + } else return movie.equals(other.movie); } } @@ -356,7 +347,7 @@ private static DocumentCreateEntity saveActor( return actors.insertDocument(value); } - private static DocumentCreateEntity saveActsIn( + private static void saveActsIn( final ArangoCollection actsIn, final String actor, final String movie, @@ -367,7 +358,7 @@ private static DocumentCreateEntity saveActsIn( value.setTo(movie); value.addAttribute("roles", roles); value.addAttribute("year", year); - return actsIn.insertDocument(value); + actsIn.insertDocument(value); } private static void createData() { diff --git a/src/test/java/com/arangodb/example/graph/BaseGraphTest.java b/src/test/java/com/arangodb/example/graph/BaseGraphTest.java index 0c488aef7..802075f30 100644 --- a/src/test/java/com/arangodb/example/graph/BaseGraphTest.java +++ b/src/test/java/com/arangodb/example/graph/BaseGraphTest.java @@ -30,7 +30,6 @@ import com.arangodb.ArangoDBException; import com.arangodb.ArangoDatabase; import com.arangodb.entity.EdgeDefinition; -import com.arangodb.entity.EdgeEntity; import com.arangodb.entity.VertexEntity; /** @@ -38,12 +37,12 @@ */ public abstract class BaseGraphTest { - protected static final String TEST_DB = "java_driver_graph_test_db"; - protected static ArangoDB arangoDB; - protected static ArangoDatabase db; - protected static final String GRAPH_NAME = "traversalGraph"; - protected static final String EDGE_COLLECTION_NAME = "edges"; - protected static final String VERTEXT_COLLECTION_NAME = "circles"; + private static final String TEST_DB = "java_driver_graph_test_db"; + private static ArangoDB arangoDB; + static ArangoDatabase db; + private static final String GRAPH_NAME = "traversalGraph"; + private static final String EDGE_COLLECTION_NAME = "edges"; + private static final String VERTEXT_COLLECTION_NAME = "circles"; @BeforeClass public static void init() { @@ -55,7 +54,7 @@ public static void init() { arangoDB.createDatabase(TEST_DB); BaseGraphTest.db = arangoDB.db(TEST_DB); - final Collection edgeDefinitions = new ArrayList(); + final Collection edgeDefinitions = new ArrayList<>(); final EdgeDefinition edgeDefinition = new EdgeDefinition().collection(EDGE_COLLECTION_NAME) .from(VERTEXT_COLLECTION_NAME).to(VERTEXT_COLLECTION_NAME); edgeDefinitions.add(edgeDefinition); @@ -101,8 +100,8 @@ private static void addExampleElements() throws ArangoDBException { saveEdge(new CircleEdge(vJ.getId(), vK.getId(), false, true, "right_zup")); } - private static EdgeEntity saveEdge(final CircleEdge edge) throws ArangoDBException { - return db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).insertEdge(edge); + private static void saveEdge(final CircleEdge edge) throws ArangoDBException { + db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).insertEdge(edge); } private static VertexEntity createVertex(final Circle vertex) throws ArangoDBException { diff --git a/src/test/java/com/arangodb/example/graph/Circle.java b/src/test/java/com/arangodb/example/graph/Circle.java index 3c2e48ff7..6a988b000 100644 --- a/src/test/java/com/arangodb/example/graph/Circle.java +++ b/src/test/java/com/arangodb/example/graph/Circle.java @@ -27,7 +27,8 @@ * @author a-brandt * */ -public class Circle { +@SuppressWarnings("unused") +class Circle { @DocumentField(Type.ID) private String id; diff --git a/src/test/java/com/arangodb/example/graph/CircleEdge.java b/src/test/java/com/arangodb/example/graph/CircleEdge.java index dfcc0dc54..bb8151abb 100644 --- a/src/test/java/com/arangodb/example/graph/CircleEdge.java +++ b/src/test/java/com/arangodb/example/graph/CircleEdge.java @@ -27,7 +27,8 @@ * @author a-brandt * */ -public class CircleEdge { +@SuppressWarnings("unused") +class CircleEdge { @DocumentField(Type.ID) private String id; diff --git a/src/test/java/com/arangodb/example/graph/ShortestPathInAQLExample.java b/src/test/java/com/arangodb/example/graph/ShortestPathInAQLExample.java index 131e14f32..38b84f843 100644 --- a/src/test/java/com/arangodb/example/graph/ShortestPathInAQLExample.java +++ b/src/test/java/com/arangodb/example/graph/ShortestPathInAQLExample.java @@ -43,6 +43,7 @@ */ public class ShortestPathInAQLExample extends BaseGraphTest { + @SuppressWarnings({"WeakerAccess", "unused"}) public static class Pair { private String vertex; @@ -75,7 +76,7 @@ public void queryShortestPathFromAToD() throws ArangoDBException { assertThat(collection, hasItems("A", "B", "C", "D")); queryString = "WITH circles FOR v, e IN OUTBOUND SHORTEST_PATH 'circles/A' TO 'circles/D' edges RETURN {'vertex': v._key, 'edge': e._key}"; - cursor = db.query(queryString, null, null, Pair.class); + db.query(queryString, null, null, Pair.class); assertThat(collection.size(), is(4)); assertThat(collection, hasItems("A", "B", "C", "D")); } @@ -89,13 +90,13 @@ public void queryShortestPathByFilter() throws ArangoDBException { assertThat(collection, hasItems("A", "B", "C", "D")); queryString = "FOR a IN circles FILTER a._key == 'A' FOR d IN circles FILTER d._key == 'D' FOR v, e IN OUTBOUND SHORTEST_PATH a TO d edges RETURN {'vertex': v._key, 'edge': e._key}"; - cursor = db.query(queryString, null, null, Pair.class); + db.query(queryString, null, null, Pair.class); assertThat(collection.size(), is(4)); assertThat(collection, hasItems("A", "B", "C", "D")); } - protected Collection toVertexCollection(final ArangoCursor cursor) { - final List result = new ArrayList(); + private Collection toVertexCollection(final ArangoCursor cursor) { + final List result = new ArrayList<>(); for (; cursor.hasNext();) { final Pair pair = cursor.next(); result.add(pair.getVertex()); diff --git a/src/test/java/com/arangodb/internal/DocumentCacheTest.java b/src/test/java/com/arangodb/internal/DocumentCacheTest.java index 71335e30f..18f981b94 100644 --- a/src/test/java/com/arangodb/internal/DocumentCacheTest.java +++ b/src/test/java/com/arangodb/internal/DocumentCacheTest.java @@ -30,7 +30,6 @@ import org.junit.Test; import com.arangodb.entity.BaseDocument; -import com.arangodb.entity.DocumentField; import com.arangodb.entity.DocumentField.Type; /** @@ -48,7 +47,7 @@ public void setValues() { assertThat(doc.getKey(), is(nullValue())); assertThat(doc.getRevision(), is(nullValue())); - final Map values = new HashMap(); + final Map values = new HashMap<>(); values.put(Type.ID, "testId"); values.put(Type.KEY, "testKey"); values.put(Type.REV, "testRev"); @@ -62,9 +61,9 @@ public void setValues() { @Test public void setValuesMap() { final DocumentCache cache = new DocumentCache(); - final Map map = new HashMap(); + final Map map = new HashMap<>(); - final Map values = new HashMap(); + final Map values = new HashMap<>(); values.put(Type.ID, "testId"); values.put(Type.KEY, "testKey"); values.put(Type.REV, "testRev"); diff --git a/src/test/java/com/arangodb/internal/velocystream/CommunicationTest.java b/src/test/java/com/arangodb/internal/velocystream/CommunicationTest.java index 1bd233568..238ebdea6 100644 --- a/src/test/java/com/arangodb/internal/velocystream/CommunicationTest.java +++ b/src/test/java/com/arangodb/internal/velocystream/CommunicationTest.java @@ -31,7 +31,6 @@ import org.junit.Test; import com.arangodb.ArangoDB; -import com.arangodb.ArangoDBException; import com.arangodb.ArangoDatabase; import com.arangodb.entity.ArangoDBVersion; @@ -55,21 +54,15 @@ public void multiThread() throws Exception { final ArangoDB arangoDB = new ArangoDB.Builder().build(); arangoDB.getVersion();// authentication - final Collection result = new ConcurrentLinkedQueue(); - final Thread fast = new Thread() { - @Override - public void run() { - arangoDB.db().query("return sleep(1)", null, null, null); - result.add(FAST); - } - }; - final Thread slow = new Thread() { - @Override - public void run() { - arangoDB.db().query("return sleep(4)", null, null, null); - result.add(SLOW); - } - }; + final Collection result = new ConcurrentLinkedQueue<>(); + final Thread fast = new Thread(() -> { + arangoDB.db().query("return sleep(1)", null, null, null); + result.add(FAST); + }); + final Thread slow = new Thread(() -> { + arangoDB.db().query("return sleep(4)", null, null, null); + result.add(SLOW); + }); slow.start(); Thread.sleep(1000); fast.start(); @@ -90,21 +83,15 @@ public void multiThreadSameDatabases() throws Exception { final ArangoDatabase db = arangoDB.db(); - final Collection result = new ConcurrentLinkedQueue(); - final Thread t1 = new Thread() { - @Override - public void run() { - db.query("return sleep(1)", null, null, null); - result.add("1"); - } - }; - final Thread t2 = new Thread() { - @Override - public void run() { - db.query("return sleep(1)", null, null, null); - result.add("1"); - } - }; + final Collection result = new ConcurrentLinkedQueue<>(); + final Thread t1 = new Thread(() -> { + db.query("return sleep(1)", null, null, null); + result.add("1"); + }); + final Thread t2 = new Thread(() -> { + db.query("return sleep(1)", null, null, null); + result.add("1"); + }); t2.start(); t1.start(); t2.join(); @@ -123,21 +110,15 @@ public void multiThreadMultiDatabases() throws Exception { final ArangoDatabase db1 = arangoDB.db("db1"); final ArangoDatabase db2 = arangoDB.db("db2"); - final Collection result = new ConcurrentLinkedQueue(); - final Thread t1 = new Thread() { - @Override - public void run() { - db1.query("return sleep(1)", null, null, null); - result.add("1"); - } - }; - final Thread t2 = new Thread() { - @Override - public void run() { - db2.query("return sleep(1)", null, null, null); - result.add("1"); - } - }; + final Collection result = new ConcurrentLinkedQueue<>(); + final Thread t1 = new Thread(() -> { + db1.query("return sleep(1)", null, null, null); + result.add("1"); + }); + final Thread t2 = new Thread(() -> { + db2.query("return sleep(1)", null, null, null); + result.add("1"); + }); t2.start(); t1.start(); t2.join(); diff --git a/src/test/java/com/arangodb/serde/CustomSerdeTest.java b/src/test/java/com/arangodb/serde/CustomSerdeTest.java index a83271395..1f3cc4e66 100644 --- a/src/test/java/com/arangodb/serde/CustomSerdeTest.java +++ b/src/test/java/com/arangodb/serde/CustomSerdeTest.java @@ -47,7 +47,7 @@ */ public class CustomSerdeTest { - private static String COLLECTION_NAME = "collection"; + private static final String COLLECTION_NAME = "collection"; private ArangoDatabase db; private ArangoCollection collection; diff --git a/src/test/java/com/arangodb/util/ArangoSerializationTest.java b/src/test/java/com/arangodb/util/ArangoSerializationTest.java index f4fda0c41..c624bb7d8 100644 --- a/src/test/java/com/arangodb/util/ArangoSerializationTest.java +++ b/src/test/java/com/arangodb/util/ArangoSerializationTest.java @@ -86,7 +86,7 @@ public void skipSerializeNullValues() { @Test public void serializeType() { - final Collection list = new ArrayList(); + final Collection list = new ArrayList<>(); list.add(new BaseDocument()); list.add(new BaseDocument()); @@ -99,7 +99,7 @@ public void serializeType() { @Test public void parseJsonIncludeNull() { - final Map entity = new HashMap(); + final Map entity = new HashMap<>(); entity.put("value", new String[] { "test", null }); final String json = util.deserialize(util.serialize(entity, new ArangoSerializer.Options()), String.class); assertThat(json, is("{\"value\":[\"test\",null]}")); From 9e44d236bad616c20c6e338d3036d231795f4d2f Mon Sep 17 00:00:00 2001 From: michele Date: Mon, 2 Sep 2019 13:32:23 +0200 Subject: [PATCH 3/4] bugfix IfMatch graph tests --- .../arangodb/ArangoEdgeCollectionTest.java | 20 +++++++++---------- .../arangodb/ArangoVertexCollectionTest.java | 12 ++++++++--- 2 files changed, 19 insertions(+), 13 deletions(-) diff --git a/src/test/java/com/arangodb/ArangoEdgeCollectionTest.java b/src/test/java/com/arangodb/ArangoEdgeCollectionTest.java index 07289527e..494cb5f06 100644 --- a/src/test/java/com/arangodb/ArangoEdgeCollectionTest.java +++ b/src/test/java/com/arangodb/ArangoEdgeCollectionTest.java @@ -33,6 +33,7 @@ import java.util.Arrays; import java.util.Collection; +import com.arangodb.entity.*; import com.arangodb.model.*; import org.junit.After; import org.junit.Before; @@ -41,13 +42,6 @@ import org.junit.runners.Parameterized; import com.arangodb.ArangoDB.Builder; -import com.arangodb.entity.BaseDocument; -import com.arangodb.entity.BaseEdgeDocument; -import com.arangodb.entity.CollectionType; -import com.arangodb.entity.EdgeDefinition; -import com.arangodb.entity.EdgeEntity; -import com.arangodb.entity.EdgeUpdateEntity; -import com.arangodb.entity.VertexEntity; /** * @author Mark Vollmary @@ -272,7 +266,9 @@ public void replaceEdgeIfMatchFail() { db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).replaceEdge(createResult.getKey(), doc, options); fail(); } catch (final ArangoDBException e) { - assertThat(e.getResponseCode(), is(412)); + // FIXME: atm the server replies 409 for HTTP_JSON or HTTP_VPACK + // assertThat(e.getResponseCode(), is(412)); + assertThat(e.getErrorNum(), is(1200)); } } @@ -355,7 +351,9 @@ public void updateEdgeIfMatchFail() { db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).updateEdge(createResult.getKey(), doc, options); fail(); } catch (final ArangoDBException e) { - assertThat(e.getResponseCode(), is(412)); + // FIXME: atm the server replies 409 for HTTP_JSON or HTTP_VPACK + // assertThat(e.getResponseCode(), is(412)); + assertThat(e.getErrorNum(), is(1200)); } } @@ -432,7 +430,9 @@ public void deleteEdgeIfMatchFail() { db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).deleteEdge(createResult.getKey(), options); fail(); } catch (final ArangoDBException e) { - assertThat(e.getResponseCode(), is(412)); + // FIXME: atm the server replies 409 for HTTP_JSON or HTTP_VPACK + // assertThat(e.getResponseCode(), is(412)); + assertThat(e.getErrorNum(), is(1200)); } } } diff --git a/src/test/java/com/arangodb/ArangoVertexCollectionTest.java b/src/test/java/com/arangodb/ArangoVertexCollectionTest.java index 992d8e05a..e6c301954 100644 --- a/src/test/java/com/arangodb/ArangoVertexCollectionTest.java +++ b/src/test/java/com/arangodb/ArangoVertexCollectionTest.java @@ -261,7 +261,9 @@ public void replaceVertexIfMatchFail() { db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME).replaceVertex(createResult.getKey(), doc, options); fail(); } catch (final ArangoDBException e) { - assertThat(e.getResponseCode(), is(412)); + // FIXME: atm the server replies 409 for HTTP_JSON or HTTP_VPACK + // assertThat(e.getResponseCode(), is(412)); + assertThat(e.getErrorNum(), is(1200)); } } @@ -348,7 +350,9 @@ public void updateVertexIfMatchFail() { db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME).updateVertex(createResult.getKey(), doc, options); fail(); } catch (final ArangoDBException e) { - assertThat(e.getResponseCode(), is(412)); + // FIXME: atm the server replies 409 for HTTP_JSON or HTTP_VPACK + // assertThat(e.getResponseCode(), is(412)); + assertThat(e.getErrorNum(), is(1200)); } } @@ -430,7 +434,9 @@ public void deleteVertexIfMatchFail() { db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME).deleteVertex(createResult.getKey(), options); fail(); } catch (final ArangoDBException e) { - assertThat(e.getResponseCode(), is(412)); + // FIXME: atm the server replies 409 for HTTP_JSON or HTTP_VPACK + // assertThat(e.getResponseCode(), is(412)); + assertThat(e.getErrorNum(), is(1200)); } } } From 4c19a4083c41e2a41245347997abd5f4e190c936 Mon Sep 17 00:00:00 2001 From: michele Date: Mon, 2 Sep 2019 15:47:11 +0200 Subject: [PATCH 4/4] bugfix assumeTrue to skip tests --- .../com/arangodb/ArangoCollectionTest.java | 120 ++++------- .../java/com/arangodb/ArangoDatabaseTest.java | 167 ++++----------- .../arangodb/ArangoEdgeCollectionTest.java | 2 +- .../java/com/arangodb/ArangoGraphTest.java | 51 ++--- .../java/com/arangodb/ArangoSearchTest.java | 74 ++----- .../arangodb/ArangoVertexCollectionTest.java | 2 +- .../java/com/arangodb/ArangoViewTest.java | 35 +--- src/test/java/com/arangodb/BaseTest.java | 17 +- .../ConcurrentStreamTransactionsTest.java | 12 +- .../com/arangodb/StreamTransactionTest.java | 198 +++++++++--------- src/test/java/com/arangodb/UserAuthTest.java | 2 +- 11 files changed, 250 insertions(+), 430 deletions(-) diff --git a/src/test/java/com/arangodb/ArangoCollectionTest.java b/src/test/java/com/arangodb/ArangoCollectionTest.java index 9b8c64a70..db97d12c1 100644 --- a/src/test/java/com/arangodb/ArangoCollectionTest.java +++ b/src/test/java/com/arangodb/ArangoCollectionTest.java @@ -34,6 +34,7 @@ import static org.hamcrest.Matchers.startsWith; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; +import static org.junit.Assume.assumeTrue; import java.util.*; @@ -115,9 +116,7 @@ public void insertDocumentReturnNew() { @Test public void insertDocumentOverwriteReturnOld() { - if (!requireVersion(3, 4)) { - return; - } + assumeTrue(isAtLeastVersion(3, 4)); final BaseDocument doc = new BaseDocument(); doc.addAttribute("value", "a"); final DocumentCreateEntity meta = db.collection(COLLECTION_NAME).insertDocument(doc); @@ -155,9 +154,7 @@ public void insertDocumentAsJson() { @Test public void insertDocumentSilent() { - if (arangoDB.getRole() != ServerRole.SINGLE) { - return; - } + assumeTrue(isSingleServer()); final DocumentCreateEntity meta = db.collection(COLLECTION_NAME) .insertDocument(new BaseDocument(), new DocumentCreateOptions().silent(true)); assertThat(meta, is(notNullValue())); @@ -168,9 +165,7 @@ public void insertDocumentSilent() { @Test public void insertDocumentSilentDontTouchInstance() { - if (arangoDB.getRole() != ServerRole.SINGLE) { - return; - } + assumeTrue(isSingleServer()); final BaseDocument doc = new BaseDocument(); final String key = "testkey"; doc.setKey(key); @@ -183,9 +178,7 @@ public void insertDocumentSilentDontTouchInstance() { @Test public void insertDocumentsSilent() { - if (arangoDB.getRole() != ServerRole.SINGLE) { - return; - } + assumeTrue(isSingleServer()); final MultiDocumentEntity> info = db.collection(COLLECTION_NAME) .insertDocuments(Arrays.asList(new BaseDocument(), new BaseDocument()), new DocumentCreateOptions().silent(true)); @@ -647,9 +640,7 @@ public void updateDocumentIgnoreRevsFalse() { @Test public void updateDocumentSilent() { - if (arangoDB.getRole() != ServerRole.SINGLE) { - return; - } + assumeTrue(isSingleServer()); final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) .insertDocument(new BaseDocument()); final DocumentUpdateEntity meta = db.collection(COLLECTION_NAME) @@ -662,9 +653,7 @@ public void updateDocumentSilent() { @Test public void updateDocumentsSilent() { - if (arangoDB.getRole() != ServerRole.SINGLE) { - return; - } + assumeTrue(isSingleServer()); final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) .insertDocument(new BaseDocument()); final MultiDocumentEntity> info = db.collection(COLLECTION_NAME) @@ -848,9 +837,7 @@ public void replaceDocumentReturnOld() { @Test public void replaceDocumentSilent() { - if (arangoDB.getRole() != ServerRole.SINGLE) { - return; - } + assumeTrue(isSingleServer()); final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) .insertDocument(new BaseDocument()); final DocumentUpdateEntity meta = db.collection(COLLECTION_NAME) @@ -863,9 +850,7 @@ public void replaceDocumentSilent() { @Test public void replaceDocumentSilentDontTouchInstance() { - if (arangoDB.getRole() != ServerRole.SINGLE) { - return; - } + assumeTrue(isSingleServer()); final BaseDocument doc = new BaseDocument(); final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME).insertDocument(doc); final String revision = doc.getRevision(); @@ -878,9 +863,7 @@ public void replaceDocumentSilentDontTouchInstance() { @Test public void replaceDocumentsSilent() { - if (arangoDB.getRole() != ServerRole.SINGLE) { - return; - } + assumeTrue(isSingleServer()); final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) .insertDocument(new BaseDocument()); final MultiDocumentEntity> info = db.collection(COLLECTION_NAME) @@ -941,9 +924,7 @@ public void deleteDocumentIfMatchFail() { @Test public void deleteDocumentSilent() { - if (arangoDB.getRole() != ServerRole.SINGLE) { - return; - } + assumeTrue(isSingleServer()); final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) .insertDocument(new BaseDocument()); final DocumentDeleteEntity meta = db.collection(COLLECTION_NAME) @@ -956,9 +937,7 @@ public void deleteDocumentSilent() { @Test public void deleteDocumentsSilent() { - if (arangoDB.getRole() != ServerRole.SINGLE) { - return; - } + assumeTrue(isSingleServer()); final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) .insertDocument(new BaseDocument()); final MultiDocumentEntity> info = db.collection(COLLECTION_NAME) @@ -1023,7 +1002,7 @@ public void createHashIndex() { assertThat(indexResult.getId(), startsWith(COLLECTION_NAME)); assertThat(indexResult.getIsNewlyCreated(), is(true)); assertThat(indexResult.getMinLength(), is(nullValue())); - if (arangoDB.getRole() == ServerRole.SINGLE) { + if (isSingleServer()) { assertThat(indexResult.getSelectivityEstimate(), is(1.)); } assertThat(indexResult.getSparse(), is(false)); @@ -1033,9 +1012,7 @@ public void createHashIndex() { @Test public void createHashIndexWithOptions() { - if (!requireVersion(3, 5)) { - return; - } + assumeTrue(isAtLeastVersion(3, 5)); final HashIndexOptions options = new HashIndexOptions(); options.name("myHashIndex"); @@ -1051,7 +1028,7 @@ public void createHashIndexWithOptions() { assertThat(indexResult.getId(), startsWith(COLLECTION_NAME)); assertThat(indexResult.getIsNewlyCreated(), is(true)); assertThat(indexResult.getMinLength(), is(nullValue())); - if (arangoDB.getRole() == ServerRole.SINGLE) { + if (isSingleServer()) { assertThat(indexResult.getSelectivityEstimate(), is(1.)); } assertThat(indexResult.getSparse(), is(false)); @@ -1072,7 +1049,7 @@ public void createGeoIndex() { assertThat(indexResult.getMinLength(), is(nullValue())); assertThat(indexResult.getSparse(), is(true)); assertThat(indexResult.getUnique(), is(false)); - if (requireVersion(3, 4)) { + if (isAtLeastVersion(3, 4)) { assertThat(indexResult.getType(), is(IndexType.geo)); } else { assertThat(indexResult.getType(), is(IndexType.geo1)); @@ -1081,9 +1058,7 @@ public void createGeoIndex() { @Test public void createGeoIndexWithOptions() { - if (!requireVersion(3, 5)) { - return; - } + assumeTrue(isAtLeastVersion(3, 5)); final GeoIndexOptions options = new GeoIndexOptions(); options.name("myGeoIndex1"); @@ -1098,7 +1073,7 @@ public void createGeoIndexWithOptions() { assertThat(indexResult.getMinLength(), is(nullValue())); assertThat(indexResult.getSparse(), is(true)); assertThat(indexResult.getUnique(), is(false)); - if (requireVersion(3, 4)) { + if (isAtLeastVersion(3, 4)) { assertThat(indexResult.getType(), is(IndexType.geo)); } else { assertThat(indexResult.getType(), is(IndexType.geo1)); @@ -1120,7 +1095,7 @@ public void createGeo2Index() { assertThat(indexResult.getMinLength(), is(nullValue())); assertThat(indexResult.getSparse(), is(true)); assertThat(indexResult.getUnique(), is(false)); - if (requireVersion(3, 4)) { + if (isAtLeastVersion(3, 4)) { assertThat(indexResult.getType(), is(IndexType.geo)); } else { assertThat(indexResult.getType(), is(IndexType.geo2)); @@ -1129,9 +1104,7 @@ public void createGeo2Index() { @Test public void createGeo2IndexWithOptions() { - if (!requireVersion(3, 5)) { - return; - } + assumeTrue(isAtLeastVersion(3, 5)); final GeoIndexOptions options = new GeoIndexOptions(); options.name("myGeoIndex2"); @@ -1148,7 +1121,7 @@ public void createGeo2IndexWithOptions() { assertThat(indexResult.getMinLength(), is(nullValue())); assertThat(indexResult.getSparse(), is(true)); assertThat(indexResult.getUnique(), is(false)); - if (requireVersion(3, 4)) { + if (isAtLeastVersion(3, 4)) { assertThat(indexResult.getType(), is(IndexType.geo)); } else { assertThat(indexResult.getType(), is(IndexType.geo2)); @@ -1176,9 +1149,7 @@ public void createSkiplistIndex() { @Test public void createSkiplistIndexWithOptions() { - if (!requireVersion(3, 5)) { - return; - } + assumeTrue(isAtLeastVersion(3, 5)); final SkiplistIndexOptions options = new SkiplistIndexOptions(); options.name("mySkiplistIndex"); @@ -1220,9 +1191,7 @@ public void createPersistentIndex() { @Test public void createPersistentIndexWithOptions() { - if (!requireVersion(3, 5)) { - return; - } + assumeTrue(isAtLeastVersion(3, 5)); final PersistentIndexOptions options = new PersistentIndexOptions(); options.name("myPersistentIndex"); @@ -1261,9 +1230,7 @@ public void createFulltextIndex() { @Test public void createFulltextIndexWithOptions() { - if (!requireVersion(3, 5)) { - return; - } + assumeTrue(isAtLeastVersion(3, 5)); final FulltextIndexOptions options = new FulltextIndexOptions(); options.name("myFulltextIndex"); @@ -1284,9 +1251,7 @@ public void createFulltextIndexWithOptions() { @Test public void createTtlIndexWithoutOptions() { - if (!requireVersion(3, 5)) { - return; - } + assumeTrue(isAtLeastVersion(3, 5)); final Collection fields = new ArrayList<>(); fields.add("a"); try { @@ -1301,9 +1266,7 @@ public void createTtlIndexWithoutOptions() { @Test public void createTtlIndexWithOptions() { - if (!requireVersion(3, 5)) { - return; - } + assumeTrue(isAtLeastVersion(3, 5)); final Collection fields = new ArrayList<>(); fields.add("a"); @@ -1446,9 +1409,7 @@ public void insertDocuments() { @Test public void insertDocumentsOverwrite() { - if (!requireVersion(3, 4)) { - return; - } + assumeTrue(isAtLeastVersion(3, 4)); final BaseDocument doc1 = new BaseDocument(); doc1.addAttribute("value", "a"); final DocumentCreateEntity meta1 = db.collection(COLLECTION_NAME).insertDocument(doc1); @@ -2258,9 +2219,7 @@ public void changeProperties() { @Test public void rename() { - if (arangoDB.getRole() != ServerRole.SINGLE) { - return; - } + assumeTrue(isSingleServer()); final CollectionEntity result = db.collection(COLLECTION_NAME).rename(COLLECTION_NAME + "1"); assertThat(result, is(notNullValue())); assertThat(result.getName(), is(COLLECTION_NAME + "1")); @@ -2277,12 +2236,8 @@ public void rename() { @Test public void responsibleShard() { - if (arangoDB.getRole() != ServerRole.COORDINATOR) { - return; - } - if (!requireVersion(3, 5)) { - return; - } + assumeTrue(isCluster()); + assumeTrue(isAtLeastVersion(3, 5)); ShardEntity shard = db.collection(COLLECTION_NAME).getResponsibleShard(new BaseDocument("testKey")); assertThat(shard, is(notNullValue())); assertThat(shard.getShardId(), is(notNullValue())); @@ -2290,16 +2245,11 @@ public void responsibleShard() { @Test public void renameDontBreaksCollectionHandler() { - if (arangoDB.getRole() != ServerRole.SINGLE) { - return; - } - try { - final ArangoCollection collection = db.collection(COLLECTION_NAME); - collection.rename(COLLECTION_NAME + "1"); - assertThat(collection.getInfo(), is(notNullValue())); - } finally { - db.collection(COLLECTION_NAME + "1").rename(COLLECTION_NAME); - } + assumeTrue(isSingleServer()); + final ArangoCollection collection = db.collection(COLLECTION_NAME); + collection.rename(COLLECTION_NAME + "1"); + assertThat(collection.getInfo(), is(notNullValue())); + db.collection(COLLECTION_NAME + "1").rename(COLLECTION_NAME); } @Test diff --git a/src/test/java/com/arangodb/ArangoDatabaseTest.java b/src/test/java/com/arangodb/ArangoDatabaseTest.java index 7a9a2fb8a..1069d58fd 100644 --- a/src/test/java/com/arangodb/ArangoDatabaseTest.java +++ b/src/test/java/com/arangodb/ArangoDatabaseTest.java @@ -37,8 +37,6 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.*; @@ -47,7 +45,9 @@ import static org.hamcrest.CoreMatchers.notNullValue; import static org.hamcrest.CoreMatchers.nullValue; import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.fail; +import static org.junit.Assume.assumeTrue; /** * @author Mark Vollmary @@ -56,8 +56,6 @@ @RunWith(Parameterized.class) public class ArangoDatabaseTest extends BaseTest { - private final Logger LOG = LoggerFactory.getLogger(ArangoDatabaseTest.class); - private static final String COLLECTION_NAME = "db_test"; private static final String GRAPH_NAME = "graph_test"; @@ -130,9 +128,7 @@ public void createCollection() { @Test public void createCollectionWithReplicationFactor() { - if (arangoDB.getRole() == ServerRole.SINGLE) { - return; - } + assumeTrue(isCluster()); final CollectionEntity result = db .createCollection(COLLECTION_NAME, new CollectionCreateOptions().replicationFactor(2)); assertThat(result, is(notNullValue())); @@ -144,17 +140,8 @@ public void createCollectionWithReplicationFactor() { @Test public void createCollectionWithMinReplicationFactor() { - - // if we do not have version at least 3.5+ => exit - if (!requireVersion(3, 5)) { - LOG.info("Skip Test 'createCollectionWithMinReplicationFactor' because feature not implemented yet."); - return; - } - - // if we do not have a cluster => exit - if (arangoDB.getRole() == ServerRole.SINGLE) { - return; - } + assumeTrue(isAtLeastVersion(3, 5)); + assumeTrue(isCluster()); final CollectionEntity result = db.createCollection(COLLECTION_NAME, new CollectionCreateOptions().replicationFactor(2).minReplicationFactor(2)); @@ -168,18 +155,10 @@ public void createCollectionWithMinReplicationFactor() { @Test public void createSatelliteCollection() { - if (arangoDB.getVersion().getLicense() == License.COMMUNITY) { - LOG.info("Skip Test 'createSatelliteCollection' on COMMUNITY VERSION"); - return; - } - - if (arangoDB.getRole() == ServerRole.SINGLE) { - LOG.info("Skip Test 'createSatelliteCollection' on SINGLE SERVER"); - return; - } + assumeTrue(isEnterprise()); + assumeTrue(isCluster()); try { - final CollectionEntity result = db .createCollection(COLLECTION_NAME, new CollectionCreateOptions().satellite(true)); @@ -187,7 +166,6 @@ public void createSatelliteCollection() { assertThat(result.getId(), is(notNullValue())); assertThat(db.collection(COLLECTION_NAME).getProperties().getReplicationFactor(), is(nullValue())); assertThat(db.collection(COLLECTION_NAME).getProperties().getSatellite(), is(true)); - } finally { db.collection(COLLECTION_NAME).drop(); } @@ -195,19 +173,14 @@ public void createSatelliteCollection() { @Test public void createCollectionWithNumberOfShards() { - if (arangoDB.getRole() == ServerRole.SINGLE) { - return; - } - + assumeTrue(isCluster()); try { - final CollectionEntity result = db .createCollection(COLLECTION_NAME, new CollectionCreateOptions().numberOfShards(2)); assertThat(result, is(notNullValue())); assertThat(result.getId(), is(notNullValue())); assertThat(db.collection(COLLECTION_NAME).getProperties().getNumberOfShards(), is(2)); - } finally { db.collection(COLLECTION_NAME).drop(); } @@ -215,15 +188,8 @@ public void createCollectionWithNumberOfShards() { @Test public void createCollectionWithShardingStrategys() { - if (!requireVersion(3, 4)) { - LOG.info("Skip Test 'createCollectionWithShardingStrategys' because feature not implemented yet."); - return; - } - - if (arangoDB.getRole() == ServerRole.SINGLE) { - LOG.info("Skip Test 'createCollectionWithShardingStrategys' on SINGLE SERVER"); - return; - } + assumeTrue(isAtLeastVersion(3, 4)); + assumeTrue(isCluster()); final CollectionEntity result = db.createCollection(COLLECTION_NAME, new CollectionCreateOptions() .shardingStrategy(ShardingStrategy.COMMUNITY_COMPAT.getInternalName())); @@ -237,20 +203,9 @@ public void createCollectionWithShardingStrategys() { @Test public void createCollectionWithSmartJoinAttribute() { - if (!requireVersion(3, 5)) { - LOG.info("Skip Test 'createCollectionWithSmartJoinAttribute' because feature not implemented yet."); - return; - } - - if (arangoDB.getVersion().getLicense() == License.COMMUNITY) { - LOG.info("Skip Test 'createCollectionWithSmartJoinAttribute' on COMMUNITY SERVER"); - return; - } - - if (arangoDB.getRole() == ServerRole.SINGLE) { - LOG.info("Skip Test 'createCollectionWithSmartJoinAttribute' on SINGLE SERVER"); - return; - } + assumeTrue(isAtLeastVersion(3, 5)); + assumeTrue(isEnterprise()); + assumeTrue(isCluster()); final CollectionEntity result = db.createCollection(COLLECTION_NAME, new CollectionCreateOptions().smartJoinAttribute("test123").shardKeys("_key:")); @@ -262,20 +217,9 @@ public void createCollectionWithSmartJoinAttribute() { @Test public void createCollectionWithSmartJoinAttributeWrong() { - if (!requireVersion(3, 5)) { - LOG.info("Skip Test 'createCollectionWithSmartJoinAttributeWrong' because feature not implemented yet."); - return; - } - - if (arangoDB.getVersion().getLicense() == License.COMMUNITY) { - LOG.info("Skip Test 'createCollectionWithSmartJoinAttributeWrong' on COMMUNITY SERVER"); - return; - } - - if (arangoDB.getRole() == ServerRole.SINGLE) { - LOG.info("Skip Test 'createCollectionWithSmartJoinAttributeWrong' on SINGLE SERVER"); - return; - } + assumeTrue(isAtLeastVersion(3, 5)); + assumeTrue(isEnterprise()); + assumeTrue(isCluster()); try { db.createCollection(COLLECTION_NAME, new CollectionCreateOptions().smartJoinAttribute("test123")); @@ -290,10 +234,7 @@ public void createCollectionWithSmartJoinAttributeWrong() { @Test public void createCollectionWithNumberOfShardsAndShardKey() { - if (arangoDB.getRole() == ServerRole.SINGLE) { - LOG.info("Skip Test 'createCollectionWithNumberOfShardsAndShardKey' on SINGLE SERVER"); - return; - } + assumeTrue(isCluster()); try { final CollectionEntity result = db @@ -310,11 +251,7 @@ public void createCollectionWithNumberOfShardsAndShardKey() { @Test public void createCollectionWithNumberOfShardsAndShardKeys() { - if (arangoDB.getRole() == ServerRole.SINGLE) { - LOG.info("Skip Test 'createCollectionWithNumberOfShardsAndShardKeys' on SINGLE SERVER"); - return; - } - + assumeTrue(isCluster()); try { final CollectionEntity result = db.createCollection(COLLECTION_NAME, new CollectionCreateOptions().numberOfShards(2).shardKeys("a", "b")); @@ -330,19 +267,17 @@ public void createCollectionWithNumberOfShardsAndShardKeys() { @Test public void createCollectionWithDistributeShardsLike() { + assumeTrue(isEnterprise()); + assumeTrue(isCluster()); - if (arangoDB.getVersion().getLicense() == License.ENTERPRISE && arangoDB.getRole() != ServerRole.SINGLE) { - - final Integer numberOfShards = 3; - - db.createCollection(COLLECTION_NAME, new CollectionCreateOptions().numberOfShards(numberOfShards)); - db.createCollection(COLLECTION_NAME + "2", - new CollectionCreateOptions().distributeShardsLike(COLLECTION_NAME)); + final Integer numberOfShards = 3; - assertThat(db.collection(COLLECTION_NAME).getProperties().getNumberOfShards(), is(numberOfShards)); - assertThat(db.collection(COLLECTION_NAME + "2").getProperties().getNumberOfShards(), is(numberOfShards)); - } + db.createCollection(COLLECTION_NAME, new CollectionCreateOptions().numberOfShards(numberOfShards)); + db.createCollection(COLLECTION_NAME + "2", + new CollectionCreateOptions().distributeShardsLike(COLLECTION_NAME)); + assertThat(db.collection(COLLECTION_NAME).getProperties().getNumberOfShards(), is(numberOfShards)); + assertThat(db.collection(COLLECTION_NAME + "2").getProperties().getNumberOfShards(), is(numberOfShards)); } @Test(expected = ArangoDBException.class) @@ -354,11 +289,6 @@ public void deleteCollection() { @Test public void deleteSystemCollection() { - - if (arangoDB.getRole() != ServerRole.SINGLE) { - return; - } - final String name = "_system_test"; db.createCollection(name, new CollectionCreateOptions().isSystem(true)); db.collection(name).drop(true); @@ -372,9 +302,6 @@ public void deleteSystemCollection() { @Test public void deleteSystemCollectionFail() { - if (arangoDB.getRole() != ServerRole.SINGLE) { - return; - } final String name = "_system_test"; ArangoCollection collection = db.collection(name); if (collection.exists()) @@ -755,9 +682,7 @@ public void changeQueryCache() { @Test public void queryWithCache() { - if (arangoDB.getRole() != ServerRole.SINGLE) { - return; - } + assumeTrue(isSingleServer()); try { db.createCollection(COLLECTION_NAME, null); for (int i = 0; i < 10; i++) { @@ -914,7 +839,7 @@ public void queryWithWarning() { @Test public void queryStream() { - if (requireVersion(3, 4)) { + if (isAtLeastVersion(3, 4)) { final ArangoCursor cursor = db .query("FOR i IN 1..2 RETURN i", null, new AqlQueryOptions().stream(true).count(true), VPackSlice.class); @@ -1075,7 +1000,7 @@ public void createGetDeleteAqlFunction() { } finally { final Integer deleteCount = db.deleteAqlFunction("myfunctions::temperature::celsiustofahrenheit", null); // compatibility with ArangoDB < 3.4 - if (requireVersion(3, 4)) { + if (isAtLeastVersion(3, 4)) { assertThat(deleteCount, is(1)); } else { assertThat(deleteCount, is(nullValue())); @@ -1099,7 +1024,7 @@ public void createGetDeleteAqlFunctionWithNamespace() { final Integer deleteCount = db .deleteAqlFunction("myfunctions::temperature", new AqlFunctionDeleteOptions().group(true)); // compatibility with ArangoDB < 3.4 - if (requireVersion(3, 4)) { + if (isAtLeastVersion(3, 4)) { assertThat(deleteCount, is(2)); } else { assertThat(deleteCount, is(nullValue())); @@ -1122,9 +1047,7 @@ public void createGraph() { @Test public void createGraphReplicationFaktor() { - if (arangoDB.getRole() == ServerRole.SINGLE) { - return; - } + assumeTrue(isCluster()); try { final String edgeCollection = COLLECTION_NAME + "edge"; final String fromCollection = COLLECTION_NAME + "from"; @@ -1144,9 +1067,7 @@ public void createGraphReplicationFaktor() { @Test public void createGraphNumberOfShards() { - if (arangoDB.getRole() == ServerRole.SINGLE) { - return; - } + assumeTrue(isCluster()); try { final String edgeCollection = COLLECTION_NAME + "edge"; final String fromCollection = COLLECTION_NAME + "from"; @@ -1268,9 +1189,7 @@ public void transactionInsertJson() { @Test public void transactionExclusiveWrite() { - if (!requireVersion(3, 4)) { - return; - } + assumeTrue(isAtLeastVersion(3, 4)); try { db.createCollection(COLLECTION_NAME); final TransactionOptions options = new TransactionOptions().params("{\"_key\":\"0\"}") @@ -1408,15 +1327,15 @@ public void getDocument() { @Test public void shouldIncludeExceptionMessage() { - if (!requireVersion(3, 2)) { - final String exceptionMessage = "My error context"; - final String action = "function (params) {" + "throw '" + exceptionMessage + "';" + "}"; - try { - db.transaction(action, VPackSlice.class, null); - fail(); - } catch (final ArangoDBException e) { - assertTrue(e.getException().contains(exceptionMessage)); - } + assumeTrue(isAtLeastVersion(3, 4)); + + final String exceptionMessage = "My error context"; + final String action = "function (params) {" + "throw '" + exceptionMessage + "';" + "}"; + try { + db.transaction(action, VPackSlice.class, null); + fail(); + } catch (final ArangoDBException e) { + assertThat(e.getErrorMessage(), is(exceptionMessage)); } } diff --git a/src/test/java/com/arangodb/ArangoEdgeCollectionTest.java b/src/test/java/com/arangodb/ArangoEdgeCollectionTest.java index 494cb5f06..eae4b843c 100644 --- a/src/test/java/com/arangodb/ArangoEdgeCollectionTest.java +++ b/src/test/java/com/arangodb/ArangoEdgeCollectionTest.java @@ -119,7 +119,7 @@ public void insertEdgeUpdateRev() { @Test public void insertEdgeViolatingUniqueConstraint() { // FIXME: remove once fix is backported to 3.4 - assumeTrue(requireVersion(3, 5)); + assumeTrue(isAtLeastVersion(3, 5)); db.collection(EDGE_COLLECTION_NAME) .ensureSkiplistIndex(Arrays.asList("_from", "_to"), new SkiplistIndexOptions().unique(true)); diff --git a/src/test/java/com/arangodb/ArangoGraphTest.java b/src/test/java/com/arangodb/ArangoGraphTest.java index 7bd4d2977..11d335d0f 100644 --- a/src/test/java/com/arangodb/ArangoGraphTest.java +++ b/src/test/java/com/arangodb/ArangoGraphTest.java @@ -26,6 +26,7 @@ import static org.hamcrest.Matchers.hasItems; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; +import static org.junit.Assume.assumeTrue; import java.util.ArrayList; import java.util.Collection; @@ -43,8 +44,6 @@ import com.arangodb.entity.CollectionPropertiesEntity; import com.arangodb.entity.EdgeDefinition; import com.arangodb.entity.GraphEntity; -import com.arangodb.entity.License; -import com.arangodb.entity.ServerRole; import com.arangodb.model.GraphCreateOptions; /** @@ -77,7 +76,7 @@ public void setup() { edgeDefinitions .add(new EdgeDefinition().collection(EDGE_COL_2).from(VERTEX_COL_2).to(VERTEX_COL_1, VERTEX_COL_3)); final GraphCreateOptions options = new GraphCreateOptions(); - if (arangoDB.getRole() != ServerRole.SINGLE) { + if (isCluster()) { options.replicationFactor(REPLICATION_FACTOR).numberOfShards(NUMBER_OF_SHARDS); } db.createGraph(GRAPH_NAME, edgeDefinitions, options); @@ -113,14 +112,8 @@ public void create() { @Test public void createWithReplicationAndMinReplicationFactor() { - if (!requireVersion(3, 5)) { - return; - } - - // if we do not have a cluster => exit - if (arangoDB.getRole() == ServerRole.SINGLE) { - return; - } + assumeTrue(isAtLeastVersion(3, 5)); + assumeTrue(isCluster()); try { final Collection edgeDefinitions = new ArrayList<>(); @@ -159,7 +152,7 @@ public void getInfo() { assertThat(e2.getTo(), hasItems(VERTEX_COL_1, VERTEX_COL_3)); assertThat(info.getOrphanCollections(), is(empty())); - if (arangoDB.getRole() != ServerRole.SINGLE) { + if (isCluster()) { for (final String collection : new String[]{EDGE_COL_1, EDGE_COL_2, VERTEX_COL_1, VERTEX_COL_2}) { final CollectionPropertiesEntity properties = db.collection(collection).getProperties(); assertThat(properties.getReplicationFactor(), is(REPLICATION_FACTOR)); @@ -213,7 +206,7 @@ public void addEdgeDefinition() { assertThat(e.getTo(), hasItem(VERTEX_COL_2)); } } - if (arangoDB.getRole() != ServerRole.SINGLE) { + if (isCluster()) { final CollectionPropertiesEntity properties = db.collection(EDGE_COL_3).getProperties(); assertThat(properties.getReplicationFactor(), is(REPLICATION_FACTOR)); assertThat(properties.getNumberOfShards(), is(NUMBER_OF_SHARDS)); @@ -254,29 +247,27 @@ public void removeEdgeDefinition() { @Test public void smartGraph() { + assumeTrue(isEnterprise()); - if (arangoDB.getVersion().getLicense() == License.ENTERPRISE) { - - for (final String collection : new String[]{EDGE_COL_1, EDGE_COL_2, VERTEX_COL_1, VERTEX_COL_2, VERTEX_COL_3, VERTEX_COL_4}) { - if (db.collection(collection).exists()) - db.collection(collection).drop(); - } + for (final String collection : new String[]{EDGE_COL_1, EDGE_COL_2, VERTEX_COL_1, VERTEX_COL_2, VERTEX_COL_3, VERTEX_COL_4}) { + if (db.collection(collection).exists()) + db.collection(collection).drop(); + } - if (db.graph(GRAPH_NAME).exists()) - db.graph(GRAPH_NAME).drop(); + if (db.graph(GRAPH_NAME).exists()) + db.graph(GRAPH_NAME).drop(); - final Collection edgeDefinitions = new ArrayList<>(); + final Collection edgeDefinitions = new ArrayList<>(); - edgeDefinitions.add(new EdgeDefinition().collection(EDGE_COL_1).from(VERTEX_COL_1).to(VERTEX_COL_2)); - edgeDefinitions.add(new EdgeDefinition().collection(EDGE_COL_2).from(VERTEX_COL_2).to(VERTEX_COL_1, VERTEX_COL_3)); + edgeDefinitions.add(new EdgeDefinition().collection(EDGE_COL_1).from(VERTEX_COL_1).to(VERTEX_COL_2)); + edgeDefinitions.add(new EdgeDefinition().collection(EDGE_COL_2).from(VERTEX_COL_2).to(VERTEX_COL_1, VERTEX_COL_3)); - final GraphEntity graph = db.createGraph(GRAPH_NAME, edgeDefinitions, new GraphCreateOptions().isSmart(true).smartGraphAttribute("test").numberOfShards(2)); + final GraphEntity graph = db.createGraph(GRAPH_NAME, edgeDefinitions, new GraphCreateOptions().isSmart(true).smartGraphAttribute("test").numberOfShards(2)); - assertThat(graph, is(notNullValue())); - assertThat(graph.getIsSmart(), is(true)); - assertThat(graph.getSmartGraphAttribute(), is("test")); - assertThat(graph.getNumberOfShards(), is(2)); - } + assertThat(graph, is(notNullValue())); + assertThat(graph.getIsSmart(), is(true)); + assertThat(graph.getSmartGraphAttribute(), is("test")); + assertThat(graph.getNumberOfShards(), is(2)); } @Test diff --git a/src/test/java/com/arangodb/ArangoSearchTest.java b/src/test/java/com/arangodb/ArangoSearchTest.java index a7f26ae52..c60a08848 100644 --- a/src/test/java/com/arangodb/ArangoSearchTest.java +++ b/src/test/java/com/arangodb/ArangoSearchTest.java @@ -21,7 +21,6 @@ package com.arangodb; import com.arangodb.ArangoDB.Builder; -import com.arangodb.entity.ServerRole; import com.arangodb.entity.ViewEntity; import com.arangodb.entity.ViewType; import com.arangodb.entity.arangosearch.*; @@ -38,6 +37,7 @@ import static org.hamcrest.Matchers.*; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; +import static org.junit.Assume.assumeTrue; /** * @author Mark Vollmary @@ -63,18 +63,14 @@ public void teardown() { @Test public void exists() { - if (!requireVersion(3, 4)) { - return; - } + assumeTrue(isAtLeastVersion(3, 4)); db.createArangoSearch(VIEW_NAME, new ArangoSearchCreateOptions()); assertThat(db.arangoSearch(VIEW_NAME).exists(), is(true)); } @Test public void getInfo() { - if (!requireVersion(3, 4)) { - return; - } + assumeTrue(isAtLeastVersion(3, 4)); db.createArangoSearch(VIEW_NAME, new ArangoSearchCreateOptions()); final ViewEntity info = db.arangoSearch(VIEW_NAME).getInfo(); assertThat(info, is(not(nullValue()))); @@ -85,9 +81,7 @@ public void getInfo() { @Test public void drop() { - if (!requireVersion(3, 4)) { - return; - } + assumeTrue(isAtLeastVersion(3, 4)); db.createArangoSearch(VIEW_NAME, new ArangoSearchCreateOptions()); final ArangoView view = db.arangoSearch(VIEW_NAME); view.drop(); @@ -96,12 +90,8 @@ public void drop() { @Test public void rename() { - if (arangoDB.getRole() != ServerRole.SINGLE) { - return; - } - if (!requireVersion(3, 4)) { - return; - } + assumeTrue(isSingleServer()); + assumeTrue(isAtLeastVersion(3, 4)); final String name = VIEW_NAME + "_new"; db.createArangoSearch(name, new ArangoSearchCreateOptions()); db.arangoSearch(name).rename(VIEW_NAME); @@ -111,9 +101,7 @@ public void rename() { @Test public void create() { - if (!requireVersion(3, 4)) { - return; - } + assumeTrue(isAtLeastVersion(3, 4)); final ViewEntity info = db.arangoSearch(VIEW_NAME).create(); assertThat(info, is(not(nullValue()))); assertThat(info.getId(), is(not(nullValue()))); @@ -124,9 +112,7 @@ public void create() { @Test public void createWithOptions() { - if (!requireVersion(3, 4)) { - return; - } + assumeTrue(isAtLeastVersion(3, 4)); final ArangoSearchCreateOptions options = new ArangoSearchCreateOptions(); final ViewEntity info = db.arangoSearch(VIEW_NAME).create(options); assertThat(info, is(not(nullValue()))); @@ -138,9 +124,7 @@ public void createWithOptions() { @Test public void createWithPrimarySort() { - if (!requireVersion(3, 5)) { - return; - } + assumeTrue(isAtLeastVersion(3, 5)); final ArangoSearchCreateOptions options = new ArangoSearchCreateOptions(); final PrimarySort primarySort = PrimarySort.on("myFieldName"); @@ -158,9 +142,7 @@ public void createWithPrimarySort() { @Test public void createWithCommitIntervalMsec() { - if (!requireVersion(3, 5)) { - return; - } + assumeTrue(isAtLeastVersion(3, 5)); final ArangoSearchCreateOptions options = new ArangoSearchCreateOptions(); options.commitIntervalMsec(666666L); @@ -179,9 +161,7 @@ public void createWithCommitIntervalMsec() { @Test public void getProperties() { - if (!requireVersion(3, 4)) { - return; - } + assumeTrue(isAtLeastVersion(3, 4)); final ArangoSearch view = db.arangoSearch(VIEW_NAME); view.create(new ArangoSearchCreateOptions()); final ArangoSearchPropertiesEntity properties = view.getProperties(); @@ -199,9 +179,7 @@ public void getProperties() { @Test public void updateProperties() { - if (!requireVersion(3, 4)) { - return; - } + assumeTrue(isAtLeastVersion(3, 4)); db.createCollection("view_update_prop_test_collection"); final ArangoSearch view = db.arangoSearch(VIEW_NAME); view.create(new ArangoSearchCreateOptions()); @@ -233,9 +211,7 @@ public void updateProperties() { @Test public void replaceProperties() { - if (!requireVersion(3, 4)) { - return; - } + assumeTrue(isAtLeastVersion(3, 4)); db.createCollection("view_replace_prop_test_collection"); final ArangoSearch view = db.arangoSearch(VIEW_NAME); @@ -298,9 +274,7 @@ private void createGetAndDeleteAnalyzer(AnalyzerEntity options) { @Test public void identityAnalyzer() { - if (!requireVersion(3, 5)) { - return; - } + assumeTrue(isAtLeastVersion(3, 5)); String name = "test-" + UUID.randomUUID().toString(); @@ -320,9 +294,7 @@ public void identityAnalyzer() { @Test public void delimiterAnalyzer() { - if (!requireVersion(3, 5)) { - return; - } + assumeTrue(isAtLeastVersion(3, 5)); String name = "test-" + UUID.randomUUID().toString(); @@ -342,9 +314,7 @@ public void delimiterAnalyzer() { @Test public void stemAnalyzer() { - if (!requireVersion(3, 5)) { - return; - } + assumeTrue(isAtLeastVersion(3, 5)); String name = "test-" + UUID.randomUUID().toString(); @@ -364,9 +334,7 @@ public void stemAnalyzer() { @Test public void normAnalyzer() { - if (!requireVersion(3, 5)) { - return; - } + assumeTrue(isAtLeastVersion(3, 5)); String name = "test-" + UUID.randomUUID().toString(); @@ -391,9 +359,7 @@ public void normAnalyzer() { @Test public void ngramAnalyzer() { - if (!requireVersion(3, 5)) { - return; - } + assumeTrue(isAtLeastVersion(3, 5)); String name = "test-" + UUID.randomUUID().toString(); @@ -418,9 +384,7 @@ public void ngramAnalyzer() { @Test public void textAnalyzer() { - if (!requireVersion(3, 5)) { - return; - } + assumeTrue(isAtLeastVersion(3, 5)); String name = "test-" + UUID.randomUUID().toString(); diff --git a/src/test/java/com/arangodb/ArangoVertexCollectionTest.java b/src/test/java/com/arangodb/ArangoVertexCollectionTest.java index e6c301954..28498bdcd 100644 --- a/src/test/java/com/arangodb/ArangoVertexCollectionTest.java +++ b/src/test/java/com/arangodb/ArangoVertexCollectionTest.java @@ -90,7 +90,7 @@ public void insertVertex() { @Test public void insertVertexViolatingUniqueConstraint() { // FIXME: remove once fix is backported to 3.4 - assumeTrue(requireVersion(3, 5)); + assumeTrue(isAtLeastVersion(3, 5)); db.collection(COLLECTION_NAME) .ensureSkiplistIndex(Collections.singletonList("properties"), new SkiplistIndexOptions().unique(true)); diff --git a/src/test/java/com/arangodb/ArangoViewTest.java b/src/test/java/com/arangodb/ArangoViewTest.java index 3dc388533..bb1bcd938 100644 --- a/src/test/java/com/arangodb/ArangoViewTest.java +++ b/src/test/java/com/arangodb/ArangoViewTest.java @@ -20,20 +20,17 @@ package com.arangodb; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.not; -import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertThat; - +import com.arangodb.ArangoDB.Builder; +import com.arangodb.entity.ViewEntity; +import com.arangodb.entity.ViewType; import org.junit.After; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; -import com.arangodb.ArangoDB.Builder; -import com.arangodb.entity.ServerRole; -import com.arangodb.entity.ViewEntity; -import com.arangodb.entity.ViewType; +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.assertThat; +import static org.junit.Assume.assumeTrue; /** * @author Mark Vollmary @@ -55,18 +52,14 @@ public void teardown() { @Test public void exists() { - if (!requireVersion(3, 4)) { - return; - } + assumeTrue(isAtLeastVersion(3, 4)); db.createView(VIEW_NAME, ViewType.ARANGO_SEARCH); assertThat(db.view(VIEW_NAME).exists(), is(true)); } @Test public void getInfo() { - if (!requireVersion(3, 4)) { - return; - } + assumeTrue(isAtLeastVersion(3, 4)); db.createView(VIEW_NAME, ViewType.ARANGO_SEARCH); final ViewEntity info = db.view(VIEW_NAME).getInfo(); assertThat(info, is(not(nullValue()))); @@ -77,9 +70,7 @@ public void getInfo() { @Test public void drop() { - if (!requireVersion(3, 4)) { - return; - } + assumeTrue(isAtLeastVersion(3, 4)); db.createView(VIEW_NAME, ViewType.ARANGO_SEARCH); final ArangoView view = db.view(VIEW_NAME); view.drop(); @@ -88,12 +79,8 @@ public void drop() { @Test public void rename() { - if (arangoDB.getRole() != ServerRole.SINGLE) { - return; - } - if (!requireVersion(3, 4)) { - return; - } + assumeTrue(isSingleServer()); + assumeTrue(isAtLeastVersion(3, 4)); final String name = VIEW_NAME + "_new"; db.createView(name, ViewType.ARANGO_SEARCH); db.view(name).rename(VIEW_NAME); diff --git a/src/test/java/com/arangodb/BaseTest.java b/src/test/java/com/arangodb/BaseTest.java index 075584726..e9a4ea2fc 100644 --- a/src/test/java/com/arangodb/BaseTest.java +++ b/src/test/java/com/arangodb/BaseTest.java @@ -21,6 +21,7 @@ package com.arangodb; import com.arangodb.entity.ArangoDBEngine; +import com.arangodb.entity.License; import com.arangodb.entity.ServerRole; import org.junit.AfterClass; import org.junit.runners.Parameterized.Parameters; @@ -65,17 +66,25 @@ public static void shutdown() { arangoDB = null; } - boolean requireVersion(final int major, final int minor) { + boolean isAtLeastVersion(final int major, final int minor) { final String[] split = arangoDB.getVersion().getVersion().split("\\."); return Integer.parseInt(split[0]) >= major && Integer.parseInt(split[1]) >= minor; } - boolean requireStorageEngine(ArangoDBEngine.StorageEngineName name) { + boolean isStorageEngine(ArangoDBEngine.StorageEngineName name) { return name.equals(arangoDB.getEngine().getName()); } - boolean requireSingleServer() { - return (arangoDB.getRole() == ServerRole.SINGLE); + boolean isSingleServer() { + return arangoDB.getRole() == ServerRole.SINGLE; + } + + boolean isCluster() { + return arangoDB.getRole() == ServerRole.COORDINATOR; + } + + boolean isEnterprise() { + return arangoDB.getVersion().getLicense() == License.ENTERPRISE; } } diff --git a/src/test/java/com/arangodb/ConcurrentStreamTransactionsTest.java b/src/test/java/com/arangodb/ConcurrentStreamTransactionsTest.java index 416ef8a69..33ad8035a 100644 --- a/src/test/java/com/arangodb/ConcurrentStreamTransactionsTest.java +++ b/src/test/java/com/arangodb/ConcurrentStreamTransactionsTest.java @@ -59,9 +59,9 @@ public void teardown() { @Test public void conflictOnInsertDocumentWithNotYetCommittedTx() { - assumeTrue(requireSingleServer()); - assumeTrue(requireVersion(3, 5)); - assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); + assumeTrue(isSingleServer()); + assumeTrue(isAtLeastVersion(3, 5)); + assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); StreamTransactionEntity tx1 = db.beginStreamTransaction( new StreamTransactionOptions().readCollections(COLLECTION_NAME).writeCollections(COLLECTION_NAME)); @@ -91,9 +91,9 @@ public void conflictOnInsertDocumentWithNotYetCommittedTx() { @Test public void conflictOnInsertDocumentWithAlreadyCommittedTx() { - assumeTrue(requireSingleServer()); - assumeTrue(requireVersion(3, 5)); - assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); + assumeTrue(isSingleServer()); + assumeTrue(isAtLeastVersion(3, 5)); + assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); StreamTransactionEntity tx1 = db.beginStreamTransaction( new StreamTransactionOptions().readCollections(COLLECTION_NAME).writeCollections(COLLECTION_NAME)); diff --git a/src/test/java/com/arangodb/StreamTransactionTest.java b/src/test/java/com/arangodb/StreamTransactionTest.java index d3fa6369f..341bcc9a6 100644 --- a/src/test/java/com/arangodb/StreamTransactionTest.java +++ b/src/test/java/com/arangodb/StreamTransactionTest.java @@ -61,9 +61,9 @@ public void teardown() { @Test public void beginStreamTransaction() { - assumeTrue(requireSingleServer()); - assumeTrue(requireVersion(3, 5)); - assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); + assumeTrue(isSingleServer()); + assumeTrue(isAtLeastVersion(3, 5)); + assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); StreamTransactionEntity tx = db.beginStreamTransaction(null); assertThat(tx.getId(), is(notNullValue())); @@ -73,18 +73,18 @@ public void beginStreamTransaction() { @Test(expected = ArangoDBException.class) public void beginStreamTransactionWithNonExistingCollectionsShouldThrow() { - assumeTrue(requireSingleServer()); - assumeTrue(requireVersion(3, 5)); - assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); + assumeTrue(isSingleServer()); + assumeTrue(isAtLeastVersion(3, 5)); + assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); db.beginStreamTransaction(new StreamTransactionOptions().writeCollections("notExistingCollection")); } @Test public void abortStreamTransaction() { - assumeTrue(requireSingleServer()); - assumeTrue(requireVersion(3, 5)); - assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); + assumeTrue(isSingleServer()); + assumeTrue(isAtLeastVersion(3, 5)); + assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); StreamTransactionEntity begunTx = db.beginStreamTransaction(null); StreamTransactionEntity abortedTx = db.abortStreamTransaction(begunTx.getId()); @@ -96,9 +96,9 @@ public void abortStreamTransaction() { @Test public void abortStreamTransactionTwice() { - assumeTrue(requireSingleServer()); - assumeTrue(requireVersion(3, 5)); - assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); + assumeTrue(isSingleServer()); + assumeTrue(isAtLeastVersion(3, 5)); + assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); StreamTransactionEntity begunTx = db.beginStreamTransaction(null); db.abortStreamTransaction(begunTx.getId()); @@ -107,27 +107,27 @@ public void abortStreamTransactionTwice() { @Test(expected = ArangoDBException.class) public void abortStreamTransactionWhenTransactionIdDoesNotExistsShouldThrow() { - assumeTrue(requireSingleServer()); - assumeTrue(requireVersion(3, 5)); - assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); + assumeTrue(isSingleServer()); + assumeTrue(isAtLeastVersion(3, 5)); + assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); db.abortStreamTransaction("000000"); } @Test(expected = ArangoDBException.class) public void abortStreamTransactionWithInvalidTransactionIdShouldThrow() { - assumeTrue(requireSingleServer()); - assumeTrue(requireVersion(3, 5)); - assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); + assumeTrue(isSingleServer()); + assumeTrue(isAtLeastVersion(3, 5)); + assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); db.abortStreamTransaction("invalidTransactionId"); } @Test(expected = ArangoDBException.class) public void abortCommittedStreamTransactionShouldThrow() { - assumeTrue(requireSingleServer()); - assumeTrue(requireVersion(3, 5)); - assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); + assumeTrue(isSingleServer()); + assumeTrue(isAtLeastVersion(3, 5)); + assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); StreamTransactionEntity createdTx = db.beginStreamTransaction(null); db.commitStreamTransaction(createdTx.getId()); @@ -136,9 +136,9 @@ public void abortCommittedStreamTransactionShouldThrow() { @Test public void getStreamTransaction() { - assumeTrue(requireSingleServer()); - assumeTrue(requireVersion(3, 5)); - assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); + assumeTrue(isSingleServer()); + assumeTrue(isAtLeastVersion(3, 5)); + assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); StreamTransactionEntity createdTx = db.beginStreamTransaction(null); StreamTransactionEntity gotTx = db.getStreamTransaction(createdTx.getId()); @@ -152,27 +152,27 @@ public void getStreamTransaction() { @Test(expected = ArangoDBException.class) public void getStreamTransactionWhenTransactionIdDoesNotExistsShouldThrow() { - assumeTrue(requireSingleServer()); - assumeTrue(requireVersion(3, 5)); - assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); + assumeTrue(isSingleServer()); + assumeTrue(isAtLeastVersion(3, 5)); + assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); db.getStreamTransaction("000000"); } @Test(expected = ArangoDBException.class) public void getStreamTransactionWithInvalidTransactionIdShouldThrow() { - assumeTrue(requireSingleServer()); - assumeTrue(requireVersion(3, 5)); - assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); + assumeTrue(isSingleServer()); + assumeTrue(isAtLeastVersion(3, 5)); + assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); db.getStreamTransaction("invalidTransactionId"); } @Test public void commitStreamTransaction() { - assumeTrue(requireSingleServer()); - assumeTrue(requireVersion(3, 5)); - assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); + assumeTrue(isSingleServer()); + assumeTrue(isAtLeastVersion(3, 5)); + assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); StreamTransactionEntity createdTx = db.beginStreamTransaction(null); StreamTransactionEntity committedTx = db.commitStreamTransaction(createdTx.getId()); @@ -184,9 +184,9 @@ public void commitStreamTransaction() { @Test public void commitStreamTransactionTwice() { - assumeTrue(requireSingleServer()); - assumeTrue(requireVersion(3, 5)); - assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); + assumeTrue(isSingleServer()); + assumeTrue(isAtLeastVersion(3, 5)); + assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); StreamTransactionEntity createdTx = db.beginStreamTransaction(null); db.commitStreamTransaction(createdTx.getId()); @@ -195,27 +195,27 @@ public void commitStreamTransactionTwice() { @Test(expected = ArangoDBException.class) public void commitStreamTransactionWhenTransactionIdDoesNotExistsShouldThrow() { - assumeTrue(requireSingleServer()); - assumeTrue(requireVersion(3, 5)); - assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); + assumeTrue(isSingleServer()); + assumeTrue(isAtLeastVersion(3, 5)); + assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); db.commitStreamTransaction("000000"); } @Test(expected = ArangoDBException.class) public void commitStreamTransactionWithInvalidTransactionIdShouldThrow() { - assumeTrue(requireSingleServer()); - assumeTrue(requireVersion(3, 5)); - assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); + assumeTrue(isSingleServer()); + assumeTrue(isAtLeastVersion(3, 5)); + assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); db.commitStreamTransaction("invalidTransactionId"); } @Test(expected = ArangoDBException.class) public void commitAbortedStreamTransactionShouldThrow() { - assumeTrue(requireSingleServer()); - assumeTrue(requireVersion(3, 5)); - assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); + assumeTrue(isSingleServer()); + assumeTrue(isAtLeastVersion(3, 5)); + assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); StreamTransactionEntity createdTx = db.beginStreamTransaction(null); db.abortStreamTransaction(createdTx.getId()); @@ -224,9 +224,9 @@ public void commitAbortedStreamTransactionShouldThrow() { @Test public void getDocument() { - assumeTrue(requireSingleServer()); - assumeTrue(requireVersion(3, 5)); - assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); + assumeTrue(isSingleServer()); + assumeTrue(isAtLeastVersion(3, 5)); + assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); StreamTransactionEntity tx = db .beginStreamTransaction(new StreamTransactionOptions().readCollections(COLLECTION_NAME)); @@ -244,9 +244,9 @@ public void getDocument() { @Test(expected = ArangoDBException.class) public void getDocumentWithNonExistingTransactionIdShouldThrow() { - assumeTrue(requireSingleServer()); - assumeTrue(requireVersion(3, 5)); - assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); + assumeTrue(isSingleServer()); + assumeTrue(isAtLeastVersion(3, 5)); + assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); db.collection(COLLECTION_NAME) .getDocument("docId", BaseDocument.class, new DocumentReadOptions().streamTransactionId("123456")); @@ -254,9 +254,9 @@ public void getDocumentWithNonExistingTransactionIdShouldThrow() { @Test(expected = ArangoDBException.class) public void getDocumentWithInvalidTransactionIdShouldThrow() { - assumeTrue(requireSingleServer()); - assumeTrue(requireVersion(3, 5)); - assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); + assumeTrue(isSingleServer()); + assumeTrue(isAtLeastVersion(3, 5)); + assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); db.collection(COLLECTION_NAME) .getDocument("docId", BaseDocument.class, new DocumentReadOptions().streamTransactionId("abcde")); @@ -264,9 +264,9 @@ public void getDocumentWithInvalidTransactionIdShouldThrow() { @Test public void getDocuments() { - assumeTrue(requireSingleServer()); - assumeTrue(requireVersion(3, 5)); - assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); + assumeTrue(isSingleServer()); + assumeTrue(isAtLeastVersion(3, 5)); + assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); StreamTransactionEntity tx = db .beginStreamTransaction(new StreamTransactionOptions().readCollections(COLLECTION_NAME)); @@ -290,9 +290,9 @@ public void getDocuments() { @Test public void insertDocument() { - assumeTrue(requireSingleServer()); - assumeTrue(requireVersion(3, 5)); - assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); + assumeTrue(isSingleServer()); + assumeTrue(isAtLeastVersion(3, 5)); + assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); StreamTransactionEntity tx = db.beginStreamTransaction( new StreamTransactionOptions().readCollections(COLLECTION_NAME).writeCollections(COLLECTION_NAME)); @@ -318,9 +318,9 @@ public void insertDocument() { @Test public void insertDocuments() { - assumeTrue(requireSingleServer()); - assumeTrue(requireVersion(3, 5)); - assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); + assumeTrue(isSingleServer()); + assumeTrue(isAtLeastVersion(3, 5)); + assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); StreamTransactionEntity tx = db.beginStreamTransaction( new StreamTransactionOptions().readCollections(COLLECTION_NAME).writeCollections(COLLECTION_NAME)); @@ -350,9 +350,9 @@ public void insertDocuments() { @Test public void replaceDocument() { - assumeTrue(requireSingleServer()); - assumeTrue(requireVersion(3, 5)); - assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); + assumeTrue(isSingleServer()); + assumeTrue(isAtLeastVersion(3, 5)); + assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); BaseDocument doc = new BaseDocument(); doc.addAttribute("test", "foo"); @@ -385,9 +385,9 @@ public void replaceDocument() { @Test public void replaceDocuments() { - assumeTrue(requireSingleServer()); - assumeTrue(requireVersion(3, 5)); - assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); + assumeTrue(isSingleServer()); + assumeTrue(isAtLeastVersion(3, 5)); + assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); List docs = IntStream.range(0, 3).mapToObj(it -> new BaseDocument()) .peek(doc -> doc.addAttribute("test", "foo")).collect(Collectors.toList()); @@ -429,9 +429,9 @@ public void replaceDocuments() { @Test public void updateDocument() { - assumeTrue(requireSingleServer()); - assumeTrue(requireVersion(3, 5)); - assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); + assumeTrue(isSingleServer()); + assumeTrue(isAtLeastVersion(3, 5)); + assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); BaseDocument doc = new BaseDocument(); doc.addAttribute("test", "foo"); @@ -465,9 +465,9 @@ public void updateDocument() { @Test public void updateDocuments() { - assumeTrue(requireSingleServer()); - assumeTrue(requireVersion(3, 5)); - assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); + assumeTrue(isSingleServer()); + assumeTrue(isAtLeastVersion(3, 5)); + assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); List docs = IntStream.range(0, 3).mapToObj(it -> new BaseDocument()) .peek(doc -> doc.addAttribute("test", "foo")).collect(Collectors.toList()); @@ -509,9 +509,9 @@ public void updateDocuments() { @Test public void deleteDocument() { - assumeTrue(requireSingleServer()); - assumeTrue(requireVersion(3, 5)); - assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); + assumeTrue(isSingleServer()); + assumeTrue(isAtLeastVersion(3, 5)); + assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); DocumentCreateEntity createdDoc = db.collection(COLLECTION_NAME) .insertDocument(new BaseDocument(), null); @@ -540,9 +540,9 @@ public void deleteDocument() { @Test public void deleteDocuments() { - assumeTrue(requireSingleServer()); - assumeTrue(requireVersion(3, 5)); - assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); + assumeTrue(isSingleServer()); + assumeTrue(isAtLeastVersion(3, 5)); + assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); List keys = db.collection(COLLECTION_NAME) .insertDocuments(Arrays.asList(new BaseDocument(), new BaseDocument(), new BaseDocument()), null) @@ -573,9 +573,9 @@ public void deleteDocuments() { @Test public void documentExists() { - assumeTrue(requireSingleServer()); - assumeTrue(requireVersion(3, 5)); - assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); + assumeTrue(isSingleServer()); + assumeTrue(isAtLeastVersion(3, 5)); + assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); StreamTransactionEntity tx = db .beginStreamTransaction(new StreamTransactionOptions().readCollections(COLLECTION_NAME)); @@ -594,9 +594,9 @@ public void documentExists() { @Test public void count() { - assumeTrue(requireSingleServer()); - assumeTrue(requireVersion(3, 5)); - assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); + assumeTrue(isSingleServer()); + assumeTrue(isAtLeastVersion(3, 5)); + assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); Long initialCount = db.collection(COLLECTION_NAME).count().getCount(); @@ -615,9 +615,9 @@ public void count() { @Test public void truncate() { - assumeTrue(requireSingleServer()); - assumeTrue(requireVersion(3, 5)); - assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); + assumeTrue(isSingleServer()); + assumeTrue(isAtLeastVersion(3, 5)); + assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); db.collection(COLLECTION_NAME).insertDocument(new BaseDocument(), null); @@ -642,9 +642,9 @@ public void truncate() { @Test public void createCursor() { - assumeTrue(requireSingleServer()); - assumeTrue(requireVersion(3, 5)); - assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); + assumeTrue(isSingleServer()); + assumeTrue(isAtLeastVersion(3, 5)); + assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); StreamTransactionEntity tx = db .beginStreamTransaction(new StreamTransactionOptions().readCollections(COLLECTION_NAME)); @@ -669,9 +669,9 @@ public void createCursor() { @Test public void nextCursor() { - assumeTrue(requireSingleServer()); - assumeTrue(requireVersion(3, 5)); - assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); + assumeTrue(isSingleServer()); + assumeTrue(isAtLeastVersion(3, 5)); + assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); StreamTransactionEntity tx = db.beginStreamTransaction( new StreamTransactionOptions().readCollections(COLLECTION_NAME).writeCollections(COLLECTION_NAME)); @@ -701,9 +701,9 @@ public void nextCursor() { @Test public void getStreamTransactions() { - assumeTrue(requireSingleServer()); - assumeTrue(requireVersion(3, 5)); - assumeTrue(requireStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); + assumeTrue(isSingleServer()); + assumeTrue(isAtLeastVersion(3, 5)); + assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); StreamTransactionEntity tx1 = db.beginStreamTransaction(null); StreamTransactionEntity tx2 = db.beginStreamTransaction(null); diff --git a/src/test/java/com/arangodb/UserAuthTest.java b/src/test/java/com/arangodb/UserAuthTest.java index 43042f55e..3175987dd 100644 --- a/src/test/java/com/arangodb/UserAuthTest.java +++ b/src/test/java/com/arangodb/UserAuthTest.java @@ -52,7 +52,7 @@ /** * @author Mark Vollmary */ -@SuppressWarnings("CatchMayIgnoreException") +@SuppressWarnings("ALL") @RunWith(Parameterized.class) @Ignore public class UserAuthTest {