diff --git a/README.md b/README.md index 843d4e3e1..b04b2be4c 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,6 @@ The official [ArangoDB](https://www.arangodb.com/) Java Driver. - [ChangeLog](ChangeLog.md) - [Examples](driver/src/test/java/com/arangodb/example) -- [Examples Async](driver/src/test/java/com/arangodb/async/example) - [Tutorial](https://www.arangodb.com/docs/stable/drivers/java-tutorial.html) - [Documentation](https://www.arangodb.com/docs/stable/drivers/java.html) - [JavaDoc](http://arangodb.github.io/arangodb-java-driver/) diff --git a/core/src/main/java/com/arangodb/async/ArangoCollectionAsync.java b/core/src/main/java/com/arangodb/async/ArangoCollectionAsync.java deleted file mode 100644 index 92da6e41a..000000000 --- a/core/src/main/java/com/arangodb/async/ArangoCollectionAsync.java +++ /dev/null @@ -1,949 +0,0 @@ -/* - * DISCLAIMER - * - * Copyright 2016 ArangoDB GmbH, Cologne, Germany - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Copyright holder is ArangoDB GmbH, Cologne, Germany - */ - -package com.arangodb.async; - -import com.arangodb.ArangoSerdeAccessor; -import com.arangodb.entity.*; -import com.arangodb.model.*; -import com.arangodb.util.RawData; - -import javax.annotation.concurrent.ThreadSafe; -import java.util.Collection; -import java.util.concurrent.CompletableFuture; - -/** - * Interface for operations on ArangoDB collection level. - * - * @author Mark Vollmary - * @see Collection API Documentation - * @see Documents API Documentation - */ -@ThreadSafe -public interface ArangoCollectionAsync extends ArangoSerdeAccessor { - - /** - * The the handler of the database the collection is within - * - * @return database handler - */ - ArangoDatabaseAsync db(); - - /** - * The name of the collection - * - * @return collection name - */ - String name(); - - /** - * Creates a new document from the given document, unless there is already a document with the _key given. If no - * _key is given, a new unique _key is generated automatically. - * - * @param value A representation of a single document (POJO or {@link com.arangodb.util.RawData}) - * @return information about the document - * @see API - * Documentation - */ - CompletableFuture> insertDocument(final Object value); - - /** - * Creates a new document from the given document, unless there is already a document with the _key given. If no - * _key is given, a new unique _key is generated automatically. - * - * @param value A representation of a single document (POJO or {@link com.arangodb.util.RawData}) - * @param options Additional options - * @return information about the document - * @see API - * Documentation - */ - CompletableFuture> insertDocument(final T value, final DocumentCreateOptions options); - - /** - * Creates a new document from the given document, unless there is already a document with the _key given. If no - * _key is given, a new unique _key is generated automatically. - * - * @param value A representation of a single document (POJO or {@link com.arangodb.util.RawData}) - * @param options Additional options - * @param type Deserialization target type for the returned documents. - * @return information about the document - * @see API - * Documentation - */ - CompletableFuture> insertDocument(final T value, final DocumentCreateOptions options, - Class type); - - /** - * Creates new documents from the given documents, unless there is already a document with the _key given. If no - * _key is given, a new unique _key is generated automatically. - * - * @param values Raw data representing a collection of documents - * @return information about the documents - * @see API - * Documentation - */ - CompletableFuture>> insertDocuments(final RawData values); - - /** - * Creates new documents from the given documents, unless there is already a document with the _key given. If no - * _key is given, a new unique _key is generated automatically. - * - * @param values Raw data representing a collection of documents - * @param options Additional options - * @return information about the documents - * @see API - * Documentation - */ - CompletableFuture>> insertDocuments( - final RawData values, - final DocumentCreateOptions options); - - /** - * Creates new documents from the given documents, unless there is already a document with the _key given. If no - * _key is given, a new unique _key is generated automatically. - * - * @param values A List of documents (POJO or {@link com.arangodb.util.RawData}) - * @return information about the documents - * @see API - * Documentation - */ - CompletableFuture>> insertDocuments(final Collection values); - - /** - * Creates new documents from the given documents, unless there is already a document with the _key given. If no - * _key is given, a new unique _key is generated automatically. - * - * @param values A List of documents (POJO or {@link com.arangodb.util.RawData}) - * @param options Additional options - * @return information about the documents - * @see API - * Documentation - */ - CompletableFuture>> insertDocuments( - final Collection values, - final DocumentCreateOptions options); - - /** - * Creates new documents from the given documents, unless there is already a document with the _key given. If no - * _key is given, a new unique _key is generated automatically. - * - * @param values A List of documents (POJO or {@link com.arangodb.util.RawData}) - * @param options Additional options - * @param type Deserialization target type for the returned documents. - * @return information about the documents - * @see API - * Documentation - */ - CompletableFuture>> insertDocuments( - final Collection values, - final DocumentCreateOptions options, - final Class type); - - /** - * Imports documents - * - * @param values A List of documents (POJO or {@link com.arangodb.util.RawData}) - * @return information about the import - */ - CompletableFuture importDocuments(final Collection values); - - /** - * Imports documents - * - * @param values A List of documents (POJO or {@link com.arangodb.util.RawData}) - * @param options Additional options, can be null - * @return information about the import - */ - CompletableFuture importDocuments( - final Collection values, - final DocumentImportOptions options); - - /** - * Imports documents - * - * @param values Raw data representing a collection of documents - * @return information about the import - */ - CompletableFuture importDocuments(final RawData values); - - /** - * Imports documents - * - * @param values Raw data representing a collection of documents - * @param options Additional options, can be null - * @return information about the import - */ - CompletableFuture importDocuments(final RawData values, final DocumentImportOptions options); - - /** - * Reads a single document - * - * @param key The key of the document - * @param type The type of the document (POJO or {@link com.arangodb.util.RawData}) - * @return the document identified by the key - * @see API - * Documentation - */ - CompletableFuture getDocument(final String key, final Class type); - - /** - * Reads a single document - * - * @param key The key of the document - * @param type The type of the document (POJO or {@link com.arangodb.util.RawData}) - * @param options Additional options, can be null - * @return the document identified by the key - * @see API - * Documentation - */ - CompletableFuture getDocument(final String key, final Class type, final DocumentReadOptions options); - - /** - * Reads multiple documents - * - * @param keys The keys of the documents - * @param type The type of the documents (POJO or {@link com.arangodb.util.RawData}) - * @return the documents and possible errors - */ - CompletableFuture> getDocuments(final Collection keys, final Class type); - - /** - * Reads multiple documents - * - * @param keys The keys of the documents - * @param type The type of the documents (POJO or {@link com.arangodb.util.RawData}) - * @param options Additional options, can be null - * @return the documents and possible errors - */ - CompletableFuture> getDocuments( - final Collection keys, - final Class type, - DocumentReadOptions options); - - /** - * Replaces the document with key with the one in the body, provided there is such a document and no precondition is - * violated - * - * @param key The key of the document - * @param value A representation of a single document (POJO or {@link com.arangodb.util.RawData}) - * @return information about the document - * @see - * API - * Documentation - */ - CompletableFuture> replaceDocument(final String key, final Object value); - - /** - * Replaces the document with key with the one in the body, provided there is such a document and no precondition is - * violated - * - * @param key The key of the document - * @param value A representation of a single document (POJO or {@link com.arangodb.util.RawData}) - * @param options Additional options - * @return information about the document - * @see - * API - * Documentation - */ - CompletableFuture> replaceDocument( - final String key, - final T value, - final DocumentReplaceOptions options); - - /** - * Replaces the document with key with the one in the body, provided there is such a document and no precondition is - * violated - * - * @param key The key of the document - * @param value A representation of a single document (POJO or {@link com.arangodb.util.RawData}) - * @param options Additional options - * @param type Deserialization target type for the returned documents. - * @return information about the document - * @see - * API - * Documentation - */ - CompletableFuture> replaceDocument( - final String key, - final T value, - final DocumentReplaceOptions options, - final Class type); - - /** - * Replaces multiple documents in the specified collection with the ones in the values, the replaced documents are - * specified by the _key attributes in the documents in values. - * - * @param values Raw data representing a collection of documents - * @return information about the documents - * @see - * API - * Documentation - */ - CompletableFuture>> replaceDocuments(final RawData values); - - /** - * Replaces multiple documents in the specified collection with the ones in the values, the replaced documents are - * specified by the _key attributes in the documents in values. - * - * @param values Raw data representing a collection of documents - * @param options Additional options - * @return information about the documents - * @see - * API - * Documentation - */ - CompletableFuture>> replaceDocuments( - final RawData values, - final DocumentReplaceOptions options); - - /** - * Replaces multiple documents in the specified collection with the ones in the values, the replaced documents are - * specified by the _key attributes in the documents in values. - * - * @param values A List of documents (POJO or {@link com.arangodb.util.RawData}) - * @return information about the documents - * @see - * API - * Documentation - */ - CompletableFuture>> replaceDocuments(final Collection values); - - /** - * Replaces multiple documents in the specified collection with the ones in the values, the replaced documents are - * specified by the _key attributes in the documents in values. - * - * @param values A List of documents (POJO or {@link com.arangodb.util.RawData}) - * @param options Additional options - * @return information about the documents - * @see - * API - * Documentation - */ - CompletableFuture>> replaceDocuments( - final Collection values, - final DocumentReplaceOptions options); - - /** - * Replaces multiple documents in the specified collection with the ones in the values, the replaced documents are - * specified by the _key attributes in the documents in values. - * - * @param values A List of documents (POJO or {@link com.arangodb.util.RawData}) - * @param options Additional options - * @param type Deserialization target type for the returned documents. - * @return information about the documents - * @see - * API - * Documentation - */ - CompletableFuture>> replaceDocuments( - final Collection values, - final DocumentReplaceOptions options, - final Class type); - - /** - * Partially updates the document identified by document-key. The value must contain a document with the attributes - * to patch (the patch document). All attributes from the patch document will be added to the existing document if - * they do not yet exist, and overwritten in the existing document if they do exist there. - * - * @param key The key of the document - * @param value A representation of a single document (POJO or {@link com.arangodb.util.RawData}) - * @return information about the document - * @see API - * Documentation - */ - CompletableFuture> updateDocument(final String key, final Object value); - - /** - * Partially updates the document identified by document-key. The value must contain a document with the attributes - * to patch (the patch document). All attributes from the patch document will be added to the existing document if - * they do not yet exist, and overwritten in the existing document if they do exist there. - * - * @param key The key of the document - * @param value A representation of a single document (POJO or {@link com.arangodb.util.RawData}) - * @param options Additional options - * @return information about the document - * @see API - * Documentation - */ - CompletableFuture> updateDocument( - final String key, - final T value, - final DocumentUpdateOptions options); - - /** - * Partially updates the document identified by document-key. The value must contain a document with the attributes - * to patch (the patch document). All attributes from the patch document will be added to the existing document if - * they do not yet exist, and overwritten in the existing document if they do exist there. - * - * @param key The key of the document - * @param value A representation of a single document (POJO or {@link com.arangodb.util.RawData}) - * @param options Additional options - * @param returnType Type of the returned newDocument and/or oldDocument - * @return information about the document - * @see API - * Documentation - */ - CompletableFuture> updateDocument( - final String key, - final Object value, - final DocumentUpdateOptions options, - final Class returnType); - - /** - * Partially updates documents, the documents to update are specified by the _key attributes in the objects on - * values. Vales must contain a list of document updates with the attributes to patch (the patch documents). All - * attributes from the patch documents will be added to the existing documents if they do not yet exist, and - * overwritten in the existing documents if they do exist there. - * - * @param values Raw data representing a collection of documents - * @return information about the documents - * @see - * API - * Documentation - */ - CompletableFuture>> updateDocuments(final RawData values); - - /** - * Partially updates documents, the documents to update are specified by the _key attributes in the objects on - * values. Vales must contain a list of document updates with the attributes to patch (the patch documents). All - * attributes from the patch documents will be added to the existing documents if they do not yet exist, and - * overwritten in the existing documents if they do exist there. - * - * @param values Raw data representing a collection of documents - * @param options Additional options - * @return information about the documents - * @see - * API - * Documentation - */ - CompletableFuture>> updateDocuments( - final RawData values, - final DocumentUpdateOptions options); - - /** - * Partially updates documents, the documents to update are specified by the _key attributes in the objects on - * values. Vales must contain a list of document updates with the attributes to patch (the patch documents). All - * attributes from the patch documents will be added to the existing documents if they do not yet exist, and - * overwritten in the existing documents if they do exist there. - * - * @param values A list of documents (POJO or {@link com.arangodb.util.RawData}) - * @return information about the documents - * @see - * API - * Documentation - */ - CompletableFuture>> updateDocuments(final Collection values); - - /** - * Partially updates documents, the documents to update are specified by the _key attributes in the objects on - * values. Vales must contain a list of document updates with the attributes to patch (the patch documents). All - * attributes from the patch documents will be added to the existing documents if they do not yet exist, and - * overwritten in the existing documents if they do exist there. - * - * @param values A list of documents (POJO or {@link com.arangodb.util.RawData}) - * @param options Additional options - * @return information about the documents - * @see - * API - * Documentation - */ - CompletableFuture>> updateDocuments( - final Collection values, - final DocumentUpdateOptions options); - - /** - * Partially updates documents, the documents to update are specified by the _key attributes in the objects on - * values. Vales must contain a list of document updates with the attributes to patch (the patch documents). All - * attributes from the patch documents will be added to the existing documents if they do not yet exist, and - * overwritten in the existing documents if they do exist there. - * - * @param values A list of documents (POJO or {@link com.arangodb.util.RawData}) - * @param options Additional options - * @param returnType Type of the returned newDocument and/or oldDocument - * @return information about the documents - * @see - * API - * Documentation - */ - CompletableFuture>> updateDocuments( - final Collection values, - final DocumentUpdateOptions options, - final Class returnType); - - /** - * Removes a document - * - * @param key The key of the document - * @return information about the document - * @see - * API - * Documentation - */ - CompletableFuture> deleteDocument(final String key); - - /** - * Removes a document - * - * @param key The key of the document - * @param options Additional options - * @return information about the document - * @see - * API - * Documentation - */ - CompletableFuture> deleteDocument( - final String key, - final DocumentDeleteOptions options); - - /** - * Removes a document - * - * @param key The key of the document - * @param type Deserialization target type for the returned documents. - * @param options Additional options - * @return information about the document - * @see - * API - * Documentation - */ - CompletableFuture> deleteDocument( - final String key, - final DocumentDeleteOptions options, - final Class type); - - /** - * Removes multiple document - * - * @param values Raw data representing the keys of the documents or the documents themselves - * @return information about the documents - * @see API - * Documentation - */ - CompletableFuture>> deleteDocuments(final RawData values); - - /** - * Removes multiple document - * - * @param values Raw data representing the keys of the documents or the documents themselves - * @param options Additional options - * @return information about the documents - * @see API - * Documentation - */ - CompletableFuture>> deleteDocuments( - final RawData values, - final DocumentDeleteOptions options); - - /** - * Removes multiple document - * - * @param values The keys of the documents or the documents themselves - * @return information about the documents - * @see API - * Documentation - */ - CompletableFuture>> deleteDocuments(final Collection values); - - /** - * Removes multiple document - * - * @param values The keys of the documents or the documents themselves - * @param options Additional options - * @return information about the documents - * @see API - * Documentation - */ - CompletableFuture>> deleteDocuments( - final Collection values, - final DocumentDeleteOptions options); - - /** - * Removes multiple document - * - * @param values The keys of the documents or the documents themselves - * @param type Deserialization target type for the returned documents. - * @param options Additional options - * @return information about the documents - * @see API - * Documentation - */ - CompletableFuture>> deleteDocuments( - final Collection values, - final DocumentDeleteOptions options, - final Class type); - - /** - * Checks if the document exists by reading a single document head - * - * @param key The key of the document - * @return true if the document was found, otherwise false - * @see API - * Documentation - */ - CompletableFuture documentExists(final String key); - - /** - * Checks if the document exists by reading a single document head - * - * @param key The key of the document - * @param options Additional options, can be null - * @return true if the document was found, otherwise false - * @see API - * Documentation - */ - CompletableFuture documentExists(final String key, final DocumentExistsOptions options); - - /** - * Returns an index - *
- * Note: inverted indexes are not returned by this method. Use - * {@link ArangoCollectionAsync#getInvertedIndex(String)} instead. - * - * @param id The index-handle - * @return information about the index - * @see - * API Documentation - */ - CompletableFuture getIndex(final String id); - - /** - * Returns an inverted index - * - * @param id The index-handle - * @return information about the index - * @see API Documentation - * @since ArangoDB 3.10 - */ - CompletableFuture getInvertedIndex(String id); - - /** - * Deletes an index - * - * @param id The index-handle - * @return the id of the index - * @see - * API Documentation - */ - CompletableFuture deleteIndex(final String id); - - /** - * Creates a persistent index for the collection, if it does not already exist. - * - * @param fields A list of attribute paths - * @param options Additional options, can be null - * @return information about the index - * @see API - * Documentation - */ - CompletableFuture ensurePersistentIndex( - final Iterable fields, - final PersistentIndexOptions options); - - /** - * Creates a geo-spatial index for the collection, if it does not already exist. - * - * @param fields A list of attribute paths - * @param options Additional options, can be null - * @return information about the index - * @see API - * Documentation - */ - CompletableFuture ensureGeoIndex(final Iterable fields, final GeoIndexOptions options); - - /** - * Creates a fulltext index for the collection, if it does not already exist. - * - * @param fields A list of attribute paths - * @param options Additional options, can be null - * @return information about the index - * @see API - * Documentation - * @deprecated since ArangoDB 3.10, use ArangoSearch or Inverted indexes instead. - */ - @Deprecated - CompletableFuture ensureFulltextIndex( - final Iterable fields, - final FulltextIndexOptions options); - - /** - * Creates a ttl index for the collection, if it does not already exist. - * - * @param fields A list of attribute paths - * @param options Additional options, can be null - * @return information about the index - * @see API - * Documentation - */ - CompletableFuture ensureTtlIndex(Iterable fields, TtlIndexOptions options); - - /** - * Creates a ZKD multi-dimensional index for the collection, if it does not already exist. - * Note that zkd indexes are an experimental feature in ArangoDB 3.9. - * - * @param fields A list of attribute paths - * @param options Additional options, can be null - * @return information about the index - * @see API Documentation - * @since ArangoDB 3.9 - */ - CompletableFuture ensureZKDIndex(final Iterable fields, final ZKDIndexOptions options); - - /** - * Creates an inverted index for the collection, if it does not already exist. - * - * @param options index creation options - * @return information about the index - * @see API Documentation - * @since ArangoDB 3.10 - */ - CompletableFuture ensureInvertedIndex(InvertedIndexOptions options); - - /** - * Returns all indexes of the collection - *
- * Note: inverted indexes are not returned by this method. Use - * {@link ArangoCollectionAsync#getInvertedIndexes()} instead. - * - * @return information about the indexes - * @see API - * Documentation - */ - CompletableFuture> getIndexes(); - - /** - * Fetches a list of all inverted indexes on this collection. - * - * @return information about the indexes - * @see API - * Documentation - * @since ArangoDB 3.10 - */ - CompletableFuture> getInvertedIndexes(); - - /** - * Checks whether the collection exists - * - * @return true if the collection exists, otherwise false - */ - CompletableFuture exists(); - - /** - * Removes all documents from the collection, but leaves the indexes intact - * - * @return information about the collection - * @see API - * Documentation - */ - CompletableFuture truncate(); - - /** - * Removes all documents from the collection, but leaves the indexes intact - * - * @return information about the collection - * @see API - * Documentation - */ - CompletableFuture truncate(CollectionTruncateOptions options); - - /** - * Counts the documents in a collection - * - * @return information about the collection, including the number of documents - * @see API - * Documentation - */ - CompletableFuture count(); - - /** - * Counts the documents in a collection - * - * @return information about the collection, including the number of documents - * @see API - * Documentation - */ - CompletableFuture count(CollectionCountOptions options); - - /** - * Creates the collection - * - * @return information about the collection - * @see API - * Documentation - */ - CompletableFuture create(); - - /** - * Creates the collection - * - * @param options Additional options, can be null - * @return information about the collection - * @see API - * Documentation - */ - CompletableFuture create(final CollectionCreateOptions options); - - /** - * Drops the collection - * - * @return void - * @see API - * Documentation - */ - CompletableFuture drop(); - - /** - * Drops the collection - * - * @param isSystem Whether or not the collection to drop is a system collection. This parameter must be set to - * true in - * order to drop a system collection. - * @return void - * @see API - * Documentation - */ - CompletableFuture drop(final boolean isSystem); - - /** - * Returns information about the collection - * - * @return information about the collection - * @see API - * Documentation - */ - CompletableFuture getInfo(); - - /** - * Reads the properties of the specified collection - * - * @return properties of the collection - * @see API - * Documentation - */ - CompletableFuture getProperties(); - - /** - * Changes the properties of a collection - * - * @param options Additional options, can be null - * @return properties of the collection - * @see API - * Documentation - */ - CompletableFuture changeProperties(final CollectionPropertiesOptions options); - - /** - * Renames a collection - * - * @param newName The new name - * @return information about the collection - * @see API - * Documentation - */ - CompletableFuture rename(final String newName); - - /** - * Returns the responsible shard for the document. - * Please note that this API is only meaningful and available on a cluster coordinator. - * - * @param value A projection of the document containing at least the shard key (_key or a custom attribute) for - * which the responsible shard should be determined - * @return information about the responsible shard - * @see - * - * API Documentation - * @since ArangoDB 3.5.0 - */ - CompletableFuture getResponsibleShard(final Object value); - - /** - * Retrieve the collections revision - * - * @return information about the collection, including the collections revision - * @see - * API - * Documentation - */ - CompletableFuture getRevision(); - - /** - * Grants or revoke access to the collection for user user. You need permission to the _system database in order to - * execute this call. - * - * @param user The name of the user - * @param permissions The permissions the user grant - * @return void - * @see API - * Documentation - */ - CompletableFuture grantAccess(final String user, final Permissions permissions); - - /** - * Revokes access to the collection for user user. You need permission to the _system database in order to execute - * this call. - * - * @param user The name of the user - * @return void - * @see API - * Documentation - */ - CompletableFuture revokeAccess(final String user); - - /** - * Clear the collection access level, revert back to the default access level. - * - * @param user The name of the user - * @return void - * @see API - * Documentation - * @since ArangoDB 3.2.0 - */ - CompletableFuture resetAccess(final String user); - - /** - * Get the collection access level - * - * @param user The name of the user - * @return permissions of the user - * @see - * - * API Documentation - * @since ArangoDB 3.2.0 - */ - CompletableFuture getPermissions(final String user); -} diff --git a/core/src/main/java/com/arangodb/async/ArangoCursorAsync.java b/core/src/main/java/com/arangodb/async/ArangoCursorAsync.java deleted file mode 100644 index e615bb401..000000000 --- a/core/src/main/java/com/arangodb/async/ArangoCursorAsync.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * DISCLAIMER - * - * Copyright 2016 ArangoDB GmbH, Cologne, Germany - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Copyright holder is ArangoDB GmbH, Cologne, Germany - */ - -package com.arangodb.async; - -import com.arangodb.ArangoCursor; - -import java.util.stream.Stream; - -/** - * @author Mark Vollmary - */ -public interface ArangoCursorAsync extends ArangoCursor { - - Stream streamRemaining(); - -} diff --git a/core/src/main/java/com/arangodb/async/ArangoDBAsync.java b/core/src/main/java/com/arangodb/async/ArangoDBAsync.java deleted file mode 100644 index 7d9ce542d..000000000 --- a/core/src/main/java/com/arangodb/async/ArangoDBAsync.java +++ /dev/null @@ -1,346 +0,0 @@ -/* - * DISCLAIMER - * - * Copyright 2016 ArangoDB GmbH, Cologne, Germany - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Copyright holder is ArangoDB GmbH, Cologne, Germany - */ - -package com.arangodb.async; - -import com.arangodb.*; -import com.arangodb.async.internal.ArangoDBAsyncImpl; -import com.arangodb.entity.*; -import com.arangodb.internal.InternalArangoDBBuilder; -import com.arangodb.internal.net.*; -import com.arangodb.model.DBCreateOptions; -import com.arangodb.model.LogOptions; -import com.arangodb.model.UserCreateOptions; -import com.arangodb.model.UserUpdateOptions; - -import javax.annotation.concurrent.ThreadSafe; -import java.util.Collection; -import java.util.ServiceLoader; -import java.util.concurrent.CompletableFuture; - -/** - * Central access point for applications to communicate with an ArangoDB server. - * - *

- * Will be instantiated through {@link ArangoDBAsync.Builder} - *

- * - *
- * ArangoDBAsync arango = new ArangoDBAsync.Builder().build();
- * ArangoDBAsync arango = new ArangoDBAsync.Builder().host("127.0.0.1", 8529).build();
- * 
- * - * @author Mark Vollmary - */ -@ThreadSafe -public interface ArangoDBAsync extends ArangoSerdeAccessor { - - void shutdown(); - - /** - * Updates the JWT used for requests authorization. It does not change already existing VST connections, since VST - * connections are authenticated during the initialization phase. - * - * @param jwt token to use - */ - void updateJwt(String jwt); - - /** - * Returns a handler of the system database - * - * @return database handler - */ - ArangoDatabaseAsync db(); - - /** - * Returns a handler of the database by the given name - * - * @param dbName Name of the database - * @return database handler - */ - ArangoDatabaseAsync db(final DbName dbName); - - /** - * @return entry point for accessing client metrics - */ - ArangoMetrics metrics(); - - /** - * Creates a new database - * - * @param dbName database name - * @return true if the database was created successfully. - * @see API - * Documentation - */ - CompletableFuture createDatabase(final DbName dbName); - - /** - * Creates a new database - * - * @param options Creation options - * @return true if the database was created successfully. - * @see API - * Documentation - * @since ArangoDB 3.6.0 - */ - CompletableFuture createDatabase(final DBCreateOptions options); - - /** - * Retrieves a list of all existing databases - * - * @return a list of all existing databases - * @see API - * Documentation - */ - CompletableFuture> getDatabases(); - - /** - * Retrieves a list of all databases the current user can access - * - * @return a list of all databases the current user can access - * @see API - * Documentation - */ - CompletableFuture> getAccessibleDatabases(); - - /** - * List available database to the specified user - * - * @param user The name of the user for which you want to query the databases - * @return - * @see API - * Documentation - */ - CompletableFuture> getAccessibleDatabasesFor(final String user); - - /** - * Returns the server name and version number. - * - * @return the server version, number - * @see API - * Documentation - */ - CompletableFuture getVersion(); - - /** - * Returns the server role. - * - * @return the server role - */ - CompletableFuture getRole(); - - /** - * Create a new user. This user will not have access to any database. You need permission to the _system database in - * order to execute this call. - * - * @param user The name of the user - * @param passwd The user password - * @return information about the user - * @see API Documentation - */ - CompletableFuture createUser(final String user, final String passwd); - - /** - * Create a new user. This user will not have access to any database. You need permission to the _system database in - * order to execute this call. - * - * @param user The name of the user - * @param passwd The user password - * @param options Additional properties of the user, can be null - * @return information about the user - * @see API Documentation - */ - CompletableFuture createUser(final String user, final String passwd, final UserCreateOptions options); - - /** - * Removes an existing user, identified by user. You need access to the _system database. - * - * @param user The name of the user - * @return void - * @see API Documentation - */ - CompletableFuture deleteUser(final String user); - - /** - * Fetches data about the specified user. You can fetch information about yourself or you need permission to the - * _system database in order to execute this call. - * - * @param user The name of the user - * @return information about the user - * @see API Documentation - */ - CompletableFuture getUser(final String user); - - /** - * Fetches data about all users. You can only execute this call if you have access to the _system database. - * - * @return informations about all users - * @see API - * Documentation - */ - CompletableFuture> getUsers(); - - /** - * Partially updates the data of an existing user. The name of an existing user must be specified in user. You can - * only change the password of your self. You need access to the _system database to change the active flag. - * - * @param user The name of the user - * @param options Properties of the user to be changed - * @return information about the user - * @see API Documentation - */ - CompletableFuture updateUser(final String user, final UserUpdateOptions options); - - /** - * Replaces the data of an existing user. The name of an existing user must be specified in user. You can only - * change the password of your self. You need access to the _system database to change the active flag. - * - * @param user The name of the user - * @param options Additional properties of the user, can be null - * @return information about the user - * @see API - * Documentation - */ - CompletableFuture replaceUser(final String user, final UserUpdateOptions options); - - /** - * Sets the default access level for databases for the user user. You need permission to the _system - * database in order to execute this call. - * - * @param user The name of the user - * @param permissions The permissions the user grant - * @return void - * @since ArangoDB 3.2.0 - */ - CompletableFuture grantDefaultDatabaseAccess(final String user, final Permissions permissions); - - /** - * Sets the default access level for collections for the user user. You need permission to the _system - * database in order to execute this call. - * - * @param user The name of the user - * @param permissions The permissions the user grant - * @return void - * @since ArangoDB 3.2.0 - */ - CompletableFuture grantDefaultCollectionAccess(final String user, final Permissions permissions); - - /** - * Execute custom requests. Requests can be programmatically built by setting low level detail such as method, path, - * query parameters, headers and body payload. - * This method can be used to call FOXX services, API endpoints not (yet) implemented in this driver or trigger - * async jobs, see - * Fire and Forget - * and - * Async Execution and later Result Retrieval - * - * @param request request - * @param type Deserialization target type for the response body (POJO or {@link com.arangodb.util.RawData}) - * @return response - */ - CompletableFuture> execute(final Request request, final Class type); - - /** - * Returns the server logs - * - * @param options Additional options, can be null - * @return the log messages - * @see API - * Documentation - * @since ArangoDB 3.8 - */ - CompletableFuture getLogEntries(final LogOptions options); - - /** - * Returns the server's current loglevel settings. - * - * @return the server's current loglevel settings - */ - CompletableFuture getLogLevel(); - - /** - * Modifies and returns the server's current loglevel settings. - * - * @param entity loglevel settings - * @return the server's current loglevel settings - */ - CompletableFuture setLogLevel(final LogLevelEntity entity); - - /** - * @return the list of available rules and their respective flags - * @since ArangoDB 3.10 - */ - CompletableFuture> getQueryOptimizerRules(); - - /** - * Builder class to build an instance of {@link ArangoDBAsync}. - * - * @author Mark Vollmary - */ - class Builder extends InternalArangoDBBuilder { - - private AsyncProtocolProvider asyncProtocolProvider(Protocol protocol) { - ServiceLoader loader = ServiceLoader.load(AsyncProtocolProvider.class); - for (AsyncProtocolProvider p : loader) { - if (p.supportsProtocol(protocol)) { - return p; - } - LOG.debug("Required protocol ({}) not supported by ProtocolProvider: {}", protocol, p.getClass().getName()); - } - throw new ArangoDBException("No ProtocolProvider found for protocol: " + protocol); - } - - /** - * Returns an instance of {@link ArangoDBAsync}. - * - * @return {@link ArangoDBAsync} - */ - public ArangoDBAsync build() { - if (config.getHosts().isEmpty()) { - throw new ArangoDBException("No host has been set!"); - } - - AsyncProtocolProvider asyncProtocolProvider = asyncProtocolProvider(Protocol.VST); - ProtocolProvider protocolProvider = protocolProvider(Protocol.VST); - - config.setProtocol(Protocol.VST); - config.setProtocolModule(asyncProtocolProvider.protocolModule()); - - final ConnectionFactory asyncConnectionFactory = asyncProtocolProvider.createConnectionFactory(); - final ConnectionFactory syncConnectionFactory = protocolProvider.createConnectionFactory(); - final HostResolver asyncHostResolver = createHostResolver(createHostList(asyncConnectionFactory), asyncConnectionFactory); - final HostResolver syncHostResolver = createHostResolver(createHostList(syncConnectionFactory), syncConnectionFactory); - final HostHandler asyncHostHandler = createHostHandler(asyncHostResolver); - final HostHandler syncHostHandler = createHostHandler(syncHostResolver); - return new ArangoDBAsyncImpl( - config, - asyncHostResolver, - syncHostResolver, - asyncProtocolProvider, - protocolProvider, - asyncHostHandler, - syncHostHandler - ); - } - } -} diff --git a/core/src/main/java/com/arangodb/async/ArangoDatabaseAsync.java b/core/src/main/java/com/arangodb/async/ArangoDatabaseAsync.java deleted file mode 100644 index bbd46f8b6..000000000 --- a/core/src/main/java/com/arangodb/async/ArangoDatabaseAsync.java +++ /dev/null @@ -1,773 +0,0 @@ -/* - * DISCLAIMER - * - * Copyright 2016 ArangoDB GmbH, Cologne, Germany - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Copyright holder is ArangoDB GmbH, Cologne, Germany - */ - -package com.arangodb.async; - -import com.arangodb.ArangoSerdeAccessor; -import com.arangodb.DbName; -import com.arangodb.entity.*; -import com.arangodb.entity.arangosearch.analyzer.SearchAnalyzer; -import com.arangodb.model.*; -import com.arangodb.model.arangosearch.AnalyzerDeleteOptions; -import com.arangodb.model.arangosearch.ArangoSearchCreateOptions; -import com.arangodb.model.arangosearch.SearchAliasCreateOptions; - -import javax.annotation.concurrent.ThreadSafe; -import java.util.Collection; -import java.util.Map; -import java.util.concurrent.CompletableFuture; - -/** - * Interface for operations on ArangoDB database level. - * - * @author Mark Vollmary - * @see Databases API Documentation - * @see Query API Documentation - */ -@ThreadSafe -public interface ArangoDatabaseAsync extends ArangoSerdeAccessor { - - /** - * Return the main entry point for the ArangoDB driver - * - * @return main entry point - */ - ArangoDBAsync arango(); - - /** - * Returns the name of the database - * - * @return database name - */ - DbName dbName(); - - /** - * Returns the server name and version number. - * - * @return the server version, number - * @see API - * Documentation - */ - CompletableFuture getVersion(); - - /** - * Returns the name of the used storage engine. - * - * @return the storage engine name - * @see - * API - * Documentation - */ - CompletableFuture getEngine(); - - /** - * Checks whether the database exists - * - * @return true if the database exists, otherwise false - */ - CompletableFuture exists(); - - /** - * Retrieves a list of all databases the current user can access - * - * @return a list of all databases the current user can access - * @see API - * Documentation - */ - CompletableFuture> getAccessibleDatabases(); - - /** - * Returns a handler of the collection by the given name - * - * @param name Name of the collection - * @return collection handler - */ - ArangoCollectionAsync collection(final String name); - - /** - * Creates a collection - * - * @param name The name of the collection - * @return information about the collection - * @see API - * Documentation - */ - CompletableFuture createCollection(final String name); - - /** - * Creates a collection - * - * @param name The name of the collection - * @param options Additional options, can be null - * @return information about the collection - * @see API - * Documentation - */ - CompletableFuture createCollection(final String name, final CollectionCreateOptions options); - - /** - * Returns all collections - * - * @return list of information about all collections - * @see API - * Documentation - */ - CompletableFuture> getCollections(); - - /** - * Returns all collections - * - * @param options Additional options, can be null - * @return list of information about all collections - * @see API - * Documentation - */ - CompletableFuture> getCollections(final CollectionsReadOptions options); - - /** - * Returns an index - * - * @param id The index-handle - * @return information about the index - * @see - * API Documentation - */ - CompletableFuture getIndex(final String id); - - /** - * Deletes an index - * - * @param id The index handle - * @return the id of the index - * @see - * API Documentation - */ - CompletableFuture deleteIndex(final String id); - - /** - * Creates the database - * - * @return true if the database was created successfully. - * @see API - * Documentation - */ - CompletableFuture create(); - - /** - * Drop an existing database - * - * @return true if the database was dropped successfully - * @see API - * Documentation - */ - CompletableFuture drop(); - - /** - * Grants access to the database dbname for user user. You need permission to the _system database in order to - * execute this call. - * - * @param user The name of the user - * @param permissions The permissions the user grant - * @return void - * @see - * API Documentation - */ - CompletableFuture grantAccess(final String user, final Permissions permissions); - - /** - * Grants access to the database dbname for user user. You need permission to the _system database in order to - * execute this call. - * - * @param user The name of the user - * @return void - * @see - * API Documentation - */ - CompletableFuture grantAccess(final String user); - - /** - * Revokes access to the database dbname for user user. You need permission to the _system database in order to - * execute this call. - * - * @param user The name of the user - * @return void - * @see - * API Documentation - */ - CompletableFuture revokeAccess(final String user); - - /** - * Clear the database access level, revert back to the default access level. - * - * @param user The name of the user - * @return void - * @see - * API Documentation - * @since ArangoDB 3.2.0 - */ - CompletableFuture resetAccess(final String user); - - /** - * Sets the default access level for collections within this database for the user user. You need - * permission to the _system database in order to execute this call. - * - * @param user The name of the user - * @param permissions The permissions the user grant - * @since ArangoDB 3.2.0 - */ - CompletableFuture grantDefaultCollectionAccess(final String user, final Permissions permissions); - - /** - * Get specific database access level - * - * @param user The name of the user - * @return permissions of the user - * @see API - * Documentation - * @since ArangoDB 3.2.0 - */ - CompletableFuture getPermissions(final String user); - - /** - * Performs a database query using the given {@code query} and {@code bindVars}, then returns a new - * {@code ArangoCursor} instance for the result list. - * - * @param query contains the query string to be executed - * @param bindVars key/value pairs representing the bind parameters - * @param options Additional options, can be null - * @param type The type of the result (POJO or {@link com.arangodb.util.RawData}) - * @return cursor of the results - * @see - * API - * Documentation - */ - CompletableFuture> query( - final String query, - final Map bindVars, - final AqlQueryOptions options, - final Class type); - - /** - * Performs a database query using the given {@code query}, then returns a new {@code ArangoCursor} instance for the - * result list. - * - * @param query contains the query string to be executed - * @param options Additional options, can be null - * @param type The type of the result (POJO or {@link com.arangodb.util.RawData}) - * @return cursor of the results - * @see - * API - * Documentation - */ - CompletableFuture> query( - final String query, - final AqlQueryOptions options, - final Class type); - - /** - * Performs a database query using the given {@code query} and {@code bindVars}, then returns a new - * {@code ArangoCursor} instance for the result list. - * - * @param query contains the query string to be executed - * @param bindVars key/value pairs representing the bind parameters - * @param type The type of the result (POJO or {@link com.arangodb.util.RawData}) - * @return cursor of the results - * @see - * API - * Documentation - */ - CompletableFuture> query( - final String query, - final Map bindVars, - final Class type); - - /** - * Performs a database query using the given {@code query}, then returns a new {@code ArangoCursor} instance for the - * result list. - * - * @param query contains the query string to be executed - * @param type The type of the result (POJO or {@link com.arangodb.util.RawData}) - * @return cursor of the results - * @see - * API - * Documentation - */ - CompletableFuture> query(final String query, final Class type); - - /** - * Return an cursor from the given cursor-ID if still existing - * - * @param cursorId The ID of the cursor - * @param type The type of the result (POJO or {@link com.arangodb.util.RawData}) - * @return cursor of the results - * @see API - * Documentation - */ - CompletableFuture> cursor(final String cursorId, final Class type); - - /** - * Explain an AQL query and return information about it - * - * @param query the query which you want explained - * @param bindVars key/value pairs representing the bind parameters - * @param options Additional options, can be null - * @return information about the query - * @see API - * Documentation - */ - CompletableFuture explainQuery( - final String query, - final Map bindVars, - final AqlQueryExplainOptions options); - - /** - * Parse an AQL query and return information about it This method is for query validation only. To actually query - * the database, see {@link ArangoDatabaseAsync#query(String, Map, AqlQueryOptions, Class)} - * - * @param query the query which you want parse - * @return imformation about the query - * @see API - * Documentation - */ - CompletableFuture parseQuery(final String query); - - /** - * Clears the AQL query cache - * - * @return void - * @see API - * Documentation - */ - CompletableFuture clearQueryCache(); - - /** - * Returns the global configuration for the AQL query cache - * - * @return configuration for the AQL query cache - * @see API - * Documentation - */ - CompletableFuture getQueryCacheProperties(); - - /** - * Changes the configuration for the AQL query cache. Note: changing the properties may invalidate all results in - * the cache. - * - * @param properties properties to be set - * @return current set of properties - * @see API - * Documentation - */ - CompletableFuture setQueryCacheProperties(final QueryCachePropertiesEntity properties); - - /** - * Returns the configuration for the AQL query tracking - * - * @return configuration for the AQL query tracking - * @see API - * Documentation - */ - CompletableFuture getQueryTrackingProperties(); - - /** - * Changes the configuration for the AQL query tracking - * - * @param properties properties to be set - * @return current set of properties - * @see API - * Documentation - */ - CompletableFuture setQueryTrackingProperties( - final QueryTrackingPropertiesEntity properties); - - /** - * Returns a list of currently running AQL queries - * - * @return a list of currently running AQL queries - * @see API - * Documentation - */ - CompletableFuture> getCurrentlyRunningQueries(); - - /** - * Returns a list of slow running AQL queries - * - * @return a list of slow running AQL queries - * @see API - * Documentation - */ - CompletableFuture> getSlowQueries(); - - /** - * Clears the list of slow AQL queries - * - * @return void - * @see API - * Documentation - */ - CompletableFuture clearSlowQueries(); - - /** - * Kills a running query. The query will be terminated at the next cancelation point. - * - * @param id The id of the query - * @return void - * @see API - * Documentation - */ - CompletableFuture killQuery(final String id); - - /** - * Create a new AQL user function - * - * @param name the fully qualified name of the user functions - * @param code a string representation of the function body - * @param options Additional options, can be null - * @return void - * @see API - * Documentation - */ - CompletableFuture createAqlFunction( - final String name, - final String code, - final AqlFunctionCreateOptions options); - - /** - * Remove an existing AQL user function - * - * @param name the name of the AQL user function - * @param options Additional options, can be null - * @return number of deleted functions (since ArangoDB 3.4.0) - * @see API - * Documentation - */ - CompletableFuture deleteAqlFunction(final String name, final AqlFunctionDeleteOptions options); - - /** - * Gets all reqistered AQL user functions - * - * @param options Additional options, can be null - * @return all reqistered AQL user functions - * @see API - * Documentation - */ - CompletableFuture> getAqlFunctions(final AqlFunctionGetOptions options); - - /** - * Returns a handler of the graph by the given name - * - * @param name Name of the graph - * @return graph handler - */ - ArangoGraphAsync graph(final String name); - - /** - * Create a new graph in the graph module. The creation of a graph requires the name of the graph and a definition - * of its edges. - * - * @param name Name of the graph - * @param edgeDefinitions An array of definitions for the edge - * @return information about the graph - * @see API - * Documentation - */ - CompletableFuture createGraph(final String name, final Collection edgeDefinitions); - - /** - * Create a new graph in the graph module. The creation of a graph requires the name of the graph and a definition - * of its edges. - * - * @param name Name of the graph - * @param edgeDefinitions An array of definitions for the edge - * @param options Additional options, can be null - * @return information about the graph - * @see API - * Documentation - */ - CompletableFuture createGraph( - final String name, - final Collection edgeDefinitions, - final GraphCreateOptions options); - - /** - * Lists all graphs known to the graph module - * - * @return graphs stored in this database - * @see API - * Documentation - */ - CompletableFuture> getGraphs(); - - /** - * Execute a server-side transaction - * - * @param action the actual transaction operations to be executed, in the form of stringified JavaScript code - * @param type The type of the result (POJO or {@link com.arangodb.util.RawData}) - * @param options Additional options, can be null - * @return the result of the transaction if it succeeded - * @see API - * Documentation - */ - CompletableFuture transaction(final String action, final Class type, final TransactionOptions options); - - /** - * Begins a Stream Transaction. - * - * @param options Additional options, can be null - * @return information about the transaction - * @see - * API - * Documentation - * @since ArangoDB 3.5.0 - */ - CompletableFuture beginStreamTransaction(StreamTransactionOptions options); - - /** - * Aborts a Stream Transaction. - * - * @return information about the transaction - * @see - * API - * Documentation - */ - CompletableFuture abortStreamTransaction(String id); - - /** - * Gets information about a Stream Transaction. - * - * @return information about the transaction - * @see - * - * API Documentation - * @since ArangoDB 3.5.0 - */ - CompletableFuture getStreamTransaction(String id); - - /** - * Gets all the currently running Stream Transactions. - * - * @return all the currently running Stream Transactions - * @see - * - * API Documentation - * @since ArangoDB 3.5.0 - */ - CompletableFuture> getStreamTransactions(); - - /** - * Commits a Stream Transaction. - * - * @return information about the transaction - * @see - * - * API Documentation - * @since ArangoDB 3.5.0 - */ - CompletableFuture commitStreamTransaction(String id); - - /** - * Retrieves information about the current database - * - * @return information about the current database - * @see API - * Documentation - */ - CompletableFuture getInfo(); - - /** - * Reads a single document - * - * @param id The id of the document - * @param type The type of the document (POJO or {@link com.arangodb.util.RawData}) - * @return the document identified by the id - * @see API - * Documentation - */ - CompletableFuture getDocument(final String id, final Class type); - - /** - * Reads a single document - * - * @param id The id of the document - * @param type The type of the document (POJO or {@link com.arangodb.util.RawData}) - * @param options Additional options, can be null - * @return the document identified by the id - * @see API - * Documentation - */ - CompletableFuture getDocument(final String id, final Class type, final DocumentReadOptions options); - - /** - * Reload the routing table. - * - * @return void - * @see API - * Documentation - */ - CompletableFuture reloadRouting(); - - /** - * Returns a new {@link ArangoRouteAsync} instance for the given path (relative to the database) that can be used to - * perform arbitrary requests. - * - * @param path The database-relative URL of the route - * @return {@link ArangoRouteAsync} - */ - ArangoRouteAsync route(String... path); - - /** - * Fetches all views from the database and returns an list of view descriptions. - * - * @return list of information about all views - * @see - * API Documentation - * @since ArangoDB 3.4.0 - */ - CompletableFuture> getViews(); - - /** - * Returns a {@code ArangoViewAsync} instance for the given view name. - * - * @param name Name of the view - * @return view handler - * @since ArangoDB 3.4.0 - */ - ArangoViewAsync view(String name); - - /** - * Returns a {@link ArangoSearchAsync} instance for the given ArangoSearch view name. - * - * @param name Name of the view - * @return ArangoSearch view handler - * @since ArangoDB 3.4.0 - */ - ArangoSearchAsync arangoSearch(String name); - - /** - * Returns a {@link SearchAliasAsync} instance for the given view name. - * - * @param name Name of the view - * @return SearchAlias view handler - * @since ArangoDB 3.10 - */ - SearchAliasAsync searchAlias(String name); - - /** - * Creates a view of the given {@code type}, then returns view information from the server. - * - * @param name The name of the view - * @param type The type of the view - * @return information about the view - * @since ArangoDB 3.4.0 - */ - CompletableFuture createView(String name, ViewType type); - - /** - * Creates a ArangoSearch view with the given {@code options}, then returns view information from the server. - * - * @param name The name of the view - * @param options Additional options, can be null - * @return information about the view - * @see API - * Documentation - * @since ArangoDB 3.4.0 - */ - CompletableFuture createArangoSearch(String name, ArangoSearchCreateOptions options); - - /** - * Creates a SearchAlias view with the given {@code options}, then returns view information from the server. - * - * @param name The name of the view - * @param options Additional options, can be null - * @return information about the view - * @see API - * Documentation - * @since ArangoDB 3.10 - */ - CompletableFuture createSearchAlias(String name, SearchAliasCreateOptions options); - - /** - * Creates an Analyzer - * - * @param analyzer SearchAnalyzer - * @return the created Analyzer - * @see API Documentation - * @since ArangoDB 3.5.0 - */ - CompletableFuture createSearchAnalyzer(SearchAnalyzer analyzer); - - /** - * Gets information about an Analyzer - * - * @param name of the Analyzer without database prefix - * @return information about an Analyzer - * @see API Documentation - * @since ArangoDB 3.5.0 - */ - CompletableFuture getSearchAnalyzer(String name); - - /** - * Retrieves all analyzers definitions. - * - * @return collection of all analyzers definitions - * @see API Documentation - * @since ArangoDB 3.5.0 - */ - CompletableFuture> getSearchAnalyzers(); - - /** - * Deletes an Analyzer - * - * @param name of the Analyzer without database prefix - * @see API Documentation - * @since ArangoDB 3.5.0 - */ - CompletableFuture deleteSearchAnalyzer(String name); - - /** - * Deletes an Analyzer - * - * @param name of the Analyzer without database prefix - * @param options AnalyzerDeleteOptions - * @see API Documentation - * @since ArangoDB 3.5.0 - */ - CompletableFuture deleteSearchAnalyzer(String name, AnalyzerDeleteOptions options); - -} diff --git a/core/src/main/java/com/arangodb/async/ArangoEdgeCollectionAsync.java b/core/src/main/java/com/arangodb/async/ArangoEdgeCollectionAsync.java deleted file mode 100644 index 4af39cd32..000000000 --- a/core/src/main/java/com/arangodb/async/ArangoEdgeCollectionAsync.java +++ /dev/null @@ -1,180 +0,0 @@ -/* - * DISCLAIMER - * - * Copyright 2016 ArangoDB GmbH, Cologne, Germany - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Copyright holder is ArangoDB GmbH, Cologne, Germany - */ - -package com.arangodb.async; - -import com.arangodb.ArangoSerdeAccessor; -import com.arangodb.entity.EdgeEntity; -import com.arangodb.entity.EdgeUpdateEntity; -import com.arangodb.model.*; - -import javax.annotation.concurrent.ThreadSafe; -import java.util.concurrent.CompletableFuture; - -/** - * Interface for operations on ArangoDB edge collection level. - * - * @author Mark Vollmary - * @see API Documentation - */ -@ThreadSafe -public interface ArangoEdgeCollectionAsync extends ArangoSerdeAccessor { - - /** - * The the handler of the named graph the edge collection is within - * - * @return graph handler - */ - ArangoGraphAsync graph(); - - /** - * The name of the edge collection - * - * @return collection name - */ - String name(); - - /** - * Remove one edge definition from the graph. - * - * @see API - * Documentation - */ - CompletableFuture drop(); - - /** - * Remove one edge definition from the graph. - * - * @param options options - * @see API - * Documentation - */ - CompletableFuture drop(EdgeCollectionDropOptions options); - - /** - * Creates a new edge in the collection - * - * @param value A representation of a single edge (POJO or {@link com.arangodb.util.RawData} - * @return information about the edge - * @see API Documentation - */ - CompletableFuture insertEdge(final Object value); - - /** - * Creates a new edge in the collection - * - * @param value A representation of a single edge (POJO or {@link com.arangodb.util.RawData} - * @param options Additional options, can be null - * @return information about the edge - * @see API Documentation - */ - CompletableFuture insertEdge(final Object value, final EdgeCreateOptions options); - - /** - * Fetches an existing edge - * - * @param key The key of the edge - * @param type The type of the edge-document (POJO or {@link com.arangodb.util.RawData} - * @return the edge identified by the key - * @see API Documentation - */ - CompletableFuture getEdge(final String key, final Class type); - - /** - * Fetches an existing edge - * - * @param key The key of the edge - * @param type The type of the edge-document (POJO or {@link com.arangodb.util.RawData} - * @param options Additional options, can be null - * @return the edge identified by the key - * @see API Documentation - */ - CompletableFuture getEdge(final String key, final Class type, final GraphDocumentReadOptions options); - - /** - * Replaces the edge with key with the one in the body, provided there is such a edge and no precondition is - * violated - * - * @param key The key of the edge - * @return information about the edge - * @see API Documentation - */ - CompletableFuture replaceEdge(final String key, final Object value); - - /** - * Replaces the edge with key with the one in the body, provided there is such a edge and no precondition is - * violated - * - * @param key The key of the edge - * @param options Additional options, can be null - * @return information about the edge - * @see API Documentation - */ - CompletableFuture replaceEdge( - final String key, - final Object value, - final EdgeReplaceOptions options); - - /** - * Partially updates the edge identified by document-key. The value must contain a document with the attributes to - * patch (the patch document). All attributes from the patch document will be added to the existing document if they - * do not yet exist, and overwritten in the existing document if they do exist there. - * - * @param key The key of the edge - * @return information about the edge - * @see API Documentation - */ - CompletableFuture updateEdge(final String key, final Object value); - - /** - * Partially updates the edge identified by document-key. The value must contain a document with the attributes to - * patch (the patch document). All attributes from the patch document will be added to the existing document if they - * do not yet exist, and overwritten in the existing document if they do exist there. - * - * @param key The key of the edge - * @param options Additional options, can be null - * @return information about the edge - * @see API Documentation - */ - CompletableFuture updateEdge( - final String key, - final Object value, - final EdgeUpdateOptions options); - - /** - * Removes a edge - * - * @param key The key of the edge - * @see API Documentation - */ - CompletableFuture deleteEdge(final String key); - - /** - * Removes a edge - * - * @param key The key of the edge - * @param options Additional options, can be null - * @see API Documentation - */ - CompletableFuture deleteEdge(final String key, final EdgeDeleteOptions options); - -} diff --git a/core/src/main/java/com/arangodb/async/ArangoGraphAsync.java b/core/src/main/java/com/arangodb/async/ArangoGraphAsync.java deleted file mode 100644 index cfdaa9b38..000000000 --- a/core/src/main/java/com/arangodb/async/ArangoGraphAsync.java +++ /dev/null @@ -1,210 +0,0 @@ -/* - * DISCLAIMER - * - * Copyright 2016 ArangoDB GmbH, Cologne, Germany - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Copyright holder is ArangoDB GmbH, Cologne, Germany - */ - -package com.arangodb.async; - -import com.arangodb.ArangoSerdeAccessor; -import com.arangodb.entity.EdgeDefinition; -import com.arangodb.entity.GraphEntity; -import com.arangodb.model.GraphCreateOptions; -import com.arangodb.model.ReplaceEdgeDefinitionOptions; -import com.arangodb.model.VertexCollectionCreateOptions; - -import javax.annotation.concurrent.ThreadSafe; -import java.util.Collection; -import java.util.concurrent.CompletableFuture; - -/** - * Interface for operations on ArangoDB graph level. - * - * @author Mark Vollmary - * @see API Documentation - */ -@ThreadSafe -public interface ArangoGraphAsync extends ArangoSerdeAccessor { - - /** - * The the handler of the database the named graph is within - * - * @return database handler - */ - ArangoDatabaseAsync db(); - - /** - * The name of the collection - * - * @return collection name - */ - String name(); - - /** - * Checks whether the graph exists - * - * @return true if the graph exists, otherwise false - */ - CompletableFuture exists(); - - /** - * Creates the graph in the graph module. The creation of a graph requires the name of the graph and a definition of - * its edges. - * - * @param edgeDefinitions An array of definitions for the edge - * @return information about the graph - * @see API - * Documentation - */ - CompletableFuture create(final Collection edgeDefinitions); - - /** - * Creates the graph in the graph module. The creation of a graph requires the name of the graph and a definition of - * its edges. - * - * @param edgeDefinitions An array of definitions for the edge - * @param options Additional options, can be null - * @return information about the graph - * @see API - * Documentation - */ - CompletableFuture createGraph( - final Collection edgeDefinitions, - final GraphCreateOptions options); - - /** - * Delete an existing graph - * - * @return void - * @see - * API Documentation - */ - CompletableFuture drop(); - - /** - * Delete an existing graph including - * - * @param dropCollections Drop collections of this graph as well. Collections will only be dropped if they are - * not used in other - * graphs. - * @return void - * @see - * API Documentation - */ - CompletableFuture drop(boolean dropCollections); - - /** - * Get a graph from the graph module - * - * @return the definition content of this graph - * @see - * API Documentation - */ - CompletableFuture getInfo(); - - /** - * Lists all vertex collections used in this graph - * - * @return all vertex collections within this graph - * @see API - * Documentation - */ - CompletableFuture> getVertexCollections(); - - /** - * Adds a vertex collection to the set of collections of the graph. If the collection does not exist, it will be - * created. - * - * @param name The name of the collection - * @return information about the graph - * @see API - * Documentation - */ - CompletableFuture addVertexCollection(final String name); - - /** - * Adds a vertex collection to the set of collections of the graph. If the collection does not exist, it will be - * created. - * - * @param name The name of the collection - * @param options additional options - * @return information about the graph - * @see API - * Documentation - * @since ArangoDB 3.9 - */ - CompletableFuture addVertexCollection(final String name, final VertexCollectionCreateOptions options); - - /** - * Returns a handler of the vertex collection by the given name - * - * @param name Name of the vertex collection - * @return collection handler - */ - ArangoVertexCollectionAsync vertexCollection(final String name); - - /** - * Returns a handler of the edge collection by the given name - * - * @param name Name of the edge collection - * @return collection handler - */ - ArangoEdgeCollectionAsync edgeCollection(final String name); - - /** - * Lists all edge collections used in this graph - * - * @return all edge collections within this graph - * @see API - * Documentation - */ - CompletableFuture> getEdgeDefinitions(); - - /** - * Add a new edge definition to the graph - * - * @param definition - * @return information about the graph - * @see API - * Documentation - */ - CompletableFuture addEdgeDefinition(final EdgeDefinition definition); - - /** - * Change one specific edge definition. This will modify all occurrences of this definition in all graphs known to - * your database - * - * @param definition The edge definition - * @return information about the graph - * @see API - * Documentation - */ - CompletableFuture replaceEdgeDefinition(final EdgeDefinition definition); - - /** - * Change one specific edge definition. This will modify all occurrences of this definition in all graphs known to - * your database - * - * @param definition The edge definition - * @param options options - * @return information about the graph - * @see API - * Documentation - */ - CompletableFuture replaceEdgeDefinition(final EdgeDefinition definition, final ReplaceEdgeDefinitionOptions options); - -} diff --git a/core/src/main/java/com/arangodb/async/ArangoRouteAsync.java b/core/src/main/java/com/arangodb/async/ArangoRouteAsync.java deleted file mode 100644 index c2ab2d221..000000000 --- a/core/src/main/java/com/arangodb/async/ArangoRouteAsync.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * DISCLAIMER - * - * Copyright 2018 ArangoDB GmbH, Cologne, Germany - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Copyright holder is ArangoDB GmbH, Cologne, Germany - */ - -package com.arangodb.async; - -import com.arangodb.ArangoSerdeAccessor; -import com.arangodb.internal.InternalResponse; - -import java.util.concurrent.CompletableFuture; - -/** - * Interface for a specific path to be used to perform arbitrary requests. - * - * @author Mark Vollmary - */ -public interface ArangoRouteAsync extends ArangoSerdeAccessor { - - /** - * Returns a new {@link ArangoRouteAsync} instance for the given path (relative to the current route) that can be - * used to perform arbitrary requests. - * - * @param path The relative URL of the route - * @return {@link ArangoRouteAsync} - */ - ArangoRouteAsync route(String... path); - - /** - * Header that should be sent with each request to the route. - * - * @param key Header key - * @param value Header value (the toString() method will be called for the value} - * @return {@link ArangoRouteAsync} - */ - ArangoRouteAsync withHeader(String key, Object value); - - /** - * Query parameter that should be sent with each request to the route. - * - * @param key Query parameter key - * @param value Query parameter value (the toString() method will be called for the value} - * @return {@link ArangoRouteAsync} - */ - ArangoRouteAsync withQueryParam(String key, Object value); - - /** - * The response body. - * - * @param body The response body - * @return {@link ArangoRouteAsync} - */ - ArangoRouteAsync withBody(Object body); - - /** - * Performs a DELETE request to the given URL and returns the server response. - * - * @return server response - */ - CompletableFuture delete(); - - /** - * Performs a GET request to the given URL and returns the server response. - * - * @return server response - */ - - CompletableFuture get(); - - /** - * Performs a HEAD request to the given URL and returns the server response. - * - * @return server response - */ - - CompletableFuture head(); - - /** - * Performs a PATCH request to the given URL and returns the server response. - * - * @return server response - */ - - CompletableFuture patch(); - - /** - * Performs a POST request to the given URL and returns the server response. - * - * @return server response - */ - - CompletableFuture post(); - - /** - * Performs a PUT request to the given URL and returns the server response. - * - * @return server response - */ - - CompletableFuture put(); - -} diff --git a/core/src/main/java/com/arangodb/async/ArangoSearchAsync.java b/core/src/main/java/com/arangodb/async/ArangoSearchAsync.java deleted file mode 100644 index 77f112a0d..000000000 --- a/core/src/main/java/com/arangodb/async/ArangoSearchAsync.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * DISCLAIMER - * - * Copyright 2018 ArangoDB GmbH, Cologne, Germany - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Copyright holder is ArangoDB GmbH, Cologne, Germany - */ - -package com.arangodb.async; - -import com.arangodb.entity.ViewEntity; -import com.arangodb.entity.arangosearch.ArangoSearchPropertiesEntity; -import com.arangodb.model.arangosearch.ArangoSearchCreateOptions; -import com.arangodb.model.arangosearch.ArangoSearchPropertiesOptions; - -import javax.annotation.concurrent.ThreadSafe; -import java.util.concurrent.CompletableFuture; - -/** - * Interface for operations on ArangoDB view level for ArangoSearch views. - * - * @author Mark Vollmary - * @see View API Documentation - * @since ArangoDB 3.4.0 - */ -@ThreadSafe -public interface ArangoSearchAsync extends ArangoViewAsync { - - /** - * Creates a view, then returns view information from the server. - * - * @return information about the view @ - * @see API - * Documentation - */ - CompletableFuture create(); - - /** - * Creates a view with the given {@code options}, then returns view information from the server. - * - * @param options Additional options, can be null - * @return information about the view @ - * @see API - * Documentation - */ - CompletableFuture create(ArangoSearchCreateOptions options); - - /** - * Reads the properties of the specified view. - * - * @return properties of the view @ - * @see API - * Documentation - */ - CompletableFuture getProperties(); - - /** - * Partially changes properties of the view. - * - * @param options properties to change - * @return properties of the view @ - * @see API - * Documentation - */ - CompletableFuture updateProperties(ArangoSearchPropertiesOptions options); - - /** - * Changes properties of the view. - * - * @param options properties to change - * @return properties of the view @ - * @see API - * Documentation - */ - CompletableFuture replaceProperties(ArangoSearchPropertiesOptions options); - -} diff --git a/core/src/main/java/com/arangodb/async/ArangoVertexCollectionAsync.java b/core/src/main/java/com/arangodb/async/ArangoVertexCollectionAsync.java deleted file mode 100644 index 2da0f7ae3..000000000 --- a/core/src/main/java/com/arangodb/async/ArangoVertexCollectionAsync.java +++ /dev/null @@ -1,188 +0,0 @@ -/* - * DISCLAIMER - * - * Copyright 2016 ArangoDB GmbH, Cologne, Germany - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Copyright holder is ArangoDB GmbH, Cologne, Germany - */ - -package com.arangodb.async; - -import com.arangodb.ArangoSerdeAccessor; -import com.arangodb.entity.VertexEntity; -import com.arangodb.entity.VertexUpdateEntity; -import com.arangodb.model.*; - -import javax.annotation.concurrent.ThreadSafe; -import java.util.concurrent.CompletableFuture; - -/** - * Interface for operations on ArangoDB vertex collection level. - * - * @author Mark Vollmary - * @see API Documentation - */ -@ThreadSafe -public interface ArangoVertexCollectionAsync extends ArangoSerdeAccessor { - - /** - * The the handler of the named graph the edge collection is within - * - * @return graph handler - */ - ArangoGraphAsync graph(); - - /** - * The name of the edge collection - * - * @return collection name - */ - String name(); - - /** - * Removes a vertex collection from the graph and optionally deletes the collection. - * - * @return void - * @see API - * Documentation - */ - CompletableFuture drop(); - - /** - * Removes a vertex collection from the graph and optionally deletes the collection. - * - * @param options options - * @return void - * @see API - * Documentation - */ - CompletableFuture drop(VertexCollectionDropOptions options); - - /** - * Creates a new vertex in the collection - * - * @param value A representation of a single vertex (POJO or {@link com.arangodb.util.RawData}) - * @return information about the vertex - * @see - * API Documentation - */ - CompletableFuture insertVertex(final Object value); - - /** - * Creates a new vertex in the collection - * - * @param value A representation of a single vertex (POJO or {@link com.arangodb.util.RawData}) - * @param options Additional options, can be null - * @return information about the vertex - * @see - * API Documentation - */ - CompletableFuture insertVertex(final Object value, final VertexCreateOptions options); - - /** - * Fetches an existing vertex - * - * @param key The key of the vertex - * @param type The type of the vertex-document (POJO or {@link com.arangodb.util.RawData}) - * @return the vertex identified by the key - * @see API Documentation - */ - CompletableFuture getVertex(final String key, final Class type); - - /** - * Fetches an existing vertex - * - * @param key The key of the vertex - * @param type The type of the vertex-document (POJO or {@link com.arangodb.util.RawData}) - * @param options Additional options, can be null - * @return the vertex identified by the key - * @see API Documentation - */ - CompletableFuture getVertex(final String key, final Class type, final GraphDocumentReadOptions options); - - /** - * Replaces the vertex with key with the one in the body, provided there is such a vertex and no precondition is - * violated - * - * @param key The key of the vertex - * @return information about the vertex - * @see API - * Documentation - */ - CompletableFuture replaceVertex(final String key, final Object value); - - /** - * Replaces the vertex with key with the one in the body, provided there is such a vertex and no precondition is - * violated - * - * @param key The key of the vertex - * @param options Additional options, can be null - * @return information about the vertex - * @see API - * Documentation - */ - CompletableFuture replaceVertex( - final String key, - final Object value, - final VertexReplaceOptions options); - - /** - * Partially updates the vertex identified by document-key. The value must contain a document with the attributes to - * patch (the patch document). All attributes from the patch document will be added to the existing document if they - * do not yet exist, and overwritten in the existing document if they do exist there. - * - * @param key The key of the vertex - * @return information about the vertex - * @see - * API Documentation - */ - CompletableFuture updateVertex(final String key, final Object value); - - /** - * Partially updates the vertex identified by document-key. The value must contain a document with the attributes to - * patch (the patch document). All attributes from the patch document will be added to the existing document if they - * do not yet exist, and overwritten in the existing document if they do exist there. - * - * @param key The key of the vertex - * @param options Additional options, can be null - * @return information about the vertex - * @see - * API Documentation - */ - CompletableFuture updateVertex( - final String key, - final Object value, - final VertexUpdateOptions options); - - /** - * Removes a vertex - * - * @param key The key of the vertex - * @see - * API Documentation - */ - CompletableFuture deleteVertex(final String key); - - /** - * Removes a vertex - * - * @param key The key of the vertex - * @param options Additional options, can be null - * @see - * API Documentation - */ - CompletableFuture deleteVertex(final String key, final VertexDeleteOptions options); - -} diff --git a/core/src/main/java/com/arangodb/async/ArangoViewAsync.java b/core/src/main/java/com/arangodb/async/ArangoViewAsync.java deleted file mode 100644 index 68fa883dc..000000000 --- a/core/src/main/java/com/arangodb/async/ArangoViewAsync.java +++ /dev/null @@ -1,88 +0,0 @@ -/* - * DISCLAIMER - * - * Copyright 2018 ArangoDB GmbH, Cologne, Germany - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Copyright holder is ArangoDB GmbH, Cologne, Germany - */ - -package com.arangodb.async; - -import com.arangodb.ArangoSerdeAccessor; -import com.arangodb.entity.ViewEntity; - -import javax.annotation.concurrent.ThreadSafe; -import java.util.concurrent.CompletableFuture; - -/** - * Interface for operations on ArangoDB view level. - * - * @author Mark Vollmary - * @see View API Documentation - * @since ArangoDB 3.4.0 - */ -@ThreadSafe -public interface ArangoViewAsync extends ArangoSerdeAccessor { - - /** - * The the handler of the database the collection is within - * - * @return database handler - */ - ArangoDatabaseAsync db(); - - /** - * The name of the view - * - * @return view name - */ - String name(); - - /** - * Checks whether the view exists. - * - * @return true if the view exists, otherwise false - */ - CompletableFuture exists(); - - /** - * Deletes the view from the database. - * - * @see - * API Documentation - */ - CompletableFuture drop(); - - /** - * Renames the view. - * - * @param newName The new name - * @return information about the view - * @see - * API Documentation - */ - CompletableFuture rename(String newName); - - /** - * Returns information about the view. - * - * @return information about the view - * @see - * API - * Documentation - */ - CompletableFuture getInfo(); - -} diff --git a/core/src/main/java/com/arangodb/async/SearchAliasAsync.java b/core/src/main/java/com/arangodb/async/SearchAliasAsync.java deleted file mode 100644 index cfb6d8a84..000000000 --- a/core/src/main/java/com/arangodb/async/SearchAliasAsync.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * DISCLAIMER - * - * Copyright 2018 ArangoDB GmbH, Cologne, Germany - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Copyright holder is ArangoDB GmbH, Cologne, Germany - */ - -package com.arangodb.async; - -import com.arangodb.entity.ViewEntity; -import com.arangodb.entity.arangosearch.SearchAliasPropertiesEntity; -import com.arangodb.model.arangosearch.SearchAliasCreateOptions; -import com.arangodb.model.arangosearch.SearchAliasPropertiesOptions; - -import java.util.concurrent.CompletableFuture; - -/** - * Interface for operations on ArangoDB view level for SearchAlias views. - * - * @author Michele Rastelli - * @see View API Documentation - * @since ArangoDB 3.10 - */ -public interface SearchAliasAsync extends ArangoViewAsync { - - /** - * Creates a view, then returns view information from the server. - * - * @return information about the view - * @see API - * Documentation - */ - CompletableFuture create(); - - /** - * Creates a view with the given {@code options}, then returns view information from the server. - * - * @param options Additional options, can be null - * @return information about the view - * @see API - * Documentation - */ - CompletableFuture create(SearchAliasCreateOptions options); - - /** - * Reads the properties of the specified view. - * - * @return properties of the view - * @see API - * Documentation - */ - CompletableFuture getProperties(); - - /** - * Partially changes properties of the view. - * - * @param options properties to change - * @return properties of the view - * @see API - * Documentation - */ - CompletableFuture updateProperties(SearchAliasPropertiesOptions options); - - /** - * Changes properties of the view. - * - * @param options properties to change - * @return properties of the view - * @see API - * Documentation - */ - CompletableFuture replaceProperties(SearchAliasPropertiesOptions options); - -} diff --git a/core/src/main/java/com/arangodb/async/internal/ArangoCollectionAsyncImpl.java b/core/src/main/java/com/arangodb/async/internal/ArangoCollectionAsyncImpl.java deleted file mode 100644 index 973a81740..000000000 --- a/core/src/main/java/com/arangodb/async/internal/ArangoCollectionAsyncImpl.java +++ /dev/null @@ -1,505 +0,0 @@ -/* - * DISCLAIMER - * - * Copyright 2016 ArangoDB GmbH, Cologne, Germany - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Copyright holder is ArangoDB GmbH, Cologne, Germany - */ - -package com.arangodb.async.internal; - -import com.arangodb.async.ArangoCollectionAsync; -import com.arangodb.entity.*; -import com.arangodb.internal.InternalArangoCollection; -import com.arangodb.internal.util.DocumentUtil; -import com.arangodb.model.*; -import com.arangodb.util.RawData; - -import java.util.Collection; -import java.util.Objects; -import java.util.concurrent.CompletableFuture; - -import static com.arangodb.internal.serde.SerdeUtils.constructParametricType; - -/** - * @author Mark Vollmary - * @author Michele Rastelli - */ -public class ArangoCollectionAsyncImpl - extends InternalArangoCollection - implements ArangoCollectionAsync { - - ArangoCollectionAsyncImpl(final ArangoDatabaseAsyncImpl db, final String name) { - super(db, name); - } - - @Override - public CompletableFuture> insertDocument(final Object value) { - return executor.execute(insertDocumentRequest(value, new DocumentCreateOptions()), - constructParametricType(DocumentCreateEntity.class, Void.class)); - } - - @Override - @SuppressWarnings("unchecked") - public CompletableFuture> insertDocument( - final T value, - final DocumentCreateOptions options) { - return insertDocument(value, options, (Class) value.getClass()); - } - - @Override - public CompletableFuture> insertDocument(T value, DocumentCreateOptions options, - Class type) { - return executor.execute(insertDocumentRequest(value, options), - constructParametricType(DocumentCreateEntity.class, type)); - } - - @Override - public CompletableFuture>> insertDocuments(RawData values) { - return executor - .execute(insertDocumentsRequest(values, new DocumentCreateOptions()), - insertDocumentsResponseDeserializer(Void.class)); - } - - @Override - @SuppressWarnings("unchecked") - public CompletableFuture>> insertDocuments(RawData values, - DocumentCreateOptions options) { - return executor - .execute(insertDocumentsRequest(values, options), - insertDocumentsResponseDeserializer((Class) values.getClass())); - } - - @Override - public CompletableFuture>> insertDocuments( - final Collection values) { - return executor - .execute(insertDocumentsRequest(values, new DocumentCreateOptions()), - insertDocumentsResponseDeserializer(Void.class)); - } - - @Override - @SuppressWarnings("unchecked") - public CompletableFuture>> insertDocuments( - final Collection values, - final DocumentCreateOptions options) { - return insertDocuments(values, options, (Class) getCollectionContentClass(values)); - } - - @Override - public CompletableFuture>> insertDocuments(Collection values, - DocumentCreateOptions options, Class type) { - return executor - .execute(insertDocumentsRequest(values, options), insertDocumentsResponseDeserializer(type)); - } - - @Override - public CompletableFuture importDocuments(final Collection values) { - return importDocuments(values, new DocumentImportOptions()); - } - - @Override - public CompletableFuture importDocuments( - final Collection values, - final DocumentImportOptions options) { - return executor.execute(importDocumentsRequest(values, options), DocumentImportEntity.class); - } - - @Override - public CompletableFuture importDocuments(RawData values) { - return executor.execute(importDocumentsRequest(values, new DocumentImportOptions()), - DocumentImportEntity.class); - } - - @Override - public CompletableFuture importDocuments(RawData values, DocumentImportOptions options) { - return executor.execute(importDocumentsRequest(values, options), DocumentImportEntity.class); - } - - @Override - public CompletableFuture getDocument(final String key, final Class type) { - return getDocument(key, type, new DocumentReadOptions()); - } - - @Override - public CompletableFuture getDocument( - final String key, - final Class type, - final DocumentReadOptions options) { - DocumentUtil.validateDocumentKey(key); - return executor.execute(getDocumentRequest(key, options), getDocumentResponseDeserializer(type)) - .exceptionally(ExceptionUtil.catchGetDocumentExceptions()); - } - - @Override - public CompletableFuture> getDocuments( - final Collection keys, - final Class type) { - return getDocuments(keys, type, new DocumentReadOptions()); - } - - @Override - public CompletableFuture> getDocuments( - final Collection keys, - final Class type, - final DocumentReadOptions options) { - return executor.execute(getDocumentsRequest(keys, options), getDocumentsResponseDeserializer(type)); - } - - @Override - public CompletableFuture> replaceDocument(final String key, final Object value) { - final DocumentReplaceOptions options = new DocumentReplaceOptions(); - return executor.execute(replaceDocumentRequest(key, value, options), - constructParametricType(DocumentUpdateEntity.class, Void.class)); - } - - @Override - @SuppressWarnings("unchecked") - public CompletableFuture> replaceDocument( - final String key, - final T value, - final DocumentReplaceOptions options) { - return replaceDocument(key, value, options, (Class) value.getClass()); - } - - @Override - public CompletableFuture> replaceDocument(String key, T value, - DocumentReplaceOptions options, - Class type) { - return executor.execute(replaceDocumentRequest(key, value, options), - constructParametricType(DocumentUpdateEntity.class, type)); - } - - @Override - public CompletableFuture>> replaceDocuments(RawData values) { - return executor.execute(replaceDocumentsRequest(values, new DocumentReplaceOptions()), - replaceDocumentsResponseDeserializer(Void.class)); - } - - @Override - @SuppressWarnings("unchecked") - public CompletableFuture>> replaceDocuments(RawData values, - DocumentReplaceOptions options) { - return executor.execute(replaceDocumentsRequest(values, options), - replaceDocumentsResponseDeserializer((Class) values.getClass())); - } - - @Override - public CompletableFuture>> replaceDocuments( - final Collection values) { - return executor.execute(replaceDocumentsRequest(values, new DocumentReplaceOptions()), - replaceDocumentsResponseDeserializer(Void.class)); - } - - @Override - @SuppressWarnings("unchecked") - public CompletableFuture>> replaceDocuments( - final Collection values, - final DocumentReplaceOptions options) { - return replaceDocuments(values, options, (Class) getCollectionContentClass(values)); - } - - @Override - public CompletableFuture>> replaceDocuments(Collection values, - DocumentReplaceOptions options, Class type) { - return executor.execute(replaceDocumentsRequest(values, options), replaceDocumentsResponseDeserializer(type)); - } - - @Override - public CompletableFuture> updateDocument(final String key, final Object value) { - return updateDocument(key, value, new DocumentUpdateOptions(), Void.class); - } - - @Override - @SuppressWarnings("unchecked") - public CompletableFuture> updateDocument( - final String key, - final T value, - final DocumentUpdateOptions options) { - return updateDocument(key, value, options, (Class) value.getClass()); - } - - @Override - public CompletableFuture> updateDocument( - final String key, - final Object value, - final DocumentUpdateOptions options, - final Class returnType) { - return executor.execute(updateDocumentRequest(key, value, options), - constructParametricType(DocumentUpdateEntity.class, returnType)); - } - - @Override - public CompletableFuture>> updateDocuments(RawData values) { - return executor - .execute(updateDocumentsRequest(values, new DocumentUpdateOptions()), - updateDocumentsResponseDeserializer(Void.class)); - } - - @Override - @SuppressWarnings("unchecked") - public CompletableFuture>> updateDocuments(RawData values, - DocumentUpdateOptions options) { - return executor - .execute(updateDocumentsRequest(values, options), - updateDocumentsResponseDeserializer((Class) values.getClass())); - } - - @Override - public CompletableFuture>> updateDocuments( - final Collection values) { - return updateDocuments(values, new DocumentUpdateOptions(), Void.class); - } - - @Override - @SuppressWarnings("unchecked") - public CompletableFuture>> updateDocuments( - final Collection values, - final DocumentUpdateOptions options) { - return updateDocuments(values, options, (Class) getCollectionContentClass(values)); - } - - @Override - public CompletableFuture>> updateDocuments( - final Collection values, - final DocumentUpdateOptions options, - final Class returnType) { - return executor - .execute(updateDocumentsRequest(values, options), updateDocumentsResponseDeserializer(returnType)); - } - - @Override - public CompletableFuture> deleteDocument(final String key) { - return deleteDocument(key, new DocumentDeleteOptions()); - } - - @Override - public CompletableFuture> deleteDocument(String key, DocumentDeleteOptions options) { - return deleteDocument(key, options, Void.class); - } - - @Override - public CompletableFuture> deleteDocument( - final String key, - final DocumentDeleteOptions options, - final Class type) { - return executor.execute(deleteDocumentRequest(key, options), - constructParametricType(DocumentDeleteEntity.class, type)); - } - - @Override - public CompletableFuture>> deleteDocuments(RawData values) { - return executor.execute(deleteDocumentsRequest(values, new DocumentDeleteOptions()), - deleteDocumentsResponseDeserializer(Void.class)); - } - - @Override - @SuppressWarnings("unchecked") - public CompletableFuture>> deleteDocuments(RawData values, - DocumentDeleteOptions options) { - return executor.execute(deleteDocumentsRequest(values, options), - deleteDocumentsResponseDeserializer((Class) values.getClass())); - } - - @Override - public CompletableFuture>> deleteDocuments( - final Collection values) { - return deleteDocuments(values, new DocumentDeleteOptions(), Void.class); - } - - @Override - @SuppressWarnings("unchecked") - public CompletableFuture>> deleteDocuments(Collection values, - DocumentDeleteOptions options) { - return deleteDocuments(values, options, (Class) getCollectionContentClass(values)); - } - - @Override - public CompletableFuture>> deleteDocuments( - final Collection values, - final DocumentDeleteOptions options, - final Class type) { - return executor.execute(deleteDocumentsRequest(values, options), deleteDocumentsResponseDeserializer(type)); - } - - @Override - public CompletableFuture documentExists(final String key) { - return documentExists(key, new DocumentExistsOptions()); - } - - @Override - public CompletableFuture documentExists(final String key, final DocumentExistsOptions options) { - return executor.execute(documentExistsRequest(key, options), response -> response) - .exceptionally(ExceptionUtil.catchGetDocumentExceptions()) - .thenApply(Objects::nonNull); - } - - @Override - public CompletableFuture getIndex(final String id) { - return executor.execute(getIndexRequest(id), IndexEntity.class); - } - - @Override - public CompletableFuture getInvertedIndex(String id) { - return executor.execute(getIndexRequest(id), InvertedIndexEntity.class); - } - - @Override - public CompletableFuture deleteIndex(final String id) { - return executor.execute(deleteIndexRequest(id), deleteIndexResponseDeserializer()); - } - - @Override - public CompletableFuture ensurePersistentIndex( - final Iterable fields, - final PersistentIndexOptions options) { - return executor.execute(createPersistentIndexRequest(fields, options), IndexEntity.class); - } - - @Override - public CompletableFuture ensureGeoIndex(final Iterable fields, final GeoIndexOptions options) { - return executor.execute(createGeoIndexRequest(fields, options), IndexEntity.class); - } - - @Deprecated - @Override - public CompletableFuture ensureFulltextIndex( - final Iterable fields, - final FulltextIndexOptions options) { - return executor.execute(createFulltextIndexRequest(fields, options), IndexEntity.class); - } - - @Override - public CompletableFuture ensureTtlIndex(Iterable fields, TtlIndexOptions options) { - return executor.execute(createTtlIndexRequest(fields, options), IndexEntity.class); - } - - @Override - public CompletableFuture ensureZKDIndex( - final Iterable fields, - final ZKDIndexOptions options) { - return executor.execute(createZKDIndexRequest(fields, options), IndexEntity.class); - } - - @Override - public CompletableFuture ensureInvertedIndex(InvertedIndexOptions options) { - return executor.execute(createInvertedIndexRequest(options), InvertedIndexEntity.class); - } - - @Override - public CompletableFuture> getIndexes() { - return executor.execute(getIndexesRequest(), getIndexesResponseDeserializer()); - } - - @Override - public CompletableFuture> getInvertedIndexes() { - return executor.execute(getIndexesRequest(), getInvertedIndexesResponseDeserializer()); - } - - @Override - public CompletableFuture exists() { - return getInfo().thenApply(Objects::nonNull).exceptionally(Objects::isNull); - } - - @Override - public CompletableFuture truncate() { - return truncate(null); - } - - @Override - public CompletableFuture truncate(CollectionTruncateOptions options) { - return executor.execute(truncateRequest(options), CollectionEntity.class); - } - - @Override - public CompletableFuture count() { - return count(null); - } - - @Override - public CompletableFuture count(CollectionCountOptions options) { - return executor.execute(countRequest(options), CollectionPropertiesEntity.class); - } - - @Override - public CompletableFuture create() { - return db().createCollection(name()); - } - - @Override - public CompletableFuture create(final CollectionCreateOptions options) { - return db().createCollection(name(), options); - } - - @Override - public CompletableFuture drop() { - return executor.execute(dropRequest(null), Void.class); - } - - @Override - public CompletableFuture drop(final boolean isSystem) { - return executor.execute(dropRequest(isSystem), Void.class); - } - - @Override - public CompletableFuture getInfo() { - return executor.execute(getInfoRequest(), CollectionEntity.class); - } - - @Override - public CompletableFuture getProperties() { - return executor.execute(getPropertiesRequest(), CollectionPropertiesEntity.class); - } - - @Override - public CompletableFuture changeProperties(final CollectionPropertiesOptions options) { - return executor.execute(changePropertiesRequest(options), CollectionPropertiesEntity.class); - } - - @Override - public CompletableFuture rename(final String newName) { - return executor.execute(renameRequest(newName), CollectionEntity.class); - } - - @Override - public CompletableFuture getResponsibleShard(Object value) { - return executor.execute(responsibleShardRequest(value), ShardEntity.class); - } - - @Override - public CompletableFuture getRevision() { - return executor.execute(getRevisionRequest(), CollectionRevisionEntity.class); - } - - @Override - public CompletableFuture grantAccess(final String user, final Permissions permissions) { - return executor.execute(grantAccessRequest(user, permissions), Void.class); - } - - @Override - public CompletableFuture revokeAccess(final String user) { - return executor.execute(grantAccessRequest(user, Permissions.NONE), Void.class); - } - - @Override - public CompletableFuture resetAccess(final String user) { - return executor.execute(resetAccessRequest(user), Void.class); - } - - @Override - public CompletableFuture getPermissions(final String user) { - return executor.execute(getPermissionsRequest(user), getPermissionsResponseDeserialzer()); - } -} diff --git a/core/src/main/java/com/arangodb/async/internal/ArangoCursorAsyncImpl.java b/core/src/main/java/com/arangodb/async/internal/ArangoCursorAsyncImpl.java deleted file mode 100644 index e8861a49e..000000000 --- a/core/src/main/java/com/arangodb/async/internal/ArangoCursorAsyncImpl.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * DISCLAIMER - * - * Copyright 2016 ArangoDB GmbH, Cologne, Germany - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Copyright holder is ArangoDB GmbH, Cologne, Germany - */ - -package com.arangodb.async.internal; - -import com.arangodb.async.ArangoCursorAsync; -import com.arangodb.internal.ArangoCursorExecute; -import com.arangodb.internal.InternalArangoDatabase; -import com.arangodb.internal.cursor.ArangoCursorImpl; -import com.arangodb.internal.cursor.entity.InternalCursorEntity; - -import java.util.Spliterator; -import java.util.Spliterators; -import java.util.stream.Stream; -import java.util.stream.StreamSupport; - -/** - * @author Mark Vollmary - */ -public class ArangoCursorAsyncImpl extends ArangoCursorImpl implements ArangoCursorAsync { - - ArangoCursorAsyncImpl(final InternalArangoDatabase db, final ArangoCursorExecute execute, - final Class type, final InternalCursorEntity result) { - super(db, execute, type, result); - } - - @Override - public Stream streamRemaining() { - return StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, Spliterator.ORDERED), false); - } -} diff --git a/core/src/main/java/com/arangodb/async/internal/ArangoDBAsyncImpl.java b/core/src/main/java/com/arangodb/async/internal/ArangoDBAsyncImpl.java deleted file mode 100644 index 12e946976..000000000 --- a/core/src/main/java/com/arangodb/async/internal/ArangoDBAsyncImpl.java +++ /dev/null @@ -1,228 +0,0 @@ -/* - * DISCLAIMER - * - * Copyright 2016 ArangoDB GmbH, Cologne, Germany - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Copyright holder is ArangoDB GmbH, Cologne, Germany - */ - -package com.arangodb.async.internal; - -import com.arangodb.ArangoMetrics; -import com.arangodb.DbName; -import com.arangodb.Request; -import com.arangodb.Response; -import com.arangodb.async.ArangoDBAsync; -import com.arangodb.async.ArangoDatabaseAsync; -import com.arangodb.entity.*; -import com.arangodb.internal.ArangoExecutorSync; -import com.arangodb.internal.ArangoMetricsImpl; -import com.arangodb.internal.InternalArangoDB; -import com.arangodb.internal.config.ArangoConfig; -import com.arangodb.internal.net.*; -import com.arangodb.internal.serde.SerdeUtils; -import com.arangodb.model.DBCreateOptions; -import com.arangodb.model.LogOptions; -import com.arangodb.model.UserCreateOptions; -import com.arangodb.model.UserUpdateOptions; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.IOException; -import java.util.Collection; -import java.util.concurrent.CompletableFuture; - -/** - * @author Mark Vollmary - */ -public class ArangoDBAsyncImpl extends InternalArangoDB implements ArangoDBAsync { - - private static final Logger LOGGER = LoggerFactory.getLogger(ArangoDBAsyncImpl.class); - - private final CommunicationProtocol cp; - private final HostHandler asyncHostHandler; - private final HostHandler syncHostHandler; - - public ArangoDBAsyncImpl( - final ArangoConfig config, - final HostResolver asyncHostResolver, - final HostResolver syncHostResolver, - final AsyncProtocolProvider asyncProtocolProvider, - final ProtocolProvider protocolProvider, - final HostHandler asyncHostHandler, - final HostHandler syncHostHandler - ) { - super(new ArangoExecutorAsync(asyncProtocolProvider.createCommunication(config, asyncHostHandler), config), config.getInternalSerde()); - cp = protocolProvider.createProtocol(config, syncHostHandler); - this.asyncHostHandler = asyncHostHandler; - this.syncHostHandler = syncHostHandler; - - ArangoExecutorSync arangoExecutorSync = new ArangoExecutorSync(cp, config); - asyncHostResolver.init(arangoExecutorSync, config.getInternalSerde()); - syncHostResolver.init(arangoExecutorSync, config.getInternalSerde()); - } - - @Override - protected ArangoExecutorAsync executor() { - return executor; - } - - @Override - public void shutdown() { - try { - executor.disconnect(); - } finally { - try { - cp.close(); - } catch (final IOException e) { - LOGGER.error("Got exception during shutdown:", e); - } - } - } - - @Override - public void updateJwt(String jwt) { - asyncHostHandler.setJwt(jwt); - syncHostHandler.setJwt(jwt); - cp.setJwt(jwt); - executor.setJwt(jwt); - } - - @Override - public ArangoDatabaseAsync db() { - return db(DbName.SYSTEM); - } - - @Override - public ArangoDatabaseAsync db(final DbName name) { - return new ArangoDatabaseAsyncImpl(this, name); - } - - @Override - public ArangoMetrics metrics() { - return new ArangoMetricsImpl(executor.getQueueTimeMetrics()); - } - - @Override - public CompletableFuture createDatabase(final DbName name) { - return createDatabase(new DBCreateOptions().name(name)); - } - - @Override - public CompletableFuture createDatabase(DBCreateOptions options) { - return executor.execute(createDatabaseRequest(options), createDatabaseResponseDeserializer()); - } - - @Override - public CompletableFuture> getDatabases() { - return executor.execute(getDatabasesRequest(db().dbName()), getDatabaseResponseDeserializer()); - } - - @Override - public CompletableFuture> getAccessibleDatabases() { - return db().getAccessibleDatabases(); - } - - @Override - public CompletableFuture> getAccessibleDatabasesFor(final String user) { - return executor.execute(getAccessibleDatabasesForRequest(db().dbName(), user), - getAccessibleDatabasesForResponseDeserializer()); - } - - @Override - public CompletableFuture getVersion() { - return db().getVersion(); - } - - @Override - public CompletableFuture getRole() { - return executor.execute(getRoleRequest(), getRoleResponseDeserializer()); - } - - @Override - public CompletableFuture createUser(final String user, final String passwd) { - return executor.execute(createUserRequest(db().dbName(), user, passwd, new UserCreateOptions()), - UserEntity.class); - } - - @Override - public CompletableFuture createUser( - final String user, - final String passwd, - final UserCreateOptions options) { - return executor.execute(createUserRequest(db().dbName(), user, passwd, options), UserEntity.class); - } - - @Override - public CompletableFuture deleteUser(final String user) { - return executor.execute(deleteUserRequest(db().dbName(), user), Void.class); - } - - @Override - public CompletableFuture getUser(final String user) { - return executor.execute(getUserRequest(db().dbName(), user), UserEntity.class); - } - - @Override - public CompletableFuture> getUsers() { - return executor.execute(getUsersRequest(db().dbName()), getUsersResponseDeserializer()); - } - - @Override - public CompletableFuture updateUser(final String user, final UserUpdateOptions options) { - return executor.execute(updateUserRequest(db().dbName(), user, options), UserEntity.class); - } - - @Override - public CompletableFuture replaceUser(final String user, final UserUpdateOptions options) { - return executor.execute(replaceUserRequest(db().dbName(), user, options), UserEntity.class); - } - - @Override - public CompletableFuture grantDefaultDatabaseAccess(final String user, final Permissions permissions) { - return executor.execute(updateUserDefaultDatabaseAccessRequest(user, permissions), Void.class); - } - - @Override - public CompletableFuture grantDefaultCollectionAccess(final String user, final Permissions permissions) { - return executor.execute(updateUserDefaultCollectionAccessRequest(user, permissions), Void.class); - } - - @Override - public CompletableFuture> execute(Request request, Class type) { - return executor.execute(executeRequest(request), responseDeserializer(type)); - } - - @Override - public CompletableFuture getLogEntries(final LogOptions options) { - return executor.execute(getLogEntriesRequest(options), LogEntriesEntity.class); - } - - @Override - public CompletableFuture getLogLevel() { - return executor.execute(getLogLevelRequest(), LogLevelEntity.class); - } - - @Override - public CompletableFuture setLogLevel(final LogLevelEntity entity) { - return executor.execute(setLogLevelRequest(entity), LogLevelEntity.class); - } - - @Override - public CompletableFuture> getQueryOptimizerRules() { - return executor.execute(getQueryOptimizerRulesRequest(), SerdeUtils.constructListType(QueryOptimizerRule.class)); - } - -} diff --git a/core/src/main/java/com/arangodb/async/internal/ArangoDatabaseAsyncImpl.java b/core/src/main/java/com/arangodb/async/internal/ArangoDatabaseAsyncImpl.java deleted file mode 100644 index fd9bce608..000000000 --- a/core/src/main/java/com/arangodb/async/internal/ArangoDatabaseAsyncImpl.java +++ /dev/null @@ -1,483 +0,0 @@ -/* - * DISCLAIMER - * - * Copyright 2016 ArangoDB GmbH, Cologne, Germany - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Copyright holder is ArangoDB GmbH, Cologne, Germany - */ - -package com.arangodb.async.internal; - -import com.arangodb.ArangoDBException; -import com.arangodb.DbName; -import com.arangodb.async.*; -import com.arangodb.entity.*; -import com.arangodb.entity.arangosearch.analyzer.SearchAnalyzer; -import com.arangodb.internal.ArangoCursorExecute; -import com.arangodb.internal.ArangoErrors; -import com.arangodb.internal.InternalArangoDatabase; -import com.arangodb.internal.cursor.entity.InternalCursorEntity; -import com.arangodb.internal.net.HostHandle; -import com.arangodb.internal.util.DocumentUtil; -import com.arangodb.model.*; -import com.arangodb.model.arangosearch.AnalyzerDeleteOptions; -import com.arangodb.model.arangosearch.ArangoSearchCreateOptions; -import com.arangodb.model.arangosearch.SearchAliasCreateOptions; -import com.arangodb.internal.InternalRequest; - -import java.util.Collection; -import java.util.Collections; -import java.util.Map; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.CompletionException; -import java.util.concurrent.ExecutionException; - -import static com.arangodb.internal.serde.SerdeUtils.constructListType; - -/** - * @author Mark Vollmary - * @author Michele Rastelli - */ -public class ArangoDatabaseAsyncImpl extends InternalArangoDatabase - implements ArangoDatabaseAsync { - - ArangoDatabaseAsyncImpl(final ArangoDBAsyncImpl arangoDB, final DbName name) { - super(arangoDB, name); - } - - @Override - public CompletableFuture getVersion() { - return executor.execute(getVersionRequest(), ArangoDBVersion.class); - } - - @Override - public CompletableFuture getEngine() { - return executor.execute(getEngineRequest(), ArangoDBEngine.class); - } - - @Override - public CompletableFuture exists() { - return getInfo() - .handle((result, ex) -> { - if (result != null) { - return true; - } - - if (ex instanceof CompletionException && ex.getCause() instanceof ArangoDBException) { - ArangoDBException e = (ArangoDBException) ex.getCause(); - if (ArangoErrors.ERROR_ARANGO_DATABASE_NOT_FOUND.equals(e.getErrorNum())) { - return false; - } - } - - throw new CompletionException(ex); - }); - } - - @Override - public CompletableFuture> getAccessibleDatabases() { - return executor.execute(getAccessibleDatabasesRequest(), getDatabaseResponseDeserializer()); - } - - @Override - public ArangoCollectionAsync collection(final String name) { - return new ArangoCollectionAsyncImpl(this, name); - } - - @Override - public CompletableFuture createCollection(final String name) { - return executor.execute(createCollectionRequest(name, new CollectionCreateOptions()), CollectionEntity.class); - } - - @Override - public CompletableFuture createCollection( - final String name, - final CollectionCreateOptions options) { - return executor.execute(createCollectionRequest(name, options), CollectionEntity.class); - } - - @Override - public CompletableFuture> getCollections() { - return executor.execute(getCollectionsRequest(new CollectionsReadOptions()), - getCollectionsResponseDeserializer()); - } - - @Override - public CompletableFuture> getCollections(final CollectionsReadOptions options) { - return executor.execute(getCollectionsRequest(options), getCollectionsResponseDeserializer()); - } - - @Override - public CompletableFuture getIndex(final String id) { - DocumentUtil.validateIndexId(id); - final String[] split = id.split("/"); - return collection(split[0]).getIndex(split[1]); - } - - @Override - public CompletableFuture deleteIndex(final String id) { - DocumentUtil.validateIndexId(id); - final String[] split = id.split("/"); - return collection(split[0]).deleteIndex(split[1]); - } - - @Override - public CompletableFuture create() { - return arango().createDatabase(dbName()); - } - - @Override - public CompletableFuture drop() { - return executor.execute(dropRequest(), createDropResponseDeserializer()); - } - - @Override - public CompletableFuture grantAccess(final String user, final Permissions permissions) { - return executor.execute(grantAccessRequest(user, permissions), Void.class); - } - - @Override - public CompletableFuture grantAccess(final String user) { - return executor.execute(grantAccessRequest(user, Permissions.RW), Void.class); - } - - @Override - public CompletableFuture revokeAccess(final String user) { - return executor.execute(grantAccessRequest(user, Permissions.NONE), Void.class); - } - - @Override - public CompletableFuture resetAccess(final String user) { - return executor.execute(resetAccessRequest(user), Void.class); - } - - @Override - public CompletableFuture grantDefaultCollectionAccess(final String user, final Permissions permissions) { - return executor.execute(updateUserDefaultCollectionAccessRequest(user, permissions), Void.class); - } - - @Override - public CompletableFuture getPermissions(final String user) { - return executor.execute(getPermissionsRequest(user), getPermissionsResponseDeserialzer()); - } - - @Override - public CompletableFuture> query( - final String query, - final Map bindVars, - final AqlQueryOptions options, - final Class type) { - final InternalRequest request = queryRequest(query, bindVars, options); - final HostHandle hostHandle = new HostHandle(); - final CompletableFuture execution = executor.execute(request, - InternalCursorEntity.class, hostHandle); - return execution.thenApply(result -> createCursor(result, type, options, hostHandle)); - } - - @Override - public CompletableFuture> query( - final String query, - final AqlQueryOptions options, - final Class type) { - return query(query, null, options, type); - } - - @Override - public CompletableFuture> query( - final String query, - final Map bindVars, - final Class type) { - return query(query, bindVars, null, type); - } - - @Override - public CompletableFuture> query(final String query, final Class type) { - return query(query, null, null, type); - } - - @Override - public CompletableFuture> cursor(final String cursorId, final Class type) { - final HostHandle hostHandle = new HostHandle(); - final CompletableFuture execution = executor.execute(queryNextRequest(cursorId, null, - null), InternalCursorEntity.class, hostHandle); - return execution.thenApply(result -> createCursor(result, type, null, hostHandle)); - } - - private ArangoCursorAsync createCursor( - final InternalCursorEntity result, - final Class type, - final AqlQueryOptions options, - final HostHandle hostHandle) { - return new ArangoCursorAsyncImpl<>(this, new ArangoCursorExecute() { - @Override - public InternalCursorEntity next(final String id, Map meta) { - final CompletableFuture result = executor.execute(queryNextRequest(id, options, - meta), - InternalCursorEntity.class, hostHandle); - try { - return result.get(); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - throw new ArangoDBException(e); - } catch (ExecutionException e) { - throw new ArangoDBException(e); - } - } - - @Override - public void close(final String id, Map meta) { - try { - executor.execute(queryCloseRequest(id, options, meta), Void.class, hostHandle).get(); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - throw new ArangoDBException(e); - } catch (ExecutionException e) { - throw new ArangoDBException(e); - } - } - }, type, result); - } - - @Override - public CompletableFuture explainQuery( - final String query, - final Map bindVars, - final AqlQueryExplainOptions options) { - return executor.execute(explainQueryRequest(query, bindVars, options), AqlExecutionExplainEntity.class); - } - - @Override - public CompletableFuture parseQuery(final String query) { - return executor.execute(parseQueryRequest(query), AqlParseEntity.class); - } - - @Override - public CompletableFuture clearQueryCache() { - return executor.execute(clearQueryCacheRequest(), Void.class); - } - - @Override - public CompletableFuture getQueryCacheProperties() { - return executor.execute(getQueryCachePropertiesRequest(), QueryCachePropertiesEntity.class); - } - - @Override - public CompletableFuture setQueryCacheProperties( - final QueryCachePropertiesEntity properties) { - return executor.execute(setQueryCachePropertiesRequest(properties), QueryCachePropertiesEntity.class); - } - - @Override - public CompletableFuture getQueryTrackingProperties() { - return executor.execute(getQueryTrackingPropertiesRequest(), QueryTrackingPropertiesEntity.class); - } - - @Override - public CompletableFuture setQueryTrackingProperties( - final QueryTrackingPropertiesEntity properties) { - return executor.execute(setQueryTrackingPropertiesRequest(properties), QueryTrackingPropertiesEntity.class); - } - - @Override - public CompletableFuture> getCurrentlyRunningQueries() { - return executor.execute(getCurrentlyRunningQueriesRequest(), - constructListType(QueryEntity.class)); - } - - @Override - public CompletableFuture> getSlowQueries() { - return executor.execute(getSlowQueriesRequest(), - constructListType(QueryEntity.class)); - } - - @Override - public CompletableFuture clearSlowQueries() { - return executor.execute(clearSlowQueriesRequest(), Void.class); - } - - @Override - public CompletableFuture killQuery(final String id) { - return executor.execute(killQueryRequest(id), Void.class); - } - - @Override - public CompletableFuture createAqlFunction( - final String name, - final String code, - final AqlFunctionCreateOptions options) { - return executor.execute(createAqlFunctionRequest(name, code, options), Void.class); - - } - - @Override - public CompletableFuture deleteAqlFunction(final String name, final AqlFunctionDeleteOptions options) { - return executor.execute(deleteAqlFunctionRequest(name, options), deleteAqlFunctionResponseDeserializer()); - } - - @Override - public CompletableFuture> getAqlFunctions(final AqlFunctionGetOptions options) { - return executor.execute(getAqlFunctionsRequest(options), getAqlFunctionsResponseDeserializer()); - } - - @Override - public ArangoGraphAsync graph(final String name) { - return new ArangoGraphAsyncImpl(this, name); - } - - @Override - public CompletableFuture createGraph( - final String name, - final Collection edgeDefinitions) { - return createGraph(name, edgeDefinitions, new GraphCreateOptions()); - } - - @Override - public CompletableFuture createGraph( - final String name, - final Collection edgeDefinitions, - final GraphCreateOptions options) { - return executor.execute(createGraphRequest(name, edgeDefinitions, options), createGraphResponseDeserializer()); - } - - @Override - public CompletableFuture> getGraphs() { - return executor.execute(getGraphsRequest(), getGraphsResponseDeserializer()); - } - - @Override - public CompletableFuture transaction( - final String action, - final Class type, - final TransactionOptions options) { - return executor.execute(transactionRequest(action, options), transactionResponseDeserializer(type)); - } - - @Override - public CompletableFuture beginStreamTransaction(StreamTransactionOptions options) { - return executor.execute(beginStreamTransactionRequest(options), streamTransactionResponseDeserializer()); - } - - @Override - public CompletableFuture abortStreamTransaction(String id) { - return executor.execute(abortStreamTransactionRequest(id), streamTransactionResponseDeserializer()); - } - - @Override - public CompletableFuture getStreamTransaction(String id) { - return executor.execute(getStreamTransactionRequest(id), streamTransactionResponseDeserializer()); - } - - @Override - public CompletableFuture> getStreamTransactions() { - return executor.execute(getStreamTransactionsRequest(), transactionsResponseDeserializer()); - } - - @Override - public CompletableFuture commitStreamTransaction(String id) { - return executor.execute(commitStreamTransactionRequest(id), streamTransactionResponseDeserializer()); - } - - @Override - public CompletableFuture getInfo() { - return executor.execute(getInfoRequest(), getInfoResponseDeserializer()); - } - - @Override - public CompletableFuture getDocument(final String id, final Class type) { - DocumentUtil.validateDocumentId(id); - final String[] split = id.split("/"); - return collection(split[0]).getDocument(split[1], type); - } - - @Override - public CompletableFuture getDocument(final String id, final Class type, - final DocumentReadOptions options) { - DocumentUtil.validateDocumentId(id); - final String[] split = id.split("/"); - return collection(split[0]).getDocument(split[1], type, options); - } - - @Override - public CompletableFuture reloadRouting() { - return executor.execute(reloadRoutingRequest(), Void.class); - } - - @Override - public ArangoRouteAsync route(final String... path) { - return new ArangoRouteAsyncImpl(this, String.join("/", path), Collections.emptyMap()); - } - - @Override - public CompletableFuture> getViews() { - return executor.execute(getViewsRequest(), getViewsResponseDeserializer()); - } - - @Override - public ArangoViewAsync view(final String name) { - return new ArangoViewAsyncImpl(this, name); - } - - @Override - public ArangoSearchAsync arangoSearch(final String name) { - return new ArangoSearchAsyncImpl(this, name); - } - - @Override - public SearchAliasAsync searchAlias(String name) { - return new SearchAliasAsyncImpl(this, name); - } - - @Override - public CompletableFuture createView(final String name, final ViewType type) { - return executor.execute(createViewRequest(name, type), ViewEntity.class); - } - - @Override - public CompletableFuture createArangoSearch(final String name, - final ArangoSearchCreateOptions options) { - return executor.execute(createArangoSearchRequest(name, options), ViewEntity.class); - } - - @Override - public CompletableFuture createSearchAlias(String name, SearchAliasCreateOptions options) { - return executor.execute(createSearchAliasRequest(name, options), ViewEntity.class); - } - - @Override - public CompletableFuture createSearchAnalyzer(SearchAnalyzer analyzer) { - return executor.execute(createAnalyzerRequest(analyzer), SearchAnalyzer.class); - } - - @Override - public CompletableFuture getSearchAnalyzer(String name) { - return executor.execute(getAnalyzerRequest(name), SearchAnalyzer.class); - } - - @Override - public CompletableFuture> getSearchAnalyzers() { - return executor.execute(getAnalyzersRequest(), getSearchAnalyzersResponseDeserializer()); - } - - @Override - public CompletableFuture deleteSearchAnalyzer(String name) { - return deleteSearchAnalyzer(name, null); - } - - @Override - public CompletableFuture deleteSearchAnalyzer(String name, AnalyzerDeleteOptions options) { - return executor.execute(deleteAnalyzerRequest(name, options), Void.class); - } - -} diff --git a/core/src/main/java/com/arangodb/async/internal/ArangoEdgeCollectionAsyncImpl.java b/core/src/main/java/com/arangodb/async/internal/ArangoEdgeCollectionAsyncImpl.java deleted file mode 100644 index c41d926f2..000000000 --- a/core/src/main/java/com/arangodb/async/internal/ArangoEdgeCollectionAsyncImpl.java +++ /dev/null @@ -1,114 +0,0 @@ -/* - * DISCLAIMER - * - * Copyright 2016 ArangoDB GmbH, Cologne, Germany - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Copyright holder is ArangoDB GmbH, Cologne, Germany - */ - -package com.arangodb.async.internal; - -import com.arangodb.async.ArangoEdgeCollectionAsync; -import com.arangodb.entity.EdgeEntity; -import com.arangodb.entity.EdgeUpdateEntity; -import com.arangodb.internal.InternalArangoEdgeCollection; -import com.arangodb.model.*; - -import java.util.concurrent.CompletableFuture; - -/** - * @author Mark Vollmary - */ -public class ArangoEdgeCollectionAsyncImpl extends - InternalArangoEdgeCollection - implements ArangoEdgeCollectionAsync { - - ArangoEdgeCollectionAsyncImpl(final ArangoGraphAsyncImpl graph, final String name) { - super(graph, name); - } - - @Override - public CompletableFuture drop() { - return drop(new EdgeCollectionDropOptions()); - } - - @Override - public CompletableFuture drop(final EdgeCollectionDropOptions options) { - return executor.execute(removeEdgeDefinitionRequest(options), Void.class); - } - - @Override - public CompletableFuture insertEdge(final Object value) { - return executor.execute(insertEdgeRequest(value, new EdgeCreateOptions()), - insertEdgeResponseDeserializer()); - } - - @Override - public CompletableFuture insertEdge(final Object value, final EdgeCreateOptions options) { - return executor.execute(insertEdgeRequest(value, options), insertEdgeResponseDeserializer()); - } - - @Override - public CompletableFuture getEdge(final String key, final Class type) { - return getEdge(key, type, null); - } - - @Override - public CompletableFuture getEdge(final String key, final Class type, - final GraphDocumentReadOptions options) { - return executor.execute(getEdgeRequest(key, options), getEdgeResponseDeserializer(type)) - .exceptionally(ExceptionUtil.catchGetDocumentExceptions()); - } - - @Override - public CompletableFuture replaceEdge(final String key, final Object value) { - return executor.execute(replaceEdgeRequest(key, value, new EdgeReplaceOptions()), - replaceEdgeResponseDeserializer()); - } - - @Override - public CompletableFuture replaceEdge( - final String key, - final Object value, - final EdgeReplaceOptions options) { - return executor.execute(replaceEdgeRequest(key, value, options), replaceEdgeResponseDeserializer()); - } - - @Override - public CompletableFuture updateEdge(final String key, final Object value) { - return executor.execute(updateEdgeRequest(key, value, new EdgeUpdateOptions()), - updateEdgeResponseDeserializer()); - } - - @Override - public CompletableFuture updateEdge( - final String key, - final Object value, - final EdgeUpdateOptions options) { - return executor.execute(updateEdgeRequest(key, value, options), updateEdgeResponseDeserializer()); - } - - @Override - public CompletableFuture deleteEdge(final String key) { - return executor.execute(deleteEdgeRequest(key, new EdgeDeleteOptions()), Void.class); - } - - @Override - public CompletableFuture deleteEdge(final String key, final EdgeDeleteOptions options) { - return executor.execute(deleteEdgeRequest(key, options), Void.class); - } - -} diff --git a/core/src/main/java/com/arangodb/async/internal/ArangoExecutorAsync.java b/core/src/main/java/com/arangodb/async/internal/ArangoExecutorAsync.java deleted file mode 100644 index 7c85ef495..000000000 --- a/core/src/main/java/com/arangodb/async/internal/ArangoExecutorAsync.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * DISCLAIMER - * - * Copyright 2016 ArangoDB GmbH, Cologne, Germany - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Copyright holder is ArangoDB GmbH, Cologne, Germany - */ - -package com.arangodb.async.internal; - -import com.arangodb.ArangoDBException; -import com.arangodb.internal.ArangoExecutor; -import com.arangodb.internal.InternalRequest; -import com.arangodb.internal.config.ArangoConfig; -import com.arangodb.internal.net.AsyncCommunication; -import com.arangodb.internal.net.HostHandle; - -import java.io.IOException; -import java.lang.reflect.Type; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - -/** - * @author Mark Vollmary - * @author Michele Rastelli - */ -public class ArangoExecutorAsync extends ArangoExecutor { - - private final AsyncCommunication communication; - private final ExecutorService outgoingExecutor = Executors.newSingleThreadExecutor(); - - public ArangoExecutorAsync(final AsyncCommunication communication, final ArangoConfig config) { - super(config); - this.communication = communication; - } - - public CompletableFuture execute(final InternalRequest request, final Type type) { - return execute(request, response -> createResult(type, response)); - } - - public CompletableFuture execute(final InternalRequest request, final Type type, final HostHandle hostHandle) { - return execute(request, response -> createResult(type, response), hostHandle); - } - - public CompletableFuture execute(final InternalRequest request, final ResponseDeserializer responseDeserializer) { - return execute(request, responseDeserializer, null); - } - - private CompletableFuture execute( - final InternalRequest request, - final ResponseDeserializer responseDeserializer, - final HostHandle hostHandle) { - - return CompletableFuture.completedFuture(null) - .thenComposeAsync(it -> communication.execute(interceptRequest(request), hostHandle), outgoingExecutor) - .thenApplyAsync(response -> { - interceptResponse(response); - return responseDeserializer.deserialize(response); - }); - } - - public void disconnect() { - try { - communication.close(); - } catch (final IOException e) { - throw new ArangoDBException(e); - } finally { - outgoingExecutor.shutdown(); - } - } - - public void setJwt(String jwt) { - communication.setJwt(jwt); - } - -} diff --git a/core/src/main/java/com/arangodb/async/internal/ArangoGraphAsyncImpl.java b/core/src/main/java/com/arangodb/async/internal/ArangoGraphAsyncImpl.java deleted file mode 100644 index 1043187c6..000000000 --- a/core/src/main/java/com/arangodb/async/internal/ArangoGraphAsyncImpl.java +++ /dev/null @@ -1,126 +0,0 @@ -/* - * DISCLAIMER - * - * Copyright 2016 ArangoDB GmbH, Cologne, Germany - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Copyright holder is ArangoDB GmbH, Cologne, Germany - */ - -package com.arangodb.async.internal; - -import com.arangodb.async.ArangoEdgeCollectionAsync; -import com.arangodb.async.ArangoGraphAsync; -import com.arangodb.async.ArangoVertexCollectionAsync; -import com.arangodb.entity.EdgeDefinition; -import com.arangodb.entity.GraphEntity; -import com.arangodb.internal.InternalArangoGraph; -import com.arangodb.model.GraphCreateOptions; -import com.arangodb.model.ReplaceEdgeDefinitionOptions; -import com.arangodb.model.VertexCollectionCreateOptions; - -import java.util.Collection; -import java.util.Objects; -import java.util.concurrent.CompletableFuture; - -/** - * @author Mark Vollmary - */ -public class ArangoGraphAsyncImpl - extends InternalArangoGraph - implements ArangoGraphAsync { - - ArangoGraphAsyncImpl(final ArangoDatabaseAsyncImpl db, final String name) { - super(db, name); - } - - @Override - public CompletableFuture exists() { - return getInfo().thenApply(Objects::nonNull).exceptionally(Objects::isNull); - } - - @Override - public CompletableFuture create(final Collection edgeDefinitions) { - return db().createGraph(name(), edgeDefinitions); - } - - @Override - public CompletableFuture createGraph( - final Collection edgeDefinitions, - final GraphCreateOptions options) { - return db().createGraph(name(), edgeDefinitions, options); - } - - @Override - public CompletableFuture drop() { - return executor.execute(dropRequest(), Void.class); - } - - @Override - public CompletableFuture drop(boolean dropCollections) { - return executor.execute(dropRequest(dropCollections), Void.class); - } - - @Override - public CompletableFuture getInfo() { - return executor.execute(getInfoRequest(), getInfoResponseDeserializer()); - } - - @Override - public CompletableFuture> getVertexCollections() { - return executor.execute(getVertexCollectionsRequest(), getVertexCollectionsResponseDeserializer()); - } - - @Override - public CompletableFuture addVertexCollection(final String name) { - return addVertexCollection(name, new VertexCollectionCreateOptions()); - } - - @Override - public CompletableFuture addVertexCollection(final String name, - final VertexCollectionCreateOptions options) { - return executor.execute(addVertexCollectionRequest(name, options), addVertexCollectionResponseDeserializer()); - } - - @Override - public ArangoVertexCollectionAsync vertexCollection(final String name) { - return new ArangoVertexCollectionAsyncImpl(this, name); - } - - @Override - public ArangoEdgeCollectionAsync edgeCollection(final String name) { - return new ArangoEdgeCollectionAsyncImpl(this, name); - } - - @Override - public CompletableFuture> getEdgeDefinitions() { - return executor.execute(getEdgeDefinitionsRequest(), getEdgeDefinitionsDeserializer()); - } - - @Override - public CompletableFuture addEdgeDefinition(final EdgeDefinition definition) { - return executor.execute(addEdgeDefinitionRequest(definition), addEdgeDefinitionResponseDeserializer()); - } - - @Override - public CompletableFuture replaceEdgeDefinition(final EdgeDefinition definition) { - return replaceEdgeDefinition(definition, new ReplaceEdgeDefinitionOptions()); - } - - @Override - public CompletableFuture replaceEdgeDefinition(final EdgeDefinition definition, final ReplaceEdgeDefinitionOptions options) { - return executor.execute(replaceEdgeDefinitionRequest(definition, options), replaceEdgeDefinitionResponseDeserializer()); - } - -} diff --git a/core/src/main/java/com/arangodb/async/internal/ArangoRouteAsyncImpl.java b/core/src/main/java/com/arangodb/async/internal/ArangoRouteAsyncImpl.java deleted file mode 100644 index 57270220d..000000000 --- a/core/src/main/java/com/arangodb/async/internal/ArangoRouteAsyncImpl.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * DISCLAIMER - * - * Copyright 2018 ArangoDB GmbH, Cologne, Germany - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Copyright holder is ArangoDB GmbH, Cologne, Germany - */ - -package com.arangodb.async.internal; - -import com.arangodb.async.ArangoRouteAsync; -import com.arangodb.internal.InternalArangoRoute; -import com.arangodb.internal.RequestType; -import com.arangodb.internal.InternalResponse; - -import java.util.Map; -import java.util.concurrent.CompletableFuture; - -/** - * @author Mark Vollmary - */ -public class ArangoRouteAsyncImpl - extends InternalArangoRoute - implements ArangoRouteAsync { - - ArangoRouteAsyncImpl(final ArangoDatabaseAsyncImpl db, final String path, - final Map headerParam) { - super(db, path, headerParam); - } - - @Override - public ArangoRouteAsync route(final String... path) { - final String[] fullPath = new String[path.length + 1]; - fullPath[0] = this.path; - System.arraycopy(path, 0, fullPath, 1, path.length); - return new ArangoRouteAsyncImpl(db, String.join("/", fullPath), headerParam); - } - - @Override - public ArangoRouteAsync withHeader(final String key, final Object value) { - _withHeader(key, value); - return this; - } - - @Override - public ArangoRouteAsync withQueryParam(final String key, final Object value) { - _withQueryParam(key, value); - return this; - } - - @Override - public ArangoRouteAsync withBody(final Object body) { - _withBody(body); - return this; - } - - private CompletableFuture request(final RequestType requestType) { - return executor.execute(createRequest(requestType), response -> response); - } - - @Override - public CompletableFuture delete() { - return request(RequestType.DELETE); - } - - @Override - public CompletableFuture get() { - return request(RequestType.GET); - } - - @Override - public CompletableFuture head() { - return request(RequestType.HEAD); - } - - @Override - public CompletableFuture patch() { - return request(RequestType.PATCH); - } - - @Override - public CompletableFuture post() { - return request(RequestType.POST); - } - - @Override - public CompletableFuture put() { - return request(RequestType.PUT); - } - -} diff --git a/core/src/main/java/com/arangodb/async/internal/ArangoSearchAsyncImpl.java b/core/src/main/java/com/arangodb/async/internal/ArangoSearchAsyncImpl.java deleted file mode 100644 index 9c9740ee4..000000000 --- a/core/src/main/java/com/arangodb/async/internal/ArangoSearchAsyncImpl.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * DISCLAIMER - * - * Copyright 2018 ArangoDB GmbH, Cologne, Germany - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Copyright holder is ArangoDB GmbH, Cologne, Germany - */ - -package com.arangodb.async.internal; - -import com.arangodb.async.ArangoSearchAsync; -import com.arangodb.entity.ViewEntity; -import com.arangodb.entity.arangosearch.ArangoSearchPropertiesEntity; -import com.arangodb.internal.InternalArangoSearch; -import com.arangodb.model.arangosearch.ArangoSearchCreateOptions; -import com.arangodb.model.arangosearch.ArangoSearchPropertiesOptions; - -import java.util.Objects; -import java.util.concurrent.CompletableFuture; - -/** - * @author Mark Vollmary - */ -public class ArangoSearchAsyncImpl - extends InternalArangoSearch - implements ArangoSearchAsync { - - ArangoSearchAsyncImpl(final ArangoDatabaseAsyncImpl db, final String name) { - super(db, name); - } - - @Override - public CompletableFuture exists() { - return getInfo().thenApply(Objects::nonNull).exceptionally(Objects::isNull); - } - - @Override - public CompletableFuture drop() { - return executor.execute(dropRequest(), Void.class); - } - - @Override - public synchronized CompletableFuture rename(final String newName) { - return executor.execute(renameRequest(newName), ViewEntity.class); - } - - @Override - public CompletableFuture getInfo() { - return executor.execute(getInfoRequest(), ViewEntity.class); - } - - @Override - public CompletableFuture create() { - return create(new ArangoSearchCreateOptions()); - } - - @Override - public CompletableFuture create(final ArangoSearchCreateOptions options) { - return db().createArangoSearch(name(), options); - } - - @Override - public CompletableFuture getProperties() { - return executor.execute(getPropertiesRequest(), ArangoSearchPropertiesEntity.class); - } - - @Override - public CompletableFuture updateProperties(final ArangoSearchPropertiesOptions options) { - return executor.execute(updatePropertiesRequest(options), ArangoSearchPropertiesEntity.class); - } - - @Override - public CompletableFuture replaceProperties( - final ArangoSearchPropertiesOptions options) { - return executor.execute(replacePropertiesRequest(options), ArangoSearchPropertiesEntity.class); - } - -} diff --git a/core/src/main/java/com/arangodb/async/internal/ArangoVertexCollectionAsyncImpl.java b/core/src/main/java/com/arangodb/async/internal/ArangoVertexCollectionAsyncImpl.java deleted file mode 100644 index 6dd8aa782..000000000 --- a/core/src/main/java/com/arangodb/async/internal/ArangoVertexCollectionAsyncImpl.java +++ /dev/null @@ -1,116 +0,0 @@ -/* - * DISCLAIMER - * - * Copyright 2016 ArangoDB GmbH, Cologne, Germany - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Copyright holder is ArangoDB GmbH, Cologne, Germany - */ - -package com.arangodb.async.internal; - -import com.arangodb.async.ArangoVertexCollectionAsync; -import com.arangodb.entity.VertexEntity; -import com.arangodb.entity.VertexUpdateEntity; -import com.arangodb.internal.InternalArangoVertexCollection; -import com.arangodb.model.*; - -import java.util.concurrent.CompletableFuture; - -/** - * @author Mark Vollmary - */ -public class ArangoVertexCollectionAsyncImpl extends - InternalArangoVertexCollection - implements ArangoVertexCollectionAsync { - - ArangoVertexCollectionAsyncImpl(final ArangoGraphAsyncImpl graph, final String name) { - super(graph, name); - } - - @Override - public CompletableFuture drop() { - return drop(new VertexCollectionDropOptions()); - } - - @Override - public CompletableFuture drop(VertexCollectionDropOptions options) { - return executor.execute(dropRequest(options), Void.class); - } - - @Override - public CompletableFuture insertVertex(final Object value) { - return executor.execute(insertVertexRequest(value, new VertexCreateOptions()), - insertVertexResponseDeserializer()); - } - - @Override - public CompletableFuture insertVertex(final Object value, final VertexCreateOptions options) { - return executor.execute(insertVertexRequest(value, options), insertVertexResponseDeserializer()); - } - - @Override - public CompletableFuture getVertex(final String key, final Class type) { - return getVertex(key, type, null); - } - - @Override - public CompletableFuture getVertex( - final String key, - final Class type, - final GraphDocumentReadOptions options) { - return executor.execute(getVertexRequest(key, options), getVertexResponseDeserializer(type)) - .exceptionally(ExceptionUtil.catchGetDocumentExceptions()); - } - - @Override - public CompletableFuture replaceVertex(final String key, final Object value) { - return executor.execute(replaceVertexRequest(key, value, new VertexReplaceOptions()), - replaceVertexResponseDeserializer()); - } - - @Override - public CompletableFuture replaceVertex( - final String key, - final Object value, - final VertexReplaceOptions options) { - return executor.execute(replaceVertexRequest(key, value, options), replaceVertexResponseDeserializer()); - } - - @Override - public CompletableFuture updateVertex(final String key, final Object value) { - return executor.execute(updateVertexRequest(key, value, new VertexUpdateOptions()), - updateVertexResponseDeserializer()); - } - - @Override - public CompletableFuture updateVertex( - final String key, - final Object value, - final VertexUpdateOptions options) { - return executor.execute(updateVertexRequest(key, value, options), updateVertexResponseDeserializer()); - } - - @Override - public CompletableFuture deleteVertex(final String key) { - return executor.execute(deleteVertexRequest(key, new VertexDeleteOptions()), Void.class); - } - - @Override - public CompletableFuture deleteVertex(final String key, final VertexDeleteOptions options) { - return executor.execute(deleteVertexRequest(key, options), Void.class); - } - -} diff --git a/core/src/main/java/com/arangodb/async/internal/ArangoViewAsyncImpl.java b/core/src/main/java/com/arangodb/async/internal/ArangoViewAsyncImpl.java deleted file mode 100644 index a019cb721..000000000 --- a/core/src/main/java/com/arangodb/async/internal/ArangoViewAsyncImpl.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * DISCLAIMER - * - * Copyright 2018 ArangoDB GmbH, Cologne, Germany - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Copyright holder is ArangoDB GmbH, Cologne, Germany - */ - -package com.arangodb.async.internal; - -import com.arangodb.async.ArangoViewAsync; -import com.arangodb.entity.ViewEntity; -import com.arangodb.internal.InternalArangoView; - -import java.util.Objects; -import java.util.concurrent.CompletableFuture; - -/** - * @author Mark Vollmary - */ -public class ArangoViewAsyncImpl extends - InternalArangoView implements ArangoViewAsync { - - ArangoViewAsyncImpl(final ArangoDatabaseAsyncImpl db, final String name) { - super(db, name); - } - - @Override - public CompletableFuture exists() { - return getInfo().thenApply(Objects::nonNull).exceptionally(Objects::isNull); - } - - @Override - public CompletableFuture drop() { - return executor.execute(dropRequest(), Void.class); - } - - @Override - public synchronized CompletableFuture rename(final String newName) { - return executor.execute(renameRequest(newName), ViewEntity.class); - } - - @Override - public CompletableFuture getInfo() { - return executor.execute(getInfoRequest(), ViewEntity.class); - } - -} diff --git a/core/src/main/java/com/arangodb/async/internal/ExceptionUtil.java b/core/src/main/java/com/arangodb/async/internal/ExceptionUtil.java deleted file mode 100644 index 422e779ed..000000000 --- a/core/src/main/java/com/arangodb/async/internal/ExceptionUtil.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * DISCLAIMER - * - * Copyright 2016 ArangoDB GmbH, Cologne, Germany - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Copyright holder is ArangoDB GmbH, Cologne, Germany - */ - -package com.arangodb.async.internal; - -import com.arangodb.ArangoDBException; - -import java.util.concurrent.CompletionException; -import java.util.function.Function; - -/** - * @author Michele Rastelli - */ -class ExceptionUtil { - - private ExceptionUtil() { - } - - static Function catchGetDocumentExceptions() { - return throwable -> { - if (throwable instanceof CompletionException) { - if (throwable.getCause() instanceof ArangoDBException) { - ArangoDBException arangoDBException = (ArangoDBException) throwable.getCause(); - - // handle Response: 404, Error: 1655 - transaction not found - if (arangoDBException.getErrorNum() != null && arangoDBException.getErrorNum() == 1655) { - throw (CompletionException) throwable; - } - - if ((arangoDBException.getResponseCode() != null && - (arangoDBException.getResponseCode() == 404 || arangoDBException.getResponseCode() == 304 || arangoDBException.getResponseCode() == 412))) { - return null; - } - } - throw (CompletionException) throwable; - } - throw new CompletionException(throwable); - }; - } -} diff --git a/core/src/main/java/com/arangodb/async/internal/SearchAliasAsyncImpl.java b/core/src/main/java/com/arangodb/async/internal/SearchAliasAsyncImpl.java deleted file mode 100644 index d5e4cbd4f..000000000 --- a/core/src/main/java/com/arangodb/async/internal/SearchAliasAsyncImpl.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * DISCLAIMER - * - * Copyright 2018 ArangoDB GmbH, Cologne, Germany - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Copyright holder is ArangoDB GmbH, Cologne, Germany - */ - -package com.arangodb.async.internal; - -import com.arangodb.async.SearchAliasAsync; -import com.arangodb.entity.ViewEntity; -import com.arangodb.entity.arangosearch.SearchAliasPropertiesEntity; -import com.arangodb.internal.InternalSearchAlias; -import com.arangodb.model.arangosearch.SearchAliasCreateOptions; -import com.arangodb.model.arangosearch.SearchAliasPropertiesOptions; - -import java.util.Objects; -import java.util.concurrent.CompletableFuture; - -public class SearchAliasAsyncImpl - extends InternalSearchAlias - implements SearchAliasAsync { - - SearchAliasAsyncImpl(final ArangoDatabaseAsyncImpl db, final String name) { - super(db, name); - } - - @Override - public CompletableFuture exists() { - return getInfo().thenApply(Objects::nonNull).exceptionally(Objects::isNull); - } - - @Override - public CompletableFuture drop() { - return executor.execute(dropRequest(), Void.class); - } - - @Override - public synchronized CompletableFuture rename(final String newName) { - return executor.execute(renameRequest(newName), ViewEntity.class); - } - - @Override - public CompletableFuture getInfo() { - return executor.execute(getInfoRequest(), ViewEntity.class); - } - - @Override - public CompletableFuture create() { - return create(new SearchAliasCreateOptions()); - } - - @Override - public CompletableFuture create(final SearchAliasCreateOptions options) { - return db().createSearchAlias(name(), options); - } - - @Override - public CompletableFuture getProperties() { - return executor.execute(getPropertiesRequest(), SearchAliasPropertiesEntity.class); - } - - @Override - public CompletableFuture updateProperties(final SearchAliasPropertiesOptions options) { - return executor.execute(updatePropertiesRequest(options), SearchAliasPropertiesEntity.class); - } - - @Override - public CompletableFuture replaceProperties( - final SearchAliasPropertiesOptions options) { - return executor.execute(replacePropertiesRequest(options), SearchAliasPropertiesEntity.class); - } - -} diff --git a/core/src/main/java/com/arangodb/async/internal/utils/CompletableFutureUtils.java b/core/src/main/java/com/arangodb/async/internal/utils/CompletableFutureUtils.java deleted file mode 100644 index 026453645..000000000 --- a/core/src/main/java/com/arangodb/async/internal/utils/CompletableFutureUtils.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.arangodb.async.internal.utils; - -import java.util.concurrent.*; - -public class CompletableFutureUtils { - - private static final ScheduledExecutorService timeoutScheduler = Executors.newSingleThreadScheduledExecutor(r -> { - Thread t = Executors.defaultThreadFactory().newThread(r); - t.setDaemon(true); - return t; - } - ); - - private CompletableFutureUtils() { - } - - public static CompletableFuture orTimeout(CompletableFuture completableFuture, long timeout, - TimeUnit unit) { - ScheduledFuture timeoutTask = timeoutScheduler.schedule(() -> - completableFuture.completeExceptionally(new TimeoutException()), timeout, unit); - completableFuture.whenComplete((v, e) -> timeoutTask.cancel(false)); - return completableFuture; - } - -} diff --git a/core/src/main/java/com/arangodb/internal/net/AsyncCommunication.java b/core/src/main/java/com/arangodb/internal/net/AsyncCommunication.java deleted file mode 100644 index abb630780..000000000 --- a/core/src/main/java/com/arangodb/internal/net/AsyncCommunication.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.arangodb.internal.net; - -import com.arangodb.internal.InternalRequest; -import com.arangodb.internal.InternalResponse; - -import java.io.Closeable; -import java.util.concurrent.CompletableFuture; - -public interface AsyncCommunication extends Closeable { - - CompletableFuture execute(final InternalRequest request, final HostHandle hostHandle); - void setJwt(String jwt); - -} diff --git a/core/src/main/java/com/arangodb/internal/net/AsyncProtocolProvider.java b/core/src/main/java/com/arangodb/internal/net/AsyncProtocolProvider.java deleted file mode 100644 index d77a8e2a9..000000000 --- a/core/src/main/java/com/arangodb/internal/net/AsyncProtocolProvider.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.arangodb.internal.net; - - -import com.arangodb.Protocol; -import com.arangodb.internal.config.ArangoConfig; -import com.fasterxml.jackson.databind.Module; - -public interface AsyncProtocolProvider { - - boolean supportsProtocol(Protocol protocol); - - ConnectionFactory createConnectionFactory(); - - AsyncCommunication createCommunication(ArangoConfig config, HostHandler hostHandler); - - Module protocolModule(); - -} diff --git a/driver/pom.xml b/driver/pom.xml index 37e752817..146851724 100644 --- a/driver/pom.xml +++ b/driver/pom.xml @@ -133,8 +133,6 @@ com.arangodb.internal, com.arangodb.internal.*, - com.arangodb.async.internal, - com.arangodb.async.internal.*, com.arangodb.http, com.arangodb.serde.jackson, com.arangodb.serde.jackson.*, diff --git a/driver/src/main/resources/META-INF/native-image/com.arangodb/arangodb-java-driver/reflect-config.json b/driver/src/main/resources/META-INF/native-image/com.arangodb/arangodb-java-driver/reflect-config.json index 36640cd4b..437cb86cf 100644 --- a/driver/src/main/resources/META-INF/native-image/com.arangodb/arangodb-java-driver/reflect-config.json +++ b/driver/src/main/resources/META-INF/native-image/com.arangodb/arangodb-java-driver/reflect-config.json @@ -1505,4 +1505,4 @@ "allDeclaredMethods": true, "allDeclaredConstructors": true } -] +] \ No newline at end of file diff --git a/driver/src/test/java/com/arangodb/async/ArangoCollectionTest.java b/driver/src/test/java/com/arangodb/async/ArangoCollectionTest.java deleted file mode 100644 index ce0f2879f..000000000 --- a/driver/src/test/java/com/arangodb/async/ArangoCollectionTest.java +++ /dev/null @@ -1,2417 +0,0 @@ -/* - * DISCLAIMER - * - * Copyright 2016 ArangoDB GmbH, Cologne, Germany - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Copyright holder is ArangoDB GmbH, Cologne, Germany - */ - -package com.arangodb.async; - -import com.arangodb.ArangoDBException; -import com.arangodb.entity.*; -import com.arangodb.internal.serde.SerdeUtils; -import com.arangodb.model.*; -import com.arangodb.model.DocumentImportOptions.OnDuplicate; -import com.arangodb.serde.jackson.JacksonSerde; -import com.arangodb.serde.jackson.Key; -import com.arangodb.util.RawData; -import com.arangodb.util.RawJson; -import com.fasterxml.jackson.annotation.JsonTypeInfo; -import com.fasterxml.jackson.databind.JsonNode; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; - -import java.util.*; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutionException; -import java.util.stream.Collectors; -import java.util.stream.IntStream; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.catchThrowable; -import static org.junit.jupiter.api.Assertions.fail; -import static org.junit.jupiter.api.Assumptions.assumeTrue; - -/** - * @author Mark Vollmary - * @author Michele Rastelli - */ -class ArangoCollectionTest extends BaseTest { - - private static final String COLLECTION_NAME = "db_collection_test"; - - ArangoCollectionTest() throws ExecutionException, InterruptedException { - ArangoCollectionAsync collection = db.collection(COLLECTION_NAME); - if (!collection.exists().get()) { - collection.create().get(); - } - } - - @BeforeAll - static void setup() throws InterruptedException, ExecutionException { - db.createCollection(COLLECTION_NAME, null).get(); - } - - @AfterEach - void teardown() throws InterruptedException, ExecutionException { - db.collection(COLLECTION_NAME).drop().get(); - } - - @Test - void create() throws InterruptedException, ExecutionException { - final CollectionEntity result = db.collection(COLLECTION_NAME + "_1").create().get(); - assertThat(result).isNotNull(); - assertThat(result.getId()).isNotNull(); - db.collection(COLLECTION_NAME + "_1").drop().get(); - } - - @Test - void insertDocument() throws InterruptedException, ExecutionException { - db.collection(COLLECTION_NAME) - .insertDocument(new BaseDocument(), null) - .whenComplete((doc, ex) -> { - assertThat(ex).isNull(); - assertThat(doc.getId()).isNotNull(); - assertThat(doc.getKey()).isNotNull(); - assertThat(doc.getRev()).isNotNull(); - assertThat(doc.getNew()).isNull(); - assertThat(doc.getId()).isEqualTo(COLLECTION_NAME + "/" + doc.getKey()); - }) - .get(); - } - - @Test - void insertDocumentReturnNew() throws InterruptedException, ExecutionException { - final DocumentCreateOptions options = new DocumentCreateOptions().returnNew(true); - db.collection(COLLECTION_NAME) - .insertDocument(new BaseDocument(), options) - .whenComplete((doc, ex) -> { - assertThat(doc).isNotNull(); - assertThat(doc.getId()).isNotNull(); - assertThat(doc.getKey()).isNotNull(); - assertThat(doc.getRev()).isNotNull(); - assertThat(doc.getNew()).isNotNull(); - }) - .get(); - } - - @Test - void insertDocumentWithTypeOverwriteModeReplace() throws InterruptedException, ExecutionException { - assumeTrue(isAtLeastVersion(3, 7)); - assumeTrue(db.getSerde().getUserSerde() instanceof JacksonSerde, "polymorphic deserialization support " + - "required"); - ArangoCollectionAsync collection = db.collection(COLLECTION_NAME); - String key = UUID.randomUUID().toString(); - Dog dog = new Dog(key, "Teddy"); - Cat cat = new Cat(key, "Luna"); - - final DocumentCreateOptions options = new DocumentCreateOptions() - .returnNew(true) - .returnOld(true) - .overwriteMode(OverwriteMode.replace); - collection.insertDocument(dog, options).get(); - final DocumentCreateEntity doc = collection.insertDocument(cat, options, Animal.class).get(); - assertThat(doc).isNotNull(); - assertThat(doc.getId()).isNotNull(); - assertThat(doc.getKey()).isNotNull().isEqualTo(key); - assertThat(doc.getRev()).isNotNull(); - - assertThat(doc.getOld()) - .isNotNull() - .isInstanceOf(Dog.class); - assertThat(doc.getOld().getKey()).isEqualTo(key); - assertThat(doc.getOld().getName()).isEqualTo("Teddy"); - - assertThat(doc.getNew()) - .isNotNull() - .isInstanceOf(Cat.class); - assertThat(doc.getNew().getKey()).isEqualTo(key); - assertThat(doc.getNew().getName()).isEqualTo("Luna"); - } - - @Test - void insertDocumentWaitForSync() throws InterruptedException, ExecutionException { - final DocumentCreateOptions options = new DocumentCreateOptions().waitForSync(true); - db.collection(COLLECTION_NAME) - .insertDocument(new BaseDocument(), options) - .whenComplete((doc, ex) -> { - assertThat(doc).isNotNull(); - assertThat(doc.getId()).isNotNull(); - assertThat(doc.getKey()).isNotNull(); - assertThat(doc.getRev()).isNotNull(); - assertThat(doc.getNew()).isNull(); - }) - .get(); - } - - @Test - void insertDocumentAsJson() throws InterruptedException, ExecutionException { - db.collection(COLLECTION_NAME) - .insertDocument(RawJson.of("{\"_key\":\"docRaw\",\"a\":\"test\"}"), null) - .whenComplete((doc, ex) -> { - assertThat(doc).isNotNull(); - assertThat(doc.getId()).isNotNull(); - assertThat(doc.getKey()).isNotNull(); - assertThat(doc.getRev()).isNotNull(); - }) - .get(); - } - - @Test - void getDocument() throws InterruptedException, ExecutionException { - final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) - .insertDocument(new BaseDocument(), null).get(); - assertThat(createResult.getKey()).isNotNull(); - db.collection(COLLECTION_NAME).getDocument(createResult.getKey(), BaseDocument.class, null) - .whenComplete((readResult, ex) -> { - assertThat(readResult.getKey()).isEqualTo(createResult.getKey()); - assertThat(readResult.getId()).isEqualTo(COLLECTION_NAME + "/" + createResult.getKey()); - }) - .get(); - } - - @Test - void getDocumentIfMatch() throws InterruptedException, ExecutionException { - final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) - .insertDocument(new BaseDocument(), null).get(); - assertThat(createResult.getKey()).isNotNull(); - final DocumentReadOptions options = new DocumentReadOptions().ifMatch(createResult.getRev()); - db.collection(COLLECTION_NAME).getDocument(createResult.getKey(), BaseDocument.class, options) - .whenComplete((readResult, ex) -> { - assertThat(readResult.getKey()).isEqualTo(createResult.getKey()); - assertThat(readResult.getId()).isEqualTo(COLLECTION_NAME + "/" + createResult.getKey()); - }) - .get(); - } - - @Test - void getDocumentIfMatchFail() throws InterruptedException, ExecutionException { - final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) - .insertDocument(new BaseDocument(), null).get(); - assertThat(createResult.getKey()).isNotNull(); - final DocumentReadOptions options = new DocumentReadOptions().ifMatch("no"); - db.collection(COLLECTION_NAME).getDocument(createResult.getKey(), BaseDocument.class, options) - .whenComplete((doc, ex) -> assertThat(doc).isNull()) - .get(); - } - - @Test - void getDocumentIfNoneMatch() throws InterruptedException, ExecutionException { - final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) - .insertDocument(new BaseDocument(), null).get(); - assertThat(createResult.getKey()).isNotNull(); - final DocumentReadOptions options = new DocumentReadOptions().ifNoneMatch("no"); - db.collection(COLLECTION_NAME).getDocument(createResult.getKey(), BaseDocument.class, options) - .whenComplete((readResult, ex) -> { - assertThat(readResult.getKey()).isEqualTo(createResult.getKey()); - assertThat(readResult.getId()).isEqualTo(COLLECTION_NAME + "/" + createResult.getKey()); - }) - .get(); - } - - @Test - void getDocumentIfNoneMatchFail() throws InterruptedException, ExecutionException { - final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) - .insertDocument(new BaseDocument(), null).get(); - assertThat(createResult.getKey()).isNotNull(); - final DocumentReadOptions options = new DocumentReadOptions().ifNoneMatch(createResult.getRev()); - db.collection(COLLECTION_NAME).getDocument(createResult.getKey(), BaseDocument.class, options) - .whenComplete((doc, ex) -> assertThat(doc).isNull()) - .get(); - } - - @Test - void getDocumentAsJson() throws InterruptedException, ExecutionException { - db.collection(COLLECTION_NAME).insertDocument(RawJson.of("{\"_key\":\"docRaw\",\"a\":\"test\"}")).get(); - db.collection(COLLECTION_NAME).getDocument("docRaw", RawJson.class) - .whenComplete((readResult, ex) -> { - assertThat(readResult.getValue().contains("\"_key\":\"docRaw\"")).isEqualTo(true); - assertThat(readResult.getValue().contains("\"_id\":\"db_collection_test/docRaw\"")).isEqualTo(true); - }) - .get(); - } - - @Test - void getDocumentNotFound() throws InterruptedException, ExecutionException { - db.collection(COLLECTION_NAME).getDocument("no", BaseDocument.class) - .whenComplete((doc, ex) -> assertThat(doc).isNull()) - .get(); - } - - @Test - void getDocumentWrongKey() { - Throwable thrown = catchThrowable(() -> db.collection(COLLECTION_NAME).getDocument("no/no", - BaseDocument.class)); - assertThat(thrown).isInstanceOf(ArangoDBException.class); - } - - @Test - void getDocuments() throws InterruptedException, ExecutionException { - 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).get(); - final MultiDocumentEntity documents = db.collection(COLLECTION_NAME) - .getDocuments(Arrays.asList("1", "2", "3"), BaseDocument.class).get(); - assertThat(documents).isNotNull(); - assertThat(documents.getDocuments()).hasSize(3); - for (final BaseDocument document : documents.getDocuments()) { - assertThat(document.getId()).isIn(COLLECTION_NAME + "/" + "1", COLLECTION_NAME + "/" + "2", - COLLECTION_NAME + "/" + "3"); - } - } - - @Test - void getDocumentsNotFound() throws InterruptedException, ExecutionException { - final MultiDocumentEntity readResult = db.collection(COLLECTION_NAME) - .getDocuments(Collections.singleton("no"), BaseDocument.class).get(); - assertThat(readResult).isNotNull(); - assertThat(readResult.getDocuments()).isEmpty(); - assertThat(readResult.getErrors()).hasSize(1); - } - - @Test - void getDocumentsWrongKey() throws InterruptedException, ExecutionException { - final MultiDocumentEntity readResult = db.collection(COLLECTION_NAME) - .getDocuments(Collections.singleton("no/no"), BaseDocument.class).get(); - assertThat(readResult).isNotNull(); - assertThat(readResult.getDocuments()).isEmpty(); - assertThat(readResult.getErrors()).hasSize(1); - } - - @Test - void updateDocument() throws InterruptedException, ExecutionException { - final BaseDocument doc = new BaseDocument(UUID.randomUUID().toString()); - doc.addAttribute("a", "test"); - doc.addAttribute("c", "test"); - final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME).insertDocument(doc, null) - .get(); - doc.updateAttribute("a", "test1"); - doc.addAttribute("b", "test"); - doc.updateAttribute("c", null); - - final CompletableFuture> f = db.collection(COLLECTION_NAME) - .updateDocument(createResult.getKey(), doc, null); - f.whenComplete((updateResult, ex) -> { - assertThat(updateResult).isNotNull(); - assertThat(updateResult.getId()).isEqualTo(createResult.getId()); - assertThat(updateResult.getNew()).isNull(); - assertThat(updateResult.getOld()).isNull(); - assertThat(updateResult.getRev()).isNotEqualTo(updateResult.getOldRev()); - assertThat(updateResult.getOldRev()).isEqualTo(createResult.getRev()); - }).get(); - final DocumentUpdateEntity updateResult = f.get(); - - final BaseDocument readResult = db.collection(COLLECTION_NAME) - .getDocument(createResult.getKey(), BaseDocument.class, null).get(); - assertThat(readResult.getKey()).isEqualTo(createResult.getKey()); - assertThat(readResult.getAttribute("a")).isNotNull(); - assertThat(String.valueOf(readResult.getAttribute("a"))).isEqualTo("test1"); - assertThat(readResult.getAttribute("b")).isNotNull(); - assertThat(String.valueOf(readResult.getAttribute("b"))).isEqualTo("test"); - assertThat(readResult.getRevision()).isEqualTo(updateResult.getRev()); - assertThat(readResult.getProperties()).containsKey("c"); - } - - @Test - void updateDocumentWithDifferentReturnType() throws ExecutionException, InterruptedException { - ArangoCollectionAsync collection = db.collection(COLLECTION_NAME); - final String key = "key-" + UUID.randomUUID(); - final BaseDocument doc = new BaseDocument(key); - doc.addAttribute("a", "test"); - collection.insertDocument(doc).get(); - - final DocumentUpdateEntity updateResult = collection - .updateDocument(key, Collections.singletonMap("b", "test"), - new DocumentUpdateOptions().returnNew(true), BaseDocument.class).get(); - assertThat(updateResult).isNotNull(); - assertThat(updateResult.getKey()).isEqualTo(key); - BaseDocument updated = updateResult.getNew(); - assertThat(updated).isNotNull(); - assertThat(updated.getAttribute("a")).isEqualTo("test"); - assertThat(updated.getAttribute("b")).isEqualTo("test"); - } - - @Test - void updateDocumentIfMatch() throws InterruptedException, ExecutionException { - final BaseDocument doc = new BaseDocument(UUID.randomUUID().toString()); - doc.addAttribute("a", "test"); - doc.addAttribute("c", "test"); - final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME).insertDocument(doc, null) - .get(); - doc.updateAttribute("a", "test1"); - doc.addAttribute("b", "test"); - doc.updateAttribute("c", null); - final DocumentUpdateOptions options = new DocumentUpdateOptions().ifMatch(createResult.getRev()); - final CompletableFuture> f = db.collection(COLLECTION_NAME) - .updateDocument(createResult.getKey(), doc, options); - assertThat(f).isNotNull(); - f.whenComplete((updateResult, ex) -> { - assertThat(updateResult).isNotNull(); - assertThat(updateResult.getId()).isEqualTo(createResult.getId()); - assertThat(updateResult.getRev()).isNotEqualTo(updateResult.getOldRev()); - assertThat(updateResult.getOldRev()).isEqualTo(createResult.getRev()); - }).get(); - final DocumentUpdateEntity updateResult = f.get(); - - final BaseDocument readResult = db.collection(COLLECTION_NAME) - .getDocument(createResult.getKey(), BaseDocument.class, null).get(); - assertThat(readResult.getKey()).isEqualTo(createResult.getKey()); - assertThat(readResult.getAttribute("a")).isNotNull(); - assertThat(String.valueOf(readResult.getAttribute("a"))).isEqualTo("test1"); - assertThat(readResult.getAttribute("b")).isNotNull(); - assertThat(String.valueOf(readResult.getAttribute("b"))).isEqualTo("test"); - assertThat(readResult.getRevision()).isEqualTo(updateResult.getRev()); - assertThat(readResult.getProperties()).containsKey("c"); - } - - @Test - void updateDocumentIfMatchFail() throws InterruptedException, ExecutionException { - final BaseDocument doc = new BaseDocument(UUID.randomUUID().toString()); - doc.addAttribute("a", "test"); - doc.addAttribute("c", "test"); - final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME).insertDocument(doc, null) - .get(); - 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).get(); - fail(); - } catch (final ExecutionException e) { - assertThat(e.getCause()).isInstanceOf(ArangoDBException.class); - } - } - - @Test - void updateDocumentReturnNew() throws InterruptedException, ExecutionException { - final BaseDocument doc = new BaseDocument(UUID.randomUUID().toString()); - doc.addAttribute("a", "test"); - final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME).insertDocument(doc, null) - .get(); - doc.updateAttribute("a", "test1"); - doc.addAttribute("b", "test"); - final DocumentUpdateOptions options = new DocumentUpdateOptions().returnNew(true); - db.collection(COLLECTION_NAME).updateDocument(createResult.getKey(), doc, options) - .whenComplete((updateResult, ex) -> { - assertThat(updateResult).isNotNull(); - assertThat(updateResult.getId()).isEqualTo(createResult.getId()); - assertThat(updateResult.getOldRev()).isEqualTo(createResult.getRev()); - assertThat(updateResult.getNew()).isNotNull(); - assertThat(updateResult.getNew().getKey()).isEqualTo(createResult.getKey()); - assertThat(updateResult.getNew().getRevision()).isNotEqualTo(createResult.getRev()); - assertThat(updateResult.getNew().getAttribute("a")).isNotNull(); - assertThat(String.valueOf(updateResult.getNew().getAttribute("a"))).isEqualTo("test1"); - assertThat(updateResult.getNew().getAttribute("b")).isNotNull(); - assertThat(String.valueOf(updateResult.getNew().getAttribute("b"))).isEqualTo("test"); - }) - .get(); - } - - @Test - void updateDocumentReturnOld() throws InterruptedException, ExecutionException { - final BaseDocument doc = new BaseDocument(UUID.randomUUID().toString()); - doc.addAttribute("a", "test"); - final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME).insertDocument(doc, null) - .get(); - doc.updateAttribute("a", "test1"); - doc.addAttribute("b", "test"); - final DocumentUpdateOptions options = new DocumentUpdateOptions().returnOld(true); - db.collection(COLLECTION_NAME).updateDocument(createResult.getKey(), doc, options) - .whenComplete((updateResult, ex) -> { - assertThat(updateResult).isNotNull(); - assertThat(updateResult.getId()).isEqualTo(createResult.getId()); - assertThat(updateResult.getOldRev()).isEqualTo(createResult.getRev()); - assertThat(updateResult.getOld()).isNotNull(); - assertThat(updateResult.getOld().getKey()).isEqualTo(createResult.getKey()); - assertThat(updateResult.getOld().getRevision()).isEqualTo(createResult.getRev()); - assertThat(updateResult.getOld().getAttribute("a")).isNotNull(); - assertThat(String.valueOf(updateResult.getOld().getAttribute("a"))).isEqualTo("test"); - assertThat(updateResult.getOld().getProperties().keySet()).doesNotContain("b"); - }) - .get(); - } - - @Test - void updateDocumentKeepNullTrue() throws InterruptedException, ExecutionException { - final BaseDocument doc = new BaseDocument(UUID.randomUUID().toString()); - doc.addAttribute("a", "test"); - final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME).insertDocument(doc, null) - .get(); - doc.updateAttribute("a", null); - final DocumentUpdateOptions options = new DocumentUpdateOptions().keepNull(true); - db.collection(COLLECTION_NAME).updateDocument(createResult.getKey(), doc, options) - .whenComplete((updateResult, ex) -> { - assertThat(updateResult).isNotNull(); - assertThat(updateResult.getId()).isEqualTo(createResult.getId()); - assertThat(updateResult.getRev()).isNotEqualTo(updateResult.getOldRev()); - assertThat(updateResult.getOldRev()).isEqualTo(createResult.getRev()); - }) - .get(); - - final BaseDocument readResult = db.collection(COLLECTION_NAME) - .getDocument(createResult.getKey(), BaseDocument.class, null).get(); - assertThat(readResult.getKey()).isEqualTo(createResult.getKey()); - assertThat(readResult.getProperties()).containsKey("a"); - } - - @Test - void updateDocumentKeepNullFalse() throws InterruptedException, ExecutionException { - final BaseDocument doc = new BaseDocument(UUID.randomUUID().toString()); - doc.addAttribute("a", "test"); - final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME).insertDocument(doc, null) - .get(); - doc.updateAttribute("a", null); - final DocumentUpdateOptions options = new DocumentUpdateOptions().keepNull(false); - db.collection(COLLECTION_NAME).updateDocument(createResult.getKey(), doc, options) - .whenComplete((updateResult, ex) -> { - assertThat(updateResult).isNotNull(); - assertThat(updateResult.getId()).isEqualTo(createResult.getId()); - assertThat(updateResult.getRev()).isNotEqualTo(updateResult.getOldRev()); - assertThat(updateResult.getOldRev()).isEqualTo(createResult.getRev()); - }) - .get(); - - final BaseDocument readResult = db.collection(COLLECTION_NAME) - .getDocument(createResult.getKey(), BaseDocument.class, null).get(); - assertThat(readResult.getKey()).isEqualTo(createResult.getKey()); - assertThat(readResult.getId()).isEqualTo(createResult.getId()); - assertThat(readResult.getRevision()).isNotNull(); - assertThat(readResult.getProperties().keySet()).doesNotContain("a"); - } - - @Test - void updateDocumentMergeObjectsTrue() throws InterruptedException, ExecutionException { - final BaseDocument doc = new BaseDocument(UUID.randomUUID().toString()); - final Map a = new HashMap<>(); - a.put("a", "test"); - doc.addAttribute("a", a); - final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME).insertDocument(doc, null) - .get(); - a.clear(); - a.put("b", "test"); - doc.updateAttribute("a", a); - final DocumentUpdateOptions options = new DocumentUpdateOptions().mergeObjects(true); - db.collection(COLLECTION_NAME).updateDocument(createResult.getKey(), doc, options) - .whenComplete((updateResult, ex) -> { - assertThat(updateResult).isNotNull(); - assertThat(updateResult.getId()).isEqualTo(createResult.getId()); - assertThat(updateResult.getRev()).isNotEqualTo(updateResult.getOldRev()); - assertThat(updateResult.getOldRev()).isEqualTo(createResult.getRev()); - }) - .get(); - - final BaseDocument readResult = db.collection(COLLECTION_NAME) - .getDocument(createResult.getKey(), BaseDocument.class, null).get(); - assertThat(readResult.getKey()).isEqualTo(createResult.getKey()); - final Object aResult = readResult.getAttribute("a"); - assertThat(aResult).isInstanceOf(Map.class); - final Map aMap = (Map) aResult; - assertThat(aMap).containsKey("a"); - assertThat(aMap).containsKey("b"); - } - - @Test - void updateDocumentMergeObjectsFalse() throws InterruptedException, ExecutionException { - final BaseDocument doc = new BaseDocument(UUID.randomUUID().toString()); - final Map a = new HashMap<>(); - a.put("a", "test"); - doc.addAttribute("a", a); - final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME).insertDocument(doc, null) - .get(); - a.clear(); - a.put("b", "test"); - doc.updateAttribute("a", a); - final DocumentUpdateOptions options = new DocumentUpdateOptions().mergeObjects(false); - db.collection(COLLECTION_NAME).updateDocument(createResult.getKey(), doc, options) - .whenComplete((updateResult, ex) -> { - assertThat(updateResult).isNotNull(); - assertThat(updateResult.getId()).isEqualTo(createResult.getId()); - assertThat(updateResult.getRev()).isNotEqualTo(updateResult.getOldRev()); - assertThat(updateResult.getOldRev()).isEqualTo(createResult.getRev()); - }) - .get(); - - final BaseDocument readResult = db.collection(COLLECTION_NAME) - .getDocument(createResult.getKey(), BaseDocument.class, null).get(); - assertThat(readResult.getKey()).isEqualTo(createResult.getKey()); - final Object aResult = readResult.getAttribute("a"); - assertThat(aResult).isInstanceOf(Map.class); - final Map aMap = (Map) aResult; - assertThat(aMap.keySet()).doesNotContain("a"); - assertThat(aMap).containsKey("b"); - } - - @Test - void updateDocumentIgnoreRevsFalse() throws InterruptedException, ExecutionException { - final BaseDocument doc = new BaseDocument(UUID.randomUUID().toString()); - doc.addAttribute("a", "test"); - final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME).insertDocument(doc, null) - .get(); - doc.updateAttribute("a", "test1"); - doc.setRevision("no"); - try { - final DocumentUpdateOptions options = new DocumentUpdateOptions().ignoreRevs(false); - db.collection(COLLECTION_NAME).updateDocument(createResult.getKey(), doc, options).get(); - fail(); - } catch (final ExecutionException e) { - assertThat(e.getCause()).isInstanceOf(ArangoDBException.class); - } - } - - @Test - void replaceDocument() throws InterruptedException, ExecutionException { - final BaseDocument doc = new BaseDocument(UUID.randomUUID().toString()); - doc.addAttribute("a", "test"); - final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME).insertDocument(doc, null) - .get(); - doc.removeAttribute("a"); - doc.addAttribute("b", "test"); - final CompletableFuture> f = db.collection(COLLECTION_NAME) - .replaceDocument(createResult.getKey(), doc, null); - f.whenComplete((replaceResult, ex) -> { - assertThat(replaceResult).isNotNull(); - assertThat(replaceResult.getId()).isEqualTo(createResult.getId()); - assertThat(replaceResult.getNew()).isNull(); - assertThat(replaceResult.getOld()).isNull(); - assertThat(replaceResult.getRev()).isNotEqualTo(replaceResult.getOldRev()); - assertThat(replaceResult.getOldRev()).isEqualTo(createResult.getRev()); - }).get(); - final DocumentUpdateEntity replaceResult = f.get(); - - final BaseDocument readResult = db.collection(COLLECTION_NAME) - .getDocument(createResult.getKey(), BaseDocument.class, null).get(); - assertThat(readResult.getKey()).isEqualTo(createResult.getKey()); - assertThat(readResult.getRevision()).isEqualTo(replaceResult.getRev()); - assertThat(readResult.getProperties().keySet()).doesNotContain("a"); - assertThat(readResult.getAttribute("b")).isNotNull(); - assertThat(String.valueOf(readResult.getAttribute("b"))).isEqualTo("test"); - } - - @Test - void replaceDocumentIfMatch() throws InterruptedException, ExecutionException { - final BaseDocument doc = new BaseDocument(UUID.randomUUID().toString()); - doc.addAttribute("a", "test"); - final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME).insertDocument(doc, null) - .get(); - doc.removeAttribute("a"); - doc.addAttribute("b", "test"); - final DocumentReplaceOptions options = new DocumentReplaceOptions().ifMatch(createResult.getRev()); - final CompletableFuture> f = db.collection(COLLECTION_NAME) - .replaceDocument(createResult.getKey(), doc, options); - f.whenComplete((replaceResult, ex) -> { - assertThat(replaceResult).isNotNull(); - assertThat(replaceResult.getId()).isEqualTo(createResult.getId()); - assertThat(replaceResult.getRev()).isNotEqualTo(replaceResult.getOldRev()); - assertThat(replaceResult.getOldRev()).isEqualTo(createResult.getRev()); - }).get(); - final DocumentUpdateEntity replaceResult = f.get(); - - final BaseDocument readResult = db.collection(COLLECTION_NAME) - .getDocument(createResult.getKey(), BaseDocument.class, null).get(); - assertThat(readResult.getKey()).isEqualTo(createResult.getKey()); - assertThat(readResult.getRevision()).isEqualTo(replaceResult.getRev()); - assertThat(readResult.getProperties().keySet()).doesNotContain("a"); - assertThat(readResult.getAttribute("b")).isNotNull(); - assertThat(String.valueOf(readResult.getAttribute("b"))).isEqualTo("test"); - } - - @Test - void replaceDocumentIfMatchFail() throws InterruptedException, ExecutionException { - final BaseDocument doc = new BaseDocument(UUID.randomUUID().toString()); - doc.addAttribute("a", "test"); - final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME).insertDocument(doc, null) - .get(); - doc.removeAttribute("a"); - doc.addAttribute("b", "test"); - try { - final DocumentReplaceOptions options = new DocumentReplaceOptions().ifMatch("no"); - db.collection(COLLECTION_NAME).replaceDocument(createResult.getKey(), doc, options).get(); - fail(); - } catch (final ExecutionException e) { - assertThat(e.getCause()).isInstanceOf(ArangoDBException.class); - } - } - - @Test - void replaceDocumentIgnoreRevsFalse() throws InterruptedException, ExecutionException { - final BaseDocument doc = new BaseDocument(UUID.randomUUID().toString()); - doc.addAttribute("a", "test"); - final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME).insertDocument(doc, null) - .get(); - doc.removeAttribute("a"); - doc.addAttribute("b", "test"); - doc.setRevision("no"); - try { - final DocumentReplaceOptions options = new DocumentReplaceOptions().ignoreRevs(false); - db.collection(COLLECTION_NAME).replaceDocument(createResult.getKey(), doc, options).get(); - fail(); - } catch (final ExecutionException e) { - assertThat(e.getCause()).isInstanceOf(ArangoDBException.class); - } - } - - @Test - void replaceDocumentReturnNew() throws InterruptedException, ExecutionException { - final BaseDocument doc = new BaseDocument(UUID.randomUUID().toString()); - doc.addAttribute("a", "test"); - final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME).insertDocument(doc, null) - .get(); - doc.removeAttribute("a"); - doc.addAttribute("b", "test"); - final DocumentReplaceOptions options = new DocumentReplaceOptions().returnNew(true); - db.collection(COLLECTION_NAME).replaceDocument(createResult.getKey(), doc, options) - .whenComplete((replaceResult, ex) -> { - assertThat(replaceResult).isNotNull(); - assertThat(replaceResult.getId()).isEqualTo(createResult.getId()); - assertThat(replaceResult.getOldRev()).isEqualTo(createResult.getRev()); - assertThat(replaceResult.getNew()).isNotNull(); - assertThat(replaceResult.getNew().getKey()).isEqualTo(createResult.getKey()); - assertThat(replaceResult.getNew().getRevision()).isNotEqualTo(createResult.getRev()); - assertThat(replaceResult.getNew().getProperties().keySet()).doesNotContain("a"); - assertThat(replaceResult.getNew().getAttribute("b")).isNotNull(); - assertThat(String.valueOf(replaceResult.getNew().getAttribute("b"))).isEqualTo("test"); - }) - .get(); - } - - @Test - void replaceDocumentReturnOld() throws InterruptedException, ExecutionException { - final BaseDocument doc = new BaseDocument(UUID.randomUUID().toString()); - doc.addAttribute("a", "test"); - final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME).insertDocument(doc, null) - .get(); - doc.removeAttribute("a"); - doc.addAttribute("b", "test"); - final DocumentReplaceOptions options = new DocumentReplaceOptions().returnOld(true); - db.collection(COLLECTION_NAME).replaceDocument(createResult.getKey(), doc, options) - .whenComplete((replaceResult, ex) -> { - assertThat(replaceResult).isNotNull(); - assertThat(replaceResult.getId()).isEqualTo(createResult.getId()); - assertThat(replaceResult.getOldRev()).isEqualTo(createResult.getRev()); - assertThat(replaceResult.getOld()).isNotNull(); - assertThat(replaceResult.getOld().getKey()).isEqualTo(createResult.getKey()); - assertThat(replaceResult.getOld().getRevision()).isEqualTo(createResult.getRev()); - assertThat(replaceResult.getOld().getAttribute("a")).isNotNull(); - assertThat(String.valueOf(replaceResult.getOld().getAttribute("a"))).isEqualTo("test"); - assertThat(replaceResult.getOld().getProperties().keySet()).doesNotContain("b"); - }) - .get(); - } - - @Test - void deleteDocument() throws InterruptedException, ExecutionException { - final BaseDocument doc = new BaseDocument(UUID.randomUUID().toString()); - final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME).insertDocument(doc, null) - .get(); - db.collection(COLLECTION_NAME).deleteDocument(createResult.getKey()).get(); - db.collection(COLLECTION_NAME).getDocument(createResult.getKey(), BaseDocument.class, null) - .whenComplete((document, ex) -> assertThat(document).isNull()) - .get(); - } - - @Test - void deleteDocumentReturnOld() throws InterruptedException, ExecutionException { - final BaseDocument doc = new BaseDocument(UUID.randomUUID().toString()); - doc.addAttribute("a", "test"); - final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME).insertDocument(doc, null) - .get(); - final DocumentDeleteOptions options = new DocumentDeleteOptions().returnOld(true); - db.collection(COLLECTION_NAME).deleteDocument(createResult.getKey(), options, BaseDocument.class) - .whenComplete((deleteResult, ex) -> { - assertThat(deleteResult.getOld()).isNotNull(); - assertThat(deleteResult.getOld()).isInstanceOf(BaseDocument.class); - assertThat(deleteResult.getOld().getAttribute("a")).isNotNull(); - assertThat(String.valueOf(deleteResult.getOld().getAttribute("a"))).isEqualTo("test"); - }) - .get(); - } - - @Test - void deleteDocumentIfMatch() throws InterruptedException, ExecutionException { - final BaseDocument doc = new BaseDocument(UUID.randomUUID().toString()); - final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME).insertDocument(doc, null) - .get(); - final DocumentDeleteOptions options = new DocumentDeleteOptions().ifMatch(createResult.getRev()); - db.collection(COLLECTION_NAME).deleteDocument(createResult.getKey(), options).get(); - db.collection(COLLECTION_NAME).getDocument(createResult.getKey(), BaseDocument.class, null) - .whenComplete((document, ex) -> assertThat(document).isNull()) - .get(); - } - - @Test - void deleteDocumentIfMatchFail() throws InterruptedException, ExecutionException { - final BaseDocument doc = new BaseDocument(UUID.randomUUID().toString()); - final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME).insertDocument(doc, null) - .get(); - final DocumentDeleteOptions options = new DocumentDeleteOptions().ifMatch("no"); - try { - db.collection(COLLECTION_NAME).deleteDocument(createResult.getKey(), options).get(); - fail(); - } catch (final ExecutionException e) { - assertThat(e.getCause()).isInstanceOf(ArangoDBException.class); - } - } - - @Test - void getIndex() throws InterruptedException, ExecutionException { - final Collection fields = new ArrayList<>(); - fields.add("a"); - final IndexEntity createResult = db.collection(COLLECTION_NAME).ensurePersistentIndex(fields, null).get(); - db.collection(COLLECTION_NAME).getIndex(createResult.getId()) - .whenComplete((readResult, ex) -> { - assertThat(readResult.getId()).isEqualTo(createResult.getId()); - assertThat(readResult.getType()).isEqualTo(createResult.getType()); - }) - .get(); - } - - @Test - void getIndexByKey() throws InterruptedException, ExecutionException { - final Collection fields = new ArrayList<>(); - fields.add("a"); - final IndexEntity createResult = db.collection(COLLECTION_NAME).ensurePersistentIndex(fields, null).get(); - db.collection(COLLECTION_NAME).getIndex(createResult.getId().split("/")[1]) - .whenComplete((readResult, ex) -> { - assertThat(readResult.getId()).isEqualTo(createResult.getId()); - assertThat(readResult.getType()).isEqualTo(createResult.getType()); - }) - .get(); - } - - @Test - void deleteIndex() throws InterruptedException, ExecutionException { - final Collection fields = new ArrayList<>(); - fields.add("deleteIndexField"); - final IndexEntity createResult = db.collection(COLLECTION_NAME).ensurePersistentIndex(fields, null).get(); - db.getIndex(createResult.getId()).get(); - db.collection(COLLECTION_NAME).deleteIndex(createResult.getId()) - .whenComplete((id, ex) -> { - assertThat(id).isEqualTo(createResult.getId()); - try { - db.getIndex(id).get(); - fail(); - } catch (final InterruptedException exception) { - exception.printStackTrace(); - fail(); - } catch (final ExecutionException exception) { - assertThat(exception.getCause()).isInstanceOf(ArangoDBException.class); - } - }) - .get(); - } - - @Test - void deleteIndexByKey() throws InterruptedException, ExecutionException { - final Collection fields = new ArrayList<>(); - fields.add("deleteIndexByKeyField"); - final IndexEntity createResult = db.collection(COLLECTION_NAME).ensurePersistentIndex(fields, null).get(); - db.getIndex(createResult.getId()).get(); - db.collection(COLLECTION_NAME).deleteIndex(createResult.getId().split("/")[1]) - .whenComplete((id, ex) -> { - assertThat(id).isEqualTo(createResult.getId()); - try { - db.getIndex(id).get(); - fail(); - } catch (final InterruptedException exception) { - exception.printStackTrace(); - fail(); - } catch (final ExecutionException exception) { - assertThat(exception.getCause()).isInstanceOf(ArangoDBException.class); - } - }) - .get(); - } - - @Test - void createGeoIndex() throws InterruptedException, ExecutionException { - final Collection fields = new ArrayList<>(); - fields.add("a"); - db.collection(COLLECTION_NAME).ensureGeoIndex(fields, null) - .whenComplete((indexResult, ex) -> { - assertThat(indexResult).isNotNull(); - assertThat(indexResult.getFields()).contains("a"); - assertThat(indexResult.getGeoJson()).isEqualTo(false); - assertThat(indexResult.getId()).startsWith(COLLECTION_NAME); - assertThat(indexResult.getIsNewlyCreated()).isEqualTo(true); - assertThat(indexResult.getMinLength()).isNull(); - assertThat(indexResult.getSelectivityEstimate()).isNull(); - assertThat(indexResult.getSparse()).isEqualTo(true); - assertThat(indexResult.getType()).isIn(IndexType.geo, IndexType.geo1); - assertThat(indexResult.getUnique()).isEqualTo(false); - }) - .get(); - } - - @Test - void createGeoIndexWithOptions() throws ExecutionException, InterruptedException { - assumeTrue(isAtLeastVersion(3, 5)); - 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).get(); - assertThat(indexResult).isNotNull(); - assertThat(indexResult.getFields()).contains("a"); - assertThat(indexResult.getId()).startsWith(COLLECTION_NAME); - assertThat(indexResult.getIsNewlyCreated()).isTrue(); - assertThat(indexResult.getMinLength()).isNull(); - assertThat(indexResult.getSparse()).isTrue(); - assertThat(indexResult.getUnique()).isFalse(); - if (isAtLeastVersion(3, 4)) { - assertThat(indexResult.getType()).isEqualTo(IndexType.geo); - } else { - assertThat(indexResult.getType()).isEqualTo(IndexType.geo1); - } - assertThat(indexResult.getName()).isEqualTo("myGeoIndex1"); - } - - @Test - void createGeo2Index() throws ExecutionException, InterruptedException { - final Collection fields = new ArrayList<>(); - fields.add("a"); - fields.add("b"); - db.collection(COLLECTION_NAME).ensureGeoIndex(fields, null).whenComplete((indexResult, ex) -> { - assertThat(indexResult).isNotNull(); - assertThat(indexResult.getFields()).contains("a"); - assertThat(indexResult.getFields()).contains("b"); - assertThat(indexResult.getId()).startsWith(COLLECTION_NAME); - assertThat(indexResult.getIsNewlyCreated()).isEqualTo(true); - assertThat(indexResult.getMinLength()).isNull(); - assertThat(indexResult.getSparse()).isEqualTo(true); - assertThat(indexResult.getUnique()).isEqualTo(false); - try { - if (isAtLeastVersion(3, 4)) { - assertThat(indexResult.getType()).isEqualTo(IndexType.geo); - } else { - assertThat(indexResult.getType()).isEqualTo(IndexType.geo2); - } - } catch (InterruptedException | ExecutionException e) { - e.printStackTrace(); - fail(); - } - }).get(); - } - - @Test - void createGeo2IndexWithOptions() throws ExecutionException, InterruptedException { - assumeTrue(isAtLeastVersion(3, 5)); - 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).get(); - assertThat(indexResult).isNotNull(); - assertThat(indexResult.getFields()).contains("a"); - assertThat(indexResult.getFields()).contains("b"); - assertThat(indexResult.getId()).startsWith(COLLECTION_NAME); - assertThat(indexResult.getIsNewlyCreated()).isTrue(); - assertThat(indexResult.getMinLength()).isNull(); - assertThat(indexResult.getSparse()).isTrue(); - assertThat(indexResult.getUnique()).isFalse(); - if (isAtLeastVersion(3, 4)) { - assertThat(indexResult.getType()).isEqualTo(IndexType.geo); - } else { - assertThat(indexResult.getType()).isEqualTo(IndexType.geo2); - } - assertThat(indexResult.getName()).isEqualTo("myGeoIndex2"); - } - - @Test - void createPersistentIndex() throws InterruptedException, ExecutionException { - final Collection fields = new ArrayList<>(); - fields.add("a"); - fields.add("b"); - db.collection(COLLECTION_NAME).ensurePersistentIndex(fields, null) - .whenComplete((indexResult, ex) -> { - assertThat(indexResult).isNotNull(); - assertThat(indexResult.getConstraint()).isNull(); - assertThat(indexResult.getFields()).contains("a"); - assertThat(indexResult.getFields()).contains("b"); - assertThat(indexResult.getGeoJson()).isNull(); - assertThat(indexResult.getId()).startsWith(COLLECTION_NAME); - assertThat(indexResult.getIsNewlyCreated()).isEqualTo(true); - assertThat(indexResult.getMinLength()).isNull(); - assertThat(indexResult.getSparse()).isEqualTo(false); - assertThat(indexResult.getType()).isEqualTo(IndexType.persistent); - assertThat(indexResult.getUnique()).isEqualTo(false); - assertThat(indexResult.getDeduplicate()).isTrue(); - }) - .get(); - } - - @Test - void createPersistentIndexWithOptions() throws ExecutionException, InterruptedException { - assumeTrue(isAtLeastVersion(3, 5)); - 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).get(); - assertThat(indexResult).isNotNull(); - assertThat(indexResult.getConstraint()).isNull(); - assertThat(indexResult.getFields()).contains("a"); - assertThat(indexResult.getFields()).contains("b"); - assertThat(indexResult.getId()).startsWith(COLLECTION_NAME); - assertThat(indexResult.getIsNewlyCreated()).isTrue(); - assertThat(indexResult.getMinLength()).isNull(); - assertThat(indexResult.getSparse()).isFalse(); - assertThat(indexResult.getType()).isEqualTo(IndexType.persistent); - assertThat(indexResult.getUnique()).isFalse(); - assertThat(indexResult.getName()).isEqualTo("myPersistentIndex"); - } - - @Test - void indexDeduplicate() throws ExecutionException, InterruptedException { - assumeTrue(isAtLeastVersion(3, 8)); - - String name = "persistentIndex-" + rnd(); - final PersistentIndexOptions options = new PersistentIndexOptions(); - options.name(name); - options.deduplicate(true); - - String f1 = "field-" + rnd(); - String f2 = "field-" + rnd(); - - final Collection fields = Arrays.asList(f1, f2); - final IndexEntity indexResult = db.collection(COLLECTION_NAME).ensurePersistentIndex(fields, options).get(); - assertThat(indexResult).isNotNull(); - assertThat(indexResult.getDeduplicate()).isTrue(); - } - - @Test - void indexDeduplicateFalse() throws ExecutionException, InterruptedException { - assumeTrue(isAtLeastVersion(3, 8)); - - String name = "persistentIndex-" + rnd(); - final PersistentIndexOptions options = new PersistentIndexOptions(); - options.name(name); - options.deduplicate(false); - - String f1 = "field-" + rnd(); - String f2 = "field-" + rnd(); - - final Collection fields = Arrays.asList(f1, f2); - final IndexEntity indexResult = db.collection(COLLECTION_NAME).ensurePersistentIndex(fields, options).get(); - assertThat(indexResult).isNotNull(); - assertThat(indexResult.getDeduplicate()).isFalse(); - } - - @Test - void createFulltextIndex() throws InterruptedException, ExecutionException { - final Collection fields = new ArrayList<>(); - fields.add("a"); - db.collection(COLLECTION_NAME).ensureFulltextIndex(fields, null) - .whenComplete((indexResult, ex) -> { - assertThat(indexResult).isNotNull(); - assertThat(indexResult.getConstraint()).isNull(); - assertThat(indexResult.getFields()).contains("a"); - assertThat(indexResult.getGeoJson()).isNull(); - assertThat(indexResult.getId()).startsWith(COLLECTION_NAME); - assertThat(indexResult.getIsNewlyCreated()).isEqualTo(true); - assertThat(indexResult.getSelectivityEstimate()).isNull(); - assertThat(indexResult.getSparse()).isEqualTo(true); - assertThat(indexResult.getType()).isEqualTo(IndexType.fulltext); - assertThat(indexResult.getUnique()).isEqualTo(false); - }) - .get(); - } - - @Test - void createFulltextIndexWithOptions() throws ExecutionException, InterruptedException { - assumeTrue(isAtLeastVersion(3, 5)); - 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).get(); - assertThat(indexResult).isNotNull(); - assertThat(indexResult.getConstraint()).isNull(); - assertThat(indexResult.getFields()).contains("a"); - assertThat(indexResult.getId()).startsWith(COLLECTION_NAME); - assertThat(indexResult.getIsNewlyCreated()).isTrue(); - assertThat(indexResult.getSparse()).isTrue(); - assertThat(indexResult.getType()).isEqualTo(IndexType.fulltext); - assertThat(indexResult.getUnique()).isFalse(); - assertThat(indexResult.getName()).isEqualTo("myFulltextIndex"); - } - - @Test - void createTtlIndexWithoutOptions() throws ExecutionException, InterruptedException { - assumeTrue(isAtLeastVersion(3, 5)); - final Collection fields = new ArrayList<>(); - fields.add("a"); - try { - db.collection(COLLECTION_NAME).ensureTtlIndex(fields, null).get(); - fail(); - } catch (ExecutionException e) { - assertThat(e.getCause()).isInstanceOf(ArangoDBException.class); - assertThat(e.getCause().getMessage()).contains("expireAfter attribute must be a number"); - assertThat(((ArangoDBException) e.getCause()).getResponseCode()).isEqualTo(400); - assertThat(((ArangoDBException) e.getCause()).getErrorNum()).isEqualTo(10); - } - } - - @Test - void createTtlIndexWithOptions() throws ExecutionException, InterruptedException { - assumeTrue(isAtLeastVersion(3, 5)); - 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).get(); - assertThat(indexResult).isNotNull(); - assertThat(indexResult.getFields()).contains("a"); - assertThat(indexResult.getId()).startsWith(COLLECTION_NAME); - assertThat(indexResult.getIsNewlyCreated()).isTrue(); - assertThat(indexResult.getType()).isEqualTo(IndexType.ttl); - assertThat(indexResult.getExpireAfter()).isEqualTo(3600); - assertThat(indexResult.getName()).isEqualTo("myTtlIndex"); - } - - @Test - void createZKDIndex() throws InterruptedException, ExecutionException { - assumeTrue(isAtLeastVersion(3, 9)); - db.collection(COLLECTION_NAME).truncate().get(); - - final Collection fields = new ArrayList<>(); - fields.add("a"); - fields.add("b"); - IndexEntity indexResult = db.collection(COLLECTION_NAME).ensureZKDIndex(fields, null).get(); - assertThat(indexResult).isNotNull(); - assertThat(indexResult.getConstraint()).isNull(); - assertThat(indexResult.getFields()).contains("a"); - assertThat(indexResult.getFields()).contains("b"); - assertThat(indexResult.getGeoJson()).isNull(); - assertThat(indexResult.getId()).startsWith(COLLECTION_NAME); - assertThat(indexResult.getIsNewlyCreated()).isTrue(); - assertThat(indexResult.getMinLength()).isNull(); - assertThat(indexResult.getType()).isEqualTo(IndexType.zkd); - assertThat(indexResult.getUnique()).isFalse(); - db.collection(COLLECTION_NAME).deleteIndex(indexResult.getId()).get(); - } - - @Test - void createZKDIndexWithOptions() throws ExecutionException, InterruptedException { - assumeTrue(isAtLeastVersion(3, 9)); - db.collection(COLLECTION_NAME).truncate().get(); - - final ZKDIndexOptions options = new ZKDIndexOptions() - .name("myZKDIndex") - .fieldValueTypes(ZKDIndexOptions.FieldValueTypes.DOUBLE); - - final Collection fields = new ArrayList<>(); - fields.add("a"); - fields.add("b"); - final IndexEntity indexResult = db.collection(COLLECTION_NAME).ensureZKDIndex(fields, options).get(); - assertThat(indexResult).isNotNull(); - assertThat(indexResult.getConstraint()).isNull(); - assertThat(indexResult.getFields()).contains("a"); - assertThat(indexResult.getFields()).contains("b"); - assertThat(indexResult.getId()).startsWith(COLLECTION_NAME); - assertThat(indexResult.getIsNewlyCreated()).isTrue(); - assertThat(indexResult.getMinLength()).isNull(); - assertThat(indexResult.getType()).isEqualTo(IndexType.zkd); - assertThat(indexResult.getUnique()).isFalse(); - assertThat(indexResult.getName()).isEqualTo("myZKDIndex"); - db.collection(COLLECTION_NAME).deleteIndex(indexResult.getId()).get(); - } - - @Test - void getIndexes() throws InterruptedException, ExecutionException { - final int initialIndexCount = db.collection(COLLECTION_NAME).getIndexes().get().size(); - final Collection fields = new ArrayList<>(); - fields.add("a"); - db.collection(COLLECTION_NAME).ensurePersistentIndex(fields, null).get(); - db.collection(COLLECTION_NAME).getIndexes() - .whenComplete((indexes, ex) -> { - assertThat(indexes).isNotNull(); - assertThat(indexes.size()).isEqualTo(initialIndexCount + 1); - for (final IndexEntity i : indexes) { - if (i.getType() == IndexType.persistent) { - assertThat(i.getFields().size()).isEqualTo(1); - assertThat(i.getFields()).contains("a"); - } - } - }) - .get(); - } - - @Test - void exists() throws InterruptedException, ExecutionException { - assertThat(db.collection(COLLECTION_NAME).exists().get()).isTrue(); - assertThat(db.collection(COLLECTION_NAME + "no").exists().get()).isFalse(); - } - - @Test - void truncate() throws InterruptedException, ExecutionException { - final BaseDocument doc = new BaseDocument(UUID.randomUUID().toString()); - db.collection(COLLECTION_NAME).insertDocument(doc, null).get(); - final BaseDocument readResult = db.collection(COLLECTION_NAME) - .getDocument(doc.getKey(), BaseDocument.class, null).get(); - assertThat(readResult.getKey()).isEqualTo(doc.getKey()); - db.collection(COLLECTION_NAME).truncate() - .whenComplete((truncateResult, ex) -> { - assertThat(truncateResult).isNotNull(); - assertThat(truncateResult.getId()).isNotNull(); - }) - .get(); - final BaseDocument document = db.collection(COLLECTION_NAME).getDocument(doc.getKey(), BaseDocument.class, null) - .get(); - assertThat(document).isNull(); - } - - @Test - void getCount() throws InterruptedException, ExecutionException { - db.collection(COLLECTION_NAME).count() - .whenComplete((countEmpty, ex) -> { - assertThat(countEmpty).isNotNull(); - assertThat(countEmpty.getCount()).isEqualTo(0L); - }) - .get(); - - db.collection(COLLECTION_NAME).insertDocument(RawJson.of("{}"), null).get(); - - db.collection(COLLECTION_NAME).count() - .whenComplete((count, ex) -> assertThat(count.getCount()).isEqualTo(1L)) - .get(); - } - - @Test - void documentExists() throws InterruptedException, ExecutionException { - db.collection(COLLECTION_NAME).documentExists("no", null) - .whenComplete((existsNot, ex) -> assertThat(existsNot).isEqualTo(false)) - .get(); - - db.collection(COLLECTION_NAME).insertDocument(RawJson.of("{\"_key\":\"abc\"}")).get(); - - db.collection(COLLECTION_NAME).documentExists("abc", null) - .whenComplete((exists, ex) -> assertThat(exists).isEqualTo(true)) - .get(); - } - - @Test - void documentExistsIfMatch() throws InterruptedException, ExecutionException { - final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) - .insertDocument(RawJson.of("{\"_key\":\"abc\"}")).get(); - final DocumentExistsOptions options = new DocumentExistsOptions().ifMatch(createResult.getRev()); - db.collection(COLLECTION_NAME).documentExists("abc", options) - .whenComplete((exists, ex) -> assertThat(exists).isEqualTo(true)) - .get(); - } - - @Test - void documentExistsIfMatchFail() throws InterruptedException, ExecutionException { - db.collection(COLLECTION_NAME).insertDocument(RawJson.of("{\"_key\":\"abc\"}")).get(); - final DocumentExistsOptions options = new DocumentExistsOptions().ifMatch("no"); - db.collection(COLLECTION_NAME).documentExists("abc", options) - .whenComplete((exists, ex) -> assertThat(exists).isEqualTo(false)) - .get(); - } - - @Test - void documentExistsIfNoneMatch() throws InterruptedException, ExecutionException { - db.collection(COLLECTION_NAME).insertDocument(RawJson.of("{\"_key\":\"abc\"}")).get(); - final DocumentExistsOptions options = new DocumentExistsOptions().ifNoneMatch("no"); - db.collection(COLLECTION_NAME).documentExists("abc", options) - .whenComplete((exists, ex) -> assertThat(exists).isEqualTo(true)) - .get(); - } - - @Test - void documentExistsIfNoneMatchFail() throws InterruptedException, ExecutionException { - final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) - .insertDocument(RawJson.of("{\"_key\":\"abc\"}")).get(); - final DocumentExistsOptions options = new DocumentExistsOptions().ifNoneMatch(createResult.getRev()); - db.collection(COLLECTION_NAME).documentExists("abc", options) - .whenComplete((exists, ex) -> assertThat(exists).isEqualTo(false)) - .get(); - } - - @Test - void insertDocuments() throws InterruptedException, ExecutionException { - final Collection values = new ArrayList<>(); - values.add(new BaseDocument()); - values.add(new BaseDocument()); - values.add(new BaseDocument()); - db.collection(COLLECTION_NAME).insertDocuments(values) - .whenComplete((docs, ex) -> { - assertThat(docs).isNotNull(); - assertThat(docs.getDocuments()).isNotNull(); - assertThat(docs.getDocuments().size()).isEqualTo(3); - assertThat(docs.getErrors()).isNotNull(); - assertThat(docs.getErrors().size()).isEqualTo(0); - }) - .get(); - } - - @Test - void insertDocumentsOne() throws InterruptedException, ExecutionException { - final Collection values = new ArrayList<>(); - values.add(new BaseDocument()); - db.collection(COLLECTION_NAME).insertDocuments(values) - .whenComplete((docs, ex) -> { - assertThat(docs).isNotNull(); - assertThat(docs.getDocuments()).isNotNull(); - assertThat(docs.getDocuments().size()).isEqualTo(1); - assertThat(docs.getErrors()).isNotNull(); - assertThat(docs.getErrors().size()).isEqualTo(0); - }) - .get(); - } - - @Test - void insertDocumentsEmpty() throws InterruptedException, ExecutionException { - final Collection values = new ArrayList<>(); - db.collection(COLLECTION_NAME).insertDocuments(values) - .whenComplete((docs, ex) -> { - assertThat(docs).isNotNull(); - assertThat(docs.getDocuments()).isNotNull(); - assertThat(docs.getDocuments().size()).isEqualTo(0); - assertThat(docs.getErrors()).isNotNull(); - assertThat(docs.getErrors().size()).isEqualTo(0); - }) - .get(); - } - - @Test - void insertDocumentsReturnNew() throws InterruptedException, ExecutionException { - final Collection values = new ArrayList<>(); - values.add(new BaseDocument()); - values.add(new BaseDocument()); - values.add(new BaseDocument()); - final DocumentCreateOptions options = new DocumentCreateOptions().returnNew(true); - db.collection(COLLECTION_NAME).insertDocuments(values, options) - .whenComplete((docs, ex) -> { - assertThat(docs).isNotNull(); - assertThat(docs.getDocuments()).isNotNull(); - assertThat(docs.getDocuments().size()).isEqualTo(3); - assertThat(docs.getErrors()).isNotNull(); - assertThat(docs.getErrors().size()).isEqualTo(0); - for (final DocumentCreateEntity doc : docs.getDocuments()) { - assertThat(doc.getNew()).isNotNull(); - final BaseDocument baseDocument = doc.getNew(); - assertThat(baseDocument.getKey()).isNotNull(); - } - }) - .get(); - } - - @Test - void insertDocumentsFail() throws InterruptedException, ExecutionException { - final Collection values = new ArrayList<>(); - values.add(new BaseDocument("1")); - values.add(new BaseDocument("2")); - values.add(new BaseDocument("2")); - db.collection(COLLECTION_NAME).insertDocuments(values) - .whenComplete((docs, ex) -> { - assertThat(docs).isNotNull(); - assertThat(docs.getDocuments()).isNotNull(); - assertThat(docs.getDocuments().size()).isEqualTo(2); - assertThat(docs.getErrors()).isNotNull(); - assertThat(docs.getErrors().size()).isEqualTo(1); - assertThat(docs.getErrors().iterator().next().getErrorNum()).isEqualTo(1210); - }) - .get(); - } - - @Test - void insertDocumentsRawData() throws ExecutionException, InterruptedException { - final RawData values = RawData.of("[{},{},{}]"); - final MultiDocumentEntity docs = db.collection(COLLECTION_NAME).insertDocuments(values).get(); - assertThat(docs).isNotNull(); - assertThat(docs.getDocuments()).isNotNull(); - assertThat(docs.getDocuments()).hasSize(3); - assertThat(docs.getErrors()).isNotNull(); - assertThat(docs.getErrors()).isEmpty(); - } - - @Test - void insertDocumentsRawDataReturnNew() throws ExecutionException, InterruptedException { - final RawData values = RawData.of("[{\"aaa\":33},{\"aaa\":33},{\"aaa\":33}]"); - final MultiDocumentEntity> docs = - db.collection(COLLECTION_NAME).insertDocuments(values, new DocumentCreateOptions().returnNew(true)).get(); - assertThat(docs).isNotNull(); - assertThat(docs.getDocuments()).isNotNull(); - assertThat(docs.getDocuments()).hasSize(3); - assertThat(docs.getErrors()).isNotNull(); - assertThat(docs.getErrors()).isEmpty(); - - for (final DocumentCreateEntity doc : docs.getDocuments()) { - RawData d = doc.getNew(); - assertThat(d) - .isNotNull() - .isInstanceOf(RawJson.class); - - JsonNode jn = SerdeUtils.INSTANCE.parseJson(((RawJson) d).getValue()); - assertThat(jn.has("aaa")).isTrue(); - assertThat(jn.get("aaa").intValue()).isEqualTo(33); - } - } - - @Test - void importDocuments() throws InterruptedException, ExecutionException { - final Collection values = new ArrayList<>(); - values.add(new BaseDocument()); - values.add(new BaseDocument()); - values.add(new BaseDocument()); - db.collection(COLLECTION_NAME).importDocuments(values) - .whenComplete((docs, ex) -> { - assertThat(docs).isNotNull(); - assertThat(docs.getCreated()).isEqualTo(values.size()); - assertThat(docs.getEmpty()).isEqualTo(0); - assertThat(docs.getErrors()).isEqualTo(0); - assertThat(docs.getIgnored()).isEqualTo(0); - assertThat(docs.getUpdated()).isEqualTo(0); - assertThat(docs.getDetails()).isEmpty(); - }) - .get(); - } - - @Test - void importDocumentsDuplicateDefaultError() throws InterruptedException, ExecutionException { - final Collection values = new ArrayList<>(); - values.add(new BaseDocument("1")); - values.add(new BaseDocument("2")); - values.add(new BaseDocument("2")); - db.collection(COLLECTION_NAME).importDocuments(values) - .whenComplete((docs, ex) -> { - assertThat(docs).isNotNull(); - assertThat(docs.getCreated()).isEqualTo(2); - assertThat(docs.getEmpty()).isEqualTo(0); - assertThat(docs.getErrors()).isEqualTo(1); - assertThat(docs.getIgnored()).isEqualTo(0); - assertThat(docs.getUpdated()).isEqualTo(0); - assertThat(docs.getDetails()).isEmpty(); - }) - .get(); - } - - @Test - void importDocumentsDuplicateError() throws InterruptedException, ExecutionException { - final Collection values = new ArrayList<>(); - values.add(new BaseDocument("1")); - values.add(new BaseDocument("2")); - values.add(new BaseDocument("2")); - db.collection(COLLECTION_NAME).importDocuments(values, -new DocumentImportOptions().onDuplicate(OnDuplicate.error)) - .whenComplete((docs, ex) -> { - assertThat(docs).isNotNull(); - assertThat(docs.getCreated()).isEqualTo(2); - assertThat(docs.getEmpty()).isEqualTo(0); - assertThat(docs.getErrors()).isEqualTo(1); - assertThat(docs.getIgnored()).isEqualTo(0); - assertThat(docs.getUpdated()).isEqualTo(0); - assertThat(docs.getDetails()).isEmpty(); - }) - .get(); - } - - @Test - void importDocumentsDuplicateIgnore() throws InterruptedException, ExecutionException { - final Collection values = new ArrayList<>(); - values.add(new BaseDocument("1")); - values.add(new BaseDocument("2")); - values.add(new BaseDocument("2")); - db.collection(COLLECTION_NAME).importDocuments(values, - new DocumentImportOptions().onDuplicate(OnDuplicate.ignore)) - .whenComplete((docs, ex) -> { - assertThat(docs).isNotNull(); - assertThat(docs.getCreated()).isEqualTo(2); - assertThat(docs.getEmpty()).isEqualTo(0); - assertThat(docs.getErrors()).isEqualTo(0); - assertThat(docs.getIgnored()).isEqualTo(1); - assertThat(docs.getUpdated()).isEqualTo(0); - assertThat(docs.getDetails()).isEmpty(); - }) - .get(); - } - - @Test - void importDocumentsDuplicateReplace() throws InterruptedException, ExecutionException { - final Collection values = new ArrayList<>(); - values.add(new BaseDocument("1")); - values.add(new BaseDocument("2")); - values.add(new BaseDocument("2")); - db.collection(COLLECTION_NAME).importDocuments(values, -new DocumentImportOptions().onDuplicate(OnDuplicate.replace)) - .whenComplete((docs, ex) -> { - assertThat(docs).isNotNull(); - assertThat(docs.getCreated()).isEqualTo(2); - assertThat(docs.getEmpty()).isEqualTo(0); - assertThat(docs.getErrors()).isEqualTo(0); - assertThat(docs.getIgnored()).isEqualTo(0); - assertThat(docs.getUpdated()).isEqualTo(1); - assertThat(docs.getDetails()).isEmpty(); - }) - .get(); - } - - @Test - void importDocumentsDuplicateUpdate() throws InterruptedException, ExecutionException { - final Collection values = new ArrayList<>(); - values.add(new BaseDocument("1")); - values.add(new BaseDocument("2")); - values.add(new BaseDocument("2")); - db.collection(COLLECTION_NAME).importDocuments(values, - new DocumentImportOptions().onDuplicate(OnDuplicate.update)) - .whenComplete((docs, ex) -> { - assertThat(docs).isNotNull(); - assertThat(docs.getCreated()).isEqualTo(2); - assertThat(docs.getEmpty()).isEqualTo(0); - assertThat(docs.getErrors()).isEqualTo(0); - assertThat(docs.getIgnored()).isEqualTo(0); - assertThat(docs.getUpdated()).isEqualTo(1); - assertThat(docs.getDetails()).isEmpty(); - }) - .get(); - } - - @Test - void importDocumentsCompleteFail() throws InterruptedException { - 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)).get(); - fail(); - } catch (ExecutionException e) { - assertThat(e.getCause()).isInstanceOf(ArangoDBException.class); - assertThat(((ArangoDBException) e.getCause()).getErrorNum()).isEqualTo(1210); - } - } - - @Test - void importDocumentsDetails() throws InterruptedException, ExecutionException { - final Collection values = new ArrayList<>(); - values.add(new BaseDocument("1")); - values.add(new BaseDocument("2")); - values.add(new BaseDocument("2")); - db.collection(COLLECTION_NAME).importDocuments(values, new DocumentImportOptions().details(true)) - .whenComplete((docs, ex) -> { - assertThat(docs).isNotNull(); - assertThat(docs.getCreated()).isEqualTo(2); - assertThat(docs.getEmpty()).isEqualTo(0); - assertThat(docs.getErrors()).isEqualTo(1); - assertThat(docs.getIgnored()).isEqualTo(0); - assertThat(docs.getUpdated()).isEqualTo(0); - assertThat(docs.getDetails().size()).isEqualTo(1); - assertThat(docs.getDetails().iterator().next()).contains("unique constraint violated"); - }) - .get(); - } - - @Test - void importDocumentsOverwriteFalse() throws InterruptedException, ExecutionException { - final ArangoCollectionAsync collection = db.collection(COLLECTION_NAME); - collection.insertDocument(new BaseDocument()).get(); - assertThat(collection.count().get().getCount()).isEqualTo(1L); - - final Collection values = new ArrayList<>(); - values.add(new BaseDocument()); - values.add(new BaseDocument()); - collection.importDocuments(values, new DocumentImportOptions().overwrite(false)).get(); - assertThat(collection.count().get().getCount()).isEqualTo(3L); - } - - @Test - void importDocumentsOverwriteTrue() throws InterruptedException, ExecutionException { - final ArangoCollectionAsync collection = db.collection(COLLECTION_NAME); - collection.insertDocument(new BaseDocument()).get(); - assertThat(collection.count().get().getCount()).isEqualTo(1L); - - final Collection values = new ArrayList<>(); - values.add(new BaseDocument()); - values.add(new BaseDocument()); - collection.importDocuments(values, new DocumentImportOptions().overwrite(true)).get(); - assertThat(collection.count().get().getCount()).isEqualTo(2L); - } - - @Test - void importDocumentsFromToPrefix() throws InterruptedException, ExecutionException { - db.createCollection(COLLECTION_NAME + "_edge", new CollectionCreateOptions().type(CollectionType.EDGES)).get(); - final ArangoCollectionAsync collection = db.collection(COLLECTION_NAME + "_edge"); - try { - final Collection values = new ArrayList<>(); - final String[] keys = {"1", "2"}; - for (String s : keys) { - values.add(new BaseEdgeDocument(s, "from", "to")); - } - assertThat(values).hasSize(keys.length); - - final DocumentImportEntity importResult = collection - .importDocuments(values, new DocumentImportOptions().fromPrefix("foo").toPrefix("bar")).get(); - assertThat(importResult).isNotNull(); - assertThat(importResult.getCreated()).isEqualTo(values.size()); - for (String key : keys) { - BaseEdgeDocument doc; - doc = collection.getDocument(key, BaseEdgeDocument.class).get(); - assertThat(doc).isNotNull(); - assertThat(doc.getFrom()).isEqualTo("foo/from"); - assertThat(doc.getTo()).isEqualTo("bar/to"); - } - } finally { - collection.drop().get(); - } - } - - @Test - void importDocumentsJson() throws InterruptedException, ExecutionException { - final String values = "[{\"_key\":\"1\"},{\"_key\":\"2\"}]"; - db.collection(COLLECTION_NAME).importDocuments(RawData.of(values)) - .whenComplete((docs, ex) -> { - assertThat(docs).isNotNull(); - assertThat(docs.getCreated()).isEqualTo(2); - assertThat(docs.getEmpty()).isEqualTo(0); - assertThat(docs.getErrors()).isEqualTo(0); - assertThat(docs.getIgnored()).isEqualTo(0); - assertThat(docs.getUpdated()).isEqualTo(0); - assertThat(docs.getDetails()).isEmpty(); - }) - .get(); - } - - @Test - void importDocumentsJsonDuplicateDefaultError() throws InterruptedException, ExecutionException { - final String values = "[{\"_key\":\"1\"},{\"_key\":\"2\"},{\"_key\":\"2\"}]"; - db.collection(COLLECTION_NAME).importDocuments(RawData.of(values)) - .whenComplete((docs, ex) -> { - assertThat(docs).isNotNull(); - assertThat(docs.getCreated()).isEqualTo(2); - assertThat(docs.getEmpty()).isEqualTo(0); - assertThat(docs.getErrors()).isEqualTo(1); - assertThat(docs.getIgnored()).isEqualTo(0); - assertThat(docs.getUpdated()).isEqualTo(0); - assertThat(docs.getDetails()).isEmpty(); - }) - .get(); - } - - @Test - void importDocumentsJsonDuplicateError() throws InterruptedException, ExecutionException { - final String values = "[{\"_key\":\"1\"},{\"_key\":\"2\"},{\"_key\":\"2\"}]"; - db.collection(COLLECTION_NAME).importDocuments(RawData.of(values), - new DocumentImportOptions().onDuplicate(OnDuplicate.error)) - .whenComplete((docs, ex) -> { - assertThat(docs).isNotNull(); - assertThat(docs.getCreated()).isEqualTo(2); - assertThat(docs.getEmpty()).isEqualTo(0); - assertThat(docs.getErrors()).isEqualTo(1); - assertThat(docs.getIgnored()).isEqualTo(0); - assertThat(docs.getUpdated()).isEqualTo(0); - assertThat(docs.getDetails()).isEmpty(); - }) - .get(); - } - - @Test - void importDocumentsJsonDuplicateIgnore() throws InterruptedException, ExecutionException { - final String values = "[{\"_key\":\"1\"},{\"_key\":\"2\"},{\"_key\":\"2\"}]"; - db.collection(COLLECTION_NAME).importDocuments(RawData.of(values), - new DocumentImportOptions().onDuplicate(OnDuplicate.ignore)) - .whenComplete((docs, ex) -> { - assertThat(docs).isNotNull(); - assertThat(docs.getCreated()).isEqualTo(2); - assertThat(docs.getEmpty()).isEqualTo(0); - assertThat(docs.getErrors()).isEqualTo(0); - assertThat(docs.getIgnored()).isEqualTo(1); - assertThat(docs.getUpdated()).isEqualTo(0); - assertThat(docs.getDetails()).isEmpty(); - }) - .get(); - } - - @Test - void importDocumentsJsonDuplicateReplace() throws InterruptedException, ExecutionException { - final String values = "[{\"_key\":\"1\"},{\"_key\":\"2\"},{\"_key\":\"2\"}]"; - db.collection(COLLECTION_NAME).importDocuments(RawData.of(values), - new DocumentImportOptions().onDuplicate(OnDuplicate.replace)) - .whenComplete((docs, ex) -> { - assertThat(docs).isNotNull(); - assertThat(docs.getCreated()).isEqualTo(2); - assertThat(docs.getEmpty()).isEqualTo(0); - assertThat(docs.getErrors()).isEqualTo(0); - assertThat(docs.getIgnored()).isEqualTo(0); - assertThat(docs.getUpdated()).isEqualTo(1); - assertThat(docs.getDetails()).isEmpty(); - }) - .get(); - } - - @Test - void importDocumentsJsonDuplicateUpdate() throws InterruptedException, ExecutionException { - final String values = "[{\"_key\":\"1\"},{\"_key\":\"2\"},{\"_key\":\"2\"}]"; - db.collection(COLLECTION_NAME).importDocuments(RawData.of(values), - new DocumentImportOptions().onDuplicate(OnDuplicate.update)) - .whenComplete((docs, ex) -> { - assertThat(docs).isNotNull(); - assertThat(docs.getCreated()).isEqualTo(2); - assertThat(docs.getEmpty()).isEqualTo(0); - assertThat(docs.getErrors()).isEqualTo(0); - assertThat(docs.getIgnored()).isEqualTo(0); - assertThat(docs.getUpdated()).isEqualTo(1); - assertThat(docs.getDetails()).isEmpty(); - }) - .get(); - } - - @Test - void importDocumentsJsonCompleteFail() throws InterruptedException { - final String values = "[{\"_key\":\"1\"},{\"_key\":\"2\"},{\"_key\":\"2\"}]"; - try { - db.collection(COLLECTION_NAME).importDocuments(RawData.of(values), - new DocumentImportOptions().complete(true)).get(); - fail(); - } catch (ExecutionException e) { - assertThat(e.getCause()).isInstanceOf(ArangoDBException.class); - assertThat(((ArangoDBException) e.getCause()).getErrorNum()).isEqualTo(1210); - } - } - - @Test - void importDocumentsJsonDetails() throws InterruptedException, ExecutionException { - final String values = "[{\"_key\":\"1\"},{\"_key\":\"2\"},{\"_key\":\"2\"}]"; - db.collection(COLLECTION_NAME).importDocuments(RawData.of(values), new DocumentImportOptions().details(true)) - .whenComplete((docs, ex) -> { - assertThat(docs).isNotNull(); - assertThat(docs.getCreated()).isEqualTo(2); - assertThat(docs.getEmpty()).isEqualTo(0); - assertThat(docs.getErrors()).isEqualTo(1); - assertThat(docs.getIgnored()).isEqualTo(0); - assertThat(docs.getUpdated()).isEqualTo(0); - assertThat(docs.getDetails().size()).isEqualTo(1); - assertThat(docs.getDetails().iterator().next()).contains("unique constraint violated"); - }) - .get(); - } - - @Test - void importDocumentsJsonOverwriteFalse() throws InterruptedException, ExecutionException { - final ArangoCollectionAsync collection = db.collection(COLLECTION_NAME); - collection.insertDocument(new BaseDocument()).get(); - assertThat(collection.count().get().getCount()).isEqualTo(1L); - - final String values = "[{\"_key\":\"1\"},{\"_key\":\"2\"}]"; - collection.importDocuments(RawData.of(values), new DocumentImportOptions().overwrite(false)).get(); - assertThat(collection.count().get().getCount()).isEqualTo(3L); - } - - @Test - void importDocumentsJsonOverwriteTrue() throws InterruptedException, ExecutionException { - final ArangoCollectionAsync collection = db.collection(COLLECTION_NAME); - collection.insertDocument(new BaseDocument()).get(); - assertThat(collection.count().get().getCount()).isEqualTo(1L); - - final String values = "[{\"_key\":\"1\"},{\"_key\":\"2\"}]"; - collection.importDocuments(RawData.of(values), new DocumentImportOptions().overwrite(true)).get(); - assertThat(collection.count().get().getCount()).isEqualTo(2L); - } - - @Test - void importDocumentsJsonFromToPrefix() throws InterruptedException, ExecutionException { - db.createCollection(COLLECTION_NAME + "_edge", new CollectionCreateOptions().type(CollectionType.EDGES)).get(); - final ArangoCollectionAsync 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(RawData.of(values), - new DocumentImportOptions().fromPrefix("foo").toPrefix("bar")).get(); - assertThat(importResult).isNotNull(); - assertThat(importResult.getCreated()).isEqualTo(2); - for (String key : keys) { - BaseEdgeDocument doc; - doc = collection.getDocument(key, BaseEdgeDocument.class).get(); - assertThat(doc).isNotNull(); - assertThat(doc.getFrom()).isEqualTo("foo/from"); - assertThat(doc.getTo()).isEqualTo("bar/to"); - } - } finally { - collection.drop().get(); - } - } - - @Test - void deleteDocumentsByKey() throws InterruptedException, ExecutionException { - final Collection values = new ArrayList<>(); - { - final BaseDocument e = new BaseDocument(UUID.randomUUID().toString()); - e.setKey("1"); - values.add(e); - } - { - final BaseDocument e = new BaseDocument(UUID.randomUUID().toString()); - e.setKey("2"); - values.add(e); - } - db.collection(COLLECTION_NAME).insertDocuments(values).get(); - final Collection keys = new ArrayList<>(); - keys.add("1"); - keys.add("2"); - db.collection(COLLECTION_NAME).deleteDocuments(keys) - .whenComplete((deleteResult, ex) -> { - assertThat(deleteResult).isNotNull(); - assertThat(deleteResult.getDocuments().size()).isEqualTo(2); - for (final DocumentDeleteEntity i : deleteResult.getDocuments()) { - assertThat(i.getKey()).isIn("1", "2"); - } - assertThat(deleteResult.getErrors().size()).isEqualTo(0); - }) - .get(); - } - - @Test - void deleteDocumentsByDocuments() throws InterruptedException, ExecutionException { - final Collection values = new ArrayList<>(); - { - final BaseDocument e = new BaseDocument(UUID.randomUUID().toString()); - e.setKey("1"); - values.add(e); - } - { - final BaseDocument e = new BaseDocument(UUID.randomUUID().toString()); - e.setKey("2"); - values.add(e); - } - db.collection(COLLECTION_NAME).insertDocuments(values).get(); - db.collection(COLLECTION_NAME).deleteDocuments(values) - .whenComplete((deleteResult, ex) -> { - assertThat(deleteResult).isNotNull(); - assertThat(deleteResult.getDocuments().size()).isEqualTo(2); - for (final DocumentDeleteEntity i : deleteResult.getDocuments()) { - assertThat(i.getKey()).isIn("1", "2"); - } - assertThat(deleteResult.getErrors().size()).isEqualTo(0); - }) - .get(); - } - - @Test - void deleteDocumentsByKeyOne() throws InterruptedException, ExecutionException { - final Collection values = new ArrayList<>(); - { - final BaseDocument e = new BaseDocument(UUID.randomUUID().toString()); - e.setKey("1"); - values.add(e); - } - db.collection(COLLECTION_NAME).insertDocuments(values).get(); - final Collection keys = new ArrayList<>(); - keys.add("1"); - db.collection(COLLECTION_NAME).deleteDocuments(keys) - .whenComplete((deleteResult, ex) -> { - assertThat(deleteResult).isNotNull(); - assertThat(deleteResult.getDocuments().size()).isEqualTo(1); - for (final DocumentDeleteEntity i : deleteResult.getDocuments()) { - assertThat(i.getKey()).isEqualTo("1"); - } - assertThat(deleteResult.getErrors().size()).isEqualTo(0); - }) - .get(); - } - - @Test - void deleteDocumentsByDocumentOne() throws InterruptedException, ExecutionException { - final Collection values = new ArrayList<>(); - { - final BaseDocument e = new BaseDocument(UUID.randomUUID().toString()); - e.setKey("1"); - values.add(e); - } - db.collection(COLLECTION_NAME).insertDocuments(values).get(); - db.collection(COLLECTION_NAME).deleteDocuments(values) - .whenComplete((deleteResult, ex) -> { - assertThat(deleteResult).isNotNull(); - assertThat(deleteResult.getDocuments().size()).isEqualTo(1); - for (final DocumentDeleteEntity i : deleteResult.getDocuments()) { - assertThat(i.getKey()).isEqualTo("1"); - } - assertThat(deleteResult.getErrors().size()).isEqualTo(0); - }) - .get(); - } - - @Test - void deleteDocumentsEmpty() throws InterruptedException, ExecutionException { - final Collection values = new ArrayList<>(); - db.collection(COLLECTION_NAME).insertDocuments(values).get(); - final Collection keys = new ArrayList<>(); - db.collection(COLLECTION_NAME).deleteDocuments(keys) - .whenComplete((deleteResult, ex) -> { - assertThat(deleteResult).isNotNull(); - assertThat(deleteResult.getDocuments().size()).isEqualTo(0); - assertThat(deleteResult.getErrors().size()).isEqualTo(0); - }) - .get(); - } - - @Test - void deleteDocumentsByKeyNotExisting() throws InterruptedException, ExecutionException { - final Collection values = new ArrayList<>(); - db.collection(COLLECTION_NAME).insertDocuments(values).get(); - final Collection keys = new ArrayList<>(); - keys.add("1"); - keys.add("2"); - db.collection(COLLECTION_NAME).deleteDocuments(keys) - .whenComplete((deleteResult, ex) -> { - assertThat(deleteResult).isNotNull(); - assertThat(deleteResult.getDocuments().size()).isEqualTo(0); - assertThat(deleteResult.getErrors().size()).isEqualTo(2); - }) - .get(); - } - - @Test - void deleteDocumentsByDocumentsNotExisting() throws InterruptedException, ExecutionException { - final Collection values = new ArrayList<>(); - { - final BaseDocument e = new BaseDocument(UUID.randomUUID().toString()); - e.setKey("1"); - values.add(e); - } - { - final BaseDocument e = new BaseDocument(UUID.randomUUID().toString()); - e.setKey("2"); - values.add(e); - } - db.collection(COLLECTION_NAME).deleteDocuments(values) - .whenComplete((deleteResult, ex) -> { - assertThat(deleteResult).isNotNull(); - assertThat(deleteResult.getDocuments().size()).isEqualTo(0); - assertThat(deleteResult.getErrors().size()).isEqualTo(2); - }) - .get(); - } - - @Test - void deleteDocumentsRawDataByKeyReturnOld() throws ExecutionException, InterruptedException { - ArangoCollectionAsync collection = db.collection(COLLECTION_NAME); - final RawData values = RawData.of("[{\"_key\":\"1\"},{\"_key\":\"2\"}]"); - collection.insertDocuments(values).get(); - final RawData keys = RawData.of("[\"1\",\"2\"]"); - MultiDocumentEntity> deleteResult = collection.deleteDocuments(keys, - new DocumentDeleteOptions().returnOld(true)).get(); - assertThat(deleteResult).isNotNull(); - assertThat(deleteResult.getDocuments()).hasSize(2); - for (final DocumentDeleteEntity i : deleteResult.getDocuments()) { - assertThat(i.getKey()).isIn("1", "2"); - assertThat(i.getOld()).isNotNull().isInstanceOf(RawJson.class); - JsonNode jn = SerdeUtils.INSTANCE.parseJson(((RawJson) i.getOld()).getValue()); - assertThat(jn.get("_key").asText()).isEqualTo(i.getKey()); - } - assertThat(deleteResult.getErrors()).isEmpty(); - } - - @Test - void updateDocuments() throws InterruptedException, ExecutionException { - final Collection values = new ArrayList<>(); - { - final BaseDocument e = new BaseDocument(UUID.randomUUID().toString()); - e.setKey("1"); - values.add(e); - } - { - final BaseDocument e = new BaseDocument(UUID.randomUUID().toString()); - e.setKey("2"); - values.add(e); - } - db.collection(COLLECTION_NAME).insertDocuments(values).get(); - final Collection updatedValues = new ArrayList<>(); - for (final BaseDocument i : values) { - i.addAttribute("a", "test"); - updatedValues.add(i); - } - db.collection(COLLECTION_NAME).updateDocuments(updatedValues) - .whenComplete((updateResult, ex) -> { - assertThat(updateResult.getDocuments().size()).isEqualTo(2); - assertThat(updateResult.getErrors().size()).isEqualTo(0); - }) - .get(); - } - - @Test - void updateDocumentsWithDifferentReturnType() throws ExecutionException, InterruptedException { - ArangoCollectionAsync collection = db.collection(COLLECTION_NAME); - List keys = - IntStream.range(0, 3).mapToObj(it -> "key-" + UUID.randomUUID()).collect(Collectors.toList()); - List docs = keys.stream() - .map(BaseDocument::new) - .peek(it -> it.addAttribute("a", "test")) - .collect(Collectors.toList()); - - collection.insertDocuments(docs).get(); - - List> modifiedDocs = docs.stream() - .peek(it -> it.addAttribute("b", "test")) - .map(it -> { - Map map = new HashMap<>(); - map.put("_key", it.getKey()); - map.put("a", it.getAttribute("a")); - map.put("b", it.getAttribute("b")); - return map; - }) - .collect(Collectors.toList()); - - final MultiDocumentEntity> updateResult = collection - .updateDocuments(modifiedDocs, new DocumentUpdateOptions().returnNew(true), BaseDocument.class).get(); - assertThat(updateResult.getDocuments()).hasSize(3); - assertThat(updateResult.getErrors()).isEmpty(); - assertThat(updateResult.getDocuments().stream().map(DocumentUpdateEntity::getNew) - .allMatch(it -> it.getAttribute("a").equals("test") && it.getAttribute("b").equals("test"))) - .isTrue(); - } - - @Test - void updateDocumentsOne() throws InterruptedException, ExecutionException { - final Collection values = new ArrayList<>(); - { - final BaseDocument e = new BaseDocument(UUID.randomUUID().toString()); - e.setKey("1"); - values.add(e); - } - db.collection(COLLECTION_NAME).insertDocuments(values).get(); - final Collection updatedValues = new ArrayList<>(); - final BaseDocument first = values.iterator().next(); - first.addAttribute("a", "test"); - updatedValues.add(first); - db.collection(COLLECTION_NAME).updateDocuments(updatedValues) - .whenComplete((updateResult, ex) -> { - assertThat(updateResult.getDocuments().size()).isEqualTo(1); - assertThat(updateResult.getErrors().size()).isEqualTo(0); - }) - .get(); - } - - @Test - void updateDocumentsEmpty() throws InterruptedException, ExecutionException { - final Collection values = new ArrayList<>(); - db.collection(COLLECTION_NAME).updateDocuments(values) - .whenComplete((updateResult, ex) -> { - assertThat(updateResult.getDocuments().size()).isEqualTo(0); - assertThat(updateResult.getErrors().size()).isEqualTo(0); - }) - .get(); - } - - @Test - void updateDocumentsWithoutKey() throws InterruptedException, ExecutionException { - final Collection values = new ArrayList<>(); - { - values.add(new BaseDocument("1")); - } - db.collection(COLLECTION_NAME).insertDocuments(values).get(); - final Collection updatedValues = new ArrayList<>(); - for (final BaseDocument i : values) { - i.addAttribute("a", "test"); - updatedValues.add(i); - } - updatedValues.add(new BaseDocument()); - db.collection(COLLECTION_NAME).updateDocuments(updatedValues) - .whenComplete((updateResult, ex) -> { - assertThat(updateResult.getDocuments().size()).isEqualTo(1); - assertThat(updateResult.getErrors().size()).isEqualTo(1); - }) - .get(); - } - - @Test - void updateDocumentsRawData() throws ExecutionException, InterruptedException { - ArangoCollectionAsync collection = db.collection(COLLECTION_NAME); - final RawData values = RawData.of("[{\"_key\":\"1\"}, {\"_key\":\"2\"}]"); - collection.insertDocuments(values).get(); - - final RawData updatedValues = RawData.of("[{\"_key\":\"1\", \"foo\":\"bar\"}, {\"_key\":\"2\", " + - "\"foo\":\"bar\"}]"); - final MultiDocumentEntity updateResult = collection.updateDocuments(updatedValues).get(); - assertThat(updateResult.getDocuments()).hasSize(2); - assertThat(updateResult.getErrors()).isEmpty(); - } - - @Test - void updateDocumentsRawDataReturnNew() throws ExecutionException, InterruptedException { - ArangoCollectionAsync collection = db.collection(COLLECTION_NAME); - final RawData values = RawData.of("[{\"_key\":\"1\"}, {\"_key\":\"2\"}]"); - collection.insertDocuments(values).get(); - - final RawData updatedValues = RawData.of("[{\"_key\":\"1\", \"foo\":\"bar\"}, {\"_key\":\"2\", " + -"\"foo\":\"bar\"}]"); - MultiDocumentEntity> updateResult = - collection.updateDocuments(updatedValues, new DocumentUpdateOptions().returnNew(true)).get(); - assertThat(updateResult.getDocuments()).hasSize(2); - assertThat(updateResult.getErrors()).isEmpty(); - for (DocumentUpdateEntity doc : updateResult.getDocuments()) { - RawData d = doc.getNew(); - assertThat(d) - .isNotNull() - .isInstanceOf(RawJson.class); - - JsonNode jn = SerdeUtils.INSTANCE.parseJson(((RawJson) d).getValue()); - assertThat(jn.has("foo")).isTrue(); - assertThat(jn.get("foo").textValue()).isEqualTo("bar"); - } - } - - @Test - void replaceDocuments() throws InterruptedException, ExecutionException { - final Collection values = new ArrayList<>(); - { - values.add(new BaseDocument("1")); - values.add(new BaseDocument("2")); - } - db.collection(COLLECTION_NAME).insertDocuments(values).get(); - final Collection updatedValues = new ArrayList<>(); - for (final BaseDocument i : values) { - i.addAttribute("a", "test"); - updatedValues.add(i); - } - db.collection(COLLECTION_NAME).replaceDocuments(updatedValues) - .whenComplete((updateResult, ex) -> { - assertThat(updateResult.getDocuments().size()).isEqualTo(2); - assertThat(updateResult.getErrors().size()).isEqualTo(0); - }) - .get(); - } - - @Test - void replaceDocumentsOne() throws InterruptedException, ExecutionException { - final Collection values = new ArrayList<>(); - { - final BaseDocument e = new BaseDocument(UUID.randomUUID().toString()); - e.setKey("1"); - values.add(e); - } - db.collection(COLLECTION_NAME).insertDocuments(values).get(); - final Collection updatedValues = new ArrayList<>(); - final BaseDocument first = values.iterator().next(); - first.addAttribute("a", "test"); - updatedValues.add(first); - db.collection(COLLECTION_NAME).updateDocuments(updatedValues) - .whenComplete((updateResult, ex) -> { - assertThat(updateResult.getDocuments().size()).isEqualTo(1); - assertThat(updateResult.getErrors().size()).isEqualTo(0); - }) - .get(); - } - - @Test - void replaceDocumentsEmpty() throws InterruptedException, ExecutionException { - final Collection values = new ArrayList<>(); - db.collection(COLLECTION_NAME).updateDocuments(values) - .whenComplete((updateResult, ex) -> { - assertThat(updateResult.getDocuments().size()).isEqualTo(0); - assertThat(updateResult.getErrors().size()).isEqualTo(0); - }) - .get(); - } - - @Test - void replaceDocumentsWithoutKey() throws InterruptedException, ExecutionException { - final Collection values = new ArrayList<>(); - { - values.add(new BaseDocument("1")); - } - db.collection(COLLECTION_NAME).insertDocuments(values).get(); - final Collection updatedValues = new ArrayList<>(); - for (final BaseDocument i : values) { - i.addAttribute("a", "test"); - updatedValues.add(i); - } - updatedValues.add(new BaseDocument()); - db.collection(COLLECTION_NAME).updateDocuments(updatedValues) - .whenComplete((updateResult, ex) -> { - assertThat(updateResult.getDocuments().size()).isEqualTo(1); - assertThat(updateResult.getErrors().size()).isEqualTo(1); - }) - .get(); - } - - @Test - void replaceDocumentsRawData() throws ExecutionException, InterruptedException { - ArangoCollectionAsync collection = db.collection(COLLECTION_NAME); - - final RawData values = RawData.of("[{\"_key\":\"1\"}, {\"_key\":\"2\"}]"); - collection.insertDocuments(values).get(); - - final RawData updatedValues = RawData.of("[{\"_key\":\"1\", \"foo\":\"bar\"}, {\"_key\":\"2\", " + -"\"foo\":\"bar\"}]"); - final MultiDocumentEntity updateResult = collection.replaceDocuments(updatedValues).get(); - assertThat(updateResult.getDocuments()).hasSize(2); - assertThat(updateResult.getErrors()).isEmpty(); - } - - @Test - void replaceDocumentsRawDataReturnNew() throws ExecutionException, InterruptedException { - ArangoCollectionAsync collection = db.collection(COLLECTION_NAME); - - final RawData values = RawData.of("[{\"_key\":\"1\"}, {\"_key\":\"2\"}]"); - collection.insertDocuments(values).get(); - - final RawData updatedValues = RawData.of("[{\"_key\":\"1\", \"foo\":\"bar\"}, {\"_key\":\"2\", " + - "\"foo\":\"bar\"}]"); - MultiDocumentEntity> updateResult = - collection.replaceDocuments(updatedValues, new DocumentReplaceOptions().returnNew(true)).get(); - assertThat(updateResult.getDocuments()).hasSize(2); - assertThat(updateResult.getErrors()).isEmpty(); - for (DocumentUpdateEntity doc : updateResult.getDocuments()) { - RawData d = doc.getNew(); - assertThat(d) - .isNotNull() - .isInstanceOf(RawJson.class); - - JsonNode jn = SerdeUtils.INSTANCE.parseJson(((RawJson) d).getValue()); - assertThat(jn.has("foo")).isTrue(); - assertThat(jn.get("foo").textValue()).isEqualTo("bar"); - } - } - - @Test - void getInfo() throws InterruptedException, ExecutionException { - db.collection(COLLECTION_NAME).getInfo() - .whenComplete((result, ex) -> assertThat(result.getName()).isEqualTo(COLLECTION_NAME)) - .get(); - } - - @Test - void getPropeties() throws InterruptedException, ExecutionException { - db.collection(COLLECTION_NAME).getProperties() - .whenComplete((result, ex) -> { - assertThat(result.getName()).isEqualTo(COLLECTION_NAME); - assertThat(result.getCount()).isNull(); - }) - .get(); - } - - @Test - void changeProperties() throws InterruptedException, ExecutionException { - final String collection = COLLECTION_NAME + "_prop"; - try { - db.createCollection(collection).get(); - final CollectionPropertiesEntity properties = db.collection(collection).getProperties().get(); - assertThat(properties.getWaitForSync()).isNotNull(); - final CollectionPropertiesOptions options = new CollectionPropertiesOptions(); - options.waitForSync(!properties.getWaitForSync()); - db.collection(collection).changeProperties(options) - .whenComplete((changedProperties, ex) -> { - assertThat(changedProperties.getWaitForSync()).isNotNull(); - assertThat(changedProperties.getWaitForSync()).isNotEqualTo(properties.getWaitForSync()); - }) - .get(); - } finally { - db.collection(collection).drop().get(); - } - } - - @Test - void rename() throws InterruptedException, ExecutionException { - assumeTrue(isSingleServer()); - db.collection(COLLECTION_NAME).rename(COLLECTION_NAME + "1") - .whenComplete((result, ex) -> { - assertThat(result).isNotNull(); - assertThat(result.getName()).isEqualTo(COLLECTION_NAME + "1"); - }) - .get(); - final CollectionEntity info = db.collection(COLLECTION_NAME + "1").getInfo().get(); - assertThat(info.getName()).isEqualTo(COLLECTION_NAME + "1"); - try { - db.collection(COLLECTION_NAME).getInfo().get(); - fail(); - } catch (final ExecutionException e) { - assertThat(e.getCause()).isInstanceOf(ArangoDBException.class); - } - db.collection(COLLECTION_NAME + "1").rename(COLLECTION_NAME).get(); - } - - @Test - void responsibleShard() throws ExecutionException, InterruptedException { - assumeTrue(isCluster()); - assumeTrue(isAtLeastVersion(3, 5)); - ShardEntity shard = db.collection(COLLECTION_NAME).getResponsibleShard(new BaseDocument("testKey")).get(); - assertThat(shard).isNotNull(); - assertThat(shard.getShardId()).isNotNull(); - } - - @Test - void getRevision() throws InterruptedException, ExecutionException { - db.collection(COLLECTION_NAME).getRevision() - .whenComplete((result, ex) -> { - assertThat(result).isNotNull(); - assertThat(result.getName()).isEqualTo(COLLECTION_NAME); - assertThat(result.getRevision()).isNotNull(); - }) - .get(); - } - - @Test - void grantAccessRW() throws InterruptedException, ExecutionException { - try { - arangoDB.createUser("user1", "1234", null).get(); - db.collection(COLLECTION_NAME).grantAccess("user1", Permissions.RW).get(); - } finally { - arangoDB.deleteUser("user1").get(); - } - } - - @Test - void grantAccessRO() throws InterruptedException, ExecutionException { - try { - arangoDB.createUser("user1", "1234", null).get(); - db.collection(COLLECTION_NAME).grantAccess("user1", Permissions.RO).get(); - } finally { - arangoDB.deleteUser("user1").get(); - } - } - - @Test - void grantAccessNONE() throws InterruptedException, ExecutionException { - try { - arangoDB.createUser("user1", "1234", null).get(); - db.collection(COLLECTION_NAME).grantAccess("user1", Permissions.NONE).get(); - } finally { - arangoDB.deleteUser("user1").get(); - } - } - - @Test - void grantAccessUserNotFound() { - Throwable thrown = - catchThrowable(() -> db.collection(COLLECTION_NAME).grantAccess("user1", Permissions.RW).get()); - assertThat(thrown).isInstanceOf(ExecutionException.class); - } - - @Test - void revokeAccess() throws InterruptedException, ExecutionException { - try { - arangoDB.createUser("user1", "1234", null).get(); - db.collection(COLLECTION_NAME).grantAccess("user1", Permissions.NONE).get(); - } finally { - arangoDB.deleteUser("user1").get(); - } - } - - @Test - void revokeAccessUserNotFound() { - Throwable thrown = - catchThrowable(() -> db.collection(COLLECTION_NAME).grantAccess("user1", Permissions.NONE).get()); - assertThat(thrown).isInstanceOf(ExecutionException.class); - } - - @Test - void resetAccess() throws InterruptedException, ExecutionException { - try { - arangoDB.createUser("user1", "1234", null).get(); - db.collection(COLLECTION_NAME).resetAccess("user1").get(); - } finally { - arangoDB.deleteUser("user1").get(); - } - } - - @Test - void resetAccessUserNotFound() { - Throwable thrown = catchThrowable(() -> db.collection(COLLECTION_NAME).resetAccess("user1").get()); - assertThat(thrown).isInstanceOf(ExecutionException.class); - } - - @Test - void getPermissions() throws InterruptedException, ExecutionException { - assertThat(db.collection(COLLECTION_NAME).getPermissions("root").get()).isEqualTo(Permissions.RW); - } - - @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, property = "type") - public interface Animal { - String getKey(); - - String getName(); - } - - public static class Dog implements Animal { - - @Key - private String key; - private String name; - - public Dog() { - } - - public Dog(String key, String name) { - this.key = key; - this.name = name; - } - - @Override - public String getKey() { - return key; - } - - public void setKey(String key) { - this.key = key; - } - - @Override - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - } - - public static class Cat implements Animal { - @Key - private String key; - private String name; - - public Cat() { - } - - public Cat(String key, String name) { - this.key = key; - this.name = name; - } - - @Override - public String getKey() { - return key; - } - - public void setKey(String key) { - this.key = key; - } - - @Override - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - } -} diff --git a/driver/src/test/java/com/arangodb/async/ArangoDBTest.java b/driver/src/test/java/com/arangodb/async/ArangoDBTest.java deleted file mode 100644 index 2a76db54c..000000000 --- a/driver/src/test/java/com/arangodb/async/ArangoDBTest.java +++ /dev/null @@ -1,566 +0,0 @@ -/* - * DISCLAIMER - * - * Copyright 2016 ArangoDB GmbH, Cologne, Germany - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Copyright holder is ArangoDB GmbH, Cologne, Germany - */ - -package com.arangodb.async; - -import com.arangodb.*; -import com.arangodb.config.ConfigUtils; -import com.arangodb.entity.*; -import com.arangodb.internal.serde.SerdeUtils; -import com.arangodb.model.*; -import com.arangodb.util.RawJson; -import com.arangodb.util.TestUtils; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.Timeout; - -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutionException; -import java.util.stream.Collectors; -import java.util.stream.IntStream; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.fail; -import static org.junit.jupiter.api.Assumptions.assumeTrue; - -/** - * @author Mark Vollmary - * @author Michele Rastelli - */ -class ArangoDBTest { - - private static final String ROOT = "root"; - private static final String USER = "mit dem mund"; - private static final String PW = "machts der hund"; - private static Boolean extendedNames; - - private final ArangoDBAsync arangoDB = new ArangoDBAsync.Builder() - .loadProperties(ConfigUtils.loadConfig()) - .build(); - private final ArangoDB arangoDBSync = new ArangoDB.Builder() - .loadProperties(ConfigUtils.loadConfig()) - .build(); - - private boolean isEnterprise() { - return arangoDBSync.getVersion().getLicense() == License.ENTERPRISE; - } - - private boolean isCluster() { - return arangoDBSync.getRole() == ServerRole.COORDINATOR; - } - - private boolean isAtLeastVersion(final int major, final int minor) { - return com.arangodb.util.TestUtils.isAtLeastVersion(arangoDBSync.getVersion().getVersion(), major, minor, 0); - } - - private boolean isLessThanVersion(final int major, final int minor) { - return com.arangodb.util.TestUtils.isLessThanVersion(arangoDBSync.getVersion().getVersion(), major, minor, 0); - } - - private boolean supportsExtendedNames() { - if (extendedNames == null) { - try { - ArangoDatabase testDb = arangoDBSync.db(DbName.of("test-" + TestUtils.generateRandomDbName(20, true))); - testDb.create(); - extendedNames = true; - testDb.drop(); - } catch (ArangoDBException e) { - extendedNames = false; - } - } - return extendedNames; - } - - @Test - void getVersion() throws InterruptedException, ExecutionException { - arangoDB.getVersion() - .whenComplete((version, ex) -> { - assertThat(version).isNotNull(); - assertThat(version.getServer()).isNotNull(); - assertThat(version.getVersion()).isNotNull(); - }) - .get(); - } - - @Test - @Timeout(2) - void nestedGetVersion() { - for (int i = 0; i < 100; i++) { - try { - arangoDB.getVersion() - .whenComplete((v1, ex1) -> { - assertThat(v1).isNotNull(); - assertThat(v1.getServer()).isNotNull(); - assertThat(v1.getVersion()).isNotNull(); - try { - arangoDB.getVersion() - .whenComplete((v2, ex2) -> { - assertThat(v2).isNotNull(); - assertThat(v2.getServer()).isNotNull(); - assertThat(v2.getVersion()).isNotNull(); - try { - arangoDB.getVersion() - .whenComplete((v3, ex3) -> { - assertThat(v3).isNotNull(); - assertThat(v3.getServer()).isNotNull(); - assertThat(v3.getVersion()).isNotNull(); - }) - .get(); - } catch (InterruptedException | ExecutionException e) { - e.printStackTrace(); - fail(); - } - }) - .get(); - } catch (InterruptedException | ExecutionException e) { - e.printStackTrace(); - fail(); - } - }) - .get(); - } catch (InterruptedException | ExecutionException e) { - e.printStackTrace(); - fail(); - } - } - } - - @Test - void createDatabase() throws InterruptedException, ExecutionException { - arangoDB.createDatabase(BaseTest.TEST_DB) - .whenComplete((result, ex) -> assertThat(result).isEqualTo(true)) - .get(); - arangoDB.db(BaseTest.TEST_DB).drop().get(); - } - - @Test - void createDatabaseWithOptions() throws ExecutionException, InterruptedException { - assumeTrue(isCluster()); - assumeTrue(isAtLeastVersion(3, 6)); - - final DbName dbName = DbName.of("testDB-" + TestUtils.generateRandomDbName(20, supportsExtendedNames())); - final Boolean resultCreate = arangoDB.createDatabase(new DBCreateOptions() - .name(dbName) - .options(new DatabaseOptions() - .writeConcern(2) - .replicationFactor(2) - .sharding("") - ) - ).get(); - assertThat(resultCreate).isTrue(); - - DatabaseEntity info = arangoDB.db(dbName).getInfo().get(); - assertThat(info.getReplicationFactor().getValue()).isEqualTo(2); - assertThat(info.getWriteConcern()).isEqualTo(2); - assertThat(info.getSharding()).isEmpty(); - - final Boolean resultDelete = arangoDB.db(dbName).drop().get(); - assertThat(resultDelete).isTrue(); - } - - @Test - void createDatabaseWithOptionsSatellite() throws ExecutionException, InterruptedException { - assumeTrue(isCluster()); - assumeTrue(isEnterprise()); - assumeTrue(isAtLeastVersion(3, 6)); - - final DbName dbName = DbName.of("testDB-" + TestUtils.generateRandomDbName(20, supportsExtendedNames())); - final Boolean resultCreate = arangoDB.createDatabase(new DBCreateOptions() - .name(dbName) - .options(new DatabaseOptions() - .writeConcern(2) - .replicationFactor(ReplicationFactor.ofSatellite()) - .sharding("") - ) - ).get(); - assertThat(resultCreate).isTrue(); - - DatabaseEntity info = arangoDB.db(dbName).getInfo().get(); - assertThat(info.getReplicationFactor()).isEqualTo(ReplicationFactor.ofSatellite()); - assertThat(info.getWriteConcern()).isEqualTo(2); - assertThat(info.getSharding()).isEmpty(); - - final Boolean resultDelete = arangoDB.db(dbName).drop().get(); - assertThat(resultDelete).isTrue(); - } - - @Test - void deleteDatabase() throws InterruptedException, ExecutionException { - final Boolean resultCreate = arangoDB.createDatabase(BaseTest.TEST_DB).get(); - assertThat(resultCreate).isTrue(); - arangoDB.db(BaseTest.TEST_DB).drop() - .whenComplete((resultDelete, ex) -> assertThat(resultDelete).isEqualTo(true)) - .get(); - } - - @Test - void getDatabases() throws InterruptedException, ExecutionException { - Collection dbs = arangoDB.getDatabases().get(); - assertThat(dbs).isNotNull(); - assertThat(dbs).isNotEmpty(); - final int dbCount = dbs.size(); - assertThat(dbs).contains("_system"); - arangoDB.createDatabase(BaseTest.TEST_DB).get(); - dbs = arangoDB.getDatabases().get(); - assertThat(dbs).hasSizeGreaterThan(dbCount); - assertThat(dbs).contains("_system"); - assertThat(dbs).contains(BaseTest.TEST_DB.get()); - arangoDB.db(BaseTest.TEST_DB).drop().get(); - } - - @Test - void getAccessibleDatabases() throws InterruptedException, ExecutionException { - arangoDB.getAccessibleDatabases() - .whenComplete((dbs, ex) -> { - assertThat(dbs).isNotNull(); - assertThat(dbs).isNotEmpty(); - assertThat(dbs).contains("_system"); - }) - .get(); - } - - @Test - void getAccessibleDatabasesFor() throws InterruptedException, ExecutionException { - arangoDB.getAccessibleDatabasesFor("root") - .whenComplete((dbs, ex) -> { - assertThat(dbs).isNotNull(); - assertThat(dbs).isNotNull(); - assertThat(dbs).isNotEmpty(); - assertThat(dbs).contains("_system"); - }) - .get(); - } - - @Test - void createUser() throws InterruptedException, ExecutionException { - try { - arangoDB.createUser(USER, PW, null) - .whenComplete((result, ex) -> { - assertThat(result).isNotNull(); - assertThat(result.getUser()).isEqualTo(USER); - }) - .get(); - } finally { - arangoDB.deleteUser(USER).get(); - } - } - - @Test - void deleteUser() throws InterruptedException, ExecutionException { - arangoDB.createUser(USER, PW, null).get(); - arangoDB.deleteUser(USER).get(); - } - - @Test - void getUserRoot() throws InterruptedException, ExecutionException { - arangoDB.getUser(ROOT) - .whenComplete((user, ex) -> { - assertThat(user).isNotNull(); - assertThat(user.getUser()).isEqualTo(ROOT); - }) - .get(); - } - - @Test - void getUser() throws InterruptedException, ExecutionException { - try { - arangoDB.createUser(USER, PW, null).get(); - arangoDB.getUser(USER) - .whenComplete((user, ex) -> assertThat(user.getUser()).isEqualTo(USER)) - .get(); - } finally { - arangoDB.deleteUser(USER).get(); - } - - } - - @Test - void getUsersOnlyRoot() throws InterruptedException, ExecutionException { - arangoDB.getUsers() - .whenComplete((users, ex) -> { - assertThat(users).isNotNull(); - assertThat(users).isNotEmpty(); - }) - .get(); - } - - @Test - void getUsers() throws InterruptedException, ExecutionException { - try { - arangoDB.createUser(USER, PW, null).get(); - arangoDB.getUsers() - .whenComplete((users, ex) -> { - assertThat(users).isNotNull(); - assertThat(users).hasSizeGreaterThanOrEqualTo(2); - assertThat( - users.stream().map(UserEntity::getUser).collect(Collectors.toList()) - ).contains(ROOT, USER); - }) - .get(); - } finally { - arangoDB.deleteUser(USER).get(); - } - } - - @Test - void updateUserNoOptions() throws InterruptedException, ExecutionException { - try { - arangoDB.createUser(USER, PW, null).get(); - arangoDB.updateUser(USER, null).get(); - } finally { - arangoDB.deleteUser(USER).get(); - } - } - - @Test - void updateUser() throws InterruptedException, ExecutionException { - try { - final Map extra = new HashMap<>(); - extra.put("hund", false); - arangoDB.createUser(USER, PW, new UserCreateOptions().extra(extra)).get(); - extra.put("hund", true); - extra.put("mund", true); - { - arangoDB.updateUser(USER, new UserUpdateOptions().extra(extra)) - .whenComplete((user, ex) -> { - assertThat(user).isNotNull(); - assertThat(user.getExtra()).hasSize(2); - assertThat(user.getExtra().get("hund")).isNotNull(); - assertThat(Boolean.valueOf(String.valueOf(user.getExtra().get("hund")))).isTrue(); - }) - .get(); - } - arangoDB.getUser(USER) - .whenComplete((user2, ex) -> { - assertThat(user2.getExtra()).hasSize(2); - assertThat(user2.getExtra().get("hund")).isNotNull(); - assertThat(Boolean.valueOf(String.valueOf(user2.getExtra().get("hund")))).isTrue(); - }) - .get(); - } finally { - arangoDB.deleteUser(USER).get(); - } - } - - @Test - void replaceUser() throws InterruptedException, ExecutionException { - try { - final Map extra = new HashMap<>(); - extra.put("hund", false); - arangoDB.createUser(USER, PW, new UserCreateOptions().extra(extra)).get(); - extra.remove("hund"); - extra.put("mund", true); - { - arangoDB.replaceUser(USER, new UserUpdateOptions().extra(extra)) - .whenComplete((user, ex) -> { - assertThat(user).isNotNull(); - assertThat(user.getExtra()).hasSize(1); - assertThat(user.getExtra().get("mund")).isNotNull(); - assertThat(Boolean.valueOf(String.valueOf(user.getExtra().get("mund")))).isTrue(); - }) - .get(); - } - { - arangoDB.getUser(USER) - .whenComplete((user2, ex) -> { - assertThat(user2.getExtra()).hasSize(1); - assertThat(user2.getExtra().get("mund")).isNotNull(); - assertThat(Boolean.valueOf(String.valueOf(user2.getExtra().get("mund")))).isTrue(); - }) - .get(); - } - } finally { - arangoDB.deleteUser(USER).get(); - } - } - - @Test - void updateUserDefaultDatabaseAccess() throws InterruptedException, ExecutionException { - try { - arangoDB.createUser(USER, PW).get(); - arangoDB.grantDefaultDatabaseAccess(USER, Permissions.RW).get(); - } finally { - arangoDB.deleteUser(USER).get(); - } - } - - @Test - void updateUserDefaultCollectionAccess() throws InterruptedException, ExecutionException { - try { - arangoDB.createUser(USER, PW).get(); - arangoDB.grantDefaultCollectionAccess(USER, Permissions.RW).get(); - } finally { - arangoDB.deleteUser(USER).get(); - } - } - - @Test - void authenticationFailPassword() throws InterruptedException { - final ArangoDBAsync arangoDB = new ArangoDBAsync.Builder() - .loadProperties(ConfigUtils.loadConfig()) - .password("no").jwt(null).build(); - try { - arangoDB.getVersion().get(); - fail(); - } catch (final ExecutionException exception) { - assertThat(exception.getCause()).isInstanceOf(ArangoDBException.class); - } - } - - @Test - void authenticationFailUser() throws InterruptedException { - final ArangoDBAsync arangoDB = new ArangoDBAsync.Builder() - .loadProperties(ConfigUtils.loadConfig()) - .user("no").jwt(null).build(); - try { - arangoDB.getVersion().get(); - fail(); - } catch (final ExecutionException exception) { - assertThat(exception.getCause()).isInstanceOf(ArangoDBException.class); - } - } - - @Test - void execute() throws InterruptedException, ExecutionException { - arangoDB - .execute(Request.builder() - .db(DbName.SYSTEM) - .method(Request.Method.GET) - .path("/_api/version") - .build(), RawJson.class) - .whenComplete((response, ex) -> { - assertThat(response.getBody()).isNotNull(); - assertThat(SerdeUtils.INSTANCE.parseJson(response.getBody().getValue()).get("version").isTextual()).isTrue(); - }) - .get(); - } - - @Test - void execute_acquireHostList_enabled() throws InterruptedException, ExecutionException { - final ArangoDBAsync arangoDB = new ArangoDBAsync.Builder() - .loadProperties(ConfigUtils.loadConfig()) - .acquireHostList(true).build(); - arangoDB - .execute(Request.builder() - .db(DbName.SYSTEM) - .method(Request.Method.GET) - .path("/_api/version") - .build(), RawJson.class) - .whenComplete((response, ex) -> { - assertThat(response.getBody()).isNotNull(); - assertThat(SerdeUtils.INSTANCE.parseJson(response.getBody().getValue()).get("version").isTextual()).isTrue(); - }) - .get(); - } - - @Test - void getLogEntries() throws InterruptedException, ExecutionException { - assumeTrue(isAtLeastVersion(3, 8)); - arangoDB.getLogEntries(null) - .whenComplete((logs, ex) -> { - assertThat(logs).isNotNull(); - assertThat(logs.getTotal()).isPositive(); - assertThat((long) logs.getMessages().size()).isEqualTo(logs.getTotal()); - }) - .get(); - } - - @Test - void getLogLevel() throws InterruptedException, ExecutionException { - assumeTrue(isAtLeastVersion(3, 7)); // it fails in 3.6 active-failover (BTS-362) - arangoDB.getLogLevel() - .whenComplete((logLevel, ex) -> { - assertThat(logLevel).isNotNull(); - assertThat(logLevel.getAgency()).isEqualTo(LogLevelEntity.LogLevel.INFO); - }) - .get(); - } - - @Test - void setLogLevel() throws InterruptedException, ExecutionException { - assumeTrue(isAtLeastVersion(3, 7)); // it fails in 3.6 active-failover (BTS-362) - final LogLevelEntity entity = new LogLevelEntity(); - try { - entity.setAgency(LogLevelEntity.LogLevel.ERROR); - arangoDB.setLogLevel(entity) - .whenComplete((logLevel, ex) -> { - assertThat(logLevel).isNotNull(); - assertThat(logLevel.getAgency()).isEqualTo(LogLevelEntity.LogLevel.ERROR); - }) - .get(); - } finally { - entity.setAgency(LogLevelEntity.LogLevel.INFO); - arangoDB.setLogLevel(entity).get(); - } - } - - @Test - @Disabled("Manual execution only") - void queueTime() throws InterruptedException, ExecutionException { - List>> reqs = IntStream.range(0, 80) - .mapToObj(__ -> arangoDB.db().query("RETURN SLEEP(1)", Void.class)) - .collect(Collectors.toList()); - for (CompletableFuture> req : reqs) { - req.get(); - } - - QueueTimeMetrics qt = arangoDB.metrics().getQueueTime(); - double avg = qt.getAvg(); - QueueTimeSample[] values = qt.getValues(); - if (isAtLeastVersion(3, 9)) { - assertThat(values).hasSize(20); - for (int i = 0; i < values.length; i++) { - assertThat(values[i]).isNotNull(); - assertThat(values[i].value).isGreaterThanOrEqualTo(0.0); - if (i > 0) { - assertThat(values[i].timestamp).isGreaterThanOrEqualTo(values[i - 1].timestamp); - } - } - assertThat(avg).isGreaterThan(0.0); - } else { - assertThat(avg).isEqualTo(0.0); - assertThat(values).isEmpty(); - } - } - - @Test - void getQueryOptimizerRules() throws ExecutionException, InterruptedException { - assumeTrue(isAtLeastVersion(3, 10)); - final Collection rules = arangoDB.getQueryOptimizerRules().get(); - assertThat(rules).isNotEmpty(); - for (QueryOptimizerRule rule : rules) { - assertThat(rule).isNotNull(); - assertThat(rule.getName()).isNotNull(); - QueryOptimizerRule.Flags flags = rule.getFlags(); - assertThat(flags.getHidden()).isNotNull(); - assertThat(flags.getClusterOnly()).isNotNull(); - assertThat(flags.getCanBeDisabled()).isNotNull(); - assertThat(flags.getCanCreateAdditionalPlans()).isNotNull(); - assertThat(flags.getDisabledByDefault()).isNotNull(); - assertThat(flags.getEnterpriseOnly()).isNotNull(); - } - } - - -} diff --git a/driver/src/test/java/com/arangodb/async/ArangoDatabaseTest.java b/driver/src/test/java/com/arangodb/async/ArangoDatabaseTest.java deleted file mode 100644 index b85f3b67d..000000000 --- a/driver/src/test/java/com/arangodb/async/ArangoDatabaseTest.java +++ /dev/null @@ -1,1024 +0,0 @@ -/* - * DISCLAIMER - * - * Copyright 2016 ArangoDB GmbH, Cologne, Germany - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Copyright holder is ArangoDB GmbH, Cologne, Germany - */ - -package com.arangodb.async; - -import com.arangodb.ArangoDBException; -import com.arangodb.DbName; -import com.arangodb.entity.AqlExecutionExplainEntity.ExecutionPlan; -import com.arangodb.entity.*; -import com.arangodb.entity.AqlParseEntity.AstNode; -import com.arangodb.entity.QueryCachePropertiesEntity.CacheMode; -import com.arangodb.model.*; -import com.arangodb.util.RawJson; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.node.JsonNodeFactory; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; - -import java.io.IOException; -import java.util.*; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.atomic.AtomicInteger; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.catchThrowable; -import static org.junit.jupiter.api.Assertions.fail; -import static org.junit.jupiter.api.Assumptions.assumeTrue; - - -/** - * @author Mark Vollmary - * @author Michele Rastelli - */ -class ArangoDatabaseTest extends BaseTest { - - private static final String COLLECTION_NAME = "db_test"; - private static final String GRAPH_NAME = "graph_test"; - - @Test - void create() throws InterruptedException, ExecutionException { - try { - final Boolean result = arangoDB.db(DbName.of(BaseTest.TEST_DB.get() + "_1")).create().get(); - assertThat(result).isTrue(); - } finally { - arangoDB.db(DbName.of(BaseTest.TEST_DB.get() + "_1")).drop().get(); - } - } - - @Test - void getVersion() throws InterruptedException, ExecutionException { - db.getVersion() - .whenComplete((version, ex) -> { - assertThat(version).isNotNull(); - assertThat(version.getServer()).isNotNull(); - assertThat(version.getVersion()).isNotNull(); - }) - .get(); - } - - @Test - void getEngine() throws ExecutionException, InterruptedException { - final ArangoDBEngine engine = db.getEngine().get(); - assertThat(engine).isNotNull(); - assertThat(engine.getName()).isNotNull(); - } - - @Test - void exists() throws InterruptedException, ExecutionException { - assertThat(db.exists().get()).isTrue(); - assertThat(arangoDB.db(DbName.of("no")).exists().get()).isFalse(); - } - - @Test - void getAccessibleDatabases() throws InterruptedException, ExecutionException { - db.getAccessibleDatabases() - .whenComplete((dbs, ex) -> { - assertThat(dbs).isNotNull(); - assertThat(dbs.size()).isGreaterThan(0); - assertThat(dbs).contains("_system"); - }) - .get(); - } - - @Test - void createCollection() throws InterruptedException, ExecutionException { - db.createCollection(COLLECTION_NAME, null) - .whenComplete((result, ex) -> { - assertThat(result).isNotNull(); - assertThat(result.getId()).isNotNull(); - }) - .get(); - db.collection(COLLECTION_NAME).drop().get(); - } - - @Test - void createCollectionWithReplicationFactor() throws InterruptedException, ExecutionException { - assumeTrue(isCluster()); - final CollectionEntity result = db - .createCollection(COLLECTION_NAME, new CollectionCreateOptions().replicationFactor(2)).get(); - assertThat(result).isNotNull(); - assertThat(result.getId()).isNotNull(); - assertThat(db.collection(COLLECTION_NAME).getProperties().get().getReplicationFactor().getValue()).isEqualTo(2); - db.collection(COLLECTION_NAME).drop().get(); - } - - @Test - void createCollectionWithWriteConcern() throws ExecutionException, InterruptedException { - assumeTrue(isAtLeastVersion(3, 5)); - assumeTrue(isCluster()); - - final CollectionEntity result = db.createCollection(COLLECTION_NAME, - new CollectionCreateOptions().replicationFactor(2).writeConcern(2)).get(); - assertThat(result).isNotNull(); - assertThat(result.getId()).isNotNull(); - assertThat(db.collection(COLLECTION_NAME).getProperties().get().getReplicationFactor().getValue()).isEqualTo(2); - assertThat(db.collection(COLLECTION_NAME).getProperties().get().getWriteConcern()).isEqualTo(2); - db.collection(COLLECTION_NAME).drop(); - } - - @Test - void createCollectionWithNumberOfShards() throws InterruptedException, ExecutionException { - assumeTrue(isCluster()); - final CollectionEntity result = db - .createCollection(COLLECTION_NAME, new CollectionCreateOptions().numberOfShards(2)).get(); - assertThat(result).isNotNull(); - assertThat(result.getId()).isNotNull(); - assertThat(db.collection(COLLECTION_NAME).getProperties().get().getNumberOfShards()).isEqualTo(2); - db.collection(COLLECTION_NAME).drop().get(); - } - - @Test - void createCollectionWithNumberOfShardsAndShardKey() throws InterruptedException, ExecutionException { - assumeTrue(isCluster()); - final CollectionEntity result = db - .createCollection(COLLECTION_NAME, new CollectionCreateOptions().numberOfShards(2).shardKeys("a")) - .get(); - assertThat(result).isNotNull(); - assertThat(result.getId()).isNotNull(); - final CollectionPropertiesEntity properties = db.collection(COLLECTION_NAME).getProperties().get(); - assertThat(properties.getNumberOfShards()).isEqualTo(2); - assertThat(properties.getShardKeys()).hasSize(1); - db.collection(COLLECTION_NAME).drop().get(); - } - - @Test - void createCollectionWithNumberOfShardsAndShardKeys() throws InterruptedException, ExecutionException { - assumeTrue(isCluster()); - final CollectionEntity result = db.createCollection(COLLECTION_NAME, - new CollectionCreateOptions().numberOfShards(2).shardKeys("a", "b")).get(); - assertThat(result).isNotNull(); - assertThat(result.getId()).isNotNull(); - final CollectionPropertiesEntity properties = db.collection(COLLECTION_NAME).getProperties().get(); - assertThat(properties.getNumberOfShards()).isEqualTo(2); - assertThat(properties.getShardKeys()).hasSize(2); - db.collection(COLLECTION_NAME).drop().get(); - } - - @Test - void deleteCollection() throws InterruptedException, ExecutionException { - db.createCollection(COLLECTION_NAME, null).get(); - db.collection(COLLECTION_NAME).drop().get(); - try { - db.collection(COLLECTION_NAME).getInfo().get(); - fail(); - } catch (final ExecutionException e) { - assertThat(e.getCause()).isInstanceOf(ArangoDBException.class); - } - } - - @Test - void deleteSystemCollection() throws InterruptedException, ExecutionException { - final String name = "_system_test"; - db.createCollection(name, new CollectionCreateOptions().isSystem(true)).get(); - db.collection(name).drop(true).get(); - try { - db.collection(name).getInfo().get(); - fail(); - } catch (final ExecutionException e) { - assertThat(e.getCause()).isInstanceOf(ArangoDBException.class); - } - } - - @Test - void deleteSystemCollectionFail() throws InterruptedException, ExecutionException { - final String name = "_system_test"; - db.createCollection(name, new CollectionCreateOptions().isSystem(true)).get(); - try { - db.collection(name).drop().get(); - fail(); - } catch (final ExecutionException e) { - assertThat(e.getCause()).isInstanceOf(ArangoDBException.class); - } - db.collection(name).drop(true).get(); - try { - db.collection(name).getInfo().get(); - fail(); - } catch (final ExecutionException e) { - assertThat(e.getCause()).isInstanceOf(ArangoDBException.class); - } - } - - @Test - void getIndex() throws InterruptedException, ExecutionException { - db.createCollection(COLLECTION_NAME, null).get(); - final Collection fields = new ArrayList<>(); - fields.add("a"); - final IndexEntity createResult = db.collection(COLLECTION_NAME).ensurePersistentIndex(fields, null).get(); - db.getIndex(createResult.getId()) - .whenComplete((readResult, ex) -> { - assertThat(readResult.getId()).isEqualTo(createResult.getId()); - assertThat(readResult.getType()).isEqualTo(createResult.getType()); - }) - .get(); - db.collection(COLLECTION_NAME).drop().get(); - } - - @Test - void deleteIndex() throws InterruptedException, ExecutionException { - try { - db.createCollection(COLLECTION_NAME, null).get(); - final Collection fields = new ArrayList<>(); - fields.add("a"); - final IndexEntity createResult = db.collection(COLLECTION_NAME).ensurePersistentIndex(fields, null).get(); - db.deleteIndex(createResult.getId()) - .whenComplete((id, ex) -> { - assertThat(id).isEqualTo(createResult.getId()); - try { - db.getIndex(id).get(); - fail(); - } catch (InterruptedException e) { - fail(); - } catch (ExecutionException e) { - assertThat(e.getCause()).isInstanceOf(ArangoDBException.class); - } - }) - .get(); - } finally { - db.collection(COLLECTION_NAME).drop().get(); - } - } - - @Test - void getCollections() throws InterruptedException, ExecutionException { - try { - final Collection systemCollections = db.getCollections(null).get(); - db.createCollection(COLLECTION_NAME + "1", null).get(); - db.createCollection(COLLECTION_NAME + "2", null).get(); - db.getCollections(null) - .whenComplete((collections, ex) -> { - assertThat(collections.size()).isEqualTo(2 + systemCollections.size()); - assertThat(collections).isNotNull(); - }) - .get(); - } finally { - db.collection(COLLECTION_NAME + "1").drop().get(); - db.collection(COLLECTION_NAME + "2").drop().get(); - } - } - - @Test - void getCollectionsExcludeSystem() throws InterruptedException, ExecutionException { - try { - final CollectionsReadOptions options = new CollectionsReadOptions().excludeSystem(true); - final Collection systemCollections = db.getCollections(options).get(); - assertThat(systemCollections).isEmpty(); - db.createCollection(COLLECTION_NAME + "1", null).get(); - db.createCollection(COLLECTION_NAME + "2", null).get(); - db.getCollections(options) - .whenComplete((collections, ex) -> { - assertThat(collections.size()).isEqualTo(2); - assertThat(collections).isNotNull(); - }) - .get(); - } finally { - db.collection(COLLECTION_NAME + "1").drop().get(); - db.collection(COLLECTION_NAME + "2").drop().get(); - } - } - - @Test - void grantAccess() throws InterruptedException, ExecutionException { - try { - arangoDB.createUser("user1", "1234", null).get(); - db.grantAccess("user1").get(); - } finally { - arangoDB.deleteUser("user1").get(); - } - } - - @Test - void grantAccessRW() throws InterruptedException, ExecutionException { - try { - arangoDB.createUser("user1", "1234", null).get(); - db.grantAccess("user1", Permissions.RW).get(); - } finally { - arangoDB.deleteUser("user1").get(); - } - } - - @Test - void grantAccessRO() throws InterruptedException, ExecutionException { - try { - arangoDB.createUser("user1", "1234", null).get(); - db.grantAccess("user1", Permissions.RO).get(); - } finally { - arangoDB.deleteUser("user1").get(); - } - } - - @Test - void grantAccessNONE() throws InterruptedException, ExecutionException { - try { - arangoDB.createUser("user1", "1234", null).get(); - db.grantAccess("user1", Permissions.NONE).get(); - } finally { - arangoDB.deleteUser("user1").get(); - } - } - - @Test - void grantAccessUserNotFound() { - Throwable thrown = catchThrowable(() -> db.grantAccess("user1", Permissions.RW).get()); - assertThat(thrown).isInstanceOf(ExecutionException.class); - } - - @Test - void revokeAccess() throws InterruptedException, ExecutionException { - try { - arangoDB.createUser("user1", "1234", null).get(); - db.revokeAccess("user1").get(); - } finally { - arangoDB.deleteUser("user1").get(); - } - } - - @Test - void revokeAccessUserNotFound() { - Throwable thrown = catchThrowable(() -> db.revokeAccess("user1").get()); - assertThat(thrown).isInstanceOf(ExecutionException.class); - } - - @Test - void resetAccess() throws InterruptedException, ExecutionException { - try { - arangoDB.createUser("user1", "1234", null).get(); - db.resetAccess("user1").get(); - } finally { - arangoDB.deleteUser("user1").get(); - } - } - - @Test - void resetAccessUserNotFound() { - Throwable thrown = catchThrowable(() -> db.resetAccess("user1").get()); - assertThat(thrown).isInstanceOf(ExecutionException.class); - } - - @Test - void grantDefaultCollectionAccess() throws InterruptedException, ExecutionException { - try { - arangoDB.createUser("user1", "1234").get(); - db.grantDefaultCollectionAccess("user1", Permissions.RW).get(); - } finally { - arangoDB.deleteUser("user1").get(); - } - } - - @Test - void getPermissions() throws InterruptedException, ExecutionException { - assertThat(db.getPermissions("root").get()).isEqualTo(Permissions.RW); - } - - @Test - void query() throws InterruptedException, ExecutionException { - try { - db.createCollection(COLLECTION_NAME, null).get(); - for (int i = 0; i < 10; i++) { - db.collection(COLLECTION_NAME).insertDocument(new BaseDocument(), null).get(); - } - db.query("for i in db_test return i._id", null, null, String.class) - .whenComplete((cursor, ex) -> { - for (int i = 0; i < 10; i++, cursor.next()) { - assertThat(cursor.hasNext()).isEqualTo(true); - } - }) - .get(); - } finally { - db.collection(COLLECTION_NAME).drop().get(); - } - } - - @Test - void queryForEach() throws InterruptedException, ExecutionException { - try { - db.createCollection(COLLECTION_NAME, null).get(); - for (int i = 0; i < 10; i++) { - db.collection(COLLECTION_NAME).insertDocument(new BaseDocument(), null).get(); - } - db.query("for i in db_test return i._id", null, null, String.class) - .whenComplete((cursor, ex) -> { - final AtomicInteger i = new AtomicInteger(0); - cursor.forEachRemaining(e -> i.incrementAndGet()); - assertThat(i.get()).isEqualTo(10); - }) - .get(); - } finally { - db.collection(COLLECTION_NAME).drop().get(); - } - } - - @Test - void queryStream() throws InterruptedException, ExecutionException { - try { - db.createCollection(COLLECTION_NAME, null).get(); - for (int i = 0; i < 10; i++) { - db.collection(COLLECTION_NAME).insertDocument(new BaseDocument(), null).get(); - } - db.query("for i in db_test return i._id", null, null, String.class) - .whenComplete((cursor, ex) -> { - final AtomicInteger i = new AtomicInteger(0); - cursor.forEachRemaining(e -> i.incrementAndGet()); - assertThat(i.get()).isEqualTo(10); - }) - .get(); - } finally { - db.collection(COLLECTION_NAME).drop().get(); - } - } - - @Test - void queryWithTimeout() throws ExecutionException, InterruptedException { - assumeTrue(isAtLeastVersion(3, 6)); - - try { - db.query("RETURN SLEEP(1)", null, new AqlQueryOptions().maxRuntime(0.1), String.class).get().next(); - fail(); - } catch (ExecutionException e) { - assertThat(e.getCause()).isInstanceOf(ArangoDBException.class); - assertThat(((ArangoDBException) e.getCause()).getResponseCode()).isEqualTo(410); - } - } - - @Test - void queryWithCount() throws InterruptedException, ExecutionException { - try { - db.createCollection(COLLECTION_NAME, null).get(); - for (int i = 0; i < 10; i++) { - db.collection(COLLECTION_NAME).insertDocument(new BaseDocument(), null).get(); - } - - db.query("for i in db_test Limit 6 return i._id", null, new AqlQueryOptions().count(true), String.class) - .whenComplete((cursor, ex) -> { - for (int i = 0; i < 6; i++, cursor.next()) { - assertThat(cursor.hasNext()).isEqualTo(true); - } - assertThat(cursor.getCount()).isEqualTo(6); - }) - .get(); - } finally { - db.collection(COLLECTION_NAME).drop().get(); - } - } - - @Test - void queryWithLimitAndFullCount() throws InterruptedException, ExecutionException { - try { - db.createCollection(COLLECTION_NAME, null).get(); - for (int i = 0; i < 10; i++) { - db.collection(COLLECTION_NAME).insertDocument(new BaseDocument(), null).get(); - } - - db.query("for i in db_test Limit 5 return i._id", null, new AqlQueryOptions().fullCount(true), String.class) - .whenComplete((cursor, ex) -> { - for (int i = 0; i < 5; i++, cursor.next()) { - assertThat(cursor.hasNext()).isEqualTo(true); - } - assertThat(cursor.getStats()).isNotNull(); - assertThat(cursor.getStats().getExecutionTime()).isPositive(); - assertThat((cursor.getStats().getFullCount())).isGreaterThanOrEqualTo(10); - }) - .get(); - } finally { - db.collection(COLLECTION_NAME).drop().get(); - } - } - - @Test - void queryWithBatchSize() throws InterruptedException, ExecutionException { - try { - db.createCollection(COLLECTION_NAME, null).get(); - for (int i = 0; i < 10; i++) { - db.collection(COLLECTION_NAME).insertDocument(new BaseDocument(), null).get(); - } - final ArangoCursorAsync cursor = db.query("for i in db_test return i._id", null, - new AqlQueryOptions().batchSize(5).count(true), String.class).get(); - for (int i = 0; i < 10; i++, cursor.next()) { - assertThat(cursor.hasNext()).isTrue(); - } - } finally { - db.collection(COLLECTION_NAME).drop().get(); - } - } - - @Test - void queryStreamWithBatchSize() throws InterruptedException, ExecutionException { - try { - db.createCollection(COLLECTION_NAME, null).get(); - for (int i = 0; i < 10; i++) { - db.collection(COLLECTION_NAME).insertDocument(new BaseDocument(), null).get(); - } - final ArangoCursorAsync cursor = db.query("for i in db_test return i._id", null, - new AqlQueryOptions().batchSize(5).count(true), String.class).get(); - final AtomicInteger i = new AtomicInteger(0); - cursor.streamRemaining().forEach(e -> i.incrementAndGet()); - assertThat(i.get()).isEqualTo(10); - } finally { - db.collection(COLLECTION_NAME).drop().get(); - } - } - - /** - * ignored. takes to long - */ - @Test - @Disabled - void queryWithTTL() throws InterruptedException, ExecutionException { - // 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).get(); - for (int i = 0; i < 10; i++) { - db.collection(COLLECTION_NAME).insertDocument(new BaseDocument(), null).get(); - } - final ArangoCursorAsync cursor = db.query("for i in db_test return i._id", null, - new AqlQueryOptions().batchSize(5).ttl(ttl), String.class).get(); - for (int i = 0; i < 10; i++, cursor.next()) { - assertThat(cursor.hasNext()).isTrue(); - if (i == 1) { - Thread.sleep(wait * 1000); - } - } - fail(); - } catch (final ArangoDBException ex) { - assertThat(ex.getResponseCode()).isEqualTo(404); - assertThat(ex.getErrorNum()).isEqualTo(1600); - } finally { - db.collection(COLLECTION_NAME).drop().get(); - } - } - - @Test - void changeQueryCache() throws InterruptedException, ExecutionException { - try { - QueryCachePropertiesEntity properties = db.getQueryCacheProperties().get(); - assertThat(properties).isNotNull(); - assertThat(properties.getMode()).isEqualTo(CacheMode.off); - assertThat(properties.getMaxResults()).isPositive(); - - properties.setMode(CacheMode.on); - properties = db.setQueryCacheProperties(properties).get(); - assertThat(properties).isNotNull(); - assertThat(properties.getMode()).isEqualTo(CacheMode.on); - - properties = db.getQueryCacheProperties().get(); - assertThat(properties.getMode()).isEqualTo(CacheMode.on); - } finally { - final QueryCachePropertiesEntity properties = new QueryCachePropertiesEntity(); - properties.setMode(CacheMode.off); - db.setQueryCacheProperties(properties).get(); - } - } - - @Test - void queryWithCache() throws InterruptedException, ExecutionException { - assumeTrue(isSingleServer()); - try { - db.createCollection(COLLECTION_NAME, null).get(); - for (int i = 0; i < 10; i++) { - db.collection(COLLECTION_NAME).insertDocument(new BaseDocument(), null).get(); - } - - final QueryCachePropertiesEntity properties = new QueryCachePropertiesEntity(); - properties.setMode(CacheMode.on); - db.setQueryCacheProperties(properties).get(); - - final ArangoCursorAsync 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) - .get(); - - assertThat(cursor.isCached()).isFalse(); - - final ArangoCursorAsync 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) - .get(); - - assertThat(cachedCursor.isCached()).isTrue(); - - } finally { - db.collection(COLLECTION_NAME).drop().get(); - final QueryCachePropertiesEntity properties = new QueryCachePropertiesEntity(); - properties.setMode(CacheMode.off); - db.setQueryCacheProperties(properties).get(); - } - } - - @Test - void queryCursor() throws InterruptedException, ExecutionException { - try { - db.createCollection(COLLECTION_NAME, null).get(); - final int numbDocs = 10; - for (int i = 0; i < numbDocs; i++) { - db.collection(COLLECTION_NAME).insertDocument(new BaseDocument(), null).get(); - } - - final int batchSize = 5; - final ArangoCursorAsync cursor = db.query("for i in db_test return i._id", null, - new AqlQueryOptions().batchSize(batchSize).count(true), String.class).get(); - assertThat(cursor.getCount()).isEqualTo(numbDocs); - - final ArangoCursorAsync cursor2 = db.cursor(cursor.getId(), String.class).get(); - assertThat(cursor2.getCount()).isEqualTo(numbDocs); - assertThat(cursor2.hasNext()).isTrue(); - - for (int i = 0; i < batchSize; i++, cursor.next()) { - assertThat(cursor.hasNext()).isTrue(); - } - } finally { - db.collection(COLLECTION_NAME).drop().get(); - } - } - - @Test - void changeQueryTrackingProperties() throws InterruptedException, ExecutionException { - try { - QueryTrackingPropertiesEntity properties = db.getQueryTrackingProperties().get(); - assertThat(properties).isNotNull(); - assertThat(properties.getEnabled()).isTrue(); - assertThat(properties.getTrackSlowQueries()).isTrue(); - assertThat(properties.getMaxQueryStringLength()).isPositive(); - assertThat(properties.getMaxSlowQueries()).isPositive(); - assertThat(properties.getSlowQueryThreshold()).isPositive(); - properties.setEnabled(false); - properties = db.setQueryTrackingProperties(properties).get(); - assertThat(properties).isNotNull(); - assertThat(properties.getEnabled()).isFalse(); - properties = db.getQueryTrackingProperties().get(); - assertThat(properties.getEnabled()).isFalse(); - } finally { - final QueryTrackingPropertiesEntity properties = new QueryTrackingPropertiesEntity(); - properties.setEnabled(true); - db.setQueryTrackingProperties(properties).get(); - } - } - - @Test - void queryWithBindVars() throws InterruptedException, ExecutionException { - try { - db.createCollection(COLLECTION_NAME, null).get(); - for (int i = 0; i < 10; i++) { - final BaseDocument baseDocument = new BaseDocument(UUID.randomUUID().toString()); - baseDocument.addAttribute("age", 20 + i); - db.collection(COLLECTION_NAME).insertDocument(baseDocument, null).get(); - } - final Map bindVars = new HashMap<>(); - bindVars.put("@coll", COLLECTION_NAME); - bindVars.put("age", 25); - db.query("FOR t IN @@coll FILTER t.age >= @age SORT t.age RETURN t._id", bindVars, null, String.class) - .whenComplete((cursor, ex) -> { - for (int i = 0; i < 5; i++, cursor.next()) { - assertThat(cursor.hasNext()).isEqualTo(true); - } - }) - .get(); - } finally { - db.collection(COLLECTION_NAME).drop().get(); - } - } - - @Test - void queryWithWarning() throws InterruptedException, ExecutionException { - arangoDB.db().query("return 1/0", null, null, String.class) - .whenComplete((cursor, ex) -> { - assertThat(cursor.getWarnings()).isNotNull(); - assertThat(cursor.getWarnings()).isNotEmpty(); - }) - .get(); - } - - @Test - void queryClose() throws IOException, InterruptedException, ExecutionException { - final ArangoCursorAsync cursor = arangoDB.db() - .query("for i in 1..2 return i", null, new AqlQueryOptions().batchSize(1), String.class).get(); - cursor.close(); - int count = 0; - try { - for (; cursor.hasNext(); cursor.next(), count++) { - } - fail(); - } catch (final ArangoDBException e) { - assertThat(count).isEqualTo(1); - } - - } - - @Test - void explainQuery() throws InterruptedException, ExecutionException { - arangoDB.db().explainQuery("for i in 1..1 return i", null, null) - .whenComplete((explain, ex) -> { - assertThat(explain).isNotNull(); - assertThat(explain.getPlan()).isNotNull(); - assertThat(explain.getPlans()).isNull(); - final ExecutionPlan plan = explain.getPlan(); - assertThat(plan.getCollections().size()).isEqualTo(0); - assertThat(plan.getEstimatedCost()).isGreaterThan(0); - assertThat(plan.getEstimatedNrItems()).isGreaterThan(0); - assertThat(plan.getVariables().size()).isEqualTo(2); - assertThat(plan.getNodes().size()).isGreaterThan(0); - }) - .get(); - } - - @Test - void parseQuery() throws InterruptedException, ExecutionException { - assumeTrue(isAtLeastVersion(3, 4)); - arangoDB.db().parseQuery("for i in _apps return i") - .whenComplete((parse, ex) -> { - assertThat(parse).isNotNull(); - assertThat(parse.getBindVars()).isEmpty(); - assertThat(parse.getCollections().size()).isEqualTo(1); - assertThat(parse.getCollections().iterator().next()).isEqualTo("_apps"); - assertThat(parse.getAst().size()).isEqualTo(1); - final AstNode root = parse.getAst().iterator().next(); - assertThat(root.getType()).isEqualTo("root"); - assertThat(root.getName()).isNull(); - assertThat(root.getSubNodes()).isNotNull(); - assertThat(root.getSubNodes().size()).isEqualTo(2); - final Iterator iterator = root.getSubNodes().iterator(); - final AstNode for_ = iterator.next(); - assertThat(for_.getType()).isEqualTo("for"); - assertThat(for_.getSubNodes()).isNotNull(); - assertThat(for_.getSubNodes().size()).isEqualTo(3); - final Iterator iterator2 = for_.getSubNodes().iterator(); - final AstNode first = iterator2.next(); - assertThat(first.getType()).isEqualTo("variable"); - assertThat(first.getName()).isEqualTo("i"); - final AstNode second = iterator2.next(); - assertThat(second.getType()).isEqualTo("collection"); - assertThat(second.getName()).isEqualTo("_apps"); - final AstNode return_ = iterator.next(); - assertThat(return_.getType()).isEqualTo("return"); - assertThat(return_.getSubNodes()).isNotNull(); - assertThat(return_.getSubNodes().size()).isEqualTo(1); - assertThat(return_.getSubNodes().iterator().next().getType()).isEqualTo("reference"); - assertThat(return_.getSubNodes().iterator().next().getName()).isEqualTo("i"); - }) - .get(); - } - - @Test - @Disabled - void getAndClearSlowQueries() throws InterruptedException, ExecutionException { - final QueryTrackingPropertiesEntity properties = db.getQueryTrackingProperties().get(); - 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().get(); - assertThat(slowQueries).isNotNull(); - assertThat(slowQueries).hasSize(1); - final QueryEntity queryEntity = slowQueries.iterator().next(); - assertThat(queryEntity.getQuery()).isEqualTo("return sleep(1.1)"); - - db.clearSlowQueries().get(); - assertThat(db.getSlowQueries().get().size()).isZero(); - } finally { - properties.setSlowQueryThreshold(slowQueryThreshold); - db.setQueryTrackingProperties(properties); - } - } - - @Test - void createGetDeleteAqlFunction() throws InterruptedException, ExecutionException { - final Collection aqlFunctionsInitial = db.getAqlFunctions(null).get(); - assertThat(aqlFunctionsInitial).isEmpty(); - try { - db.createAqlFunction("myfunctions::temperature::celsiustofahrenheit", - "function (celsius) { return celsius * 1.8 + 32; }", null).get(); - - final Collection aqlFunctions = db.getAqlFunctions(null).get(); - assertThat(aqlFunctions).hasSizeGreaterThan(aqlFunctionsInitial.size()); - } finally { - final Integer deleteCount = db.deleteAqlFunction("myfunctions::temperature::celsiustofahrenheit", null) - .get(); - // compatibility with ArangoDB < 3.4 - if (isAtLeastVersion(3, 4)) { - assertThat(deleteCount).isEqualTo(1); - } else { - assertThat(deleteCount).isNull(); - } - - final Collection aqlFunctions = db.getAqlFunctions(null).get(); - assertThat(aqlFunctions).hasSameSizeAs(aqlFunctionsInitial); - } - } - - @Test - void createGetDeleteAqlFunctionWithNamespace() throws InterruptedException, ExecutionException { - final Collection aqlFunctionsInitial = db.getAqlFunctions(null).get(); - assertThat(aqlFunctionsInitial).isEmpty(); - try { - db.createAqlFunction("myfunctions::temperature::celsiustofahrenheit1", - "function (celsius) { return celsius * 1.8 + 32; }", null).get(); - db.createAqlFunction("myfunctions::temperature::celsiustofahrenheit2", - "function (celsius) { return celsius * 1.8 + 32; }", null).get(); - - } finally { - db.deleteAqlFunction("myfunctions::temperature", new AqlFunctionDeleteOptions().group(true)).get(); - - final Collection aqlFunctions = db.getAqlFunctions(null).get(); - assertThat(aqlFunctions).hasSameSizeAs(aqlFunctionsInitial); - } - } - - @Test - void createGraph() throws InterruptedException, ExecutionException { - try { - db.createGraph(GRAPH_NAME, null, null) - .whenComplete((result, ex) -> { - assertThat(result).isNotNull(); - assertThat(result.getName()).isEqualTo(GRAPH_NAME); - }) - .get(); - } finally { - db.graph(GRAPH_NAME).drop().get(); - } - } - - @Test - void getGraphs() throws InterruptedException, ExecutionException { - try { - db.createGraph(GRAPH_NAME, null, null).get(); - db.getGraphs() - .whenComplete((graphs, ex) -> { - assertThat(graphs).isNotNull(); - assertThat(graphs.size()).isEqualTo(1); - }) - .get(); - } finally { - db.graph(GRAPH_NAME).drop().get(); - } - } - - @Test - void transactionString() throws InterruptedException, ExecutionException { - final TransactionOptions options = new TransactionOptions().params("test"); - db.transaction("function (params) {return params;}", RawJson.class, options) - .whenComplete((result, ex) -> assertThat(result.getValue()).isEqualTo("\"test\"")) - .get(); - } - - @Test - void transactionNumber() throws InterruptedException, ExecutionException { - final TransactionOptions options = new TransactionOptions().params(5); - db.transaction("function (params) {return params;}", Integer.class, options) - .whenComplete((result, ex) -> assertThat(result).isEqualTo(5)) - .get(); - } - - @Test - void transactionJsonNode() throws InterruptedException, ExecutionException { - final TransactionOptions options = new TransactionOptions().params(JsonNodeFactory.instance.textNode("test")); - db.transaction("function (params) {return params;}", JsonNode.class, options) - .whenComplete((result, ex) -> { - assertThat(result.isTextual()).isEqualTo(true); - assertThat(result.asText()).isEqualTo("test"); - }) - .get(); - } - - @Test - void transactionEmpty() throws InterruptedException, ExecutionException { - db.transaction("function () {}", Void.class, null).get(); - } - - @Test - void transactionAllowImplicit() throws InterruptedException, ExecutionException { - try { - db.createCollection("someCollection", null).get(); - db.createCollection("someOtherCollection", null).get(); - 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, Void.class, options).get(); - try { - options.allowImplicit(false); - db.transaction(action, Void.class, options).get(); - fail(); - } catch (final ExecutionException e) { - assertThat(e.getCause()).isInstanceOf(ArangoDBException.class); - } - } finally { - db.collection("someCollection").drop().get(); - db.collection("someOtherCollection").drop().get(); - } - } - - @Test - void transactionPojoReturn() throws ExecutionException, InterruptedException { - final String action = "function() { return {'value':'hello world'}; }"; - db.transaction(action, TransactionTestEntity.class, new TransactionOptions()) - .whenComplete((res, ex) -> { - assertThat(res).isNotNull(); - assertThat(res.value).isEqualTo("hello world"); - }) - .get(); - } - - @Test - void getInfo() throws InterruptedException, ExecutionException { - final CompletableFuture f = db.getInfo(); - assertThat(f).isNotNull(); - f.whenComplete((info, ex) -> { - assertThat(info).isNotNull(); - assertThat(info.getId()).isNotNull(); - assertThat(info.getName()).isEqualTo(TEST_DB.get()); - assertThat(info.getPath()).isNotNull(); - assertThat(info.getIsSystem()).isFalse(); - - try { - if (isAtLeastVersion(3, 6) && isCluster()) { - assertThat(info.getSharding()).isNotNull(); - assertThat(info.getWriteConcern()).isNotNull(); - assertThat(info.getReplicationFactor()).isNotNull(); - } - } catch (InterruptedException | ExecutionException e) { - e.printStackTrace(); - fail(); - } - - }); - f.get(); - } - - @Test - void getDocument() throws InterruptedException, ExecutionException { - String collectionName = COLLECTION_NAME + "getDocument"; - db.createCollection(collectionName).get(); - final BaseDocument value = new BaseDocument(UUID.randomUUID().toString()); - value.setKey("123"); - db.collection(collectionName).insertDocument(value).get(); - db.getDocument(collectionName + "/123", BaseDocument.class) - .whenComplete((document, ex) -> { - assertThat(document).isNotNull(); - assertThat(document.getKey()).isEqualTo("123"); - }) - .get(); - db.collection(collectionName).drop().get(); - } - - @Test - void shouldIncludeExceptionMessage() throws InterruptedException, ExecutionException { - final String exceptionMessage = "My error context"; - final String action = "function (params) {" + "throw '" + exceptionMessage + "';" + "}"; - try { - db.transaction(action, Void.class, null).get(); - fail(); - } catch (final ExecutionException e) { - assertThat(e.getCause()).isInstanceOf(ArangoDBException.class); - ArangoDBException cause = ((ArangoDBException) e.getCause()); - assertThat(cause.getErrorNum()).isEqualTo(1650); - if (isAtLeastVersion(3, 4)) { - assertThat(cause.getErrorMessage()).isEqualTo(exceptionMessage); - } - } - } - - @Test - void getDocumentWrongId() { - Throwable thrown = catchThrowable(() -> db.getDocument("123", BaseDocument.class).get()); - assertThat(thrown).isInstanceOf(ArangoDBException.class); - } - - @Test - void reloadRouting() throws InterruptedException, ExecutionException { - db.reloadRouting().get(); - } - - public static class TransactionTestEntity { - private String value; - - public TransactionTestEntity() { - super(); - } - - public String getValue() { - return value; - } - } -} diff --git a/driver/src/test/java/com/arangodb/async/ArangoEdgeCollectionTest.java b/driver/src/test/java/com/arangodb/async/ArangoEdgeCollectionTest.java deleted file mode 100644 index e1b106875..000000000 --- a/driver/src/test/java/com/arangodb/async/ArangoEdgeCollectionTest.java +++ /dev/null @@ -1,367 +0,0 @@ -/* - * DISCLAIMER - * - * Copyright 2016 ArangoDB GmbH, Cologne, Germany - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Copyright holder is ArangoDB GmbH, Cologne, Germany - */ - -package com.arangodb.async; - -import com.arangodb.ArangoDBException; -import com.arangodb.entity.*; -import com.arangodb.model.*; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.concurrent.ExecutionException; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.fail; - -/** - * @author Mark Vollmary - */ -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"; - - @BeforeAll - static void setup() throws InterruptedException, ExecutionException { - if (!db.collection(VERTEX_COLLECTION_NAME).exists().get()) { - db.createCollection(VERTEX_COLLECTION_NAME, null).get(); - } - if (!db.collection(EDGE_COLLECTION_NAME).exists().get()) { - db.createCollection(EDGE_COLLECTION_NAME, new CollectionCreateOptions().type(CollectionType.EDGES)).get(); - } - 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).get(); - } - - @AfterEach - void teardown() throws InterruptedException, ExecutionException { - for (final String collection : new String[]{VERTEX_COLLECTION_NAME, EDGE_COLLECTION_NAME}) { - db.collection(collection).truncate().get(); - } - } - - private BaseEdgeDocument createEdgeValue() throws InterruptedException, ExecutionException { - final VertexEntity v1 = db.graph(GRAPH_NAME).vertexCollection(VERTEX_COLLECTION_NAME) - .insertVertex(new BaseDocument(), null).get(); - final VertexEntity v2 = db.graph(GRAPH_NAME).vertexCollection(VERTEX_COLLECTION_NAME) - .insertVertex(new BaseDocument(), null).get(); - - final BaseEdgeDocument value = new BaseEdgeDocument(); - value.setFrom(v1.getId()); - value.setTo(v2.getId()); - return value; - } - - @Test - void insertEdge() throws InterruptedException, ExecutionException { - final BaseEdgeDocument value = createEdgeValue(); - final EdgeEntity edge = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).insertEdge(value, null).get(); - assertThat(edge).isNotNull(); - final BaseEdgeDocument document = db.collection(EDGE_COLLECTION_NAME) - .getDocument(edge.getKey(), BaseEdgeDocument.class, null).get(); - assertThat(document).isNotNull(); - assertThat(document.getKey()).isEqualTo(edge.getKey()); - } - - @Test - void getEdge() throws InterruptedException, ExecutionException { - final BaseEdgeDocument value = createEdgeValue(); - final EdgeEntity edge = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).insertEdge(value, null).get(); - final BaseDocument document = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME) - .getEdge(edge.getKey(), BaseDocument.class, null).get(); - assertThat(document).isNotNull(); - assertThat(document.getKey()).isEqualTo(edge.getKey()); - } - - @Test - void getEdgeIfMatch() throws InterruptedException, ExecutionException { - final BaseEdgeDocument value = createEdgeValue(); - final EdgeEntity edge = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).insertEdge(value, null).get(); - 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).get(); - assertThat(document).isNotNull(); - assertThat(document.getKey()).isEqualTo(edge.getKey()); - } - - @Test - void getEdgeIfMatchFail() throws InterruptedException, ExecutionException { - final BaseEdgeDocument value = createEdgeValue(); - final EdgeEntity edge = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).insertEdge(value, null).get(); - final GraphDocumentReadOptions options = new GraphDocumentReadOptions().ifMatch("no"); - BaseEdgeDocument doc = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME) - .getEdge(edge.getKey(), BaseEdgeDocument.class, options).get(); - assertThat(doc).isNull(); - } - - @Test - void getEdgeIfNoneMatch() throws InterruptedException, ExecutionException { - final BaseEdgeDocument value = createEdgeValue(); - final EdgeEntity edge = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).insertEdge(value, null).get(); - final GraphDocumentReadOptions options = new GraphDocumentReadOptions().ifNoneMatch("no"); - final BaseDocument document = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME) - .getEdge(edge.getKey(), BaseDocument.class, options).get(); - assertThat(document).isNotNull(); - assertThat(document.getKey()).isEqualTo(edge.getKey()); - } - - @Test - void getEdgeIfNoneMatchFail() throws InterruptedException, ExecutionException { - final BaseEdgeDocument value = createEdgeValue(); - final EdgeEntity edge = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).insertEdge(value, null).get(); - final GraphDocumentReadOptions options = new GraphDocumentReadOptions().ifNoneMatch(edge.getRev()); - BaseEdgeDocument doc = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME) - .getEdge(edge.getKey(), BaseEdgeDocument.class, options).get(); - assertThat(doc).isNull(); - } - - @Test - void replaceEdge() throws InterruptedException, ExecutionException { - final BaseEdgeDocument doc = createEdgeValue(); - doc.addAttribute("a", "test"); - final EdgeEntity createResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).insertEdge(doc, null) - .get(); - doc.removeAttribute("a"); - doc.addAttribute("b", "test"); - final EdgeUpdateEntity replaceResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME) - .replaceEdge(createResult.getKey(), doc, null).get(); - assertThat(replaceResult).isNotNull(); - assertThat(replaceResult.getId()).isEqualTo(createResult.getId()); - assertThat(replaceResult.getRev()).isNotEqualTo(replaceResult.getOldRev()); - assertThat(replaceResult.getOldRev()).isEqualTo(createResult.getRev()); - - final BaseEdgeDocument readResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME) - .getEdge(createResult.getKey(), BaseEdgeDocument.class, null).get(); - assertThat(readResult.getKey()).isEqualTo(createResult.getKey()); - assertThat(readResult.getRevision()).isEqualTo(replaceResult.getRev()); - assertThat(readResult.getProperties().keySet()).doesNotContain("a"); - assertThat(readResult.getAttribute("b")).isNotNull(); - assertThat(String.valueOf(readResult.getAttribute("b"))).isEqualTo("test"); - } - - @Test - void replaceEdgeIfMatch() throws InterruptedException, ExecutionException { - final BaseEdgeDocument doc = createEdgeValue(); - doc.addAttribute("a", "test"); - final EdgeEntity createResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).insertEdge(doc, null) - .get(); - doc.removeAttribute("a"); - 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).get(); - assertThat(replaceResult).isNotNull(); - assertThat(replaceResult.getId()).isEqualTo(createResult.getId()); - assertThat(replaceResult.getRev()).isNotEqualTo(replaceResult.getOldRev()); - assertThat(replaceResult.getOldRev()).isEqualTo(createResult.getRev()); - - final BaseEdgeDocument readResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME) - .getEdge(createResult.getKey(), BaseEdgeDocument.class, null).get(); - assertThat(readResult.getKey()).isEqualTo(createResult.getKey()); - assertThat(readResult.getRevision()).isEqualTo(replaceResult.getRev()); - assertThat(readResult.getProperties().keySet()).doesNotContain("a"); - assertThat(readResult.getAttribute("b")).isNotNull(); - assertThat(String.valueOf(readResult.getAttribute("b"))).isEqualTo("test"); - } - - @Test - void replaceEdgeIfMatchFail() throws InterruptedException, ExecutionException { - final BaseEdgeDocument doc = createEdgeValue(); - doc.addAttribute("a", "test"); - final EdgeEntity createResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).insertEdge(doc, null) - .get(); - doc.removeAttribute("a"); - 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) - .get(); - fail(); - } catch (final ExecutionException e) { - assertThat(e.getCause()).isInstanceOf(ArangoDBException.class); - } - } - - @Test - void updateEdge() throws InterruptedException, ExecutionException { - 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) - .get(); - 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).get(); - assertThat(updateResult).isNotNull(); - assertThat(updateResult.getId()).isEqualTo(createResult.getId()); - assertThat(updateResult.getRev()).isNotEqualTo(updateResult.getOldRev()); - assertThat(updateResult.getOldRev()).isEqualTo(createResult.getRev()); - - final BaseEdgeDocument readResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME) - .getEdge(createResult.getKey(), BaseEdgeDocument.class, null).get(); - assertThat(readResult.getKey()).isEqualTo(createResult.getKey()); - assertThat(readResult.getAttribute("a")).isNotNull(); - assertThat(String.valueOf(readResult.getAttribute("a"))).isEqualTo("test1"); - assertThat(readResult.getAttribute("b")).isNotNull(); - assertThat(String.valueOf(readResult.getAttribute("b"))).isEqualTo("test"); - assertThat(readResult.getRevision()).isEqualTo(updateResult.getRev()); - assertThat(readResult.getProperties()).containsKey("c"); - } - - @Test - void updateEdgeIfMatch() throws InterruptedException, ExecutionException { - 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) - .get(); - 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).get(); - assertThat(updateResult).isNotNull(); - assertThat(updateResult.getId()).isEqualTo(createResult.getId()); - assertThat(updateResult.getRev()).isNotEqualTo(updateResult.getOldRev()); - assertThat(updateResult.getOldRev()).isEqualTo(createResult.getRev()); - - final BaseEdgeDocument readResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME) - .getEdge(createResult.getKey(), BaseEdgeDocument.class, null).get(); - assertThat(readResult.getKey()).isEqualTo(createResult.getKey()); - assertThat(readResult.getAttribute("a")).isNotNull(); - assertThat(String.valueOf(readResult.getAttribute("a"))).isEqualTo("test1"); - assertThat(readResult.getAttribute("b")).isNotNull(); - assertThat(String.valueOf(readResult.getAttribute("b"))).isEqualTo("test"); - assertThat(readResult.getRevision()).isEqualTo(updateResult.getRev()); - assertThat(readResult.getProperties()).containsKey("c"); - } - - @Test - void updateEdgeIfMatchFail() throws InterruptedException, ExecutionException { - 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) - .get(); - 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) - .get(); - fail(); - } catch (final ExecutionException e) { - assertThat(e.getCause()).isInstanceOf(ArangoDBException.class); - } - } - - @Test - void updateEdgeKeepNullTrue() throws InterruptedException, ExecutionException { - final BaseEdgeDocument doc = createEdgeValue(); - doc.addAttribute("a", "test"); - final EdgeEntity createResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).insertEdge(doc, null) - .get(); - 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).get(); - assertThat(updateResult).isNotNull(); - assertThat(updateResult.getId()).isEqualTo(createResult.getId()); - assertThat(updateResult.getRev()).isNotEqualTo(updateResult.getOldRev()); - assertThat(updateResult.getOldRev()).isEqualTo(createResult.getRev()); - - final BaseEdgeDocument readResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME) - .getEdge(createResult.getKey(), BaseEdgeDocument.class, null).get(); - assertThat(readResult.getKey()).isEqualTo(createResult.getKey()); - assertThat(readResult.getProperties().keySet()).hasSize(6); - assertThat(readResult.getProperties()).containsKey("a"); - } - - @Test - void updateEdgeKeepNullFalse() throws InterruptedException, ExecutionException { - final BaseEdgeDocument doc = createEdgeValue(); - doc.addAttribute("a", "test"); - final EdgeEntity createResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).insertEdge(doc, null) - .get(); - 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).get(); - assertThat(updateResult).isNotNull(); - assertThat(updateResult.getId()).isEqualTo(createResult.getId()); - assertThat(updateResult.getRev()).isNotEqualTo(updateResult.getOldRev()); - assertThat(updateResult.getOldRev()).isEqualTo(createResult.getRev()); - - final BaseEdgeDocument readResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME) - .getEdge(createResult.getKey(), BaseEdgeDocument.class, null).get(); - assertThat(readResult.getKey()).isEqualTo(createResult.getKey()); - assertThat(readResult.getId()).isEqualTo(createResult.getId()); - assertThat(readResult.getRevision()).isNotNull(); - assertThat(readResult.getProperties().keySet()).doesNotContain("a"); - } - - @Test - void deleteEdge() throws InterruptedException, ExecutionException { - final BaseEdgeDocument doc = createEdgeValue(); - final EdgeEntity createResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).insertEdge(doc, null) - .get(); - db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).deleteEdge(createResult.getKey(), null).get(); - BaseEdgeDocument res = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME) - .getEdge(createResult.getKey(), BaseEdgeDocument.class, new GraphDocumentReadOptions()).get(); - assertThat(res).isNull(); - } - - @Test - void deleteEdgeIfMatch() throws InterruptedException, ExecutionException { - final BaseEdgeDocument doc = createEdgeValue(); - final EdgeEntity createResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).insertEdge(doc, null) - .get(); - final EdgeDeleteOptions options = new EdgeDeleteOptions().ifMatch(createResult.getRev()); - db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).deleteEdge(createResult.getKey(), options).get(); - BaseEdgeDocument res = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME) - .getEdge(createResult.getKey(), BaseEdgeDocument.class, new GraphDocumentReadOptions()).get(); - assertThat(res).isNull(); - } - - @Test - void deleteEdgeIfMatchFail() throws InterruptedException, ExecutionException { - final BaseEdgeDocument doc = createEdgeValue(); - final EdgeEntity createResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).insertEdge(doc, null) - .get(); - final EdgeDeleteOptions options = new EdgeDeleteOptions().ifMatch("no"); - try { - db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).deleteEdge(createResult.getKey(), options).get(); - fail(); - } catch (final ExecutionException e) { - assertThat(e.getCause()).isInstanceOf(ArangoDBException.class); - } - } -} diff --git a/driver/src/test/java/com/arangodb/async/ArangoGraphTest.java b/driver/src/test/java/com/arangodb/async/ArangoGraphTest.java deleted file mode 100644 index 1df01632d..000000000 --- a/driver/src/test/java/com/arangodb/async/ArangoGraphTest.java +++ /dev/null @@ -1,403 +0,0 @@ -/* - * DISCLAIMER - * - * Copyright 2016 ArangoDB GmbH, Cologne, Germany - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Copyright holder is ArangoDB GmbH, Cologne, Germany - */ - -package com.arangodb.async; - -import com.arangodb.entity.*; -import com.arangodb.model.EdgeCollectionDropOptions; -import com.arangodb.model.GraphCreateOptions; -import com.arangodb.model.VertexCollectionCreateOptions; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Iterator; -import java.util.concurrent.ExecutionException; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assumptions.assumeTrue; - -/** - * @author Mark Vollmary - */ -class ArangoGraphTest extends BaseTest { - - private static final String GRAPH_NAME = "db_collection_test"; - private static final String EDGE_COL_1 = "db_edge1_collection_test"; - private static final String EDGE_COL_2 = "db_edge2_collection_test"; - private static final String EDGE_COL_3 = "db_edge3_collection_test"; - private static final String VERTEX_COL_1 = "db_vertex1_collection_test"; - private static final String VERTEX_COL_2 = "db_vertex2_collection_test"; - private static final String VERTEX_COL_3 = "db_vertex3_collection_test"; - private static final String VERTEX_COL_4 = "db_vertex4_collection_test"; - private static final Integer REPLICATION_FACTOR = 2; - private static final Integer NUMBER_OF_SHARDS = 2; - - @BeforeAll - static void setup() throws InterruptedException, ExecutionException { - if (db.graph(GRAPH_NAME).exists().get()) { - db.graph(GRAPH_NAME).drop().get(); - } - 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)); - final GraphCreateOptions options = new GraphCreateOptions(); - if (arangoDB.getRole().get() != ServerRole.SINGLE) { - options.replicationFactor(REPLICATION_FACTOR).numberOfShards(NUMBER_OF_SHARDS); - } - db.createGraph(GRAPH_NAME, edgeDefinitions, options).get(); - } - - @AfterEach - void teardown() throws InterruptedException, ExecutionException { - for (final String collection : new String[]{EDGE_COL_1, EDGE_COL_2, VERTEX_COL_1, VERTEX_COL_2, VERTEX_COL_3, - VERTEX_COL_4}) { - final ArangoCollectionAsync c = db.collection(collection); - if (c.exists().get()) { - c.truncate().get(); - } - } - } - - @Test - void create() throws InterruptedException, ExecutionException { - try { - final GraphEntity result = db.graph(GRAPH_NAME + "_1").create(null).get(); - assertThat(result).isNotNull(); - assertThat(result.getName()).isEqualTo(GRAPH_NAME + "_1"); - } finally { - db.graph(GRAPH_NAME + "_1").drop().get(); - } - } - - @Test - void createWithReplicationAndWriteConcern() throws ExecutionException, InterruptedException { - assumeTrue(isAtLeastVersion(3, 5)); - assumeTrue(isCluster()); - final Collection edgeDefinitions = new ArrayList<>(); - final GraphEntity graph = db.createGraph(GRAPH_NAME + "_1", edgeDefinitions, - new GraphCreateOptions().isSmart(true).replicationFactor(2).writeConcern(2)).get(); - assertThat(graph).isNotNull(); - assertThat(graph.getName()).isEqualTo(GRAPH_NAME + "_1"); - assertThat(graph.getWriteConcern()).isEqualTo(2); - assertThat(graph.getReplicationFactor().getValue()).isEqualTo(2); - db.graph(GRAPH_NAME + "_1").drop(); - } - - @Test - void getGraphs() throws InterruptedException, ExecutionException { - final Collection graphs = db.getGraphs().get(); - assertThat(graphs).isNotNull(); - assertThat(graphs).isNotEmpty(); - } - - @Test - void getInfo() throws InterruptedException, ExecutionException { - final GraphEntity info = db.graph(GRAPH_NAME).getInfo().get(); - assertThat(info).isNotNull(); - assertThat(info.getName()).isEqualTo(GRAPH_NAME); - assertThat(info.getEdgeDefinitions()).hasSize(2); - final Iterator iterator = info.getEdgeDefinitions().iterator(); - final EdgeDefinition e1 = iterator.next(); - assertThat(e1.getCollection()).isEqualTo(EDGE_COL_1); - assertThat(e1.getFrom()).contains(VERTEX_COL_1); - assertThat(e1.getTo()).contains(VERTEX_COL_2); - final EdgeDefinition e2 = iterator.next(); - assertThat(e2.getCollection()).isEqualTo(EDGE_COL_2); - assertThat(e2.getFrom()).contains(VERTEX_COL_2); - assertThat(e2.getTo()).contains(VERTEX_COL_1, VERTEX_COL_3); - assertThat(info.getOrphanCollections()).isEmpty(); - - if (isCluster()) { - for (final String collection : new String[]{VERTEX_COL_1, VERTEX_COL_2}) { - final CollectionPropertiesEntity properties = db.collection(collection).getProperties().get(); - assertThat(properties.getReplicationFactor().getValue()).isEqualTo(REPLICATION_FACTOR); - assertThat(properties.getNumberOfShards()).isEqualTo(NUMBER_OF_SHARDS); - } - for (final String collection : new String[]{EDGE_COL_1, EDGE_COL_2}) { - final CollectionPropertiesEntity properties = db.collection(collection).getProperties().get(); - assertThat(properties.getReplicationFactor().getValue()).isEqualTo(REPLICATION_FACTOR); - } - } - } - - @Test - void getVertexCollections() throws InterruptedException, ExecutionException { - final Collection vertexCollections = db.graph(GRAPH_NAME).getVertexCollections().get(); - assertThat(vertexCollections).isNotNull(); - assertThat(vertexCollections).hasSize(3); - assertThat(vertexCollections).contains(VERTEX_COL_1, VERTEX_COL_2, VERTEX_COL_3); - } - - @Test - void addVertexCollection() throws InterruptedException, ExecutionException { - final GraphEntity graph = db.graph(GRAPH_NAME).addVertexCollection(VERTEX_COL_4).get(); - assertThat(graph).isNotNull(); - final Collection vertexCollections = db.graph(GRAPH_NAME).getVertexCollections().get(); - assertThat(vertexCollections).contains(VERTEX_COL_1, VERTEX_COL_2, VERTEX_COL_3, VERTEX_COL_4); - setup(); - } - - @Test - void addSatelliteVertexCollection() throws ExecutionException, InterruptedException { - assumeTrue(isCluster()); - assumeTrue(isEnterprise()); - assumeTrue(isAtLeastVersion(3, 9)); - - String v1Name = "vertex-" + rnd(); - - ArangoGraphAsync g = db.graph(GRAPH_NAME + rnd()); - g.createGraph(null, new GraphCreateOptions().isSmart(true).smartGraphAttribute("test")).get(); - g.addVertexCollection(v1Name, new VertexCollectionCreateOptions().satellites(v1Name)).get(); - - Collection vertexCollections = g.getVertexCollections().get(); - assertThat(vertexCollections).contains(v1Name); - assertThat(db.collection(v1Name).getProperties().get().getReplicationFactor()).isEqualTo(ReplicationFactor.ofSatellite()); - - // revert - g.drop().get(); - } - - @Test - void getEdgeCollections() throws InterruptedException, ExecutionException { - final Collection edgeCollections = db.graph(GRAPH_NAME).getEdgeDefinitions().get(); - assertThat(edgeCollections).isNotNull(); - assertThat(edgeCollections).hasSize(2); - assertThat(edgeCollections).contains(EDGE_COL_1, EDGE_COL_2); - } - - @Test - void addEdgeDefinition() throws InterruptedException, ExecutionException { - final GraphEntity graph = db.graph(GRAPH_NAME) - .addEdgeDefinition(new EdgeDefinition().collection(EDGE_COL_3).from(VERTEX_COL_1).to(VERTEX_COL_2)) - .get(); - assertThat(graph).isNotNull(); - final Collection edgeDefinitions = graph.getEdgeDefinitions(); - assertThat(edgeDefinitions).hasSize(3); - int count = 0; - for (final EdgeDefinition e : edgeDefinitions) { - if (e.getCollection().equals(EDGE_COL_3)) { - count++; - } - } - assertThat(count).isEqualTo(1); - for (final EdgeDefinition e : edgeDefinitions) { - if (e.getCollection().equals(EDGE_COL_3)) { - assertThat(e.getFrom()).contains(VERTEX_COL_1); - assertThat(e.getTo()).contains(VERTEX_COL_2); - } - } - if (isCluster()) { - final CollectionPropertiesEntity properties = db.collection(EDGE_COL_3).getProperties().get(); - assertThat(properties.getReplicationFactor().getValue()).isEqualTo(REPLICATION_FACTOR); - assertThat(properties.getNumberOfShards()).isEqualTo(NUMBER_OF_SHARDS); - } - setup(); - } - - @Test - void addSatelliteEdgeDefinition() throws ExecutionException, InterruptedException { - assumeTrue(isCluster()); - assumeTrue(isEnterprise()); - assumeTrue(isAtLeastVersion(3, 9)); - - String eName = "edge-" + rnd(); - String v1Name = "vertex-" + rnd(); - String v2Name = "vertex-" + rnd(); - EdgeDefinition ed = new EdgeDefinition().collection(eName).from(v1Name).to(v2Name).satellites(v1Name); - - ArangoGraphAsync g = db.graph(GRAPH_NAME + rnd()); - g.createGraph(null, new GraphCreateOptions().isSmart(true).smartGraphAttribute("test")).get(); - g.addEdgeDefinition(ed).get(); - final GraphEntity ge = g.getInfo().get(); - assertThat(ge).isNotNull(); - final Collection edgeDefinitions = ge.getEdgeDefinitions(); - assertThat(edgeDefinitions).hasSize(1); - EdgeDefinition e = edgeDefinitions.iterator().next(); - assertThat(e.getCollection()).isEqualTo(eName); - assertThat(e.getFrom()).contains(v1Name); - assertThat(e.getTo()).contains(v2Name); - - assertThat(db.collection(v1Name).getProperties().get().getReplicationFactor()).isEqualTo(ReplicationFactor.ofSatellite()); - - // revert - g.drop().get(); - } - - @Test - void replaceEdgeDefinition() throws InterruptedException, ExecutionException { - final GraphEntity graph = db.graph(GRAPH_NAME) - .replaceEdgeDefinition(new EdgeDefinition().collection(EDGE_COL_1).from(VERTEX_COL_3).to(VERTEX_COL_4)) - .get(); - final Collection edgeDefinitions = graph.getEdgeDefinitions(); - assertThat(edgeDefinitions).hasSize(2); - int count = 0; - for (final EdgeDefinition e : edgeDefinitions) { - if (e.getCollection().equals(EDGE_COL_1)) { - count++; - } - } - assertThat(count).isEqualTo(1); - for (final EdgeDefinition e : edgeDefinitions) { - if (e.getCollection().equals(EDGE_COL_1)) { - assertThat(e.getFrom()).contains(VERTEX_COL_3); - assertThat(e.getTo()).contains(VERTEX_COL_4); - } - } - setup(); - } - - @Test - void removeEdgeDefinition() throws InterruptedException, ExecutionException { - db.graph(GRAPH_NAME).edgeCollection(EDGE_COL_1).drop().get(); - Collection edgeDefinitions = db.graph(GRAPH_NAME).getEdgeDefinitions().get(); - assertThat(edgeDefinitions).hasSize(1); - assertThat(edgeDefinitions.iterator().next()).isEqualTo(EDGE_COL_2); - assertThat(db.collection(EDGE_COL_1).exists().get()).isTrue(); - setup(); - } - - @Test - void removeEdgeDefinitionDropCollections() throws InterruptedException, ExecutionException { - db.graph(GRAPH_NAME).edgeCollection(EDGE_COL_1) - .drop(new EdgeCollectionDropOptions() - .dropCollections(true) - .waitForSync(true) - ).get(); - Collection edgeDefinitions = db.graph(GRAPH_NAME).getEdgeDefinitions().get(); - assertThat(edgeDefinitions).hasSize(1); - assertThat(edgeDefinitions.iterator().next()).isEqualTo(EDGE_COL_2); - assertThat(db.collection(EDGE_COL_1).exists().get()).isFalse(); - setup(); - } - - @Test - void smartGraph() throws InterruptedException, ExecutionException { - assumeTrue(isCluster()); - assumeTrue(isEnterprise()); - 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().get()) { - db.collection(collection).drop().get(); - } - } - 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)); - final GraphEntity graph = db.createGraph(GRAPH_NAME + "_smart", edgeDefinitions, - new GraphCreateOptions().isSmart(true).smartGraphAttribute("test").replicationFactor(REPLICATION_FACTOR) - .numberOfShards(NUMBER_OF_SHARDS)) - .get(); - assertThat(graph).isNotNull(); - assertThat(graph.getIsSmart()).isTrue(); - assertThat(graph.getSmartGraphAttribute()).isEqualTo("test"); - assertThat(graph.getNumberOfShards()).isEqualTo(2); - if (db.graph(GRAPH_NAME + "_smart").exists().get()) { - db.graph(GRAPH_NAME + "_smart").drop().get(); - } - } - - @Test - void hybridSmartGraph() throws ExecutionException, InterruptedException { - assumeTrue(isEnterprise()); - assumeTrue(isCluster()); - assumeTrue((isAtLeastVersion(3, 9))); - - final Collection edgeDefinitions = new ArrayList<>(); - String eName = "hybridSmartGraph-edge-" + rnd(); - String v1Name = "hybridSmartGraph-vertex-" + rnd(); - String v2Name = "hybridSmartGraph-vertex-" + rnd(); - edgeDefinitions.add(new EdgeDefinition().collection(eName).from(v1Name).to(v2Name)); - - String graphId = GRAPH_NAME + rnd(); - final GraphEntity g = db.createGraph(graphId, edgeDefinitions, new GraphCreateOptions() - .satellites(eName, v1Name) - .isSmart(true).smartGraphAttribute("test").replicationFactor(2).numberOfShards(2)).get(); - - assertThat(g).isNotNull(); - assertThat(g.getIsSmart()).isTrue(); - assertThat(g.getSmartGraphAttribute()).isEqualTo("test"); - assertThat(g.getNumberOfShards()).isEqualTo(2); - - assertThat(db.collection(eName).getProperties().get().getReplicationFactor()).isEqualTo(ReplicationFactor.ofSatellite()); - assertThat(db.collection(v1Name).getProperties().get().getReplicationFactor()).isEqualTo(ReplicationFactor.ofSatellite()); - assertThat(db.collection(v2Name).getProperties().get().getReplicationFactor().getValue()).isEqualTo(2); - } - - @Test - void hybridDisjointSmartGraph() throws ExecutionException, InterruptedException { - assumeTrue(isEnterprise()); - assumeTrue(isCluster()); - assumeTrue((isAtLeastVersion(3, 9))); - - final Collection edgeDefinitions = new ArrayList<>(); - String eName = "hybridDisjointSmartGraph-edge-" + rnd(); - String v1Name = "hybridDisjointSmartGraph-vertex-" + rnd(); - String v2Name = "hybridDisjointSmartGraph-vertex-" + rnd(); - edgeDefinitions.add(new EdgeDefinition().collection(eName).from(v1Name).to(v2Name)); - - String graphId = GRAPH_NAME + rnd(); - final GraphEntity g = db.createGraph(graphId, edgeDefinitions, new GraphCreateOptions() - .satellites(v1Name) - .isSmart(true).isDisjoint(true).smartGraphAttribute("test").replicationFactor(2).numberOfShards(2)).get(); - - assertThat(g).isNotNull(); - assertThat(g.getIsSmart()).isTrue(); - assertThat(g.getIsDisjoint()).isTrue(); - assertThat(g.getSmartGraphAttribute()).isEqualTo("test"); - assertThat(g.getNumberOfShards()).isEqualTo(2); - - assertThat(db.collection(v1Name).getProperties().get().getReplicationFactor()).isEqualTo(ReplicationFactor.ofSatellite()); - assertThat(db.collection(v2Name).getProperties().get().getReplicationFactor().getValue()).isEqualTo(2); - } - - @Test - void drop() throws InterruptedException, ExecutionException { - final String edgeCollection = "edge_drop"; - final String vertexCollection = "vertex_drop"; - final String graph = GRAPH_NAME + "_drop"; - final GraphEntity result = db.graph(graph).create(Collections - .singleton(new EdgeDefinition().collection(edgeCollection).from(vertexCollection).to(vertexCollection))) - .get(); - assertThat(result).isNotNull(); - db.graph(graph).drop().get(); - assertThat(db.collection(edgeCollection).exists().get()).isTrue(); - assertThat(db.collection(vertexCollection).exists().get()).isTrue(); - } - - @Test - void dropPlusDropCollections() throws InterruptedException, ExecutionException { - final String edgeCollection = "edge_dropC"; - final String vertexCollection = "vertex_dropC"; - final String graph = GRAPH_NAME + "_dropC"; - final GraphEntity result = db.graph(graph).create(Collections - .singleton(new EdgeDefinition().collection(edgeCollection).from(vertexCollection).to(vertexCollection))) - .get(); - assertThat(result).isNotNull(); - db.graph(graph).drop(true).get(); - assertThat(db.collection(edgeCollection).exists().get()).isFalse(); - assertThat(db.collection(vertexCollection).exists().get()).isFalse(); - } -} diff --git a/driver/src/test/java/com/arangodb/async/ArangoRouteTest.java b/driver/src/test/java/com/arangodb/async/ArangoRouteTest.java deleted file mode 100644 index 772e593f5..000000000 --- a/driver/src/test/java/com/arangodb/async/ArangoRouteTest.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * DISCLAIMER - * - * Copyright 2018 ArangoDB GmbH, Cologne, Germany - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Copyright holder is ArangoDB GmbH, Cologne, Germany - */ - -package com.arangodb.async; - -import com.arangodb.ArangoDBException; -import com.arangodb.entity.BaseDocument; -import com.arangodb.internal.ArangoRequestParam; -import org.junit.jupiter.api.Test; - -import java.util.UUID; -import java.util.concurrent.ExecutionException; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.fail; - -/** - * @author Mark Vollmary - */ -class ArangoRouteTest extends BaseTest { - - /* - @Test - void get() throws InterruptedException, ExecutionException { - final Response res = db.route("/_api/version").get().get(); - assertThat(res.getBody().get("version").isString()).isEqualTo(true); - }*/ - - /* - @Test - void withHeader() throws InterruptedException, ExecutionException { - final ArangoCollectionAsync collection = db.collection("route-test-col"); - try { - collection.create(); - final BaseDocument doc = new BaseDocument(UUID.randomUUID().toString()); - collection.insertDocument(doc).get(); - db.route("/_api/document", doc.getId()).withHeader(ArangoRequestParam.IF_NONE_MATCH, doc.getRevision()) - .get().get(); - fail(); - } catch (final ExecutionException e) { - assertThat(e.getCause() instanceof ArangoDBException).isEqualTo(true); - } finally { - collection.drop(); - } - } - */ - - @Test - void withParentHeader() throws InterruptedException, ExecutionException { - final ArangoCollectionAsync collection = db.collection("route-test-col"); - try { - collection.create().get(); - final BaseDocument doc = new BaseDocument(UUID.randomUUID().toString()); - collection.insertDocument(doc).get(); - db.route("/_api/document").withHeader(ArangoRequestParam.IF_NONE_MATCH, doc.getRevision()) - .route(doc.getId()).get().get(); - fail(); - } catch (final ExecutionException e) { - assertThat(e.getCause()).isInstanceOf(ArangoDBException.class); - } - collection.drop().get(); - } - -} diff --git a/driver/src/test/java/com/arangodb/async/ArangoSearchTest.java b/driver/src/test/java/com/arangodb/async/ArangoSearchTest.java deleted file mode 100644 index 84dc1ba01..000000000 --- a/driver/src/test/java/com/arangodb/async/ArangoSearchTest.java +++ /dev/null @@ -1,551 +0,0 @@ -/* - * DISCLAIMER - * - * Copyright 2018 ArangoDB GmbH, Cologne, Germany - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Copyright holder is ArangoDB GmbH, Cologne, Germany - */ - -package com.arangodb.async; - -import com.arangodb.ArangoDBException; -import com.arangodb.entity.InvertedIndexField; -import com.arangodb.entity.ViewEntity; -import com.arangodb.entity.ViewType; -import com.arangodb.entity.arangosearch.*; -import com.arangodb.entity.arangosearch.analyzer.*; -import com.arangodb.model.InvertedIndexOptions; -import com.arangodb.model.arangosearch.*; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; - -import java.util.Collection; -import java.util.HashSet; -import java.util.Set; -import java.util.UUID; -import java.util.concurrent.ExecutionException; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.fail; -import static org.junit.jupiter.api.Assumptions.assumeTrue; - -/** - * @author Mark Vollmary - */ - -class ArangoSearchTest extends BaseTest { - - private static final String VIEW_NAME = "view_test"; - private static final String COLL_1 = "view_update_prop_test_collection"; - private static final String COLL_2 = "view_replace_prop_test_collection"; - - @BeforeAll - static void setup() throws InterruptedException, ExecutionException { - if (!isAtLeastVersion(arangoDB, 3, 4)) - return; - db.createArangoSearch(VIEW_NAME, new ArangoSearchCreateOptions()).get(); - db.createCollection(COLL_1).get(); - db.createCollection(COLL_2).get(); - } - - @Test - void exists() throws InterruptedException, ExecutionException { - assumeTrue(isAtLeastVersion(3, 4)); - assertThat(db.arangoSearch(VIEW_NAME).exists().get()).isTrue(); - } - - @Test - void createAndExistsSearchAlias() throws ExecutionException, InterruptedException { - assumeTrue(isAtLeastVersion(3, 10)); - String viewName = "view-" + rnd(); - db.createSearchAlias(viewName, new SearchAliasCreateOptions()).get(); - assertThat(db.arangoSearch(viewName).exists().get()).isTrue(); - } - - @Test - void getInfo() throws InterruptedException, ExecutionException { - assumeTrue(isAtLeastVersion(3, 4)); - final ViewEntity info = db.arangoSearch(VIEW_NAME).getInfo().get(); - assertThat(info).isNotNull(); - assertThat(info.getId()).isNotNull(); - assertThat(info.getName()).isEqualTo(VIEW_NAME); - assertThat(info.getType()).isEqualTo(ViewType.ARANGO_SEARCH); - } - - @Test - void drop() throws InterruptedException, ExecutionException { - assumeTrue(isAtLeastVersion(3, 4)); - final String name = VIEW_NAME + "_droptest"; - db.createArangoSearch(name, new ArangoSearchCreateOptions()).get(); - final ArangoViewAsync view = db.arangoSearch(name); - view.drop().get(); - assertThat(view.exists().get()).isFalse(); - } - - @Test - void rename() throws InterruptedException, ExecutionException { - assumeTrue(isSingleServer()); - assumeTrue(isAtLeastVersion(3, 4)); - final String name = VIEW_NAME + "_renametest"; - final String newName = name + "_new"; - db.createArangoSearch(name, new ArangoSearchCreateOptions()).get(); - db.arangoSearch(name).rename(newName).get(); - assertThat(db.arangoSearch(name).exists().get()).isFalse(); - assertThat(db.arangoSearch(newName).exists().get()).isTrue(); - } - - @Test - void createArangoSearchView() throws InterruptedException, ExecutionException { - assumeTrue(isAtLeastVersion(3, 4)); - final String name = VIEW_NAME + "_createtest"; - final ViewEntity info = db.arangoSearch(name).create().get(); - assertThat(info).isNotNull(); - assertThat(info.getId()).isNotNull(); - assertThat(info.getName()).isEqualTo(name); - assertThat(info.getType()).isEqualTo(ViewType.ARANGO_SEARCH); - assertThat(db.arangoSearch(name).exists().get()).isTrue(); - } - - @Test - void createSearchAliasView() throws ExecutionException, InterruptedException { - assumeTrue(isAtLeastVersion(3, 10)); - String viewName = "view-" + rnd(); - final ViewEntity info = db.searchAlias(viewName).create().get(); - assertThat(info).isNotNull(); - assertThat(info.getId()).isNotNull(); - assertThat(info.getName()).isEqualTo(viewName); - assertThat(info.getType()).isEqualTo(ViewType.SEARCH_ALIAS); - assertThat(db.searchAlias(viewName).exists().get()).isTrue(); - } - - @Test - void createArangoSearchViewWithOptions() throws InterruptedException, ExecutionException { - assumeTrue(isAtLeastVersion(3, 4)); - final String name = VIEW_NAME + "_createtest_withotpions"; - final ViewEntity info = db.arangoSearch(name).create(new ArangoSearchCreateOptions()).get(); - assertThat(info).isNotNull(); - assertThat(info.getId()).isNotNull(); - assertThat(info.getName()).isEqualTo(name); - assertThat(info.getType()).isEqualTo(ViewType.ARANGO_SEARCH); - assertThat(db.arangoSearch(name).exists().get()).isTrue(); - } - - @Test - void createArangoSearchViewWithPrimarySort() throws ExecutionException, InterruptedException { - assumeTrue(isAtLeastVersion(3, 5)); - final String name = "createWithPrimarySort"; - 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(name).create(options).get(); - assertThat(info).isNotNull(); - assertThat(info.getId()).isNotNull(); - assertThat(info.getName()).isEqualTo(name); - assertThat(info.getType()).isEqualTo(ViewType.ARANGO_SEARCH); - assertThat(db.arangoSearch(name).exists().get()).isTrue(); - } - - @Test - void createArangoSearchViewWithCommitIntervalMsec() throws ExecutionException, InterruptedException { - assumeTrue(isAtLeastVersion(3, 5)); - final String name = "createWithCommitIntervalMsec"; - final ArangoSearchCreateOptions options = new ArangoSearchCreateOptions(); - options.commitIntervalMsec(666666L); - - final ViewEntity info = db.arangoSearch(name).create(options).get(); - assertThat(info).isNotNull(); - assertThat(info.getId()).isNotNull(); - assertThat(info.getName()).isEqualTo(name); - assertThat(info.getType()).isEqualTo(ViewType.ARANGO_SEARCH); - assertThat(db.arangoSearch(name).exists().get()).isTrue(); - - // check commit interval msec property - final ArangoSearchAsync view = db.arangoSearch(name); - final ArangoSearchPropertiesEntity properties = view.getProperties().get(); - assertThat(properties.getCommitIntervalMsec()).isEqualTo(666666L); - } - - @Test - void createSearchAliasViewWithOptions() throws ExecutionException, InterruptedException { - assumeTrue(isAtLeastVersion(3, 10)); - String viewName = "view-" + rnd(); - final SearchAliasCreateOptions options = new SearchAliasCreateOptions(); - final ViewEntity info = db.searchAlias(viewName).create(options).get(); - assertThat(info).isNotNull(); - assertThat(info.getId()).isNotNull(); - assertThat(info.getName()).isEqualTo(viewName); - assertThat(info.getType()).isEqualTo(ViewType.SEARCH_ALIAS); - assertThat(db.searchAlias(viewName).exists().get()).isTrue(); - } - - @Test - void createSearchAliasViewWithIndexesAndGetProperties() throws ExecutionException, InterruptedException { - assumeTrue(isAtLeastVersion(3, 10)); - ArangoCollectionAsync col = db.collection(COLL_1); - String idxName = "idx-" + rnd(); - col.ensureInvertedIndex(new InvertedIndexOptions() - .name(idxName) - .fields(new InvertedIndexField().name("a" + rnd()))) - .get(); - String viewName = "view-" + rnd(); - final SearchAliasCreateOptions options = new SearchAliasCreateOptions() - .indexes(new SearchAliasIndex(COLL_1, idxName)); - final ViewEntity info = db.searchAlias(viewName).create(options).get(); - assertThat(info).isNotNull(); - assertThat(info.getId()).isNotNull(); - assertThat(info.getName()).isEqualTo(viewName); - assertThat(info.getType()).isEqualTo(ViewType.SEARCH_ALIAS); - - final SearchAliasPropertiesEntity properties = db.searchAlias(viewName).getProperties().get(); - assertThat(properties).isNotNull(); - assertThat(properties.getId()).isNotNull(); - assertThat(properties.getName()).isEqualTo(viewName); - assertThat(properties.getType()).isEqualTo(ViewType.SEARCH_ALIAS); - assertThat(properties.getIndexes()) - .isNotNull() - .isNotEmpty() - .anyMatch(i -> i.getCollection().equals(COLL_1) && i.getIndex().equals(idxName)); - } - - @Test - void getArangoSearchViewProperties() throws InterruptedException, ExecutionException { - assumeTrue(isAtLeastVersion(3, 4)); - final String name = VIEW_NAME + "_getpropertiestest"; - final ArangoSearchAsync view = db.arangoSearch(name); - view.create(new ArangoSearchCreateOptions()).get(); - final ArangoSearchPropertiesEntity properties = view.getProperties().get(); - assertThat(properties).isNotNull(); - assertThat(properties.getId()).isNotNull(); - assertThat(properties.getName()).isEqualTo(name); - assertThat(properties.getType()).isEqualTo(ViewType.ARANGO_SEARCH); - assertThat(properties.getConsolidationIntervalMsec()).isNotNull(); - assertThat(properties.getCleanupIntervalStep()).isNotNull(); - final ConsolidationPolicy consolidate = properties.getConsolidationPolicy(); - assertThat(consolidate).isNotNull(); - final Collection links = properties.getLinks(); - assertThat(links).isEmpty(); - } - - @Test - void updateArangoSearchViewProperties() throws InterruptedException, ExecutionException { - assumeTrue(isAtLeastVersion(3, 4)); - final String name = VIEW_NAME + "_updatepropertiestest"; - final ArangoSearchAsync view = db.arangoSearch(name); - view.create(new ArangoSearchCreateOptions()).get(); - 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).get(); - assertThat(properties).isNotNull(); - assertThat(properties.getCleanupIntervalStep()).isEqualTo(15L); - assertThat(properties.getConsolidationIntervalMsec()).isEqualTo(65000L); - final ConsolidationPolicy consolidate = properties.getConsolidationPolicy(); - assertThat(consolidate).isNotNull(); - assertThat(consolidate.getType()).isEqualTo(ConsolidationType.BYTES_ACCUM); - assertThat(consolidate.getThreshold()).isEqualTo(1.); - assertThat(properties.getLinks()).hasSize(1); - final CollectionLink link = properties.getLinks().iterator().next(); - assertThat(link.getName()).isEqualTo("view_update_prop_test_collection"); - assertThat(link.getFields()).hasSize(1); - final FieldLink next = link.getFields().iterator().next(); - assertThat(next.getName()).isEqualTo("value"); - assertThat(next.getIncludeAllFields()).isTrue(); - assertThat(next.getTrackListPositions()).isTrue(); - assertThat(next.getStoreValues()).isEqualTo(StoreValuesType.ID); - } - - @Test - void updateSearchAliasViewWithIndexesAndGetProperties() throws ExecutionException, InterruptedException { - assumeTrue(isAtLeastVersion(3, 10)); - ArangoCollectionAsync col = db.collection(COLL_1); - String idxName = "idx-" + rnd(); - col.ensureInvertedIndex(new InvertedIndexOptions() - .name(idxName) - .fields(new InvertedIndexField().name("a" + rnd()))) - .get(); - ArangoCollectionAsync col2 = db.collection(COLL_2); - String idxName2 = "idx-" + rnd(); - col2.ensureInvertedIndex(new InvertedIndexOptions() - .name(idxName2) - .fields(new InvertedIndexField().name("a" + rnd()))) - .get(); - - String viewName = "view-" + rnd(); - final SearchAliasCreateOptions options = new SearchAliasCreateOptions() - .indexes(new SearchAliasIndex(COLL_1, idxName)); - final ViewEntity info = db.searchAlias(viewName).create(options).get(); - db.searchAlias(viewName).updateProperties(new SearchAliasPropertiesOptions() - .indexes(new SearchAliasIndex(COLL_2, idxName2))).get(); - - assertThat(info).isNotNull(); - assertThat(info.getId()).isNotNull(); - assertThat(info.getName()).isEqualTo(viewName); - assertThat(info.getType()).isEqualTo(ViewType.SEARCH_ALIAS); - - final SearchAliasPropertiesEntity properties = db.searchAlias(viewName).getProperties().get(); - assertThat(properties).isNotNull(); - assertThat(properties.getId()).isNotNull(); - assertThat(properties.getName()).isEqualTo(viewName); - assertThat(properties.getType()).isEqualTo(ViewType.SEARCH_ALIAS); - assertThat(properties.getIndexes()) - .isNotNull() - .isNotEmpty() - .hasSize(2) - .anyMatch(i -> i.getCollection().equals(COLL_1) && i.getIndex().equals(idxName)) - .anyMatch(i -> i.getCollection().equals(COLL_2) && i.getIndex().equals(idxName2)); - } - - @Test - void replaceArangoSearchViewProperties() throws InterruptedException, ExecutionException { - assumeTrue(isAtLeastVersion(3, 4)); - final String name = VIEW_NAME + "_replacepropertiestest"; - final ArangoSearchAsync view = db.arangoSearch(name); - view.create(new ArangoSearchCreateOptions()).get(); - 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).get(); - assertThat(properties).isNotNull(); - assertThat(properties.getLinks()).hasSize(1); - final CollectionLink link = properties.getLinks().iterator().next(); - assertThat(link.getName()).isEqualTo("view_replace_prop_test_collection"); - assertThat(link.getFields()).hasSize(1); - assertThat(link.getFields().iterator().next().getName()).isEqualTo("value"); - } - - @Test - void replaceSearchAliasViewWithIndexesAndGetProperties() throws ExecutionException, InterruptedException { - assumeTrue(isAtLeastVersion(3, 10)); - ArangoCollectionAsync col = db.collection(COLL_1); - String idxName = "idx-" + rnd(); - col.ensureInvertedIndex(new InvertedIndexOptions() - .name(idxName) - .fields(new InvertedIndexField().name("a" + rnd()))) - .get(); - ArangoCollectionAsync col2 = db.collection(COLL_2); - String idxName2 = "idx-" + rnd(); - col2.ensureInvertedIndex(new InvertedIndexOptions() - .name(idxName2) - .fields(new InvertedIndexField().name("a" + rnd()))) - .get(); - - String viewName = "view-" + rnd(); - final SearchAliasCreateOptions options = new SearchAliasCreateOptions() - .indexes(new SearchAliasIndex(COLL_1, idxName)); - final ViewEntity info = db.searchAlias(viewName).create(options).get(); - db.searchAlias(viewName).replaceProperties(new SearchAliasPropertiesOptions() - .indexes(new SearchAliasIndex(COLL_2, idxName2))).get(); - - assertThat(info).isNotNull(); - assertThat(info.getId()).isNotNull(); - assertThat(info.getName()).isEqualTo(viewName); - assertThat(info.getType()).isEqualTo(ViewType.SEARCH_ALIAS); - - final SearchAliasPropertiesEntity properties = db.searchAlias(viewName).getProperties().get(); - assertThat(properties).isNotNull(); - assertThat(properties.getId()).isNotNull(); - assertThat(properties.getName()).isEqualTo(viewName); - assertThat(properties.getType()).isEqualTo(ViewType.SEARCH_ALIAS); - assertThat(properties.getIndexes()) - .isNotNull() - .isNotEmpty() - .hasSize(1) - .anyMatch(i -> i.getCollection().equals(COLL_2) && i.getIndex().equals(idxName2)); - } - - private void createGetAndDeleteTypedAnalyzer(SearchAnalyzer analyzer) throws ExecutionException, - InterruptedException { - - String fullyQualifiedName = db.dbName().get() + "::" + analyzer.getName(); - analyzer.setName(fullyQualifiedName); - - // createAnalyzer - SearchAnalyzer createdAnalyzer = db.createSearchAnalyzer(analyzer).get(); - assertThat(createdAnalyzer).isEqualTo(analyzer); - - // getAnalyzer - SearchAnalyzer gotAnalyzer = db.getSearchAnalyzer(analyzer.getName()).get(); - assertThat(gotAnalyzer).isEqualTo(analyzer); - - // getAnalyzers - SearchAnalyzer foundAnalyzer = - db.getSearchAnalyzers().get().stream().filter(it -> it.getName().equals(fullyQualifiedName)) - .findFirst().get(); - assertThat(foundAnalyzer).isEqualTo(analyzer); - - // deleteAnalyzer - AnalyzerDeleteOptions deleteOptions = new AnalyzerDeleteOptions(); - deleteOptions.setForce(true); - - db.deleteSearchAnalyzer(analyzer.getName(), deleteOptions).get(); - - try { - db.getSearchAnalyzer(analyzer.getName()).get(); - fail("deleted analyzer should not be found!"); - } catch (ExecutionException e) { - assertThat(e.getCause()).isInstanceOf(ArangoDBException.class); - assertThat(((ArangoDBException) e.getCause()).getResponseCode()).isEqualTo(404); - assertThat(((ArangoDBException) e.getCause()).getErrorNum()).isEqualTo(1202); - } - - } - - @Test - void identityAnalyzerTyped() throws ExecutionException, InterruptedException { - assumeTrue(isAtLeastVersion(3, 5)); - - String name = "test-" + UUID.randomUUID(); - - Set features = new HashSet<>(); - features.add(AnalyzerFeature.frequency); - features.add(AnalyzerFeature.norm); - features.add(AnalyzerFeature.position); - - IdentityAnalyzer analyzer = new IdentityAnalyzer(); - analyzer.setFeatures(features); - analyzer.setName(name); - - createGetAndDeleteTypedAnalyzer(analyzer); - } - - @Test - void delimiterAnalyzerTyped() throws ExecutionException, InterruptedException { - assumeTrue(isAtLeastVersion(3, 5)); - - String name = "test-" + UUID.randomUUID(); - - Set features = new HashSet<>(); - features.add(AnalyzerFeature.frequency); - features.add(AnalyzerFeature.norm); - features.add(AnalyzerFeature.position); - - DelimiterAnalyzerProperties properties = new DelimiterAnalyzerProperties(); - properties.setDelimiter("-"); - - DelimiterAnalyzer analyzer = new DelimiterAnalyzer(); - analyzer.setFeatures(features); - analyzer.setName(name); - analyzer.setProperties(properties); - - createGetAndDeleteTypedAnalyzer(analyzer); - } - - @Test - void stemAnalyzerTyped() throws ExecutionException, InterruptedException { - assumeTrue(isAtLeastVersion(3, 5)); - - String name = "test-" + UUID.randomUUID(); - - Set features = new HashSet<>(); - features.add(AnalyzerFeature.frequency); - features.add(AnalyzerFeature.norm); - features.add(AnalyzerFeature.position); - - StemAnalyzerProperties properties = new StemAnalyzerProperties(); - properties.setLocale("ru"); - - StemAnalyzer options = new StemAnalyzer(); - options.setFeatures(features); - options.setName(name); - options.setProperties(properties); - - createGetAndDeleteTypedAnalyzer(options); - } - - @Test - void normAnalyzerTyped() throws ExecutionException, InterruptedException { - assumeTrue(isAtLeastVersion(3, 5)); - - String name = "test-" + UUID.randomUUID(); - - Set features = new HashSet<>(); - features.add(AnalyzerFeature.frequency); - features.add(AnalyzerFeature.norm); - features.add(AnalyzerFeature.position); - - NormAnalyzerProperties properties = new NormAnalyzerProperties(); - properties.setLocale("ru"); - properties.setAnalyzerCase(SearchAnalyzerCase.lower); - properties.setAccent(true); - - NormAnalyzer options = new NormAnalyzer(); - options.setFeatures(features); - options.setName(name); - options.setProperties(properties); - - createGetAndDeleteTypedAnalyzer(options); - } - - @Test - void ngramAnalyzerTyped() throws ExecutionException, InterruptedException { - assumeTrue(isAtLeastVersion(3, 5)); - - String name = "test-" + UUID.randomUUID(); - - Set features = new HashSet<>(); - features.add(AnalyzerFeature.frequency); - features.add(AnalyzerFeature.norm); - features.add(AnalyzerFeature.position); - - NGramAnalyzerProperties properties = new NGramAnalyzerProperties(); - properties.setMax(6L); - properties.setMin(3L); - properties.setPreserveOriginal(true); - - NGramAnalyzer analyzer = new NGramAnalyzer(); - analyzer.setFeatures(features); - analyzer.setName(name); - analyzer.setType(AnalyzerType.ngram); - analyzer.setProperties(properties); - - createGetAndDeleteTypedAnalyzer(analyzer); - } - - @Test - void textAnalyzerTyped() throws ExecutionException, InterruptedException { - assumeTrue(isAtLeastVersion(3, 5)); - - String name = "test-" + UUID.randomUUID(); - - Set features = new HashSet<>(); - features.add(AnalyzerFeature.frequency); - features.add(AnalyzerFeature.norm); - features.add(AnalyzerFeature.position); - - TextAnalyzerProperties properties = new TextAnalyzerProperties(); - properties.setLocale("ru"); - properties.setAnalyzerCase(SearchAnalyzerCase.lower); - properties.setAccent(true); - properties.setStemming(true); - - TextAnalyzer analyzer = new TextAnalyzer(); - analyzer.setFeatures(features); - analyzer.setName(name); - analyzer.setType(AnalyzerType.text); - analyzer.setProperties(properties); - - createGetAndDeleteTypedAnalyzer(analyzer); - } - -} diff --git a/driver/src/test/java/com/arangodb/async/ArangoVertexCollectionTest.java b/driver/src/test/java/com/arangodb/async/ArangoVertexCollectionTest.java deleted file mode 100644 index ea75787dd..000000000 --- a/driver/src/test/java/com/arangodb/async/ArangoVertexCollectionTest.java +++ /dev/null @@ -1,375 +0,0 @@ -/* - * DISCLAIMER - * - * Copyright 2016 ArangoDB GmbH, Cologne, Germany - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Copyright holder is ArangoDB GmbH, Cologne, Germany - */ - -package com.arangodb.async; - -import com.arangodb.ArangoDBException; -import com.arangodb.entity.BaseDocument; -import com.arangodb.entity.VertexEntity; -import com.arangodb.entity.VertexUpdateEntity; -import com.arangodb.model.*; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; - -import java.util.Collection; -import java.util.UUID; -import java.util.concurrent.ExecutionException; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.fail; - -/** - * @author Mark Vollmary - */ -class ArangoVertexCollectionTest extends BaseTest { - - private static final String GRAPH_NAME = "db_collection_test"; - private static final String COLLECTION_NAME = "db_vertex_collection_test"; - - @BeforeAll - static void setup() throws InterruptedException, ExecutionException { - initCollections(); - final GraphCreateOptions options = new GraphCreateOptions().orphanCollections(COLLECTION_NAME); - db.createGraph(GRAPH_NAME, null, options).get(); - } - - private static void initCollections() throws ExecutionException, InterruptedException { - if (!db.collection(COLLECTION_NAME).exists().get()) { - db.createCollection(COLLECTION_NAME, null).get(); - } - } - - @AfterEach - void teardown() throws InterruptedException, ExecutionException { - db.collection(COLLECTION_NAME).truncate().get(); - } - - @Test - void dropVertexCollection() throws InterruptedException, ExecutionException { - db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME).drop().get(); - final Collection vertexCollections = db.graph(GRAPH_NAME).getVertexCollections().get(); - assertThat(vertexCollections).doesNotContain(COLLECTION_NAME); - - // revert - db.graph(GRAPH_NAME).addVertexCollection(COLLECTION_NAME).get(); - } - - @Test - void dropVertexCollectionDropCollectionTrue() throws InterruptedException, ExecutionException { - db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME).drop(new VertexCollectionDropOptions().dropCollection(true)).get(); - final Collection vertexCollections = db.graph(GRAPH_NAME).getVertexCollections().get(); - assertThat(vertexCollections).doesNotContain(COLLECTION_NAME); - assertThat(db.collection(COLLECTION_NAME).exists().get()).isFalse(); - - // revert - initCollections(); - db.graph(GRAPH_NAME).addVertexCollection(COLLECTION_NAME).get(); - } - - @Test - void insertVertex() throws InterruptedException, ExecutionException { - final VertexEntity vertex = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) - .insertVertex(new BaseDocument(), null).get(); - assertThat(vertex).isNotNull(); - final BaseDocument document = db.collection(COLLECTION_NAME) - .getDocument(vertex.getKey(), BaseDocument.class, null).get(); - assertThat(document).isNotNull(); - assertThat(document.getKey()).isEqualTo(vertex.getKey()); - } - - @Test - void getVertex() throws InterruptedException, ExecutionException { - final VertexEntity vertex = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) - .insertVertex(new BaseDocument(), null).get(); - final BaseDocument document = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) - .getVertex(vertex.getKey(), BaseDocument.class, null).get(); - assertThat(document).isNotNull(); - assertThat(document.getKey()).isEqualTo(vertex.getKey()); - } - - @Test - void getVertexIfMatch() throws InterruptedException, ExecutionException { - final VertexEntity vertex = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) - .insertVertex(new BaseDocument(), null).get(); - final GraphDocumentReadOptions options = new GraphDocumentReadOptions().ifMatch(vertex.getRev()); - final BaseDocument document = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) - .getVertex(vertex.getKey(), BaseDocument.class, options).get(); - assertThat(document).isNotNull(); - assertThat(document.getKey()).isEqualTo(vertex.getKey()); - } - - @Test - void getVertexIfMatchFail() throws InterruptedException, ExecutionException { - final VertexEntity vertex = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) - .insertVertex(new BaseDocument(), null).get(); - final GraphDocumentReadOptions options = new GraphDocumentReadOptions().ifMatch("no"); - BaseDocument res = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) - .getVertex(vertex.getKey(), BaseDocument.class, options).get(); - assertThat(res).isNull(); - } - - @Test - void getVertexIfNoneMatch() throws InterruptedException, ExecutionException { - final VertexEntity vertex = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) - .insertVertex(new BaseDocument(), null).get(); - final GraphDocumentReadOptions options = new GraphDocumentReadOptions().ifNoneMatch("no"); - final BaseDocument document = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) - .getVertex(vertex.getKey(), BaseDocument.class, options).get(); - assertThat(document).isNotNull(); - assertThat(document.getKey()).isEqualTo(vertex.getKey()); - } - - @Test - void getVertexIfNoneMatchFail() throws InterruptedException, ExecutionException { - final VertexEntity vertex = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) - .insertVertex(new BaseDocument(), null).get(); - final GraphDocumentReadOptions options = new GraphDocumentReadOptions().ifNoneMatch(vertex.getRev()); - BaseDocument res = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) - .getVertex(vertex.getKey(), BaseDocument.class, options).get(); - assertThat(res).isNull(); - } - - @Test - void replaceVertex() throws InterruptedException, ExecutionException { - final BaseDocument doc = new BaseDocument(UUID.randomUUID().toString()); - doc.addAttribute("a", "test"); - final VertexEntity createResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME).insertVertex(doc, null) - .get(); - doc.removeAttribute("a"); - doc.addAttribute("b", "test"); - final VertexUpdateEntity replaceResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) - .replaceVertex(createResult.getKey(), doc, null).get(); - assertThat(replaceResult).isNotNull(); - assertThat(replaceResult.getId()).isEqualTo(createResult.getId()); - assertThat(replaceResult.getRev()).isNotEqualTo(replaceResult.getOldRev()); - assertThat(replaceResult.getOldRev()).isEqualTo(createResult.getRev()); - - final BaseDocument readResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) - .getVertex(createResult.getKey(), BaseDocument.class, null).get(); - assertThat(readResult.getKey()).isEqualTo(createResult.getKey()); - assertThat(readResult.getRevision()).isEqualTo(replaceResult.getRev()); - assertThat(readResult.getProperties().keySet()).doesNotContain("a"); - assertThat(readResult.getAttribute("b")).isNotNull(); - assertThat(String.valueOf(readResult.getAttribute("b"))).isEqualTo("test"); - } - - @Test - void replaceVertexIfMatch() throws InterruptedException, ExecutionException { - final BaseDocument doc = new BaseDocument(UUID.randomUUID().toString()); - doc.addAttribute("a", "test"); - final VertexEntity createResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME).insertVertex(doc, null) - .get(); - doc.removeAttribute("a"); - 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).get(); - assertThat(replaceResult).isNotNull(); - assertThat(replaceResult.getId()).isEqualTo(createResult.getId()); - assertThat(replaceResult.getRev()).isNotEqualTo(replaceResult.getOldRev()); - assertThat(replaceResult.getOldRev()).isEqualTo(createResult.getRev()); - - final BaseDocument readResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) - .getVertex(createResult.getKey(), BaseDocument.class, null).get(); - assertThat(readResult.getKey()).isEqualTo(createResult.getKey()); - assertThat(readResult.getRevision()).isEqualTo(replaceResult.getRev()); - assertThat(readResult.getProperties().keySet()).doesNotContain("a"); - assertThat(readResult.getAttribute("b")).isNotNull(); - assertThat(String.valueOf(readResult.getAttribute("b"))).isEqualTo("test"); - } - - @Test - void replaceVertexIfMatchFail() throws InterruptedException, ExecutionException { - final BaseDocument doc = new BaseDocument(UUID.randomUUID().toString()); - doc.addAttribute("a", "test"); - final VertexEntity createResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME).insertVertex(doc, null) - .get(); - doc.removeAttribute("a"); - doc.addAttribute("b", "test"); - try { - final VertexReplaceOptions options = new VertexReplaceOptions().ifMatch("no"); - db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME).replaceVertex(createResult.getKey(), doc, options) - .get(); - fail(); - } catch (final ExecutionException e) { - assertThat(e.getCause()).isInstanceOf(ArangoDBException.class); - } - } - - @Test - void updateVertex() throws InterruptedException, ExecutionException { - final BaseDocument doc = new BaseDocument(UUID.randomUUID().toString()); - doc.addAttribute("a", "test"); - doc.addAttribute("c", "test"); - final VertexEntity createResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME).insertVertex(doc, null) - .get(); - 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).get(); - assertThat(updateResult).isNotNull(); - assertThat(updateResult.getId()).isEqualTo(createResult.getId()); - assertThat(updateResult.getRev()).isNotEqualTo(updateResult.getOldRev()); - assertThat(updateResult.getOldRev()).isEqualTo(createResult.getRev()); - - final BaseDocument readResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) - .getVertex(createResult.getKey(), BaseDocument.class, null).get(); - assertThat(readResult.getKey()).isEqualTo(createResult.getKey()); - assertThat(readResult.getAttribute("a")).isNotNull(); - assertThat(String.valueOf(readResult.getAttribute("a"))).isEqualTo("test1"); - assertThat(readResult.getAttribute("b")).isNotNull(); - assertThat(String.valueOf(readResult.getAttribute("b"))).isEqualTo("test"); - assertThat(readResult.getRevision()).isEqualTo(updateResult.getRev()); - assertThat(readResult.getProperties()).containsKey("c"); - } - - @Test - void updateVertexIfMatch() throws InterruptedException, ExecutionException { - final BaseDocument doc = new BaseDocument(UUID.randomUUID().toString()); - doc.addAttribute("a", "test"); - doc.addAttribute("c", "test"); - final VertexEntity createResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME).insertVertex(doc, null) - .get(); - 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).get(); - assertThat(updateResult).isNotNull(); - assertThat(updateResult.getId()).isEqualTo(createResult.getId()); - assertThat(updateResult.getRev()).isNotEqualTo(updateResult.getOldRev()); - assertThat(updateResult.getOldRev()).isEqualTo(createResult.getRev()); - - final BaseDocument readResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) - .getVertex(createResult.getKey(), BaseDocument.class, null).get(); - assertThat(readResult.getKey()).isEqualTo(createResult.getKey()); - assertThat(readResult.getAttribute("a")).isNotNull(); - assertThat(String.valueOf(readResult.getAttribute("a"))).isEqualTo("test1"); - assertThat(readResult.getAttribute("b")).isNotNull(); - assertThat(String.valueOf(readResult.getAttribute("b"))).isEqualTo("test"); - assertThat(readResult.getRevision()).isEqualTo(updateResult.getRev()); - assertThat(readResult.getProperties()).containsKey("c"); - } - - @Test - void updateVertexIfMatchFail() throws InterruptedException, ExecutionException { - final BaseDocument doc = new BaseDocument(UUID.randomUUID().toString()); - doc.addAttribute("a", "test"); - doc.addAttribute("c", "test"); - final VertexEntity createResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME).insertVertex(doc, null) - .get(); - 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) - .get(); - fail(); - } catch (final ExecutionException e) { - assertThat(e.getCause()).isInstanceOf(ArangoDBException.class); - } - } - - @Test - void updateVertexKeepNullTrue() throws InterruptedException, ExecutionException { - final BaseDocument doc = new BaseDocument(UUID.randomUUID().toString()); - doc.addAttribute("a", "test"); - final VertexEntity createResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME).insertVertex(doc, null) - .get(); - 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).get(); - assertThat(updateResult).isNotNull(); - assertThat(updateResult.getId()).isEqualTo(createResult.getId()); - assertThat(updateResult.getRev()).isNotEqualTo(updateResult.getOldRev()); - assertThat(updateResult.getOldRev()).isEqualTo(createResult.getRev()); - - final BaseDocument readResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) - .getVertex(createResult.getKey(), BaseDocument.class, null).get(); - assertThat(readResult.getKey()).isEqualTo(createResult.getKey()); - assertThat(readResult.getProperties().keySet()).hasSize(4); - assertThat(readResult.getProperties()).containsKey("a"); - } - - @Test - void updateVertexKeepNullFalse() throws InterruptedException, ExecutionException { - final BaseDocument doc = new BaseDocument(UUID.randomUUID().toString()); - doc.addAttribute("a", "test"); - final VertexEntity createResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME).insertVertex(doc, null) - .get(); - 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).get(); - assertThat(updateResult).isNotNull(); - assertThat(updateResult.getId()).isEqualTo(createResult.getId()); - assertThat(updateResult.getRev()).isNotEqualTo(updateResult.getOldRev()); - assertThat(updateResult.getOldRev()).isEqualTo(createResult.getRev()); - - final BaseDocument readResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) - .getVertex(createResult.getKey(), BaseDocument.class, null).get(); - assertThat(readResult.getKey()).isEqualTo(createResult.getKey()); - assertThat(readResult.getId()).isEqualTo(createResult.getId()); - assertThat(readResult.getRevision()).isNotNull(); - assertThat(readResult.getProperties().keySet()).doesNotContain("a"); - } - - @Test - void deleteVertex() throws InterruptedException, ExecutionException { - final BaseDocument doc = new BaseDocument(UUID.randomUUID().toString()); - final VertexEntity createResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME).insertVertex(doc, null) - .get(); - db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME).deleteVertex(createResult.getKey(), null).get(); - BaseDocument res = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) - .getVertex(createResult.getKey(), BaseDocument.class, new GraphDocumentReadOptions()).get(); - assertThat(res).isNull(); - } - - @Test - void deleteVertexIfMatch() throws InterruptedException, ExecutionException { - final BaseDocument doc = new BaseDocument(UUID.randomUUID().toString()); - final VertexEntity createResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME).insertVertex(doc, null) - .get(); - final VertexDeleteOptions options = new VertexDeleteOptions().ifMatch(createResult.getRev()); - db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME).deleteVertex(createResult.getKey(), options).get(); - BaseDocument res = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) - .getVertex(createResult.getKey(), BaseDocument.class, new GraphDocumentReadOptions()).get(); - assertThat(res).isNull(); - } - - @Test - void deleteVertexIfMatchFail() throws InterruptedException, ExecutionException { - final BaseDocument doc = new BaseDocument(UUID.randomUUID().toString()); - final VertexEntity createResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME).insertVertex(doc, null) - .get(); - final VertexDeleteOptions options = new VertexDeleteOptions().ifMatch("no"); - try { - db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME).deleteVertex(createResult.getKey(), options).get(); - fail(); - } catch (final ExecutionException e) { - assertThat(e.getCause()).isInstanceOf(ArangoDBException.class); - } - } -} diff --git a/driver/src/test/java/com/arangodb/async/ArangoViewTest.java b/driver/src/test/java/com/arangodb/async/ArangoViewTest.java deleted file mode 100644 index 8bc81b238..000000000 --- a/driver/src/test/java/com/arangodb/async/ArangoViewTest.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * DISCLAIMER - * - * Copyright 2018 ArangoDB GmbH, Cologne, Germany - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Copyright holder is ArangoDB GmbH, Cologne, Germany - */ - -package com.arangodb.async; - -import com.arangodb.entity.ViewEntity; -import com.arangodb.entity.ViewType; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; - -import java.util.concurrent.ExecutionException; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assumptions.assumeTrue; - -/** - * @author Mark Vollmary - */ - -class ArangoViewTest extends BaseTest { - - private static final String VIEW_NAME = "view_test"; - - @BeforeAll - static void setup() throws InterruptedException, ExecutionException { - if (!isAtLeastVersion(arangoDB, 3, 4)) - return; - db.createView(VIEW_NAME, ViewType.ARANGO_SEARCH).get(); - } - - @Test - void exists() throws InterruptedException, ExecutionException { - assumeTrue(isAtLeastVersion(3, 4)); - assertThat(db.view(VIEW_NAME).exists().get()).isTrue(); - } - - @Test - void getInfo() throws InterruptedException, ExecutionException { - assumeTrue(isAtLeastVersion(3, 4)); - final ViewEntity info = db.view(VIEW_NAME).getInfo().get(); - assertThat(info).isNotNull(); - assertThat(info.getId()).isNotNull(); - assertThat(info.getName()).isEqualTo(VIEW_NAME); - assertThat(info.getType()).isEqualTo(ViewType.ARANGO_SEARCH); - } - - @Test - void drop() throws InterruptedException, ExecutionException { - assumeTrue(isAtLeastVersion(3, 4)); - final String name = VIEW_NAME + "_droptest"; - db.createView(name, ViewType.ARANGO_SEARCH).get(); - final ArangoViewAsync view = db.view(name); - view.drop().get(); - assertThat(view.exists().get()).isFalse(); - } - - @Test - void rename() throws InterruptedException, ExecutionException { - assumeTrue(isSingleServer()); - assumeTrue(isAtLeastVersion(3, 4)); - final String name = VIEW_NAME + "_renametest"; - final String newName = name + "_new"; - db.createView(name, ViewType.ARANGO_SEARCH).get(); - db.view(name).rename(newName).get(); - assertThat(db.view(name).exists().get()).isFalse(); - assertThat(db.view(newName).exists().get()).isTrue(); - } - -} diff --git a/driver/src/test/java/com/arangodb/async/BaseTest.java b/driver/src/test/java/com/arangodb/async/BaseTest.java deleted file mode 100644 index 261996ab9..000000000 --- a/driver/src/test/java/com/arangodb/async/BaseTest.java +++ /dev/null @@ -1,119 +0,0 @@ -/* - * DISCLAIMER - * - * Copyright 2016 ArangoDB GmbH, Cologne, Germany - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Copyright holder is ArangoDB GmbH, Cologne, Germany - */ - -package com.arangodb.async; - -import com.arangodb.DbName; -import com.arangodb.config.ArangoConfigProperties; -import com.arangodb.config.ConfigUtils; -import com.arangodb.entity.ArangoDBEngine; -import com.arangodb.entity.License; -import com.arangodb.entity.ServerRole; -import com.arangodb.util.TestUtils; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; - -import java.util.UUID; -import java.util.concurrent.ExecutionException; - - -/** - * @author Mark Vollmary - */ -public abstract class BaseTest { - protected static final ArangoConfigProperties config = ConfigUtils.loadConfig(); - static final DbName TEST_DB = DbName.of("java_driver_test_db"); - static ArangoDBAsync arangoDB; - static ArangoDatabaseAsync db; - - @BeforeAll - static void init() throws InterruptedException, ExecutionException { - if (arangoDB == null) { - arangoDB = new ArangoDBAsync.Builder() - .loadProperties(ConfigUtils.loadConfig()) - .build(); - } - - if (arangoDB.db(TEST_DB).exists().get()) { - arangoDB.db(TEST_DB).drop().get(); - } - - arangoDB.createDatabase(TEST_DB).get(); - BaseTest.db = arangoDB.db(TEST_DB); - } - - @AfterAll - static void shutdown() throws InterruptedException, ExecutionException { - arangoDB.db(TEST_DB).drop().get(); - arangoDB.shutdown(); - arangoDB = null; - } - - static String rnd() { - return UUID.randomUUID().toString(); - } - - protected static boolean isAtLeastVersion(final ArangoDBAsync arangoDB, final int major, final int minor, - final int patch) - throws InterruptedException, ExecutionException { - return com.arangodb.util.TestUtils.isAtLeastVersion(arangoDB.getVersion().get().getVersion(), major, minor, - patch); - } - - protected static boolean isAtLeastVersion(final ArangoDBAsync arangoDB, final int major, final int minor) - throws InterruptedException, ExecutionException { - return isAtLeastVersion(arangoDB, major, minor, 0); - } - - protected boolean isAtLeastVersion(final int major, final int minor, final int patch) throws InterruptedException - , ExecutionException { - return isAtLeastVersion(arangoDB, major, minor, patch); - } - - protected boolean isAtLeastVersion(final int major, final int minor) throws InterruptedException, - ExecutionException { - return isAtLeastVersion(major, minor, 0); - } - - boolean isLessThanVersion(final int major, final int minor) throws ExecutionException, InterruptedException { - return isLessThanVersion(major, minor, 0); - } - - boolean isLessThanVersion(final int major, final int minor, final int patch) throws ExecutionException, InterruptedException { - return TestUtils.isLessThanVersion(db.getVersion().get().getVersion(), major, minor, patch); - } - - boolean isStorageEngine(ArangoDBEngine.StorageEngineName name) throws ExecutionException, InterruptedException { - return name.equals(db.getEngine().get().getName()); - } - - boolean isSingleServer() throws ExecutionException, InterruptedException { - return (arangoDB.getRole().get() == ServerRole.SINGLE); - } - - boolean isCluster() throws ExecutionException, InterruptedException { - return arangoDB.getRole().get() == ServerRole.COORDINATOR; - } - - boolean isEnterprise() throws ExecutionException, InterruptedException { - return arangoDB.getVersion().get().getLicense() == License.ENTERPRISE; - } - -} diff --git a/driver/src/test/java/com/arangodb/async/CommunicationTest.java b/driver/src/test/java/com/arangodb/async/CommunicationTest.java deleted file mode 100644 index 0b2b6c962..000000000 --- a/driver/src/test/java/com/arangodb/async/CommunicationTest.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * DISCLAIMER - * - * Copyright 2016 ArangoDB GmbH, Cologne, Germany - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Copyright holder is ArangoDB GmbH, Cologne, Germany - */ - -package com.arangodb.async; - -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; - -import java.util.concurrent.CompletableFuture; - -import static org.assertj.core.api.Assertions.assertThat; - - -/** - * @author Mark Vollmary - */ -class CommunicationTest { - - @Test - @Disabled - void disconnect() { - final ArangoDBAsync arangoDB = new ArangoDBAsync.Builder().build(); - final CompletableFuture> result = arangoDB.db().query("return sleep(1)", null, null, - null); - arangoDB.shutdown(); - assertThat(result.isCompletedExceptionally()).isEqualTo(true); - } - -} diff --git a/driver/src/test/java/com/arangodb/async/ConcurrencyTest.java b/driver/src/test/java/com/arangodb/async/ConcurrencyTest.java deleted file mode 100644 index f0643c2ca..000000000 --- a/driver/src/test/java/com/arangodb/async/ConcurrencyTest.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * DISCLAIMER - * - * Copyright 2016 ArangoDB GmbH, Cologne, Germany - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Copyright holder is ArangoDB GmbH, Cologne, Germany - */ - -package com.arangodb.async; - - -import com.arangodb.async.internal.ArangoExecutorAsync; -import com.arangodb.entity.ArangoDBVersion; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.Timeout; - -import java.util.List; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutionException; -import java.util.stream.Collectors; -import java.util.stream.IntStream; - -import static org.junit.jupiter.api.Assertions.fail; - - -/** - * @author Michele Rastelli - */ -class ConcurrencyTest { - - private ArangoDBAsync arangoDB; - - @BeforeEach - void initialize() { - arangoDB = new ArangoDBAsync.Builder().build(); - } - - /** - * FIXME: make the user executor configurable in com.arangodb.internal.ArangoExecutorAsync::execute - * (eg. this test passes using a CachedThreadPool) - */ - @Disabled - @Test - @Timeout(2) - void executorLimit() { - List> futures = IntStream.range(0, 20) - .mapToObj(i -> arangoDB.getVersion() - .whenComplete((dbVersion, ex) -> { - System.out.println(Thread.currentThread().getName()); - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - })) - .collect(Collectors.toList()); - - futures.forEach(future -> { - try { - future.get(); - } catch (InterruptedException | ExecutionException e) { - e.printStackTrace(); - fail(); - } - }); - } - - - /** - * outgoing requests should be queued in the {@link ArangoExecutorAsync} outgoingExecutor - */ - @Disabled - @Test - @Timeout(1) - void outgoingRequestsParallelismTest() { - for (int i = 0; i < 50_000; i++) { - arangoDB.getVersion(); - } - } -} diff --git a/driver/src/test/java/com/arangodb/async/ConcurrencyTests.java b/driver/src/test/java/com/arangodb/async/ConcurrencyTests.java deleted file mode 100644 index 278486efc..000000000 --- a/driver/src/test/java/com/arangodb/async/ConcurrencyTests.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.arangodb.async; - - -import com.arangodb.config.ConfigUtils; -import org.junit.jupiter.api.Test; - -import java.util.List; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutionException; -import java.util.stream.Collectors; -import java.util.stream.IntStream; - -class ConcurrencyTests { - - @Test - void concurrentPendingRequests() throws ExecutionException, InterruptedException { - ArangoDBAsync adb = new ArangoDBAsync.Builder() - .loadProperties(ConfigUtils.loadConfig()) - .build(); - List>> reqs = IntStream.range(0, 10) - .mapToObj(__ -> adb.db().query("RETURN SLEEP(1)", Void.class)) - .collect(Collectors.toList()); - for (CompletableFuture> req : reqs) { - req.get(); - } - adb.shutdown(); - } - -} diff --git a/driver/src/test/java/com/arangodb/async/InvertedIndexTest.java b/driver/src/test/java/com/arangodb/async/InvertedIndexTest.java deleted file mode 100644 index e4451f77c..000000000 --- a/driver/src/test/java/com/arangodb/async/InvertedIndexTest.java +++ /dev/null @@ -1,199 +0,0 @@ -package com.arangodb.async; - -import com.arangodb.entity.*; -import com.arangodb.entity.arangosearch.*; -import com.arangodb.entity.arangosearch.analyzer.DelimiterAnalyzer; -import com.arangodb.entity.arangosearch.analyzer.DelimiterAnalyzerProperties; -import com.arangodb.model.InvertedIndexOptions; -import com.arangodb.model.PersistentIndexOptions; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; - -import java.util.*; -import java.util.concurrent.ExecutionException; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assumptions.assumeTrue; - -public class InvertedIndexTest extends BaseTest { - - private static final String COLLECTION_NAME = "InvertedIndexTestAsync_collection"; - - InvertedIndexTest() throws ExecutionException, InterruptedException { - ArangoCollectionAsync collection = db.collection(COLLECTION_NAME); - if (!collection.exists().get()) { - collection.create().get(); - } - } - - @BeforeAll - static void setup() throws InterruptedException, ExecutionException { - db.createCollection(COLLECTION_NAME, null).get(); - } - - @AfterEach - void teardown() throws InterruptedException, ExecutionException { - db.collection(COLLECTION_NAME).drop().get(); - } - - - private void createAnalyzer(String analyzerName, ArangoDatabaseAsync db) throws ExecutionException, InterruptedException { - Set features = new HashSet<>(); - features.add(AnalyzerFeature.frequency); - features.add(AnalyzerFeature.norm); - features.add(AnalyzerFeature.position); - - DelimiterAnalyzer da = new DelimiterAnalyzer(); - da.setName(analyzerName); - da.setFeatures(features); - DelimiterAnalyzerProperties props = new DelimiterAnalyzerProperties(); - props.setDelimiter("-"); - da.setProperties(props); - - db.createSearchAnalyzer(da).get(); - } - - private InvertedIndexOptions createOptions(String analyzerName) throws ExecutionException, InterruptedException { - InvertedIndexField field = new InvertedIndexField() - .name("foo") - .analyzer(AnalyzerType.identity.toString()) - .includeAllFields(true) - .searchField(false) - .trackListPositions(false) - .features( - AnalyzerFeature.position, - AnalyzerFeature.frequency, - AnalyzerFeature.norm, - AnalyzerFeature.offset - ); - - if (isEnterprise()) { - field.nested( - new InvertedIndexField() - .name("bar") - .analyzer(analyzerName) - .searchField(true) - .features(AnalyzerFeature.position, AnalyzerFeature.frequency) - .nested( - new InvertedIndexField() - .name("baz") - .analyzer(AnalyzerType.identity.toString()) - .searchField(false) - .features(AnalyzerFeature.frequency) - ) - ); - } - - return new InvertedIndexOptions() - .name("invertedIndex-" + UUID.randomUUID()) - .inBackground(true) - .parallelism(5) - .primarySort(new InvertedIndexPrimarySort() - .fields( - new InvertedIndexPrimarySort.Field("f1", InvertedIndexPrimarySort.Field.Direction.asc), - new InvertedIndexPrimarySort.Field("f2", InvertedIndexPrimarySort.Field.Direction.desc) - ) - .compression(ArangoSearchCompression.lz4) - ) - .storedValues(new StoredValue(Arrays.asList("f3", "f4"), ArangoSearchCompression.none)) - .analyzer(analyzerName) - .features(AnalyzerFeature.position, AnalyzerFeature.frequency) - .includeAllFields(false) - .trackListPositions(true) - .searchField(true) - .fields(field) - .consolidationIntervalMsec(11L) - .commitIntervalMsec(22L) - .cleanupIntervalStep(33L) - .consolidationPolicy(ConsolidationPolicy.of(ConsolidationType.BYTES_ACCUM).threshold(1.)) - .writebufferIdle(44L) - .writebufferActive(55L) - .writebufferSizeMax(66L); - } - - private void assertCorrectIndexEntity(InvertedIndexEntity indexResult, InvertedIndexOptions options) { - assertThat(indexResult).isNotNull(); - assertThat(indexResult.getId()).isNotNull().isNotEmpty(); - // FIXME: in single server this is null - // assertThat(indexResult.getIsNewlyCreated()).isTrue(); - assertThat(indexResult.getUnique()).isFalse(); - assertThat(indexResult.getSparse()).isTrue(); - assertThat(indexResult.getVersion()).isNotNull(); - assertThat(indexResult.getCode()).isNotNull(); - assertThat(indexResult.getType()).isEqualTo(IndexType.inverted); - assertThat(indexResult.getName()).isEqualTo(options.getName()); - assertThat(indexResult.getFields()).containsExactlyElementsOf(options.getFields()); - assertThat(indexResult.getSearchField()).isEqualTo(options.getSearchField()); - assertThat(indexResult.getStoredValues()).containsExactlyElementsOf(options.getStoredValues()); - assertThat(indexResult.getPrimarySort()).isEqualTo(options.getPrimarySort()); - assertThat(indexResult.getAnalyzer()).isEqualTo(options.getAnalyzer()); - assertThat(indexResult.getFeatures()).hasSameElementsAs(options.getFeatures()); - assertThat(indexResult.getIncludeAllFields()).isEqualTo(options.getIncludeAllFields()); - assertThat(indexResult.getTrackListPositions()).isEqualTo(options.getTrackListPositions()); - assertThat(indexResult.getCleanupIntervalStep()).isEqualTo(options.getCleanupIntervalStep()); - assertThat(indexResult.getCommitIntervalMsec()).isEqualTo(options.getCommitIntervalMsec()); - assertThat(indexResult.getConsolidationIntervalMsec()).isEqualTo(options.getConsolidationIntervalMsec()); - assertThat(indexResult.getConsolidationPolicy()).isEqualTo(options.getConsolidationPolicy()); - assertThat(indexResult.getWritebufferIdle()).isEqualTo(options.getWritebufferIdle()); - assertThat(indexResult.getWritebufferActive()).isEqualTo(options.getWritebufferActive()); - assertThat(indexResult.getWritebufferSizeMax()).isEqualTo(options.getWritebufferSizeMax()); - } - - @Test - void createAndGetInvertedIndex() throws ExecutionException, InterruptedException { - assumeTrue(isAtLeastVersion(3, 10)); - - ArangoCollectionAsync collection = db.collection(COLLECTION_NAME); - String analyzerName = "delimiter-" + UUID.randomUUID(); - createAnalyzer(analyzerName, collection.db()); - InvertedIndexOptions options = createOptions(analyzerName); - InvertedIndexEntity created = collection.ensureInvertedIndex(options).get(); - assertCorrectIndexEntity(created, options); - InvertedIndexEntity loadedIndex = collection.getInvertedIndex(created.getName()).get(); - assertCorrectIndexEntity(loadedIndex, options); - } - - @Test - void getInvertedIndexesShouldNotReturnOtherIndexTypes() throws ExecutionException, InterruptedException { - assumeTrue(isAtLeastVersion(3, 10)); - - ArangoCollectionAsync collection = db.collection(COLLECTION_NAME); - - // create persistent index - collection.ensurePersistentIndex(Collections.singletonList("foo"), new PersistentIndexOptions().name("persistentIndex")); - - // create inverted index - String analyzerName = "delimiter-" + UUID.randomUUID(); - createAnalyzer(analyzerName, collection.db()); - InvertedIndexOptions options = createOptions(analyzerName); - InvertedIndexEntity created = collection.ensureInvertedIndex(options).get(); - - Collection loadedIndexes = collection.getInvertedIndexes().get(); - assertThat(loadedIndexes).map(InvertedIndexEntity::getName) - .doesNotContain("persistentIndex") - .contains(created.getName()); - } - - @Test - void getIndexesShouldNotReturnInvertedIndexes() throws ExecutionException, InterruptedException { - assumeTrue(isAtLeastVersion(3, 10)); - - ArangoCollectionAsync collection = db.collection(COLLECTION_NAME); - - // create persistent index - collection.ensurePersistentIndex(Collections.singletonList("foo"), new PersistentIndexOptions().name("persistentIndex")).get(); - - // create inverted index - String analyzerName = "delimiter-" + UUID.randomUUID(); - createAnalyzer(analyzerName, collection.db()); - InvertedIndexOptions options = createOptions(analyzerName); - InvertedIndexEntity created = collection.ensureInvertedIndex(options).get(); - - Collection loadedIndexes = collection.getIndexes().get(); - assertThat(loadedIndexes).map(IndexEntity::getName) - .doesNotContain(created.getName()) - .contains("persistentIndex"); - } - -} diff --git a/driver/src/test/java/com/arangodb/async/JwtAuthTest.java b/driver/src/test/java/com/arangodb/async/JwtAuthTest.java deleted file mode 100644 index 04bbfc98d..000000000 --- a/driver/src/test/java/com/arangodb/async/JwtAuthTest.java +++ /dev/null @@ -1,103 +0,0 @@ -package com.arangodb.async; - -import com.arangodb.*; -import com.arangodb.config.ConfigUtils; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; - -import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.ExecutionException; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.fail; - -class JwtAuthTest { - - private static String jwt; - private ArangoDBAsync arangoDB; - - @BeforeAll - static void init() { - ArangoDB arangoDB = new ArangoDB.Builder() - .loadProperties(ConfigUtils.loadConfig()) - .build(); - jwt = getJwt(arangoDB); - arangoDB.shutdown(); - } - - private static String getJwt(ArangoDB arangoDB) { - Map reqBody = new HashMap<>(); - reqBody.put("username", "root"); - reqBody.put("password", "test"); - - Request req = Request.builder() - .db(DbName.SYSTEM) - .method(Request.Method.POST) - .path("/_open/auth") - .body(reqBody) - .build(); - - Response resp = arangoDB.execute(req, Map.class); - return (String) resp.getBody().get("jwt"); - } - - @AfterEach - void after() { - if (arangoDB != null) - arangoDB.shutdown(); - } - - @Test - void notAuthenticated() throws InterruptedException { - arangoDB = getBuilder().build(); - try { - arangoDB.getVersion().get(); - fail(); - } catch (ExecutionException e) { - assertThat(e.getCause()).isInstanceOf(ArangoDBException.class); - assertThat(((ArangoDBException) e.getCause()).getResponseCode()).isEqualTo(401); - } - arangoDB.shutdown(); - } - - @Test - void authenticated() throws ExecutionException, InterruptedException { - arangoDB = getBuilder() - .jwt(jwt) - .build(); - arangoDB.getVersion().get(); - arangoDB.shutdown(); - } - - @Test - @Disabled("DE-423") - void updateJwt() throws ExecutionException, InterruptedException { - arangoDB = getBuilder() - .jwt(jwt) - .build(); - arangoDB.getVersion().get(); - arangoDB.updateJwt("bla"); - try { - arangoDB.getVersion().get(); - fail(); - } catch (ExecutionException e) { - assertThat(e.getCause()).isInstanceOf(ArangoDBException.class); - assertThat(((ArangoDBException) e.getCause()).getResponseCode()).isEqualTo(401); - } - - arangoDB.updateJwt(jwt); - arangoDB.getVersion().get(); - arangoDB.shutdown(); - } - - private ArangoDBAsync.Builder getBuilder() { - return new ArangoDBAsync.Builder() - .loadProperties(ConfigUtils.loadConfig()) - .jwt(null) // unset credentials from properties file - .user(null) // unset credentials from properties file - .password(null); // unset credentials from properties file - } -} diff --git a/driver/src/test/java/com/arangodb/async/StreamTransactionConflictsTest.java b/driver/src/test/java/com/arangodb/async/StreamTransactionConflictsTest.java deleted file mode 100644 index 659781ae2..000000000 --- a/driver/src/test/java/com/arangodb/async/StreamTransactionConflictsTest.java +++ /dev/null @@ -1,120 +0,0 @@ -/* - * DISCLAIMER - * - * Copyright 2016 ArangoDB GmbH, Cologne, Germany - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Copyright holder is ArangoDB GmbH, Cologne, Germany - */ - -package com.arangodb.async; - -import com.arangodb.ArangoDBException; -import com.arangodb.entity.ArangoDBEngine; -import com.arangodb.entity.BaseDocument; -import com.arangodb.entity.StreamTransactionEntity; -import com.arangodb.model.DocumentCreateOptions; -import com.arangodb.model.StreamTransactionOptions; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Test; - -import java.util.UUID; -import java.util.concurrent.ExecutionException; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.fail; -import static org.junit.jupiter.api.Assumptions.assumeTrue; - -/** - * @author Michele Rastelli - */ -class StreamTransactionConflictsTest extends BaseTest { - - private static final String COLLECTION_NAME = "db_concurrent_stream_transactions_test"; - - public StreamTransactionConflictsTest() throws ExecutionException, InterruptedException { - if (db.collection(COLLECTION_NAME).exists().get()) - db.collection(COLLECTION_NAME).drop().get(); - - db.createCollection(COLLECTION_NAME, null).get(); - } - - @AfterEach - void teardown() throws ExecutionException, InterruptedException { - if (db.collection(COLLECTION_NAME).exists().get()) - db.collection(COLLECTION_NAME).drop().get(); - } - - @Test - void conflictOnInsertDocumentWithNotYetCommittedTx() throws ExecutionException, InterruptedException { - assumeTrue(isAtLeastVersion(3, 5)); - assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); - - StreamTransactionEntity tx1 = db.beginStreamTransaction( - new StreamTransactionOptions().readCollections(COLLECTION_NAME).writeCollections(COLLECTION_NAME)).get(); - - StreamTransactionEntity tx2 = db.beginStreamTransaction( - new StreamTransactionOptions().readCollections(COLLECTION_NAME).writeCollections(COLLECTION_NAME)).get(); - - String key = UUID.randomUUID().toString(); - - // insert a document from within tx1 - db.collection(COLLECTION_NAME) - .insertDocument(new BaseDocument(key), new DocumentCreateOptions().streamTransactionId(tx1.getId())).get(); - - try { - // insert conflicting document from within tx2 - db.collection(COLLECTION_NAME).insertDocument(new BaseDocument(key), - new DocumentCreateOptions().streamTransactionId(tx2.getId())).get(); - fail(); - } catch (ExecutionException e) { - assertThat(e.getCause()).isInstanceOf(ArangoDBException.class); - } - - db.abortStreamTransaction(tx1.getId()).get(); - db.abortStreamTransaction(tx2.getId()).get(); - } - - @Test - void conflictOnInsertDocumentWithAlreadyCommittedTx() throws ExecutionException, InterruptedException { - assumeTrue(isAtLeastVersion(3, 5)); - assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); - - StreamTransactionEntity tx1 = db.beginStreamTransaction( - new StreamTransactionOptions().readCollections(COLLECTION_NAME).writeCollections(COLLECTION_NAME)).get(); - - StreamTransactionEntity tx2 = db.beginStreamTransaction( - new StreamTransactionOptions().readCollections(COLLECTION_NAME).writeCollections(COLLECTION_NAME)).get(); - - String key = UUID.randomUUID().toString(); - - // insert a document from within tx1 - db.collection(COLLECTION_NAME) - .insertDocument(new BaseDocument(key), new DocumentCreateOptions().streamTransactionId(tx1.getId())).get(); - - // commit tx1 - db.commitStreamTransaction(tx1.getId()).get(); - - try { - // insert conflicting document from within tx2 - db.collection(COLLECTION_NAME).insertDocument(new BaseDocument(key), - new DocumentCreateOptions().streamTransactionId(tx2.getId())).get(); - fail(); - } catch (ExecutionException e) { - assertThat(e.getCause()).isInstanceOf(ArangoDBException.class); - } - - db.abortStreamTransaction(tx2.getId()).get(); - } -} diff --git a/driver/src/test/java/com/arangodb/async/StreamTransactionGraphTest.java b/driver/src/test/java/com/arangodb/async/StreamTransactionGraphTest.java deleted file mode 100644 index 60ee6ea11..000000000 --- a/driver/src/test/java/com/arangodb/async/StreamTransactionGraphTest.java +++ /dev/null @@ -1,398 +0,0 @@ -/* - * DISCLAIMER - * - * Copyright 2016 ArangoDB GmbH, Cologne, Germany - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Copyright holder is ArangoDB GmbH, Cologne, Germany - */ - -package com.arangodb.async; - - -import com.arangodb.entity.*; -import com.arangodb.model.*; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Test; - -import java.util.Collections; -import java.util.UUID; -import java.util.concurrent.ExecutionException; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assumptions.assumeTrue; - - -/** - * @author Michele Rastelli - */ -class StreamTransactionGraphTest extends BaseTest { - - private static final String GRAPH_NAME = "graph_stream_transaction_graph_test"; - private static final String EDGE_COLLECTION = "edge_collection_stream_transaction_graph_test"; - private static final String VERTEX_COLLECTION_1 = "vertex_collection_1_stream_transaction_graph_test"; - private static final String VERTEX_COLLECTION_2 = "vertex_collection_2_stream_transaction_graph_test"; - - private final ArangoGraphAsync graph; - private final ArangoVertexCollectionAsync vertexCollection1; - private final ArangoVertexCollectionAsync vertexCollection2; - private final ArangoEdgeCollectionAsync edgeCollection; - - public StreamTransactionGraphTest() throws ExecutionException, InterruptedException { - - graph = db.graph(GRAPH_NAME); - - if (graph.exists().get()) - graph.drop().get(); - - graph.create(Collections.singletonList(new EdgeDefinition().collection(EDGE_COLLECTION).from(VERTEX_COLLECTION_1).to(VERTEX_COLLECTION_2))).get(); - - vertexCollection1 = graph.vertexCollection(VERTEX_COLLECTION_1); - vertexCollection2 = graph.vertexCollection(VERTEX_COLLECTION_2); - edgeCollection = graph.edgeCollection(EDGE_COLLECTION); - } - - @AfterEach - void teardown() throws ExecutionException, InterruptedException { - if (graph.exists().get()) - graph.drop().get(); - if (db.collection(EDGE_COLLECTION).exists().get()) - db.collection(EDGE_COLLECTION).drop().get(); - if (db.collection(VERTEX_COLLECTION_1).exists().get()) - db.collection(VERTEX_COLLECTION_1).drop().get(); - if (db.collection(VERTEX_COLLECTION_2).exists().get()) - db.collection(VERTEX_COLLECTION_2).drop().get(); - } - - private BaseEdgeDocument createEdgeValue(String streamTransactionId) throws ExecutionException, - InterruptedException { - final VertexEntity v1 = vertexCollection1.insertVertex(new BaseDocument(), - new VertexCreateOptions().streamTransactionId(streamTransactionId)).get(); - final VertexEntity v2 = vertexCollection2.insertVertex(new BaseDocument(), - new VertexCreateOptions().streamTransactionId(streamTransactionId)).get(); - final BaseEdgeDocument value = new BaseEdgeDocument(); - value.setFrom(v1.getId()); - value.setTo(v2.getId()); - return value; - } - - @Test - void getVertex() throws ExecutionException, InterruptedException { - assumeTrue(isSingleServer()); - assumeTrue(isAtLeastVersion(3, 5)); - assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); - - StreamTransactionEntity tx = db - .beginStreamTransaction(new StreamTransactionOptions() - .readCollections(VERTEX_COLLECTION_1, VERTEX_COLLECTION_2, EDGE_COLLECTION) - .writeCollections(VERTEX_COLLECTION_1, VERTEX_COLLECTION_2, EDGE_COLLECTION)).get(); - - // insert a vertex from outside the tx - VertexEntity createdVertex = vertexCollection1.insertVertex(new BaseDocument()).get(); - - // assert that the vertex is not found from within the tx - assertThat(vertexCollection1.getVertex(createdVertex.getKey(), BaseDocument.class, - new GraphDocumentReadOptions().streamTransactionId(tx.getId())).get()).isNull(); - - db.abortStreamTransaction(tx.getId()).get(); - } - - - @Test - void createVertex() throws ExecutionException, InterruptedException { - assumeTrue(isSingleServer()); - assumeTrue(isAtLeastVersion(3, 5)); - assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); - - StreamTransactionEntity tx = db.beginStreamTransaction( - new StreamTransactionOptions() - .readCollections(VERTEX_COLLECTION_1, VERTEX_COLLECTION_2, EDGE_COLLECTION) - .writeCollections(VERTEX_COLLECTION_1, VERTEX_COLLECTION_2, EDGE_COLLECTION)).get(); - - // insert a vertex from within the tx - VertexEntity createdVertex = vertexCollection1.insertVertex(new BaseDocument(), - new VertexCreateOptions().streamTransactionId(tx.getId())).get(); - - // assert that the vertex is not found from outside the tx - assertThat(vertexCollection1.getVertex(createdVertex.getKey(), BaseDocument.class, null).get()).isNull(); - - // assert that the vertex is found from within the tx - assertThat(vertexCollection1.getVertex(createdVertex.getKey(), BaseDocument.class, - new GraphDocumentReadOptions().streamTransactionId(tx.getId())).get()).isNotNull(); - - db.commitStreamTransaction(tx.getId()).get(); - - // assert that the vertex is found after commit - assertThat(vertexCollection1.getVertex(createdVertex.getKey(), BaseDocument.class, null).get()).isNotNull(); - } - - @Test - void replaceVertex() throws ExecutionException, InterruptedException { - assumeTrue(isSingleServer()); - assumeTrue(isAtLeastVersion(3, 5)); - assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); - - BaseDocument doc = new BaseDocument(UUID.randomUUID().toString()); - doc.addAttribute("test", "foo"); - - VertexEntity createdVertex = vertexCollection1.insertVertex(doc, null).get(); - - StreamTransactionEntity tx = db.beginStreamTransaction( - new StreamTransactionOptions() - .readCollections(VERTEX_COLLECTION_1, VERTEX_COLLECTION_2, EDGE_COLLECTION) - .writeCollections(VERTEX_COLLECTION_1, VERTEX_COLLECTION_2, EDGE_COLLECTION)).get(); - - // replace vertex from within the tx - doc.updateAttribute("test", "bar"); - vertexCollection1.replaceVertex(createdVertex.getKey(), doc, - new VertexReplaceOptions().streamTransactionId(tx.getId())).get(); - - // assert that the vertex has not been replaced from outside the tx - assertThat(vertexCollection1.getVertex(createdVertex.getKey(), BaseDocument.class, null).get() - .getProperties()).containsEntry("test", "foo"); - - // assert that the vertex has been replaced from within the tx - assertThat(vertexCollection1.getVertex(createdVertex.getKey(), BaseDocument.class, - new GraphDocumentReadOptions().streamTransactionId(tx.getId())).get().getProperties()).containsEntry( - "test", "bar"); - - db.commitStreamTransaction(tx.getId()).get(); - - // assert that the vertex has been replaced after commit - assertThat(vertexCollection1.getVertex(createdVertex.getKey(), BaseDocument.class, null).get() - .getProperties()).containsEntry("test", "bar"); - } - - @Test - void updateVertex() throws ExecutionException, InterruptedException { - assumeTrue(isSingleServer()); - assumeTrue(isAtLeastVersion(3, 5)); - assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); - - BaseDocument doc = new BaseDocument(UUID.randomUUID().toString()); - doc.addAttribute("test", "foo"); - - VertexEntity createdDoc = vertexCollection1.insertVertex(doc, null).get(); - - StreamTransactionEntity tx = db.beginStreamTransaction( - new StreamTransactionOptions() - .readCollections(VERTEX_COLLECTION_1, VERTEX_COLLECTION_2, EDGE_COLLECTION) - .writeCollections(VERTEX_COLLECTION_1, VERTEX_COLLECTION_2, EDGE_COLLECTION)).get(); - - // update vertex from within the tx - doc.updateAttribute("test", "bar"); - vertexCollection1.updateVertex(createdDoc.getKey(), doc, - new VertexUpdateOptions().streamTransactionId(tx.getId())).get(); - - // assert that the vertex has not been updated from outside the tx - assertThat(vertexCollection1.getVertex(createdDoc.getKey(), BaseDocument.class, null).get() - .getProperties()).containsEntry("test", "foo"); - - // assert that the vertex has been updated from within the tx - assertThat(vertexCollection1.getVertex(createdDoc.getKey(), BaseDocument.class, - new GraphDocumentReadOptions().streamTransactionId(tx.getId())).get().getProperties()).containsEntry( - "test", "bar"); - - db.commitStreamTransaction(tx.getId()).get(); - - // assert that the vertex has been updated after commit - assertThat(vertexCollection1.getVertex(createdDoc.getKey(), BaseDocument.class, null).get() - .getProperties()).containsEntry("test", "bar"); - } - - @Test - void deleteVertex() throws ExecutionException, InterruptedException { - assumeTrue(isSingleServer()); - assumeTrue(isAtLeastVersion(3, 5)); - assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); - - VertexEntity createdDoc = vertexCollection1.insertVertex(new BaseDocument(), null).get(); - - StreamTransactionEntity tx = db.beginStreamTransaction( - new StreamTransactionOptions() - .readCollections(VERTEX_COLLECTION_1, VERTEX_COLLECTION_2, EDGE_COLLECTION) - .writeCollections(VERTEX_COLLECTION_1, VERTEX_COLLECTION_2, EDGE_COLLECTION)).get(); - - // delete vertex from within the tx - vertexCollection1.deleteVertex(createdDoc.getKey(), - new VertexDeleteOptions().streamTransactionId(tx.getId())).get(); - - // assert that the vertex has not been deleted from outside the tx - assertThat(vertexCollection1.getVertex(createdDoc.getKey(), BaseDocument.class, null).get()).isNotNull(); - - // assert that the vertex has been deleted from within the tx - assertThat(vertexCollection1.getVertex(createdDoc.getKey(), BaseDocument.class, - new GraphDocumentReadOptions().streamTransactionId(tx.getId())).get()).isNull(); - - db.commitStreamTransaction(tx.getId()).get(); - - // assert that the vertex has been deleted after commit - assertThat(vertexCollection1.getVertex(createdDoc.getKey(), BaseDocument.class, null).get()).isNull(); - } - - - @Test - void getEdge() throws ExecutionException, InterruptedException { - assumeTrue(isSingleServer()); - assumeTrue(isAtLeastVersion(3, 5)); - assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); - - StreamTransactionEntity tx = db - .beginStreamTransaction(new StreamTransactionOptions() - .readCollections(VERTEX_COLLECTION_1, VERTEX_COLLECTION_2, EDGE_COLLECTION) - .writeCollections(VERTEX_COLLECTION_1, VERTEX_COLLECTION_2, EDGE_COLLECTION)).get(); - - // insert an edge from outside the tx - EdgeEntity createdEdge = edgeCollection.insertEdge(createEdgeValue(null)).get(); - - // assert that the edge is not found from within the tx - assertThat(edgeCollection.getEdge(createdEdge.getKey(), BaseEdgeDocument.class, - new GraphDocumentReadOptions().streamTransactionId(tx.getId())).get()).isNull(); - - db.abortStreamTransaction(tx.getId()).get(); - } - - - @Test - void createEdge() throws ExecutionException, InterruptedException { - assumeTrue(isSingleServer()); - assumeTrue(isAtLeastVersion(3, 5)); - assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); - - StreamTransactionEntity tx = db.beginStreamTransaction( - new StreamTransactionOptions() - .readCollections(VERTEX_COLLECTION_1, VERTEX_COLLECTION_2, EDGE_COLLECTION) - .writeCollections(VERTEX_COLLECTION_1, VERTEX_COLLECTION_2, EDGE_COLLECTION)).get(); - - // insert an edge from within the tx - EdgeEntity createdEdge = edgeCollection.insertEdge(createEdgeValue(tx.getId()), - new EdgeCreateOptions().streamTransactionId(tx.getId())).get(); - - // assert that the edge is not found from outside the tx - assertThat(edgeCollection.getEdge(createdEdge.getKey(), BaseEdgeDocument.class, null).get()).isNull(); - - // assert that the edge is found from within the tx - assertThat(edgeCollection.getEdge(createdEdge.getKey(), BaseEdgeDocument.class, - new GraphDocumentReadOptions().streamTransactionId(tx.getId())).get()).isNotNull(); - - db.commitStreamTransaction(tx.getId()).get(); - - // assert that the edge is found after commit - assertThat(edgeCollection.getEdge(createdEdge.getKey(), BaseEdgeDocument.class, null).get()).isNotNull(); - } - - @Test - void replaceEdge() throws ExecutionException, InterruptedException { - assumeTrue(isSingleServer()); - assumeTrue(isAtLeastVersion(3, 5)); - assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); - - BaseEdgeDocument doc = createEdgeValue(null); - doc.addAttribute("test", "foo"); - - EdgeEntity createdEdge = edgeCollection.insertEdge(doc, null).get(); - - StreamTransactionEntity tx = db.beginStreamTransaction( - new StreamTransactionOptions() - .readCollections(VERTEX_COLLECTION_1, VERTEX_COLLECTION_2, EDGE_COLLECTION) - .writeCollections(VERTEX_COLLECTION_1, VERTEX_COLLECTION_2, EDGE_COLLECTION)).get(); - - // replace edge from within the tx - doc.updateAttribute("test", "bar"); - edgeCollection.replaceEdge(createdEdge.getKey(), doc, - new EdgeReplaceOptions().streamTransactionId(tx.getId())).get(); - - // assert that the edge has not been replaced from outside the tx - assertThat(edgeCollection.getEdge(createdEdge.getKey(), BaseEdgeDocument.class, null).get() - .getProperties()).containsEntry("test", "foo"); - - // assert that the edge has been replaced from within the tx - assertThat(edgeCollection.getEdge(createdEdge.getKey(), BaseEdgeDocument.class, - new GraphDocumentReadOptions().streamTransactionId(tx.getId())).get().getProperties()).containsEntry( - "test", "bar"); - - db.commitStreamTransaction(tx.getId()).get(); - - // assert that the edge has been replaced after commit - assertThat(edgeCollection.getEdge(createdEdge.getKey(), BaseEdgeDocument.class, null).get() - .getProperties()).containsEntry("test", "bar"); - } - - @Test - void updateEdge() throws ExecutionException, InterruptedException { - assumeTrue(isSingleServer()); - assumeTrue(isAtLeastVersion(3, 5)); - assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); - - BaseEdgeDocument doc = createEdgeValue(null); - doc.addAttribute("test", "foo"); - - EdgeEntity createdDoc = edgeCollection.insertEdge(doc, null).get(); - - StreamTransactionEntity tx = db.beginStreamTransaction( - new StreamTransactionOptions() - .readCollections(VERTEX_COLLECTION_1, VERTEX_COLLECTION_2, EDGE_COLLECTION) - .writeCollections(VERTEX_COLLECTION_1, VERTEX_COLLECTION_2, EDGE_COLLECTION)).get(); - - // update edge from within the tx - doc.updateAttribute("test", "bar"); - edgeCollection.updateEdge(createdDoc.getKey(), doc, new EdgeUpdateOptions().streamTransactionId(tx.getId())) - .get(); - - // assert that the edge has not been updated from outside the tx - assertThat(edgeCollection.getEdge(createdDoc.getKey(), BaseEdgeDocument.class, null).get() - .getProperties()).containsEntry("test", "foo"); - - // assert that the edge has been updated from within the tx - assertThat(edgeCollection.getEdge(createdDoc.getKey(), BaseEdgeDocument.class, - new GraphDocumentReadOptions().streamTransactionId(tx.getId())).get().getProperties()).containsEntry( - "test", "bar"); - - db.commitStreamTransaction(tx.getId()).get(); - - // assert that the edge has been updated after commit - assertThat(edgeCollection.getEdge(createdDoc.getKey(), BaseEdgeDocument.class, null).get() - .getProperties()).containsEntry("test", "bar"); - } - - @Test - void deleteEdge() throws ExecutionException, InterruptedException { - assumeTrue(isSingleServer()); - assumeTrue(isAtLeastVersion(3, 5)); - assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); - - EdgeEntity createdDoc = edgeCollection.insertEdge(createEdgeValue(null), null).get(); - - StreamTransactionEntity tx = db.beginStreamTransaction( - new StreamTransactionOptions() - .readCollections(VERTEX_COLLECTION_1, VERTEX_COLLECTION_2, EDGE_COLLECTION) - .writeCollections(VERTEX_COLLECTION_1, VERTEX_COLLECTION_2, EDGE_COLLECTION)).get(); - - // delete edge from within the tx - edgeCollection.deleteEdge(createdDoc.getKey(), new EdgeDeleteOptions().streamTransactionId(tx.getId())).get(); - - // assert that the edge has not been deleted from outside the tx - assertThat(edgeCollection.getEdge(createdDoc.getKey(), BaseEdgeDocument.class, null).get()).isNotNull(); - - // assert that the edge has been deleted from within the tx - assertThat(edgeCollection.getEdge(createdDoc.getKey(), BaseEdgeDocument.class, - new GraphDocumentReadOptions().streamTransactionId(tx.getId())).get()).isNull(); - - db.commitStreamTransaction(tx.getId()).get(); - - // assert that the edge has been deleted after commit - assertThat(edgeCollection.getEdge(createdDoc.getKey(), BaseEdgeDocument.class, null).get()).isNull(); - } - -} diff --git a/driver/src/test/java/com/arangodb/async/StreamTransactionTest.java b/driver/src/test/java/com/arangodb/async/StreamTransactionTest.java deleted file mode 100644 index 658bab18b..000000000 --- a/driver/src/test/java/com/arangodb/async/StreamTransactionTest.java +++ /dev/null @@ -1,362 +0,0 @@ -/* - * DISCLAIMER - * - * Copyright 2016 ArangoDB GmbH, Cologne, Germany - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Copyright holder is ArangoDB GmbH, Cologne, Germany - */ - -package com.arangodb.async; - -import com.arangodb.ArangoDBException; -import com.arangodb.entity.*; -import com.arangodb.model.DocumentCreateOptions; -import com.arangodb.model.DocumentReadOptions; -import com.arangodb.model.StreamTransactionOptions; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Test; - -import java.util.Arrays; -import java.util.List; -import java.util.Set; -import java.util.concurrent.ExecutionException; -import java.util.stream.Collectors; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.fail; -import static org.junit.jupiter.api.Assumptions.assumeTrue; - -/** - * @author Michele Rastelli - */ -class StreamTransactionTest extends BaseTest { - - private static final String COLLECTION_NAME = "db_stream_transaction_test"; - - public StreamTransactionTest() throws ExecutionException, InterruptedException { - if (db.collection(COLLECTION_NAME).exists().get()) - db.collection(COLLECTION_NAME).drop().get(); - - db.createCollection(COLLECTION_NAME, null).get(); - } - - @AfterEach - void teardown() throws ExecutionException, InterruptedException { - if (db.collection(COLLECTION_NAME).exists().get()) - db.collection(COLLECTION_NAME).drop().get(); - } - - @Test - void beginStreamTransaction() throws ExecutionException, InterruptedException { - assumeTrue(isSingleServer()); - assumeTrue(isAtLeastVersion(3, 5)); - assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); - - StreamTransactionEntity tx = db.beginStreamTransaction(null).get(); - assertThat(tx.getId()).isNotNull(); - assertThat(tx.getStatus()).isEqualTo(StreamTransactionStatus.running); - db.abortStreamTransaction(tx.getId()).get(); - } - - @Test - void beginStreamTransactionWithNonExistingCollectionsShouldThrow() throws ExecutionException, InterruptedException { - assumeTrue(isSingleServer()); - assumeTrue(isAtLeastVersion(3, 5)); - assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); - - try { - db.beginStreamTransaction(new StreamTransactionOptions().writeCollections("notExistingCollection")).get(); - fail(); - } catch (ExecutionException e) { - assertThat(e.getCause()).isInstanceOf(ArangoDBException.class); - } - } - - @Test - void abortStreamTransaction() throws ExecutionException, InterruptedException { - assumeTrue(isSingleServer()); - assumeTrue(isAtLeastVersion(3, 5)); - assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); - - StreamTransactionEntity begunTx = db.beginStreamTransaction(null).get(); - StreamTransactionEntity abortedTx = db.abortStreamTransaction(begunTx.getId()).get(); - - assertThat(abortedTx.getId()).isNotNull(); - assertThat(abortedTx.getId()).isEqualTo(begunTx.getId()); - assertThat(abortedTx.getStatus()).isEqualTo(StreamTransactionStatus.aborted); - } - - @Test - void abortStreamTransactionTwice() throws ExecutionException, InterruptedException { - assumeTrue(isSingleServer()); - assumeTrue(isAtLeastVersion(3, 5)); - assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); - - StreamTransactionEntity begunTx = db.beginStreamTransaction(null).get(); - db.abortStreamTransaction(begunTx.getId()).get(); - db.abortStreamTransaction(begunTx.getId()).get(); - } - - @Test - void abortStreamTransactionWhenTransactionIdDoesNotExistsShouldThrow() throws ExecutionException, - InterruptedException { - assumeTrue(isSingleServer()); - assumeTrue(isAtLeastVersion(3, 5)); - assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); - - try { - db.abortStreamTransaction("000000").get(); - fail(); - } catch (ExecutionException e) { - assertThat(e.getCause()).isInstanceOf(ArangoDBException.class); - } - } - - @Test - void abortStreamTransactionWithInvalidTransactionIdShouldThrow() throws ExecutionException, InterruptedException { - assumeTrue(isSingleServer()); - assumeTrue(isAtLeastVersion(3, 5)); - assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); - - try { - db.abortStreamTransaction("invalidTransactionId").get(); - fail(); - } catch (ExecutionException e) { - assertThat(e.getCause()).isInstanceOf(ArangoDBException.class); - } - } - - @Test - void abortCommittedStreamTransactionShouldThrow() throws ExecutionException, InterruptedException { - assumeTrue(isSingleServer()); - assumeTrue(isAtLeastVersion(3, 5)); - assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); - - StreamTransactionEntity createdTx = db.beginStreamTransaction(null).get(); - db.commitStreamTransaction(createdTx.getId()).get(); - - try { - db.abortStreamTransaction(createdTx.getId()).get(); - fail(); - } catch (ExecutionException e) { - assertThat(e.getCause()).isInstanceOf(ArangoDBException.class); - } - } - - @Test - void getStreamTransaction() throws ExecutionException, InterruptedException { - assumeTrue(isSingleServer()); - assumeTrue(isAtLeastVersion(3, 5)); - assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); - - StreamTransactionEntity createdTx = db.beginStreamTransaction(null).get(); - StreamTransactionEntity gotTx = db.getStreamTransaction(createdTx.getId()).get(); - - assertThat(gotTx.getId()).isNotNull(); - assertThat(gotTx.getId()).isEqualTo(createdTx.getId()); - assertThat(gotTx.getStatus()).isEqualTo(StreamTransactionStatus.running); - - db.abortStreamTransaction(createdTx.getId()).get(); - } - - @Test - void getStreamTransactionWhenTransactionIdDoesNotExistsShouldThrow() throws ExecutionException, - InterruptedException { - assumeTrue(isSingleServer()); - assumeTrue(isAtLeastVersion(3, 5)); - assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); - - try { - db.getStreamTransaction("000000").get(); - fail(); - } catch (ExecutionException e) { - assertThat(e.getCause()).isInstanceOf(ArangoDBException.class); - } - } - - @Test - void getStreamTransactionWithInvalidTransactionIdShouldThrow() throws ExecutionException, InterruptedException { - assumeTrue(isSingleServer()); - assumeTrue(isAtLeastVersion(3, 5)); - assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); - - try { - db.getStreamTransaction("invalidTransactionId").get(); - fail(); - } catch (ExecutionException e) { - assertThat(e.getCause()).isInstanceOf(ArangoDBException.class); - } - } - - @Test - void commitStreamTransaction() throws ExecutionException, InterruptedException { - assumeTrue(isSingleServer()); - assumeTrue(isAtLeastVersion(3, 5)); - assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); - - StreamTransactionEntity createdTx = db.beginStreamTransaction(null).get(); - StreamTransactionEntity committedTx = db.commitStreamTransaction(createdTx.getId()).get(); - - assertThat(committedTx.getId()).isNotNull(); - assertThat(committedTx.getId()).isEqualTo(createdTx.getId()); - assertThat(committedTx.getStatus()).isEqualTo(StreamTransactionStatus.committed); - } - - @Test - void commitStreamTransactionTwice() throws ExecutionException, InterruptedException { - assumeTrue(isSingleServer()); - assumeTrue(isAtLeastVersion(3, 5)); - assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); - - StreamTransactionEntity createdTx = db.beginStreamTransaction(null).get(); - db.commitStreamTransaction(createdTx.getId()).get(); - db.commitStreamTransaction(createdTx.getId()).get(); - } - - @Test - void commitStreamTransactionWhenTransactionIdDoesNotExistsShouldThrow() throws ExecutionException, - InterruptedException { - assumeTrue(isSingleServer()); - assumeTrue(isAtLeastVersion(3, 5)); - assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); - - try { - db.commitStreamTransaction("000000").get(); - fail(); - } catch (ExecutionException e) { - assertThat(e.getCause()).isInstanceOf(ArangoDBException.class); - } - } - - @Test - void commitStreamTransactionWithInvalidTransactionIdShouldThrow() throws ExecutionException, InterruptedException { - assumeTrue(isSingleServer()); - assumeTrue(isAtLeastVersion(3, 5)); - assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); - - try { - db.commitStreamTransaction("invalidTransactionId").get(); - fail(); - } catch (ExecutionException e) { - assertThat(e.getCause()).isInstanceOf(ArangoDBException.class); - } - } - - @Test - void commitAbortedStreamTransactionShouldThrow() throws ExecutionException, InterruptedException { - assumeTrue(isSingleServer()); - assumeTrue(isAtLeastVersion(3, 5)); - assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); - - StreamTransactionEntity createdTx = db.beginStreamTransaction(null).get(); - db.abortStreamTransaction(createdTx.getId()).get(); - - try { - db.commitStreamTransaction(createdTx.getId()).get(); - fail(); - } catch (ExecutionException e) { - assertThat(e.getCause()).isInstanceOf(ArangoDBException.class); - } - } - - @Test - void getDocument() throws ExecutionException, InterruptedException { - assumeTrue(isSingleServer()); - assumeTrue(isAtLeastVersion(3, 5)); - assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); - - StreamTransactionEntity tx = db - .beginStreamTransaction(new StreamTransactionOptions().readCollections(COLLECTION_NAME)).get(); - - // insert a document from outside the tx - DocumentCreateEntity externalDoc = db.collection(COLLECTION_NAME) - .insertDocument(new BaseDocument(), null).get(); - - // 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())).get()).isNull(); - - db.abortStreamTransaction(tx.getId()).get(); - } - - @Test - void getDocumentWithNonExistingTransactionIdShouldThrow() throws ExecutionException, InterruptedException { - assumeTrue(isSingleServer()); - assumeTrue(isAtLeastVersion(3, 5)); - assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); - - try { - db.collection(COLLECTION_NAME) - .getDocument("docId", BaseDocument.class, new DocumentReadOptions().streamTransactionId("123456")) - .get(); - fail(); - } catch (ExecutionException e) { - assertThat(e.getCause()).isInstanceOf(ArangoDBException.class); - } - } - - @Test - void insertDocumentWithNonExistingTransactionIdShouldThrow() throws ExecutionException, InterruptedException { - assumeTrue(isSingleServer()); - assumeTrue(isAtLeastVersion(3, 5)); - assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); - - try { - db.collection(COLLECTION_NAME) - .insertDocument(new BaseDocument(), new DocumentCreateOptions().streamTransactionId("123456")).get(); - fail(); - } catch (ExecutionException e) { - assertThat(e.getCause()).isInstanceOf(ArangoDBException.class); - } - } - - @Test - void getDocumentWithInvalidTransactionIdShouldThrow() throws ExecutionException, InterruptedException { - assumeTrue(isSingleServer()); - assumeTrue(isAtLeastVersion(3, 5)); - assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); - - try { - db.collection(COLLECTION_NAME) - .getDocument("docId", BaseDocument.class, new DocumentReadOptions().streamTransactionId("abcde")) - .get(); - fail(); - } catch (ExecutionException e) { - assertThat(e.getCause()).isInstanceOf(ArangoDBException.class); - } - } - - @Test - void getStreamTransactions() throws ExecutionException, InterruptedException { - assumeTrue(isSingleServer()); - assumeTrue(isAtLeastVersion(3, 5)); - assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); - - StreamTransactionEntity tx1 = db.beginStreamTransaction(null).get(); - StreamTransactionEntity tx2 = db.beginStreamTransaction(null).get(); - - List createdIds = Arrays.asList(tx1.getId(), tx2.getId()); - Set gotTxs = db.getStreamTransactions().get().stream(). - filter(it -> createdIds.contains(it.getId())).collect(Collectors.toSet()); - - assertThat(gotTxs).hasSameSizeAs(createdIds); - assertThat(gotTxs.stream() - .allMatch(it -> it.getState() == StreamTransactionStatus.running)).isTrue(); - - db.abortStreamTransaction(tx1.getId()).get(); - db.abortStreamTransaction(tx2.getId()).get(); - } - -} diff --git a/driver/src/test/java/com/arangodb/async/UserAgentTest.java b/driver/src/test/java/com/arangodb/async/UserAgentTest.java deleted file mode 100644 index 5ad3e3976..000000000 --- a/driver/src/test/java/com/arangodb/async/UserAgentTest.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.arangodb.async; - - -import com.arangodb.PackageVersion; -import com.arangodb.Request; -import com.arangodb.Response; -import com.arangodb.config.ArangoConfigProperties; -import com.fasterxml.jackson.databind.JsonNode; -import org.junit.jupiter.api.Test; - -import java.util.concurrent.ExecutionException; - -import static org.assertj.core.api.Assertions.assertThat; - -class UserAgentTest { - @Test - void userAgentHeader() throws ExecutionException, InterruptedException { - ArangoDBAsync adb = new ArangoDBAsync.Builder() - .loadProperties(ArangoConfigProperties.fromFile()) - .build(); - - Response resp = adb.execute(Request.builder() - .method(Request.Method.GET) - .path("/_admin/echo") - .build(), JsonNode.class) - .get(); - String headerValue = resp.getBody().get("headers").get("x-arango-driver").textValue(); - - String jvmVersion = System.getProperty("java.specification.version"); - String expected = "JavaDriver/" + PackageVersion.VERSION + " (JVM/" + jvmVersion + ")"; - - assertThat(headerValue).isEqualTo(expected); - adb.shutdown(); - } -} \ No newline at end of file diff --git a/driver/src/test/java/com/arangodb/async/debug/ConsolidationIntervalMsecTest.java b/driver/src/test/java/com/arangodb/async/debug/ConsolidationIntervalMsecTest.java deleted file mode 100644 index 330ce8eb9..000000000 --- a/driver/src/test/java/com/arangodb/async/debug/ConsolidationIntervalMsecTest.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * DISCLAIMER - * - * Copyright 2016 ArangoDB GmbH, Cologne, Germany - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Copyright holder is ArangoDB GmbH, Cologne, Germany - */ - -package com.arangodb.async.debug; - -import com.arangodb.DbName; -import com.arangodb.async.ArangoDBAsync; -import com.arangodb.async.ArangoDatabaseAsync; -import com.arangodb.async.BaseTest; -import com.arangodb.entity.ViewEntity; -import com.arangodb.entity.ViewType; -import com.arangodb.entity.arangosearch.ArangoSearchPropertiesEntity; -import com.arangodb.entity.arangosearch.CollectionLink; -import com.arangodb.entity.arangosearch.FieldLink; -import com.arangodb.model.arangosearch.ArangoSearchCreateOptions; -import org.junit.jupiter.api.Test; - -import java.util.concurrent.ExecutionException; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assumptions.assumeTrue; - -/** - * @author Michele Rastelli - *

- * https://github.com/arangodb/arangodb-java-driver-async/issues/15 - */ -class ConsolidationIntervalMsecTest extends BaseTest { - - @Test - void consolidationIntervalMsec() throws ExecutionException, InterruptedException { - assumeTrue(isAtLeastVersion(3, 4)); - - ArangoDBAsync arango = new ArangoDBAsync.Builder() - .loadProperties(config) - .user("root") - .password("test") - .build(); - - ArangoDatabaseAsync db = arango.db(DbName.of("database_of_things")); - if (db.exists().join()) { - db.drop().join(); - } - - db.create().join(); - db.collection("Thing").create().join(); - - ViewEntity result = db.createArangoSearch("ThingsSearchView", new ArangoSearchCreateOptions() - .consolidationIntervalMsec(60000L) //<== This line breaks it - .link(CollectionLink.on("Thing") - .fields(FieldLink.on("name") - .analyzers("identity")))) - .join(); - - assertThat(result.getName()).isEqualTo("ThingsSearchView"); - assertThat(result.getType()).isEqualTo(ViewType.ARANGO_SEARCH); - - ArangoSearchPropertiesEntity props = db.arangoSearch("ThingsSearchView").getProperties().join(); - assertThat(props.getName()).isEqualTo("ThingsSearchView"); - assertThat(props.getConsolidationIntervalMsec()).isEqualTo(60000L); - assertThat(props.getLinks().iterator().hasNext()).isTrue(); - assertThat(props.getLinks().iterator().next().getName()).isEqualTo("Thing"); - } - -} diff --git a/driver/src/test/java/com/arangodb/async/example/ExampleBase.java b/driver/src/test/java/com/arangodb/async/example/ExampleBase.java deleted file mode 100644 index 7881fd617..000000000 --- a/driver/src/test/java/com/arangodb/async/example/ExampleBase.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * DISCLAIMER - * - * Copyright 2016 ArangoDB GmbH, Cologne, Germany - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Copyright holder is ArangoDB GmbH, Cologne, Germany - */ - -package com.arangodb.async.example; - -import com.arangodb.DbName; -import com.arangodb.async.ArangoCollectionAsync; -import com.arangodb.async.ArangoDBAsync; -import com.arangodb.async.ArangoDatabaseAsync; -import com.arangodb.config.ConfigUtils; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; - -import java.util.concurrent.ExecutionException; - -/** - * @author Mark Vollmary - */ -public class ExampleBase { - - protected static final String COLLECTION_NAME = "json_example_collection"; - private static final DbName DB_NAME = DbName.of("json_example_db"); - protected static ArangoDatabaseAsync db; - protected static ArangoCollectionAsync collection; - private static ArangoDBAsync arangoDB; - - @BeforeAll - static void setUp() throws InterruptedException, ExecutionException { - arangoDB = new ArangoDBAsync.Builder() - .loadProperties(ConfigUtils.loadConfig()) - .build(); - if (arangoDB.db(DB_NAME).exists().get()) { - arangoDB.db(DB_NAME).drop().get(); - } - arangoDB.createDatabase(DB_NAME).get(); - db = arangoDB.db(DB_NAME); - db.createCollection(COLLECTION_NAME).get(); - collection = db.collection(COLLECTION_NAME); - } - - @AfterAll - static void tearDown() throws InterruptedException, ExecutionException { - db.drop().get(); - arangoDB.shutdown(); - } - -} diff --git a/driver/src/test/java/com/arangodb/async/example/document/AqlQueryWithSpecialReturnTypesExampleTest.java b/driver/src/test/java/com/arangodb/async/example/document/AqlQueryWithSpecialReturnTypesExampleTest.java deleted file mode 100644 index 9ab6624df..000000000 --- a/driver/src/test/java/com/arangodb/async/example/document/AqlQueryWithSpecialReturnTypesExampleTest.java +++ /dev/null @@ -1,128 +0,0 @@ -/* - * DISCLAIMER - * - * Copyright 2016 ArangoDB GmbH, Cologne, Germany - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Copyright holder is ArangoDB GmbH, Cologne, Germany - */ - -package com.arangodb.async.example.document; - -import com.arangodb.async.example.ExampleBase; -import com.arangodb.entity.BaseDocument; -import com.fasterxml.jackson.databind.node.ArrayNode; -import com.fasterxml.jackson.databind.node.ObjectNode; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; - -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.UUID; -import java.util.concurrent.ExecutionException; - -import static org.assertj.core.api.Assertions.assertThat; - - -/** - * @author Mark Vollmary - */ -class AqlQueryWithSpecialReturnTypesExampleTest extends ExampleBase { - - @BeforeAll - static void before() throws InterruptedException, ExecutionException { - createExamples(); - } - - private static void createExamples() throws InterruptedException, ExecutionException { - for (int i = 0; i < 100; i++) { - final BaseDocument value = new BaseDocument(UUID.randomUUID().toString()); - 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).get(); - } - } - - @Test - void aqlWithLimitQueryAsJsonObject() throws InterruptedException, ExecutionException { - final String query = "FOR t IN " + COLLECTION_NAME - + " FILTER t.age >= 20 && t.age < 30 && t.gender == @gender RETURN t"; - final Map bindVars = Collections.singletonMap("gender", Gender.FEMALE); - db.query(query, bindVars, null, ObjectNode.class) - .whenComplete((cursor, ex) -> cursor.forEachRemaining(node -> { - assertThat(node.get("name").asText()).isIn("TestUser11", "TestUser13", "TestUser15", "TestUser17" - , "TestUser19"); - assertThat(node.get("gender").asText()).isEqualTo(Gender.FEMALE.name()); - assertThat(node.get("age").asInt()).isIn(21, 23, 25, 27, 29); - })) - .get(); - } - - @Test - void aqlWithLimitQueryAsArrayNode() throws InterruptedException, ExecutionException { - 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 = Collections.singletonMap("gender", Gender.FEMALE); - db.query(query, bindVars, null, ArrayNode.class) - .whenComplete((cursor, ex) -> cursor.forEachRemaining(arrNode -> { - assertThat(arrNode.get(0).asText()).isIn("TestUser11", "TestUser13", "TestUser15", "TestUser17", - "TestUser19"); - assertThat(arrNode.get(1).asText()).isEqualTo(Gender.FEMALE.name()); - assertThat(arrNode.get(2).asInt()).isIn(21, 23, 25, 27, 29); - })) - .get(); - } - - @Test - void aqlWithLimitQueryAsMap() throws InterruptedException, ExecutionException { - final String query = "FOR t IN " + COLLECTION_NAME - + " FILTER t.age >= 20 && t.age < 30 && t.gender == @gender RETURN t"; - final Map bindVars = Collections.singletonMap("gender", Gender.FEMALE); - db.query(query, bindVars, null, Map.class) - .whenComplete((cursor, ex) -> cursor.forEachRemaining(map -> { - assertThat(map.get("name")).isNotNull(); - assertThat(String.valueOf(map.get("name"))).isIn("TestUser11", "TestUser13", "TestUser15", - "TestUser17", "TestUser19"); - assertThat(map.get("gender")).isNotNull(); - assertThat(String.valueOf(map.get("gender"))).isEqualTo(Gender.FEMALE.name()); - assertThat(map.get("age")).isNotNull(); - assertThat(Long.valueOf(map.get("age").toString())).isIn(21L, 23L, 25L, 27L, 29L); - })) - .get(); - } - - @Test - void aqlWithLimitQueryAsList() throws InterruptedException, ExecutionException { - 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 = Collections.singletonMap("gender", Gender.FEMALE); - db.query(query, bindVars, null, List.class) - .whenComplete((cursor, ex) -> cursor.forEachRemaining(list -> { - assertThat(list.get(0)).isNotNull(); - assertThat(String.valueOf(list.get(0))).isIn("TestUser11", "TestUser13", "TestUser15", - "TestUser17", "TestUser19"); - assertThat(list.get(1)).isNotNull(); - assertThat(Gender.valueOf(String.valueOf(list.get(1)))).isEqualTo(Gender.FEMALE); - assertThat(list.get(2)).isNotNull(); - assertThat(Long.valueOf(String.valueOf(list.get(2)))).isIn(21L, 23L, 25L, 27L, 29L); - })) - .get(); - } - - public enum Gender { - MALE, FEMALE - } -} diff --git a/driver/src/test/java/com/arangodb/async/example/document/GetDocumentExampleTest.java b/driver/src/test/java/com/arangodb/async/example/document/GetDocumentExampleTest.java deleted file mode 100644 index 01a6c149d..000000000 --- a/driver/src/test/java/com/arangodb/async/example/document/GetDocumentExampleTest.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * DISCLAIMER - * - * Copyright 2016 ArangoDB GmbH, Cologne, Germany - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Copyright holder is ArangoDB GmbH, Cologne, Germany - */ - -package com.arangodb.async.example.document; - -import com.arangodb.async.example.ExampleBase; -import com.arangodb.entity.BaseDocument; -import com.arangodb.util.RawJson; -import com.fasterxml.jackson.databind.JsonNode; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; - -import java.util.UUID; -import java.util.concurrent.ExecutionException; - -import static org.assertj.core.api.Assertions.assertThat; - - -/** - * @author Mark Vollmary - */ -class GetDocumentExampleTest extends ExampleBase { - - private static String key = null; - - @BeforeAll - static void before() throws InterruptedException, ExecutionException { - final BaseDocument value = new BaseDocument(UUID.randomUUID().toString()); - value.addAttribute("foo", "bar"); - key = collection.insertDocument(value).get().getKey(); - } - - @Test - void getAsBean() throws InterruptedException, ExecutionException { - collection.getDocument(key, TestEntity.class) - .whenComplete((doc, ex) -> { - assertThat(doc).isNotNull(); - assertThat(doc.getFoo()).isEqualTo("bar"); - }) - .get(); - } - - @Test - void getAsBaseDocument() throws InterruptedException, ExecutionException { - collection.getDocument(key, BaseDocument.class) - .whenComplete((doc, ex) -> { - assertThat(doc).isNotNull(); - assertThat(doc.getAttribute("foo")).isNotNull(); - assertThat(String.valueOf(doc.getAttribute("foo"))).isEqualTo("bar"); - }) - .get(); - } - - @Test - void getAsJsonNode() throws InterruptedException, ExecutionException { - collection.getDocument(key, JsonNode.class) - .whenComplete((doc, ex) -> { - assertThat(doc).isNotNull(); - assertThat(doc.get("foo").isTextual()).isEqualTo(true); - assertThat(doc.get("foo").asText()).isEqualTo("bar"); - }) - .get(); - } - - @Test - void getAsJson() throws InterruptedException, ExecutionException { - collection.getDocument(key, RawJson.class) - .whenComplete((doc, ex) -> { - assertThat(doc.getValue()) - .isNotNull() - .contains("foo") - .contains("bar"); - }) - .get(); - } - -} diff --git a/driver/src/test/java/com/arangodb/async/example/document/ImportDocumentExampleTest.java b/driver/src/test/java/com/arangodb/async/example/document/ImportDocumentExampleTest.java deleted file mode 100644 index dacf1bd87..000000000 --- a/driver/src/test/java/com/arangodb/async/example/document/ImportDocumentExampleTest.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * DISCLAIMER - * - * Copyright 2016 ArangoDB GmbH, Cologne, Germany - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Copyright holder is ArangoDB GmbH, Cologne, Germany - */ - -package com.arangodb.async.example.document; - -import com.arangodb.async.example.ExampleBase; -import com.arangodb.entity.DocumentImportEntity; -import com.arangodb.model.DocumentImportOptions; -import org.junit.jupiter.api.Test; - -import java.util.List; -import java.util.UUID; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.atomic.AtomicLong; -import java.util.stream.Collectors; -import java.util.stream.IntStream; -import java.util.stream.Stream; - -import static org.junit.jupiter.api.Assertions.fail; - -/** - * @author Michele Rastelli - */ -class ImportDocumentExampleTest extends ExampleBase { - - private static final int MAX_PENDING_REQUESTS = 10; - - @Test - void importDocument() { - AtomicLong pendingReqsCount = new AtomicLong(); - - Stream> chunks = IntStream.range(0, 100) - .mapToObj(i -> IntStream.range(0, 500) - .mapToObj(it -> new TestEntity(UUID.randomUUID().toString())).collect(Collectors.toList()) - ); - - List> completableFutures = chunks - .map(p -> { - // wait for pending requests - while (pendingReqsCount.get() > MAX_PENDING_REQUESTS) { - try { - Thread.sleep(10); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - - pendingReqsCount.incrementAndGet(); - return collection.importDocuments(p, new DocumentImportOptions()) - .thenApply(it -> { - pendingReqsCount.decrementAndGet(); - return it; - }); - } - ) - .collect(Collectors.toList()); - - completableFutures.forEach(cf -> { - try { - cf.get(); - } catch (InterruptedException | ExecutionException e) { - e.printStackTrace(); - fail(); - } - }); - - } - -} diff --git a/driver/src/test/java/com/arangodb/async/example/document/InsertDocumentExampleTest.java b/driver/src/test/java/com/arangodb/async/example/document/InsertDocumentExampleTest.java deleted file mode 100644 index e55eda546..000000000 --- a/driver/src/test/java/com/arangodb/async/example/document/InsertDocumentExampleTest.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * DISCLAIMER - * - * Copyright 2016 ArangoDB GmbH, Cologne, Germany - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Copyright holder is ArangoDB GmbH, Cologne, Germany - */ - -package com.arangodb.async.example.document; - -import com.arangodb.async.example.ExampleBase; -import com.arangodb.entity.BaseDocument; -import com.arangodb.util.RawJson; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.node.ObjectNode; -import org.junit.jupiter.api.Test; - -import java.util.UUID; -import java.util.concurrent.ExecutionException; - -import static org.assertj.core.api.Assertions.assertThat; - - -/** - * @author Mark Vollmary - */ -class InsertDocumentExampleTest extends ExampleBase { - - @Test - void insertBean() throws ExecutionException, InterruptedException { - collection.insertDocument(new TestEntity("bar")) - .whenComplete((doc, ex) -> assertThat(doc.getKey()).isNotNull()) - .get(); - } - - @Test - void insertBaseDocument() throws ExecutionException, InterruptedException { - final BaseDocument value = new BaseDocument(UUID.randomUUID().toString()); - value.addAttribute("foo", "bar"); - collection.insertDocument(value) - .whenComplete((doc, ex) -> assertThat(doc.getKey()).isNotNull()) - .get(); - } - - @Test - void insertJsonNode() throws ExecutionException, InterruptedException { - ObjectMapper mapper = new ObjectMapper(); - ObjectNode node = mapper.createObjectNode(); - node.put("foo", "bar"); - collection.insertDocument(node) - .whenComplete((doc, ex) -> assertThat(doc.getKey()).isNotNull()) - .get(); - } - - @Test - void insertJson() throws ExecutionException, InterruptedException { - collection.insertDocument(RawJson.of("{\"foo\":\"bar\"}")) - .whenComplete((doc, ex) -> assertThat(doc.getKey()).isNotNull()) - .get(); - } - -} diff --git a/driver/src/test/java/com/arangodb/async/example/document/TestEntity.java b/driver/src/test/java/com/arangodb/async/example/document/TestEntity.java deleted file mode 100644 index 2ef89c19f..000000000 --- a/driver/src/test/java/com/arangodb/async/example/document/TestEntity.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * DISCLAIMER - * - * Copyright 2016 ArangoDB GmbH, Cologne, Germany - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Copyright holder is ArangoDB GmbH, Cologne, Germany - */ - -package com.arangodb.async.example.document; - -/** - * @author Mark Vollmary - */ -public class TestEntity { - - private String foo; - - public TestEntity() { - super(); - } - - public TestEntity(final String foo) { - super(); - this.foo = foo; - } - - public String getFoo() { - return foo; - } - - void setFoo(final String foo) { - this.foo = foo; - } - -} diff --git a/driver/src/test/java/com/arangodb/async/example/graph/AQLActorsAndMoviesExampleTest.java b/driver/src/test/java/com/arangodb/async/example/graph/AQLActorsAndMoviesExampleTest.java deleted file mode 100644 index d21f78f02..000000000 --- a/driver/src/test/java/com/arangodb/async/example/graph/AQLActorsAndMoviesExampleTest.java +++ /dev/null @@ -1,605 +0,0 @@ -/* - * DISCLAIMER - * - * Copyright 2016 ArangoDB GmbH, Cologne, Germany - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Copyright holder is ArangoDB GmbH, Cologne, Germany - */ - -package com.arangodb.async.example.graph; - -import com.arangodb.DbName; -import com.arangodb.async.ArangoCollectionAsync; -import com.arangodb.async.ArangoCursorAsync; -import com.arangodb.async.ArangoDBAsync; -import com.arangodb.async.ArangoDatabaseAsync; -import com.arangodb.config.ConfigUtils; -import com.arangodb.entity.BaseDocument; -import com.arangodb.entity.BaseEdgeDocument; -import com.arangodb.entity.CollectionType; -import com.arangodb.entity.DocumentCreateEntity; -import com.arangodb.model.CollectionCreateOptions; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; - -import java.util.UUID; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutionException; - -import static org.assertj.core.api.Assertions.assertThat; - - -/** - * @author Mark Vollmary - * @see - * AQL Example Queries on an - * Actors and Movies Database - */ -class AQLActorsAndMoviesExampleTest { - - private static final DbName TEST_DB = DbName.of("actors_movies_test_db"); - private static ArangoDBAsync arangoDB; - private static ArangoDatabaseAsync db; - - @BeforeAll - static void setUp() throws InterruptedException, ExecutionException { - arangoDB = new ArangoDBAsync.Builder() - .loadProperties(ConfigUtils.loadConfig()) - .build(); - if (arangoDB.db(TEST_DB).exists().get()) { - arangoDB.db(TEST_DB).drop().get(); - } - arangoDB.createDatabase(TEST_DB).get(); - db = arangoDB.db(TEST_DB); - createData(); - } - - @AfterAll - static void tearDown() throws InterruptedException, ExecutionException { - db.drop().get(); - arangoDB.shutdown(); - } - - private static DocumentCreateEntity saveMovie( - final ArangoCollectionAsync movies, - final String key, - final String title, - final int released, - final String tagline) throws InterruptedException, ExecutionException { - final BaseDocument value = new BaseDocument(UUID.randomUUID().toString()); - value.setKey(key); - value.addAttribute("title", title); - value.addAttribute("released", released); - value.addAttribute("tagline", tagline); - return movies.insertDocument(value).get(); - } - - private static DocumentCreateEntity saveActor( - final ArangoCollectionAsync actors, - final String key, - final String name, - final int born) throws InterruptedException, ExecutionException { - final BaseDocument value = new BaseDocument(UUID.randomUUID().toString()); - value.setKey(key); - value.addAttribute("name", name); - value.addAttribute("born", born); - return actors.insertDocument(value).get(); - } - - private static void saveActsIn( - final ArangoCollectionAsync actsIn, - final String actor, - final String movie, - final String[] roles, - final int year) throws InterruptedException, ExecutionException { - final BaseEdgeDocument value = new BaseEdgeDocument(); - value.setFrom(actor); - value.setTo(movie); - value.addAttribute("roles", roles); - value.addAttribute("year", year); - actsIn.insertDocument(value).get(); - } - - private static void createData() throws InterruptedException, ExecutionException { - db.createCollection("actors").get(); - final ArangoCollectionAsync actors = db.collection("actors"); - db.createCollection("movies").get(); - final ArangoCollectionAsync movies = db.collection("movies"); - db.createCollection("actsIn", new CollectionCreateOptions().type(CollectionType.EDGES)).get(); - final ArangoCollectionAsync 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); - } - - /** - * @throws ExecutionException - * @throws InterruptedException - * @see AQL - * Example Queries on an Actors and Movies Database - */ - @Test - void allActorsActsInMovie1or2() throws InterruptedException, ExecutionException { - final CompletableFuture> f = db.query( - "WITH actors, movies FOR x IN ANY 'movies/TheMatrix' actsIn OPTIONS {bfs: true, uniqueVertices: " + - "'global'} RETURN x._id", - null, null, String.class); - f.whenComplete((cursor, ex) -> assertThat(cursor.asListRemaining()).contains("actors/Keanu", "actors/Hugo", - "actors/Emil", "actors/Carrie", "actors/Laurence")).get(); - } - - /** - * @throws ExecutionException - * @throws InterruptedException - * @see AQL - * Example Queries on an Actors and Movies Database - */ - @Test - void allActorsActsInMovie1or2UnionDistinct() throws InterruptedException, ExecutionException { - final CompletableFuture> f = db.query( - "WITH actors, movies 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); - f.whenComplete((cursor, ex) -> assertThat(cursor.asListRemaining()).contains( - "actors/Emil", "actors/Hugo", "actors/Carrie", - "actors/Laurence", "actors/Keanu", "actors/Al", "actors/Charlize")).get(); - } - - /** - * @throws ExecutionException - * @throws InterruptedException - * @see AQL - * Example Queries on an Actors and Movies Database - */ - @Test - void allActorsActsInMovie1and2() throws InterruptedException, ExecutionException { - final CompletableFuture> f = db.query( - "WITH actors, movies 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); - f.whenComplete((cursor, ex) -> assertThat(cursor.asListRemaining()).contains("actors/Keanu")).get(); - } - - /** - * @throws ExecutionException - * @throws InterruptedException - * @see AQL - * Example Queries on an Actors and Movies Database - */ - @Test - void allMoviesBetweenActor1andActor2() throws InterruptedException, ExecutionException { - final CompletableFuture> f = db.query( - "WITH actors, 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); - f.whenComplete((cursor, ex) -> assertThat(cursor.asListRemaining()).contains("movies/TheMatrixRevolutions", - "movies/TheMatrixReloaded", "movies/TheMatrix")).get(); - } - - /** - * @throws ExecutionException - * @throws InterruptedException - * @see AQL - * Example Queries on an Actors and Movies Database - */ - @Test - void allActorsWhoActedIn3orMoreMovies() throws InterruptedException, ExecutionException { - final CompletableFuture> f = 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); - f.whenComplete((cursor, ex) -> assertThat(cursor.asListRemaining()).contains( - 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))).get(); - } - - /** - * @throws ExecutionException - * @throws InterruptedException - * @see AQL - * Example Queries on an Actors and Movies Database - */ - @Test - void allMoviesWhereExactly6ActorsActedIn() throws InterruptedException, ExecutionException { - final CompletableFuture> f = db.query( - "FOR x IN actsIn COLLECT movie = x._to WITH COUNT INTO counter FILTER counter == 6 RETURN movie", null, - null, String.class); - f.whenComplete((cursor, ex) -> assertThat(cursor.asListRemaining()).contains("movies/SleeplessInSeattle", - "movies/TopGun", "movies/YouveGotMail")).get(); - } - - /** - * @throws ExecutionException - * @throws InterruptedException - * @see AQL - * Example Queries on an Actors and Movies Database - */ - @Test - void theNumberOfActorsByMovie() throws InterruptedException, ExecutionException { - final CompletableFuture> f = db.query( - "FOR x IN actsIn COLLECT movie = x._to WITH COUNT INTO counter RETURN {movie: movie, actors: counter}", - null, null, Movie.class); - f.whenComplete((cursor, ex) -> assertThat(cursor.asListRemaining()).contains( - 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))).get(); - } - - /** - * @throws ExecutionException - * @throws InterruptedException - * @see AQL - * Example Queries on an Actors and Movies Database - */ - @Test - void theNumberOfMoviesByActor() throws InterruptedException, ExecutionException { - final CompletableFuture> f = db.query( - "FOR x IN actsIn COLLECT actor = x._from WITH COUNT INTO counter RETURN {actor: actor, movies: " + - "counter}", - null, null, Actor.class); - f.whenComplete((cursor, ex) -> assertThat(cursor.asListRemaining()).contains( - 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))).get(); - } - - /** - * @throws ExecutionException - * @throws InterruptedException - * @see AQL - * Example Queries on an Actors and Movies Database - */ - @Test - void theNumberOfMoviesActedInBetween2005and2010byActor() throws InterruptedException, ExecutionException { - final CompletableFuture> f = 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); - f.whenComplete((cursor, ex) -> assertThat(cursor.asListRemaining()).contains( - 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))).get(); - } - - public static class Actor { - private final String actor; - private final Integer movies; - - - @JsonCreator - public Actor(@JsonProperty("actor") final String actor, @JsonProperty("movies") 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) { - return other.movies == null; - } else return movies.equals(other.movies); - } - - } - - public static class Movie { - private final String movie; - private final Integer actors; - - @JsonCreator - public Movie(@JsonProperty("movie") final String movie, @JsonProperty("actors") 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) { - return other.movie == null; - } else return movie.equals(other.movie); - } - - } - -} diff --git a/driver/src/test/java/com/arangodb/async/example/graph/BaseGraphTest.java b/driver/src/test/java/com/arangodb/async/example/graph/BaseGraphTest.java deleted file mode 100644 index 41a4e6edf..000000000 --- a/driver/src/test/java/com/arangodb/async/example/graph/BaseGraphTest.java +++ /dev/null @@ -1,116 +0,0 @@ -/* - * DISCLAIMER - * - * Copyright 2016 ArangoDB GmbH, Cologne, Germany - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Copyright holder is ArangoDB GmbH, Cologne, Germany - */ - -package com.arangodb.async.example.graph; - -import com.arangodb.DbName; -import com.arangodb.async.ArangoDBAsync; -import com.arangodb.async.ArangoDatabaseAsync; -import com.arangodb.config.ConfigUtils; -import com.arangodb.entity.EdgeDefinition; -import com.arangodb.entity.VertexEntity; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.concurrent.ExecutionException; - -/** - * @author Mark Vollmary - */ -public abstract class BaseGraphTest { - - private static final DbName TEST_DB = DbName.of("java_driver_graph_test_db"); - private static final String GRAPH_NAME = "traversalGraph"; - private static final String EDGE_COLLECTION_NAME = "edges"; - private static final String VERTEX_COLLECTION_NAME = "circles"; - static ArangoDatabaseAsync db; - private static ArangoDBAsync arangoDB; - - @BeforeAll - static void init() throws InterruptedException, ExecutionException { - if (arangoDB == null) { - arangoDB = new ArangoDBAsync.Builder() - .loadProperties(ConfigUtils.loadConfig()) - .build(); - } - if (arangoDB.db(TEST_DB).exists().get()) { - arangoDB.db(TEST_DB).drop().get(); - } - arangoDB.createDatabase(TEST_DB).get(); - BaseGraphTest.db = arangoDB.db(TEST_DB); - - final Collection edgeDefinitions = new ArrayList<>(); - final EdgeDefinition edgeDefinition = new EdgeDefinition().collection(EDGE_COLLECTION_NAME) - .from(VERTEX_COLLECTION_NAME).to(VERTEX_COLLECTION_NAME); - edgeDefinitions.add(edgeDefinition); - db.createGraph(GRAPH_NAME, edgeDefinitions, null).get(); - addExampleElements(); - } - - @AfterAll - static void shutdown() throws InterruptedException, ExecutionException { - arangoDB.db(TEST_DB).drop().get(); - arangoDB.shutdown(); - arangoDB = null; - } - - private static void addExampleElements() throws InterruptedException, ExecutionException { - - // 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 void saveEdge(final CircleEdge edge) - throws InterruptedException, ExecutionException { - db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).insertEdge(edge).get(); - } - - private static VertexEntity createVertex(final Circle vertex) - throws InterruptedException, ExecutionException { - return db.graph(GRAPH_NAME).vertexCollection(VERTEX_COLLECTION_NAME).insertVertex(vertex).get(); - } - -} diff --git a/driver/src/test/java/com/arangodb/async/example/graph/Circle.java b/driver/src/test/java/com/arangodb/async/example/graph/Circle.java deleted file mode 100644 index e828aaeb3..000000000 --- a/driver/src/test/java/com/arangodb/async/example/graph/Circle.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * DISCLAIMER - * - * Copyright 2016 ArangoDB GmbH, Cologne, Germany - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Copyright holder is ArangoDB GmbH, Cologne, Germany - */ - -package com.arangodb.async.example.graph; - -import com.arangodb.serde.jackson.Id; -import com.arangodb.serde.jackson.Key; -import com.arangodb.serde.jackson.Rev; - -/** - * @author a-brandt - */ -class Circle { - - @Id - private String id; - - @Key - private String key; - - @Rev - private String revision; - - private String label; - - public Circle(String key, String label) { - this.key = key; - this.label = label; - } - - public String getId() { - return id; - } - - void setId(String id) { - this.id = id; - } - - public String getKey() { - return key; - } - - void setKey(String key) { - this.key = key; - } - - public String getRevision() { - return revision; - } - - void setRevision(String revision) { - this.revision = revision; - } - - public String getLabel() { - return label; - } - - void setLabel(String label) { - this.label = label; - } - -} diff --git a/driver/src/test/java/com/arangodb/async/example/graph/CircleEdge.java b/driver/src/test/java/com/arangodb/async/example/graph/CircleEdge.java deleted file mode 100644 index bfaa65210..000000000 --- a/driver/src/test/java/com/arangodb/async/example/graph/CircleEdge.java +++ /dev/null @@ -1,122 +0,0 @@ -/* - * DISCLAIMER - * - * Copyright 2016 ArangoDB GmbH, Cologne, Germany - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Copyright holder is ArangoDB GmbH, Cologne, Germany - */ - -package com.arangodb.async.example.graph; - -import com.arangodb.serde.jackson.*; - -/** - * @author a-brandt - */ -class CircleEdge { - - @Id - private String id; - - @Key - private String key; - - @Rev - private String revision; - - @From - private String from; - - @To - private String to; - - private Boolean theFalse; - private Boolean theTruth; - private String label; - - public CircleEdge(final String from, final String to, final Boolean theFalse, final Boolean theTruth, - final String label) { - this.from = from; - this.to = to; - this.theFalse = theFalse; - this.theTruth = theTruth; - this.label = label; - } - - public String getId() { - return id; - } - - void setId(String id) { - this.id = id; - } - - public String getKey() { - return key; - } - - void setKey(String key) { - this.key = key; - } - - public String getRevision() { - return revision; - } - - void setRevision(String revision) { - this.revision = revision; - } - - public String getFrom() { - return from; - } - - void setFrom(String from) { - this.from = from; - } - - public String getTo() { - return to; - } - - void setTo(String to) { - this.to = to; - } - - public Boolean getTheFalse() { - return theFalse; - } - - void setTheFalse(Boolean theFalse) { - this.theFalse = theFalse; - } - - public Boolean getTheTruth() { - return theTruth; - } - - void setTheTruth(Boolean theTruth) { - this.theTruth = theTruth; - } - - public String getLabel() { - return label; - } - - void setLabel(String label) { - this.label = label; - } - -} diff --git a/driver/src/test/java/com/arangodb/async/example/graph/GraphTraversalsInAQLExampleTest.java b/driver/src/test/java/com/arangodb/async/example/graph/GraphTraversalsInAQLExampleTest.java deleted file mode 100644 index b3628f572..000000000 --- a/driver/src/test/java/com/arangodb/async/example/graph/GraphTraversalsInAQLExampleTest.java +++ /dev/null @@ -1,122 +0,0 @@ -/* - * DISCLAIMER - * - * Copyright 2016 ArangoDB GmbH, Cologne, Germany - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Copyright holder is ArangoDB GmbH, Cologne, Germany - */ - -package com.arangodb.async.example.graph; - -import com.arangodb.async.ArangoCursorAsync; -import org.junit.jupiter.api.Test; - -import java.util.Collection; -import java.util.concurrent.ExecutionException; - -import static org.assertj.core.api.Assertions.assertThat; - - -/** - * Graph traversals in AQL - * - * @author a-brandt - * @see Graph traversals in AQL - */ -class GraphTraversalsInAQLExampleTest extends BaseGraphTest { - - @Test - void queryAllVertices() throws InterruptedException, ExecutionException { - String queryString = "FOR v IN 1..3 OUTBOUND 'circles/A' GRAPH 'traversalGraph' RETURN v._key"; - ArangoCursorAsync cursor = db.query(queryString, null, null, String.class).get(); - Collection result = cursor.asListRemaining(); - assertThat(result).hasSize(10); - - queryString = "WITH circles FOR v IN 1..3 OUTBOUND 'circles/A' edges RETURN v._key"; - cursor = db.query(queryString, null, null, String.class).get(); - result = cursor.asListRemaining(); - assertThat(result).hasSize(10); - } - - @Test - void queryDepthTwo() throws InterruptedException, ExecutionException { - String queryString = "FOR v IN 2..2 OUTBOUND 'circles/A' GRAPH 'traversalGraph' return v._key"; - ArangoCursorAsync cursor = db.query(queryString, null, null, String.class).get(); - Collection result = cursor.asListRemaining(); - assertThat(result).hasSize(4); - assertThat(result).contains("C", "E", "H", "J"); - - queryString = "FOR v IN 2 OUTBOUND 'circles/A' GRAPH 'traversalGraph' return v._key"; - cursor = db.query(queryString, null, null, String.class).get(); - result = cursor.asListRemaining(); - assertThat(result).hasSize(4); - assertThat(result).contains("C", "E", "H", "J"); - } - - @Test - void queryWithFilter() throws InterruptedException, ExecutionException { - String queryString = "FOR v, e, p IN 1..3 OUTBOUND 'circles/A' GRAPH 'traversalGraph' FILTER p.vertices[1]" + - "._key != 'G' RETURN v._key"; - ArangoCursorAsync cursor = db.query(queryString, null, null, String.class).get(); - Collection result = cursor.asListRemaining(); - assertThat(result).hasSize(5); - assertThat(result).contains("B", "C", "D", "E", "F"); - - queryString = "FOR v, e, p IN 1..3 OUTBOUND 'circles/A' GRAPH 'traversalGraph' FILTER p.edges[0].label != " + - "'right_foo' RETURN v._key"; - cursor = db.query(queryString, null, null, String.class).get(); - result = cursor.asListRemaining(); - assertThat(result).hasSize(5); - assertThat(result).contains("B", "C", "D", "E", "F"); - - queryString = "FOR v,e,p IN 1..3 OUTBOUND 'circles/A' GRAPH 'traversalGraph' FILTER p.vertices[1]._key != 'G'" + - " FILTER p.edges[1].label != 'left_blub' return v._key"; - cursor = db.query(queryString, null, null, String.class).get(); - - result = cursor.asListRemaining(); - assertThat(result).hasSize(3); - assertThat(result).contains("B", "C", "D"); - - queryString = "FOR v,e,p IN 1..3 OUTBOUND 'circles/A' GRAPH 'traversalGraph' FILTER p.vertices[1]._key != 'G'" + - " AND p.edges[1].label != 'left_blub' return v._key"; - cursor = db.query(queryString, null, null, String.class).get(); - result = cursor.asListRemaining(); - assertThat(result).hasSize(3); - assertThat(result).contains("B", "C", "D"); - } - - @Test - void queryOutboundInbound() throws InterruptedException, ExecutionException { - String queryString = "FOR v IN 1..3 OUTBOUND 'circles/E' GRAPH 'traversalGraph' return v._key"; - ArangoCursorAsync cursor = db.query(queryString, null, null, String.class).get(); - Collection result = cursor.asListRemaining(); - assertThat(result).hasSize(1); - assertThat(result).contains("F"); - - queryString = "FOR v IN 1..3 INBOUND 'circles/E' GRAPH 'traversalGraph' return v._key"; - cursor = db.query(queryString, null, null, String.class).get(); - result = cursor.asListRemaining(); - assertThat(result).hasSize(2); - assertThat(result).contains("B", "A"); - - queryString = "FOR v IN 1..3 ANY 'circles/E' GRAPH 'traversalGraph' return v._key"; - cursor = db.query(queryString, null, null, String.class).get(); - - result = cursor.asListRemaining(); - assertThat(result).hasSize(6); - assertThat(result).contains("F", "B", "C", "D", "A", "G"); - } - -} diff --git a/driver/src/test/java/com/arangodb/async/example/graph/ShortestPathInAQLExampleTest.java b/driver/src/test/java/com/arangodb/async/example/graph/ShortestPathInAQLExampleTest.java deleted file mode 100644 index 515f8e13f..000000000 --- a/driver/src/test/java/com/arangodb/async/example/graph/ShortestPathInAQLExampleTest.java +++ /dev/null @@ -1,106 +0,0 @@ -/* - * DISCLAIMER - * - * Copyright 2016 ArangoDB GmbH, Cologne, Germany - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Copyright holder is ArangoDB GmbH, Cologne, Germany - */ - -package com.arangodb.async.example.graph; - -import com.arangodb.async.ArangoCursorAsync; -import org.junit.jupiter.api.Test; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.concurrent.ExecutionException; - -import static org.assertj.core.api.Assertions.assertThat; - - -/** - * Shortest Path in AQL - * - * @author a-brandt - * @see Shortest Path in AQL - */ -class ShortestPathInAQLExampleTest extends BaseGraphTest { - - @Test - void queryShortestPathFromAToD() throws InterruptedException, ExecutionException { - String queryString = "FOR v, e IN OUTBOUND SHORTEST_PATH 'circles/A' TO 'circles/D' GRAPH 'traversalGraph' " + - "RETURN {'vertex': v._key, 'edge': e._key}"; - ArangoCursorAsync cursor = db.query(queryString, null, null, Pair.class).get(); - final Collection collection = toVertexCollection(cursor); - assertThat(collection).hasSize(4); - assertThat(collection).contains("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}"; - db.query(queryString, null, null, Pair.class).get(); - assertThat(collection).hasSize(4); - assertThat(collection).contains("A", "B", "C", "D"); - } - - @Test - void queryShortestPathByFilter() throws InterruptedException, ExecutionException { - String 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 GRAPH 'traversalGraph' RETURN {'vertex':v._key, 'edge':e._key}"; - ArangoCursorAsync cursor = db.query(queryString, null, null, Pair.class).get(); - final Collection collection = toVertexCollection(cursor); - assertThat(collection).hasSize(4); - assertThat(collection).contains("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}"; - db.query(queryString, null, null, Pair.class).get(); - assertThat(collection).hasSize(4); - assertThat(collection).contains("A", "B", "C", "D"); - } - - private Collection toVertexCollection(final ArangoCursorAsync cursor) { - final List result = new ArrayList<>(); - while (cursor.hasNext()) { - final Pair pair = cursor.next(); - result.add(pair.getVertex()); - } - return result; - } - - public static class Pair { - - private String vertex; - private String edge; - - public String getVertex() { - return vertex; - } - - void setVertex(final String vertex) { - this.vertex = vertex; - } - - public String getEdge() { - return edge; - } - - void setEdge(final String edge) { - this.edge = edge; - } - - } - -} diff --git a/driver/src/test/java/com/arangodb/async/example/ssl/SslExampleTest.java b/driver/src/test/java/com/arangodb/async/example/ssl/SslExampleTest.java deleted file mode 100644 index c90175310..000000000 --- a/driver/src/test/java/com/arangodb/async/example/ssl/SslExampleTest.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * DISCLAIMER - * - * Copyright 2016 ArangoDB GmbH, Cologne, Germany - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Copyright holder is ArangoDB GmbH, Cologne, Germany - */ - -package com.arangodb.async.example.ssl; - -import com.arangodb.async.ArangoDBAsync; -import com.arangodb.entity.ArangoDBVersion; -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.condition.EnabledIfSystemProperty; - -import javax.net.ssl.KeyManagerFactory; -import javax.net.ssl.SSLContext; -import javax.net.ssl.TrustManagerFactory; -import java.security.KeyStore; - -import static org.assertj.core.api.Assertions.assertThat; - - -/** - * @author Mark Vollmary - */ -@Tag("ssl") -@EnabledIfSystemProperty(named = "SslTest", matches = "true") -class SslExampleTest { - - /*- - * a SSL trust store - * - * create the trust store for the self signed certificate: - * keytool -import -alias "my arangodb server cert" -file UnitTests/server.pem -keystore example.truststore - * - * Documentation: - * https://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/conn/ssl/SSLSocketFactory.html - */ - private static final String SSL_TRUSTSTORE = "/example.truststore"; - private static final String SSL_TRUSTSTORE_PASSWORD = "12345678"; - - @Test - void connect() throws Exception { - final KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); - ks.load(this.getClass().getResourceAsStream(SSL_TRUSTSTORE), SSL_TRUSTSTORE_PASSWORD.toCharArray()); - - final KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); - kmf.init(ks, SSL_TRUSTSTORE_PASSWORD.toCharArray()); - - final TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); - tmf.init(ks); - - final SSLContext sc = SSLContext.getInstance("TLS"); - sc.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); - - final ArangoDBAsync arangoDB = new ArangoDBAsync.Builder() - .host("localhost", 8529) - .password("test") - .useSsl(true) - .sslContext(sc).build(); - final ArangoDBVersion version = arangoDB.getVersion().get(); - assertThat(version).isNotNull(); - } - -} diff --git a/driver/src/test/java/com/arangodb/async/serde/CustomSerdeTest.java b/driver/src/test/java/com/arangodb/async/serde/CustomSerdeTest.java deleted file mode 100644 index 616dc1b1f..000000000 --- a/driver/src/test/java/com/arangodb/async/serde/CustomSerdeTest.java +++ /dev/null @@ -1,176 +0,0 @@ -/* - * DISCLAIMER - * - * Copyright 2016 ArangoDB GmbH, Cologne, Germany - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Copyright holder is ArangoDB GmbH, Cologne, Germany - */ - -package com.arangodb.async.serde; - - -import com.arangodb.DbName; -import com.arangodb.async.ArangoCollectionAsync; -import com.arangodb.async.ArangoDBAsync; -import com.arangodb.async.ArangoDatabaseAsync; -import com.arangodb.config.ConfigUtils; -import com.arangodb.model.DocumentCreateOptions; -import com.arangodb.ContentType; -import com.arangodb.serde.jackson.JacksonSerde; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import java.math.BigInteger; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; -import java.util.concurrent.ExecutionException; - -import static com.fasterxml.jackson.databind.DeserializationFeature.USE_BIG_INTEGER_FOR_INTS; -import static com.fasterxml.jackson.databind.SerializationFeature.WRITE_SINGLE_ELEM_ARRAYS_UNWRAPPED; -import static org.assertj.core.api.Assertions.assertThat; - - -/** - * @author Michele Rastelli - */ -class CustomSerdeTest { - - private static final String COLLECTION_NAME = "collection"; - - private ArangoDatabaseAsync db; - private ArangoCollectionAsync collection; - - @BeforeEach - void init() throws ExecutionException, InterruptedException { - JacksonSerde serde = JacksonSerde.of(ContentType.VPACK); - serde.configure((mapper) -> { - mapper.configure(WRITE_SINGLE_ELEM_ARRAYS_UNWRAPPED, true); - mapper.configure(USE_BIG_INTEGER_FOR_INTS, true); - }); - ArangoDBAsync arangoDB = new ArangoDBAsync.Builder() - .loadProperties(ConfigUtils.loadConfig()) - .serde(serde).build(); - - DbName TEST_DB = DbName.of("custom-serde-test"); - db = arangoDB.db(TEST_DB); - if (!db.exists().get()) { - db.create().get(); - } - - collection = db.collection(COLLECTION_NAME); - if (!collection.exists().get()) { - collection.create().get(); - } - } - - @AfterEach - void shutdown() throws ExecutionException, InterruptedException { - db.drop().get(); - } - - @Test - void aqlSerialization() throws ExecutionException, InterruptedException { - String key = "test-" + UUID.randomUUID(); - - Map doc = new HashMap<>(); - doc.put("_key", key); - doc.put("arr", Collections.singletonList("hello")); - doc.put("int", 10); - - HashMap params = new HashMap<>(); - params.put("doc", doc); - params.put("@collection", COLLECTION_NAME); - - Map result = db.query( - "INSERT @doc INTO @@collection RETURN NEW", - params, - Map.class - ).get().next(); - - assertThat(result.get("arr")).isInstanceOf(String.class); - assertThat(result.get("arr")).isEqualTo("hello"); - assertThat(result.get("int")).isInstanceOf(BigInteger.class); - assertThat(result.get("int")).isEqualTo(BigInteger.valueOf(10)); - } - - @Test - void aqlDeserialization() throws ExecutionException, InterruptedException { - String key = "test-" + UUID.randomUUID(); - - Map doc = new HashMap<>(); - doc.put("_key", key); - doc.put("arr", Collections.singletonList("hello")); - doc.put("int", 10); - - collection.insertDocument(doc).get(); - - final Map result = db.query( - "RETURN DOCUMENT(@docId)", - Collections.singletonMap("docId", COLLECTION_NAME + "/" + key), - Map.class - ).get().next(); - - assertThat(result.get("arr")).isInstanceOf(String.class); - assertThat(result.get("arr")).isEqualTo("hello"); - assertThat(result.get("int")).isInstanceOf(BigInteger.class); - assertThat(result.get("int")).isEqualTo(BigInteger.valueOf(10)); - } - - @Test - void insertDocument() throws ExecutionException, InterruptedException { - String key = "test-" + UUID.randomUUID(); - - Map doc = new HashMap<>(); - doc.put("_key", key); - doc.put("arr", Collections.singletonList("hello")); - doc.put("int", 10); - - Map result = collection.insertDocument( - doc, - new DocumentCreateOptions().returnNew(true) - ).get().getNew(); - - assertThat(result.get("arr")).isInstanceOf(String.class); - assertThat(result.get("arr")).isEqualTo("hello"); - assertThat(result.get("int")).isInstanceOf(BigInteger.class); - assertThat(result.get("int")).isEqualTo(BigInteger.valueOf(10)); - } - - @Test - void getDocument() throws ExecutionException, InterruptedException { - String key = "test-" + UUID.randomUUID(); - - Map doc = new HashMap<>(); - doc.put("_key", key); - doc.put("arr", Collections.singletonList("hello")); - doc.put("int", 10); - - collection.insertDocument(doc).get(); - - final Map result = db.collection(COLLECTION_NAME).getDocument( - key, - Map.class, - null).get(); - - assertThat(result.get("arr")).isInstanceOf(String.class); - assertThat(result.get("arr")).isEqualTo("hello"); - assertThat(result.get("int")).isInstanceOf(BigInteger.class); - assertThat(result.get("int")).isEqualTo(BigInteger.valueOf(10)); - } - -} diff --git a/driver/src/test/resources/META-INF/native-image/reflect-config.json b/driver/src/test/resources/META-INF/native-image/reflect-config.json index 904da3577..50aea7d0b 100644 --- a/driver/src/test/resources/META-INF/native-image/reflect-config.json +++ b/driver/src/test/resources/META-INF/native-image/reflect-config.json @@ -36,69 +36,6 @@ "allDeclaredConstructors": true, "allDeclaredClasses": true }, - { - "name": "com.arangodb.async.ArangoDatabaseTest$TransactionTestEntity", - "allDeclaredFields": true, - "allDeclaredMethods": true, - "allPublicMethods": true, - "allDeclaredConstructors": true, - "allDeclaredClasses": true - }, - { - "name": "com.arangodb.async.example.document.AqlQueryWithSpecialReturnTypesExampleTest$Gender", - "allDeclaredFields": true, - "allDeclaredMethods": true, - "allPublicMethods": true, - "allDeclaredClasses": true - }, - { - "name": "com.arangodb.async.example.document.TestEntity", - "allDeclaredFields": true, - "allDeclaredMethods": true, - "allPublicMethods": true, - "allDeclaredConstructors": true, - "allDeclaredClasses": true - }, - { - "name": "com.arangodb.async.example.graph.AQLActorsAndMoviesExampleTest$Actor", - "allDeclaredFields": true, - "allDeclaredMethods": true, - "allPublicMethods": true, - "allDeclaredConstructors": true, - "allDeclaredClasses": true - }, - { - "name": "com.arangodb.async.example.graph.AQLActorsAndMoviesExampleTest$Movie", - "allDeclaredFields": true, - "allDeclaredMethods": true, - "allPublicMethods": true, - "allDeclaredConstructors": true, - "allDeclaredClasses": true - }, - { - "name": "com.arangodb.async.example.graph.Circle", - "allDeclaredFields": true, - "allDeclaredMethods": true, - "allPublicMethods": true, - "allDeclaredConstructors": true, - "allDeclaredClasses": true - }, - { - "name": "com.arangodb.async.example.graph.CircleEdge", - "allDeclaredFields": true, - "allDeclaredMethods": true, - "allPublicMethods": true, - "allDeclaredConstructors": true, - "allDeclaredClasses": true - }, - { - "name": "com.arangodb.async.example.graph.ShortestPathInAQLExampleTest$Pair", - "allDeclaredFields": true, - "allDeclaredMethods": true, - "allPublicMethods": true, - "allDeclaredConstructors": true, - "allDeclaredClasses": true - }, { "name": "com.arangodb.example.document.AqlQueryWithSpecialReturnTypesExampleTest$Gender", "allDeclaredFields": true, @@ -230,28 +167,6 @@ } ] }, - { - "name":"com.arangodb.async.ArangoCollectionTest$Animal", - "allDeclaredMethods":true, - "allPublicMethods":true, - "allDeclaredClasses":true - }, - { - "name":"com.arangodb.async.ArangoCollectionTest$Cat", - "allDeclaredFields":true, - "allDeclaredMethods":true, - "allPublicMethods":true, - "allDeclaredConstructors":true, - "allDeclaredClasses":true - }, - { - "name":"com.arangodb.async.ArangoCollectionTest$Dog", - "allDeclaredFields":true, - "allDeclaredMethods":true, - "allPublicMethods":true, - "allDeclaredConstructors":true, - "allDeclaredClasses":true - }, { "name":"com.arangodb.ArangoCollectionTest$Animal", "allDeclaredMethods":true, diff --git a/resilience-tests/src/test/java/resilience/ActiveFailoverTest.java b/resilience-tests/src/test/java/resilience/ActiveFailoverTest.java index 8b2573a5b..fcf1bbc7d 100644 --- a/resilience-tests/src/test/java/resilience/ActiveFailoverTest.java +++ b/resilience-tests/src/test/java/resilience/ActiveFailoverTest.java @@ -2,7 +2,6 @@ import ch.qos.logback.classic.Level; import com.arangodb.ArangoDB; -import com.arangodb.async.ArangoDBAsync; import resilience.utils.MemoryAppender; import eu.rekawek.toxiproxy.Proxy; import eu.rekawek.toxiproxy.ToxiproxyClient; @@ -65,12 +64,4 @@ protected static ArangoDB.Builder dbBuilder() { return builder; } - protected static ArangoDBAsync.Builder dbBuilderAsync() { - ArangoDBAsync.Builder builder = new ArangoDBAsync.Builder().password(PASSWORD); - for (Endpoint ph : endpoints) { - builder.host(ph.getHost(), ph.getPort()); - } - return builder; - } - } diff --git a/resilience-tests/src/test/java/resilience/ClusterTest.java b/resilience-tests/src/test/java/resilience/ClusterTest.java index a757f5f76..bfa6c0a35 100644 --- a/resilience-tests/src/test/java/resilience/ClusterTest.java +++ b/resilience-tests/src/test/java/resilience/ClusterTest.java @@ -2,7 +2,6 @@ import ch.qos.logback.classic.Level; import com.arangodb.ArangoDB; -import com.arangodb.async.ArangoDBAsync; import resilience.utils.MemoryAppender; import eu.rekawek.toxiproxy.Proxy; import eu.rekawek.toxiproxy.ToxiproxyClient; @@ -65,12 +64,4 @@ protected static ArangoDB.Builder dbBuilder() { return builder; } - protected static ArangoDBAsync.Builder dbBuilderAsync() { - ArangoDBAsync.Builder builder = new ArangoDBAsync.Builder().password(PASSWORD); - for (Endpoint ph : endpoints) { - builder.host(ph.getHost(), ph.getPort()); - } - return builder; - } - } diff --git a/resilience-tests/src/test/java/resilience/SingleServerTest.java b/resilience-tests/src/test/java/resilience/SingleServerTest.java index 05c87d7e2..e16798f49 100644 --- a/resilience-tests/src/test/java/resilience/SingleServerTest.java +++ b/resilience-tests/src/test/java/resilience/SingleServerTest.java @@ -2,7 +2,6 @@ import ch.qos.logback.classic.Level; import com.arangodb.ArangoDB; -import com.arangodb.async.ArangoDBAsync; import resilience.utils.MemoryAppender; import eu.rekawek.toxiproxy.Proxy; import eu.rekawek.toxiproxy.ToxiproxyClient; @@ -51,12 +50,6 @@ protected static ArangoDB.Builder dbBuilder() { .password(PASSWORD); } - protected static ArangoDBAsync.Builder dbBuilderAsync() { - return new ArangoDBAsync.Builder() - .host(endpoint.getHost(), endpoint.getPort()) - .password(PASSWORD); - } - protected void enableEndpoint(){ try { getEndpoint().getProxy().enable(); diff --git a/resilience-tests/src/test/java/resilience/vstKeepAlive/VstKeepAliveCloseAsyncTest.java b/resilience-tests/src/test/java/resilience/vstKeepAlive/VstKeepAliveCloseAsyncTest.java deleted file mode 100644 index 6a751da8d..000000000 --- a/resilience-tests/src/test/java/resilience/vstKeepAlive/VstKeepAliveCloseAsyncTest.java +++ /dev/null @@ -1,54 +0,0 @@ -package resilience.vstKeepAlive; - -import ch.qos.logback.classic.Level; -import com.arangodb.async.ArangoDBAsync; -import resilience.SingleServerTest; -import eu.rekawek.toxiproxy.model.ToxicDirection; -import eu.rekawek.toxiproxy.model.toxic.Latency; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.Timeout; - -import java.io.IOException; -import java.util.concurrent.ExecutionException; - -import static org.awaitility.Awaitility.await; - -/** - * @author Michele Rastelli - */ -class VstKeepAliveCloseAsyncTest extends SingleServerTest { - - private ArangoDBAsync arangoDB; - - @BeforeEach - void init() { - arangoDB = dbBuilderAsync() - .timeout(1000) - .keepAliveInterval(1) - .build(); - } - - @AfterEach - void shutDown() { - arangoDB.shutdown(); - } - - /** - * after 3 consecutive VST keepAlive failures: - * - log ERROR Connection unresponsive - * - reconnect on next request - */ - @Test - @Timeout(10) - void keepAliveCloseAndReconnect() throws IOException, ExecutionException, InterruptedException { - arangoDB.getVersion().get(); - Latency toxic = getEndpoint().getProxy().toxics().latency("latency", ToxicDirection.DOWNSTREAM, 10_000); - await().until(() -> logs.getLoggedEvents().stream() - .filter(e -> e.getLevel().equals(Level.ERROR)) - .anyMatch(e -> e.getMessage().contains("Connection unresponsive!"))); - toxic.setLatency(0L); - arangoDB.getVersion().get(); - } -} diff --git a/shaded/src/main/resources/META-INF/services/com.arangodb.internal.net.AsyncProtocolProvider b/shaded/src/main/resources/META-INF/services/com.arangodb.internal.net.AsyncProtocolProvider deleted file mode 100644 index dc7f09560..000000000 --- a/shaded/src/main/resources/META-INF/services/com.arangodb.internal.net.AsyncProtocolProvider +++ /dev/null @@ -1 +0,0 @@ -com.arangodb.vst.VstAsyncProtocolProvider diff --git a/vst/src/main/java/com/arangodb/vst/VstAsyncProtocolProvider.java b/vst/src/main/java/com/arangodb/vst/VstAsyncProtocolProvider.java deleted file mode 100644 index 8bb1a19d9..000000000 --- a/vst/src/main/java/com/arangodb/vst/VstAsyncProtocolProvider.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.arangodb.vst; - -import com.arangodb.Protocol; -import com.arangodb.internal.config.ArangoConfig; -import com.arangodb.internal.net.*; -import com.arangodb.vst.async.VstCommunicationAsync; -import com.arangodb.vst.async.VstConnectionFactoryAsync; -import com.fasterxml.jackson.databind.Module; - -public class VstAsyncProtocolProvider implements AsyncProtocolProvider { - @Override - public boolean supportsProtocol(Protocol protocol) { - return Protocol.VST.equals(protocol); - } - - @Override - public ConnectionFactory createConnectionFactory() { - return new VstConnectionFactoryAsync(); - } - - @Override - public AsyncCommunication createCommunication(final ArangoConfig config, final HostHandler hostHandler) { - return new VstCommunicationAsync(config, hostHandler); - } - - @Override - public Module protocolModule() { - return VstModule.INSTANCE.get(); - } -} diff --git a/vst/src/main/java/com/arangodb/vst/async/VstCommunicationAsync.java b/vst/src/main/java/com/arangodb/vst/async/VstCommunicationAsync.java deleted file mode 100644 index c787c0cbf..000000000 --- a/vst/src/main/java/com/arangodb/vst/async/VstCommunicationAsync.java +++ /dev/null @@ -1,157 +0,0 @@ -/* - * DISCLAIMER - * - * Copyright 2016 ArangoDB GmbH, Cologne, Germany - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Copyright holder is ArangoDB GmbH, Cologne, Germany - */ - -package com.arangodb.vst.async; - -import com.arangodb.ArangoDBException; -import com.arangodb.config.HostDescription; -import com.arangodb.internal.InternalRequest; -import com.arangodb.internal.InternalResponse; -import com.arangodb.internal.config.ArangoConfig; -import com.arangodb.internal.net.ArangoDBRedirectException; -import com.arangodb.internal.net.AsyncCommunication; -import com.arangodb.internal.net.HostHandle; -import com.arangodb.internal.net.HostHandler; -import com.arangodb.internal.util.HostUtils; -import com.arangodb.velocypack.exception.VPackException; -import com.arangodb.velocypack.exception.VPackParserException; -import com.arangodb.vst.VstCommunication; -import com.arangodb.vst.internal.AuthenticationRequest; -import com.arangodb.vst.internal.JwtAuthenticationRequest; -import com.arangodb.vst.internal.Message; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutionException; - -/** - * @author Mark Vollmary - */ -public class VstCommunicationAsync - extends VstCommunication, VstConnectionAsync> - implements AsyncCommunication { - - private static final Logger LOGGER = LoggerFactory.getLogger(VstCommunicationAsync.class); - - public VstCommunicationAsync(ArangoConfig config, HostHandler hostHandler) { - super(config, hostHandler); - } - - @Override - protected CompletableFuture execute(final InternalRequest request, final VstConnectionAsync connection) { - return execute(request, connection, 0); - } - - @Override - protected CompletableFuture execute(final InternalRequest request, final VstConnectionAsync connection, - final int attemptCount) { - final CompletableFuture rfuture = new CompletableFuture<>(); - try { - final Message message = createMessage(request); - if (LOGGER.isDebugEnabled()) { - String body = request.getBody() == null ? "" : serde.toJsonString(request.getBody()); - LOGGER.debug("Send Request [id={}]: {} {}", message.getId(), request, body); - } - send(message, connection).whenComplete((m, ex) -> { - if (m != null) { - final InternalResponse response; - try { - response = createResponse(m); - } catch (final VPackParserException e) { - LOGGER.error(e.getMessage(), e); - rfuture.completeExceptionally(e); - return; - } - - try { - checkError(response); - } catch (final ArangoDBRedirectException e) { - if (attemptCount >= 3) { - rfuture.completeExceptionally(e); - return; - } - final String location = e.getLocation(); - final HostDescription redirectHost = HostUtils.createFromLocation(location); - hostHandler.failIfNotMatch(redirectHost, e); - execute(request, new HostHandle().setHost(redirectHost), attemptCount + 1) - .whenComplete((v, err) -> { - if (v != null) { - rfuture.complete(v); - } else if (err != null) { - rfuture.completeExceptionally(err); - } else { - rfuture.cancel(true); - } - }); - return; - } catch (ArangoDBException e) { - rfuture.completeExceptionally(e); - } - if (LOGGER.isDebugEnabled()) { - String body = response.getBody() == null ? "" : serde.toJsonString(response.getBody()); - LOGGER.debug("Received Response [id={}]: {} {}", m.getId(), response, body); - } - rfuture.complete(response); - } else if (ex != null) { - LOGGER.error(ex.getMessage(), ex); - rfuture.completeExceptionally(ex); - } else { - rfuture.cancel(true); - } - }); - } catch (final VPackException e) { - LOGGER.error(e.getMessage(), e); - rfuture.completeExceptionally(e); - } - return rfuture; - } - - private CompletableFuture send(final Message message, final VstConnectionAsync connection) { - return connection.write(message, buildChunks(message)); - } - - @Override - protected void authenticate(final VstConnectionAsync connection) { - InternalRequest authRequest; - if (jwt != null) { - authRequest = new JwtAuthenticationRequest(jwt, ENCRYPTION_JWT); - } else { - authRequest = new AuthenticationRequest(user, password != null ? password : "", ENCRYPTION_PLAIN); - } - - InternalResponse response; - try { - response = execute(authRequest, connection).get(); - } catch (final InterruptedException e) { - Thread.currentThread().interrupt(); - throw new ArangoDBException(e); - } catch (final ExecutionException e) { - Throwable cause = e.getCause(); - if (cause instanceof ArangoDBException) { - throw (ArangoDBException) cause; - } else { - throw new ArangoDBException(e.getCause()); - } - } - checkError(response); - } - -} diff --git a/vst/src/main/java/com/arangodb/vst/async/VstConnectionAsync.java b/vst/src/main/java/com/arangodb/vst/async/VstConnectionAsync.java deleted file mode 100644 index 41e6265d3..000000000 --- a/vst/src/main/java/com/arangodb/vst/async/VstConnectionAsync.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * DISCLAIMER - * - * Copyright 2016 ArangoDB GmbH, Cologne, Germany - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Copyright holder is ArangoDB GmbH, Cologne, Germany - */ - -package com.arangodb.vst.async; - -import com.arangodb.async.internal.utils.CompletableFutureUtils; -import com.arangodb.config.HostDescription; -import com.arangodb.internal.config.ArangoConfig; -import com.arangodb.vst.internal.Chunk; -import com.arangodb.vst.internal.Message; -import com.arangodb.vst.internal.VstConnection; - -import java.util.Collection; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.FutureTask; -import java.util.concurrent.TimeUnit; - -/** - * @author Mark Vollmary - */ -public class VstConnectionAsync extends VstConnection> { - - VstConnectionAsync(final ArangoConfig config, final HostDescription host) { - super(config, host); - } - - @Override - public synchronized CompletableFuture write(final Message message, final Collection chunks) { - final CompletableFuture future = new CompletableFuture<>(); - final FutureTask task = new FutureTask<>(() -> { - try { - future.complete(messageStore.get(message.getId())); - } catch (final Exception e) { - future.completeExceptionally(e); - } - return null; - }); - messageStore.storeMessage(message.getId(), task); - super.writeIntern(message, chunks); - if (timeout == null || timeout == 0L) { - return future; - } else { - return CompletableFutureUtils.orTimeout(future, timeout, TimeUnit.MILLISECONDS); - } - } - - @Override - protected void doKeepAlive() { - sendKeepAlive().join(); - } - -} diff --git a/vst/src/main/java/com/arangodb/vst/async/VstConnectionFactoryAsync.java b/vst/src/main/java/com/arangodb/vst/async/VstConnectionFactoryAsync.java deleted file mode 100644 index 3c02a24fd..000000000 --- a/vst/src/main/java/com/arangodb/vst/async/VstConnectionFactoryAsync.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * DISCLAIMER - * - * Copyright 2018 ArangoDB GmbH, Cologne, Germany - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Copyright holder is ArangoDB GmbH, Cologne, Germany - */ - -package com.arangodb.vst.async; - -import com.arangodb.config.HostDescription; -import com.arangodb.internal.config.ArangoConfig; -import com.arangodb.internal.net.Connection; -import com.arangodb.internal.net.ConnectionFactory; - -/** - * @author Mark Vollmary - */ -public class VstConnectionFactoryAsync implements ConnectionFactory { - - @Override - public Connection create(final ArangoConfig config, final HostDescription host) { - return new VstConnectionAsync(config, host); - } -} diff --git a/vst/src/main/resources/META-INF/native-image/com.arangodb/vst-protocol/reflect-config-spi.json b/vst/src/main/resources/META-INF/native-image/com.arangodb/vst-protocol/reflect-config-spi.json index c582132f6..57c85201e 100644 --- a/vst/src/main/resources/META-INF/native-image/com.arangodb/vst-protocol/reflect-config-spi.json +++ b/vst/src/main/resources/META-INF/native-image/com.arangodb/vst-protocol/reflect-config-spi.json @@ -1,13 +1,4 @@ [ - { - "name": "com.arangodb.vst.VstAsyncProtocolProvider", - "methods": [ - { - "name": "", - "parameterTypes": [] - } - ] - }, { "name": "com.arangodb.vst.VstProtocolProvider", "methods": [ diff --git a/vst/src/main/resources/META-INF/native-image/com.arangodb/vst-protocol/resource-config-spi.json b/vst/src/main/resources/META-INF/native-image/com.arangodb/vst-protocol/resource-config-spi.json index b4ecc2447..9037d85e5 100644 --- a/vst/src/main/resources/META-INF/native-image/com.arangodb/vst-protocol/resource-config-spi.json +++ b/vst/src/main/resources/META-INF/native-image/com.arangodb/vst-protocol/resource-config-spi.json @@ -1,9 +1,6 @@ { "resources": { "includes": [ - { - "pattern": "META-INF/services/com.arangodb.internal.net.AsyncProtocolProvider" - }, { "pattern": "META-INF/services/com.arangodb.internal.net.ProtocolProvider" } diff --git a/vst/src/main/resources/META-INF/services/com.arangodb.internal.net.AsyncProtocolProvider b/vst/src/main/resources/META-INF/services/com.arangodb.internal.net.AsyncProtocolProvider deleted file mode 100644 index dc7f09560..000000000 --- a/vst/src/main/resources/META-INF/services/com.arangodb.internal.net.AsyncProtocolProvider +++ /dev/null @@ -1 +0,0 @@ -com.arangodb.vst.VstAsyncProtocolProvider