From d00ddb1afe787199e604424020475953defd46b3 Mon Sep 17 00:00:00 2001 From: Michele Rastelli Date: Mon, 23 Dec 2019 11:11:11 +0100 Subject: [PATCH] linter format --- .travis.yml | 4 +- docker/start_db_cluster.sh | 36 +- docker/start_db_single.sh | 4 +- docker/start_db_single_ssl.sh | 4 +- formatter.xml | 726 ++++---- pom.xml | 532 +++--- .../java/com/arangodb/ArangoCollection.java | 1356 +++++++------- src/main/java/com/arangodb/ArangoCursor.java | 69 +- src/main/java/com/arangodb/ArangoDB.java | 1619 ++++++++--------- .../java/com/arangodb/ArangoDBException.java | 99 +- .../java/com/arangodb/ArangoDatabase.java | 1466 +++++++-------- .../com/arangodb/ArangoEdgeCollection.java | 281 ++- src/main/java/com/arangodb/ArangoGraph.java | 332 ++-- .../java/com/arangodb/ArangoIterable.java | 142 +- .../java/com/arangodb/ArangoIterator.java | 1 - src/main/java/com/arangodb/ArangoRoute.java | 182 +- src/main/java/com/arangodb/ArangoSearch.java | 107 +- .../arangodb/ArangoSerializationAccessor.java | 30 +- .../com/arangodb/ArangoVertexCollection.java | 305 ++-- src/main/java/com/arangodb/ArangoView.java | 93 +- src/main/java/com/arangodb/Consumer.java | 17 +- src/main/java/com/arangodb/Function.java | 23 +- src/main/java/com/arangodb/Predicate.java | 19 +- src/main/java/com/arangodb/Protocol.java | 33 +- .../com/arangodb/async/ArangoDBAsync.java | 2 +- .../entity/AqlExecutionExplainEntity.java | 485 +++-- .../arangodb/entity/AqlFunctionEntity.java | 65 +- .../com/arangodb/entity/AqlParseEntity.java | 69 +- .../com/arangodb/entity/ArangoDBEngine.java | 26 +- .../com/arangodb/entity/ArangoDBVersion.java | 61 +- .../com/arangodb/entity/BaseDocument.java | 289 ++- .../com/arangodb/entity/BaseEdgeDocument.java | 201 +- .../com/arangodb/entity/CollectionEntity.java | 63 +- .../entity/CollectionPropertiesEntity.java | 251 ++- .../entity/CollectionRevisionEntity.java | 11 +- .../com/arangodb/entity/CollectionStatus.java | 33 +- .../com/arangodb/entity/CollectionType.java | 33 +- .../com/arangodb/entity/CursorEntity.java | 286 ++- .../arangodb/entity/DocumentCreateEntity.java | 55 +- .../arangodb/entity/DocumentDeleteEntity.java | 33 +- .../com/arangodb/entity/DocumentEntity.java | 37 +- .../com/arangodb/entity/DocumentField.java | 25 +- .../arangodb/entity/DocumentImportEntity.java | 155 +- .../arangodb/entity/DocumentUpdateEntity.java | 68 +- .../com/arangodb/entity/EdgeDefinition.java | 49 +- .../java/com/arangodb/entity/EdgeEntity.java | 7 +- .../com/arangodb/entity/EdgeUpdateEntity.java | 17 +- src/main/java/com/arangodb/entity/Entity.java | 1 - .../java/com/arangodb/entity/ErrorEntity.java | 65 +- .../java/com/arangodb/entity/GraphEntity.java | 74 +- .../java/com/arangodb/entity/IndexEntity.java | 149 +- .../java/com/arangodb/entity/IndexType.java | 3 +- .../java/com/arangodb/entity/KeyOptions.java | 77 +- .../java/com/arangodb/entity/License.java | 4 +- .../entity/LoadBalancingStrategy.java | 3 +- .../java/com/arangodb/entity/LogEntity.java | 77 +- .../java/com/arangodb/entity/LogLevel.java | 33 +- .../com/arangodb/entity/LogLevelEntity.java | 317 ++-- .../java/com/arangodb/entity/MetaAware.java | 5 +- .../arangodb/entity/MinReplicationFactor.java | 21 +- .../arangodb/entity/MultiDocumentEntity.java | 67 +- .../java/com/arangodb/entity/PathEntity.java | 37 +- .../java/com/arangodb/entity/Permissions.java | 19 +- .../entity/QueryCachePropertiesEntity.java | 71 +- .../java/com/arangodb/entity/QueryEntity.java | 94 +- .../arangodb/entity/QueryExecutionState.java | 21 +- .../entity/QueryTrackingPropertiesEntity.java | 174 +- .../arangodb/entity/ReplicationFactor.java | 35 +- .../java/com/arangodb/entity/ServerMode.java | 3 +- .../java/com/arangodb/entity/ServerRole.java | 3 +- .../java/com/arangodb/entity/ShardEntity.java | 14 +- .../com/arangodb/entity/ShardingStrategy.java | 28 +- .../entity/StreamTransactionEntity.java | 16 +- .../entity/StreamTransactionStatus.java | 2 +- .../arangodb/entity/TransactionEntity.java | 16 +- .../com/arangodb/entity/TraversalEntity.java | 37 +- .../java/com/arangodb/entity/UserEntity.java | 59 +- .../com/arangodb/entity/VertexEntity.java | 7 +- .../arangodb/entity/VertexUpdateEntity.java | 17 +- .../java/com/arangodb/entity/ViewEntity.java | 43 +- .../java/com/arangodb/entity/ViewType.java | 3 +- .../entity/arangosearch/AnalyzerEntity.java | 60 +- .../entity/arangosearch/AnalyzerFeature.java | 2 +- .../entity/arangosearch/AnalyzerType.java | 2 +- .../arangosearch/ArangoSearchProperties.java | 121 +- .../ArangoSearchPropertiesEntity.java | 4 +- .../entity/arangosearch/CollectionLink.java | 189 +- .../arangosearch/ConsolidationPolicy.java | 77 +- .../arangosearch/ConsolidationType.java | 2 +- .../entity/arangosearch/FieldLink.java | 190 +- .../entity/arangosearch/PrimarySort.java | 57 +- .../entity/arangosearch/StoreValuesType.java | 17 +- .../internal/ArangoCollectionImpl.java | 747 ++++---- .../com/arangodb/internal/ArangoContext.java | 31 +- .../internal/ArangoCursorExecute.java | 9 +- .../com/arangodb/internal/ArangoDBImpl.java | 391 ++-- .../arangodb/internal/ArangoDatabaseImpl.java | 810 ++++----- .../com/arangodb/internal/ArangoDefaults.java | 41 +- .../internal/ArangoEdgeCollectionImpl.java | 164 +- .../com/arangodb/internal/ArangoErrors.java | 13 +- .../arangodb/internal/ArangoExecuteable.java | 99 +- .../com/arangodb/internal/ArangoExecutor.java | 2 +- .../arangodb/internal/ArangoExecutorSync.java | 105 +- .../arangodb/internal/ArangoGraphImpl.java | 175 +- .../arangodb/internal/ArangoRequestParam.java | 19 +- .../internal/ArangoResponseField.java | 11 +- .../arangodb/internal/ArangoRouteImpl.java | 123 +- .../arangodb/internal/ArangoSearchImpl.java | 105 +- .../internal/ArangoVertexCollectionImpl.java | 176 +- .../com/arangodb/internal/ArangoViewImpl.java | 61 +- .../com/arangodb/internal/DocumentCache.java | 123 +- .../internal/InternalArangoCollection.java | 800 ++++---- .../arangodb/internal/InternalArangoDB.java | 267 ++- .../internal/InternalArangoDBBuilder.java | 600 +++--- .../InternalArangoEdgeCollection.java | 215 ++- .../internal/InternalArangoGraph.java | 201 +- .../internal/InternalArangoRoute.java | 77 +- .../internal/InternalArangoSearch.java | 43 +- .../InternalArangoVertexCollection.java | 227 ++- .../arangodb/internal/InternalArangoView.java | 55 +- .../cursor/AbstractArangoIterable.java | 123 +- .../internal/cursor/ArangoCursorImpl.java | 195 +- .../internal/cursor/ArangoCursorIterator.java | 85 +- .../internal/cursor/ArangoFilterIterable.java | 39 +- .../internal/cursor/ArangoFilterIterator.java | 77 +- .../cursor/ArangoMappingIterable.java | 35 +- .../cursor/ArangoMappingIterator.java | 47 +- .../internal/http/HttpCommunication.java | 121 +- .../internal/http/HttpConnection.java | 577 +++--- .../internal/http/HttpConnectionFactory.java | 29 +- .../internal/http/HttpDeleteWithBody.java | 23 +- .../arangodb/internal/http/HttpProtocol.java | 41 +- .../com/arangodb/internal/net/AccessType.java | 3 +- .../net/ArangoDBRedirectException.java | 19 +- .../internal/net/CommunicationProtocol.java | 7 +- .../com/arangodb/internal/net/Connection.java | 1 - .../internal/net/ConnectionFactory.java | 3 +- .../arangodb/internal/net/ConnectionPool.java | 5 +- .../internal/net/ConnectionPoolImpl.java | 2 +- .../internal/net/DirtyReadHostHandler.java | 89 +- .../internal/net/ExtendedHostResolver.java | 227 ++- .../java/com/arangodb/internal/net/Host.java | 13 +- .../internal/net/HostDescription.java | 93 +- .../com/arangodb/internal/net/HostHandle.java | 23 +- .../arangodb/internal/net/HostHandler.java | 15 +- .../com/arangodb/internal/net/HostImpl.java | 144 +- .../arangodb/internal/net/HostResolver.java | 5 +- .../com/arangodb/internal/net/HostSet.java | 174 +- .../internal/net/RandomHostHandler.java | 95 +- .../internal/net/RoundRobinHostHandler.java | 147 +- .../internal/net/SimpleHostResolver.java | 37 +- .../internal/util/ArangoDeserializerImpl.java | 49 +- .../util/ArangoSerializationFactory.java | 45 +- .../internal/util/ArangoSerializerImpl.java | 85 +- .../arangodb/internal/util/CURLLogger.java | 79 +- .../util/DefaultArangoSerialization.java | 51 +- .../arangodb/internal/util/DocumentUtil.java | 63 +- .../arangodb/internal/util/EncodeUtils.java | 13 +- .../com/arangodb/internal/util/HostUtils.java | 39 +- .../com/arangodb/internal/util/IOUtils.java | 79 +- .../arangodb/internal/util/RequestUtils.java | 39 +- .../arangodb/internal/util/ResponseUtils.java | 49 +- .../velocypack/VPackDeserializers.java | 393 ++-- .../velocypack/VPackDriverModule.java | 87 +- .../velocystream/VstCommunication.java | 249 ++- .../velocystream/VstCommunicationSync.java | 222 ++- .../VstConnectionFactorySync.java | 27 +- .../internal/velocystream/VstProtocol.java | 31 +- .../internal/AuthenticationRequest.java | 47 +- .../internal/velocystream/internal/Chunk.java | 99 +- .../velocystream/internal/ChunkStore.java | 65 +- .../velocystream/internal/Message.java | 63 +- .../velocystream/internal/MessageStore.java | 127 +- .../velocystream/internal/VstConnection.java | 459 +++-- .../internal/VstConnectionSync.java | 119 +- .../model/AqlFunctionCreateOptions.java | 88 +- .../model/AqlFunctionDeleteOptions.java | 40 +- .../arangodb/model/AqlFunctionGetOptions.java | 36 +- .../model/AqlQueryExplainOptions.java | 204 +-- .../com/arangodb/model/AqlQueryOptions.java | 820 ++++----- .../arangodb/model/AqlQueryParseOptions.java | 32 +- .../model/CollectionCountOptions.java | 32 +- .../model/CollectionCreateOptions.java | 614 +++---- .../model/CollectionPropertiesOptions.java | 63 +- .../model/CollectionRenameOptions.java | 32 +- .../model/CollectionTruncateOptions.java | 32 +- .../model/CollectionsReadOptions.java | 34 +- .../arangodb/model/DocumentCreateOptions.java | 190 +- .../arangodb/model/DocumentDeleteOptions.java | 132 +- .../arangodb/model/DocumentExistsOptions.java | 106 +- .../arangodb/model/DocumentImportOptions.java | 256 ++- .../arangodb/model/DocumentReadOptions.java | 167 +- .../model/DocumentReplaceOptions.java | 223 ++- .../arangodb/model/DocumentUpdateOptions.java | 312 ++-- .../com/arangodb/model/EdgeDeleteOptions.java | 57 +- .../arangodb/model/EdgeReplaceOptions.java | 57 +- .../com/arangodb/model/EdgeUpdateOptions.java | 88 +- .../arangodb/model/FulltextIndexOptions.java | 69 +- .../com/arangodb/model/GeoIndexOptions.java | 67 +- .../arangodb/model/GraphCreateOptions.java | 371 ++-- .../model/GraphDocumentReadOptions.java | 128 +- .../com/arangodb/model/HashIndexOptions.java | 115 +- .../java/com/arangodb/model/ImportType.java | 3 +- .../java/com/arangodb/model/IndexOptions.java | 2 +- .../java/com/arangodb/model/LogOptions.java | 246 ++- .../com/arangodb/model/OptionsBuilder.java | 181 +- .../model/PersistentIndexOptions.java | 92 +- .../arangodb/model/SkiplistIndexOptions.java | 123 +- .../model/StreamTransactionOptions.java | 160 +- .../model/TransactionCollectionOptions.java | 64 +- .../arangodb/model/TransactionOptions.java | 242 +-- .../com/arangodb/model/TraversalOptions.java | 679 ++++--- .../com/arangodb/model/UserAccessOptions.java | 23 +- .../com/arangodb/model/UserCreateOptions.java | 109 +- .../com/arangodb/model/UserUpdateOptions.java | 84 +- .../model/VertexCollectionCreateOptions.java | 32 +- .../arangodb/model/VertexCreateOptions.java | 32 +- .../arangodb/model/VertexDeleteOptions.java | 57 +- .../arangodb/model/VertexReplaceOptions.java | 57 +- .../arangodb/model/VertexUpdateOptions.java | 88 +- .../com/arangodb/model/ViewCreateOptions.java | 31 +- .../com/arangodb/model/ViewRenameOptions.java | 32 +- .../arangosearch/AnalyzerDeleteOptions.java | 18 +- .../ArangoSearchCreateOptions.java | 169 +- .../ArangoSearchOptionsBuilder.java | 13 +- .../ArangoSearchPropertiesOptions.java | 118 +- .../util/ArangoCursorInitializer.java | 11 +- .../com/arangodb/util/ArangoDeserializer.java | 25 +- .../arangodb/util/ArangoSerialization.java | 1 - .../com/arangodb/util/ArangoSerializer.java | 182 +- .../java/com/arangodb/util/MapBuilder.java | 23 +- .../com/arangodb/velocystream/Request.java | 157 +- .../arangodb/velocystream/RequestType.java | 53 +- .../com/arangodb/velocystream/Response.java | 79 +- .../java/com/arangodb/ArangoCursorTest.java | 336 ++-- src/test/java/com/arangodb/ArangoDBTest.java | 25 +- .../com/arangodb/ArangoDocumentUtilTest.java | 80 +- .../java/com/arangodb/ArangoRouteTest.java | 96 +- src/test/java/com/arangodb/ArangoSslTest.java | 101 +- .../ConcurrentStreamTransactionsTest.java | 2 +- src/test/java/com/arangodb/DocumentTest.java | 17 +- src/test/java/com/arangodb/UserAuthTest.java | 33 +- .../com/arangodb/entity/BaseDocumentTest.java | 102 +- .../com/arangodb/example/ExampleBase.java | 5 +- .../com/arangodb/example/FirstProject.java | 242 +-- ...AqlQueryWithSpecialReturnTypesExample.java | 19 +- .../example/document/GetDocumentExample.java | 104 +- .../document/InsertDocumentExample.java | 60 +- .../arangodb/example/document/TestEntity.java | 29 +- .../graph/AQLActorsAndMoviesExample.java | 13 +- .../arangodb/example/graph/BaseGraphTest.java | 11 +- .../com/arangodb/example/graph/Circle.java | 71 +- .../arangodb/example/graph/CircleEdge.java | 139 +- .../graph/GraphTraversalsInAQLExample.java | 173 +- .../graph/ShortestPathInAQLExample.java | 139 +- .../com/arangodb/example/ssl/SslExample.java | 4 +- .../example/velocypack/VPackExample.java | 160 +- .../arangodb/internal/DocumentCacheTest.java | 68 +- .../velocystream/CommunicationTest.java | 23 +- .../util/ArangoSerializationTest.java | 126 +- .../com/arangodb/util/MapBuilderTest.java | 23 +- src/test/resources/logback-test.xml | 20 +- tests/travis/setup_arangodb.sh | 20 +- 263 files changed, 16105 insertions(+), 16567 deletions(-) diff --git a/.travis.yml b/.travis.yml index b029a227f..b1ec09396 100644 --- a/.travis.yml +++ b/.travis.yml @@ -4,9 +4,9 @@ before_script: - chmod 777 ./tests/travis/setup_arangodb.sh - ./tests/travis/setup_arangodb.sh -after_script: +after_script: - killall -9 arangod_x86_64 - + install: mvn install -DskipTests=true -Dgpg.skip=true -Dmaven.javadoc.skip=true -B -V jdk: diff --git a/docker/start_db_cluster.sh b/docker/start_db_cluster.sh index 988c096ab..de9af0b6c 100755 --- a/docker/start_db_cluster.sh +++ b/docker/start_db_cluster.sh @@ -13,15 +13,14 @@ LOCATION=$(pwd)/$(dirname "$0") docker network create arangodb --subnet 172.28.0.0/16 -echo "Averysecretword" > "$LOCATION"/jwtSecret -docker run --rm -v "$LOCATION"/jwtSecret:/jwtSecret "$1" arangodb auth header --auth.jwt-secret /jwtSecret > "$LOCATION"/jwtHeader +echo "Averysecretword" >"$LOCATION"/jwtSecret +docker run --rm -v "$LOCATION"/jwtSecret:/jwtSecret "$1" arangodb auth header --auth.jwt-secret /jwtSecret >"$LOCATION"/jwtHeader AUTHORIZATION_HEADER=$(cat "$LOCATION"/jwtHeader) debug_container() { running=$(docker inspect -f '{{.State.Running}}' "$1") - if [ "$running" = false ] - then + if [ "$running" = false ]; then echo "$1 is not running!" echo "---" docker logs "$1" @@ -32,27 +31,26 @@ debug_container() { debug() { for c in agent1 \ - agent2 \ - agent3 \ - dbserver1 \ - dbserver2 \ - dbserver3 \ - coordinator1 \ - coordinator2 ; do - debug_container $c + agent2 \ + agent3 \ + dbserver1 \ + dbserver2 \ + dbserver3 \ + coordinator1 \ + coordinator2; do + debug_container $c done } wait_server() { - # shellcheck disable=SC2091 - until $(curl --output /dev/null --silent --head --fail -i -H "$AUTHORIZATION_HEADER" "http://$1/_api/version"); do - printf '.' - debug - sleep 1 - done + # shellcheck disable=SC2091 + until $(curl --output /dev/null --silent --head --fail -i -H "$AUTHORIZATION_HEADER" "http://$1/_api/version"); do + printf '.' + debug + sleep 1 + done } - echo "Starting containers..." docker run -d -v "$LOCATION"/jwtSecret:/jwtSecret -e ARANGO_LICENSE_KEY="$ARANGO_LICENSE_KEY" --network arangodb --ip 172.28.1.1 --name agent1 "$1" arangodb --cluster.start-dbserver false --cluster.start-coordinator false --auth.jwt-secret /jwtSecret diff --git a/docker/start_db_single.sh b/docker/start_db_single.sh index cc4580067..cabdb8083 100755 --- a/docker/start_db_single.sh +++ b/docker/start_db_single.sh @@ -15,7 +15,7 @@ echo "waiting for arangodb ..." # shellcheck disable=SC2091 until $(curl --output /dev/null --silent --head --fail -i -u root:test 'http://localhost:8529/_api/version'); do - printf '.' - sleep 1 + printf '.' + sleep 1 done echo "READY!" diff --git a/docker/start_db_single_ssl.sh b/docker/start_db_single_ssl.sh index d7c030ce5..2a175bcef 100755 --- a/docker/start_db_single_ssl.sh +++ b/docker/start_db_single_ssl.sh @@ -15,7 +15,7 @@ echo "waiting for arangodb ..." # shellcheck disable=SC2091 until $(curl --output /dev/null --silent --head --fail -i --insecure -u root:test 'https://127.0.0.1:8529/_api/version'); do - printf '.' - sleep 1 + printf '.' + sleep 1 done echo "READY!" diff --git a/formatter.xml b/formatter.xml index a8fe8b3a4..0485cd4ba 100644 --- a/formatter.xml +++ b/formatter.xml @@ -1,313 +1,419 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/pom.xml b/pom.xml index 17bd8332a..1e61078d6 100644 --- a/pom.xml +++ b/pom.xml @@ -1,284 +1,284 @@ - 4.0.0 + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + 4.0.0 - com.arangodb - arangodb-java-driver - 6.4.1 - 2016 - jar + com.arangodb + arangodb-java-driver + 6.4.1 + 2016 + jar - arangodb-java-driver - ArangoDB Java Driver - http://maven.apache.org + arangodb-java-driver + ArangoDB Java Driver + http://maven.apache.org - - - Apache License 2.0 - http://www.apache.org/licenses/LICENSE-2.0 - repo - - + + + Apache License 2.0 + http://www.apache.org/licenses/LICENSE-2.0 + repo + + - - UTF-8 - 1.7.28 - 2.1.0 + + UTF-8 + 1.7.28 + 2.1.0 - - 4.5.9 + + 4.5.9 - - 1.2.3 - 1.3 - 4.12 + + 1.2.3 + 1.3 + 4.12 - - - + + + - - - Michele Rastelli - https://github.com/rashtao - - - mpv1989 - Mark Vollmary - https://github.com/mpv1989 - - + + + Michele Rastelli + https://github.com/rashtao + + + mpv1989 + Mark Vollmary + https://github.com/mpv1989 + + - - - ossrh - https://oss.sonatype.org/content/repositories/snapshots - - - ossrh - https://oss.sonatype.org/service/local/staging/deploy/maven2/ - - + + + ossrh + https://oss.sonatype.org/content/repositories/snapshots + + + ossrh + https://oss.sonatype.org/service/local/staging/deploy/maven2/ + + - - - doclint-java8-disable - - [1.8,) - - - none - - - + + + doclint-java8-disable + + [1.8,) + + + none + + + - - - - org.sonatype.plugins - nexus-staging-maven-plugin - 1.6.8 - true - - ossrh - https://oss.sonatype.org/ - 84aff6e87e214c - false - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.8.1 - - 1.8 - 1.8 - - - - org.apache.maven.plugins - maven-resources-plugin - 3.1.0 - - UTF-8 - - - - org.apache.maven.plugins - maven-source-plugin - 3.1.0 - - - - jar - - - - - - org.apache.maven.plugins - maven-javadoc-plugin - 3.1.1 - - - attach-javadocs - - jar - - - ${javadoc.opts} - com.arangodb.internal - - - - - - org.apache.maven.plugins - maven-surefire-plugin - 2.22.2 - - - **/*Test.java - **/*Example.java - - - - - org.apache.maven.plugins - maven-deploy-plugin - 2.8.2 - - false - 10 - - - - org.apache.maven.plugins - maven-gpg-plugin - 1.6 - - - sign-artifacts - verify - - sign - - - - - - + + + + org.sonatype.plugins + nexus-staging-maven-plugin + 1.6.8 + true + + ossrh + https://oss.sonatype.org/ + 84aff6e87e214c + false + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.8.1 + + 1.8 + 1.8 + + + + org.apache.maven.plugins + maven-resources-plugin + 3.1.0 + + UTF-8 + + + + org.apache.maven.plugins + maven-source-plugin + 3.1.0 + + + + jar + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + 3.1.1 + + + attach-javadocs + + jar + + + ${javadoc.opts} + com.arangodb.internal + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.22.2 + + + **/*Test.java + **/*Example.java + + + + + org.apache.maven.plugins + maven-deploy-plugin + 2.8.2 + + false + 10 + + + + org.apache.maven.plugins + maven-gpg-plugin + 1.6 + + + sign-artifacts + verify + + sign + + + + + + - - - org.apache.httpcomponents - httpclient - provided - - - org.apache.httpcomponents - httpcore - provided - - - commons-logging - commons-logging - - - commons-codec - commons-codec - - - com.arangodb - velocypack - - - org.slf4j - slf4j-api - - - ch.qos.logback - logback-classic - test - - - junit - junit - test - - - org.hamcrest - hamcrest-all - test - - - com.arangodb - jackson-dataformat-velocypack - 0.1.4 - test - - + + + org.apache.httpcomponents + httpclient + provided + + + org.apache.httpcomponents + httpcore + provided + + + commons-logging + commons-logging + + + commons-codec + commons-codec + + + com.arangodb + velocypack + + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + test + + + junit + junit + test + + + org.hamcrest + hamcrest-all + test + + + com.arangodb + jackson-dataformat-velocypack + 0.1.4 + test + + - - - - org.apache.httpcomponents - httpclient - ${httpclient.version} - - - org.apache.httpcomponents - httpcore - 4.4.11 - - - commons-codec - commons-codec - 1.13 - - - commons-logging - commons-logging - 1.2 - - - com.arangodb - velocypack - ${arangodb.velocypack.version} - - - org.slf4j - slf4j-api - ${slf4j-api.version} - - - ch.qos.logback - logback-classic - ${logback-classic.version} - - - junit - junit - ${junit.version} - - - org.hamcrest - hamcrest-all - ${hamcrest-all.version} - - - + + + + org.apache.httpcomponents + httpclient + ${httpclient.version} + + + org.apache.httpcomponents + httpcore + 4.4.11 + + + commons-codec + commons-codec + 1.13 + + + commons-logging + commons-logging + 1.2 + + + com.arangodb + velocypack + ${arangodb.velocypack.version} + + + org.slf4j + slf4j-api + ${slf4j-api.version} + + + ch.qos.logback + logback-classic + ${logback-classic.version} + + + junit + junit + ${junit.version} + + + org.hamcrest + hamcrest-all + ${hamcrest-all.version} + + + - - https://github.com/arangodb/arangodb-java-driver - scm:git:git://github.com/arangodb/arangodb-java-driver.git - scm:git:git://github.com/arangodb/arangodb-java-driver.git - + + https://github.com/arangodb/arangodb-java-driver + scm:git:git://github.com/arangodb/arangodb-java-driver.git + scm:git:git://github.com/arangodb/arangodb-java-driver.git + - - ArangoDB GmbH - https://www.arangodb.com - + + ArangoDB GmbH + https://www.arangodb.com + diff --git a/src/main/java/com/arangodb/ArangoCollection.java b/src/main/java/com/arangodb/ArangoCollection.java index 9a5ca3b0e..25a83511b 100644 --- a/src/main/java/com/arangodb/ArangoCollection.java +++ b/src/main/java/com/arangodb/ArangoCollection.java @@ -37,683 +37,683 @@ @SuppressWarnings("UnusedReturnValue") public interface ArangoCollection extends ArangoSerializationAccessor { - /** - * The the handler of the database the collection is within - * - * @return database handler - */ - ArangoDatabase 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, VPackSlice or String for JSON) - * @return information about the document - * @throws ArangoDBException - * @see API - * Documentation - */ - DocumentCreateEntity insertDocument(T value) throws ArangoDBException; - - /** - * 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, VPackSlice or String for JSON) - * @param options Additional options, can be null - * @return information about the document - * @throws ArangoDBException - * @see API - * Documentation - */ - DocumentCreateEntity insertDocument(T value, DocumentCreateOptions options) throws ArangoDBException; - - /** - * 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, VPackSlice or String for JSON) - * @return information about the documents - * @throws ArangoDBException - * @see API - * Documentation - */ - MultiDocumentEntity> insertDocuments(Collection values) throws ArangoDBException; - - /** - * 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, VPackSlice or String for JSON) - * @param options Additional options, can be null - * @return information about the documents - * @throws ArangoDBException - * @see API - * Documentation - */ - MultiDocumentEntity> insertDocuments( - Collection values, DocumentCreateOptions options) throws ArangoDBException; - - /** - * Bulk imports the given values into the collection. - * - * @param values a list of Objects that will be stored as documents - * @return information about the import - * @throws ArangoDBException - */ - DocumentImportEntity importDocuments(Collection values) throws ArangoDBException; - - /** - * Bulk imports the given values into the collection. - * - * @param values a list of Objects that will be stored as documents - * @param options Additional options, can be null - * @return information about the import - * @throws ArangoDBException - */ - DocumentImportEntity importDocuments(Collection values, DocumentImportOptions options) throws ArangoDBException; - - /** - * Bulk imports the given values into the collection. - * - * @param values JSON-encoded array of objects that will be stored as documents - * @return information about the import - * @throws ArangoDBException - */ - DocumentImportEntity importDocuments(String values) throws ArangoDBException; - - /** - * Bulk imports the given values into the collection. - * - * @param values JSON-encoded array of objects that will be stored as documents - * @param options Additional options, can be null - * @return information about the import - * @throws ArangoDBException - */ - DocumentImportEntity importDocuments(String values, DocumentImportOptions options) throws ArangoDBException; - - /** - * Retrieves the document with the given {@code key} from the collection. - * - * @param key The key of the document - * @param type The type of the document (POJO class, VPackSlice or String for JSON) - * @return the document identified by the key - * @throws ArangoDBException - * @see API - * Documentation - */ - T getDocument(String key, Class type) throws ArangoDBException; - - /** - * Retrieves the document with the given {@code key} from the collection. - * - * @param key The key of the document - * @param type The type of the document (POJO class, VPackSlice or String for JSON) - * @param options Additional options, can be null - * @return the document identified by the key - * @throws ArangoDBException - * @see API - * Documentation - */ - T getDocument(String key, Class type, DocumentReadOptions options) throws ArangoDBException; - - /** - * Retrieves multiple documents with the given {@code _key} from the collection. - * - * @param keys The keys of the documents - * @param type The type of the documents (POJO class, VPackSlice or String for JSON) - * @return the documents and possible errors - * @throws ArangoDBException - */ - MultiDocumentEntity getDocuments(Collection keys, Class type) throws ArangoDBException; - - /** - * Retrieves multiple documents with the given {@code _key} from the collection. - * - * @param keys The keys of the documents - * @param type The type of the documents (POJO class, VPackSlice or String for JSON) - * @param options Additional options, can be null - * @return the documents and possible errors - * @throws ArangoDBException - */ - MultiDocumentEntity getDocuments(Collection keys, Class type, DocumentReadOptions options) - throws ArangoDBException; - - /** - * Replaces the document with {@code 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, VPackSlice or String for JSON) - * @return information about the document - * @throws ArangoDBException - * @see API - * Documentation - */ - DocumentUpdateEntity replaceDocument(String key, T value) throws ArangoDBException; - - /** - * Replaces the document with {@code 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, VPackSlice or String for JSON) - * @param options Additional options, can be null - * @return information about the document - * @throws ArangoDBException - * @see API - * Documentation - */ - DocumentUpdateEntity replaceDocument(String key, T value, DocumentReplaceOptions options) - throws ArangoDBException; - - /** - * 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, VPackSlice or String for JSON) - * @return information about the documents - * @throws ArangoDBException - * @see API - * Documentation - */ - MultiDocumentEntity> replaceDocuments(Collection values) throws ArangoDBException; - - /** - * 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, VPackSlice or String for JSON) - * @param options Additional options, can be null - * @return information about the documents - * @throws ArangoDBException - * @see API - * Documentation - */ - MultiDocumentEntity> replaceDocuments( - Collection values, DocumentReplaceOptions options) throws ArangoDBException; - - /** - * 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, VPackSlice or String for JSON) - * @return information about the document - * @throws ArangoDBException - * @see API - * Documentation - */ - DocumentUpdateEntity updateDocument(String key, T value) throws ArangoDBException; - - /** - * 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, VPackSlice or String for JSON) - * @param options Additional options, can be null - * @return information about the document - * @throws ArangoDBException - * @see API - * Documentation - */ - DocumentUpdateEntity updateDocument(String key, T value, DocumentUpdateOptions options) - throws ArangoDBException; - - /** - * 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, VPackSlice or String for JSON) - * @return information about the documents - * @throws ArangoDBException - * @see API - * Documentation - */ - MultiDocumentEntity> updateDocuments(Collection values) throws ArangoDBException; - - /** - * 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, VPackSlice or String for JSON) - * @param options Additional options, can be null - * @return information about the documents - * @throws ArangoDBException - * @see API - * Documentation - */ - MultiDocumentEntity> updateDocuments( - Collection values, DocumentUpdateOptions options) throws ArangoDBException; - - /** - * Deletes the document with the given {@code key} from the collection. - * - * @param key The key of the document - * @return information about the document - * @throws ArangoDBException - * @see API - * Documentation - */ - DocumentDeleteEntity deleteDocument(String key) throws ArangoDBException; - - /** - * Deletes the document with the given {@code key} from the collection. - * - * @param key The key of the document - * @param type The type of the document (POJO class, VPackSlice or String for JSON). Only necessary if - * options.returnOld is set to true, otherwise can be null. - * @param options Additional options, can be null - * @return information about the document - * @throws ArangoDBException - * @see API - * Documentation - */ - DocumentDeleteEntity deleteDocument(String key, Class type, DocumentDeleteOptions options) - throws ArangoDBException; - - /** - * Deletes multiple documents from the collection. - * - * @param values The keys of the documents or the documents themselves - * @return information about the documents - * @throws ArangoDBException - * @see API - * Documentation - */ - MultiDocumentEntity> deleteDocuments(Collection values) throws ArangoDBException; - - /** - * Deletes multiple documents from the collection. - * - * @param values The keys of the documents or the documents themselves - * @param type The type of the documents (POJO class, VPackSlice or String for JSON). Only necessary if - * options.returnOld is set to true, otherwise can be null. - * @param options Additional options, can be null - * @return information about the documents - * @throws ArangoDBException - * @see API - * Documentation - */ - MultiDocumentEntity> deleteDocuments( - Collection values, Class type, DocumentDeleteOptions options) throws ArangoDBException; - - /** - * 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 - */ - Boolean documentExists(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 - * @throws ArangoDBException only thrown when {@link DocumentExistsOptions#isCatchException()} == false - * @see API - * Documentation - */ - Boolean documentExists(String key, DocumentExistsOptions options) throws ArangoDBException; - - /** - * Fetches information about the index with the given {@code id} and returns it. - * - * @param id The index-handle - * @return information about the index - * @throws ArangoDBException - * @see API Documentation - */ - IndexEntity getIndex(String id) throws ArangoDBException; - - /** - * Deletes the index with the given {@code id} from the collection. - * - * @param id The index-handle - * @return the id of the index - * @throws ArangoDBException - * @see API Documentation - */ - String deleteIndex(String id) throws ArangoDBException; - - /** - * Creates a hash 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 - * @throws ArangoDBException - * @see API Documentation - */ - IndexEntity ensureHashIndex(Iterable fields, HashIndexOptions options) throws ArangoDBException; - - /** - * Creates a skip-list 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 - * @throws ArangoDBException - * @see API - * Documentation - */ - IndexEntity ensureSkiplistIndex(Iterable fields, SkiplistIndexOptions options) throws ArangoDBException; - - /** - * 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 - * @throws ArangoDBException - * @see API - * Documentation - */ - IndexEntity ensurePersistentIndex(Iterable fields, PersistentIndexOptions options) throws ArangoDBException; - - /** - * 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 - * @throws ArangoDBException - * @see API - * Documentation - */ - IndexEntity ensureGeoIndex(Iterable fields, GeoIndexOptions options) throws ArangoDBException; - - /** - * 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 - * @throws ArangoDBException - * @see API - * Documentation - */ - IndexEntity ensureFulltextIndex(Iterable fields, FulltextIndexOptions options) throws ArangoDBException; - - /** - * 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 - * @throws ArangoDBException - * @see API - * Documentation - */ - IndexEntity ensureTtlIndex(Iterable fields, TtlIndexOptions options) throws ArangoDBException; - - /** - * Fetches a list of all indexes on this collection. - * - * @return information about the indexes - * @throws ArangoDBException - * @see API - * Documentation - */ - Collection getIndexes() throws ArangoDBException; - - /** - * Checks whether the collection exists - * - * @return true if the collection exists, otherwise false - */ - boolean exists() throws ArangoDBException; - - /** - * Removes all documents from the collection, but leaves the indexes intact - * - * @return information about the collection - * @throws ArangoDBException - * @see API - * Documentation - */ - CollectionEntity truncate() throws ArangoDBException; - - /** - * Removes all documents from the collection, but leaves the indexes intact - * - * @param options - * @return information about the collection - * @throws ArangoDBException - * @see API - * Documentation - * @since ArangoDB 3.5.0 - */ - CollectionEntity truncate(CollectionTruncateOptions options) throws ArangoDBException; - - /** - * Counts the documents in a collection - * - * @return information about the collection, including the number of documents - * @throws ArangoDBException - * @see API - * Documentation - */ - CollectionPropertiesEntity count() throws ArangoDBException; - - /** - * Counts the documents in a collection - * - * @param options - * @return information about the collection, including the number of documents - * @throws ArangoDBException - * @see API - * Documentation - * @since ArangoDB 3.5.0 - */ - CollectionPropertiesEntity count(CollectionCountOptions options) throws ArangoDBException; - - /** - * Creates a collection for this collection's name, then returns collection information from the server. - * - * @return information about the collection - * @throws ArangoDBException - * @see API - * Documentation - */ - CollectionEntity create() throws ArangoDBException; - - /** - * Creates a collection with the given {@code options} for this collection's name, then returns collection - * information from the server. - * - * @param options Additional options, can be null - * @return information about the collection - * @throws ArangoDBException - * @see API - * Documentation - */ - CollectionEntity create(CollectionCreateOptions options) throws ArangoDBException; - - /** - * Deletes the collection from the database. - * - * @throws ArangoDBException - * @see API - * Documentation - */ - void drop() throws ArangoDBException; - - /** - * Deletes the collection from the database. - * - * @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. - * @throws ArangoDBException - * @see API - * Documentation - * @since ArangoDB 3.1.0 - */ - void drop(boolean isSystem) throws ArangoDBException; - - /** - * Tells the server to load the collection into memory. - * - * @return information about the collection - * @throws ArangoDBException - * @see API - * Documentation - */ - CollectionEntity load() throws ArangoDBException; - - /** - * Tells the server to remove the collection from memory. This call does not delete any documents. You can use the - * collection afterwards; in which case it will be loaded into memory, again. - * - * @return information about the collection - * @throws ArangoDBException - * @see API - * Documentation - */ - CollectionEntity unload() throws ArangoDBException; - - /** - * Returns information about the collection - * - * @return information about the collection - * @throws ArangoDBException - * @see API - * Documentation - */ - CollectionEntity getInfo() throws ArangoDBException; - - /** - * Reads the properties of the specified collection - * - * @return properties of the collection - * @throws ArangoDBException - * @see API - * Documentation - */ - CollectionPropertiesEntity getProperties() throws ArangoDBException; - - /** - * Changes the properties of the collection - * - * @param options Additional options, can be null - * @return properties of the collection - * @throws ArangoDBException - * @see API - * Documentation - */ - CollectionPropertiesEntity changeProperties(CollectionPropertiesOptions options) throws ArangoDBException; - - /** - * Renames the collection - * - * @param newName The new name - * @return information about the collection - * @throws ArangoDBException - * @see API - * Documentation - */ - CollectionEntity rename(String newName) throws ArangoDBException; - - /** - * 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 - * @throws ArangoDBException - * @see - * API Documentation - * @since ArangoDB 3.5.0 - */ - ShardEntity getResponsibleShard(final Object value); - - /** - * Retrieve the collections revision - * - * @return information about the collection, including the collections revision - * @throws ArangoDBException - * @see API - * Documentation - */ - CollectionRevisionEntity getRevision() throws ArangoDBException; - - /** - * 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 - * @throws ArangoDBException - * @see API - * Documentation - */ - void grantAccess(String user, Permissions permissions) throws ArangoDBException; - - /** - * 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 - * @throws ArangoDBException - * @see API - * Documentation - */ - void revokeAccess(String user) throws ArangoDBException; - - /** - * Clear the collection access level, revert back to the default access level. - * - * @param user The name of the user - * @throws ArangoDBException - * @see API - * Documentation - * @since ArangoDB 3.2.0 - */ - void resetAccess(String user) throws ArangoDBException; - - /** - * Get the collection access level - * - * @param user The name of the user - * @return permissions of the user - * @throws ArangoDBException - * @see - * API Documentation - * @since ArangoDB 3.2.0 - */ - Permissions getPermissions(String user) throws ArangoDBException; + /** + * The the handler of the database the collection is within + * + * @return database handler + */ + ArangoDatabase 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, VPackSlice or String for JSON) + * @return information about the document + * @throws ArangoDBException + * @see API + * Documentation + */ + DocumentCreateEntity insertDocument(T value) throws ArangoDBException; + + /** + * 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, VPackSlice or String for JSON) + * @param options Additional options, can be null + * @return information about the document + * @throws ArangoDBException + * @see API + * Documentation + */ + DocumentCreateEntity insertDocument(T value, DocumentCreateOptions options) throws ArangoDBException; + + /** + * 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, VPackSlice or String for JSON) + * @return information about the documents + * @throws ArangoDBException + * @see API + * Documentation + */ + MultiDocumentEntity> insertDocuments(Collection values) throws ArangoDBException; + + /** + * 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, VPackSlice or String for JSON) + * @param options Additional options, can be null + * @return information about the documents + * @throws ArangoDBException + * @see API + * Documentation + */ + MultiDocumentEntity> insertDocuments( + Collection values, DocumentCreateOptions options) throws ArangoDBException; + + /** + * Bulk imports the given values into the collection. + * + * @param values a list of Objects that will be stored as documents + * @return information about the import + * @throws ArangoDBException + */ + DocumentImportEntity importDocuments(Collection values) throws ArangoDBException; + + /** + * Bulk imports the given values into the collection. + * + * @param values a list of Objects that will be stored as documents + * @param options Additional options, can be null + * @return information about the import + * @throws ArangoDBException + */ + DocumentImportEntity importDocuments(Collection values, DocumentImportOptions options) throws ArangoDBException; + + /** + * Bulk imports the given values into the collection. + * + * @param values JSON-encoded array of objects that will be stored as documents + * @return information about the import + * @throws ArangoDBException + */ + DocumentImportEntity importDocuments(String values) throws ArangoDBException; + + /** + * Bulk imports the given values into the collection. + * + * @param values JSON-encoded array of objects that will be stored as documents + * @param options Additional options, can be null + * @return information about the import + * @throws ArangoDBException + */ + DocumentImportEntity importDocuments(String values, DocumentImportOptions options) throws ArangoDBException; + + /** + * Retrieves the document with the given {@code key} from the collection. + * + * @param key The key of the document + * @param type The type of the document (POJO class, VPackSlice or String for JSON) + * @return the document identified by the key + * @throws ArangoDBException + * @see API + * Documentation + */ + T getDocument(String key, Class type) throws ArangoDBException; + + /** + * Retrieves the document with the given {@code key} from the collection. + * + * @param key The key of the document + * @param type The type of the document (POJO class, VPackSlice or String for JSON) + * @param options Additional options, can be null + * @return the document identified by the key + * @throws ArangoDBException + * @see API + * Documentation + */ + T getDocument(String key, Class type, DocumentReadOptions options) throws ArangoDBException; + + /** + * Retrieves multiple documents with the given {@code _key} from the collection. + * + * @param keys The keys of the documents + * @param type The type of the documents (POJO class, VPackSlice or String for JSON) + * @return the documents and possible errors + * @throws ArangoDBException + */ + MultiDocumentEntity getDocuments(Collection keys, Class type) throws ArangoDBException; + + /** + * Retrieves multiple documents with the given {@code _key} from the collection. + * + * @param keys The keys of the documents + * @param type The type of the documents (POJO class, VPackSlice or String for JSON) + * @param options Additional options, can be null + * @return the documents and possible errors + * @throws ArangoDBException + */ + MultiDocumentEntity getDocuments(Collection keys, Class type, DocumentReadOptions options) + throws ArangoDBException; + + /** + * Replaces the document with {@code 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, VPackSlice or String for JSON) + * @return information about the document + * @throws ArangoDBException + * @see API + * Documentation + */ + DocumentUpdateEntity replaceDocument(String key, T value) throws ArangoDBException; + + /** + * Replaces the document with {@code 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, VPackSlice or String for JSON) + * @param options Additional options, can be null + * @return information about the document + * @throws ArangoDBException + * @see API + * Documentation + */ + DocumentUpdateEntity replaceDocument(String key, T value, DocumentReplaceOptions options) + throws ArangoDBException; + + /** + * 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, VPackSlice or String for JSON) + * @return information about the documents + * @throws ArangoDBException + * @see API + * Documentation + */ + MultiDocumentEntity> replaceDocuments(Collection values) throws ArangoDBException; + + /** + * 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, VPackSlice or String for JSON) + * @param options Additional options, can be null + * @return information about the documents + * @throws ArangoDBException + * @see API + * Documentation + */ + MultiDocumentEntity> replaceDocuments( + Collection values, DocumentReplaceOptions options) throws ArangoDBException; + + /** + * 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, VPackSlice or String for JSON) + * @return information about the document + * @throws ArangoDBException + * @see API + * Documentation + */ + DocumentUpdateEntity updateDocument(String key, T value) throws ArangoDBException; + + /** + * 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, VPackSlice or String for JSON) + * @param options Additional options, can be null + * @return information about the document + * @throws ArangoDBException + * @see API + * Documentation + */ + DocumentUpdateEntity updateDocument(String key, T value, DocumentUpdateOptions options) + throws ArangoDBException; + + /** + * 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, VPackSlice or String for JSON) + * @return information about the documents + * @throws ArangoDBException + * @see API + * Documentation + */ + MultiDocumentEntity> updateDocuments(Collection values) throws ArangoDBException; + + /** + * 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, VPackSlice or String for JSON) + * @param options Additional options, can be null + * @return information about the documents + * @throws ArangoDBException + * @see API + * Documentation + */ + MultiDocumentEntity> updateDocuments( + Collection values, DocumentUpdateOptions options) throws ArangoDBException; + + /** + * Deletes the document with the given {@code key} from the collection. + * + * @param key The key of the document + * @return information about the document + * @throws ArangoDBException + * @see API + * Documentation + */ + DocumentDeleteEntity deleteDocument(String key) throws ArangoDBException; + + /** + * Deletes the document with the given {@code key} from the collection. + * + * @param key The key of the document + * @param type The type of the document (POJO class, VPackSlice or String for JSON). Only necessary if + * options.returnOld is set to true, otherwise can be null. + * @param options Additional options, can be null + * @return information about the document + * @throws ArangoDBException + * @see API + * Documentation + */ + DocumentDeleteEntity deleteDocument(String key, Class type, DocumentDeleteOptions options) + throws ArangoDBException; + + /** + * Deletes multiple documents from the collection. + * + * @param values The keys of the documents or the documents themselves + * @return information about the documents + * @throws ArangoDBException + * @see API + * Documentation + */ + MultiDocumentEntity> deleteDocuments(Collection values) throws ArangoDBException; + + /** + * Deletes multiple documents from the collection. + * + * @param values The keys of the documents or the documents themselves + * @param type The type of the documents (POJO class, VPackSlice or String for JSON). Only necessary if + * options.returnOld is set to true, otherwise can be null. + * @param options Additional options, can be null + * @return information about the documents + * @throws ArangoDBException + * @see API + * Documentation + */ + MultiDocumentEntity> deleteDocuments( + Collection values, Class type, DocumentDeleteOptions options) throws ArangoDBException; + + /** + * 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 + */ + Boolean documentExists(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 + * @throws ArangoDBException only thrown when {@link DocumentExistsOptions#isCatchException()} == false + * @see API + * Documentation + */ + Boolean documentExists(String key, DocumentExistsOptions options) throws ArangoDBException; + + /** + * Fetches information about the index with the given {@code id} and returns it. + * + * @param id The index-handle + * @return information about the index + * @throws ArangoDBException + * @see API Documentation + */ + IndexEntity getIndex(String id) throws ArangoDBException; + + /** + * Deletes the index with the given {@code id} from the collection. + * + * @param id The index-handle + * @return the id of the index + * @throws ArangoDBException + * @see API Documentation + */ + String deleteIndex(String id) throws ArangoDBException; + + /** + * Creates a hash 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 + * @throws ArangoDBException + * @see API Documentation + */ + IndexEntity ensureHashIndex(Iterable fields, HashIndexOptions options) throws ArangoDBException; + + /** + * Creates a skip-list 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 + * @throws ArangoDBException + * @see API + * Documentation + */ + IndexEntity ensureSkiplistIndex(Iterable fields, SkiplistIndexOptions options) throws ArangoDBException; + + /** + * 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 + * @throws ArangoDBException + * @see API + * Documentation + */ + IndexEntity ensurePersistentIndex(Iterable fields, PersistentIndexOptions options) throws ArangoDBException; + + /** + * 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 + * @throws ArangoDBException + * @see API + * Documentation + */ + IndexEntity ensureGeoIndex(Iterable fields, GeoIndexOptions options) throws ArangoDBException; + + /** + * 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 + * @throws ArangoDBException + * @see API + * Documentation + */ + IndexEntity ensureFulltextIndex(Iterable fields, FulltextIndexOptions options) throws ArangoDBException; + + /** + * 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 + * @throws ArangoDBException + * @see API + * Documentation + */ + IndexEntity ensureTtlIndex(Iterable fields, TtlIndexOptions options) throws ArangoDBException; + + /** + * Fetches a list of all indexes on this collection. + * + * @return information about the indexes + * @throws ArangoDBException + * @see API + * Documentation + */ + Collection getIndexes() throws ArangoDBException; + + /** + * Checks whether the collection exists + * + * @return true if the collection exists, otherwise false + */ + boolean exists() throws ArangoDBException; + + /** + * Removes all documents from the collection, but leaves the indexes intact + * + * @return information about the collection + * @throws ArangoDBException + * @see API + * Documentation + */ + CollectionEntity truncate() throws ArangoDBException; + + /** + * Removes all documents from the collection, but leaves the indexes intact + * + * @param options + * @return information about the collection + * @throws ArangoDBException + * @see API + * Documentation + * @since ArangoDB 3.5.0 + */ + CollectionEntity truncate(CollectionTruncateOptions options) throws ArangoDBException; + + /** + * Counts the documents in a collection + * + * @return information about the collection, including the number of documents + * @throws ArangoDBException + * @see API + * Documentation + */ + CollectionPropertiesEntity count() throws ArangoDBException; + + /** + * Counts the documents in a collection + * + * @param options + * @return information about the collection, including the number of documents + * @throws ArangoDBException + * @see API + * Documentation + * @since ArangoDB 3.5.0 + */ + CollectionPropertiesEntity count(CollectionCountOptions options) throws ArangoDBException; + + /** + * Creates a collection for this collection's name, then returns collection information from the server. + * + * @return information about the collection + * @throws ArangoDBException + * @see API + * Documentation + */ + CollectionEntity create() throws ArangoDBException; + + /** + * Creates a collection with the given {@code options} for this collection's name, then returns collection + * information from the server. + * + * @param options Additional options, can be null + * @return information about the collection + * @throws ArangoDBException + * @see API + * Documentation + */ + CollectionEntity create(CollectionCreateOptions options) throws ArangoDBException; + + /** + * Deletes the collection from the database. + * + * @throws ArangoDBException + * @see API + * Documentation + */ + void drop() throws ArangoDBException; + + /** + * Deletes the collection from the database. + * + * @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. + * @throws ArangoDBException + * @see API + * Documentation + * @since ArangoDB 3.1.0 + */ + void drop(boolean isSystem) throws ArangoDBException; + + /** + * Tells the server to load the collection into memory. + * + * @return information about the collection + * @throws ArangoDBException + * @see API + * Documentation + */ + CollectionEntity load() throws ArangoDBException; + + /** + * Tells the server to remove the collection from memory. This call does not delete any documents. You can use the + * collection afterwards; in which case it will be loaded into memory, again. + * + * @return information about the collection + * @throws ArangoDBException + * @see API + * Documentation + */ + CollectionEntity unload() throws ArangoDBException; + + /** + * Returns information about the collection + * + * @return information about the collection + * @throws ArangoDBException + * @see API + * Documentation + */ + CollectionEntity getInfo() throws ArangoDBException; + + /** + * Reads the properties of the specified collection + * + * @return properties of the collection + * @throws ArangoDBException + * @see API + * Documentation + */ + CollectionPropertiesEntity getProperties() throws ArangoDBException; + + /** + * Changes the properties of the collection + * + * @param options Additional options, can be null + * @return properties of the collection + * @throws ArangoDBException + * @see API + * Documentation + */ + CollectionPropertiesEntity changeProperties(CollectionPropertiesOptions options) throws ArangoDBException; + + /** + * Renames the collection + * + * @param newName The new name + * @return information about the collection + * @throws ArangoDBException + * @see API + * Documentation + */ + CollectionEntity rename(String newName) throws ArangoDBException; + + /** + * 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 + * @throws ArangoDBException + * @see + * API Documentation + * @since ArangoDB 3.5.0 + */ + ShardEntity getResponsibleShard(final Object value); + + /** + * Retrieve the collections revision + * + * @return information about the collection, including the collections revision + * @throws ArangoDBException + * @see API + * Documentation + */ + CollectionRevisionEntity getRevision() throws ArangoDBException; + + /** + * 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 + * @throws ArangoDBException + * @see API + * Documentation + */ + void grantAccess(String user, Permissions permissions) throws ArangoDBException; + + /** + * 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 + * @throws ArangoDBException + * @see API + * Documentation + */ + void revokeAccess(String user) throws ArangoDBException; + + /** + * Clear the collection access level, revert back to the default access level. + * + * @param user The name of the user + * @throws ArangoDBException + * @see API + * Documentation + * @since ArangoDB 3.2.0 + */ + void resetAccess(String user) throws ArangoDBException; + + /** + * Get the collection access level + * + * @param user The name of the user + * @return permissions of the user + * @throws ArangoDBException + * @see + * API Documentation + * @since ArangoDB 3.2.0 + */ + Permissions getPermissions(String user) throws ArangoDBException; } diff --git a/src/main/java/com/arangodb/ArangoCursor.java b/src/main/java/com/arangodb/ArangoCursor.java index fbb83eb4b..eab1e2a88 100644 --- a/src/main/java/com/arangodb/ArangoCursor.java +++ b/src/main/java/com/arangodb/ArangoCursor.java @@ -20,55 +20,54 @@ package com.arangodb; +import com.arangodb.entity.CursorEntity.Stats; +import com.arangodb.entity.CursorEntity.Warning; + import java.io.Closeable; import java.util.Collection; import java.util.List; -import com.arangodb.entity.CursorEntity.Stats; -import com.arangodb.entity.CursorEntity.Warning; - /** * @author Mark Vollmary - * */ public interface ArangoCursor extends ArangoIterable, ArangoIterator, Closeable { - /** - * @return id of temporary cursor created on the server - */ - String getId(); + /** + * @return id of temporary cursor created on the server + */ + String getId(); - /** - * @return the type of the result elements - */ - Class getType(); + /** + * @return the type of the result elements + */ + Class getType(); - /** - * @return the total number of result documents available (only available if the query was executed with the count - * attribute set) - */ - Integer getCount(); + /** + * @return the total number of result documents available (only available if the query was executed with the count + * attribute set) + */ + Integer getCount(); - /** - * @return extra information about the query result. For data-modification queries, the stats will contain the - * number of modified documents and the number of documents that could not be modified due to an error (if - * ignoreErrors query option is specified) - */ - Stats getStats(); + /** + * @return extra information about the query result. For data-modification queries, the stats will contain the + * number of modified documents and the number of documents that could not be modified due to an error (if + * ignoreErrors query option is specified) + */ + Stats getStats(); - /** - * @return warnings which the query could have been produced - */ - Collection getWarnings(); + /** + * @return warnings which the query could have been produced + */ + Collection getWarnings(); - /** - * @return indicating whether the query result was served from the query cache or not - */ - boolean isCached(); + /** + * @return indicating whether the query result was served from the query cache or not + */ + boolean isCached(); - /** - * @return the remaining results as a {@code List} - */ - List asListRemaining(); + /** + * @return the remaining results as a {@code List} + */ + List asListRemaining(); } diff --git a/src/main/java/com/arangodb/ArangoDB.java b/src/main/java/com/arangodb/ArangoDB.java index ca502a0db..e60e9383d 100644 --- a/src/main/java/com/arangodb/ArangoDB.java +++ b/src/main/java/com/arangodb/ArangoDB.java @@ -70,842 +70,787 @@ @SuppressWarnings("UnusedReturnValue") public interface ArangoDB extends ArangoSerializationAccessor { - /** - * Builder class to build an instance of {@link ArangoDB}. - * - * @author Mark Vollmary - */ - class Builder extends InternalArangoDBBuilder { - - private static final String PROPERTY_KEY_PROTOCOL = "arangodb.protocol"; - - protected Protocol protocol; - - public Builder() { - super(); - } - - @Override - protected void loadProperties(final Properties properties) { - super.loadProperties(properties); - protocol = loadProtocol(properties, protocol); - } - - private static Protocol loadProtocol(final Properties properties, final Protocol currentValue) { - return Protocol.valueOf( - getProperty(properties, PROPERTY_KEY_PROTOCOL, currentValue, ArangoDefaults.DEFAULT_NETWORK_PROTOCOL) - .toUpperCase()); - } - - public Builder useProtocol(final Protocol protocol) { - this.protocol = protocol; - return this; - } - - @Override - public Builder loadProperties(final InputStream in) throws ArangoDBException { - super.loadProperties(in); - return this; - } - - /** - * Adds a host to connect to. Multiple hosts can be added to provide fallbacks. - * - * @param host - * address of the host - * @param port - * port of the host - * @return {@link ArangoDB.Builder} - */ - public Builder host(final String host, final int port) { - setHost(host, port); - return this; - } - - /** - * Sets the connection and request timeout in milliseconds. - * - * @param timeout - * timeout in milliseconds - * @return {@link ArangoDB.Builder} - */ - public Builder timeout(final Integer timeout) { - setTimeout(timeout); - return this; - } - - /** - * Sets the username to use for authentication. - * - * @param user - * the user in the database (default: {@code root}) - * @return {@link ArangoDB.Builder} - */ - public Builder user(final String user) { - setUser(user); - return this; - } - - /** - * Sets the password for the user for authentication. - * - * @param password - * the password of the user in the database (default: {@code null}) - * @return {@link ArangoDB.Builder} - */ - public Builder password(final String password) { - setPassword(password); - return this; - } - - /** - * If set to {@code true} SSL will be used when connecting to an ArangoDB server. - * - * @param useSsl - * whether or not use SSL (default: {@code false}) - * @return {@link ArangoDB.Builder} - */ - public Builder useSsl(final Boolean useSsl) { - setUseSsl(useSsl); - return this; - } - - /** - * Sets the SSL context to be used when {@code true} is passed through {@link #useSsl(Boolean)}. - * - * @param sslContext - * SSL context to be used - * @return {@link ArangoDB.Builder} - */ - public Builder sslContext(final SSLContext sslContext) { - setSslContext(sslContext); - return this; - } - - /** - * Sets the chunk size when {@link Protocol#VST} is used. - * - * @param chunksize - * size of a chunk in bytes - * @return {@link ArangoDB.Builder} - */ - public Builder chunksize(final Integer chunksize) { - setChunksize(chunksize); - return this; - } - - /** - * Sets the maximum number of connections the built in connection pool will open per host. - * - *

- * Defaults: - *

- * - *
-		 * {@link Protocol#VST} == 1
-		 * {@link Protocol#HTTP_JSON} == 20
-		 * {@link Protocol#HTTP_VPACK} == 20
-		 * 
- * - * @param maxConnections - * max number of connections - * @return {@link ArangoDB.Builder} - */ - public Builder maxConnections(final Integer maxConnections) { - setMaxConnections(maxConnections); - return this; - } - - /** - * Set the maximum time to life of a connection. After this time the connection will be closed automatically. - * - * @param connectionTtl - * the maximum time to life of a connection in milliseconds - * @return {@link ArangoDB.Builder} - */ - public Builder connectionTtl(final Long connectionTtl) { - setConnectionTtl(connectionTtl); - return this; - } - - /** - * Whether or not the driver should acquire a list of available coordinators in an ArangoDB cluster or a single - * server with active failover. - * - *

- * The host list will be used for failover and load balancing. - *

- * - * @param acquireHostList - * whether or not automatically acquire a list of available hosts (default: false) - * @return {@link ArangoDB.Builder} - */ - public Builder acquireHostList(final Boolean acquireHostList) { - setAcquireHostList(acquireHostList); - return this; - } - - /** - * Setting the Interval for acquireHostList - * - * @param acquireHostListInterval Interval in Seconds - * - * @return {@link ArangoDB.Builder} - */ - public Builder acquireHostListInterval(final Integer acquireHostListInterval) { - setAcquireHostListInterval(acquireHostListInterval); - return this; - } - - /** - * Sets the load balancing strategy to be used in an ArangoDB cluster setup. - * - * @param loadBalancingStrategy - * the load balancing strategy to be used (default: {@link LoadBalancingStrategy#NONE} - * @return {@link ArangoDB.Builder} - */ - public Builder loadBalancingStrategy(final LoadBalancingStrategy loadBalancingStrategy) { - setLoadBalancingStrategy(loadBalancingStrategy); - return this; - } - - /** - * Register a custom {@link VPackSerializer} for a specific type to be used within the internal serialization - * process. - * - *

- * Attention:can not be used together with {@link #serializer(ArangoSerialization)} - *

- * - * @param clazz - * the type the serializer should be registered for - * @param serializer - * serializer to register - * @return {@link ArangoDB.Builder} - */ - public Builder registerSerializer(final Class clazz, final VPackSerializer serializer) { - vpackBuilder.registerSerializer(clazz, serializer); - return this; - } - - /** - * Register a special serializer for a member class which can only be identified by its enclosing class. - * - *

- * Attention:can not be used together with {@link #serializer(ArangoSerialization)} - *

- * - * @param clazz - * the type of the enclosing class - * @param serializer - * serializer to register - * @return {@link ArangoDB.Builder} - */ - public Builder registerEnclosingSerializer(final Class clazz, final VPackSerializer serializer) { - vpackBuilder.registerEnclosingSerializer(clazz, serializer); - return this; - } - - /** - * Register a custom {@link VPackDeserializer} for a specific type to be used within the internal serialization - * process. - * - *

- * Attention:can not be used together with {@link #serializer(ArangoSerialization)} - *

- * - * @param clazz - * the type the serializer should be registered for - * @param deserializer - * @return {@link ArangoDB.Builder} - */ - public Builder registerDeserializer(final Class clazz, final VPackDeserializer deserializer) { - vpackBuilder.registerDeserializer(clazz, deserializer); - return this; - } - - /** - * Register a custom {@link VPackInstanceCreator} for a specific type to be used within the internal - * serialization process. - * - *

- * Attention:can not be used together with {@link #serializer(ArangoSerialization)} - *

- * - * @param clazz - * the type the instance creator should be registered for - * @param creator - * @return {@link ArangoDB.Builder} - */ - public Builder registerInstanceCreator(final Class clazz, final VPackInstanceCreator creator) { - vpackBuilder.registerInstanceCreator(clazz, creator); - return this; - } - - /** - * Register a custom {@link VPackJsonDeserializer} for a specific type to be used within the internal - * serialization process. - * - *

- * Attention:can not be used together with {@link #serializer(ArangoSerialization)} - *

- * - * @param type - * the type the serializer should be registered for - * @param deserializer - * @return {@link ArangoDB.Builder} - */ - public Builder registerJsonDeserializer(final ValueType type, final VPackJsonDeserializer deserializer) { - vpackParserBuilder.registerDeserializer(type, deserializer); - return this; - } - - /** - * Register a custom {@link VPackJsonDeserializer} for a specific type and attribute name to be used within the - * internal serialization process. - * - *

- * Attention:can not be used together with {@link #serializer(ArangoSerialization)} - *

- * - * @param attribute - * @param type - * the type the serializer should be registered for - * @param deserializer - * @return {@link ArangoDB.Builder} - */ - public Builder registerJsonDeserializer( - final String attribute, - final ValueType type, - final VPackJsonDeserializer deserializer) { - vpackParserBuilder.registerDeserializer(attribute, type, deserializer); - return this; - } - - /** - * Register a custom {@link VPackJsonSerializer} for a specific type to be used within the internal - * serialization process. - * - *

- * Attention:can not be used together with {@link #serializer(ArangoSerialization)} - *

- * - * @param clazz - * the type the serializer should be registered for - * @param serializer - * @return {@link ArangoDB.Builder} - */ - public Builder registerJsonSerializer(final Class clazz, final VPackJsonSerializer serializer) { - vpackParserBuilder.registerSerializer(clazz, serializer); - return this; - } - - /** - * Register a custom {@link VPackJsonSerializer} for a specific type and attribute name to be used within the - * internal serialization process. - * - *

- * Attention:can not be used together with {@link #serializer(ArangoSerialization)} - *

- * - * @param attribute - * @param clazz - * the type the serializer should be registered for - * @param serializer - * @return {@link ArangoDB.Builder} - */ - public Builder registerJsonSerializer( - final String attribute, - final Class clazz, - final VPackJsonSerializer serializer) { - vpackParserBuilder.registerSerializer(attribute, clazz, serializer); - return this; - } - - /** - * Register a custom {@link VPackAnnotationFieldFilter} for a specific type to be used within the internal - * serialization process. - * - *

- * Attention:can not be used together with {@link #serializer(ArangoSerialization)} - *

- * - * @param type - * the type the serializer should be registered for - * @param fieldFilter - * @return {@link ArangoDB.Builder} - */ - public Builder annotationFieldFilter( - final Class type, - final VPackAnnotationFieldFilter fieldFilter) { - vpackBuilder.annotationFieldFilter(type, fieldFilter); - return this; - } - - /** - * Register a custom {@link VPackAnnotationFieldNaming} for a specific type to be used within the internal - * serialization process. - * - *

- * Attention:can not be used together with {@link #serializer(ArangoSerialization)} - *

- * - * @param type - * the type the serializer should be registered for - * @param fieldNaming - * @return {@link ArangoDB.Builder} - */ - public
Builder annotationFieldNaming( - final Class type, - final VPackAnnotationFieldNaming fieldNaming) { - vpackBuilder.annotationFieldNaming(type, fieldNaming); - return this; - } - - /** - * Register a {@link VPackModule} to be used within the internal serialization process. - * - *

- * Attention:can not be used together with {@link #serializer(ArangoSerialization)} - *

- * - * @param module - * module to register - * @return {@link ArangoDB.Builder} - */ - public Builder registerModule(final VPackModule module) { - vpackBuilder.registerModule(module); - return this; - } - - /** - * Register a list of {@link VPackModule} to be used within the internal serialization process. - * - *

- * Attention:can not be used together with {@link #serializer(ArangoSerialization)} - *

- * - * @param modules - * modules to register - * @return {@link ArangoDB.Builder} - */ - public Builder registerModules(final VPackModule... modules) { - vpackBuilder.registerModules(modules); - return this; - } - - /** - * Register a {@link VPackParserModule} to be used within the internal serialization process. - * - *

- * Attention:can not be used together with {@link #serializer(ArangoSerialization)} - *

- * - * @param module - * module to register - * @return {@link ArangoDB.Builder} - */ - public Builder registerJsonModule(final VPackParserModule module) { - vpackParserBuilder.registerModule(module); - return this; - } - - /** - * Register a list of {@link VPackParserModule} to be used within the internal serialization process. - * - *

- * Attention:can not be used together with {@link #serializer(ArangoSerialization)} - *

- * - * @param modules - * modules to register - * @return {@link ArangoDB.Builder} - */ - public Builder registerJsonModules(final VPackParserModule... modules) { - vpackParserBuilder.registerModules(modules); - return this; - } - - /** - * Replace the built-in serializer with the given serializer. - * - *
- * ATTENTION!: Use at your own risk - * - * @param serializer - * custom serializer - * @deprecated use {@link #serializer(ArangoSerialization)} instead - * @return {@link ArangoDB.Builder} - */ - @Deprecated - public Builder setSerializer(final ArangoSerializer serializer) { - serializer(serializer); - return this; - } - - /** - * Replace the built-in deserializer with the given deserializer. - * - *
- * ATTENTION!: Use at your own risk - * - * @param deserializer - * custom deserializer - * @deprecated use {@link #serializer(ArangoSerialization)} instead - * @return {@link ArangoDB.Builder} - */ - @Deprecated - public Builder setDeserializer(final ArangoDeserializer deserializer) { - deserializer(deserializer); - return this; - } - - /** - * Replace the built-in serializer/deserializer with the given one. - * - *
- * ATTENTION!: Any registered custom serializer/deserializer or module will be ignored. - * - * @param serialization - * custom serializer/deserializer - * @return {@link ArangoDB.Builder} - */ - public Builder serializer(final ArangoSerialization serialization) { - setSerializer(serialization); - return this; - } - - /** - * Returns an instance of {@link ArangoDB}. - * - * @return {@link ArangoDB} - */ - public synchronized ArangoDB build() { - if (hosts.isEmpty()) { - hosts.add(host); - } - final VPack vpacker = vpackBuilder.serializeNullValues(false).build(); - final VPack vpackerNull = vpackBuilder.serializeNullValues(true).build(); - final VPackParser vpackParser = vpackParserBuilder.build(); - final ArangoSerializer serializerTemp = serializer != null ? serializer - : new ArangoSerializerImpl(vpacker, vpackerNull, vpackParser); - final ArangoDeserializer deserializerTemp = deserializer != null ? deserializer - : new ArangoDeserializerImpl(vpackerNull, vpackParser); - final DefaultArangoSerialization internal = new DefaultArangoSerialization(serializerTemp, - deserializerTemp); - final ArangoSerialization custom = customSerializer != null ? customSerializer : internal; - final ArangoSerializationFactory util = new ArangoSerializationFactory(internal, custom); - - int protocolMaxConnections = protocol == Protocol.VST ? - ArangoDefaults.MAX_CONNECTIONS_VST_DEFAULT : - ArangoDefaults.MAX_CONNECTIONS_HTTP_DEFAULT; - final int max = maxConnections != null ? Math.max(1, maxConnections) : protocolMaxConnections; - - final ConnectionFactory connectionFactory = (protocol == null || Protocol.VST == protocol) - ? new VstConnectionFactorySync(host, timeout, connectionTtl, useSsl, sslContext) - : new HttpConnectionFactory(timeout, user, password, useSsl, sslContext, custom, protocol, - connectionTtl, httpCookieSpec); - - final Collection hostList = createHostList(max, connectionFactory); - final HostResolver hostResolver = createHostResolver(hostList, max, connectionFactory); - final HostHandler hostHandler = createHostHandler(hostResolver); - - return new ArangoDBImpl( - new VstCommunicationSync.Builder(hostHandler).timeout(timeout).user(user).password(password) - .useSsl(useSsl).sslContext(sslContext).chunksize(chunksize).maxConnections(maxConnections) - .connectionTtl(connectionTtl), - new HttpCommunication.Builder(hostHandler), util, protocol, hostResolver, new ArangoContext()); - } - - } - - /** - * Releases all connections to the server and clear the connection pool. - * - * @throws ArangoDBException - */ - void shutdown() throws ArangoDBException; - - /** - * Returns a {@code ArangoDatabase} instance for the {@code _system} database. - * - * @return database handler - */ - ArangoDatabase db(); - - /** - * Returns a {@code ArangoDatabase} instance for the given database name. - * - * @param name - * Name of the database - * @return database handler - */ - ArangoDatabase db(String name); - - /** - * Creates a new database with the given name. - * - * @see
API - * Documentation - * @param name - * Name of the database to create - * @return true if the database was created successfully. - * @throws ArangoDBException - */ - Boolean createDatabase(String name) throws ArangoDBException; - - /** - * Creates a new database with the given name. - * - * @see API - * Documentation - * @param options Creation options - * @return true if the database was created successfully. - * @since ArangoDB 3.6.0 - * @throws ArangoDBException - */ - Boolean createDatabase(DBCreateOptions options) throws ArangoDBException; - - /** - * Retrieves a list of all existing databases - * - * @see API - * Documentation - * @return a list of all existing databases - * @throws ArangoDBException - */ - Collection getDatabases() throws ArangoDBException; - - /** - * Retrieves a list of all databases the current user can access - * - * @see API - * Documentation - * @return a list of all databases the current user can access - * @throws ArangoDBException - */ - Collection getAccessibleDatabases() throws ArangoDBException; - - /** - * List available database to the specified user - * - * @see API - * Documentation - * @param user - * The name of the user for which you want to query the databases - * @return list of database names which are available for the specified user - * @throws ArangoDBException - */ - Collection getAccessibleDatabasesFor(String user) throws ArangoDBException; - - /** - * Returns the server name and version number. - * - * @see API - * Documentation - * @return the server version, number - * @throws ArangoDBException - */ - ArangoDBVersion getVersion() throws ArangoDBException; - - /** - * Returns the server storage engine. - * - * @see API - * Documentation - * @return the storage engine name - * @throws ArangoDBException - */ - ArangoDBEngine getEngine() throws ArangoDBException; - - /** - * Returns the server role. - * - * @return the server role - * @throws ArangoDBException - */ - ServerRole getRole() throws ArangoDBException; - - /** - * 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. - * - * @see API Documentation - * @param user - * The name of the user - * @param passwd - * The user password - * @return information about the user - * @throws ArangoDBException - */ - UserEntity createUser(String user, String passwd) throws ArangoDBException; - - /** - * 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. - * - * @see API Documentation - * @param user - * The name of the user - * @param passwd - * The user password - * @param options - * Additional options, can be null - * @return information about the user - * @throws ArangoDBException - */ - UserEntity createUser(String user, String passwd, UserCreateOptions options) throws ArangoDBException; - - /** - * Removes an existing user, identified by user. You need access to the _system database. - * - * @see API Documentation - * @param user - * The name of the user - * @throws ArangoDBException - */ - void deleteUser(String user) throws ArangoDBException; - - /** - * 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. - * - * @see API Documentation - * @param user - * The name of the user - * @return information about the user - * @throws ArangoDBException - */ - UserEntity getUser(String user) throws ArangoDBException; - - /** - * Fetches data about all users. You can only execute this call if you have access to the _system database. - * - * @see API - * Documentation - * @return informations about all users - * @throws ArangoDBException - */ - Collection getUsers() throws ArangoDBException; - - /** - * 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. - * - * @see API Documentation - * @param user - * The name of the user - * @param options - * Properties of the user to be changed - * @return information about the user - * @throws ArangoDBException - */ - UserEntity updateUser(String user, UserUpdateOptions options) throws ArangoDBException; - - /** - * 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. - * - * @see API - * Documentation - * @param user - * The name of the user - * @param options - * Additional properties of the user, can be null - * @return information about the user - * @throws ArangoDBException - */ - UserEntity replaceUser(String user, UserUpdateOptions options) throws ArangoDBException; - - /** - * Sets the default access level for databases for the user {@code 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 - * @throws ArangoDBException - */ - void grantDefaultDatabaseAccess(String user, Permissions permissions) throws ArangoDBException; - - /** - * Sets the default access level for collections for the user {@code 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 - * @throws ArangoDBException - */ - void grantDefaultCollectionAccess(String user, Permissions permissions) throws ArangoDBException; - - /** - * Generic Execute. Use this method to execute custom FOXX services. - * - * @param request - * VelocyStream request - * @return VelocyStream response - * @throws ArangoDBException - */ - Response execute(Request request) throws ArangoDBException; - - /** - * Generic Execute. Use this method to execute custom FOXX services. - * - * @param request - * VelocyStream request - * @param hostHandle - * Used to stick to a specific host when using {@link LoadBalancingStrategy#ROUND_ROBIN} - * @return VelocyStream response - * @throws ArangoDBException - */ - Response execute(Request request, HostHandle hostHandle) throws ArangoDBException; - - /** - * Returns fatal, error, warning or info log messages from the server's global log. - * - * @see API - * Documentation - * @param options - * Additional options, can be null - * @return the log messages - * @throws ArangoDBException - */ - LogEntity getLogs(LogOptions options) throws ArangoDBException; - - /** - * Returns the server's current loglevel settings. - * - * @return the server's current loglevel settings - * @since ArangoDB 3.1.0 - * @throws ArangoDBException - */ - LogLevelEntity getLogLevel() throws ArangoDBException; - - /** - * Modifies and returns the server's current loglevel settings. - * - * @param entity - * loglevel settings - * @return the server's current loglevel settings - * @since ArangoDB 3.1.0 - * @throws ArangoDBException - */ - LogLevelEntity setLogLevel(LogLevelEntity entity) throws ArangoDBException; - - /** - * Attention: Please do not use! - * - * @param cursorInitializer - * @return ArangoDB - */ - ArangoDB _setCursorInitializer(ArangoCursorInitializer cursorInitializer); + /** + * Builder class to build an instance of {@link ArangoDB}. + * + * @author Mark Vollmary + */ + class Builder extends InternalArangoDBBuilder { + + private static final String PROPERTY_KEY_PROTOCOL = "arangodb.protocol"; + + protected Protocol protocol; + + public Builder() { + super(); + } + + @Override + protected void loadProperties(final Properties properties) { + super.loadProperties(properties); + protocol = loadProtocol(properties, protocol); + } + + private static Protocol loadProtocol(final Properties properties, final Protocol currentValue) { + return Protocol.valueOf( + getProperty(properties, PROPERTY_KEY_PROTOCOL, currentValue, ArangoDefaults.DEFAULT_NETWORK_PROTOCOL) + .toUpperCase()); + } + + public Builder useProtocol(final Protocol protocol) { + this.protocol = protocol; + return this; + } + + @Override + public Builder loadProperties(final InputStream in) throws ArangoDBException { + super.loadProperties(in); + return this; + } + + /** + * Adds a host to connect to. Multiple hosts can be added to provide fallbacks. + * + * @param host address of the host + * @param port port of the host + * @return {@link ArangoDB.Builder} + */ + public Builder host(final String host, final int port) { + setHost(host, port); + return this; + } + + /** + * Sets the connection and request timeout in milliseconds. + * + * @param timeout timeout in milliseconds + * @return {@link ArangoDB.Builder} + */ + public Builder timeout(final Integer timeout) { + setTimeout(timeout); + return this; + } + + /** + * Sets the username to use for authentication. + * + * @param user the user in the database (default: {@code root}) + * @return {@link ArangoDB.Builder} + */ + public Builder user(final String user) { + setUser(user); + return this; + } + + /** + * Sets the password for the user for authentication. + * + * @param password the password of the user in the database (default: {@code null}) + * @return {@link ArangoDB.Builder} + */ + public Builder password(final String password) { + setPassword(password); + return this; + } + + /** + * If set to {@code true} SSL will be used when connecting to an ArangoDB server. + * + * @param useSsl whether or not use SSL (default: {@code false}) + * @return {@link ArangoDB.Builder} + */ + public Builder useSsl(final Boolean useSsl) { + setUseSsl(useSsl); + return this; + } + + /** + * Sets the SSL context to be used when {@code true} is passed through {@link #useSsl(Boolean)}. + * + * @param sslContext SSL context to be used + * @return {@link ArangoDB.Builder} + */ + public Builder sslContext(final SSLContext sslContext) { + setSslContext(sslContext); + return this; + } + + /** + * Sets the chunk size when {@link Protocol#VST} is used. + * + * @param chunksize size of a chunk in bytes + * @return {@link ArangoDB.Builder} + */ + public Builder chunksize(final Integer chunksize) { + setChunksize(chunksize); + return this; + } + + /** + * Sets the maximum number of connections the built in connection pool will open per host. + * + *

+ * Defaults: + *

+ * + *
+         * {@link Protocol#VST} == 1
+         * {@link Protocol#HTTP_JSON} == 20
+         * {@link Protocol#HTTP_VPACK} == 20
+         * 
+ * + * @param maxConnections max number of connections + * @return {@link ArangoDB.Builder} + */ + public Builder maxConnections(final Integer maxConnections) { + setMaxConnections(maxConnections); + return this; + } + + /** + * Set the maximum time to life of a connection. After this time the connection will be closed automatically. + * + * @param connectionTtl the maximum time to life of a connection in milliseconds + * @return {@link ArangoDB.Builder} + */ + public Builder connectionTtl(final Long connectionTtl) { + setConnectionTtl(connectionTtl); + return this; + } + + /** + * Whether or not the driver should acquire a list of available coordinators in an ArangoDB cluster or a single + * server with active failover. + * + *

+ * The host list will be used for failover and load balancing. + *

+ * + * @param acquireHostList whether or not automatically acquire a list of available hosts (default: false) + * @return {@link ArangoDB.Builder} + */ + public Builder acquireHostList(final Boolean acquireHostList) { + setAcquireHostList(acquireHostList); + return this; + } + + /** + * Setting the Interval for acquireHostList + * + * @param acquireHostListInterval Interval in Seconds + * @return {@link ArangoDB.Builder} + */ + public Builder acquireHostListInterval(final Integer acquireHostListInterval) { + setAcquireHostListInterval(acquireHostListInterval); + return this; + } + + /** + * Sets the load balancing strategy to be used in an ArangoDB cluster setup. + * + * @param loadBalancingStrategy the load balancing strategy to be used (default: {@link LoadBalancingStrategy#NONE} + * @return {@link ArangoDB.Builder} + */ + public Builder loadBalancingStrategy(final LoadBalancingStrategy loadBalancingStrategy) { + setLoadBalancingStrategy(loadBalancingStrategy); + return this; + } + + /** + * Register a custom {@link VPackSerializer} for a specific type to be used within the internal serialization + * process. + * + *

+ * Attention:can not be used together with {@link #serializer(ArangoSerialization)} + *

+ * + * @param clazz the type the serializer should be registered for + * @param serializer serializer to register + * @return {@link ArangoDB.Builder} + */ + public Builder registerSerializer(final Class clazz, final VPackSerializer serializer) { + vpackBuilder.registerSerializer(clazz, serializer); + return this; + } + + /** + * Register a special serializer for a member class which can only be identified by its enclosing class. + * + *

+ * Attention:can not be used together with {@link #serializer(ArangoSerialization)} + *

+ * + * @param clazz the type of the enclosing class + * @param serializer serializer to register + * @return {@link ArangoDB.Builder} + */ + public Builder registerEnclosingSerializer(final Class clazz, final VPackSerializer serializer) { + vpackBuilder.registerEnclosingSerializer(clazz, serializer); + return this; + } + + /** + * Register a custom {@link VPackDeserializer} for a specific type to be used within the internal serialization + * process. + * + *

+ * Attention:can not be used together with {@link #serializer(ArangoSerialization)} + *

+ * + * @param clazz the type the serializer should be registered for + * @param deserializer + * @return {@link ArangoDB.Builder} + */ + public Builder registerDeserializer(final Class clazz, final VPackDeserializer deserializer) { + vpackBuilder.registerDeserializer(clazz, deserializer); + return this; + } + + /** + * Register a custom {@link VPackInstanceCreator} for a specific type to be used within the internal + * serialization process. + * + *

+ * Attention:can not be used together with {@link #serializer(ArangoSerialization)} + *

+ * + * @param clazz the type the instance creator should be registered for + * @param creator + * @return {@link ArangoDB.Builder} + */ + public Builder registerInstanceCreator(final Class clazz, final VPackInstanceCreator creator) { + vpackBuilder.registerInstanceCreator(clazz, creator); + return this; + } + + /** + * Register a custom {@link VPackJsonDeserializer} for a specific type to be used within the internal + * serialization process. + * + *

+ * Attention:can not be used together with {@link #serializer(ArangoSerialization)} + *

+ * + * @param type the type the serializer should be registered for + * @param deserializer + * @return {@link ArangoDB.Builder} + */ + public Builder registerJsonDeserializer(final ValueType type, final VPackJsonDeserializer deserializer) { + vpackParserBuilder.registerDeserializer(type, deserializer); + return this; + } + + /** + * Register a custom {@link VPackJsonDeserializer} for a specific type and attribute name to be used within the + * internal serialization process. + * + *

+ * Attention:can not be used together with {@link #serializer(ArangoSerialization)} + *

+ * + * @param attribute + * @param type the type the serializer should be registered for + * @param deserializer + * @return {@link ArangoDB.Builder} + */ + public Builder registerJsonDeserializer( + final String attribute, + final ValueType type, + final VPackJsonDeserializer deserializer) { + vpackParserBuilder.registerDeserializer(attribute, type, deserializer); + return this; + } + + /** + * Register a custom {@link VPackJsonSerializer} for a specific type to be used within the internal + * serialization process. + * + *

+ * Attention:can not be used together with {@link #serializer(ArangoSerialization)} + *

+ * + * @param clazz the type the serializer should be registered for + * @param serializer + * @return {@link ArangoDB.Builder} + */ + public Builder registerJsonSerializer(final Class clazz, final VPackJsonSerializer serializer) { + vpackParserBuilder.registerSerializer(clazz, serializer); + return this; + } + + /** + * Register a custom {@link VPackJsonSerializer} for a specific type and attribute name to be used within the + * internal serialization process. + * + *

+ * Attention:can not be used together with {@link #serializer(ArangoSerialization)} + *

+ * + * @param attribute + * @param clazz the type the serializer should be registered for + * @param serializer + * @return {@link ArangoDB.Builder} + */ + public Builder registerJsonSerializer( + final String attribute, + final Class clazz, + final VPackJsonSerializer serializer) { + vpackParserBuilder.registerSerializer(attribute, clazz, serializer); + return this; + } + + /** + * Register a custom {@link VPackAnnotationFieldFilter} for a specific type to be used within the internal + * serialization process. + * + *

+ * Attention:can not be used together with {@link #serializer(ArangoSerialization)} + *

+ * + * @param type the type the serializer should be registered for + * @param fieldFilter + * @return {@link ArangoDB.Builder} + */ + public Builder annotationFieldFilter( + final Class type, + final VPackAnnotationFieldFilter fieldFilter) { + vpackBuilder.annotationFieldFilter(type, fieldFilter); + return this; + } + + /** + * Register a custom {@link VPackAnnotationFieldNaming} for a specific type to be used within the internal + * serialization process. + * + *

+ * Attention:can not be used together with {@link #serializer(ArangoSerialization)} + *

+ * + * @param type the type the serializer should be registered for + * @param fieldNaming + * @return {@link ArangoDB.Builder} + */ + public
Builder annotationFieldNaming( + final Class type, + final VPackAnnotationFieldNaming fieldNaming) { + vpackBuilder.annotationFieldNaming(type, fieldNaming); + return this; + } + + /** + * Register a {@link VPackModule} to be used within the internal serialization process. + * + *

+ * Attention:can not be used together with {@link #serializer(ArangoSerialization)} + *

+ * + * @param module module to register + * @return {@link ArangoDB.Builder} + */ + public Builder registerModule(final VPackModule module) { + vpackBuilder.registerModule(module); + return this; + } + + /** + * Register a list of {@link VPackModule} to be used within the internal serialization process. + * + *

+ * Attention:can not be used together with {@link #serializer(ArangoSerialization)} + *

+ * + * @param modules modules to register + * @return {@link ArangoDB.Builder} + */ + public Builder registerModules(final VPackModule... modules) { + vpackBuilder.registerModules(modules); + return this; + } + + /** + * Register a {@link VPackParserModule} to be used within the internal serialization process. + * + *

+ * Attention:can not be used together with {@link #serializer(ArangoSerialization)} + *

+ * + * @param module module to register + * @return {@link ArangoDB.Builder} + */ + public Builder registerJsonModule(final VPackParserModule module) { + vpackParserBuilder.registerModule(module); + return this; + } + + /** + * Register a list of {@link VPackParserModule} to be used within the internal serialization process. + * + *

+ * Attention:can not be used together with {@link #serializer(ArangoSerialization)} + *

+ * + * @param modules modules to register + * @return {@link ArangoDB.Builder} + */ + public Builder registerJsonModules(final VPackParserModule... modules) { + vpackParserBuilder.registerModules(modules); + return this; + } + + /** + * Replace the built-in serializer with the given serializer. + *

+ *
+ * ATTENTION!: Use at your own risk + * + * @param serializer custom serializer + * @return {@link ArangoDB.Builder} + * @deprecated use {@link #serializer(ArangoSerialization)} instead + */ + @Deprecated + public Builder setSerializer(final ArangoSerializer serializer) { + serializer(serializer); + return this; + } + + /** + * Replace the built-in deserializer with the given deserializer. + *

+ *
+ * ATTENTION!: Use at your own risk + * + * @param deserializer custom deserializer + * @return {@link ArangoDB.Builder} + * @deprecated use {@link #serializer(ArangoSerialization)} instead + */ + @Deprecated + public Builder setDeserializer(final ArangoDeserializer deserializer) { + deserializer(deserializer); + return this; + } + + /** + * Replace the built-in serializer/deserializer with the given one. + *

+ *
+ * ATTENTION!: Any registered custom serializer/deserializer or module will be ignored. + * + * @param serialization custom serializer/deserializer + * @return {@link ArangoDB.Builder} + */ + public Builder serializer(final ArangoSerialization serialization) { + setSerializer(serialization); + return this; + } + + /** + * Returns an instance of {@link ArangoDB}. + * + * @return {@link ArangoDB} + */ + public synchronized ArangoDB build() { + if (hosts.isEmpty()) { + hosts.add(host); + } + final VPack vpacker = vpackBuilder.serializeNullValues(false).build(); + final VPack vpackerNull = vpackBuilder.serializeNullValues(true).build(); + final VPackParser vpackParser = vpackParserBuilder.build(); + final ArangoSerializer serializerTemp = serializer != null ? serializer + : new ArangoSerializerImpl(vpacker, vpackerNull, vpackParser); + final ArangoDeserializer deserializerTemp = deserializer != null ? deserializer + : new ArangoDeserializerImpl(vpackerNull, vpackParser); + final DefaultArangoSerialization internal = new DefaultArangoSerialization(serializerTemp, + deserializerTemp); + final ArangoSerialization custom = customSerializer != null ? customSerializer : internal; + final ArangoSerializationFactory util = new ArangoSerializationFactory(internal, custom); + + int protocolMaxConnections = protocol == Protocol.VST ? + ArangoDefaults.MAX_CONNECTIONS_VST_DEFAULT : + ArangoDefaults.MAX_CONNECTIONS_HTTP_DEFAULT; + final int max = maxConnections != null ? Math.max(1, maxConnections) : protocolMaxConnections; + + final ConnectionFactory connectionFactory = (protocol == null || Protocol.VST == protocol) + ? new VstConnectionFactorySync(host, timeout, connectionTtl, useSsl, sslContext) + : new HttpConnectionFactory(timeout, user, password, useSsl, sslContext, custom, protocol, + connectionTtl, httpCookieSpec); + + final Collection hostList = createHostList(max, connectionFactory); + final HostResolver hostResolver = createHostResolver(hostList, max, connectionFactory); + final HostHandler hostHandler = createHostHandler(hostResolver); + + return new ArangoDBImpl( + new VstCommunicationSync.Builder(hostHandler).timeout(timeout).user(user).password(password) + .useSsl(useSsl).sslContext(sslContext).chunksize(chunksize).maxConnections(maxConnections) + .connectionTtl(connectionTtl), + new HttpCommunication.Builder(hostHandler), util, protocol, hostResolver, new ArangoContext()); + } + + } + + /** + * Releases all connections to the server and clear the connection pool. + * + * @throws ArangoDBException + */ + void shutdown() throws ArangoDBException; + + /** + * Returns a {@code ArangoDatabase} instance for the {@code _system} database. + * + * @return database handler + */ + ArangoDatabase db(); + + /** + * Returns a {@code ArangoDatabase} instance for the given database name. + * + * @param name Name of the database + * @return database handler + */ + ArangoDatabase db(String name); + + /** + * Creates a new database with the given name. + * + * @param name Name of the database to create + * @return true if the database was created successfully. + * @throws ArangoDBException + * @see
API + * Documentation + */ + Boolean createDatabase(String name) throws ArangoDBException; + + /** + * Creates a new database with the given name. + * + * @param options Creation options + * @return true if the database was created successfully. + * @throws ArangoDBException + * @see API + * Documentation + * @since ArangoDB 3.6.0 + */ + Boolean createDatabase(DBCreateOptions options) throws ArangoDBException; + + /** + * Retrieves a list of all existing databases + * + * @return a list of all existing databases + * @throws ArangoDBException + * @see API + * Documentation + */ + Collection getDatabases() throws ArangoDBException; + + /** + * Retrieves a list of all databases the current user can access + * + * @return a list of all databases the current user can access + * @throws ArangoDBException + * @see API + * Documentation + */ + Collection getAccessibleDatabases() throws ArangoDBException; + + /** + * List available database to the specified user + * + * @param user The name of the user for which you want to query the databases + * @return list of database names which are available for the specified user + * @throws ArangoDBException + * @see API + * Documentation + */ + Collection getAccessibleDatabasesFor(String user) throws ArangoDBException; + + /** + * Returns the server name and version number. + * + * @return the server version, number + * @throws ArangoDBException + * @see API + * Documentation + */ + ArangoDBVersion getVersion() throws ArangoDBException; + + /** + * Returns the server storage engine. + * + * @return the storage engine name + * @throws ArangoDBException + * @see API + * Documentation + */ + ArangoDBEngine getEngine() throws ArangoDBException; + + /** + * Returns the server role. + * + * @return the server role + * @throws ArangoDBException + */ + ServerRole getRole() throws ArangoDBException; + + /** + * 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 + * @throws ArangoDBException + * @see API Documentation + */ + UserEntity createUser(String user, String passwd) throws ArangoDBException; + + /** + * 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 options, can be null + * @return information about the user + * @throws ArangoDBException + * @see API Documentation + */ + UserEntity createUser(String user, String passwd, UserCreateOptions options) throws ArangoDBException; + + /** + * Removes an existing user, identified by user. You need access to the _system database. + * + * @param user The name of the user + * @throws ArangoDBException + * @see API Documentation + */ + void deleteUser(String user) throws ArangoDBException; + + /** + * 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 + * @throws ArangoDBException + * @see API Documentation + */ + UserEntity getUser(String user) throws ArangoDBException; + + /** + * Fetches data about all users. You can only execute this call if you have access to the _system database. + * + * @return informations about all users + * @throws ArangoDBException + * @see API + * Documentation + */ + Collection getUsers() throws ArangoDBException; + + /** + * 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 + * @throws ArangoDBException + * @see API Documentation + */ + UserEntity updateUser(String user, UserUpdateOptions options) throws ArangoDBException; + + /** + * 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 + * @throws ArangoDBException + * @see API + * Documentation + */ + UserEntity replaceUser(String user, UserUpdateOptions options) throws ArangoDBException; + + /** + * Sets the default access level for databases for the user {@code 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 + * @throws ArangoDBException + * @since ArangoDB 3.2.0 + */ + void grantDefaultDatabaseAccess(String user, Permissions permissions) throws ArangoDBException; + + /** + * Sets the default access level for collections for the user {@code 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 + * @throws ArangoDBException + * @since ArangoDB 3.2.0 + */ + void grantDefaultCollectionAccess(String user, Permissions permissions) throws ArangoDBException; + + /** + * Generic Execute. Use this method to execute custom FOXX services. + * + * @param request VelocyStream request + * @return VelocyStream response + * @throws ArangoDBException + */ + Response execute(Request request) throws ArangoDBException; + + /** + * Generic Execute. Use this method to execute custom FOXX services. + * + * @param request VelocyStream request + * @param hostHandle Used to stick to a specific host when using {@link LoadBalancingStrategy#ROUND_ROBIN} + * @return VelocyStream response + * @throws ArangoDBException + */ + Response execute(Request request, HostHandle hostHandle) throws ArangoDBException; + + /** + * Returns fatal, error, warning or info log messages from the server's global log. + * + * @param options Additional options, can be null + * @return the log messages + * @throws ArangoDBException + * @see API + * Documentation + */ + LogEntity getLogs(LogOptions options) throws ArangoDBException; + + /** + * Returns the server's current loglevel settings. + * + * @return the server's current loglevel settings + * @throws ArangoDBException + * @since ArangoDB 3.1.0 + */ + LogLevelEntity getLogLevel() throws ArangoDBException; + + /** + * Modifies and returns the server's current loglevel settings. + * + * @param entity loglevel settings + * @return the server's current loglevel settings + * @throws ArangoDBException + * @since ArangoDB 3.1.0 + */ + LogLevelEntity setLogLevel(LogLevelEntity entity) throws ArangoDBException; + + /** + * Attention: Please do not use! + * + * @param cursorInitializer + * @return ArangoDB + */ + ArangoDB _setCursorInitializer(ArangoCursorInitializer cursorInitializer); } diff --git a/src/main/java/com/arangodb/ArangoDBException.java b/src/main/java/com/arangodb/ArangoDBException.java index 908d6b9ad..7e5c45886 100644 --- a/src/main/java/com/arangodb/ArangoDBException.java +++ b/src/main/java/com/arangodb/ArangoDBException.java @@ -24,66 +24,65 @@ /** * @author Mark Vollmary - * */ public class ArangoDBException extends RuntimeException { - private static final long serialVersionUID = 6165638002614173801L; - private final ErrorEntity entity; - private final Integer responseCode; + private static final long serialVersionUID = 6165638002614173801L; + private final ErrorEntity entity; + private final Integer responseCode; - public ArangoDBException(final ErrorEntity errorEntity) { - super(String.format("Response: %s, Error: %s - %s", errorEntity.getCode(), errorEntity.getErrorNum(), - errorEntity.getErrorMessage())); - this.entity = errorEntity; - this.responseCode = null; - } + public ArangoDBException(final ErrorEntity errorEntity) { + super(String.format("Response: %s, Error: %s - %s", errorEntity.getCode(), errorEntity.getErrorNum(), + errorEntity.getErrorMessage())); + this.entity = errorEntity; + this.responseCode = null; + } - public ArangoDBException(final String message) { - super(message); - this.entity = null; - this.responseCode = null; - } + public ArangoDBException(final String message) { + super(message); + this.entity = null; + this.responseCode = null; + } - public ArangoDBException(final String message, final Integer responseCode) { - super(message); - this.entity = null; - this.responseCode = responseCode; - } + public ArangoDBException(final String message, final Integer responseCode) { + super(message); + this.entity = null; + this.responseCode = responseCode; + } - public ArangoDBException(final Throwable cause) { - super(cause); - this.entity = null; - this.responseCode = null; - } + public ArangoDBException(final Throwable cause) { + super(cause); + this.entity = null; + this.responseCode = null; + } - /** - * @return ArangoDB error message - */ - public String getErrorMessage() { - return entity != null ? entity.getErrorMessage() : null; - } + /** + * @return ArangoDB error message + */ + public String getErrorMessage() { + return entity != null ? entity.getErrorMessage() : null; + } - /** - * @return ArangoDB exception - */ - public String getException() { - return entity != null ? entity.getException() : null; - } + /** + * @return ArangoDB exception + */ + public String getException() { + return entity != null ? entity.getException() : null; + } - /** - * @return HTTP response code - */ - public Integer getResponseCode() { - Integer entityResponseCode = entity != null ? entity.getCode() : null; - return responseCode != null ? responseCode : entityResponseCode; - } + /** + * @return HTTP response code + */ + public Integer getResponseCode() { + Integer entityResponseCode = entity != null ? entity.getCode() : null; + return responseCode != null ? responseCode : entityResponseCode; + } - /** - * @return ArangoDB error number - */ - public Integer getErrorNum() { - return entity != null ? entity.getErrorNum() : null; - } + /** + * @return ArangoDB error number + */ + public Integer getErrorNum() { + return entity != null ? entity.getErrorNum() : null; + } } diff --git a/src/main/java/com/arangodb/ArangoDatabase.java b/src/main/java/com/arangodb/ArangoDatabase.java index 00a8f9203..029ba7a6f 100644 --- a/src/main/java/com/arangodb/ArangoDatabase.java +++ b/src/main/java/com/arangodb/ArangoDatabase.java @@ -40,738 +40,738 @@ @SuppressWarnings("UnusedReturnValue") public interface ArangoDatabase extends ArangoSerializationAccessor { - /** - * Return the main entry point for the ArangoDB driver - * - * @return main entry point - */ - ArangoDB arango(); - - /** - * Returns the name of the database - * - * @return database name - */ - String name(); - - /** - * Returns the server name and version number. - * - * @return the server version, number - * @throws ArangoDBException - * @see API - * Documentation - */ - ArangoDBVersion getVersion() throws ArangoDBException; - - /** - * Returns the name of the used storage engine. - * - * @return the storage engine name - * @throws ArangoDBException - * @see API - * Documentation - */ - ArangoDBEngine getEngine() throws ArangoDBException; - - /** - * Checks whether the database exists - * - * @return true if the database exists, otherwise false - */ - boolean exists() throws ArangoDBException; - - /** - * Retrieves a list of all databases the current user can access - * - * @return a list of all databases the current user can access - * @throws ArangoDBException - * @see API - * Documentation - */ - Collection getAccessibleDatabases() throws ArangoDBException; - - /** - * Returns a {@code ArangoCollection} instance for the given collection name. - * - * @param name Name of the collection - * @return collection handler - */ - ArangoCollection collection(String name); - - /** - * Creates a collection for the given collection's name, then returns collection information from the server. - * - * @param name The name of the collection - * @return information about the collection - * @throws ArangoDBException - * @see API - * Documentation - */ - CollectionEntity createCollection(String name) throws ArangoDBException; - - /** - * Creates a collection with the given {@code options} for this collection's name, then returns collection - * information from the server. - * - * @param name The name of the collection - * @param options Additional options, can be null - * @return information about the collection - * @throws ArangoDBException - * @see API - * Documentation - */ - CollectionEntity createCollection(String name, CollectionCreateOptions options) throws ArangoDBException; - - /** - * Fetches all collections from the database and returns an list of collection descriptions. - * - * @return list of information about all collections - * @throws ArangoDBException - * @see API - * Documentation - */ - Collection getCollections() throws ArangoDBException; - - /** - * Fetches all collections from the database and returns an list of collection descriptions. - * - * @param options Additional options, can be null - * @return list of information about all collections - * @throws ArangoDBException - * @see API - * Documentation - */ - Collection getCollections(CollectionsReadOptions options) throws ArangoDBException; - - /** - * Returns an index - * - * @param id The index-handle - * @return information about the index - * @throws ArangoDBException - * @see API Documentation - */ - IndexEntity getIndex(String id) throws ArangoDBException; - - /** - * Deletes an index - * - * @param id The index-handle - * @return the id of the index - * @throws ArangoDBException - * @see API Documentation - */ - String deleteIndex(String id) throws ArangoDBException; - - /** - * Creates the database - * - * @return true if the database was created successfully. - * @throws ArangoDBException - * @see API - * Documentation - */ - Boolean create() throws ArangoDBException; - - /** - * Deletes the database from the server. - * - * @return true if the database was dropped successfully - * @throws ArangoDBException - * @see API - * Documentation - */ - Boolean drop() throws ArangoDBException; - - /** - * Grants or revoke access to the database for user {@code 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 - * @throws ArangoDBException - * @see - * API Documentation - */ - void grantAccess(String user, Permissions permissions) throws ArangoDBException; - - /** - * Grants access to the database for user {@code user}. You need permission to the _system database in order to - * execute this call. - * - * @param user The name of the user - * @throws ArangoDBException - * @see - * API Documentation - */ - void grantAccess(String user) throws ArangoDBException; - - /** - * Revokes access to the database dbname for user {@code user}. You need permission to the _system database in order - * to execute this call. - * - * @param user The name of the user - * @throws ArangoDBException - * @see - * API Documentation - */ - void revokeAccess(String user) throws ArangoDBException; - - /** - * Clear the database access level, revert back to the default access level. - * - * @param user The name of the user - * @throws ArangoDBException - * @see - * API Documentation - * @since ArangoDB 3.2.0 - */ - void resetAccess(String user) throws ArangoDBException; - - /** - * Sets the default access level for collections within this database for the user {@code 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 - * @throws ArangoDBException - * @since ArangoDB 3.2.0 - */ - void grantDefaultCollectionAccess(String user, Permissions permissions) throws ArangoDBException; - - /** - * Get specific database access level - * - * @param user The name of the user - * @return permissions of the user - * @throws ArangoDBException - * @see API - * Documentation - * @since ArangoDB 3.2.0 - */ - Permissions getPermissions(String user) throws ArangoDBException; - - /** - * 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 An AQL query string - * @param bindVars key/value pairs defining the variables to bind the query to - * @param options Additional options that will be passed to the query API, can be null - * @param type The type of the result (POJO class, VPackSlice, String for JSON, or Collection/List/Map) - * @return cursor of the results - * @throws ArangoDBException - * @see API - * Documentation - */ - ArangoCursor query(String query, Map bindVars, AqlQueryOptions options, Class type) - throws ArangoDBException; - - /** - * Performs a database query using the given {@code query}, then returns a new {@code ArangoCursor} instance for the - * result list. - * - * @param query An AQL query string - * @param options Additional options that will be passed to the query API, can be null - * @param type The type of the result (POJO class, VPackSlice, String for JSON, or Collection/List/Map) - * @return cursor of the results - * @throws ArangoDBException - * @see API - * Documentation - */ - ArangoCursor query(String query, AqlQueryOptions options, Class type) throws ArangoDBException; - - /** - * 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 An AQL query string - * @param bindVars key/value pairs defining the variables to bind the query to - * @param type The type of the result (POJO class, VPackSlice, String for JSON, or Collection/List/Map) - * @return cursor of the results - * @throws ArangoDBException - * @see API - * Documentation - */ - ArangoCursor query(String query, Map bindVars, Class type) throws ArangoDBException; - - /** - * Performs a database query using the given {@code query}, then returns a new {@code ArangoCursor} instance for the - * result list. - * - * @param query An AQL query string - * @param type The type of the result (POJO class, VPackSlice, String for JSON, or Collection/List/Map) - * @return cursor of the results - * @throws ArangoDBException - * @see API - * Documentation - */ - ArangoCursor query(String query, Class type) throws ArangoDBException; - - /** - * 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 class, VPackSlice, String for JSON, or Collection/List/Map) - * @return cursor of the results - * @throws ArangoDBException - * @see API - * Documentation - */ - ArangoCursor cursor(String cursorId, Class type) throws ArangoDBException; - - /** - * 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 - * @throws ArangoDBException - * @see API - * Documentation - */ - AqlExecutionExplainEntity explainQuery(String query, Map bindVars, AqlQueryExplainOptions options) - throws ArangoDBException; - - /** - * Parse an AQL query and return information about it This method is for query validation only. To actually query - * the database, see {@link ArangoDatabase#query(String, Map, AqlQueryOptions, Class)} - * - * @param query the query which you want parse - * @return imformation about the query - * @throws ArangoDBException - * @see API - * Documentation - */ - AqlParseEntity parseQuery(String query) throws ArangoDBException; - - /** - * Clears the AQL query cache - * - * @throws ArangoDBException - * @see API - * Documentation - */ - void clearQueryCache() throws ArangoDBException; - - /** - * Returns the global configuration for the AQL query cache - * - * @return configuration for the AQL query cache - * @throws ArangoDBException - * @see API - * Documentation - */ - QueryCachePropertiesEntity getQueryCacheProperties() throws ArangoDBException; - - /** - * 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 - * @throws ArangoDBException - * @see API - * Documentation - */ - QueryCachePropertiesEntity setQueryCacheProperties(QueryCachePropertiesEntity properties) throws ArangoDBException; - - /** - * Returns the configuration for the AQL query tracking - * - * @return configuration for the AQL query tracking - * @throws ArangoDBException - * @see API - * Documentation - */ - QueryTrackingPropertiesEntity getQueryTrackingProperties() throws ArangoDBException; - - /** - * Changes the configuration for the AQL query tracking - * - * @param properties properties to be set - * @return current set of properties - * @throws ArangoDBException - * @see API - * Documentation - */ - QueryTrackingPropertiesEntity setQueryTrackingProperties(QueryTrackingPropertiesEntity properties) - throws ArangoDBException; - - /** - * Returns a list of currently running AQL queries - * - * @return a list of currently running AQL queries - * @throws ArangoDBException - * @see API - * Documentation - */ - Collection getCurrentlyRunningQueries() throws ArangoDBException; - - /** - * Returns a list of slow running AQL queries - * - * @return a list of slow running AQL queries - * @throws ArangoDBException - * @see API - * Documentation - */ - Collection getSlowQueries() throws ArangoDBException; - - /** - * Clears the list of slow AQL queries - * - * @throws ArangoDBException - * @see API - * Documentation - */ - void clearSlowQueries() throws ArangoDBException; - - /** - * Kills a running query. The query will be terminated at the next cancelation point. - * - * @param id The id of the query - * @throws ArangoDBException - * @see API - * Documentation - */ - void killQuery(String id) throws ArangoDBException; - - /** - * Create a new AQL user function - * - * @param name A valid AQL function name, e.g.: `"myfuncs::accounting::calculate_vat"` - * @param code A String evaluating to a JavaScript function - * @param options Additional options, can be null - * @throws ArangoDBException - * @see API - * Documentation - */ - void createAqlFunction(String name, String code, AqlFunctionCreateOptions options) throws ArangoDBException; - - /** - * Deletes the AQL user function with the given name from the database. - * - * @param name The name of the user function to delete - * @param options Additional options, can be null - * @return number of deleted functions (since ArangoDB 3.4.0) - * @throws ArangoDBException - * @see API - * Documentation - */ - Integer deleteAqlFunction(String name, AqlFunctionDeleteOptions options) throws ArangoDBException; - - /** - * Gets all reqistered AQL user functions - * - * @param options Additional options, can be null - * @return all reqistered AQL user functions - * @throws ArangoDBException - * @see API - * Documentation - */ - Collection getAqlFunctions(AqlFunctionGetOptions options) throws ArangoDBException; - - /** - * Returns a {@code ArangoGraph} instance for the given graph name. - * - * @param name Name of the graph - * @return graph handler - */ - ArangoGraph graph(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 - * @throws ArangoDBException - * @see API - * Documentation - */ - GraphEntity createGraph(String name, Collection edgeDefinitions) throws ArangoDBException; - - /** - * 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 - * @throws ArangoDBException - * @see API - * Documentation - */ - GraphEntity createGraph(String name, Collection edgeDefinitions, GraphCreateOptions options) - throws ArangoDBException; - - /** - * Lists all graphs known to the graph module - * - * @return graphs stored in this database - * @throws ArangoDBException - * @see API - * Documentation - */ - Collection getGraphs() throws ArangoDBException; - - /** - * Performs a server-side transaction and returns its return value. - * - * @param action A String evaluating to a JavaScript function to be executed on the server. - * @param type The type of the result (POJO class, VPackSlice or String for JSON) - * @param options Additional options, can be null - * @return the result of the transaction if it succeeded - * @throws ArangoDBException - * @see API - * Documentation - */ - T transaction(String action, Class type, TransactionOptions options) throws ArangoDBException; - - /** - * Begins a Stream Transaction. - * - * @param options Additional options, can be null - * @return information about the transaction - * @throws ArangoDBException - * @see API - * Documentation - * @since ArangoDB 3.5.0 - */ - StreamTransactionEntity beginStreamTransaction(StreamTransactionOptions options) throws ArangoDBException; - - /** - * Aborts a Stream Transaction. - * - * @return information about the transaction - * @throws ArangoDBException - * @see API - * Documentation - */ - StreamTransactionEntity abortStreamTransaction(String id) throws ArangoDBException; - - /** - * Gets information about a Stream Transaction. - * - * @return information about the transaction - * @throws ArangoDBException - * @see - * API Documentation - * @since ArangoDB 3.5.0 - */ - StreamTransactionEntity getStreamTransaction(String id) throws ArangoDBException; - - /** - * Gets all the currently running Stream Transactions. - * - * @return all the currently running Stream Transactions - * @throws ArangoDBException - * @see - * API Documentation - * @since ArangoDB 3.5.0 - */ - Collection getStreamTransactions() throws ArangoDBException; - - /** - * Commits a Stream Transaction. - * - * @return information about the transaction - * @throws ArangoDBException - * @see - * API Documentation - * @since ArangoDB 3.5.0 - */ - StreamTransactionEntity commitStreamTransaction(String id) throws ArangoDBException; - - /** - * Retrieves information about the current database - * - * @return information about the current database - * @throws ArangoDBException - * @see API - * Documentation - */ - DatabaseEntity getInfo() throws ArangoDBException; - - /** - * Execute a server-side traversal - * - * @param vertexClass The type of the vertex documents (POJO class, VPackSlice or String for JSON) - * @param edgeClass The type of the edge documents (POJO class, VPackSlice or String for JSON) - * @param options Additional options - * @return Result of the executed traversal - * @throws ArangoDBException - * @see API - * Documentation - */ - TraversalEntity executeTraversal(Class vertexClass, Class edgeClass, TraversalOptions options) - throws ArangoDBException; - - /** - * Reads a single document - * - * @param id The id of the document - * @param type The type of the document (POJO class, VPackSlice or String for JSON) - * @return the document identified by the id - * @throws ArangoDBException - * @see API - * Documentation - */ - T getDocument(String id, Class type) throws ArangoDBException; - - /** - * Reads a single document - * - * @param id The id of the document - * @param type The type of the document (POJO class, VPackSlice or String for JSON) - * @param options Additional options, can be null - * @return the document identified by the id - * @throws ArangoDBException - * @see API - * Documentation - */ - T getDocument(String id, Class type, DocumentReadOptions options) throws ArangoDBException; - - /** - * Reload the routing table. - * - * @throws ArangoDBException - * @see API - * Documentation - */ - void reloadRouting() throws ArangoDBException; - - /** - * Returns a new {@link ArangoRoute} 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 ArangoRoute} - */ - ArangoRoute route(String... path); - - /** - * Fetches all views from the database and returns an list of view descriptions. - * - * @return list of information about all views - * @throws ArangoDBException - * @see API Documentation - * @since ArangoDB 3.4.0 - */ - Collection getViews() throws ArangoDBException; - - /** - * Returns a {@code ArangoView} instance for the given view name. - * - * @param name Name of the view - * @return view handler - * @since ArangoDB 3.4.0 - */ - ArangoView view(String name); - - /** - * Returns a {@code ArangoSearch} instance for the given ArangoSearch view name. - * - * @param name Name of the view - * @return ArangoSearch view handler - * @since ArangoDB 3.4.0 - */ - ArangoSearch arangoSearch(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 - * @throws ArangoDBException - * @since ArangoDB 3.4.0 - */ - ViewEntity createView(String name, ViewType type) throws ArangoDBException; - - /** - * 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 - * @throws ArangoDBException - * @see API - * Documentation - * @since ArangoDB 3.4.0 - */ - ViewEntity createArangoSearch(String name, ArangoSearchCreateOptions options) throws ArangoDBException; - - /** - * Creates an Analyzer - * - * @param options AnalyzerEntity - * @return the created Analyzer - * @throws ArangoDBException - * @see API Documentation - * @since ArangoDB 3.5.0 - */ - AnalyzerEntity createAnalyzer(AnalyzerEntity options) throws ArangoDBException; - - /** - * Gets information about an Analyzer - * - * @param name of the Analyzer without database prefix - * @return information about an Analyzer - * @throws ArangoDBException - * @see API Documentation - * @since ArangoDB 3.5.0 - */ - AnalyzerEntity getAnalyzer(String name) throws ArangoDBException; - - /** - * Retrieves all analyzers definitions. - * - * @return collection of all analyzers definitions - * @throws ArangoDBException - * @see API Documentation - * @since ArangoDB 3.5.0 - */ - Collection getAnalyzers() throws ArangoDBException; - - /** - * Deletes an Analyzer - * - * @param name of the Analyzer without database prefix - * @throws ArangoDBException - * @see API Documentation - * @since ArangoDB 3.5.0 - */ - void deleteAnalyzer(String name) throws ArangoDBException; - - /** - * Deletes an Analyzer - * - * @param name of the Analyzer without database prefix - * @param options AnalyzerDeleteOptions - * @throws ArangoDBException - * @see API Documentation - * @since ArangoDB 3.5.0 - */ - void deleteAnalyzer(String name, AnalyzerDeleteOptions options) throws ArangoDBException; + /** + * Return the main entry point for the ArangoDB driver + * + * @return main entry point + */ + ArangoDB arango(); + + /** + * Returns the name of the database + * + * @return database name + */ + String name(); + + /** + * Returns the server name and version number. + * + * @return the server version, number + * @throws ArangoDBException + * @see API + * Documentation + */ + ArangoDBVersion getVersion() throws ArangoDBException; + + /** + * Returns the name of the used storage engine. + * + * @return the storage engine name + * @throws ArangoDBException + * @see API + * Documentation + */ + ArangoDBEngine getEngine() throws ArangoDBException; + + /** + * Checks whether the database exists + * + * @return true if the database exists, otherwise false + */ + boolean exists() throws ArangoDBException; + + /** + * Retrieves a list of all databases the current user can access + * + * @return a list of all databases the current user can access + * @throws ArangoDBException + * @see API + * Documentation + */ + Collection getAccessibleDatabases() throws ArangoDBException; + + /** + * Returns a {@code ArangoCollection} instance for the given collection name. + * + * @param name Name of the collection + * @return collection handler + */ + ArangoCollection collection(String name); + + /** + * Creates a collection for the given collection's name, then returns collection information from the server. + * + * @param name The name of the collection + * @return information about the collection + * @throws ArangoDBException + * @see API + * Documentation + */ + CollectionEntity createCollection(String name) throws ArangoDBException; + + /** + * Creates a collection with the given {@code options} for this collection's name, then returns collection + * information from the server. + * + * @param name The name of the collection + * @param options Additional options, can be null + * @return information about the collection + * @throws ArangoDBException + * @see API + * Documentation + */ + CollectionEntity createCollection(String name, CollectionCreateOptions options) throws ArangoDBException; + + /** + * Fetches all collections from the database and returns an list of collection descriptions. + * + * @return list of information about all collections + * @throws ArangoDBException + * @see API + * Documentation + */ + Collection getCollections() throws ArangoDBException; + + /** + * Fetches all collections from the database and returns an list of collection descriptions. + * + * @param options Additional options, can be null + * @return list of information about all collections + * @throws ArangoDBException + * @see API + * Documentation + */ + Collection getCollections(CollectionsReadOptions options) throws ArangoDBException; + + /** + * Returns an index + * + * @param id The index-handle + * @return information about the index + * @throws ArangoDBException + * @see API Documentation + */ + IndexEntity getIndex(String id) throws ArangoDBException; + + /** + * Deletes an index + * + * @param id The index-handle + * @return the id of the index + * @throws ArangoDBException + * @see API Documentation + */ + String deleteIndex(String id) throws ArangoDBException; + + /** + * Creates the database + * + * @return true if the database was created successfully. + * @throws ArangoDBException + * @see API + * Documentation + */ + Boolean create() throws ArangoDBException; + + /** + * Deletes the database from the server. + * + * @return true if the database was dropped successfully + * @throws ArangoDBException + * @see API + * Documentation + */ + Boolean drop() throws ArangoDBException; + + /** + * Grants or revoke access to the database for user {@code 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 + * @throws ArangoDBException + * @see + * API Documentation + */ + void grantAccess(String user, Permissions permissions) throws ArangoDBException; + + /** + * Grants access to the database for user {@code user}. You need permission to the _system database in order to + * execute this call. + * + * @param user The name of the user + * @throws ArangoDBException + * @see + * API Documentation + */ + void grantAccess(String user) throws ArangoDBException; + + /** + * Revokes access to the database dbname for user {@code user}. You need permission to the _system database in order + * to execute this call. + * + * @param user The name of the user + * @throws ArangoDBException + * @see + * API Documentation + */ + void revokeAccess(String user) throws ArangoDBException; + + /** + * Clear the database access level, revert back to the default access level. + * + * @param user The name of the user + * @throws ArangoDBException + * @see + * API Documentation + * @since ArangoDB 3.2.0 + */ + void resetAccess(String user) throws ArangoDBException; + + /** + * Sets the default access level for collections within this database for the user {@code 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 + * @throws ArangoDBException + * @since ArangoDB 3.2.0 + */ + void grantDefaultCollectionAccess(String user, Permissions permissions) throws ArangoDBException; + + /** + * Get specific database access level + * + * @param user The name of the user + * @return permissions of the user + * @throws ArangoDBException + * @see API + * Documentation + * @since ArangoDB 3.2.0 + */ + Permissions getPermissions(String user) throws ArangoDBException; + + /** + * 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 An AQL query string + * @param bindVars key/value pairs defining the variables to bind the query to + * @param options Additional options that will be passed to the query API, can be null + * @param type The type of the result (POJO class, VPackSlice, String for JSON, or Collection/List/Map) + * @return cursor of the results + * @throws ArangoDBException + * @see API + * Documentation + */ + ArangoCursor query(String query, Map bindVars, AqlQueryOptions options, Class type) + throws ArangoDBException; + + /** + * Performs a database query using the given {@code query}, then returns a new {@code ArangoCursor} instance for the + * result list. + * + * @param query An AQL query string + * @param options Additional options that will be passed to the query API, can be null + * @param type The type of the result (POJO class, VPackSlice, String for JSON, or Collection/List/Map) + * @return cursor of the results + * @throws ArangoDBException + * @see API + * Documentation + */ + ArangoCursor query(String query, AqlQueryOptions options, Class type) throws ArangoDBException; + + /** + * 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 An AQL query string + * @param bindVars key/value pairs defining the variables to bind the query to + * @param type The type of the result (POJO class, VPackSlice, String for JSON, or Collection/List/Map) + * @return cursor of the results + * @throws ArangoDBException + * @see API + * Documentation + */ + ArangoCursor query(String query, Map bindVars, Class type) throws ArangoDBException; + + /** + * Performs a database query using the given {@code query}, then returns a new {@code ArangoCursor} instance for the + * result list. + * + * @param query An AQL query string + * @param type The type of the result (POJO class, VPackSlice, String for JSON, or Collection/List/Map) + * @return cursor of the results + * @throws ArangoDBException + * @see API + * Documentation + */ + ArangoCursor query(String query, Class type) throws ArangoDBException; + + /** + * 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 class, VPackSlice, String for JSON, or Collection/List/Map) + * @return cursor of the results + * @throws ArangoDBException + * @see API + * Documentation + */ + ArangoCursor cursor(String cursorId, Class type) throws ArangoDBException; + + /** + * 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 + * @throws ArangoDBException + * @see API + * Documentation + */ + AqlExecutionExplainEntity explainQuery(String query, Map bindVars, AqlQueryExplainOptions options) + throws ArangoDBException; + + /** + * Parse an AQL query and return information about it This method is for query validation only. To actually query + * the database, see {@link ArangoDatabase#query(String, Map, AqlQueryOptions, Class)} + * + * @param query the query which you want parse + * @return imformation about the query + * @throws ArangoDBException + * @see API + * Documentation + */ + AqlParseEntity parseQuery(String query) throws ArangoDBException; + + /** + * Clears the AQL query cache + * + * @throws ArangoDBException + * @see API + * Documentation + */ + void clearQueryCache() throws ArangoDBException; + + /** + * Returns the global configuration for the AQL query cache + * + * @return configuration for the AQL query cache + * @throws ArangoDBException + * @see API + * Documentation + */ + QueryCachePropertiesEntity getQueryCacheProperties() throws ArangoDBException; + + /** + * 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 + * @throws ArangoDBException + * @see API + * Documentation + */ + QueryCachePropertiesEntity setQueryCacheProperties(QueryCachePropertiesEntity properties) throws ArangoDBException; + + /** + * Returns the configuration for the AQL query tracking + * + * @return configuration for the AQL query tracking + * @throws ArangoDBException + * @see API + * Documentation + */ + QueryTrackingPropertiesEntity getQueryTrackingProperties() throws ArangoDBException; + + /** + * Changes the configuration for the AQL query tracking + * + * @param properties properties to be set + * @return current set of properties + * @throws ArangoDBException + * @see API + * Documentation + */ + QueryTrackingPropertiesEntity setQueryTrackingProperties(QueryTrackingPropertiesEntity properties) + throws ArangoDBException; + + /** + * Returns a list of currently running AQL queries + * + * @return a list of currently running AQL queries + * @throws ArangoDBException + * @see API + * Documentation + */ + Collection getCurrentlyRunningQueries() throws ArangoDBException; + + /** + * Returns a list of slow running AQL queries + * + * @return a list of slow running AQL queries + * @throws ArangoDBException + * @see API + * Documentation + */ + Collection getSlowQueries() throws ArangoDBException; + + /** + * Clears the list of slow AQL queries + * + * @throws ArangoDBException + * @see API + * Documentation + */ + void clearSlowQueries() throws ArangoDBException; + + /** + * Kills a running query. The query will be terminated at the next cancelation point. + * + * @param id The id of the query + * @throws ArangoDBException + * @see API + * Documentation + */ + void killQuery(String id) throws ArangoDBException; + + /** + * Create a new AQL user function + * + * @param name A valid AQL function name, e.g.: `"myfuncs::accounting::calculate_vat"` + * @param code A String evaluating to a JavaScript function + * @param options Additional options, can be null + * @throws ArangoDBException + * @see API + * Documentation + */ + void createAqlFunction(String name, String code, AqlFunctionCreateOptions options) throws ArangoDBException; + + /** + * Deletes the AQL user function with the given name from the database. + * + * @param name The name of the user function to delete + * @param options Additional options, can be null + * @return number of deleted functions (since ArangoDB 3.4.0) + * @throws ArangoDBException + * @see API + * Documentation + */ + Integer deleteAqlFunction(String name, AqlFunctionDeleteOptions options) throws ArangoDBException; + + /** + * Gets all reqistered AQL user functions + * + * @param options Additional options, can be null + * @return all reqistered AQL user functions + * @throws ArangoDBException + * @see API + * Documentation + */ + Collection getAqlFunctions(AqlFunctionGetOptions options) throws ArangoDBException; + + /** + * Returns a {@code ArangoGraph} instance for the given graph name. + * + * @param name Name of the graph + * @return graph handler + */ + ArangoGraph graph(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 + * @throws ArangoDBException + * @see API + * Documentation + */ + GraphEntity createGraph(String name, Collection edgeDefinitions) throws ArangoDBException; + + /** + * 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 + * @throws ArangoDBException + * @see API + * Documentation + */ + GraphEntity createGraph(String name, Collection edgeDefinitions, GraphCreateOptions options) + throws ArangoDBException; + + /** + * Lists all graphs known to the graph module + * + * @return graphs stored in this database + * @throws ArangoDBException + * @see API + * Documentation + */ + Collection getGraphs() throws ArangoDBException; + + /** + * Performs a server-side transaction and returns its return value. + * + * @param action A String evaluating to a JavaScript function to be executed on the server. + * @param type The type of the result (POJO class, VPackSlice or String for JSON) + * @param options Additional options, can be null + * @return the result of the transaction if it succeeded + * @throws ArangoDBException + * @see API + * Documentation + */ + T transaction(String action, Class type, TransactionOptions options) throws ArangoDBException; + + /** + * Begins a Stream Transaction. + * + * @param options Additional options, can be null + * @return information about the transaction + * @throws ArangoDBException + * @see API + * Documentation + * @since ArangoDB 3.5.0 + */ + StreamTransactionEntity beginStreamTransaction(StreamTransactionOptions options) throws ArangoDBException; + + /** + * Aborts a Stream Transaction. + * + * @return information about the transaction + * @throws ArangoDBException + * @see API + * Documentation + */ + StreamTransactionEntity abortStreamTransaction(String id) throws ArangoDBException; + + /** + * Gets information about a Stream Transaction. + * + * @return information about the transaction + * @throws ArangoDBException + * @see + * API Documentation + * @since ArangoDB 3.5.0 + */ + StreamTransactionEntity getStreamTransaction(String id) throws ArangoDBException; + + /** + * Gets all the currently running Stream Transactions. + * + * @return all the currently running Stream Transactions + * @throws ArangoDBException + * @see + * API Documentation + * @since ArangoDB 3.5.0 + */ + Collection getStreamTransactions() throws ArangoDBException; + + /** + * Commits a Stream Transaction. + * + * @return information about the transaction + * @throws ArangoDBException + * @see + * API Documentation + * @since ArangoDB 3.5.0 + */ + StreamTransactionEntity commitStreamTransaction(String id) throws ArangoDBException; + + /** + * Retrieves information about the current database + * + * @return information about the current database + * @throws ArangoDBException + * @see API + * Documentation + */ + DatabaseEntity getInfo() throws ArangoDBException; + + /** + * Execute a server-side traversal + * + * @param vertexClass The type of the vertex documents (POJO class, VPackSlice or String for JSON) + * @param edgeClass The type of the edge documents (POJO class, VPackSlice or String for JSON) + * @param options Additional options + * @return Result of the executed traversal + * @throws ArangoDBException + * @see API + * Documentation + */ + TraversalEntity executeTraversal(Class vertexClass, Class edgeClass, TraversalOptions options) + throws ArangoDBException; + + /** + * Reads a single document + * + * @param id The id of the document + * @param type The type of the document (POJO class, VPackSlice or String for JSON) + * @return the document identified by the id + * @throws ArangoDBException + * @see API + * Documentation + */ + T getDocument(String id, Class type) throws ArangoDBException; + + /** + * Reads a single document + * + * @param id The id of the document + * @param type The type of the document (POJO class, VPackSlice or String for JSON) + * @param options Additional options, can be null + * @return the document identified by the id + * @throws ArangoDBException + * @see API + * Documentation + */ + T getDocument(String id, Class type, DocumentReadOptions options) throws ArangoDBException; + + /** + * Reload the routing table. + * + * @throws ArangoDBException + * @see API + * Documentation + */ + void reloadRouting() throws ArangoDBException; + + /** + * Returns a new {@link ArangoRoute} 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 ArangoRoute} + */ + ArangoRoute route(String... path); + + /** + * Fetches all views from the database and returns an list of view descriptions. + * + * @return list of information about all views + * @throws ArangoDBException + * @see API Documentation + * @since ArangoDB 3.4.0 + */ + Collection getViews() throws ArangoDBException; + + /** + * Returns a {@code ArangoView} instance for the given view name. + * + * @param name Name of the view + * @return view handler + * @since ArangoDB 3.4.0 + */ + ArangoView view(String name); + + /** + * Returns a {@code ArangoSearch} instance for the given ArangoSearch view name. + * + * @param name Name of the view + * @return ArangoSearch view handler + * @since ArangoDB 3.4.0 + */ + ArangoSearch arangoSearch(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 + * @throws ArangoDBException + * @since ArangoDB 3.4.0 + */ + ViewEntity createView(String name, ViewType type) throws ArangoDBException; + + /** + * 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 + * @throws ArangoDBException + * @see API + * Documentation + * @since ArangoDB 3.4.0 + */ + ViewEntity createArangoSearch(String name, ArangoSearchCreateOptions options) throws ArangoDBException; + + /** + * Creates an Analyzer + * + * @param options AnalyzerEntity + * @return the created Analyzer + * @throws ArangoDBException + * @see API Documentation + * @since ArangoDB 3.5.0 + */ + AnalyzerEntity createAnalyzer(AnalyzerEntity options) throws ArangoDBException; + + /** + * Gets information about an Analyzer + * + * @param name of the Analyzer without database prefix + * @return information about an Analyzer + * @throws ArangoDBException + * @see API Documentation + * @since ArangoDB 3.5.0 + */ + AnalyzerEntity getAnalyzer(String name) throws ArangoDBException; + + /** + * Retrieves all analyzers definitions. + * + * @return collection of all analyzers definitions + * @throws ArangoDBException + * @see API Documentation + * @since ArangoDB 3.5.0 + */ + Collection getAnalyzers() throws ArangoDBException; + + /** + * Deletes an Analyzer + * + * @param name of the Analyzer without database prefix + * @throws ArangoDBException + * @see API Documentation + * @since ArangoDB 3.5.0 + */ + void deleteAnalyzer(String name) throws ArangoDBException; + + /** + * Deletes an Analyzer + * + * @param name of the Analyzer without database prefix + * @param options AnalyzerDeleteOptions + * @throws ArangoDBException + * @see API Documentation + * @since ArangoDB 3.5.0 + */ + void deleteAnalyzer(String name, AnalyzerDeleteOptions options) throws ArangoDBException; } diff --git a/src/main/java/com/arangodb/ArangoEdgeCollection.java b/src/main/java/com/arangodb/ArangoEdgeCollection.java index 229161653..17d6d054b 100644 --- a/src/main/java/com/arangodb/ArangoEdgeCollection.java +++ b/src/main/java/com/arangodb/ArangoEdgeCollection.java @@ -26,161 +26,140 @@ /** * Interface for operations on ArangoDB edge collection level. - * - * @see API Documentation + * * @author Mark Vollmary + * @see API Documentation */ @SuppressWarnings("UnusedReturnValue") public interface ArangoEdgeCollection extends ArangoSerializationAccessor { - /** - * The the handler of the named graph the edge collection is within - * - * @return graph handler - */ - ArangoGraph graph(); - - /** - * The name of the edge collection - * - * @return collection name - */ - String name(); - - /** - * Creates a new edge in the collection - * - * @see API Documentation - * @param value - * A representation of a single edge (POJO, VPackSlice or String for JSON) - * @return information about the edge - * @throws ArangoDBException - */ - EdgeEntity insertEdge(T value) throws ArangoDBException; - - /** - * Creates a new edge in the collection - * - * @see API Documentation - * @param value - * A representation of a single edge (POJO, VPackSlice or String for JSON) - * @param options - * Additional options, can be null - * @return information about the edge - * @throws ArangoDBException - */ - EdgeEntity insertEdge(T value, EdgeCreateOptions options) throws ArangoDBException; - - /** - * Fetches an existing edge - * - * @see API Documentation - * @param key - * The key of the edge - * @param type - * The type of the edge-document (POJO class, VPackSlice or String for JSON) - * @return the edge identified by the key - * @throws ArangoDBException - */ - T getEdge(String key, Class type) throws ArangoDBException; - - /** - * Fetches an existing edge - * - * @see API Documentation - * @param key - * The key of the edge - * @param type - * The type of the edge-document (POJO class, VPackSlice or String for JSON) - * @param options - * Additional options, can be null - * @return the edge identified by the key - * @throws ArangoDBException - */ - T getEdge(String key, Class type, GraphDocumentReadOptions options) throws ArangoDBException; - - /** - * Replaces the edge with key with the one in the body, provided there is such a edge and no precondition is - * violated - * - * @see API Documentation - * @param key - * The key of the edge - * @param - * The type of the edge-document (POJO class, VPackSlice or String for JSON) - * @return information about the edge - * @throws ArangoDBException - */ - EdgeUpdateEntity replaceEdge(String key, T value) throws ArangoDBException; - - /** - * Replaces the edge with key with the one in the body, provided there is such a edge and no precondition is - * violated - * - * @see API Documentation - * @param key - * The key of the edge - * @param - * The type of the edge-document (POJO class, VPackSlice or String for JSON) - * @param options - * Additional options, can be null - * @return information about the edge - * @throws ArangoDBException - */ - EdgeUpdateEntity replaceEdge(String key, T value, EdgeReplaceOptions options) throws ArangoDBException; - - /** - * 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. - * - * @see API Documentation - * @param key - * The key of the edge - * @param - * The type of the edge-document (POJO class, VPackSlice or String for JSON) - * @return information about the edge - * @throws ArangoDBException - */ - EdgeUpdateEntity updateEdge(String key, T value) throws ArangoDBException; - - /** - * 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. - * - * @see API Documentation - * @param key - * The key of the edge - * @param - * The type of the edge-document (POJO class, VPackSlice or String for JSON) - * @param options - * Additional options, can be null - * @return information about the edge - * @throws ArangoDBException - */ - EdgeUpdateEntity updateEdge(String key, T value, EdgeUpdateOptions options) throws ArangoDBException; - - /** - * Removes a edge - * - * @see API Documentation - * @param key - * The key of the edge - * @throws ArangoDBException - */ - void deleteEdge(String key) throws ArangoDBException; - - /** - * Removes a edge - * - * @see API Documentation - * @param key - * The key of the edge - * @param options - * Additional options, can be null - * @throws ArangoDBException - */ - void deleteEdge(String key, EdgeDeleteOptions options) throws ArangoDBException; + /** + * The the handler of the named graph the edge collection is within + * + * @return graph handler + */ + ArangoGraph graph(); + + /** + * The name of the edge collection + * + * @return collection name + */ + String name(); + + /** + * Creates a new edge in the collection + * + * @param value A representation of a single edge (POJO, VPackSlice or String for JSON) + * @return information about the edge + * @throws ArangoDBException + * @see API Documentation + */ + EdgeEntity insertEdge(T value) throws ArangoDBException; + + /** + * Creates a new edge in the collection + * + * @param value A representation of a single edge (POJO, VPackSlice or String for JSON) + * @param options Additional options, can be null + * @return information about the edge + * @throws ArangoDBException + * @see API Documentation + */ + EdgeEntity insertEdge(T value, EdgeCreateOptions options) throws ArangoDBException; + + /** + * Fetches an existing edge + * + * @param key The key of the edge + * @param type The type of the edge-document (POJO class, VPackSlice or String for JSON) + * @return the edge identified by the key + * @throws ArangoDBException + * @see API Documentation + */ + T getEdge(String key, Class type) throws ArangoDBException; + + /** + * Fetches an existing edge + * + * @param key The key of the edge + * @param type The type of the edge-document (POJO class, VPackSlice or String for JSON) + * @param options Additional options, can be null + * @return the edge identified by the key + * @throws ArangoDBException + * @see API Documentation + */ + T getEdge(String key, Class type, GraphDocumentReadOptions options) throws ArangoDBException; + + /** + * 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 The type of the edge-document (POJO class, VPackSlice or String for JSON) + * @return information about the edge + * @throws ArangoDBException + * @see API Documentation + */ + EdgeUpdateEntity replaceEdge(String key, T value) throws ArangoDBException; + + /** + * 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 The type of the edge-document (POJO class, VPackSlice or String for JSON) + * @param options Additional options, can be null + * @return information about the edge + * @throws ArangoDBException + * @see API Documentation + */ + EdgeUpdateEntity replaceEdge(String key, T value, EdgeReplaceOptions options) throws ArangoDBException; + + /** + * 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 The type of the edge-document (POJO class, VPackSlice or String for JSON) + * @return information about the edge + * @throws ArangoDBException + * @see API Documentation + */ + EdgeUpdateEntity updateEdge(String key, T value) throws ArangoDBException; + + /** + * 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 The type of the edge-document (POJO class, VPackSlice or String for JSON) + * @param options Additional options, can be null + * @return information about the edge + * @throws ArangoDBException + * @see API Documentation + */ + EdgeUpdateEntity updateEdge(String key, T value, EdgeUpdateOptions options) throws ArangoDBException; + + /** + * Removes a edge + * + * @param key The key of the edge + * @throws ArangoDBException + * @see API Documentation + */ + void deleteEdge(String key) throws ArangoDBException; + + /** + * Removes a edge + * + * @param key The key of the edge + * @param options Additional options, can be null + * @throws ArangoDBException + * @see API Documentation + */ + void deleteEdge(String key, EdgeDeleteOptions options) throws ArangoDBException; } diff --git a/src/main/java/com/arangodb/ArangoGraph.java b/src/main/java/com/arangodb/ArangoGraph.java index bd748a8a7..7a9a8d63c 100644 --- a/src/main/java/com/arangodb/ArangoGraph.java +++ b/src/main/java/com/arangodb/ArangoGraph.java @@ -20,187 +20,177 @@ package com.arangodb; -import java.util.Collection; - import com.arangodb.entity.EdgeDefinition; import com.arangodb.entity.GraphEntity; import com.arangodb.model.GraphCreateOptions; +import java.util.Collection; + /** * Interface for operations on ArangoDB graph level. * - * @see API Documentation * @author Mark Vollmary + * @see API Documentation */ public interface ArangoGraph extends ArangoSerializationAccessor { - /** - * The the handler of the database the named graph is within - * - * @return database handler - */ - ArangoDatabase db(); - - /** - * The name of the collection - * - * @return collection name - */ - String name(); - - /** - * Checks whether the graph exists - * - * @return true if the graph exists, otherwise false - */ - boolean exists() throws ArangoDBException; - - /** - * Creates the graph in the graph module. The creation of a graph requires the name of the graph and a definition of - * its edges. - * - * @see API - * Documentation - * @param edgeDefinitions - * An array of definitions for the edge - * @return information about the graph - * @throws ArangoDBException - */ - GraphEntity create(Collection edgeDefinitions) throws ArangoDBException; - - /** - * Creates the graph in the graph module. The creation of a graph requires the name of the graph and a definition of - * its edges. - * - * @see API - * Documentation - * @param edgeDefinitions - * An array of definitions for the edge - * @param options - * Additional options, can be null - * @return information about the graph - * @throws ArangoDBException - */ - GraphEntity create(Collection edgeDefinitions, GraphCreateOptions options) throws ArangoDBException; - - /** - * Deletes the graph from the database. - * - * @see API Documentation - * @throws ArangoDBException - */ - void drop() throws ArangoDBException; - - /** - * Deletes the graph from the database. - * - * @see API - * Documentation - * @param dropCollections - * Drop collections of this graph as well. Collections will only be - * dropped if they are not used in other graphs. - * @throws ArangoDBException - */ - void drop(boolean dropCollections) throws ArangoDBException; - - /** - * Retrieves general information about the graph. - * - * @see API Documentation - * @return the definition content of this graph - * @throws ArangoDBException - */ - GraphEntity getInfo() throws ArangoDBException; - - /** - * Fetches all vertex collections from the graph and returns a list of collection names. - * - * @see API - * Documentation - * @return all vertex collections within this graph - * @throws ArangoDBException - */ - Collection getVertexCollections() throws ArangoDBException; - - /** - * Adds a vertex collection to the set of collections of the graph. If the collection does not exist, it will be - * created. - * - * @see API - * Documentation - * @param name - * Name of the vertex collection - * @return information about the graph - * @throws ArangoDBException - */ - GraphEntity addVertexCollection(String name) throws ArangoDBException; - - /** - * Returns a {@code ArangoVertexCollection} instance for the given vertex collection name. - * - * @param name - * Name of the vertex collection - * @return collection handler - */ - ArangoVertexCollection vertexCollection(String name); - - /** - * Returns a {@code ArangoEdgeCollection} instance for the given edge collection name. - * - * @param name - * Name of the edge collection - * @return collection handler - */ - ArangoEdgeCollection edgeCollection(String name); - - /** - * Fetches all edge collections from the graph and returns a list of collection names. - * - * @see API - * Documentation - * @return all edge collections within this graph - * @throws ArangoDBException - */ - Collection getEdgeDefinitions() throws ArangoDBException; - - /** - * Adds the given edge definition to the graph. - * - * @see API - * Documentation - * @param definition - * The edge definition - * @return information about the graph - * @throws ArangoDBException - */ - GraphEntity addEdgeDefinition(EdgeDefinition definition) throws ArangoDBException; - - /** - * Change one specific edge definition. This will modify all occurrences of this definition in all graphs known to - * your database - * - * @see API - * Documentation - * @param definition - * The edge definition - * @return information about the graph - * @throws ArangoDBException - */ - GraphEntity replaceEdgeDefinition(EdgeDefinition definition) throws ArangoDBException; - - /** - * Remove one edge definition from the graph. This will only remove the edge collection, the vertex collections - * remain untouched and can still be used in your queries - * - * @see API - * Documentation - * @param definitionName - * The name of the edge collection used in the definition - * @return information about the graph - * @throws ArangoDBException - */ - GraphEntity removeEdgeDefinition(String definitionName) throws ArangoDBException; + /** + * The the handler of the database the named graph is within + * + * @return database handler + */ + ArangoDatabase db(); + + /** + * The name of the collection + * + * @return collection name + */ + String name(); + + /** + * Checks whether the graph exists + * + * @return true if the graph exists, otherwise false + */ + boolean exists() throws ArangoDBException; + + /** + * 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 + * @throws ArangoDBException + * @see API + * Documentation + */ + GraphEntity create(Collection edgeDefinitions) throws ArangoDBException; + + /** + * 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 + * @throws ArangoDBException + * @see API + * Documentation + */ + GraphEntity create(Collection edgeDefinitions, GraphCreateOptions options) throws ArangoDBException; + + /** + * Deletes the graph from the database. + * + * @throws ArangoDBException + * @see API Documentation + */ + void drop() throws ArangoDBException; + + /** + * Deletes the graph from the database. + * + * @param dropCollections Drop collections of this graph as well. Collections will only be + * dropped if they are not used in other graphs. + * @throws ArangoDBException + * @see API + * Documentation + */ + void drop(boolean dropCollections) throws ArangoDBException; + + /** + * Retrieves general information about the graph. + * + * @return the definition content of this graph + * @throws ArangoDBException + * @see API Documentation + */ + GraphEntity getInfo() throws ArangoDBException; + + /** + * Fetches all vertex collections from the graph and returns a list of collection names. + * + * @return all vertex collections within this graph + * @throws ArangoDBException + * @see API + * Documentation + */ + Collection getVertexCollections() throws ArangoDBException; + + /** + * Adds a vertex collection to the set of collections of the graph. If the collection does not exist, it will be + * created. + * + * @param name Name of the vertex collection + * @return information about the graph + * @throws ArangoDBException + * @see API + * Documentation + */ + GraphEntity addVertexCollection(String name) throws ArangoDBException; + + /** + * Returns a {@code ArangoVertexCollection} instance for the given vertex collection name. + * + * @param name Name of the vertex collection + * @return collection handler + */ + ArangoVertexCollection vertexCollection(String name); + + /** + * Returns a {@code ArangoEdgeCollection} instance for the given edge collection name. + * + * @param name Name of the edge collection + * @return collection handler + */ + ArangoEdgeCollection edgeCollection(String name); + + /** + * Fetches all edge collections from the graph and returns a list of collection names. + * + * @return all edge collections within this graph + * @throws ArangoDBException + * @see API + * Documentation + */ + Collection getEdgeDefinitions() throws ArangoDBException; + + /** + * Adds the given edge definition to the graph. + * + * @param definition The edge definition + * @return information about the graph + * @throws ArangoDBException + * @see API + * Documentation + */ + GraphEntity addEdgeDefinition(EdgeDefinition definition) throws ArangoDBException; + + /** + * 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 + * @throws ArangoDBException + * @see API + * Documentation + */ + GraphEntity replaceEdgeDefinition(EdgeDefinition definition) throws ArangoDBException; + + /** + * Remove one edge definition from the graph. This will only remove the edge collection, the vertex collections + * remain untouched and can still be used in your queries + * + * @param definitionName The name of the edge collection used in the definition + * @return information about the graph + * @throws ArangoDBException + * @see API + * Documentation + */ + GraphEntity removeEdgeDefinition(String definitionName) throws ArangoDBException; } diff --git a/src/main/java/com/arangodb/ArangoIterable.java b/src/main/java/com/arangodb/ArangoIterable.java index f2272ac5c..0323fa7a5 100644 --- a/src/main/java/com/arangodb/ArangoIterable.java +++ b/src/main/java/com/arangodb/ArangoIterable.java @@ -24,92 +24,84 @@ /** * @author Mark Vollmary - * */ public interface ArangoIterable extends Iterable { - @Override - ArangoIterator iterator(); + @Override + ArangoIterator iterator(); - /** - * Performs the given action for each element of the {@code ArangoIterable} - * - * @param action - * a action to perform on the elements - */ - void foreach(Consumer action); + /** + * Performs the given action for each element of the {@code ArangoIterable} + * + * @param action a action to perform on the elements + */ + void foreach(Consumer action); - /** - * Returns a {@code ArangoIterable} consisting of the results of applying the given function to the elements of this - * {@code ArangoIterable}. - * - * @param mapper - * a function to apply to each element - * @return the new {@code ArangoIterable} - */ - ArangoIterable map(Function mapper); + /** + * Returns a {@code ArangoIterable} consisting of the results of applying the given function to the elements of this + * {@code ArangoIterable}. + * + * @param mapper a function to apply to each element + * @return the new {@code ArangoIterable} + */ + ArangoIterable map(Function mapper); - /** - * Returns a {@code ArangoIterable} consisting of the elements of this {@code ArangoIterable} that match the given - * predicate. - * - * @param predicate - * a predicate to apply to each element to determine if it should be included - * @return the new {@code ArangoIterable} - */ - ArangoIterable filter(Predicate predicate); + /** + * Returns a {@code ArangoIterable} consisting of the elements of this {@code ArangoIterable} that match the given + * predicate. + * + * @param predicate a predicate to apply to each element to determine if it should be included + * @return the new {@code ArangoIterable} + */ + ArangoIterable filter(Predicate predicate); - /** - * Returns the first element or {@code null} if no element exists. - * - * @return first element or {@code null} - */ - T first(); + /** + * Returns the first element or {@code null} if no element exists. + * + * @return first element or {@code null} + */ + T first(); - /** - * Returns the count of elements of this {@code ArangoIterable}. - * - * @return the count of elements - */ - long count(); + /** + * Returns the count of elements of this {@code ArangoIterable}. + * + * @return the count of elements + */ + long count(); - /** - * Returns whether any elements of this {@code ArangoIterable} match the provided predicate. - * - * @param predicate - * a predicate to apply to elements of this {@code ArangoIterable} - * @return {@code true} if any elements of the {@code ArangoIterable} match the provided predicate, otherwise - * {@code false} - */ - boolean anyMatch(Predicate predicate); + /** + * Returns whether any elements of this {@code ArangoIterable} match the provided predicate. + * + * @param predicate a predicate to apply to elements of this {@code ArangoIterable} + * @return {@code true} if any elements of the {@code ArangoIterable} match the provided predicate, otherwise + * {@code false} + */ + boolean anyMatch(Predicate predicate); - /** - * Returns whether all elements of this {@code ArangoIterable} match the provided predicate. - * - * @param predicate - * a predicate to apply to elements of this {@code ArangoIterable} - * @return {@code true} if all elements of the {@code ArangoIterable} match the provided predicate, otherwise - * {@code false} - */ - boolean allMatch(Predicate predicate); + /** + * Returns whether all elements of this {@code ArangoIterable} match the provided predicate. + * + * @param predicate a predicate to apply to elements of this {@code ArangoIterable} + * @return {@code true} if all elements of the {@code ArangoIterable} match the provided predicate, otherwise + * {@code false} + */ + boolean allMatch(Predicate predicate); - /** - * Returns whether no elements of this {@code ArangoIterable} match the provided predicate. - * - * @param predicate - * a predicate to apply to elements of this {@code ArangoIterable} - * @return {@code true} if no elements of the {@code ArangoIterable} match the provided predicate, otherwise - * {@code false} - */ - boolean noneMatch(Predicate predicate); + /** + * Returns whether no elements of this {@code ArangoIterable} match the provided predicate. + * + * @param predicate a predicate to apply to elements of this {@code ArangoIterable} + * @return {@code true} if no elements of the {@code ArangoIterable} match the provided predicate, otherwise + * {@code false} + */ + boolean noneMatch(Predicate predicate); - /** - * Iterates over all elements of this {@code ArangoIterable} and adds each to the given target. - * - * @param target - * the collection to insert into - * @return the filled target - */ - > R collectInto(R target); + /** + * Iterates over all elements of this {@code ArangoIterable} and adds each to the given target. + * + * @param target the collection to insert into + * @return the filled target + */ + > R collectInto(R target); } diff --git a/src/main/java/com/arangodb/ArangoIterator.java b/src/main/java/com/arangodb/ArangoIterator.java index 6456bf4fc..26fd8ae46 100644 --- a/src/main/java/com/arangodb/ArangoIterator.java +++ b/src/main/java/com/arangodb/ArangoIterator.java @@ -24,7 +24,6 @@ /** * @author Mark Vollmary - * */ public interface ArangoIterator extends Iterator { diff --git a/src/main/java/com/arangodb/ArangoRoute.java b/src/main/java/com/arangodb/ArangoRoute.java index b5f18552d..71a470fdf 100644 --- a/src/main/java/com/arangodb/ArangoRoute.java +++ b/src/main/java/com/arangodb/ArangoRoute.java @@ -25,103 +25,97 @@ /** * Interface for a specific path to be used to perform arbitrary requests. - * + * * @author Mark Vollmary */ public interface ArangoRoute extends ArangoSerializationAccessor { - /** - * Returns a new {@link ArangoRoute} 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 ArangoRoute} - */ - ArangoRoute route(String... path); - - /** - * Header that should be sent with each request to the route. - * - * @param key - * Header key - * @param value - * Header value (the {@code toString()} method will be called for the value} - * @return {@link ArangoRoute} - */ - ArangoRoute 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 {@code toString()} method will be called for the value} - * @return {@link ArangoRoute} - */ - ArangoRoute withQueryParam(String key, Object value); - - /** - * The response body. The body will be serialized to {@link VPackSlice}. - * - * @param body - * The request body - * @return {@link ArangoRoute} - */ - ArangoRoute withBody(Object body); - - /** - * Performs a DELETE request to the given URL and returns the server response. - * - * @return server response - * @throws ArangoDBException - */ - Response delete() throws ArangoDBException; - - /** - * Performs a GET request to the given URL and returns the server response. - * - * @return server response - * @throws ArangoDBException - */ - - Response get() throws ArangoDBException; - - /** - * Performs a HEAD request to the given URL and returns the server response. - * - * @return server response - * @throws ArangoDBException - */ - - Response head() throws ArangoDBException; - - /** - * Performs a PATCH request to the given URL and returns the server response. - * - * @return server response - * @throws ArangoDBException - */ - - Response patch() throws ArangoDBException; - - /** - * Performs a POST request to the given URL and returns the server response. - * - * @return server response - * @throws ArangoDBException - */ - - Response post() throws ArangoDBException; - - /** - * Performs a PUT request to the given URL and returns the server response. - * - * @return server response - * @throws ArangoDBException - */ - - Response put() throws ArangoDBException; + /** + * Returns a new {@link ArangoRoute} 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 ArangoRoute} + */ + ArangoRoute route(String... path); + + /** + * Header that should be sent with each request to the route. + * + * @param key Header key + * @param value Header value (the {@code toString()} method will be called for the value} + * @return {@link ArangoRoute} + */ + ArangoRoute 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 {@code toString()} method will be called for the value} + * @return {@link ArangoRoute} + */ + ArangoRoute withQueryParam(String key, Object value); + + /** + * The response body. The body will be serialized to {@link VPackSlice}. + * + * @param body The request body + * @return {@link ArangoRoute} + */ + ArangoRoute withBody(Object body); + + /** + * Performs a DELETE request to the given URL and returns the server response. + * + * @return server response + * @throws ArangoDBException + */ + Response delete() throws ArangoDBException; + + /** + * Performs a GET request to the given URL and returns the server response. + * + * @return server response + * @throws ArangoDBException + */ + + Response get() throws ArangoDBException; + + /** + * Performs a HEAD request to the given URL and returns the server response. + * + * @return server response + * @throws ArangoDBException + */ + + Response head() throws ArangoDBException; + + /** + * Performs a PATCH request to the given URL and returns the server response. + * + * @return server response + * @throws ArangoDBException + */ + + Response patch() throws ArangoDBException; + + /** + * Performs a POST request to the given URL and returns the server response. + * + * @return server response + * @throws ArangoDBException + */ + + Response post() throws ArangoDBException; + + /** + * Performs a PUT request to the given URL and returns the server response. + * + * @return server response + * @throws ArangoDBException + */ + + Response put() throws ArangoDBException; } diff --git a/src/main/java/com/arangodb/ArangoSearch.java b/src/main/java/com/arangodb/ArangoSearch.java index 65f1af0e1..7a6600d79 100644 --- a/src/main/java/com/arangodb/ArangoSearch.java +++ b/src/main/java/com/arangodb/ArangoSearch.java @@ -27,69 +27,66 @@ /** * Interface for operations on ArangoDB view level for ArangoSearch views. - * - * @see View API Documentation + * * @author Mark Vollmary + * @see View API Documentation * @since ArangoDB 3.4.0 */ public interface ArangoSearch extends ArangoView { - /** - * Creates a view, then returns view information from the server. - * - * @see API - * Documentation - * @return information about the view - * @throws ArangoDBException - */ - ViewEntity create() throws ArangoDBException; + /** + * Creates a view, then returns view information from the server. + * + * @return information about the view + * @throws ArangoDBException + * @see API + * Documentation + */ + ViewEntity create() throws ArangoDBException; - /** - * Creates a view with the given {@code options}, then returns view information from the server. - * - * @see API - * Documentation - * @param options - * Additional options, can be null - * @return information about the view - * @throws ArangoDBException - */ - ViewEntity create(ArangoSearchCreateOptions options) throws ArangoDBException; + /** + * 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 + * @throws ArangoDBException + * @see API + * Documentation + */ + ViewEntity create(ArangoSearchCreateOptions options) throws ArangoDBException; - /** - * Reads the properties of the specified view. - * - * @see API - * Documentation - * @return properties of the view - * @throws ArangoDBException - */ - ArangoSearchPropertiesEntity getProperties() throws ArangoDBException; + /** + * Reads the properties of the specified view. + * + * @return properties of the view + * @throws ArangoDBException + * @see API + * Documentation + */ + ArangoSearchPropertiesEntity getProperties() throws ArangoDBException; - /** - * Partially changes properties of the view. - * - * @see API - * Documentation - * @param options - * properties to change - * @return properties of the view - * @throws ArangoDBException - */ - ArangoSearchPropertiesEntity updateProperties(ArangoSearchPropertiesOptions options) throws ArangoDBException; + /** + * Partially changes properties of the view. + * + * @param options properties to change + * @return properties of the view + * @throws ArangoDBException + * @see API + * Documentation + */ + ArangoSearchPropertiesEntity updateProperties(ArangoSearchPropertiesOptions options) throws ArangoDBException; - /** - * Changes properties of the view. - * - * @see API - * Documentation - * @param options - * properties to change - * @return properties of the view - * @throws ArangoDBException - */ - ArangoSearchPropertiesEntity replaceProperties(ArangoSearchPropertiesOptions options) throws ArangoDBException; + /** + * Changes properties of the view. + * + * @param options properties to change + * @return properties of the view + * @throws ArangoDBException + * @see API + * Documentation + */ + ArangoSearchPropertiesEntity replaceProperties(ArangoSearchPropertiesOptions options) throws ArangoDBException; } diff --git a/src/main/java/com/arangodb/ArangoSerializationAccessor.java b/src/main/java/com/arangodb/ArangoSerializationAccessor.java index b1914edd2..0e298cd7b 100644 --- a/src/main/java/com/arangodb/ArangoSerializationAccessor.java +++ b/src/main/java/com/arangodb/ArangoSerializationAccessor.java @@ -26,25 +26,23 @@ /** * @author Mark Vollmary - * */ public interface ArangoSerializationAccessor { - /** - * Returns driver internal serialization API for serializing and deserializing Java POJOs to/from {@link VPackSlice} - * - * @return ArangoSerialization - */ - ArangoSerialization util(); + /** + * Returns driver internal serialization API for serializing and deserializing Java POJOs to/from {@link VPackSlice} + * + * @return ArangoSerialization + */ + ArangoSerialization util(); - /** - * Returns serialization API for serializing and deserializing Java POJOs to/from {@link VPackSlice} by the given - * type - * - * @param serializer - * type of serializer - * @return ArangoSerialization - */ - ArangoSerialization util(Serializer serializer); + /** + * Returns serialization API for serializing and deserializing Java POJOs to/from {@link VPackSlice} by the given + * type + * + * @param serializer type of serializer + * @return ArangoSerialization + */ + ArangoSerialization util(Serializer serializer); } diff --git a/src/main/java/com/arangodb/ArangoVertexCollection.java b/src/main/java/com/arangodb/ArangoVertexCollection.java index 68e44e3c3..e34705cf4 100644 --- a/src/main/java/com/arangodb/ArangoVertexCollection.java +++ b/src/main/java/com/arangodb/ArangoVertexCollection.java @@ -26,172 +26,151 @@ /** * Interface for operations on ArangoDB vertex collection level. - * - * @see API Documentation + * * @author Mark Vollmary + * @see API Documentation */ public interface ArangoVertexCollection extends ArangoSerializationAccessor { - /** - * The the handler of the named graph the edge collection is within - * - * @return graph handler - */ - ArangoGraph graph(); - - /** - * The name of the edge collection - * - * @return collection name - */ - String name(); - - /** - * Removes a vertex collection from the graph and optionally deletes the collection, if it is not used in any other - * graph - * - * @see API - * Documentation - * @throws ArangoDBException - */ - void drop() throws ArangoDBException; - - /** - * Creates a new vertex in the collection - * - * @see API Documentation - * @param value - * A representation of a single vertex (POJO, VPackSlice or String for JSON) - * @return information about the vertex - * @throws ArangoDBException - */ - VertexEntity insertVertex(T value) throws ArangoDBException; - - /** - * Creates a new vertex in the collection - * - * @see API Documentation - * @param value - * A representation of a single vertex (POJO, VPackSlice or String for JSON) - * @param options - * Additional options, can be null - * @return information about the vertex - * @throws ArangoDBException - */ - VertexEntity insertVertex(T value, VertexCreateOptions options) throws ArangoDBException; - - /** - * Retrieves the vertex document with the given {@code key} from the collection. - * - * @see API Documentation - * @param key - * The key of the vertex - * @param type - * The type of the vertex-document (POJO class, VPackSlice or String for JSON) - * @return the vertex identified by the key - * @throws ArangoDBException - */ - T getVertex(String key, Class type) throws ArangoDBException; - - /** - * Retrieves the vertex document with the given {@code key} from the collection. - * - * @see API Documentation - * @param key - * The key of the vertex - * @param type - * The type of the vertex-document (POJO class, VPackSlice or String for JSON) - * @param options - * Additional options, can be null - * @return the vertex identified by the key - * @throws ArangoDBException - */ - T getVertex(String key, Class type, GraphDocumentReadOptions options) throws ArangoDBException; - - /** - * Replaces the vertex with key with the one in the body, provided there is such a vertex and no precondition is - * violated - * - * @see API - * Documentation - * @param key - * The key of the vertex - * @param value - * A representation of a single vertex (POJO, VPackSlice or String for JSON) - * @return information about the vertex - * @throws ArangoDBException - */ - VertexUpdateEntity replaceVertex(String key, T value) throws ArangoDBException; - - /** - * Replaces the vertex with key with the one in the body, provided there is such a vertex and no precondition is - * violated - * - * @see API - * Documentation - * @param key - * The key of the vertex - * @param value - * A representation of a single vertex (POJO, VPackSlice or String for JSON) - * @param options - * Additional options, can be null - * @return information about the vertex - * @throws ArangoDBException - */ - VertexUpdateEntity replaceVertex(String key, T value, VertexReplaceOptions options) throws ArangoDBException; - - /** - * 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. - * - * @see API Documentation - * @param key - * The key of the vertex - * @param - * The type of the vertex-document (POJO class, VPackSlice or String for JSON) - * @return information about the vertex - * @throws ArangoDBException - */ - VertexUpdateEntity updateVertex(String key, T value) throws ArangoDBException; - - /** - * 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. - * - * @see API Documentation - * @param key - * The key of the vertex - * @param - * The type of the vertex-document (POJO class, VPackSlice or String for JSON) - * @param options - * Additional options, can be null - * @return information about the vertex - * @throws ArangoDBException - */ - VertexUpdateEntity updateVertex(String key, T value, VertexUpdateOptions options) throws ArangoDBException; - - /** - * Deletes the vertex with the given {@code key} from the collection. - * - * @see API Documentation - * @param key - * The key of the vertex - * @throws ArangoDBException - */ - void deleteVertex(String key) throws ArangoDBException; - - /** - * Deletes the vertex with the given {@code key} from the collection. - * - * @see API Documentation - * @param key - * The key of the vertex - * @param options - * Additional options, can be null - * @throws ArangoDBException - */ - void deleteVertex(String key, VertexDeleteOptions options) throws ArangoDBException; + /** + * The the handler of the named graph the edge collection is within + * + * @return graph handler + */ + ArangoGraph graph(); + + /** + * The name of the edge collection + * + * @return collection name + */ + String name(); + + /** + * Removes a vertex collection from the graph and optionally deletes the collection, if it is not used in any other + * graph + * + * @throws ArangoDBException + * @see API + * Documentation + */ + void drop() throws ArangoDBException; + + /** + * Creates a new vertex in the collection + * + * @param value A representation of a single vertex (POJO, VPackSlice or String for JSON) + * @return information about the vertex + * @throws ArangoDBException + * @see API Documentation + */ + VertexEntity insertVertex(T value) throws ArangoDBException; + + /** + * Creates a new vertex in the collection + * + * @param value A representation of a single vertex (POJO, VPackSlice or String for JSON) + * @param options Additional options, can be null + * @return information about the vertex + * @throws ArangoDBException + * @see API Documentation + */ + VertexEntity insertVertex(T value, VertexCreateOptions options) throws ArangoDBException; + + /** + * Retrieves the vertex document with the given {@code key} from the collection. + * + * @param key The key of the vertex + * @param type The type of the vertex-document (POJO class, VPackSlice or String for JSON) + * @return the vertex identified by the key + * @throws ArangoDBException + * @see API Documentation + */ + T getVertex(String key, Class type) throws ArangoDBException; + + /** + * Retrieves the vertex document with the given {@code key} from the collection. + * + * @param key The key of the vertex + * @param type The type of the vertex-document (POJO class, VPackSlice or String for JSON) + * @param options Additional options, can be null + * @return the vertex identified by the key + * @throws ArangoDBException + * @see API Documentation + */ + T getVertex(String key, Class type, GraphDocumentReadOptions options) throws ArangoDBException; + + /** + * 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 value A representation of a single vertex (POJO, VPackSlice or String for JSON) + * @return information about the vertex + * @throws ArangoDBException + * @see API + * Documentation + */ + VertexUpdateEntity replaceVertex(String key, T value) throws ArangoDBException; + + /** + * 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 value A representation of a single vertex (POJO, VPackSlice or String for JSON) + * @param options Additional options, can be null + * @return information about the vertex + * @throws ArangoDBException + * @see API + * Documentation + */ + VertexUpdateEntity replaceVertex(String key, T value, VertexReplaceOptions options) throws ArangoDBException; + + /** + * 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 The type of the vertex-document (POJO class, VPackSlice or String for JSON) + * @return information about the vertex + * @throws ArangoDBException + * @see API Documentation + */ + VertexUpdateEntity updateVertex(String key, T value) throws ArangoDBException; + + /** + * 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 The type of the vertex-document (POJO class, VPackSlice or String for JSON) + * @param options Additional options, can be null + * @return information about the vertex + * @throws ArangoDBException + * @see API Documentation + */ + VertexUpdateEntity updateVertex(String key, T value, VertexUpdateOptions options) throws ArangoDBException; + + /** + * Deletes the vertex with the given {@code key} from the collection. + * + * @param key The key of the vertex + * @throws ArangoDBException + * @see API Documentation + */ + void deleteVertex(String key) throws ArangoDBException; + + /** + * Deletes the vertex with the given {@code key} from the collection. + * + * @param key The key of the vertex + * @param options Additional options, can be null + * @throws ArangoDBException + * @see API Documentation + */ + void deleteVertex(String key, VertexDeleteOptions options) throws ArangoDBException; } diff --git a/src/main/java/com/arangodb/ArangoView.java b/src/main/java/com/arangodb/ArangoView.java index e0afbede5..56a3a7995 100644 --- a/src/main/java/com/arangodb/ArangoView.java +++ b/src/main/java/com/arangodb/ArangoView.java @@ -24,63 +24,62 @@ /** * Interface for operations on ArangoDB view level. - * - * @see View API Documentation + * * @author Mark Vollmary + * @see View API Documentation * @since ArangoDB 3.4.0 */ @SuppressWarnings("UnusedReturnValue") public interface ArangoView extends ArangoSerializationAccessor { - /** - * The the handler of the database the collection is within - * - * @return database handler - */ - ArangoDatabase db(); + /** + * The the handler of the database the collection is within + * + * @return database handler + */ + ArangoDatabase db(); - /** - * The name of the view - * - * @return view name - */ - String name(); + /** + * The name of the view + * + * @return view name + */ + String name(); - /** - * Checks whether the view exists. - * - * @return true if the view exists, otherwise false - * @throws ArangoDBException - */ - boolean exists() throws ArangoDBException; + /** + * Checks whether the view exists. + * + * @return true if the view exists, otherwise false + * @throws ArangoDBException + */ + boolean exists() throws ArangoDBException; - /** - * Deletes the view from the database. - * - * @see API Documentation - * @throws ArangoDBException - */ - void drop() throws ArangoDBException; + /** + * Deletes the view from the database. + * + * @throws ArangoDBException + * @see API Documentation + */ + void drop() throws ArangoDBException; - /** - * Renames the view. - * - * @see API Documentation - * @param newName - * The new name - * @return information about the view - * @throws ArangoDBException - */ - ViewEntity rename(String newName) throws ArangoDBException; + /** + * Renames the view. + * + * @param newName The new name + * @return information about the view + * @throws ArangoDBException + * @see API Documentation + */ + ViewEntity rename(String newName) throws ArangoDBException; - /** - * Returns information about the view. - * - * @see API - * Documentation - * @return information about the view - * @throws ArangoDBException - */ - ViewEntity getInfo() throws ArangoDBException; + /** + * Returns information about the view. + * + * @return information about the view + * @throws ArangoDBException + * @see API + * Documentation + */ + ViewEntity getInfo() throws ArangoDBException; } diff --git a/src/main/java/com/arangodb/Consumer.java b/src/main/java/com/arangodb/Consumer.java index 7496dc59a..b4015bf2c 100644 --- a/src/main/java/com/arangodb/Consumer.java +++ b/src/main/java/com/arangodb/Consumer.java @@ -21,19 +21,16 @@ package com.arangodb; /** + * @param the type of the input to the operation * @author Mark Vollmary - * @param - * the type of the input to the operation - * */ public interface Consumer { - /** - * Performs this operation on the given argument. - * - * @param t - * the input argument - */ - void accept(T t); + /** + * Performs this operation on the given argument. + * + * @param t the input argument + */ + void accept(T t); } diff --git a/src/main/java/com/arangodb/Function.java b/src/main/java/com/arangodb/Function.java index d5ce37eca..b0af90c5b 100644 --- a/src/main/java/com/arangodb/Function.java +++ b/src/main/java/com/arangodb/Function.java @@ -21,23 +21,18 @@ package com.arangodb; /** - * + * @param the type of the input to the function + * @param the type of the result of the function * @author Mark Vollmary - * - * @param - * the type of the input to the function - * @param - * the type of the result of the function */ public interface Function { - /** - * Applies this function to the given argument. - * - * @param t - * the function argument - * @return the function result - */ - R apply(T t); + /** + * Applies this function to the given argument. + * + * @param t the function argument + * @return the function result + */ + R apply(T t); } diff --git a/src/main/java/com/arangodb/Predicate.java b/src/main/java/com/arangodb/Predicate.java index 52f55e66d..5f0326618 100644 --- a/src/main/java/com/arangodb/Predicate.java +++ b/src/main/java/com/arangodb/Predicate.java @@ -21,20 +21,17 @@ package com.arangodb; /** + * @param the type of the input to the predicate * @author Mark Vollmary - * @param - * the type of the input to the predicate - * */ public interface Predicate { - /** - * Evaluates this predicate on the given argument. - * - * @param t - * the input argument - * @return {@code true} if the input argument matches the predicate, otherwise {@code false} - */ - boolean test(T t); + /** + * Evaluates this predicate on the given argument. + * + * @param t the input argument + * @return {@code true} if the input argument matches the predicate, otherwise {@code false} + */ + boolean test(T t); } diff --git a/src/main/java/com/arangodb/Protocol.java b/src/main/java/com/arangodb/Protocol.java index 066861ba6..486ab62f7 100644 --- a/src/main/java/com/arangodb/Protocol.java +++ b/src/main/java/com/arangodb/Protocol.java @@ -22,23 +22,22 @@ /** * @author Mark Vollmary - * */ public enum Protocol { - /** - * VelocyStream - * - * @see VelocyStream specification - */ - VST, - /** - * HTTP with JSON body - */ - HTTP_JSON, - /** - * HTTP with VelocyPack body - * - * @see VelocyPack specification - */ - HTTP_VPACK + /** + * VelocyStream + * + * @see VelocyStream specification + */ + VST, + /** + * HTTP with JSON body + */ + HTTP_JSON, + /** + * HTTP with VelocyPack body + * + * @see VelocyPack specification + */ + HTTP_VPACK } diff --git a/src/main/java/com/arangodb/async/ArangoDBAsync.java b/src/main/java/com/arangodb/async/ArangoDBAsync.java index 18671517f..36f8e74d1 100644 --- a/src/main/java/com/arangodb/async/ArangoDBAsync.java +++ b/src/main/java/com/arangodb/async/ArangoDBAsync.java @@ -103,9 +103,9 @@ public interface ArangoDBAsync extends ArangoSerializationAccessor { * * @param options Creation options * @return true if the database was created successfully. - * @since ArangoDB 3.6.0 * @see API * Documentation + * @since ArangoDB 3.6.0 */ CompletableFuture createDatabase(final DBCreateOptions options); diff --git a/src/main/java/com/arangodb/entity/AqlExecutionExplainEntity.java b/src/main/java/com/arangodb/entity/AqlExecutionExplainEntity.java index dfea4b6a9..b913a267c 100644 --- a/src/main/java/com/arangodb/entity/AqlExecutionExplainEntity.java +++ b/src/main/java/com/arangodb/entity/AqlExecutionExplainEntity.java @@ -24,274 +24,273 @@ /** * @author Mark Vollmary - * * @see API Documentation */ public class AqlExecutionExplainEntity implements Entity { - public static class ExecutionPlan { - private Collection nodes; - private Collection rules; - private Collection collections; - private Collection variables; - private Integer estimatedCost; - private Integer estimatedNrItems; - - public Collection getNodes() { - return nodes; - } - - public Collection getRules() { - return rules; - } - - public Collection getCollections() { - return collections; - } - - public Collection getVariables() { - return variables; - } - - public Integer getEstimatedCost() { - return estimatedCost; - } - - public Integer getEstimatedNrItems() { - return estimatedNrItems; - } - } - - public static class ExecutionNode { - private String type; - private Collection dependencies; - private Long id; - private Integer estimatedCost; - private Integer estimatedNrItems; - private Long depth; - private String database; - private String collection; - private ExecutionVariable inVariable; - private ExecutionVariable outVariable; - private ExecutionVariable conditionVariable; - private Boolean random; - private Long offset; - private Long limit; - private Boolean fullCount; - private ExecutionNode subquery; - private Boolean isConst; - private Boolean canThrow; - private String expressionType; + public static class ExecutionPlan { + private Collection nodes; + private Collection rules; + private Collection collections; + private Collection variables; + private Integer estimatedCost; + private Integer estimatedNrItems; + + public Collection getNodes() { + return nodes; + } + + public Collection getRules() { + return rules; + } + + public Collection getCollections() { + return collections; + } + + public Collection getVariables() { + return variables; + } + + public Integer getEstimatedCost() { + return estimatedCost; + } + + public Integer getEstimatedNrItems() { + return estimatedNrItems; + } + } + + public static class ExecutionNode { + private String type; + private Collection dependencies; + private Long id; + private Integer estimatedCost; + private Integer estimatedNrItems; + private Long depth; + private String database; + private String collection; + private ExecutionVariable inVariable; + private ExecutionVariable outVariable; + private ExecutionVariable conditionVariable; + private Boolean random; + private Long offset; + private Long limit; + private Boolean fullCount; + private ExecutionNode subquery; + private Boolean isConst; + private Boolean canThrow; + private String expressionType; private Collection indexes; - private ExecutionExpression expression; - private ExecutionCollection condition; - private Boolean reverse; + private ExecutionExpression expression; + private ExecutionCollection condition; + private Boolean reverse; - public String getType() { - return type; - } + public String getType() { + return type; + } - public Collection getDependencies() { - return dependencies; - } + public Collection getDependencies() { + return dependencies; + } - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public Integer getEstimatedCost() { - return estimatedCost; - } + public Integer getEstimatedCost() { + return estimatedCost; + } - public Integer getEstimatedNrItems() { - return estimatedNrItems; - } + public Integer getEstimatedNrItems() { + return estimatedNrItems; + } - public Long getDepth() { - return depth; - } + public Long getDepth() { + return depth; + } - public String getDatabase() { - return database; - } + public String getDatabase() { + return database; + } - public String getCollection() { - return collection; - } + public String getCollection() { + return collection; + } - public ExecutionVariable getInVariable() { - return inVariable; - } + public ExecutionVariable getInVariable() { + return inVariable; + } - public ExecutionVariable getOutVariable() { - return outVariable; - } + public ExecutionVariable getOutVariable() { + return outVariable; + } - public ExecutionVariable getConditionVariable() { - return conditionVariable; - } + public ExecutionVariable getConditionVariable() { + return conditionVariable; + } - public Boolean getRandom() { - return random; - } + public Boolean getRandom() { + return random; + } - public Long getOffset() { - return offset; - } + public Long getOffset() { + return offset; + } - public Long getLimit() { - return limit; - } + public Long getLimit() { + return limit; + } - public Boolean getFullCount() { - return fullCount; - } + public Boolean getFullCount() { + return fullCount; + } - public ExecutionNode getSubquery() { - return subquery; - } + public ExecutionNode getSubquery() { + return subquery; + } - public Boolean getIsConst() { - return isConst; - } + public Boolean getIsConst() { + return isConst; + } - public Boolean getCanThrow() { - return canThrow; - } + public Boolean getCanThrow() { + return canThrow; + } - public String getExpressionType() { - return expressionType; - } + public String getExpressionType() { + return expressionType; + } public Collection getIndexes() { - return indexes; - } - - public ExecutionExpression getExpression() { - return expression; - } - - public ExecutionCollection getCondition() { - return condition; - } - - public Boolean getReverse() { - return reverse; - } - } - - public static class ExecutionVariable { - private Long id; - private String name; - - public Long getId() { - return id; - } - - public String getName() { - return name; - } - } - - public static class ExecutionExpression { - private String type; - private String name; - private Long id; - private Object value; - private Boolean sorted; - private String quantifier; - private Collection levels; - private Collection subNodes; - - public String getType() { - return type; - } - - public String getName() { - return name; - } - - public Long getId() { - return id; - } - - public Object getValue() { - return value; - } - - public Boolean getSorted() { - return sorted; - } - - public String getQuantifier() { - return quantifier; - } - - public Collection getLevels() { - return levels; - } - - public Collection getSubNodes() { - return subNodes; - } - } - - public static class ExecutionCollection { - private String name; - private String type; - - public String getName() { - return name; - } - - public String getType() { - return type; - } - } - - public static class ExecutionStats { - private Integer rulesExecuted; - private Integer rulesSkipped; - private Integer plansCreated; - - public Integer getRulesExecuted() { - return rulesExecuted; - } - - public Integer getRulesSkipped() { - return rulesSkipped; - } - - public Integer getPlansCreated() { - return plansCreated; - } - - } - - private ExecutionPlan plan; - private Collection plans; - private Collection warnings; - private ExecutionStats stats; - private Boolean cacheable; - - public ExecutionPlan getPlan() { - return plan; - } - - public Collection getPlans() { - return plans; - } - - public Collection getWarnings() { - return warnings; - } - - public ExecutionStats getStats() { - return stats; - } - - public Boolean getCacheable() { - return cacheable; - } + return indexes; + } + + public ExecutionExpression getExpression() { + return expression; + } + + public ExecutionCollection getCondition() { + return condition; + } + + public Boolean getReverse() { + return reverse; + } + } + + public static class ExecutionVariable { + private Long id; + private String name; + + public Long getId() { + return id; + } + + public String getName() { + return name; + } + } + + public static class ExecutionExpression { + private String type; + private String name; + private Long id; + private Object value; + private Boolean sorted; + private String quantifier; + private Collection levels; + private Collection subNodes; + + public String getType() { + return type; + } + + public String getName() { + return name; + } + + public Long getId() { + return id; + } + + public Object getValue() { + return value; + } + + public Boolean getSorted() { + return sorted; + } + + public String getQuantifier() { + return quantifier; + } + + public Collection getLevels() { + return levels; + } + + public Collection getSubNodes() { + return subNodes; + } + } + + public static class ExecutionCollection { + private String name; + private String type; + + public String getName() { + return name; + } + + public String getType() { + return type; + } + } + + public static class ExecutionStats { + private Integer rulesExecuted; + private Integer rulesSkipped; + private Integer plansCreated; + + public Integer getRulesExecuted() { + return rulesExecuted; + } + + public Integer getRulesSkipped() { + return rulesSkipped; + } + + public Integer getPlansCreated() { + return plansCreated; + } + + } + + private ExecutionPlan plan; + private Collection plans; + private Collection warnings; + private ExecutionStats stats; + private Boolean cacheable; + + public ExecutionPlan getPlan() { + return plan; + } + + public Collection getPlans() { + return plans; + } + + public Collection getWarnings() { + return warnings; + } + + public ExecutionStats getStats() { + return stats; + } + + public Boolean getCacheable() { + return cacheable; + } } diff --git a/src/main/java/com/arangodb/entity/AqlFunctionEntity.java b/src/main/java/com/arangodb/entity/AqlFunctionEntity.java index b4dfbdc3b..57f5d78c4 100644 --- a/src/main/java/com/arangodb/entity/AqlFunctionEntity.java +++ b/src/main/java/com/arangodb/entity/AqlFunctionEntity.java @@ -22,42 +22,41 @@ /** * @author Mark Vollmary - * * @see API - * Documentation + * "https://www.arangodb.com/docs/stable/http/aql-user-functions.html#return-registered-aql-user-functions">API + * Documentation */ public class AqlFunctionEntity implements Entity { - private String name; - private String code; - private Boolean isDeterministic; - - public AqlFunctionEntity() { - super(); - } - - /** - * @return The fully qualified name of the user function - */ - public String getName() { - return name; - } - - /** - * @return A string representation of the function body - */ - public String getCode() { - return code; - } - - /** - * @return An optional boolean value to indicate whether the function results are fully deterministic (function - * return value solely depends on the input value and return value is the same for repeated calls with same - * input). The isDeterministic attribute is currently not used but may be used later for optimizations. - */ - public Boolean getIsDeterministic() { - return isDeterministic; - } + private String name; + private String code; + private Boolean isDeterministic; + + public AqlFunctionEntity() { + super(); + } + + /** + * @return The fully qualified name of the user function + */ + public String getName() { + return name; + } + + /** + * @return A string representation of the function body + */ + public String getCode() { + return code; + } + + /** + * @return An optional boolean value to indicate whether the function results are fully deterministic (function + * return value solely depends on the input value and return value is the same for repeated calls with same + * input). The isDeterministic attribute is currently not used but may be used later for optimizations. + */ + public Boolean getIsDeterministic() { + return isDeterministic; + } } diff --git a/src/main/java/com/arangodb/entity/AqlParseEntity.java b/src/main/java/com/arangodb/entity/AqlParseEntity.java index 00b9020bd..f5f16e059 100644 --- a/src/main/java/com/arangodb/entity/AqlParseEntity.java +++ b/src/main/java/com/arangodb/entity/AqlParseEntity.java @@ -24,54 +24,53 @@ /** * @author Mark Vollmary - * * @see API Documentation */ public class AqlParseEntity implements Entity { - public static class AstNode { - private String type; - private Collection subNodes; - private String name; - private Long id; - private Object value; + public static class AstNode { + private String type; + private Collection subNodes; + private String name; + private Long id; + private Object value; - public String getType() { - return type; - } + public String getType() { + return type; + } - public Collection getSubNodes() { - return subNodes; - } + public Collection getSubNodes() { + return subNodes; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public Object getValue() { - return value; - } + public Object getValue() { + return value; + } - } + } - private Collection collections; - private Collection bindVars; - private Collection ast; + private Collection collections; + private Collection bindVars; + private Collection ast; - public Collection getCollections() { - return collections; - } + public Collection getCollections() { + return collections; + } - public Collection getBindVars() { - return bindVars; - } + public Collection getBindVars() { + return bindVars; + } - public Collection getAst() { - return ast; - } + public Collection getAst() { + return ast; + } } diff --git a/src/main/java/com/arangodb/entity/ArangoDBEngine.java b/src/main/java/com/arangodb/entity/ArangoDBEngine.java index 30157ea49..37ea0bfc8 100644 --- a/src/main/java/com/arangodb/entity/ArangoDBEngine.java +++ b/src/main/java/com/arangodb/entity/ArangoDBEngine.java @@ -27,21 +27,21 @@ */ public class ArangoDBEngine implements Entity { - public enum StorageEngineName { - mmfiles, rocksdb - } + public enum StorageEngineName { + mmfiles, rocksdb + } - private StorageEngineName name; + private StorageEngineName name; - public ArangoDBEngine() { - super(); - } + public ArangoDBEngine() { + super(); + } - /** - * @return the storage engine name - */ - public StorageEngineName getName() { - return name; - } + /** + * @return the storage engine name + */ + public StorageEngineName getName() { + return name; + } } diff --git a/src/main/java/com/arangodb/entity/ArangoDBVersion.java b/src/main/java/com/arangodb/entity/ArangoDBVersion.java index 6fa6f4c6a..db339bd88 100644 --- a/src/main/java/com/arangodb/entity/ArangoDBVersion.java +++ b/src/main/java/com/arangodb/entity/ArangoDBVersion.java @@ -22,40 +22,39 @@ /** * @author Mark Vollmary - * * @see API - * Documentation + * Documentation */ public class ArangoDBVersion implements Entity { - private String server; - private String version; - private License license; - - public ArangoDBVersion() { - super(); - } - - /** - * @return will always contain arango - */ - public String getServer() { - return server; - } - - /** - * @return the server version string. The string has the format "major.minor.sub". major and minor will be numeric, - * and sub may contain a number or a textual version. - */ - public String getVersion() { - return version; - } - - /** - * @return the license - */ - public License getLicense() { - return license; - } + private String server; + private String version; + private License license; + + public ArangoDBVersion() { + super(); + } + + /** + * @return will always contain arango + */ + public String getServer() { + return server; + } + + /** + * @return the server version string. The string has the format "major.minor.sub". major and minor will be numeric, + * and sub may contain a number or a textual version. + */ + public String getVersion() { + return version; + } + + /** + * @return the license + */ + public License getLicense() { + return license; + } } \ No newline at end of file diff --git a/src/main/java/com/arangodb/entity/BaseDocument.java b/src/main/java/com/arangodb/entity/BaseDocument.java index a1a92b81a..e242a3707 100644 --- a/src/main/java/com/arangodb/entity/BaseDocument.java +++ b/src/main/java/com/arangodb/entity/BaseDocument.java @@ -28,153 +28,152 @@ /** * @author Mark Vollmary - * */ public class BaseDocument implements Serializable { - private static final long serialVersionUID = -1824742667228719116L; - - @DocumentField(Type.ID) - protected String id; - @DocumentField(Type.KEY) - protected String key; - @DocumentField(Type.REV) - protected String revision; - protected Map properties; - - public BaseDocument() { - super(); - properties = new HashMap<>(); - } - - public BaseDocument(final String key) { - this(); - this.key = key; - } - - public BaseDocument(final Map properties) { - this(); - final Object tmpId = properties.remove(DocumentField.Type.ID.getSerializeName()); - if (tmpId != null) { - id = tmpId.toString(); - } - final Object tmpKey = properties.remove(DocumentField.Type.KEY.getSerializeName()); - if (tmpKey != null) { - key = tmpKey.toString(); - } - final Object tmpRev = properties.remove(DocumentField.Type.REV.getSerializeName()); - if (tmpRev != null) { - revision = tmpRev.toString(); - } - this.properties = properties; - } - - public String getId() { - return id; - } - - public void setId(final String id) { - this.id = id; - } - - public String getKey() { - return key; - } - - public void setKey(final String key) { - this.key = key; - } - - public String getRevision() { - return revision; - } - - public void setRevision(final String revision) { - this.revision = revision; - } - - public Map getProperties() { - return properties; - } - - public void setProperties(final Map properties) { - this.properties = properties; - } - - public void addAttribute(final String key, final Object value) { - properties.put(key, value); - } - - public void updateAttribute(final String key, final Object value) { - if (properties.containsKey(key)) { - properties.put(key, value); - } - } - - public Object getAttribute(final String key) { - return properties.get(key); - } - - @Override - public String toString() { - return "BaseDocument [documentRevision=" + - revision + - ", documentHandle=" + - id + - ", documentKey=" + - key + - ", properties=" + - properties + - "]"; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((id == null) ? 0 : id.hashCode()); - result = prime * result + ((key == null) ? 0 : key.hashCode()); - result = prime * result + ((properties == null) ? 0 : properties.hashCode()); - result = prime * result + ((revision == null) ? 0 : revision.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 BaseDocument other = (BaseDocument) obj; - if (id == null) { - if (other.id != null) { - return false; - } - } else if (!id.equals(other.id)) { - return false; - } - if (key == null) { - if (other.key != null) { - return false; - } - } else if (!key.equals(other.key)) { - return false; - } - if (properties == null) { - if (other.properties != null) { - return false; - } - } else if (!properties.equals(other.properties)) { - return false; - } - if (revision == null) { - return other.revision == null; - } else return revision.equals(other.revision); - } + private static final long serialVersionUID = -1824742667228719116L; + + @DocumentField(Type.ID) + protected String id; + @DocumentField(Type.KEY) + protected String key; + @DocumentField(Type.REV) + protected String revision; + protected Map properties; + + public BaseDocument() { + super(); + properties = new HashMap<>(); + } + + public BaseDocument(final String key) { + this(); + this.key = key; + } + + public BaseDocument(final Map properties) { + this(); + final Object tmpId = properties.remove(DocumentField.Type.ID.getSerializeName()); + if (tmpId != null) { + id = tmpId.toString(); + } + final Object tmpKey = properties.remove(DocumentField.Type.KEY.getSerializeName()); + if (tmpKey != null) { + key = tmpKey.toString(); + } + final Object tmpRev = properties.remove(DocumentField.Type.REV.getSerializeName()); + if (tmpRev != null) { + revision = tmpRev.toString(); + } + this.properties = properties; + } + + public String getId() { + return id; + } + + public void setId(final String id) { + this.id = id; + } + + public String getKey() { + return key; + } + + public void setKey(final String key) { + this.key = key; + } + + public String getRevision() { + return revision; + } + + public void setRevision(final String revision) { + this.revision = revision; + } + + public Map getProperties() { + return properties; + } + + public void setProperties(final Map properties) { + this.properties = properties; + } + + public void addAttribute(final String key, final Object value) { + properties.put(key, value); + } + + public void updateAttribute(final String key, final Object value) { + if (properties.containsKey(key)) { + properties.put(key, value); + } + } + + public Object getAttribute(final String key) { + return properties.get(key); + } + + @Override + public String toString() { + return "BaseDocument [documentRevision=" + + revision + + ", documentHandle=" + + id + + ", documentKey=" + + key + + ", properties=" + + properties + + "]"; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((id == null) ? 0 : id.hashCode()); + result = prime * result + ((key == null) ? 0 : key.hashCode()); + result = prime * result + ((properties == null) ? 0 : properties.hashCode()); + result = prime * result + ((revision == null) ? 0 : revision.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 BaseDocument other = (BaseDocument) obj; + if (id == null) { + if (other.id != null) { + return false; + } + } else if (!id.equals(other.id)) { + return false; + } + if (key == null) { + if (other.key != null) { + return false; + } + } else if (!key.equals(other.key)) { + return false; + } + if (properties == null) { + if (other.properties != null) { + return false; + } + } else if (!properties.equals(other.properties)) { + return false; + } + if (revision == null) { + return other.revision == null; + } else return revision.equals(other.revision); + } } diff --git a/src/main/java/com/arangodb/entity/BaseEdgeDocument.java b/src/main/java/com/arangodb/entity/BaseEdgeDocument.java index fb0b50371..3c00a1444 100644 --- a/src/main/java/com/arangodb/entity/BaseEdgeDocument.java +++ b/src/main/java/com/arangodb/entity/BaseEdgeDocument.java @@ -26,109 +26,108 @@ /** * @author Mark Vollmary - * */ public class BaseEdgeDocument extends BaseDocument { - private static final long serialVersionUID = 6904923804449368783L; - - @DocumentField(Type.FROM) - private String from; - @DocumentField(Type.TO) - private String to; - - public BaseEdgeDocument() { - super(); - } - - public BaseEdgeDocument(final String from, final String to) { - super(); - this.from = from; - this.to = to; - } - - public BaseEdgeDocument(final String key, final String from, final String to) { - super(key); - this.from = from; - this.to = to; - } - - public BaseEdgeDocument(final Map properties) { - super(properties); - final Object tmpFrom = properties.remove(DocumentField.Type.FROM.getSerializeName()); - if (tmpFrom != null) { - from = tmpFrom.toString(); - } - final Object tmpTo = properties.remove(DocumentField.Type.TO.getSerializeName()); - if (tmpTo != null) { - to = tmpTo.toString(); - } - } - - public String getFrom() { - return from; - } - - public void setFrom(final String from) { - this.from = from; - } - - public String getTo() { - return to; - } - - public void setTo(final String to) { - this.to = to; - } - - @Override - public String toString() { - return "BaseDocument [documentRevision=" + - revision + - ", documentHandle=" + - id + - ", documentKey=" + - key + - ", from=" + - from + - ", to=" + - to + - ", properties=" + - properties + - "]"; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = super.hashCode(); - result = prime * result + ((from == null) ? 0 : from.hashCode()); - result = prime * result + ((to == null) ? 0 : to.hashCode()); - return result; - } - - @Override - public boolean equals(final Object obj) { - if (this == obj) { - return true; - } - if (!super.equals(obj)) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final BaseEdgeDocument other = (BaseEdgeDocument) obj; - if (from == null) { - if (other.from != null) { - return false; - } - } else if (!from.equals(other.from)) { - return false; - } - if (to == null) { - return other.to == null; - } else return to.equals(other.to); - } + private static final long serialVersionUID = 6904923804449368783L; + + @DocumentField(Type.FROM) + private String from; + @DocumentField(Type.TO) + private String to; + + public BaseEdgeDocument() { + super(); + } + + public BaseEdgeDocument(final String from, final String to) { + super(); + this.from = from; + this.to = to; + } + + public BaseEdgeDocument(final String key, final String from, final String to) { + super(key); + this.from = from; + this.to = to; + } + + public BaseEdgeDocument(final Map properties) { + super(properties); + final Object tmpFrom = properties.remove(DocumentField.Type.FROM.getSerializeName()); + if (tmpFrom != null) { + from = tmpFrom.toString(); + } + final Object tmpTo = properties.remove(DocumentField.Type.TO.getSerializeName()); + if (tmpTo != null) { + to = tmpTo.toString(); + } + } + + public String getFrom() { + return from; + } + + public void setFrom(final String from) { + this.from = from; + } + + public String getTo() { + return to; + } + + public void setTo(final String to) { + this.to = to; + } + + @Override + public String toString() { + return "BaseDocument [documentRevision=" + + revision + + ", documentHandle=" + + id + + ", documentKey=" + + key + + ", from=" + + from + + ", to=" + + to + + ", properties=" + + properties + + "]"; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = super.hashCode(); + result = prime * result + ((from == null) ? 0 : from.hashCode()); + result = prime * result + ((to == null) ? 0 : to.hashCode()); + return result; + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) { + return true; + } + if (!super.equals(obj)) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final BaseEdgeDocument other = (BaseEdgeDocument) obj; + if (from == null) { + if (other.from != null) { + return false; + } + } else if (!from.equals(other.from)) { + return false; + } + if (to == null) { + return other.to == null; + } else return to.equals(other.to); + } } diff --git a/src/main/java/com/arangodb/entity/CollectionEntity.java b/src/main/java/com/arangodb/entity/CollectionEntity.java index 1239027a4..5cc3f6fe0 100644 --- a/src/main/java/com/arangodb/entity/CollectionEntity.java +++ b/src/main/java/com/arangodb/entity/CollectionEntity.java @@ -22,49 +22,48 @@ /** * @author Mark Vollmary - * * @see API Documentation */ public class CollectionEntity implements Entity { - private String id; - private String name; - private Boolean waitForSync; - private Boolean isVolatile; - private Boolean isSystem; - private CollectionStatus status; - private CollectionType type; + private String id; + private String name; + private Boolean waitForSync; + private Boolean isVolatile; + private Boolean isSystem; + private CollectionStatus status; + private CollectionType type; - public CollectionEntity() { - super(); - } + public CollectionEntity() { + super(); + } - public String getId() { - return id; - } + public String getId() { + return id; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public Boolean getWaitForSync() { - return waitForSync; - } + public Boolean getWaitForSync() { + return waitForSync; + } - public Boolean getIsVolatile() { - return isVolatile; - } + public Boolean getIsVolatile() { + return isVolatile; + } - public Boolean getIsSystem() { - return isSystem; - } + public Boolean getIsSystem() { + return isSystem; + } - public CollectionStatus getStatus() { - return status; - } + public CollectionStatus getStatus() { + return status; + } - public CollectionType getType() { - return type; - } + public CollectionType getType() { + return type; + } } diff --git a/src/main/java/com/arangodb/entity/CollectionPropertiesEntity.java b/src/main/java/com/arangodb/entity/CollectionPropertiesEntity.java index 16e9ad879..14fc1fe92 100644 --- a/src/main/java/com/arangodb/entity/CollectionPropertiesEntity.java +++ b/src/main/java/com/arangodb/entity/CollectionPropertiesEntity.java @@ -24,135 +24,134 @@ /** * @author Mark Vollmary - * * @see API - * Documentation + * Documentation */ public class CollectionPropertiesEntity extends CollectionEntity { - private Boolean doCompact; - private Long journalSize; - private Integer indexBuckets; - private KeyOptions keyOptions; - private Long count; - private Integer numberOfShards; - private Collection shardKeys; - private final ReplicationFactor replicationFactor; - private final MinReplicationFactor minReplicationFactor; - - private String shardingStrategy; // cluster option - private String smartJoinAttribute; // enterprise option - - public CollectionPropertiesEntity() { - super(); - replicationFactor = new ReplicationFactor(); - minReplicationFactor = new MinReplicationFactor(); - } - - public Boolean getDoCompact() { - return doCompact; - } - - public void setDoCompact(final Boolean doCompact) { - this.doCompact = doCompact; - } - - public Long getJournalSize() { - return journalSize; - } - - public void setJournalSize(final Long journalSize) { - this.journalSize = journalSize; - } - - public Integer getIndexBuckets() { - return indexBuckets; - } - - public void setIndexBuckets(final Integer indexBuckets) { - this.indexBuckets = indexBuckets; - } - - public KeyOptions getKeyOptions() { - return keyOptions; - } - - public void setKeyOptions(final KeyOptions keyOptions) { - this.keyOptions = keyOptions; - } - - public Long getCount() { - return count; - } - - public void setCount(final Long count) { - this.count = count; - } - - /** - * @return the number of shards of the collection. Only in a cluster setup (else returning null). - */ - public Integer getNumberOfShards() { - return numberOfShards; - } - - public void setNumberOfShards(final Integer numberOfShards) { - this.numberOfShards = numberOfShards; - } - - /** - * @return the names of document attributes that are used to determine the target shard for documents. - * Only in a cluster setup (else returning null). - */ - public Collection getShardKeys() { - return shardKeys; - } - - public void setShardKeys(final Collection shardKeys) { - this.shardKeys = shardKeys; - } - - public Integer getReplicationFactor() { - return replicationFactor.getReplicationFactor(); - } - - public void setReplicationFactor(final Integer replicationFactor) { - this.replicationFactor.setReplicationFactor(replicationFactor); - } - - public Integer getMinReplicationFactor() { - return minReplicationFactor.getMinReplicationFactor(); - } - - public void setMinReplicationFactor(final Integer minReplicationFactor) { - this.minReplicationFactor.setMinReplicationFactor(minReplicationFactor); - } - - /** - * @return whether the collection is a satellite collection. Only in an enterprise cluster setup (else returning null). - */ - public Boolean getSatellite() { - return this.replicationFactor.getSatellite(); - } - - public void setSatellite(final Boolean satellite) { - this.replicationFactor.setSatellite(satellite); - } - - public String getShardingStrategy() { - return shardingStrategy; - } - - public void setShardingStrategy(String shardingStrategy) { - this.shardingStrategy = shardingStrategy; - } - - public String getSmartJoinAttribute() { - return smartJoinAttribute; - } - - public void setSmartJoinAttribute(String smartJoinAttribute) { - this.smartJoinAttribute = smartJoinAttribute; - } + private Boolean doCompact; + private Long journalSize; + private Integer indexBuckets; + private KeyOptions keyOptions; + private Long count; + private Integer numberOfShards; + private Collection shardKeys; + private final ReplicationFactor replicationFactor; + private final MinReplicationFactor minReplicationFactor; + + private String shardingStrategy; // cluster option + private String smartJoinAttribute; // enterprise option + + public CollectionPropertiesEntity() { + super(); + replicationFactor = new ReplicationFactor(); + minReplicationFactor = new MinReplicationFactor(); + } + + public Boolean getDoCompact() { + return doCompact; + } + + public void setDoCompact(final Boolean doCompact) { + this.doCompact = doCompact; + } + + public Long getJournalSize() { + return journalSize; + } + + public void setJournalSize(final Long journalSize) { + this.journalSize = journalSize; + } + + public Integer getIndexBuckets() { + return indexBuckets; + } + + public void setIndexBuckets(final Integer indexBuckets) { + this.indexBuckets = indexBuckets; + } + + public KeyOptions getKeyOptions() { + return keyOptions; + } + + public void setKeyOptions(final KeyOptions keyOptions) { + this.keyOptions = keyOptions; + } + + public Long getCount() { + return count; + } + + public void setCount(final Long count) { + this.count = count; + } + + /** + * @return the number of shards of the collection. Only in a cluster setup (else returning null). + */ + public Integer getNumberOfShards() { + return numberOfShards; + } + + public void setNumberOfShards(final Integer numberOfShards) { + this.numberOfShards = numberOfShards; + } + + /** + * @return the names of document attributes that are used to determine the target shard for documents. + * Only in a cluster setup (else returning null). + */ + public Collection getShardKeys() { + return shardKeys; + } + + public void setShardKeys(final Collection shardKeys) { + this.shardKeys = shardKeys; + } + + public Integer getReplicationFactor() { + return replicationFactor.getReplicationFactor(); + } + + public void setReplicationFactor(final Integer replicationFactor) { + this.replicationFactor.setReplicationFactor(replicationFactor); + } + + public Integer getMinReplicationFactor() { + return minReplicationFactor.getMinReplicationFactor(); + } + + public void setMinReplicationFactor(final Integer minReplicationFactor) { + this.minReplicationFactor.setMinReplicationFactor(minReplicationFactor); + } + + /** + * @return whether the collection is a satellite collection. Only in an enterprise cluster setup (else returning null). + */ + public Boolean getSatellite() { + return this.replicationFactor.getSatellite(); + } + + public void setSatellite(final Boolean satellite) { + this.replicationFactor.setSatellite(satellite); + } + + public String getShardingStrategy() { + return shardingStrategy; + } + + public void setShardingStrategy(String shardingStrategy) { + this.shardingStrategy = shardingStrategy; + } + + public String getSmartJoinAttribute() { + return smartJoinAttribute; + } + + public void setSmartJoinAttribute(String smartJoinAttribute) { + this.smartJoinAttribute = smartJoinAttribute; + } } diff --git a/src/main/java/com/arangodb/entity/CollectionRevisionEntity.java b/src/main/java/com/arangodb/entity/CollectionRevisionEntity.java index 73d912c59..d04ec000d 100644 --- a/src/main/java/com/arangodb/entity/CollectionRevisionEntity.java +++ b/src/main/java/com/arangodb/entity/CollectionRevisionEntity.java @@ -22,16 +22,15 @@ /** * @author Mark Vollmary - * * @see API - * Documentation + * Documentation */ public class CollectionRevisionEntity extends CollectionEntity { - private String revision; + private String revision; - public String getRevision() { - return revision; - } + public String getRevision() { + return revision; + } } diff --git a/src/main/java/com/arangodb/entity/CollectionStatus.java b/src/main/java/com/arangodb/entity/CollectionStatus.java index eea53185a..43fc338bd 100644 --- a/src/main/java/com/arangodb/entity/CollectionStatus.java +++ b/src/main/java/com/arangodb/entity/CollectionStatus.java @@ -22,29 +22,28 @@ /** * @author Mark Vollmary - * */ public enum CollectionStatus { - NEW_BORN_COLLECTION(1), UNLOADED(2), LOADED(3), IN_THE_PROCESS_OF_BEING_UNLOADED(4), DELETED(5); + NEW_BORN_COLLECTION(1), UNLOADED(2), LOADED(3), IN_THE_PROCESS_OF_BEING_UNLOADED(4), DELETED(5); - private final int status; + private final int status; - CollectionStatus(final int status) { - this.status = status; - } + CollectionStatus(final int status) { + this.status = status; + } - public int getStatus() { - return status; - } + public int getStatus() { + return status; + } - public static CollectionStatus fromStatus(final int status) { - for (final CollectionStatus cStatus : CollectionStatus.values()) { - if (cStatus.status == status) { - return cStatus; - } - } - return null; - } + public static CollectionStatus fromStatus(final int status) { + for (final CollectionStatus cStatus : CollectionStatus.values()) { + if (cStatus.status == status) { + return cStatus; + } + } + return null; + } } diff --git a/src/main/java/com/arangodb/entity/CollectionType.java b/src/main/java/com/arangodb/entity/CollectionType.java index 5b16e1be5..af6f56797 100644 --- a/src/main/java/com/arangodb/entity/CollectionType.java +++ b/src/main/java/com/arangodb/entity/CollectionType.java @@ -22,28 +22,27 @@ /** * @author Mark Vollmary - * */ public enum CollectionType { - DOCUMENT(2), EDGES(3); + DOCUMENT(2), EDGES(3); - private final int type; + private final int type; - CollectionType(final int type) { - this.type = type; - } + CollectionType(final int type) { + this.type = type; + } - public int getType() { - return type; - } + public int getType() { + return type; + } - public static CollectionType fromType(final int type) { - for (final CollectionType cType : CollectionType.values()) { - if (cType.type == type) { - return cType; - } - } - return null; - } + public static CollectionType fromType(final int type) { + for (final CollectionType cType : CollectionType.values()) { + if (cType.type == type) { + return cType; + } + } + return null; + } } diff --git a/src/main/java/com/arangodb/entity/CursorEntity.java b/src/main/java/com/arangodb/entity/CursorEntity.java index cae5f3e84..98b9780ad 100644 --- a/src/main/java/com/arangodb/entity/CursorEntity.java +++ b/src/main/java/com/arangodb/entity/CursorEntity.java @@ -20,157 +20,155 @@ package com.arangodb.entity; -import java.util.Collection; -import java.util.Map; - +import com.arangodb.velocypack.VPackSlice; import org.apache.http.protocol.HTTP; -import com.arangodb.velocypack.VPackSlice; +import java.util.Collection; +import java.util.Map; /** * @author Mark Vollmary - * * @see API - * Documentation + * Documentation */ public class CursorEntity implements Entity, MetaAware { - private String id; - private Integer count; - private Extras extra; - private Boolean cached; - private Boolean hasMore; - private VPackSlice result; - - private Map meta; - - public String getId() { - return id; - } - - /** - * @return the total number of result documents available (only available if the query was executed with the count - * attribute set) - */ - public Integer getCount() { - return count; - } - - /** - * @return an optional object with extra information about the query result contained in its stats sub-attribute. - * For data-modification queries, the extra.stats sub-attribute will contain the number of modified - * documents and the number of documents that could not be modified due to an error (if ignoreErrors query - * option is specified) - */ - public Extras getExtra() { - return extra; - } - - /** - * @return a boolean flag indicating whether the query result was served from the query cache or not. If the query - * result is served from the query cache, the extra return attribute will not contain any stats - * sub-attribute and no profile sub-attribute. - */ - public Boolean getCached() { - return cached; - } - - /** - * @return A boolean indicator whether there are more results available for the cursor on the server - */ - public Boolean getHasMore() { - return hasMore; - } - - /** - * @return an vpack-array of result documents (might be empty if query has no results) - */ - public VPackSlice getResult() { - return result; - } - - public Map getMeta() { - return meta; - } - - /** - * @return remove not allowed (valid storable) meta information - */ - public Map cleanupMeta(Map meta) { - meta.remove(HTTP.CONTENT_LEN); - meta.remove(HTTP.TRANSFER_ENCODING); - return meta; - } - - public void setMeta(Map meta) { - this.meta = cleanupMeta(meta); - } - - public static class Warning { - - private Integer code; - private String message; - - public Integer getCode() { - return code; - } - - public String getMessage() { - return message; - } - - } - - public static class Extras { - private Stats stats; - private Collection warnings; - - public Stats getStats() { - return stats; - } - - public Collection getWarnings() { - return warnings; - } - - } - - public static class Stats { - private Long writesExecuted; - private Long writesIgnored; - private Long scannedFull; - private Long scannedIndex; - private Long filtered; - private Long fullCount; - private Double executionTime; - - public Long getWritesExecuted() { - return writesExecuted; - } - - public Long getWritesIgnored() { - return writesIgnored; - } - - public Long getScannedFull() { - return scannedFull; - } - - public Long getScannedIndex() { - return scannedIndex; - } - - public Long getFiltered() { - return filtered; - } - - public Long getFullCount() { - return fullCount; - } - - public Double getExecutionTime() { - return executionTime; - } - - } + private String id; + private Integer count; + private Extras extra; + private Boolean cached; + private Boolean hasMore; + private VPackSlice result; + + private Map meta; + + public String getId() { + return id; + } + + /** + * @return the total number of result documents available (only available if the query was executed with the count + * attribute set) + */ + public Integer getCount() { + return count; + } + + /** + * @return an optional object with extra information about the query result contained in its stats sub-attribute. + * For data-modification queries, the extra.stats sub-attribute will contain the number of modified + * documents and the number of documents that could not be modified due to an error (if ignoreErrors query + * option is specified) + */ + public Extras getExtra() { + return extra; + } + + /** + * @return a boolean flag indicating whether the query result was served from the query cache or not. If the query + * result is served from the query cache, the extra return attribute will not contain any stats + * sub-attribute and no profile sub-attribute. + */ + public Boolean getCached() { + return cached; + } + + /** + * @return A boolean indicator whether there are more results available for the cursor on the server + */ + public Boolean getHasMore() { + return hasMore; + } + + /** + * @return an vpack-array of result documents (might be empty if query has no results) + */ + public VPackSlice getResult() { + return result; + } + + public Map getMeta() { + return meta; + } + + /** + * @return remove not allowed (valid storable) meta information + */ + public Map cleanupMeta(Map meta) { + meta.remove(HTTP.CONTENT_LEN); + meta.remove(HTTP.TRANSFER_ENCODING); + return meta; + } + + public void setMeta(Map meta) { + this.meta = cleanupMeta(meta); + } + + public static class Warning { + + private Integer code; + private String message; + + public Integer getCode() { + return code; + } + + public String getMessage() { + return message; + } + + } + + public static class Extras { + private Stats stats; + private Collection warnings; + + public Stats getStats() { + return stats; + } + + public Collection getWarnings() { + return warnings; + } + + } + + public static class Stats { + private Long writesExecuted; + private Long writesIgnored; + private Long scannedFull; + private Long scannedIndex; + private Long filtered; + private Long fullCount; + private Double executionTime; + + public Long getWritesExecuted() { + return writesExecuted; + } + + public Long getWritesIgnored() { + return writesIgnored; + } + + public Long getScannedFull() { + return scannedFull; + } + + public Long getScannedIndex() { + return scannedIndex; + } + + public Long getFiltered() { + return filtered; + } + + public Long getFullCount() { + return fullCount; + } + + public Double getExecutionTime() { + return executionTime; + } + + } } diff --git a/src/main/java/com/arangodb/entity/DocumentCreateEntity.java b/src/main/java/com/arangodb/entity/DocumentCreateEntity.java index a9b4e6a10..9469325bf 100644 --- a/src/main/java/com/arangodb/entity/DocumentCreateEntity.java +++ b/src/main/java/com/arangodb/entity/DocumentCreateEntity.java @@ -24,42 +24,41 @@ /** * @author Mark Vollmary - * * @see API - * Documentation + * Documentation */ public class DocumentCreateEntity extends DocumentEntity { - @Expose(deserialize = false) - private T newDocument; - @Expose(deserialize = false) - private T oldDocument; + @Expose(deserialize = false) + private T newDocument; + @Expose(deserialize = false) + private T oldDocument; - public DocumentCreateEntity() { - super(); - } + public DocumentCreateEntity() { + super(); + } - /** - * @return If the query parameter returnNew is true, then the complete new document is returned. - */ - public T getNew() { - return newDocument; - } + /** + * @return If the query parameter returnNew is true, then the complete new document is returned. + */ + public T getNew() { + return newDocument; + } - public void setNew(final T newDocument) { - this.newDocument = newDocument; - } + public void setNew(final T newDocument) { + this.newDocument = newDocument; + } - /** - * @return If the query parameter returnOld is true, then the complete previous revision of the document is - * returned. - */ - public T getOld() { - return oldDocument; - } + /** + * @return If the query parameter returnOld is true, then the complete previous revision of the document is + * returned. + */ + public T getOld() { + return oldDocument; + } - public void setOld(final T oldDocument) { - this.oldDocument = oldDocument; - } + public void setOld(final T oldDocument) { + this.oldDocument = oldDocument; + } } diff --git a/src/main/java/com/arangodb/entity/DocumentDeleteEntity.java b/src/main/java/com/arangodb/entity/DocumentDeleteEntity.java index a010eed63..336ec53c1 100644 --- a/src/main/java/com/arangodb/entity/DocumentDeleteEntity.java +++ b/src/main/java/com/arangodb/entity/DocumentDeleteEntity.java @@ -24,28 +24,27 @@ /** * @author Mark Vollmary - * * @see API - * Documentation + * Documentation */ public class DocumentDeleteEntity extends DocumentEntity { - @Expose(deserialize = false) - private T oldDocument; + @Expose(deserialize = false) + private T oldDocument; - public DocumentDeleteEntity() { - super(); - } + public DocumentDeleteEntity() { + super(); + } - /** - * @return If the query parameter returnOld is true, then the complete previous revision of the document is - * returned. - */ - public T getOld() { - return oldDocument; - } + /** + * @return If the query parameter returnOld is true, then the complete previous revision of the document is + * returned. + */ + public T getOld() { + return oldDocument; + } - public void setOld(final T oldDocument) { - this.oldDocument = oldDocument; - } + public void setOld(final T oldDocument) { + this.oldDocument = oldDocument; + } } diff --git a/src/main/java/com/arangodb/entity/DocumentEntity.java b/src/main/java/com/arangodb/entity/DocumentEntity.java index 6cf674cc5..c6d9551d4 100644 --- a/src/main/java/com/arangodb/entity/DocumentEntity.java +++ b/src/main/java/com/arangodb/entity/DocumentEntity.java @@ -24,31 +24,30 @@ /** * @author Mark Vollmary - * */ public class DocumentEntity implements Entity { - @DocumentField(Type.KEY) - private String key; - @DocumentField(Type.ID) - private String id; - @DocumentField(Type.REV) - private String rev; + @DocumentField(Type.KEY) + private String key; + @DocumentField(Type.ID) + private String id; + @DocumentField(Type.REV) + private String rev; - public DocumentEntity() { - super(); - } + public DocumentEntity() { + super(); + } - public String getKey() { - return key; - } + public String getKey() { + return key; + } - public String getId() { - return id; - } + public String getId() { + return id; + } - public String getRev() { - return rev; - } + public String getRev() { + return rev; + } } diff --git a/src/main/java/com/arangodb/entity/DocumentField.java b/src/main/java/com/arangodb/entity/DocumentField.java index d6ff3d158..a4002ae17 100644 --- a/src/main/java/com/arangodb/entity/DocumentField.java +++ b/src/main/java/com/arangodb/entity/DocumentField.java @@ -27,26 +27,25 @@ /** * @author Mark Vollmary - * */ @Retention(RetentionPolicy.RUNTIME) -@Target({ ElementType.FIELD }) +@Target({ElementType.FIELD}) public @interface DocumentField { - enum Type { - ID("_id"), KEY("_key"), REV("_rev"), FROM("_from"), TO("_to"); + enum Type { + ID("_id"), KEY("_key"), REV("_rev"), FROM("_from"), TO("_to"); - private final String serializeName; + private final String serializeName; - Type(final String serializeName) { - this.serializeName = serializeName; - } + Type(final String serializeName) { + this.serializeName = serializeName; + } - public String getSerializeName() { - return serializeName; - } - } + public String getSerializeName() { + return serializeName; + } + } - Type value(); + Type value(); } diff --git a/src/main/java/com/arangodb/entity/DocumentImportEntity.java b/src/main/java/com/arangodb/entity/DocumentImportEntity.java index 50dc741b2..bd57c65fc 100644 --- a/src/main/java/com/arangodb/entity/DocumentImportEntity.java +++ b/src/main/java/com/arangodb/entity/DocumentImportEntity.java @@ -25,88 +25,87 @@ /** * @author Mark Vollmary - * */ public class DocumentImportEntity implements Entity { - private Integer created; - private Integer errors; - private Integer empty; - private Integer updated; - private Integer ignored; - private Collection details; + private Integer created; + private Integer errors; + private Integer empty; + private Integer updated; + private Integer ignored; + private Collection details; - public DocumentImportEntity() { - super(); + public DocumentImportEntity() { + super(); details = new ArrayList<>(); - } - - /** - * @return number of documents imported. - */ - public Integer getCreated() { - return created; - } - - public void setCreated(final Integer created) { - this.created = created; - } - - /** - * @return number of documents that were not imported due to an error. - */ - public Integer getErrors() { - return errors; - } - - public void setErrors(final Integer errors) { - this.errors = errors; - } - - /** - * @return number of empty lines found in the input (will only contain a value greater zero for types documents or - * auto). - */ - public Integer getEmpty() { - return empty; - } - - public void setEmpty(final Integer empty) { - this.empty = empty; - } - - /** - * @return number of updated/replaced documents (in case onDuplicate was set to either update or replace). - */ - public Integer getUpdated() { - return updated; - } - - public void setUpdated(final Integer updated) { - this.updated = updated; - } - - /** - * @return number of failed but ignored insert operations (in case onDuplicate was set to ignore). - */ - public Integer getIgnored() { - return ignored; - } - - public void setIgnored(final Integer ignored) { - this.ignored = ignored; - } - - /** - * @return if query parameter details is set to true, the result contain details with more detailed information - * about which documents could not be inserted. - */ - public Collection getDetails() { - return details; - } - - public void setDetails(final Collection details) { - this.details = details; - } + } + + /** + * @return number of documents imported. + */ + public Integer getCreated() { + return created; + } + + public void setCreated(final Integer created) { + this.created = created; + } + + /** + * @return number of documents that were not imported due to an error. + */ + public Integer getErrors() { + return errors; + } + + public void setErrors(final Integer errors) { + this.errors = errors; + } + + /** + * @return number of empty lines found in the input (will only contain a value greater zero for types documents or + * auto). + */ + public Integer getEmpty() { + return empty; + } + + public void setEmpty(final Integer empty) { + this.empty = empty; + } + + /** + * @return number of updated/replaced documents (in case onDuplicate was set to either update or replace). + */ + public Integer getUpdated() { + return updated; + } + + public void setUpdated(final Integer updated) { + this.updated = updated; + } + + /** + * @return number of failed but ignored insert operations (in case onDuplicate was set to ignore). + */ + public Integer getIgnored() { + return ignored; + } + + public void setIgnored(final Integer ignored) { + this.ignored = ignored; + } + + /** + * @return if query parameter details is set to true, the result contain details with more detailed information + * about which documents could not be inserted. + */ + public Collection getDetails() { + return details; + } + + public void setDetails(final Collection details) { + this.details = details; + } } diff --git a/src/main/java/com/arangodb/entity/DocumentUpdateEntity.java b/src/main/java/com/arangodb/entity/DocumentUpdateEntity.java index 2a76a03d3..009468000 100644 --- a/src/main/java/com/arangodb/entity/DocumentUpdateEntity.java +++ b/src/main/java/com/arangodb/entity/DocumentUpdateEntity.java @@ -24,51 +24,49 @@ import com.arangodb.velocypack.annotations.SerializedName; /** - * @author Mark Vollmary * @param - * + * @author Mark Vollmary * @see API - * Documentation - * + * Documentation */ public class DocumentUpdateEntity extends DocumentEntity { - @SerializedName("_oldRev") - private String oldRev; - @Expose(deserialize = false) - private T newDocument; - @Expose(deserialize = false) - private T oldDocument; + @SerializedName("_oldRev") + private String oldRev; + @Expose(deserialize = false) + private T newDocument; + @Expose(deserialize = false) + private T oldDocument; - public DocumentUpdateEntity() { - super(); - } + public DocumentUpdateEntity() { + super(); + } - public String getOldRev() { - return oldRev; - } + public String getOldRev() { + return oldRev; + } - /** - * @return If the query parameter returnNew is true, then the complete new document is returned. - */ - public T getNew() { - return newDocument; - } + /** + * @return If the query parameter returnNew is true, then the complete new document is returned. + */ + public T getNew() { + return newDocument; + } - public void setNew(final T newDocument) { - this.newDocument = newDocument; - } + public void setNew(final T newDocument) { + this.newDocument = newDocument; + } - /** - * @return If the query parameter returnOld is true, then the complete previous revision of the document is - * returned. - */ - public T getOld() { - return oldDocument; - } + /** + * @return If the query parameter returnOld is true, then the complete previous revision of the document is + * returned. + */ + public T getOld() { + return oldDocument; + } - public void setOld(final T oldDocument) { - this.oldDocument = oldDocument; - } + public void setOld(final T oldDocument) { + this.oldDocument = oldDocument; + } } diff --git a/src/main/java/com/arangodb/entity/EdgeDefinition.java b/src/main/java/com/arangodb/entity/EdgeDefinition.java index eb4c72b52..598ef58d3 100644 --- a/src/main/java/com/arangodb/entity/EdgeDefinition.java +++ b/src/main/java/com/arangodb/entity/EdgeDefinition.java @@ -25,40 +25,39 @@ /** * @author Mark Vollmary - * * @see API Documentation */ public class EdgeDefinition { - private String collection; - private Collection from; - private Collection to; + private String collection; + private Collection from; + private Collection to; - public String getCollection() { - return collection; - } + public String getCollection() { + return collection; + } - public EdgeDefinition collection(final String collection) { - this.collection = collection; - return this; - } + public EdgeDefinition collection(final String collection) { + this.collection = collection; + return this; + } - public Collection getFrom() { - return from; - } + public Collection getFrom() { + return from; + } - public EdgeDefinition from(final String... from) { - this.from = Arrays.asList(from); - return this; - } + public EdgeDefinition from(final String... from) { + this.from = Arrays.asList(from); + return this; + } - public Collection getTo() { - return to; - } + public Collection getTo() { + return to; + } - public EdgeDefinition to(final String... to) { - this.to = Arrays.asList(to); - return this; - } + public EdgeDefinition to(final String... to) { + this.to = Arrays.asList(to); + return this; + } } diff --git a/src/main/java/com/arangodb/entity/EdgeEntity.java b/src/main/java/com/arangodb/entity/EdgeEntity.java index 57d0c35b7..c62f7d131 100644 --- a/src/main/java/com/arangodb/entity/EdgeEntity.java +++ b/src/main/java/com/arangodb/entity/EdgeEntity.java @@ -22,12 +22,11 @@ /** * @author Mark Vollmary - * */ public class EdgeEntity extends DocumentEntity { - public EdgeEntity() { - super(); - } + public EdgeEntity() { + super(); + } } diff --git a/src/main/java/com/arangodb/entity/EdgeUpdateEntity.java b/src/main/java/com/arangodb/entity/EdgeUpdateEntity.java index 585922599..f872666a3 100644 --- a/src/main/java/com/arangodb/entity/EdgeUpdateEntity.java +++ b/src/main/java/com/arangodb/entity/EdgeUpdateEntity.java @@ -24,20 +24,19 @@ /** * @author Mark Vollmary - * * @see API Documentation */ public class EdgeUpdateEntity extends DocumentEntity { - @SerializedName("_oldRev") - private String oldRev; + @SerializedName("_oldRev") + private String oldRev; - public EdgeUpdateEntity() { - super(); - } + public EdgeUpdateEntity() { + super(); + } - public String getOldRev() { - return oldRev; - } + public String getOldRev() { + return oldRev; + } } diff --git a/src/main/java/com/arangodb/entity/Entity.java b/src/main/java/com/arangodb/entity/Entity.java index 7935970b4..146e561ae 100644 --- a/src/main/java/com/arangodb/entity/Entity.java +++ b/src/main/java/com/arangodb/entity/Entity.java @@ -22,7 +22,6 @@ /** * @author Mark Vollmary - * */ public interface Entity { diff --git a/src/main/java/com/arangodb/entity/ErrorEntity.java b/src/main/java/com/arangodb/entity/ErrorEntity.java index 6e309f16c..48a1c582b 100644 --- a/src/main/java/com/arangodb/entity/ErrorEntity.java +++ b/src/main/java/com/arangodb/entity/ErrorEntity.java @@ -24,47 +24,46 @@ /** * @author Mark Vollmary - * */ public class ErrorEntity implements Serializable, Entity { - private static final long serialVersionUID = -5918898261563691261L; + private static final long serialVersionUID = -5918898261563691261L; - private String errorMessage; - private String exception; - private int code; - private int errorNum; + private String errorMessage; + private String exception; + private int code; + private int errorNum; - public ErrorEntity() { - super(); - } + public ErrorEntity() { + super(); + } - /** - * @return a descriptive error message - */ - public String getErrorMessage() { - return errorMessage; - } + /** + * @return a descriptive error message + */ + public String getErrorMessage() { + return errorMessage; + } - /** - * @return the exception message, passed when transaction fails - */ - public String getException() { - return exception; - } + /** + * @return the exception message, passed when transaction fails + */ + public String getException() { + return exception; + } - /** - * @return the status code - */ - public int getCode() { - return code; - } + /** + * @return the status code + */ + public int getCode() { + return code; + } - /** - * @return the server error number - */ - public int getErrorNum() { - return errorNum; - } + /** + * @return the server error number + */ + public int getErrorNum() { + return errorNum; + } } diff --git a/src/main/java/com/arangodb/entity/GraphEntity.java b/src/main/java/com/arangodb/entity/GraphEntity.java index 9c8689ffa..3c29ab3de 100644 --- a/src/main/java/com/arangodb/entity/GraphEntity.java +++ b/src/main/java/com/arangodb/entity/GraphEntity.java @@ -24,53 +24,53 @@ /** * @author Mark Vollmary - * * @see API Documentation */ public class GraphEntity implements Entity { - private String name; - /** - * Special case where {@code _key} is used instead of {@code name}. - */ - private String _key; - private Collection edgeDefinitions; - private Collection orphanCollections; - private Boolean isSmart; - private Integer numberOfShards; - private String smartGraphAttribute; - private Integer replicationFactor; - private Integer minReplicationFactor; + private String name; + /** + * Special case where {@code _key} is used instead of {@code name}. + */ + private String _key; + private Collection edgeDefinitions; + private Collection orphanCollections; + private Boolean isSmart; + private Integer numberOfShards; + private String smartGraphAttribute; + private Integer replicationFactor; + private Integer minReplicationFactor; + + public String getName() { + return name != null ? name : _key; + } - public String getName() { - return name != null ? name : _key; - } + public Collection getEdgeDefinitions() { + return edgeDefinitions; + } - public Collection getEdgeDefinitions() { - return edgeDefinitions; - } + public Collection getOrphanCollections() { + return orphanCollections; + } - public Collection getOrphanCollections() { - return orphanCollections; - } + public Boolean getIsSmart() { + return isSmart; + } - public Boolean getIsSmart() { - return isSmart; - } + public Integer getNumberOfShards() { + return numberOfShards; + } - public Integer getNumberOfShards() { - return numberOfShards; - } + public Integer getReplicationFactor() { + return replicationFactor; + } - public Integer getReplicationFactor() { - return replicationFactor; - } - public Integer getMinReplicationFactor() { - return minReplicationFactor; - } + public Integer getMinReplicationFactor() { + return minReplicationFactor; + } - public String getSmartGraphAttribute() { - return smartGraphAttribute; - } + public String getSmartGraphAttribute() { + return smartGraphAttribute; + } } diff --git a/src/main/java/com/arangodb/entity/IndexEntity.java b/src/main/java/com/arangodb/entity/IndexEntity.java index 201396e09..5be2d0b87 100644 --- a/src/main/java/com/arangodb/entity/IndexEntity.java +++ b/src/main/java/com/arangodb/entity/IndexEntity.java @@ -24,83 +24,82 @@ /** * @author Mark Vollmary - * */ public class IndexEntity implements Entity { - private String id; - private String name; - private IndexType type; - private Collection fields; - private Double selectivityEstimate; - private Boolean unique; - private Boolean sparse; - private Integer minLength; - private Boolean isNewlyCreated; - private Boolean geoJson; - private Boolean constraint; - private Boolean deduplicate; - private Integer expireAfter; - private Boolean inBackground; - - public IndexEntity() { - super(); - } - - public String getId() { - return id; - } - - public Boolean getInBackground() { - return inBackground; - } - - public String getName() { - return name; - } - - public IndexType getType() { - return type; - } - - public Collection getFields() { - return fields; - } - - public Double getSelectivityEstimate() { - return selectivityEstimate; - } - - public Boolean getUnique() { - return unique; - } - - public Boolean getSparse() { - return sparse; - } - - public Integer getMinLength() { - return minLength; - } - - public Boolean getIsNewlyCreated() { - return isNewlyCreated; - } - - public Boolean getGeoJson() { - return geoJson; - } - - public Integer getExpireAfter() { - return expireAfter; - } - - public Boolean getConstraint() { - return constraint; - } - - public Boolean getDeduplicate() { - return deduplicate; - } + private String id; + private String name; + private IndexType type; + private Collection fields; + private Double selectivityEstimate; + private Boolean unique; + private Boolean sparse; + private Integer minLength; + private Boolean isNewlyCreated; + private Boolean geoJson; + private Boolean constraint; + private Boolean deduplicate; + private Integer expireAfter; + private Boolean inBackground; + + public IndexEntity() { + super(); + } + + public String getId() { + return id; + } + + public Boolean getInBackground() { + return inBackground; + } + + public String getName() { + return name; + } + + public IndexType getType() { + return type; + } + + public Collection getFields() { + return fields; + } + + public Double getSelectivityEstimate() { + return selectivityEstimate; + } + + public Boolean getUnique() { + return unique; + } + + public Boolean getSparse() { + return sparse; + } + + public Integer getMinLength() { + return minLength; + } + + public Boolean getIsNewlyCreated() { + return isNewlyCreated; + } + + public Boolean getGeoJson() { + return geoJson; + } + + public Integer getExpireAfter() { + return expireAfter; + } + + public Boolean getConstraint() { + return constraint; + } + + public Boolean getDeduplicate() { + return deduplicate; + } } diff --git a/src/main/java/com/arangodb/entity/IndexType.java b/src/main/java/com/arangodb/entity/IndexType.java index 1507ec3d8..9440063aa 100644 --- a/src/main/java/com/arangodb/entity/IndexType.java +++ b/src/main/java/com/arangodb/entity/IndexType.java @@ -23,8 +23,7 @@ /** * @author Mark Vollmary * @author Heiko Kernbach - * */ public enum IndexType { - primary, hash, skiplist, persistent, geo, geo1, geo2, fulltext, edge, ttl + primary, hash, skiplist, persistent, geo, geo1, geo2, fulltext, edge, ttl } diff --git a/src/main/java/com/arangodb/entity/KeyOptions.java b/src/main/java/com/arangodb/entity/KeyOptions.java index 41ec5fdfe..261450638 100644 --- a/src/main/java/com/arangodb/entity/KeyOptions.java +++ b/src/main/java/com/arangodb/entity/KeyOptions.java @@ -22,57 +22,56 @@ /** * @author Mark Vollmary - * */ public class KeyOptions { - private Boolean allowUserKeys; - private KeyType type; - private Integer increment; - private Integer offset; + private Boolean allowUserKeys; + private KeyType type; + private Integer increment; + private Integer offset; - public KeyOptions() { - super(); - } + public KeyOptions() { + super(); + } - public KeyOptions(final Boolean allowUserKeys, final KeyType type, final Integer increment, final Integer offset) { - super(); - this.allowUserKeys = allowUserKeys; - this.type = type; - this.increment = increment; - this.offset = offset; - } + public KeyOptions(final Boolean allowUserKeys, final KeyType type, final Integer increment, final Integer offset) { + super(); + this.allowUserKeys = allowUserKeys; + this.type = type; + this.increment = increment; + this.offset = offset; + } - public Boolean getAllowUserKeys() { - return allowUserKeys; - } + public Boolean getAllowUserKeys() { + return allowUserKeys; + } - public void setAllowUserKeys(final Boolean allowUserKeys) { - this.allowUserKeys = allowUserKeys; - } + public void setAllowUserKeys(final Boolean allowUserKeys) { + this.allowUserKeys = allowUserKeys; + } - public KeyType getType() { - return type; - } + public KeyType getType() { + return type; + } - public void setType(final KeyType type) { - this.type = type; - } + public void setType(final KeyType type) { + this.type = type; + } - public Integer getIncrement() { - return increment; - } + public Integer getIncrement() { + return increment; + } - public void setIncrement(final Integer increment) { - this.increment = increment; - } + public void setIncrement(final Integer increment) { + this.increment = increment; + } - public Integer getOffset() { - return offset; - } + public Integer getOffset() { + return offset; + } - public void setOffset(final Integer offset) { - this.offset = offset; - } + public void setOffset(final Integer offset) { + this.offset = offset; + } } diff --git a/src/main/java/com/arangodb/entity/License.java b/src/main/java/com/arangodb/entity/License.java index 0b9b8e789..053b2ca64 100644 --- a/src/main/java/com/arangodb/entity/License.java +++ b/src/main/java/com/arangodb/entity/License.java @@ -25,6 +25,6 @@ */ public enum License { - ENTERPRISE, COMMUNITY - + ENTERPRISE, COMMUNITY + } diff --git a/src/main/java/com/arangodb/entity/LoadBalancingStrategy.java b/src/main/java/com/arangodb/entity/LoadBalancingStrategy.java index b75257b0a..9508dff48 100644 --- a/src/main/java/com/arangodb/entity/LoadBalancingStrategy.java +++ b/src/main/java/com/arangodb/entity/LoadBalancingStrategy.java @@ -22,8 +22,7 @@ /** * @author Mark Vollmary - * */ public enum LoadBalancingStrategy { - NONE, ROUND_ROBIN, ONE_RANDOM + NONE, ROUND_ROBIN, ONE_RANDOM } diff --git a/src/main/java/com/arangodb/entity/LogEntity.java b/src/main/java/com/arangodb/entity/LogEntity.java index a7db6e717..fe4e52ea8 100644 --- a/src/main/java/com/arangodb/entity/LogEntity.java +++ b/src/main/java/com/arangodb/entity/LogEntity.java @@ -24,53 +24,52 @@ /** * @author Mark Vollmary - * * @see API - * Documentation + * "https://www.arangodb.com/docs/stable/http/administration-and-monitoring.html#read-global-logs-from-the-server">API + * Documentation */ public class LogEntity implements Entity { - private List lid; - private List level; - private List timestamp; - private List text; - private Long totalAmount; + private List lid; + private List level; + private List timestamp; + private List text; + private Long totalAmount; - /** - * @return a list of log entry identifiers. Each log message is uniquely identified by its @LIT{lid} and the - * identifiers are in ascending order - */ - public List getLid() { - return lid; - } + /** + * @return a list of log entry identifiers. Each log message is uniquely identified by its @LIT{lid} and the + * identifiers are in ascending order + */ + public List getLid() { + return lid; + } - /** - * @return a list of the log-levels for all log entries - */ - public List getLevel() { - return level; - } + /** + * @return a list of the log-levels for all log entries + */ + public List getLevel() { + return level; + } - /** - * @return a list of the timestamps as seconds since 1970-01-01 for all log entries - */ - public List getTimestamp() { - return timestamp; - } + /** + * @return a list of the timestamps as seconds since 1970-01-01 for all log entries + */ + public List getTimestamp() { + return timestamp; + } - /** - * @return a list of the texts of all log entries - */ - public List getText() { - return text; - } + /** + * @return a list of the texts of all log entries + */ + public List getText() { + return text; + } - /** - * @return the total amount of log entries before pagination - */ - public Long getTotalAmount() { - return totalAmount; - } + /** + * @return the total amount of log entries before pagination + */ + public Long getTotalAmount() { + return totalAmount; + } } diff --git a/src/main/java/com/arangodb/entity/LogLevel.java b/src/main/java/com/arangodb/entity/LogLevel.java index a3780c883..4e220339f 100644 --- a/src/main/java/com/arangodb/entity/LogLevel.java +++ b/src/main/java/com/arangodb/entity/LogLevel.java @@ -22,29 +22,28 @@ /** * @author Mark Vollmary - * */ public enum LogLevel { - FATAL(0), ERROR(1), WARNING(2), INFO(3), DEBUG(4); + FATAL(0), ERROR(1), WARNING(2), INFO(3), DEBUG(4); - private final int level; + private final int level; - LogLevel(final int level) { - this.level = level; - } + LogLevel(final int level) { + this.level = level; + } - public int getLevel() { - return level; - } + public int getLevel() { + return level; + } - public static LogLevel fromLevel(final int level) { - for (final LogLevel logLevel : LogLevel.values()) { - if (logLevel.level == level) { - return logLevel; - } - } - return null; - } + public static LogLevel fromLevel(final int level) { + for (final LogLevel logLevel : LogLevel.values()) { + if (logLevel.level == level) { + return logLevel; + } + } + return null; + } } diff --git a/src/main/java/com/arangodb/entity/LogLevelEntity.java b/src/main/java/com/arangodb/entity/LogLevelEntity.java index 192ed1d51..dea5d4475 100644 --- a/src/main/java/com/arangodb/entity/LogLevelEntity.java +++ b/src/main/java/com/arangodb/entity/LogLevelEntity.java @@ -22,179 +22,178 @@ /** * @author Mark Vollmary - * */ public class LogLevelEntity implements Entity { - public enum LogLevel { - FATAL, ERROR, WARNING, INFO, DEBUG, TRACE, DEFAULT - } - - private LogLevel agency; - private LogLevel agencycomm; - private LogLevel cluster; - private LogLevel collector; - private LogLevel communication; - private LogLevel compactor; - private LogLevel config; - private LogLevel datafiles; - private LogLevel graphs; - private LogLevel heartbeat; - private LogLevel mmap; - private LogLevel performance; - private LogLevel queries; - private LogLevel replication; - private LogLevel requests; - private LogLevel startup; - private LogLevel threads; - private LogLevel v8; - - public LogLevelEntity() { - super(); - } - - public LogLevel getAgency() { - return agency; - } - - public void setAgency(final LogLevel agency) { - this.agency = agency; - } - - public LogLevel getAgencycomm() { - return agencycomm; - } - - public void setAgencycomm(final LogLevel agencycomm) { - this.agencycomm = agencycomm; - } - - public LogLevel getCluster() { - return cluster; - } - - public void setCluster(final LogLevel cluster) { - this.cluster = cluster; - } - - public LogLevel getCollector() { - return collector; - } - - public void setCollector(final LogLevel collector) { - this.collector = collector; - } - - public LogLevel getCommunication() { - return communication; - } - - public void setCommunication(final LogLevel communication) { - this.communication = communication; - } - - public LogLevel getCompactor() { - return compactor; - } - - public void setCompactor(final LogLevel compactor) { - this.compactor = compactor; - } - - public LogLevel getConfig() { - return config; - } - - public void setConfig(final LogLevel config) { - this.config = config; - } - - public LogLevel getDatafiles() { - return datafiles; - } - - public void setDatafiles(final LogLevel datafiles) { - this.datafiles = datafiles; - } - - public LogLevel getGraphs() { - return graphs; - } - - public void setGraphs(final LogLevel graphs) { - this.graphs = graphs; - } - - public LogLevel getHeartbeat() { - return heartbeat; - } - - public void setHeartbeat(final LogLevel heartbeat) { - this.heartbeat = heartbeat; - } - - public LogLevel getMmap() { - return mmap; - } - - public void setMmap(final LogLevel mmap) { - this.mmap = mmap; - } - - public LogLevel getPerformance() { - return performance; - } - - public void setPerformance(final LogLevel performance) { - this.performance = performance; - } + public enum LogLevel { + FATAL, ERROR, WARNING, INFO, DEBUG, TRACE, DEFAULT + } + + private LogLevel agency; + private LogLevel agencycomm; + private LogLevel cluster; + private LogLevel collector; + private LogLevel communication; + private LogLevel compactor; + private LogLevel config; + private LogLevel datafiles; + private LogLevel graphs; + private LogLevel heartbeat; + private LogLevel mmap; + private LogLevel performance; + private LogLevel queries; + private LogLevel replication; + private LogLevel requests; + private LogLevel startup; + private LogLevel threads; + private LogLevel v8; + + public LogLevelEntity() { + super(); + } + + public LogLevel getAgency() { + return agency; + } + + public void setAgency(final LogLevel agency) { + this.agency = agency; + } + + public LogLevel getAgencycomm() { + return agencycomm; + } + + public void setAgencycomm(final LogLevel agencycomm) { + this.agencycomm = agencycomm; + } + + public LogLevel getCluster() { + return cluster; + } + + public void setCluster(final LogLevel cluster) { + this.cluster = cluster; + } + + public LogLevel getCollector() { + return collector; + } + + public void setCollector(final LogLevel collector) { + this.collector = collector; + } + + public LogLevel getCommunication() { + return communication; + } + + public void setCommunication(final LogLevel communication) { + this.communication = communication; + } + + public LogLevel getCompactor() { + return compactor; + } + + public void setCompactor(final LogLevel compactor) { + this.compactor = compactor; + } + + public LogLevel getConfig() { + return config; + } + + public void setConfig(final LogLevel config) { + this.config = config; + } + + public LogLevel getDatafiles() { + return datafiles; + } + + public void setDatafiles(final LogLevel datafiles) { + this.datafiles = datafiles; + } + + public LogLevel getGraphs() { + return graphs; + } + + public void setGraphs(final LogLevel graphs) { + this.graphs = graphs; + } + + public LogLevel getHeartbeat() { + return heartbeat; + } + + public void setHeartbeat(final LogLevel heartbeat) { + this.heartbeat = heartbeat; + } + + public LogLevel getMmap() { + return mmap; + } + + public void setMmap(final LogLevel mmap) { + this.mmap = mmap; + } + + public LogLevel getPerformance() { + return performance; + } + + public void setPerformance(final LogLevel performance) { + this.performance = performance; + } - public LogLevel getQueries() { - return queries; - } + public LogLevel getQueries() { + return queries; + } - public void setQueries(final LogLevel queries) { - this.queries = queries; - } + public void setQueries(final LogLevel queries) { + this.queries = queries; + } - public LogLevel getReplication() { - return replication; - } + public LogLevel getReplication() { + return replication; + } - public void setReplication(final LogLevel replication) { - this.replication = replication; - } + public void setReplication(final LogLevel replication) { + this.replication = replication; + } - public LogLevel getRequests() { - return requests; - } + public LogLevel getRequests() { + return requests; + } - public void setRequests(final LogLevel requests) { - this.requests = requests; - } + public void setRequests(final LogLevel requests) { + this.requests = requests; + } - public LogLevel getStartup() { - return startup; - } + public LogLevel getStartup() { + return startup; + } - public void setStartup(final LogLevel startup) { - this.startup = startup; - } + public void setStartup(final LogLevel startup) { + this.startup = startup; + } - public LogLevel getThreads() { - return threads; - } + public LogLevel getThreads() { + return threads; + } - public void setThreads(final LogLevel threads) { - this.threads = threads; - } + public void setThreads(final LogLevel threads) { + this.threads = threads; + } - public LogLevel getV8() { - return v8; - } + public LogLevel getV8() { + return v8; + } - public void setV8(final LogLevel v8) { - this.v8 = v8; - } + public void setV8(final LogLevel v8) { + this.v8 = v8; + } } diff --git a/src/main/java/com/arangodb/entity/MetaAware.java b/src/main/java/com/arangodb/entity/MetaAware.java index 952f5697a..a6ddc9e14 100644 --- a/src/main/java/com/arangodb/entity/MetaAware.java +++ b/src/main/java/com/arangodb/entity/MetaAware.java @@ -4,12 +4,11 @@ /** * @author Mark Vollmary - * */ public interface MetaAware { - Map getMeta(); + Map getMeta(); - void setMeta(final Map meta); + void setMeta(final Map meta); } diff --git a/src/main/java/com/arangodb/entity/MinReplicationFactor.java b/src/main/java/com/arangodb/entity/MinReplicationFactor.java index 3fc5ff7fc..60b39976e 100644 --- a/src/main/java/com/arangodb/entity/MinReplicationFactor.java +++ b/src/main/java/com/arangodb/entity/MinReplicationFactor.java @@ -22,22 +22,21 @@ /** * @author Heiko Kernbach - * */ public class MinReplicationFactor { - private Integer minReplicationFactor; + private Integer minReplicationFactor; - public MinReplicationFactor() { - super(); - } + public MinReplicationFactor() { + super(); + } - public Integer getMinReplicationFactor() { - return minReplicationFactor; - } + public Integer getMinReplicationFactor() { + return minReplicationFactor; + } - public void setMinReplicationFactor(final Integer minReplicationFactor) { - this.minReplicationFactor = minReplicationFactor; - } + public void setMinReplicationFactor(final Integer minReplicationFactor) { + this.minReplicationFactor = minReplicationFactor; + } } \ No newline at end of file diff --git a/src/main/java/com/arangodb/entity/MultiDocumentEntity.java b/src/main/java/com/arangodb/entity/MultiDocumentEntity.java index ff69f9fa3..bd619c4f9 100644 --- a/src/main/java/com/arangodb/entity/MultiDocumentEntity.java +++ b/src/main/java/com/arangodb/entity/MultiDocumentEntity.java @@ -24,49 +24,48 @@ /** * @author Mark Vollmary - * */ public class MultiDocumentEntity implements Entity { - private Collection documents; - private Collection errors; - private Collection documentsAndErrors; + private Collection documents; + private Collection errors; + private Collection documentsAndErrors; - public MultiDocumentEntity() { - super(); - } + public MultiDocumentEntity() { + super(); + } - /** - * @return all successfully processed documents - */ - public Collection getDocuments() { - return documents; - } + /** + * @return all successfully processed documents + */ + public Collection getDocuments() { + return documents; + } - public void setDocuments(final Collection documents) { - this.documents = documents; - } + public void setDocuments(final Collection documents) { + this.documents = documents; + } - /** - * @return all errors - */ - public Collection getErrors() { - return errors; - } + /** + * @return all errors + */ + public Collection getErrors() { + return errors; + } - public void setErrors(final Collection errors) { - this.errors = errors; - } + public void setErrors(final Collection errors) { + this.errors = errors; + } - /** - * @return all successfully processed documents and all errors in the same order they are processed - */ - public Collection getDocumentsAndErrors() { - return documentsAndErrors; - } + /** + * @return all successfully processed documents and all errors in the same order they are processed + */ + public Collection getDocumentsAndErrors() { + return documentsAndErrors; + } - public void setDocumentsAndErrors(final Collection documentsAndErrors) { - this.documentsAndErrors = documentsAndErrors; - } + public void setDocumentsAndErrors(final Collection documentsAndErrors) { + this.documentsAndErrors = documentsAndErrors; + } } diff --git a/src/main/java/com/arangodb/entity/PathEntity.java b/src/main/java/com/arangodb/entity/PathEntity.java index 619bdf605..91bcc29c1 100644 --- a/src/main/java/com/arangodb/entity/PathEntity.java +++ b/src/main/java/com/arangodb/entity/PathEntity.java @@ -24,33 +24,32 @@ /** * @author Mark Vollmary - * * @see API - * Documentation + * Documentation */ public class PathEntity implements Entity { - private Collection edges; - private Collection vertices; + private Collection edges; + private Collection vertices; - public PathEntity() { - super(); - } + public PathEntity() { + super(); + } - public Collection getEdges() { - return edges; - } + public Collection getEdges() { + return edges; + } - public void setEdges(final Collection edges) { - this.edges = edges; - } + public void setEdges(final Collection edges) { + this.edges = edges; + } - public Collection getVertices() { - return vertices; - } + public Collection getVertices() { + return vertices; + } - public void setVertices(final Collection vertices) { - this.vertices = vertices; - } + public void setVertices(final Collection vertices) { + this.vertices = vertices; + } } diff --git a/src/main/java/com/arangodb/entity/Permissions.java b/src/main/java/com/arangodb/entity/Permissions.java index 34c256ce9..774f36c42 100644 --- a/src/main/java/com/arangodb/entity/Permissions.java +++ b/src/main/java/com/arangodb/entity/Permissions.java @@ -22,18 +22,17 @@ /** * @author Mark Vollmary - * */ public enum Permissions { - /** - * read and write access - */ - RW, - /** - * read-only access - */ - RO, - NONE + /** + * read and write access + */ + RW, + /** + * read-only access + */ + RO, + NONE } diff --git a/src/main/java/com/arangodb/entity/QueryCachePropertiesEntity.java b/src/main/java/com/arangodb/entity/QueryCachePropertiesEntity.java index 5b0d540b1..d820aa0c9 100644 --- a/src/main/java/com/arangodb/entity/QueryCachePropertiesEntity.java +++ b/src/main/java/com/arangodb/entity/QueryCachePropertiesEntity.java @@ -22,52 +22,49 @@ /** * @author Mark Vollmary - * * @see API - * Documentation + * "https://www.arangodb.com/docs/stable/http/aql-query-cache.html">API + * Documentation */ public class QueryCachePropertiesEntity implements Entity { - public enum CacheMode { - off, on, demand - } + public enum CacheMode { + off, on, demand + } - private CacheMode mode; - private Long maxResults; + private CacheMode mode; + private Long maxResults; - public QueryCachePropertiesEntity() { - super(); - } + public QueryCachePropertiesEntity() { + super(); + } - /** - * @return the mode the AQL query cache operates in. The mode is one of the following values: off, on or demand - */ - public CacheMode getMode() { - return mode; - } + /** + * @return the mode the AQL query cache operates in. The mode is one of the following values: off, on or demand + */ + public CacheMode getMode() { + return mode; + } - /** - * @param mode - * the mode the AQL query cache operates in. The mode is one of the following values: off, on or demand - */ - public void setMode(final CacheMode mode) { - this.mode = mode; - } + /** + * @param mode the mode the AQL query cache operates in. The mode is one of the following values: off, on or demand + */ + public void setMode(final CacheMode mode) { + this.mode = mode; + } - /** - * @return the maximum number of query results that will be stored per database-specific cache - */ - public Long getMaxResults() { - return maxResults; - } + /** + * @return the maximum number of query results that will be stored per database-specific cache + */ + public Long getMaxResults() { + return maxResults; + } - /** - * @param maxResults - * the maximum number of query results that will be stored per database-specific cache - */ - public void setMaxResults(final Long maxResults) { - this.maxResults = maxResults; - } + /** + * @param maxResults the maximum number of query results that will be stored per database-specific cache + */ + public void setMaxResults(final Long maxResults) { + this.maxResults = maxResults; + } } diff --git a/src/main/java/com/arangodb/entity/QueryEntity.java b/src/main/java/com/arangodb/entity/QueryEntity.java index 513785b30..2e78b1ed4 100644 --- a/src/main/java/com/arangodb/entity/QueryEntity.java +++ b/src/main/java/com/arangodb/entity/QueryEntity.java @@ -25,64 +25,62 @@ /** * @author Mark Vollmary - * */ public class QueryEntity implements Entity { - public static final String PROPERTY_STARTED = "started"; + public static final String PROPERTY_STARTED = "started"; - private String id; - private String query; - private Date started; - private Double runTime; - private Map bindVars; - private QueryExecutionState state; + private String id; + private String query; + private Date started; + private Double runTime; + private Map bindVars; + private QueryExecutionState state; - public QueryEntity() { - super(); - } + public QueryEntity() { + super(); + } - /** - * @return the query's id - */ - public String getId() { - return id; - } + /** + * @return the query's id + */ + public String getId() { + return id; + } - /** - * @return the query string (potentially truncated) - */ - public String getQuery() { - return query; - } + /** + * @return the query string (potentially truncated) + */ + public String getQuery() { + return query; + } - /** - * @return the date and time when the query was started - */ - public Date getStarted() { - return started; - } + /** + * @return the date and time when the query was started + */ + public Date getStarted() { + return started; + } - /** - * - * @return the query's run time up to the point the list of queries was queried - */ - public Double getRunTime() { - return runTime; - } + /** + * @return the query's run time up to the point the list of queries was queried + */ + public Double getRunTime() { + return runTime; + } - /** - * @return the bind parameter values used by the query - */ - public Map getBindVars() { - return bindVars; - } + /** + * @return the bind parameter values used by the query + */ + public Map getBindVars() { + return bindVars; + } - /** - * @return the query's current execution state - */ - public QueryExecutionState getState() { - return state; - } + /** + * @return the query's current execution state + */ + public QueryExecutionState getState() { + return state; + } } diff --git a/src/main/java/com/arangodb/entity/QueryExecutionState.java b/src/main/java/com/arangodb/entity/QueryExecutionState.java index 628ba0301..0f7afe085 100644 --- a/src/main/java/com/arangodb/entity/QueryExecutionState.java +++ b/src/main/java/com/arangodb/entity/QueryExecutionState.java @@ -22,17 +22,16 @@ /** * @author Mark Vollmary - * */ public enum QueryExecutionState { - INITIALIZING, - PARSING, - OPTIMIZING_AST, - LOADING_COLLECTIONS, - INSTANTIATING_PLAN, - OPTIMIZING_PLAN, - EXECUTING, - FINALIZING, - FINISHED, - INVALID + INITIALIZING, + PARSING, + OPTIMIZING_AST, + LOADING_COLLECTIONS, + INSTANTIATING_PLAN, + OPTIMIZING_PLAN, + EXECUTING, + FINALIZING, + FINISHED, + INVALID } diff --git a/src/main/java/com/arangodb/entity/QueryTrackingPropertiesEntity.java b/src/main/java/com/arangodb/entity/QueryTrackingPropertiesEntity.java index f2382c5f2..dc82e447d 100644 --- a/src/main/java/com/arangodb/entity/QueryTrackingPropertiesEntity.java +++ b/src/main/java/com/arangodb/entity/QueryTrackingPropertiesEntity.java @@ -22,109 +22,103 @@ /** * @author Mark Vollmary - * */ public class QueryTrackingPropertiesEntity implements Entity { - private Boolean enabled; - private Boolean trackSlowQueries; - private Long maxSlowQueries; - private Long slowQueryThreshold; - private Long maxQueryStringLength; + private Boolean enabled; + private Boolean trackSlowQueries; + private Long maxSlowQueries; + private Long slowQueryThreshold; + private Long maxQueryStringLength; - public QueryTrackingPropertiesEntity() { - super(); - } + public QueryTrackingPropertiesEntity() { + super(); + } - /** - * @return If set to true, then queries will be tracked. If set to false, neither queries nor slow queries will be - * tracked - */ - public Boolean getEnabled() { - return enabled; - } + /** + * @return If set to true, then queries will be tracked. If set to false, neither queries nor slow queries will be + * tracked + */ + public Boolean getEnabled() { + return enabled; + } - /** - * @param enabled - * If set to true, then queries will be tracked. If set to false, neither queries nor slow queries will - * be tracked - */ - public void setEnabled(final Boolean enabled) { - this.enabled = enabled; - } + /** + * @param enabled If set to true, then queries will be tracked. If set to false, neither queries nor slow queries will + * be tracked + */ + public void setEnabled(final Boolean enabled) { + this.enabled = enabled; + } - /** - * @return If set to true, then slow queries will be tracked in the list of slow queries if their runtime exceeds - * the value set in slowQueryThreshold. In order for slow queries to be tracked, the enabled property must - * also be set to true. - */ - public Boolean getTrackSlowQueries() { - return trackSlowQueries; - } + /** + * @return If set to true, then slow queries will be tracked in the list of slow queries if their runtime exceeds + * the value set in slowQueryThreshold. In order for slow queries to be tracked, the enabled property must + * also be set to true. + */ + public Boolean getTrackSlowQueries() { + return trackSlowQueries; + } - /** - * @param trackSlowQueries - * If set to true, then slow queries will be tracked in the list of slow queries if their runtime exceeds - * the value set in slowQueryThreshold. In order for slow queries to be tracked, the enabled property - * must also be set to true. - */ - public void setTrackSlowQueries(final Boolean trackSlowQueries) { - this.trackSlowQueries = trackSlowQueries; - } + /** + * @param trackSlowQueries If set to true, then slow queries will be tracked in the list of slow queries if their runtime exceeds + * the value set in slowQueryThreshold. In order for slow queries to be tracked, the enabled property + * must also be set to true. + */ + public void setTrackSlowQueries(final Boolean trackSlowQueries) { + this.trackSlowQueries = trackSlowQueries; + } - /** - * @return The maximum number of slow queries to keep in the list of slow queries. If the list of slow queries is - * full, the oldest entry in it will be discarded when additional slow queries occur. - */ - public Long getMaxSlowQueries() { - return maxSlowQueries; - } + /** + * @return The maximum number of slow queries to keep in the list of slow queries. If the list of slow queries is + * full, the oldest entry in it will be discarded when additional slow queries occur. + */ + public Long getMaxSlowQueries() { + return maxSlowQueries; + } - /** - * @param maxSlowQueries - * The maximum number of slow queries to keep in the list of slow queries. If the list of slow queries is - * full, the oldest entry in it will be discarded when additional slow queries occur. - */ - public void setMaxSlowQueries(final Long maxSlowQueries) { - this.maxSlowQueries = maxSlowQueries; - } + /** + * @param maxSlowQueries The maximum number of slow queries to keep in the list of slow queries. If the list of slow queries is + * full, the oldest entry in it will be discarded when additional slow queries occur. + */ + public void setMaxSlowQueries(final Long maxSlowQueries) { + this.maxSlowQueries = maxSlowQueries; + } - /** - * @return The threshold value for treating a query as slow. A query with a runtime greater or equal to this - * threshold value will be put into the list of slow queries when slow query tracking is enabled. The value - * for slowQueryThreshold is specified in seconds. - */ - public Long getSlowQueryThreshold() { - return slowQueryThreshold; - } + /** + * @return The threshold value for treating a query as slow. A query with a runtime greater or equal to this + * threshold value will be put into the list of slow queries when slow query tracking is enabled. The value + * for slowQueryThreshold is specified in seconds. + */ + public Long getSlowQueryThreshold() { + return slowQueryThreshold; + } - /** - * @param slowQueryThreshold - * The threshold value for treating a query as slow. A query with a runtime greater or equal to this - * threshold value will be put into the list of slow queries when slow query tracking is enabled. The - * value for slowQueryThreshold is specified in seconds. - */ - public void setSlowQueryThreshold(final Long slowQueryThreshold) { - this.slowQueryThreshold = slowQueryThreshold; - } + /** + * @param slowQueryThreshold The threshold value for treating a query as slow. A query with a runtime greater or equal to this + * threshold value will be put into the list of slow queries when slow query tracking is enabled. The + * value for slowQueryThreshold is specified in seconds. + */ + public void setSlowQueryThreshold(final Long slowQueryThreshold) { + this.slowQueryThreshold = slowQueryThreshold; + } - /** - * @return The maximum query string length to keep in the list of queries. Query strings can have arbitrary lengths, - * and this property can be used to save memory in case very long query strings are used. The value is - * specified in bytes. - */ - public Long getMaxQueryStringLength() { - return maxQueryStringLength; - } + /** + * @return The maximum query string length to keep in the list of queries. Query strings can have arbitrary lengths, + * and this property can be used to save memory in case very long query strings are used. The value is + * specified in bytes. + */ + public Long getMaxQueryStringLength() { + return maxQueryStringLength; + } - /** - * @param maxQueryStringLength - * The maximum query string length to keep in the list of queries. Query strings can have arbitrary - * lengths, and this property can be used to save memory in case very long query strings are used. The - * value is specified in bytes. - */ - public void setMaxQueryStringLength(final Long maxQueryStringLength) { - this.maxQueryStringLength = maxQueryStringLength; - } + /** + * @param maxQueryStringLength The maximum query string length to keep in the list of queries. Query strings can have arbitrary + * lengths, and this property can be used to save memory in case very long query strings are used. The + * value is specified in bytes. + */ + public void setMaxQueryStringLength(final Long maxQueryStringLength) { + this.maxQueryStringLength = maxQueryStringLength; + } } diff --git a/src/main/java/com/arangodb/entity/ReplicationFactor.java b/src/main/java/com/arangodb/entity/ReplicationFactor.java index ad329f1ca..b228f3f66 100644 --- a/src/main/java/com/arangodb/entity/ReplicationFactor.java +++ b/src/main/java/com/arangodb/entity/ReplicationFactor.java @@ -22,31 +22,30 @@ /** * @author Mark Vollmary - * */ public class ReplicationFactor { - private Integer replicationFactor; - private Boolean satellite; + private Integer replicationFactor; + private Boolean satellite; - public ReplicationFactor() { - super(); - } + public ReplicationFactor() { + super(); + } - public Integer getReplicationFactor() { - return replicationFactor; - } + public Integer getReplicationFactor() { + return replicationFactor; + } - public void setReplicationFactor(final Integer replicationFactor) { - this.replicationFactor = replicationFactor; - } + public void setReplicationFactor(final Integer replicationFactor) { + this.replicationFactor = replicationFactor; + } - public Boolean getSatellite() { - return satellite; - } + public Boolean getSatellite() { + return satellite; + } - public void setSatellite(final Boolean satellite) { - this.satellite = satellite; - } + public void setSatellite(final Boolean satellite) { + this.satellite = satellite; + } } diff --git a/src/main/java/com/arangodb/entity/ServerMode.java b/src/main/java/com/arangodb/entity/ServerMode.java index 2072cb064..b7f95040c 100644 --- a/src/main/java/com/arangodb/entity/ServerMode.java +++ b/src/main/java/com/arangodb/entity/ServerMode.java @@ -22,8 +22,7 @@ /** * @author Mark Vollmary - * */ public enum ServerMode { - DEFAULT, RESILIENT + DEFAULT, RESILIENT } diff --git a/src/main/java/com/arangodb/entity/ServerRole.java b/src/main/java/com/arangodb/entity/ServerRole.java index 276ac6ef4..71e1b7473 100644 --- a/src/main/java/com/arangodb/entity/ServerRole.java +++ b/src/main/java/com/arangodb/entity/ServerRole.java @@ -22,8 +22,7 @@ /** * @author Mark Vollmary - * */ public enum ServerRole { - SINGLE, AGENT, COORDINATOR, PRIMARY, SECONDARY, UNDEFINED + SINGLE, AGENT, COORDINATOR, PRIMARY, SECONDARY, UNDEFINED } \ No newline at end of file diff --git a/src/main/java/com/arangodb/entity/ShardEntity.java b/src/main/java/com/arangodb/entity/ShardEntity.java index 01b2c4fe5..deeb49db3 100644 --- a/src/main/java/com/arangodb/entity/ShardEntity.java +++ b/src/main/java/com/arangodb/entity/ShardEntity.java @@ -25,14 +25,14 @@ */ public class ShardEntity implements Entity { - private String shardId; + private String shardId; - public ShardEntity() { - super(); - } + public ShardEntity() { + super(); + } - public String getShardId() { - return shardId; - } + public String getShardId() { + return shardId; + } } diff --git a/src/main/java/com/arangodb/entity/ShardingStrategy.java b/src/main/java/com/arangodb/entity/ShardingStrategy.java index dc0f4d441..a75e3b74d 100644 --- a/src/main/java/com/arangodb/entity/ShardingStrategy.java +++ b/src/main/java/com/arangodb/entity/ShardingStrategy.java @@ -25,21 +25,21 @@ * https://www.arangodb.com/docs/stable/http/collection-creating.html */ public enum ShardingStrategy { - - COMMUNITY_COMPAT("community-compat"), - ENTERPRISE_COMPAT("enterprise-compat"), - ENTERPRISE_SMART_EDGE_COMPAT("enterprise-smart-edge-compat"), - HASH("hash"), - ENTERPRISE_HASH_SMART_EDGE("enterprise-hash-smart-edge"); - private final String internalName; + COMMUNITY_COMPAT("community-compat"), + ENTERPRISE_COMPAT("enterprise-compat"), + ENTERPRISE_SMART_EDGE_COMPAT("enterprise-smart-edge-compat"), + HASH("hash"), + ENTERPRISE_HASH_SMART_EDGE("enterprise-hash-smart-edge"); - ShardingStrategy(String internalName) { - this.internalName = internalName; - } - - public String getInternalName() { - return this.internalName; - } + private final String internalName; + + ShardingStrategy(String internalName) { + this.internalName = internalName; + } + + public String getInternalName() { + return this.internalName; + } } diff --git a/src/main/java/com/arangodb/entity/StreamTransactionEntity.java b/src/main/java/com/arangodb/entity/StreamTransactionEntity.java index 5ebf0adf3..b7fee3817 100644 --- a/src/main/java/com/arangodb/entity/StreamTransactionEntity.java +++ b/src/main/java/com/arangodb/entity/StreamTransactionEntity.java @@ -28,15 +28,15 @@ */ public class StreamTransactionEntity implements Entity { - private String id; - private StreamTransactionStatus status; + private String id; + private StreamTransactionStatus status; - public String getId() { - return id; - } + public String getId() { + return id; + } - public StreamTransactionStatus getStatus() { - return status; - } + public StreamTransactionStatus getStatus() { + return status; + } } diff --git a/src/main/java/com/arangodb/entity/StreamTransactionStatus.java b/src/main/java/com/arangodb/entity/StreamTransactionStatus.java index fc8ce7b0b..f03de5da5 100644 --- a/src/main/java/com/arangodb/entity/StreamTransactionStatus.java +++ b/src/main/java/com/arangodb/entity/StreamTransactionStatus.java @@ -24,5 +24,5 @@ * @author Michele Rastelli */ public enum StreamTransactionStatus { - running, committed, aborted + running, committed, aborted } diff --git a/src/main/java/com/arangodb/entity/TransactionEntity.java b/src/main/java/com/arangodb/entity/TransactionEntity.java index 333a1e538..a700541f2 100644 --- a/src/main/java/com/arangodb/entity/TransactionEntity.java +++ b/src/main/java/com/arangodb/entity/TransactionEntity.java @@ -28,15 +28,15 @@ */ public class TransactionEntity implements Entity { - private String id; - private StreamTransactionStatus state; + private String id; + private StreamTransactionStatus state; - public String getId() { - return id; - } + public String getId() { + return id; + } - public StreamTransactionStatus getStatus() { - return state; - } + public StreamTransactionStatus getStatus() { + return state; + } } diff --git a/src/main/java/com/arangodb/entity/TraversalEntity.java b/src/main/java/com/arangodb/entity/TraversalEntity.java index 77e231046..4dd679281 100644 --- a/src/main/java/com/arangodb/entity/TraversalEntity.java +++ b/src/main/java/com/arangodb/entity/TraversalEntity.java @@ -24,33 +24,32 @@ /** * @author Mark Vollmary - * * @see API - * Documentation + * Documentation */ public class TraversalEntity implements Entity { - private Collection vertices; - private Collection> paths; + private Collection vertices; + private Collection> paths; - public TraversalEntity() { - super(); - } + public TraversalEntity() { + super(); + } - public Collection getVertices() { - return vertices; - } + public Collection getVertices() { + return vertices; + } - public void setVertices(final Collection vertices) { - this.vertices = vertices; - } + public void setVertices(final Collection vertices) { + this.vertices = vertices; + } - public Collection> getPaths() { - return paths; - } + public Collection> getPaths() { + return paths; + } - public void setPaths(final Collection> paths) { - this.paths = paths; - } + public void setPaths(final Collection> paths) { + this.paths = paths; + } } diff --git a/src/main/java/com/arangodb/entity/UserEntity.java b/src/main/java/com/arangodb/entity/UserEntity.java index 87a302eb7..fa082c5c7 100644 --- a/src/main/java/com/arangodb/entity/UserEntity.java +++ b/src/main/java/com/arangodb/entity/UserEntity.java @@ -24,39 +24,38 @@ /** * @author Mark Vollmary - * * @see API Documentation */ public class UserEntity implements Entity { - private String user; - private Boolean active; - private Map extra; - private Boolean changePassword; - - /** - * @return The name of the user as a string - */ - public String getUser() { - return user; - } - - /** - * @return An flag that specifies whether the user is active - */ - public Boolean getActive() { - return active; - } - - /** - * @return An object with arbitrary extra data about the user - */ - public Map getExtra() { - return extra; - } - - public Boolean getChangePassword() { - return changePassword; - } + private String user; + private Boolean active; + private Map extra; + private Boolean changePassword; + + /** + * @return The name of the user as a string + */ + public String getUser() { + return user; + } + + /** + * @return An flag that specifies whether the user is active + */ + public Boolean getActive() { + return active; + } + + /** + * @return An object with arbitrary extra data about the user + */ + public Map getExtra() { + return extra; + } + + public Boolean getChangePassword() { + return changePassword; + } } diff --git a/src/main/java/com/arangodb/entity/VertexEntity.java b/src/main/java/com/arangodb/entity/VertexEntity.java index 77e24983f..161ed9fd4 100644 --- a/src/main/java/com/arangodb/entity/VertexEntity.java +++ b/src/main/java/com/arangodb/entity/VertexEntity.java @@ -22,12 +22,11 @@ /** * @author Mark Vollmary - * */ public class VertexEntity extends DocumentEntity { - public VertexEntity() { - super(); - } + public VertexEntity() { + super(); + } } diff --git a/src/main/java/com/arangodb/entity/VertexUpdateEntity.java b/src/main/java/com/arangodb/entity/VertexUpdateEntity.java index 4d722af97..22d2d1078 100644 --- a/src/main/java/com/arangodb/entity/VertexUpdateEntity.java +++ b/src/main/java/com/arangodb/entity/VertexUpdateEntity.java @@ -24,19 +24,18 @@ /** * @author Mark Vollmary - * */ public class VertexUpdateEntity extends DocumentEntity { - @SerializedName("_oldRev") - private String oldRev; + @SerializedName("_oldRev") + private String oldRev; - public VertexUpdateEntity() { - super(); - } + public VertexUpdateEntity() { + super(); + } - public String getOldRev() { - return oldRev; - } + public String getOldRev() { + return oldRev; + } } diff --git a/src/main/java/com/arangodb/entity/ViewEntity.java b/src/main/java/com/arangodb/entity/ViewEntity.java index 37d115f57..07da45f88 100644 --- a/src/main/java/com/arangodb/entity/ViewEntity.java +++ b/src/main/java/com/arangodb/entity/ViewEntity.java @@ -22,35 +22,34 @@ /** * @author Mark Vollmary - * */ public class ViewEntity implements Entity { - private String id; - private String name; - private ViewType type; + private String id; + private String name; + private ViewType type; - public ViewEntity() { - super(); - } + public ViewEntity() { + super(); + } - public ViewEntity(final String id, final String name, final ViewType type) { - super(); - this.id = id; - this.name = name; - this.type = type; - } + public ViewEntity(final String id, final String name, final ViewType type) { + super(); + this.id = id; + this.name = name; + this.type = type; + } - public String getId() { - return id; - } + public String getId() { + return id; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public ViewType getType() { - return type; - } + public ViewType getType() { + return type; + } } diff --git a/src/main/java/com/arangodb/entity/ViewType.java b/src/main/java/com/arangodb/entity/ViewType.java index 77397291d..21c039906 100644 --- a/src/main/java/com/arangodb/entity/ViewType.java +++ b/src/main/java/com/arangodb/entity/ViewType.java @@ -22,10 +22,9 @@ /** * @author Mark Vollmary - * */ public enum ViewType { - ARANGO_SEARCH + ARANGO_SEARCH } diff --git a/src/main/java/com/arangodb/entity/arangosearch/AnalyzerEntity.java b/src/main/java/com/arangodb/entity/arangosearch/AnalyzerEntity.java index 71c7e358b..1d82d5fed 100644 --- a/src/main/java/com/arangodb/entity/arangosearch/AnalyzerEntity.java +++ b/src/main/java/com/arangodb/entity/arangosearch/AnalyzerEntity.java @@ -28,44 +28,44 @@ */ public class AnalyzerEntity { - private Set features; - private AnalyzerType type; - private String name; - private Map properties; + private Set features; + private AnalyzerType type; + private String name; + private Map properties; - public AnalyzerEntity() { - } + public AnalyzerEntity() { + } - public Set getFeatures() { - return features; - } + public Set getFeatures() { + return features; + } - public void setFeatures(Set features) { - this.features = features; - } + public void setFeatures(Set features) { + this.features = features; + } - public AnalyzerType getType() { - return type; - } + public AnalyzerType getType() { + return type; + } - public void setType(AnalyzerType type) { - this.type = type; - } + public void setType(AnalyzerType type) { + this.type = type; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public Map getProperties() { - return properties; - } + public Map getProperties() { + return properties; + } - public void setProperties(Map properties) { - this.properties = properties; - } + public void setProperties(Map properties) { + this.properties = properties; + } } diff --git a/src/main/java/com/arangodb/entity/arangosearch/AnalyzerFeature.java b/src/main/java/com/arangodb/entity/arangosearch/AnalyzerFeature.java index 1b40357bb..b61c16eaa 100644 --- a/src/main/java/com/arangodb/entity/arangosearch/AnalyzerFeature.java +++ b/src/main/java/com/arangodb/entity/arangosearch/AnalyzerFeature.java @@ -24,5 +24,5 @@ * @author Michele Rastelli */ public enum AnalyzerFeature { - frequency, norm, position + frequency, norm, position } diff --git a/src/main/java/com/arangodb/entity/arangosearch/AnalyzerType.java b/src/main/java/com/arangodb/entity/arangosearch/AnalyzerType.java index 5b6d1d1db..de2d76e4e 100644 --- a/src/main/java/com/arangodb/entity/arangosearch/AnalyzerType.java +++ b/src/main/java/com/arangodb/entity/arangosearch/AnalyzerType.java @@ -24,5 +24,5 @@ * @author Michele Rastelli */ public enum AnalyzerType { - identity, delimiter, stem, norm, ngram, text + identity, delimiter, stem, norm, ngram, text } diff --git a/src/main/java/com/arangodb/entity/arangosearch/ArangoSearchProperties.java b/src/main/java/com/arangodb/entity/arangosearch/ArangoSearchProperties.java index e6ef631f0..135c50de2 100644 --- a/src/main/java/com/arangodb/entity/arangosearch/ArangoSearchProperties.java +++ b/src/main/java/com/arangodb/entity/arangosearch/ArangoSearchProperties.java @@ -27,68 +27,67 @@ /** * @author Mark Vollmary * @author Heiko Kernbach - * */ public class ArangoSearchProperties { - private Long consolidationIntervalMsec; - private Long commitIntervalMsec; - private Long cleanupIntervalStep; - private ConsolidationPolicy consolidationPolicy; - private final Collection primarySorts; - private final Collection links; - - public ArangoSearchProperties() { - super(); - links = new ArrayList<>(); - primarySorts = new ArrayList<>(); - } - - public Long getCommitIntervalMsec() { - return commitIntervalMsec; - } - - public void setCommitIntervalMsec(final Long commitIntervalMsec) { - this.commitIntervalMsec = commitIntervalMsec; - } - - public Long getConsolidationIntervalMsec() { - return consolidationIntervalMsec; - } - - public void setConsolidationIntervalMsec(final Long consolidationIntervalMsec) { - this.consolidationIntervalMsec = consolidationIntervalMsec; - } - - public Long getCleanupIntervalStep() { - return cleanupIntervalStep; - } - - public void setCleanupIntervalStep(final Long cleanupIntervalStep) { - this.cleanupIntervalStep = cleanupIntervalStep; - } - - public ConsolidationPolicy getConsolidationPolicy() { - return consolidationPolicy; - } - - public void setConsolidationPolicy(final ConsolidationPolicy consolidationPolicy) { - this.consolidationPolicy = consolidationPolicy; - } - - public Collection getLinks() { - return links; - } - - public void addLink(final CollectionLink... links) { - this.links.addAll(Arrays.asList(links)); - } - - public Collection getPrimarySort() { - return primarySorts; - } - - public void addPrimarySort(final PrimarySort... primarySorts) { - this.primarySorts.addAll(Arrays.asList(primarySorts)); - } + private Long consolidationIntervalMsec; + private Long commitIntervalMsec; + private Long cleanupIntervalStep; + private ConsolidationPolicy consolidationPolicy; + private final Collection primarySorts; + private final Collection links; + + public ArangoSearchProperties() { + super(); + links = new ArrayList<>(); + primarySorts = new ArrayList<>(); + } + + public Long getCommitIntervalMsec() { + return commitIntervalMsec; + } + + public void setCommitIntervalMsec(final Long commitIntervalMsec) { + this.commitIntervalMsec = commitIntervalMsec; + } + + public Long getConsolidationIntervalMsec() { + return consolidationIntervalMsec; + } + + public void setConsolidationIntervalMsec(final Long consolidationIntervalMsec) { + this.consolidationIntervalMsec = consolidationIntervalMsec; + } + + public Long getCleanupIntervalStep() { + return cleanupIntervalStep; + } + + public void setCleanupIntervalStep(final Long cleanupIntervalStep) { + this.cleanupIntervalStep = cleanupIntervalStep; + } + + public ConsolidationPolicy getConsolidationPolicy() { + return consolidationPolicy; + } + + public void setConsolidationPolicy(final ConsolidationPolicy consolidationPolicy) { + this.consolidationPolicy = consolidationPolicy; + } + + public Collection getLinks() { + return links; + } + + public void addLink(final CollectionLink... links) { + this.links.addAll(Arrays.asList(links)); + } + + public Collection getPrimarySort() { + return primarySorts; + } + + public void addPrimarySort(final PrimarySort... primarySorts) { + this.primarySorts.addAll(Arrays.asList(primarySorts)); + } } diff --git a/src/main/java/com/arangodb/entity/arangosearch/ArangoSearchPropertiesEntity.java b/src/main/java/com/arangodb/entity/arangosearch/ArangoSearchPropertiesEntity.java index dd8b9f634..82e8097fc 100644 --- a/src/main/java/com/arangodb/entity/arangosearch/ArangoSearchPropertiesEntity.java +++ b/src/main/java/com/arangodb/entity/arangosearch/ArangoSearchPropertiesEntity.java @@ -20,11 +20,11 @@ package com.arangodb.entity.arangosearch; -import java.util.Collection; - import com.arangodb.entity.ViewEntity; import com.arangodb.entity.ViewType; +import java.util.Collection; + /** * @author Mark Vollmary */ diff --git a/src/main/java/com/arangodb/entity/arangosearch/CollectionLink.java b/src/main/java/com/arangodb/entity/arangosearch/CollectionLink.java index 78bcd5250..adf57d9da 100644 --- a/src/main/java/com/arangodb/entity/arangosearch/CollectionLink.java +++ b/src/main/java/com/arangodb/entity/arangosearch/CollectionLink.java @@ -26,109 +26,102 @@ /** * @author Mark Vollmary - * */ public class CollectionLink { - private final String name; - private final Collection analyzers; - private Boolean includeAllFields; - private Boolean trackListPositions; - private StoreValuesType storeValues; - private final Collection fields; + private final String name; + private final Collection analyzers; + private Boolean includeAllFields; + private Boolean trackListPositions; + private StoreValuesType storeValues; + private final Collection fields; - private CollectionLink(final String name) { - super(); - this.name = name; + private CollectionLink(final String name) { + super(); + this.name = name; fields = new ArrayList<>(); analyzers = new ArrayList<>(); - } - - /** - * Creates an instance of {@code CollectionLink} on the given collection name - * - * @param name - * Name of a collection - * @return new instance of {@code CollectionLink} - */ - public static CollectionLink on(final String name) { - return new CollectionLink(name); - } - - /** - * @param analyzers - * The list of analyzers to be used for indexing of string values (default: ["identity"]). - * @return link - */ - public CollectionLink analyzers(final String... analyzers) { - this.analyzers.addAll(Arrays.asList(analyzers)); - return this; - } - - /** - * @param includeAllFields - * The flag determines whether or not to index all fields on a particular level of depth (default: - * false). - * @return link - */ - public CollectionLink includeAllFields(final Boolean includeAllFields) { - this.includeAllFields = includeAllFields; - return this; - } - - /** - * @param trackListPositions - * The flag determines whether or not values in a lists should be treated separate (default: false). - * @return link - */ - public CollectionLink trackListPositions(final Boolean trackListPositions) { - this.trackListPositions = trackListPositions; - return this; - } - - /** - * @param storeValues - * How should the view track the attribute values, this setting allows for additional value retrieval - * optimizations (default "none"). - * @return link - */ - public CollectionLink storeValues(final StoreValuesType storeValues) { - this.storeValues = storeValues; - return this; - } - - /** - * @param fields - * A list of linked fields - * @return link - */ - public CollectionLink fields(final FieldLink... fields) { - this.fields.addAll(Arrays.asList(fields)); - return this; - } - - public String getName() { - return name; - } - - public Collection getAnalyzers() { - return analyzers; - } - - public Boolean getIncludeAllFields() { - return includeAllFields; - } - - public Boolean getTrackListPositions() { - return trackListPositions; - } - - public StoreValuesType getStoreValues() { - return storeValues; - } - - public Collection getFields() { - return fields; - } + } + + /** + * Creates an instance of {@code CollectionLink} on the given collection name + * + * @param name Name of a collection + * @return new instance of {@code CollectionLink} + */ + public static CollectionLink on(final String name) { + return new CollectionLink(name); + } + + /** + * @param analyzers The list of analyzers to be used for indexing of string values (default: ["identity"]). + * @return link + */ + public CollectionLink analyzers(final String... analyzers) { + this.analyzers.addAll(Arrays.asList(analyzers)); + return this; + } + + /** + * @param includeAllFields The flag determines whether or not to index all fields on a particular level of depth (default: + * false). + * @return link + */ + public CollectionLink includeAllFields(final Boolean includeAllFields) { + this.includeAllFields = includeAllFields; + return this; + } + + /** + * @param trackListPositions The flag determines whether or not values in a lists should be treated separate (default: false). + * @return link + */ + public CollectionLink trackListPositions(final Boolean trackListPositions) { + this.trackListPositions = trackListPositions; + return this; + } + + /** + * @param storeValues How should the view track the attribute values, this setting allows for additional value retrieval + * optimizations (default "none"). + * @return link + */ + public CollectionLink storeValues(final StoreValuesType storeValues) { + this.storeValues = storeValues; + return this; + } + + /** + * @param fields A list of linked fields + * @return link + */ + public CollectionLink fields(final FieldLink... fields) { + this.fields.addAll(Arrays.asList(fields)); + return this; + } + + public String getName() { + return name; + } + + public Collection getAnalyzers() { + return analyzers; + } + + public Boolean getIncludeAllFields() { + return includeAllFields; + } + + public Boolean getTrackListPositions() { + return trackListPositions; + } + + public StoreValuesType getStoreValues() { + return storeValues; + } + + public Collection getFields() { + return fields; + } } \ No newline at end of file diff --git a/src/main/java/com/arangodb/entity/arangosearch/ConsolidationPolicy.java b/src/main/java/com/arangodb/entity/arangosearch/ConsolidationPolicy.java index 08ed9f9d4..ddb21911c 100644 --- a/src/main/java/com/arangodb/entity/arangosearch/ConsolidationPolicy.java +++ b/src/main/java/com/arangodb/entity/arangosearch/ConsolidationPolicy.java @@ -22,55 +22,52 @@ /** * @author Mark Vollmary - * */ public class ConsolidationPolicy { - private final ConsolidationType type; - private Double threshold; - private Long segmentThreshold; + private final ConsolidationType type; + private Double threshold; + private Long segmentThreshold; - private ConsolidationPolicy(final ConsolidationType type) { - super(); - this.type = type; - } + private ConsolidationPolicy(final ConsolidationType type) { + super(); + this.type = type; + } - public static ConsolidationPolicy of(final ConsolidationType type) { - return new ConsolidationPolicy(type); - } + public static ConsolidationPolicy of(final ConsolidationType type) { + return new ConsolidationPolicy(type); + } - /** - * @param threshold - * Select a given segment for "consolidation" if and only if the formula based on type (as defined above) - * evaluates to true, valid value range [0.0, 1.0] (default: 0.85) - * @return policy - */ - public ConsolidationPolicy threshold(final Double threshold) { - this.threshold = threshold; - return this; - } + /** + * @param threshold Select a given segment for "consolidation" if and only if the formula based on type (as defined above) + * evaluates to true, valid value range [0.0, 1.0] (default: 0.85) + * @return policy + */ + public ConsolidationPolicy threshold(final Double threshold) { + this.threshold = threshold; + return this; + } - /** - * @param segmentThreshold - * Apply the "consolidation" operation if and only if (default: 300): {segmentThreshold} < - * number_of_segments - * @return policy - */ - public ConsolidationPolicy segmentThreshold(final Long segmentThreshold) { - this.segmentThreshold = segmentThreshold; - return this; - } + /** + * @param segmentThreshold Apply the "consolidation" operation if and only if (default: 300): {segmentThreshold} < + * number_of_segments + * @return policy + */ + public ConsolidationPolicy segmentThreshold(final Long segmentThreshold) { + this.segmentThreshold = segmentThreshold; + return this; + } - public ConsolidationType getType() { - return type; - } + public ConsolidationType getType() { + return type; + } - public Double getThreshold() { - return threshold; - } + public Double getThreshold() { + return threshold; + } - public Long getSegmentThreshold() { - return segmentThreshold; - } + public Long getSegmentThreshold() { + return segmentThreshold; + } } diff --git a/src/main/java/com/arangodb/entity/arangosearch/ConsolidationType.java b/src/main/java/com/arangodb/entity/arangosearch/ConsolidationType.java index 81f7f3c5e..978a6a0d5 100644 --- a/src/main/java/com/arangodb/entity/arangosearch/ConsolidationType.java +++ b/src/main/java/com/arangodb/entity/arangosearch/ConsolidationType.java @@ -2,6 +2,6 @@ public enum ConsolidationType { - BYTES_ACCUM, TIER + BYTES_ACCUM, TIER } \ No newline at end of file diff --git a/src/main/java/com/arangodb/entity/arangosearch/FieldLink.java b/src/main/java/com/arangodb/entity/arangosearch/FieldLink.java index de3acf967..d6bf26381 100644 --- a/src/main/java/com/arangodb/entity/arangosearch/FieldLink.java +++ b/src/main/java/com/arangodb/entity/arangosearch/FieldLink.java @@ -6,105 +6,99 @@ public class FieldLink { - private final String name; - private final Collection analyzers; - private Boolean includeAllFields; - private Boolean trackListPositions; - private StoreValuesType storeValues; - private final Collection fields; - - private FieldLink(final String name) { - super(); - this.name = name; + private final String name; + private final Collection analyzers; + private Boolean includeAllFields; + private Boolean trackListPositions; + private StoreValuesType storeValues; + private final Collection fields; + + private FieldLink(final String name) { + super(); + this.name = name; fields = new ArrayList<>(); analyzers = new ArrayList<>(); - } - - /** - * Creates an instance of {@code FieldLink} on the given field name - * - * @param name - * Name of a field - * @return new instance of {@code FieldLink} - */ - public static FieldLink on(final String name) { - return new FieldLink(name); - } - - /** - * @param analyzers - * The list of analyzers to be used for indexing of string values (default: ["identity"]). - * @return link - */ - public FieldLink analyzers(final String... analyzers) { - this.analyzers.addAll(Arrays.asList(analyzers)); - return this; - } - - /** - * @param includeAllFields - * The flag determines whether or not to index all fields on a particular level of depth (default: - * false). - * @return link - */ - public FieldLink includeAllFields(final Boolean includeAllFields) { - this.includeAllFields = includeAllFields; - return this; - } - - /** - * @param trackListPositions - * The flag determines whether or not values in a lists should be treated separate (default: false). - * @return link - */ - public FieldLink trackListPositions(final Boolean trackListPositions) { - this.trackListPositions = trackListPositions; - return this; - } - - /** - * @param storeValues - * How should the view track the attribute values, this setting allows for additional value retrieval - * optimizations (default "none"). - * @return link - */ - public FieldLink storeValues(final StoreValuesType storeValues) { - this.storeValues = storeValues; - return this; - } - - /** - * @param fields - * A list of linked fields - * @return link - */ - public FieldLink fields(final FieldLink... fields) { - this.fields.addAll(Arrays.asList(fields)); - return this; - } - - public String getName() { - return name; - } - - public Collection getAnalyzers() { - return analyzers; - } - - public Boolean getIncludeAllFields() { - return includeAllFields; - } - - public Boolean getTrackListPositions() { - return trackListPositions; - } - - public StoreValuesType getStoreValues() { - return storeValues; - } - - public Collection getFields() { - return fields; - } + } + + /** + * Creates an instance of {@code FieldLink} on the given field name + * + * @param name Name of a field + * @return new instance of {@code FieldLink} + */ + public static FieldLink on(final String name) { + return new FieldLink(name); + } + + /** + * @param analyzers The list of analyzers to be used for indexing of string values (default: ["identity"]). + * @return link + */ + public FieldLink analyzers(final String... analyzers) { + this.analyzers.addAll(Arrays.asList(analyzers)); + return this; + } + + /** + * @param includeAllFields The flag determines whether or not to index all fields on a particular level of depth (default: + * false). + * @return link + */ + public FieldLink includeAllFields(final Boolean includeAllFields) { + this.includeAllFields = includeAllFields; + return this; + } + + /** + * @param trackListPositions The flag determines whether or not values in a lists should be treated separate (default: false). + * @return link + */ + public FieldLink trackListPositions(final Boolean trackListPositions) { + this.trackListPositions = trackListPositions; + return this; + } + + /** + * @param storeValues How should the view track the attribute values, this setting allows for additional value retrieval + * optimizations (default "none"). + * @return link + */ + public FieldLink storeValues(final StoreValuesType storeValues) { + this.storeValues = storeValues; + return this; + } + + /** + * @param fields A list of linked fields + * @return link + */ + public FieldLink fields(final FieldLink... fields) { + this.fields.addAll(Arrays.asList(fields)); + return this; + } + + public String getName() { + return name; + } + + public Collection getAnalyzers() { + return analyzers; + } + + public Boolean getIncludeAllFields() { + return includeAllFields; + } + + public Boolean getTrackListPositions() { + return trackListPositions; + } + + public StoreValuesType getStoreValues() { + return storeValues; + } + + public Collection getFields() { + return fields; + } } \ No newline at end of file diff --git a/src/main/java/com/arangodb/entity/arangosearch/PrimarySort.java b/src/main/java/com/arangodb/entity/arangosearch/PrimarySort.java index 60df3c67e..32c3a34a3 100644 --- a/src/main/java/com/arangodb/entity/arangosearch/PrimarySort.java +++ b/src/main/java/com/arangodb/entity/arangosearch/PrimarySort.java @@ -22,36 +22,35 @@ /** * @author Heiko Kernbach - * */ public class PrimarySort { - private final String fieldName; - private Boolean ascending; - - private PrimarySort(final String fieldName) { - super(); - this.fieldName = fieldName; - } - - public static PrimarySort on(final String fieldName) { - return new PrimarySort(fieldName); - } - - /** - * @param ascending - * @return primarySort - */ - public PrimarySort ascending(final Boolean ascending) { - this.ascending = ascending; - return this; - } - - public Boolean getAscending() { - return ascending; - } - - public String getFieldName() { - return fieldName; - } + private final String fieldName; + private Boolean ascending; + + private PrimarySort(final String fieldName) { + super(); + this.fieldName = fieldName; + } + + public static PrimarySort on(final String fieldName) { + return new PrimarySort(fieldName); + } + + /** + * @param ascending + * @return primarySort + */ + public PrimarySort ascending(final Boolean ascending) { + this.ascending = ascending; + return this; + } + + public Boolean getAscending() { + return ascending; + } + + public String getFieldName() { + return fieldName; + } } diff --git a/src/main/java/com/arangodb/entity/arangosearch/StoreValuesType.java b/src/main/java/com/arangodb/entity/arangosearch/StoreValuesType.java index e879564fc..3630e903a 100644 --- a/src/main/java/com/arangodb/entity/arangosearch/StoreValuesType.java +++ b/src/main/java/com/arangodb/entity/arangosearch/StoreValuesType.java @@ -22,18 +22,17 @@ /** * @author Mark Vollmary - * */ public enum StoreValuesType { - /** - * Do not track values by the view - */ - NONE, + /** + * Do not track values by the view + */ + NONE, - /** - * Track only value presence, to allow use of the EXISTS() function. - */ - ID + /** + * Track only value presence, to allow use of the EXISTS() function. + */ + ID } diff --git a/src/main/java/com/arangodb/internal/ArangoCollectionImpl.java b/src/main/java/com/arangodb/internal/ArangoCollectionImpl.java index ff8c82755..1fd8fddcc 100644 --- a/src/main/java/com/arangodb/internal/ArangoCollectionImpl.java +++ b/src/main/java/com/arangodb/internal/ArangoCollectionImpl.java @@ -20,389 +20,388 @@ package com.arangodb.internal; -import java.util.Collection; - -import com.arangodb.entity.*; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.arangodb.model.*; import com.arangodb.ArangoCollection; import com.arangodb.ArangoDBException; +import com.arangodb.entity.*; import com.arangodb.internal.util.DocumentUtil; +import com.arangodb.model.*; import com.arangodb.velocypack.VPackSlice; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.Collection; /** * @author Mark Vollmary * @author Michele Rastelli */ public class ArangoCollectionImpl extends InternalArangoCollection - implements ArangoCollection { - - private static final Logger LOGGER = LoggerFactory.getLogger(ArangoCollection.class); - - protected ArangoCollectionImpl(final ArangoDatabaseImpl db, final String name) { - super(db, name); - } - - @Override - public DocumentCreateEntity insertDocument(final T value) throws ArangoDBException { - return insertDocument(value, new DocumentCreateOptions()); - } - - @Override - public DocumentCreateEntity insertDocument(final T value, final DocumentCreateOptions options) - throws ArangoDBException { - return executor - .execute(insertDocumentRequest(value, options), insertDocumentResponseDeserializer(value, options)); - } - - @Override - public MultiDocumentEntity> insertDocuments(final Collection values) - throws ArangoDBException { - return insertDocuments(values, new DocumentCreateOptions()); - } - - @Override - public MultiDocumentEntity> insertDocuments( - final Collection values, final DocumentCreateOptions options) throws ArangoDBException { - final DocumentCreateOptions params = (options != null ? options : new DocumentCreateOptions()); - return executor - .execute(insertDocumentsRequest(values, params), insertDocumentsResponseDeserializer(values, params)); - } - - @Override - public DocumentImportEntity importDocuments(final Collection values) throws ArangoDBException { - return importDocuments(values, new DocumentImportOptions()); - } - - @Override - public DocumentImportEntity importDocuments(final Collection values, final DocumentImportOptions options) - throws ArangoDBException { - return executor.execute(importDocumentsRequest(values, options), DocumentImportEntity.class); - } - - @Override - public DocumentImportEntity importDocuments(final String values) throws ArangoDBException { - return importDocuments(values, new DocumentImportOptions()); - } - - @Override - public DocumentImportEntity importDocuments(final String values, final DocumentImportOptions options) - throws ArangoDBException { - return executor.execute(importDocumentsRequest(values, options), DocumentImportEntity.class); - } - - @Override - public T getDocument(final String key, final Class type) throws ArangoDBException { - return getDocument(key, type, new DocumentReadOptions()); - } - - @Override - public T getDocument(final String key, final Class type, final DocumentReadOptions options) - throws ArangoDBException { - DocumentUtil.validateDocumentKey(key); - try { - return executor.execute(getDocumentRequest(key, options), type); - } catch (final ArangoDBException e) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug(e.getMessage(), e); - } - - // handle Response: 404, Error: 1655 - transaction not found - if (e.getErrorNum() != null && e.getErrorNum() == 1655) { - throw e; - } - - if ((e.getResponseCode() != null && (e.getResponseCode() == 404 || e.getResponseCode() == 304 - || e.getResponseCode() == 412)) && (options == null || options.isCatchException())) { - return null; - } - throw e; - } - } - - @Override - public MultiDocumentEntity getDocuments(final Collection keys, final Class type) - throws ArangoDBException { - return getDocuments(keys, type, new DocumentReadOptions()); - } - - @Override - public MultiDocumentEntity getDocuments( - final Collection keys, final Class type, final DocumentReadOptions options) - throws ArangoDBException { - return executor.execute(getDocumentsRequest(keys, options), getDocumentsResponseDeserializer(type, options)); - } - - @Override - public DocumentUpdateEntity replaceDocument(final String key, final T value) throws ArangoDBException { - return replaceDocument(key, value, new DocumentReplaceOptions()); - } - - @Override - public DocumentUpdateEntity replaceDocument( - final String key, final T value, final DocumentReplaceOptions options) throws ArangoDBException { - return executor.execute(replaceDocumentRequest(key, value, options), - replaceDocumentResponseDeserializer(value, options)); - } - - @Override - public MultiDocumentEntity> replaceDocuments(final Collection values) - throws ArangoDBException { - return replaceDocuments(values, new DocumentReplaceOptions()); - } - - @Override - public MultiDocumentEntity> replaceDocuments( - final Collection values, final DocumentReplaceOptions options) throws ArangoDBException { - final DocumentReplaceOptions params = (options != null ? options : new DocumentReplaceOptions()); - return executor - .execute(replaceDocumentsRequest(values, params), replaceDocumentsResponseDeserializer(values, params)); - } - - @Override - public DocumentUpdateEntity updateDocument(final String key, final T value) throws ArangoDBException { - return updateDocument(key, value, new DocumentUpdateOptions()); - } - - @Override - public DocumentUpdateEntity updateDocument( - final String key, final T value, final DocumentUpdateOptions options) throws ArangoDBException { - return executor.execute(updateDocumentRequest(key, value, options), - updateDocumentResponseDeserializer(value, options)); - } - - @Override - public MultiDocumentEntity> updateDocuments(final Collection values) - throws ArangoDBException { - return updateDocuments(values, new DocumentUpdateOptions()); - } - - @Override - public MultiDocumentEntity> updateDocuments( - final Collection values, final DocumentUpdateOptions options) throws ArangoDBException { - final DocumentUpdateOptions params = (options != null ? options : new DocumentUpdateOptions()); - return executor - .execute(updateDocumentsRequest(values, params), updateDocumentsResponseDeserializer(values, params)); - } - - @Override - public DocumentDeleteEntity deleteDocument(final String key) throws ArangoDBException { - return executor.execute(deleteDocumentRequest(key, new DocumentDeleteOptions()), - deleteDocumentResponseDeserializer(Void.class)); - } - - @Override - public DocumentDeleteEntity deleteDocument( - final String key, final Class type, final DocumentDeleteOptions options) throws ArangoDBException { - return executor.execute(deleteDocumentRequest(key, options), deleteDocumentResponseDeserializer(type)); - } - - @Override - public MultiDocumentEntity> deleteDocuments(final Collection values) - throws ArangoDBException { - return executor.execute(deleteDocumentsRequest(values, new DocumentDeleteOptions()), - deleteDocumentsResponseDeserializer(Void.class)); - } - - @Override - public MultiDocumentEntity> deleteDocuments( - final Collection values, final Class type, final DocumentDeleteOptions options) - throws ArangoDBException { - return executor.execute(deleteDocumentsRequest(values, options), deleteDocumentsResponseDeserializer(type)); - } - - @Override - public Boolean documentExists(final String key) { - return documentExists(key, new DocumentExistsOptions()); - } - - @Override - public Boolean documentExists(final String key, final DocumentExistsOptions options) throws ArangoDBException { - try { - executor.execute(documentExistsRequest(key, options), VPackSlice.class); - return true; - } catch (final ArangoDBException e) { - - // handle Response: 404, Error: 1655 - transaction not found - if (e.getErrorNum() != null && e.getErrorNum() == 1655) { - throw e; - } - - if ((e.getResponseCode() != null && (e.getResponseCode() == 404 || e.getResponseCode() == 304 - || e.getResponseCode() == 412)) && (options == null || options.isCatchException())) { - return false; - } - throw e; - } - } - - @Override - public IndexEntity getIndex(final String id) throws ArangoDBException { - return executor.execute(getIndexRequest(id), IndexEntity.class); - } - - @Override - public String deleteIndex(final String id) throws ArangoDBException { - return executor.execute(deleteIndexRequest(id), deleteIndexResponseDeserializer()); - } - - @Override - public IndexEntity ensureHashIndex(final Iterable fields, final HashIndexOptions options) - throws ArangoDBException { - return executor.execute(createHashIndexRequest(fields, options), IndexEntity.class); - } - - @Override - public IndexEntity ensureSkiplistIndex(final Iterable fields, final SkiplistIndexOptions options) - throws ArangoDBException { - return executor.execute(createSkiplistIndexRequest(fields, options), IndexEntity.class); - } - - @Override - public IndexEntity ensurePersistentIndex(final Iterable fields, final PersistentIndexOptions options) - throws ArangoDBException { - return executor.execute(createPersistentIndexRequest(fields, options), IndexEntity.class); - } - - @Override - public IndexEntity ensureGeoIndex(final Iterable fields, final GeoIndexOptions options) - throws ArangoDBException { - return executor.execute(createGeoIndexRequest(fields, options), IndexEntity.class); - } - - @Override - public IndexEntity ensureFulltextIndex(final Iterable fields, final FulltextIndexOptions options) - throws ArangoDBException { - return executor.execute(createFulltextIndexRequest(fields, options), IndexEntity.class); - } - - @Override - public IndexEntity ensureTtlIndex(final Iterable fields, final TtlIndexOptions options) - throws ArangoDBException { - return executor.execute(createTtlIndexRequest(fields, options), IndexEntity.class); - } - - @Override - public Collection getIndexes() throws ArangoDBException { - return executor.execute(getIndexesRequest(), getIndexesResponseDeserializer()); - } - - @Override - public boolean exists() throws ArangoDBException { - try { - getInfo(); - return true; - } catch (final ArangoDBException e) { - if (ArangoErrors.ERROR_ARANGO_DATA_SOURCE_NOT_FOUND.equals(e.getErrorNum())) { - return false; - } - throw e; - } - } - - @Override - public CollectionEntity truncate() throws ArangoDBException { - return truncate(null); - } - - @Override - public CollectionEntity truncate(CollectionTruncateOptions options) throws ArangoDBException { - return executor.execute(truncateRequest(options), CollectionEntity.class); - } - - @Override - public CollectionPropertiesEntity count() throws ArangoDBException { - return count(null); - } - - @Override - public CollectionPropertiesEntity count(CollectionCountOptions options) throws ArangoDBException { - return executor.execute(countRequest(options), CollectionPropertiesEntity.class); - } - - @Override - public CollectionEntity create() throws ArangoDBException { - return db().createCollection(name()); - } - - @Override - public CollectionEntity create(final CollectionCreateOptions options) throws ArangoDBException { - return db().createCollection(name(), options); - } - - @Override - public void drop() throws ArangoDBException { - executor.execute(dropRequest(null), Void.class); - } - - @Override - public void drop(final boolean isSystem) throws ArangoDBException { - executor.execute(dropRequest(isSystem), Void.class); - } - - @Override - public CollectionEntity load() throws ArangoDBException { - return executor.execute(loadRequest(), CollectionEntity.class); - } - - @Override - public CollectionEntity unload() throws ArangoDBException { - return executor.execute(unloadRequest(), CollectionEntity.class); - } - - @Override - public CollectionEntity getInfo() throws ArangoDBException { - return executor.execute(getInfoRequest(), CollectionEntity.class); - } - - @Override - public CollectionPropertiesEntity getProperties() throws ArangoDBException { - return executor.execute(getPropertiesRequest(), CollectionPropertiesEntity.class); - } - - @Override - public CollectionPropertiesEntity changeProperties(final CollectionPropertiesOptions options) - throws ArangoDBException { - return executor.execute(changePropertiesRequest(options), CollectionPropertiesEntity.class); - } - - @Override - public synchronized CollectionEntity rename(final String newName) throws ArangoDBException { - final CollectionEntity result = executor.execute(renameRequest(newName), CollectionEntity.class); - name = result.getName(); - return result; - } - - @Override - public ShardEntity getResponsibleShard(final Object value) throws ArangoDBException { - return executor.execute(responsibleShardRequest(value), ShardEntity.class); - } - - @Override - public CollectionRevisionEntity getRevision() throws ArangoDBException { - return executor.execute(getRevisionRequest(), CollectionRevisionEntity.class); - } - - @Override - public void grantAccess(final String user, final Permissions permissions) throws ArangoDBException { - executor.execute(grantAccessRequest(user, permissions), Void.class); - } - - @Override - public void revokeAccess(final String user) throws ArangoDBException { - executor.execute(grantAccessRequest(user, Permissions.NONE), Void.class); - } - - @Override - public void resetAccess(final String user) throws ArangoDBException { - executor.execute(resetAccessRequest(user), Void.class); - } - - @Override - public Permissions getPermissions(final String user) throws ArangoDBException { - return executor.execute(getPermissionsRequest(user), getPermissionsResponseDeserialzer()); - } + implements ArangoCollection { + + private static final Logger LOGGER = LoggerFactory.getLogger(ArangoCollection.class); + + protected ArangoCollectionImpl(final ArangoDatabaseImpl db, final String name) { + super(db, name); + } + + @Override + public DocumentCreateEntity insertDocument(final T value) throws ArangoDBException { + return insertDocument(value, new DocumentCreateOptions()); + } + + @Override + public DocumentCreateEntity insertDocument(final T value, final DocumentCreateOptions options) + throws ArangoDBException { + return executor + .execute(insertDocumentRequest(value, options), insertDocumentResponseDeserializer(value, options)); + } + + @Override + public MultiDocumentEntity> insertDocuments(final Collection values) + throws ArangoDBException { + return insertDocuments(values, new DocumentCreateOptions()); + } + + @Override + public MultiDocumentEntity> insertDocuments( + final Collection values, final DocumentCreateOptions options) throws ArangoDBException { + final DocumentCreateOptions params = (options != null ? options : new DocumentCreateOptions()); + return executor + .execute(insertDocumentsRequest(values, params), insertDocumentsResponseDeserializer(values, params)); + } + + @Override + public DocumentImportEntity importDocuments(final Collection values) throws ArangoDBException { + return importDocuments(values, new DocumentImportOptions()); + } + + @Override + public DocumentImportEntity importDocuments(final Collection values, final DocumentImportOptions options) + throws ArangoDBException { + return executor.execute(importDocumentsRequest(values, options), DocumentImportEntity.class); + } + + @Override + public DocumentImportEntity importDocuments(final String values) throws ArangoDBException { + return importDocuments(values, new DocumentImportOptions()); + } + + @Override + public DocumentImportEntity importDocuments(final String values, final DocumentImportOptions options) + throws ArangoDBException { + return executor.execute(importDocumentsRequest(values, options), DocumentImportEntity.class); + } + + @Override + public T getDocument(final String key, final Class type) throws ArangoDBException { + return getDocument(key, type, new DocumentReadOptions()); + } + + @Override + public T getDocument(final String key, final Class type, final DocumentReadOptions options) + throws ArangoDBException { + DocumentUtil.validateDocumentKey(key); + try { + return executor.execute(getDocumentRequest(key, options), type); + } catch (final ArangoDBException e) { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug(e.getMessage(), e); + } + + // handle Response: 404, Error: 1655 - transaction not found + if (e.getErrorNum() != null && e.getErrorNum() == 1655) { + throw e; + } + + if ((e.getResponseCode() != null && (e.getResponseCode() == 404 || e.getResponseCode() == 304 + || e.getResponseCode() == 412)) && (options == null || options.isCatchException())) { + return null; + } + throw e; + } + } + + @Override + public MultiDocumentEntity getDocuments(final Collection keys, final Class type) + throws ArangoDBException { + return getDocuments(keys, type, new DocumentReadOptions()); + } + + @Override + public MultiDocumentEntity getDocuments( + final Collection keys, final Class type, final DocumentReadOptions options) + throws ArangoDBException { + return executor.execute(getDocumentsRequest(keys, options), getDocumentsResponseDeserializer(type, options)); + } + + @Override + public DocumentUpdateEntity replaceDocument(final String key, final T value) throws ArangoDBException { + return replaceDocument(key, value, new DocumentReplaceOptions()); + } + + @Override + public DocumentUpdateEntity replaceDocument( + final String key, final T value, final DocumentReplaceOptions options) throws ArangoDBException { + return executor.execute(replaceDocumentRequest(key, value, options), + replaceDocumentResponseDeserializer(value, options)); + } + + @Override + public MultiDocumentEntity> replaceDocuments(final Collection values) + throws ArangoDBException { + return replaceDocuments(values, new DocumentReplaceOptions()); + } + + @Override + public MultiDocumentEntity> replaceDocuments( + final Collection values, final DocumentReplaceOptions options) throws ArangoDBException { + final DocumentReplaceOptions params = (options != null ? options : new DocumentReplaceOptions()); + return executor + .execute(replaceDocumentsRequest(values, params), replaceDocumentsResponseDeserializer(values, params)); + } + + @Override + public DocumentUpdateEntity updateDocument(final String key, final T value) throws ArangoDBException { + return updateDocument(key, value, new DocumentUpdateOptions()); + } + + @Override + public DocumentUpdateEntity updateDocument( + final String key, final T value, final DocumentUpdateOptions options) throws ArangoDBException { + return executor.execute(updateDocumentRequest(key, value, options), + updateDocumentResponseDeserializer(value, options)); + } + + @Override + public MultiDocumentEntity> updateDocuments(final Collection values) + throws ArangoDBException { + return updateDocuments(values, new DocumentUpdateOptions()); + } + + @Override + public MultiDocumentEntity> updateDocuments( + final Collection values, final DocumentUpdateOptions options) throws ArangoDBException { + final DocumentUpdateOptions params = (options != null ? options : new DocumentUpdateOptions()); + return executor + .execute(updateDocumentsRequest(values, params), updateDocumentsResponseDeserializer(values, params)); + } + + @Override + public DocumentDeleteEntity deleteDocument(final String key) throws ArangoDBException { + return executor.execute(deleteDocumentRequest(key, new DocumentDeleteOptions()), + deleteDocumentResponseDeserializer(Void.class)); + } + + @Override + public DocumentDeleteEntity deleteDocument( + final String key, final Class type, final DocumentDeleteOptions options) throws ArangoDBException { + return executor.execute(deleteDocumentRequest(key, options), deleteDocumentResponseDeserializer(type)); + } + + @Override + public MultiDocumentEntity> deleteDocuments(final Collection values) + throws ArangoDBException { + return executor.execute(deleteDocumentsRequest(values, new DocumentDeleteOptions()), + deleteDocumentsResponseDeserializer(Void.class)); + } + + @Override + public MultiDocumentEntity> deleteDocuments( + final Collection values, final Class type, final DocumentDeleteOptions options) + throws ArangoDBException { + return executor.execute(deleteDocumentsRequest(values, options), deleteDocumentsResponseDeserializer(type)); + } + + @Override + public Boolean documentExists(final String key) { + return documentExists(key, new DocumentExistsOptions()); + } + + @Override + public Boolean documentExists(final String key, final DocumentExistsOptions options) throws ArangoDBException { + try { + executor.execute(documentExistsRequest(key, options), VPackSlice.class); + return true; + } catch (final ArangoDBException e) { + + // handle Response: 404, Error: 1655 - transaction not found + if (e.getErrorNum() != null && e.getErrorNum() == 1655) { + throw e; + } + + if ((e.getResponseCode() != null && (e.getResponseCode() == 404 || e.getResponseCode() == 304 + || e.getResponseCode() == 412)) && (options == null || options.isCatchException())) { + return false; + } + throw e; + } + } + + @Override + public IndexEntity getIndex(final String id) throws ArangoDBException { + return executor.execute(getIndexRequest(id), IndexEntity.class); + } + + @Override + public String deleteIndex(final String id) throws ArangoDBException { + return executor.execute(deleteIndexRequest(id), deleteIndexResponseDeserializer()); + } + + @Override + public IndexEntity ensureHashIndex(final Iterable fields, final HashIndexOptions options) + throws ArangoDBException { + return executor.execute(createHashIndexRequest(fields, options), IndexEntity.class); + } + + @Override + public IndexEntity ensureSkiplistIndex(final Iterable fields, final SkiplistIndexOptions options) + throws ArangoDBException { + return executor.execute(createSkiplistIndexRequest(fields, options), IndexEntity.class); + } + + @Override + public IndexEntity ensurePersistentIndex(final Iterable fields, final PersistentIndexOptions options) + throws ArangoDBException { + return executor.execute(createPersistentIndexRequest(fields, options), IndexEntity.class); + } + + @Override + public IndexEntity ensureGeoIndex(final Iterable fields, final GeoIndexOptions options) + throws ArangoDBException { + return executor.execute(createGeoIndexRequest(fields, options), IndexEntity.class); + } + + @Override + public IndexEntity ensureFulltextIndex(final Iterable fields, final FulltextIndexOptions options) + throws ArangoDBException { + return executor.execute(createFulltextIndexRequest(fields, options), IndexEntity.class); + } + + @Override + public IndexEntity ensureTtlIndex(final Iterable fields, final TtlIndexOptions options) + throws ArangoDBException { + return executor.execute(createTtlIndexRequest(fields, options), IndexEntity.class); + } + + @Override + public Collection getIndexes() throws ArangoDBException { + return executor.execute(getIndexesRequest(), getIndexesResponseDeserializer()); + } + + @Override + public boolean exists() throws ArangoDBException { + try { + getInfo(); + return true; + } catch (final ArangoDBException e) { + if (ArangoErrors.ERROR_ARANGO_DATA_SOURCE_NOT_FOUND.equals(e.getErrorNum())) { + return false; + } + throw e; + } + } + + @Override + public CollectionEntity truncate() throws ArangoDBException { + return truncate(null); + } + + @Override + public CollectionEntity truncate(CollectionTruncateOptions options) throws ArangoDBException { + return executor.execute(truncateRequest(options), CollectionEntity.class); + } + + @Override + public CollectionPropertiesEntity count() throws ArangoDBException { + return count(null); + } + + @Override + public CollectionPropertiesEntity count(CollectionCountOptions options) throws ArangoDBException { + return executor.execute(countRequest(options), CollectionPropertiesEntity.class); + } + + @Override + public CollectionEntity create() throws ArangoDBException { + return db().createCollection(name()); + } + + @Override + public CollectionEntity create(final CollectionCreateOptions options) throws ArangoDBException { + return db().createCollection(name(), options); + } + + @Override + public void drop() throws ArangoDBException { + executor.execute(dropRequest(null), Void.class); + } + + @Override + public void drop(final boolean isSystem) throws ArangoDBException { + executor.execute(dropRequest(isSystem), Void.class); + } + + @Override + public CollectionEntity load() throws ArangoDBException { + return executor.execute(loadRequest(), CollectionEntity.class); + } + + @Override + public CollectionEntity unload() throws ArangoDBException { + return executor.execute(unloadRequest(), CollectionEntity.class); + } + + @Override + public CollectionEntity getInfo() throws ArangoDBException { + return executor.execute(getInfoRequest(), CollectionEntity.class); + } + + @Override + public CollectionPropertiesEntity getProperties() throws ArangoDBException { + return executor.execute(getPropertiesRequest(), CollectionPropertiesEntity.class); + } + + @Override + public CollectionPropertiesEntity changeProperties(final CollectionPropertiesOptions options) + throws ArangoDBException { + return executor.execute(changePropertiesRequest(options), CollectionPropertiesEntity.class); + } + + @Override + public synchronized CollectionEntity rename(final String newName) throws ArangoDBException { + final CollectionEntity result = executor.execute(renameRequest(newName), CollectionEntity.class); + name = result.getName(); + return result; + } + + @Override + public ShardEntity getResponsibleShard(final Object value) throws ArangoDBException { + return executor.execute(responsibleShardRequest(value), ShardEntity.class); + } + + @Override + public CollectionRevisionEntity getRevision() throws ArangoDBException { + return executor.execute(getRevisionRequest(), CollectionRevisionEntity.class); + } + + @Override + public void grantAccess(final String user, final Permissions permissions) throws ArangoDBException { + executor.execute(grantAccessRequest(user, permissions), Void.class); + } + + @Override + public void revokeAccess(final String user) throws ArangoDBException { + executor.execute(grantAccessRequest(user, Permissions.NONE), Void.class); + } + + @Override + public void resetAccess(final String user) throws ArangoDBException { + executor.execute(resetAccessRequest(user), Void.class); + } + + @Override + public Permissions getPermissions(final String user) throws ArangoDBException { + return executor.execute(getPermissionsRequest(user), getPermissionsResponseDeserialzer()); + } } diff --git a/src/main/java/com/arangodb/internal/ArangoContext.java b/src/main/java/com/arangodb/internal/ArangoContext.java index 058bcb97f..67c80c238 100644 --- a/src/main/java/com/arangodb/internal/ArangoContext.java +++ b/src/main/java/com/arangodb/internal/ArangoContext.java @@ -25,26 +25,25 @@ /** * @author Mark Vollmary - * */ public class ArangoContext { - private final Map headerParam; + private final Map headerParam; - public ArangoContext() { - super(); + public ArangoContext() { + super(); headerParam = new HashMap<>(); - } - - public Map getHeaderParam() { - return headerParam; - } - - public ArangoContext putHeaderParam(final String key, final Object value) { - if (value != null) { - headerParam.put(key, value.toString()); - } - return this; - } + } + + public Map getHeaderParam() { + return headerParam; + } + + public ArangoContext putHeaderParam(final String key, final Object value) { + if (value != null) { + headerParam.put(key, value.toString()); + } + return this; + } } diff --git a/src/main/java/com/arangodb/internal/ArangoCursorExecute.java b/src/main/java/com/arangodb/internal/ArangoCursorExecute.java index 21fb01cff..455844113 100644 --- a/src/main/java/com/arangodb/internal/ArangoCursorExecute.java +++ b/src/main/java/com/arangodb/internal/ArangoCursorExecute.java @@ -20,19 +20,18 @@ package com.arangodb.internal; -import java.util.Map; - import com.arangodb.ArangoDBException; import com.arangodb.entity.CursorEntity; +import java.util.Map; + /** * @author Mark Vollmary - * */ public interface ArangoCursorExecute { - CursorEntity next(String id, Map meta) throws ArangoDBException; + CursorEntity next(String id, Map meta) throws ArangoDBException; - void close(String id, Map meta) throws ArangoDBException; + void close(String id, Map meta) throws ArangoDBException; } diff --git a/src/main/java/com/arangodb/internal/ArangoDBImpl.java b/src/main/java/com/arangodb/internal/ArangoDBImpl.java index 3ed59a1d6..88a67b7a7 100644 --- a/src/main/java/com/arangodb/internal/ArangoDBImpl.java +++ b/src/main/java/com/arangodb/internal/ArangoDBImpl.java @@ -52,203 +52,202 @@ * @author Mark Vollmary * @author Heiko Kernbach * @author Michele Rastelli - * */ public class ArangoDBImpl extends InternalArangoDB implements ArangoDB { - - private static final Logger LOGGER = LoggerFactory.getLogger(ArangoDBImpl.class); - - private ArangoCursorInitializer cursorInitializer; - private final CommunicationProtocol cp; - - public ArangoDBImpl(final VstCommunicationSync.Builder vstBuilder, final HttpCommunication.Builder httpBuilder, - final ArangoSerializationFactory util, final Protocol protocol, final HostResolver hostResolver, - final ArangoContext context) { - - super(new ArangoExecutorSync( - createProtocol(vstBuilder, httpBuilder, util.get(Serializer.INTERNAL), protocol), - util, - new DocumentCache()), - util, - context); - - cp = createProtocol( - new VstCommunicationSync.Builder(vstBuilder).maxConnections(1), - new HttpCommunication.Builder(httpBuilder), - util.get(Serializer.INTERNAL), - protocol); - - hostResolver.init(this.executor(), util()); - - LOGGER.debug("ArangoDB Client is ready to use"); - - } - - private static CommunicationProtocol createProtocol( - final VstCommunicationSync.Builder vstBuilder, - final HttpCommunication.Builder httpBuilder, - final ArangoSerialization util, - final Protocol protocol) { - - return (protocol == null || Protocol.VST == protocol) ? createVST(vstBuilder, util) - : createHTTP(httpBuilder, util); - } - - private static CommunicationProtocol createVST( - final VstCommunicationSync.Builder builder, - final ArangoSerialization util) { - return new VstProtocol(builder.build(util)); - } - - private static CommunicationProtocol createHTTP( - final HttpCommunication.Builder builder, - final ArangoSerialization util) { - return new HttpProtocol(builder.build(util)); - } - - @Override - protected ArangoExecutorSync executor() { - return executor; - } - - @Override - public void shutdown() throws ArangoDBException { - try { - executor.disconnect(); - cp.close(); - } catch (final IOException e) { - throw new ArangoDBException(e); - } - } - - @Override - public ArangoDatabase db() { - return db(ArangoRequestParam.SYSTEM); - } - - @Override - public ArangoDatabase db(final String name) { - return new ArangoDatabaseImpl(this, name).setCursorInitializer(cursorInitializer); - } - - @Override - public Boolean createDatabase(final String name) throws ArangoDBException { - return createDatabase(new DBCreateOptions().name(name)); - } - - @Override - public Boolean createDatabase(DBCreateOptions options) throws ArangoDBException { - return executor.execute(createDatabaseRequest(options), createDatabaseResponseDeserializer()); - } - - @Override - public Collection getDatabases() throws ArangoDBException { - return executor.execute(getDatabasesRequest(db().name()), getDatabaseResponseDeserializer()); - } - - @Override - public Collection getAccessibleDatabases() throws ArangoDBException { - return db().getAccessibleDatabases(); - } - - @Override - public Collection getAccessibleDatabasesFor(final String user) throws ArangoDBException { - return executor.execute(getAccessibleDatabasesForRequest(db().name(), user), - getAccessibleDatabasesForResponseDeserializer()); - } - - @Override - public ArangoDBVersion getVersion() throws ArangoDBException { - return db().getVersion(); - } - - @Override - public ArangoDBEngine getEngine() throws ArangoDBException { - return db().getEngine(); - } - - @Override - public ServerRole getRole() throws ArangoDBException { - return executor.execute(getRoleRequest(), getRoleResponseDeserializer()); - } - - @Override - public UserEntity createUser(final String user, final String passwd) throws ArangoDBException { - return executor.execute(createUserRequest(db().name(), user, passwd, new UserCreateOptions()), - UserEntity.class); - } - - @Override - public UserEntity createUser(final String user, final String passwd, final UserCreateOptions options) - throws ArangoDBException { - return executor.execute(createUserRequest(db().name(), user, passwd, options), UserEntity.class); - } - - @Override - public void deleteUser(final String user) throws ArangoDBException { - executor.execute(deleteUserRequest(db().name(), user), Void.class); - } - - @Override - public UserEntity getUser(final String user) throws ArangoDBException { - return executor.execute(getUserRequest(db().name(), user), UserEntity.class); - } - - @Override - public Collection getUsers() throws ArangoDBException { - return executor.execute(getUsersRequest(db().name()), getUsersResponseDeserializer()); - } - - @Override - public UserEntity updateUser(final String user, final UserUpdateOptions options) throws ArangoDBException { - return executor.execute(updateUserRequest(db().name(), user, options), UserEntity.class); - } - - @Override - public UserEntity replaceUser(final String user, final UserUpdateOptions options) throws ArangoDBException { - return executor.execute(replaceUserRequest(db().name(), user, options), UserEntity.class); - } - - @Override - public void grantDefaultDatabaseAccess(final String user, final Permissions permissions) throws ArangoDBException { - executor.execute(updateUserDefaultDatabaseAccessRequest(user, permissions), Void.class); - } - - @Override - public void grantDefaultCollectionAccess(final String user, final Permissions permissions) - throws ArangoDBException { - executor.execute(updateUserDefaultCollectionAccessRequest(user, permissions), Void.class); - } - - @Override - public Response execute(final Request request) throws ArangoDBException { - return executor.execute(request, response -> response); - } - - @Override - public Response execute(final Request request, final HostHandle hostHandle) throws ArangoDBException { - return executor.execute(request, response -> response, hostHandle); - } - - @Override - public LogEntity getLogs(final LogOptions options) throws ArangoDBException { - return executor.execute(getLogsRequest(options), LogEntity.class); - } - - @Override - public LogLevelEntity getLogLevel() throws ArangoDBException { - return executor.execute(getLogLevelRequest(), LogLevelEntity.class); - } - - @Override - public LogLevelEntity setLogLevel(final LogLevelEntity entity) throws ArangoDBException { - return executor.execute(setLogLevelRequest(entity), LogLevelEntity.class); - } - - @Override - public ArangoDBImpl _setCursorInitializer(final ArangoCursorInitializer cursorInitializer) { - this.cursorInitializer = cursorInitializer; - return this; - } + + private static final Logger LOGGER = LoggerFactory.getLogger(ArangoDBImpl.class); + + private ArangoCursorInitializer cursorInitializer; + private final CommunicationProtocol cp; + + public ArangoDBImpl(final VstCommunicationSync.Builder vstBuilder, final HttpCommunication.Builder httpBuilder, + final ArangoSerializationFactory util, final Protocol protocol, final HostResolver hostResolver, + final ArangoContext context) { + + super(new ArangoExecutorSync( + createProtocol(vstBuilder, httpBuilder, util.get(Serializer.INTERNAL), protocol), + util, + new DocumentCache()), + util, + context); + + cp = createProtocol( + new VstCommunicationSync.Builder(vstBuilder).maxConnections(1), + new HttpCommunication.Builder(httpBuilder), + util.get(Serializer.INTERNAL), + protocol); + + hostResolver.init(this.executor(), util()); + + LOGGER.debug("ArangoDB Client is ready to use"); + + } + + private static CommunicationProtocol createProtocol( + final VstCommunicationSync.Builder vstBuilder, + final HttpCommunication.Builder httpBuilder, + final ArangoSerialization util, + final Protocol protocol) { + + return (protocol == null || Protocol.VST == protocol) ? createVST(vstBuilder, util) + : createHTTP(httpBuilder, util); + } + + private static CommunicationProtocol createVST( + final VstCommunicationSync.Builder builder, + final ArangoSerialization util) { + return new VstProtocol(builder.build(util)); + } + + private static CommunicationProtocol createHTTP( + final HttpCommunication.Builder builder, + final ArangoSerialization util) { + return new HttpProtocol(builder.build(util)); + } + + @Override + protected ArangoExecutorSync executor() { + return executor; + } + + @Override + public void shutdown() throws ArangoDBException { + try { + executor.disconnect(); + cp.close(); + } catch (final IOException e) { + throw new ArangoDBException(e); + } + } + + @Override + public ArangoDatabase db() { + return db(ArangoRequestParam.SYSTEM); + } + + @Override + public ArangoDatabase db(final String name) { + return new ArangoDatabaseImpl(this, name).setCursorInitializer(cursorInitializer); + } + + @Override + public Boolean createDatabase(final String name) throws ArangoDBException { + return createDatabase(new DBCreateOptions().name(name)); + } + + @Override + public Boolean createDatabase(DBCreateOptions options) throws ArangoDBException { + return executor.execute(createDatabaseRequest(options), createDatabaseResponseDeserializer()); + } + + @Override + public Collection getDatabases() throws ArangoDBException { + return executor.execute(getDatabasesRequest(db().name()), getDatabaseResponseDeserializer()); + } + + @Override + public Collection getAccessibleDatabases() throws ArangoDBException { + return db().getAccessibleDatabases(); + } + + @Override + public Collection getAccessibleDatabasesFor(final String user) throws ArangoDBException { + return executor.execute(getAccessibleDatabasesForRequest(db().name(), user), + getAccessibleDatabasesForResponseDeserializer()); + } + + @Override + public ArangoDBVersion getVersion() throws ArangoDBException { + return db().getVersion(); + } + + @Override + public ArangoDBEngine getEngine() throws ArangoDBException { + return db().getEngine(); + } + + @Override + public ServerRole getRole() throws ArangoDBException { + return executor.execute(getRoleRequest(), getRoleResponseDeserializer()); + } + + @Override + public UserEntity createUser(final String user, final String passwd) throws ArangoDBException { + return executor.execute(createUserRequest(db().name(), user, passwd, new UserCreateOptions()), + UserEntity.class); + } + + @Override + public UserEntity createUser(final String user, final String passwd, final UserCreateOptions options) + throws ArangoDBException { + return executor.execute(createUserRequest(db().name(), user, passwd, options), UserEntity.class); + } + + @Override + public void deleteUser(final String user) throws ArangoDBException { + executor.execute(deleteUserRequest(db().name(), user), Void.class); + } + + @Override + public UserEntity getUser(final String user) throws ArangoDBException { + return executor.execute(getUserRequest(db().name(), user), UserEntity.class); + } + + @Override + public Collection getUsers() throws ArangoDBException { + return executor.execute(getUsersRequest(db().name()), getUsersResponseDeserializer()); + } + + @Override + public UserEntity updateUser(final String user, final UserUpdateOptions options) throws ArangoDBException { + return executor.execute(updateUserRequest(db().name(), user, options), UserEntity.class); + } + + @Override + public UserEntity replaceUser(final String user, final UserUpdateOptions options) throws ArangoDBException { + return executor.execute(replaceUserRequest(db().name(), user, options), UserEntity.class); + } + + @Override + public void grantDefaultDatabaseAccess(final String user, final Permissions permissions) throws ArangoDBException { + executor.execute(updateUserDefaultDatabaseAccessRequest(user, permissions), Void.class); + } + + @Override + public void grantDefaultCollectionAccess(final String user, final Permissions permissions) + throws ArangoDBException { + executor.execute(updateUserDefaultCollectionAccessRequest(user, permissions), Void.class); + } + + @Override + public Response execute(final Request request) throws ArangoDBException { + return executor.execute(request, response -> response); + } + + @Override + public Response execute(final Request request, final HostHandle hostHandle) throws ArangoDBException { + return executor.execute(request, response -> response, hostHandle); + } + + @Override + public LogEntity getLogs(final LogOptions options) throws ArangoDBException { + return executor.execute(getLogsRequest(options), LogEntity.class); + } + + @Override + public LogLevelEntity getLogLevel() throws ArangoDBException { + return executor.execute(getLogLevelRequest(), LogLevelEntity.class); + } + + @Override + public LogLevelEntity setLogLevel(final LogLevelEntity entity) throws ArangoDBException { + return executor.execute(setLogLevelRequest(entity), LogLevelEntity.class); + } + + @Override + public ArangoDBImpl _setCursorInitializer(final ArangoCursorInitializer cursorInitializer) { + this.cursorInitializer = cursorInitializer; + return this; + } } diff --git a/src/main/java/com/arangodb/internal/ArangoDatabaseImpl.java b/src/main/java/com/arangodb/internal/ArangoDatabaseImpl.java index 174ebeb48..885633b69 100644 --- a/src/main/java/com/arangodb/internal/ArangoDatabaseImpl.java +++ b/src/main/java/com/arangodb/internal/ArangoDatabaseImpl.java @@ -42,410 +42,410 @@ * @author Michele Rastelli */ public class ArangoDatabaseImpl extends InternalArangoDatabase - implements ArangoDatabase { - - private ArangoCursorInitializer cursorInitializer; - - protected ArangoDatabaseImpl(final ArangoDBImpl arangoDB, final String name) { - super(arangoDB, name); - } - - @Override - public ArangoDBVersion getVersion() throws ArangoDBException { - return executor.execute(getVersionRequest(), ArangoDBVersion.class); - } - - @Override - public ArangoDBEngine getEngine() throws ArangoDBException { - return executor.execute(getEngineRequest(), ArangoDBEngine.class); - } - - @Override - public boolean exists() throws ArangoDBException { - try { - getInfo(); - return true; - } catch (final ArangoDBException e) { - if (ArangoErrors.ERROR_ARANGO_DATABASE_NOT_FOUND.equals(e.getErrorNum())) { - return false; - } - throw e; - } - } - - @Override - public Collection getAccessibleDatabases() throws ArangoDBException { - return executor.execute(getAccessibleDatabasesRequest(), getDatabaseResponseDeserializer()); - } - - @Override - public ArangoCollection collection(final String name) { - return new ArangoCollectionImpl(this, name); - } - - @Override - public CollectionEntity createCollection(final String name) throws ArangoDBException { - return executor.execute(createCollectionRequest(name, new CollectionCreateOptions()), CollectionEntity.class); - } - - @Override - public CollectionEntity createCollection(final String name, final CollectionCreateOptions options) - throws ArangoDBException { - return executor.execute(createCollectionRequest(name, options), CollectionEntity.class); - } - - @Override - public Collection getCollections() throws ArangoDBException { - return executor - .execute(getCollectionsRequest(new CollectionsReadOptions()), getCollectionsResponseDeserializer()); - } - - @Override - public Collection getCollections(final CollectionsReadOptions options) throws ArangoDBException { - return executor.execute(getCollectionsRequest(options), getCollectionsResponseDeserializer()); - } - - @Override - public IndexEntity getIndex(final String id) throws ArangoDBException { - DocumentUtil.validateIndexId(id); - final String[] split = id.split("/"); - return collection(split[0]).getIndex(split[1]); - } - - @Override - public String deleteIndex(final String id) throws ArangoDBException { - DocumentUtil.validateIndexId(id); - final String[] split = id.split("/"); - return collection(split[0]).deleteIndex(split[1]); - } - - @Override - public Boolean create() throws ArangoDBException { - return arango().createDatabase(name()); - } - - @Override - public Boolean drop() throws ArangoDBException { - return executor.execute(dropRequest(), createDropResponseDeserializer()); - } - - @Override - public void grantAccess(final String user, final Permissions permissions) throws ArangoDBException { - executor.execute(grantAccessRequest(user, permissions), Void.class); - } - - @Override - public void grantAccess(final String user) throws ArangoDBException { - executor.execute(grantAccessRequest(user, Permissions.RW), Void.class); - } - - @Override - public void revokeAccess(final String user) throws ArangoDBException { - executor.execute(grantAccessRequest(user, Permissions.NONE), Void.class); - } - - @Override - public void resetAccess(final String user) throws ArangoDBException { - executor.execute(resetAccessRequest(user), Void.class); - } - - @Override - public void grantDefaultCollectionAccess(final String user, final Permissions permissions) - throws ArangoDBException { - executor.execute(updateUserDefaultCollectionAccessRequest(user, permissions), Void.class); - } - - @Override - public Permissions getPermissions(final String user) throws ArangoDBException { - return executor.execute(getPermissionsRequest(user), getPermissionsResponseDeserialzer()); - } - - @Override - public ArangoCursor query( - final String query, final Map bindVars, final AqlQueryOptions options, final Class type) - throws ArangoDBException { - - final Request request = queryRequest(query, bindVars, options); - final HostHandle hostHandle = new HostHandle(); - final CursorEntity result = executor.execute(request, CursorEntity.class, hostHandle); - - return createCursor(result, type, options, hostHandle); - - } - - @Override - public ArangoCursor query( - final String query, final Map bindVars, final Class type) throws ArangoDBException { - return query(query, bindVars, null, type); - } - - @Override - public ArangoCursor query(final String query, final AqlQueryOptions options, final Class type) - throws ArangoDBException { - return query(query, null, options, type); - } - - @Override - public ArangoCursor query(final String query, final Class type) throws ArangoDBException { - return query(query, null, null, type); - } - - @Override - public ArangoCursor cursor(final String cursorId, final Class type) throws ArangoDBException { - final HostHandle hostHandle = new HostHandle(); - final CursorEntity result = executor - .execute(queryNextRequest(cursorId, null, null), CursorEntity.class, hostHandle); - return createCursor(result, type, null, hostHandle); - } - - private ArangoCursor createCursor( - final CursorEntity result, - final Class type, - final AqlQueryOptions options, - final HostHandle hostHandle) { - - final ArangoCursorExecute execute = new ArangoCursorExecute() { - @Override - public CursorEntity next(final String id, Map meta) { - return executor.execute(queryNextRequest(id, options, meta), CursorEntity.class, hostHandle); - } - - @Override - public void close(final String id, Map meta) { - executor.execute(queryCloseRequest(id, options, meta), Void.class, hostHandle); - } - }; - - return cursorInitializer != null ? - cursorInitializer.createInstance(this, execute, type, result) : - new ArangoCursorImpl<>(this, execute, type, result); - } - - @Override - public AqlExecutionExplainEntity explainQuery( - final String query, final Map bindVars, final AqlQueryExplainOptions options) - throws ArangoDBException { - return executor.execute(explainQueryRequest(query, bindVars, options), AqlExecutionExplainEntity.class); - } - - @Override - public AqlParseEntity parseQuery(final String query) throws ArangoDBException { - return executor.execute(parseQueryRequest(query), AqlParseEntity.class); - } - - @Override - public void clearQueryCache() throws ArangoDBException { - executor.execute(clearQueryCacheRequest(), Void.class); - } - - @Override - public QueryCachePropertiesEntity getQueryCacheProperties() throws ArangoDBException { - return executor.execute(getQueryCachePropertiesRequest(), QueryCachePropertiesEntity.class); - } - - @Override - public QueryCachePropertiesEntity setQueryCacheProperties(final QueryCachePropertiesEntity properties) - throws ArangoDBException { - return executor.execute(setQueryCachePropertiesRequest(properties), QueryCachePropertiesEntity.class); - } - - @Override - public QueryTrackingPropertiesEntity getQueryTrackingProperties() throws ArangoDBException { - return executor.execute(getQueryTrackingPropertiesRequest(), QueryTrackingPropertiesEntity.class); - } - - @Override - public QueryTrackingPropertiesEntity setQueryTrackingProperties(final QueryTrackingPropertiesEntity properties) - throws ArangoDBException { - return executor.execute(setQueryTrackingPropertiesRequest(properties), QueryTrackingPropertiesEntity.class); - } - - @Override - public Collection getCurrentlyRunningQueries() throws ArangoDBException { - return executor.execute(getCurrentlyRunningQueriesRequest(), new Type>() { - }.getType()); - } - - @Override - public Collection getSlowQueries() throws ArangoDBException { - return executor.execute(getSlowQueriesRequest(), new Type>() { - }.getType()); - } - - @Override - public void clearSlowQueries() throws ArangoDBException { - executor.execute(clearSlowQueriesRequest(), Void.class); - } - - @Override - public void killQuery(final String id) throws ArangoDBException { - executor.execute(killQueryRequest(id), Void.class); - } - - @Override - public void createAqlFunction( - final String name, final String code, final AqlFunctionCreateOptions options) throws ArangoDBException { - executor.execute(createAqlFunctionRequest(name, code, options), Void.class); - } - - @Override - public Integer deleteAqlFunction(final String name, final AqlFunctionDeleteOptions options) - throws ArangoDBException { - return executor.execute(deleteAqlFunctionRequest(name, options), deleteAqlFunctionResponseDeserializer()); - } - - @Override - public Collection getAqlFunctions(final AqlFunctionGetOptions options) throws ArangoDBException { - return executor.execute(getAqlFunctionsRequest(options), getAqlFunctionsResponseDeserializer()); - } - - @Override - public ArangoGraph graph(final String name) { - return new ArangoGraphImpl(this, name); - } - - @Override - public GraphEntity createGraph(final String name, final Collection edgeDefinitions) - throws ArangoDBException { - return executor.execute(createGraphRequest(name, edgeDefinitions, new GraphCreateOptions()), - createGraphResponseDeserializer()); - } - - @Override - public GraphEntity createGraph( - final String name, final Collection edgeDefinitions, final GraphCreateOptions options) - throws ArangoDBException { - return executor.execute(createGraphRequest(name, edgeDefinitions, options), createGraphResponseDeserializer()); - } - - @Override - public Collection getGraphs() throws ArangoDBException { - return executor.execute(getGraphsRequest(), getGraphsResponseDeserializer()); - } - - @Override - public T transaction(final String action, final Class type, final TransactionOptions options) - throws ArangoDBException { - return executor.execute(transactionRequest(action, options), transactionResponseDeserializer(type)); - } - - @Override - public StreamTransactionEntity beginStreamTransaction(StreamTransactionOptions options) throws ArangoDBException { - return executor.execute(beginStreamTransactionRequest(options), streamTransactionResponseDeserializer()); - } - - @Override - public StreamTransactionEntity abortStreamTransaction(String id) throws ArangoDBException { - return executor.execute(abortStreamTransactionRequest(id), streamTransactionResponseDeserializer()); - } - - @Override - public StreamTransactionEntity getStreamTransaction(String id) throws ArangoDBException { - return executor.execute(getStreamTransactionRequest(id), streamTransactionResponseDeserializer()); - } - - @Override - public Collection getStreamTransactions() throws ArangoDBException { - return executor.execute(getStreamTransactionsRequest(), transactionsResponseDeserializer()); - } - - @Override - public StreamTransactionEntity commitStreamTransaction(String id) throws ArangoDBException { - return executor.execute(commitStreamTransactionRequest(id), streamTransactionResponseDeserializer()); - } - - @Override - public DatabaseEntity getInfo() throws ArangoDBException { - return executor.execute(getInfoRequest(), getInfoResponseDeserializer()); - } - - @Override - public TraversalEntity executeTraversal( - final Class vertexClass, final Class edgeClass, final TraversalOptions options) - throws ArangoDBException { - final Request request = executeTraversalRequest(options); - return executor.execute(request, executeTraversalResponseDeserializer(vertexClass, edgeClass)); - } - - @Override - public T getDocument(final String id, final Class type) throws ArangoDBException { - DocumentUtil.validateDocumentId(id); - final String[] split = id.split("/"); - return collection(split[0]).getDocument(split[1], type); - } - - @Override - public T getDocument(final String id, final Class type, final DocumentReadOptions options) - throws ArangoDBException { - DocumentUtil.validateDocumentId(id); - final String[] split = id.split("/"); - return collection(split[0]).getDocument(split[1], type, options); - } - - @Override - public void reloadRouting() throws ArangoDBException { - executor.execute(reloadRoutingRequest(), Void.class); - } - - protected ArangoDatabaseImpl setCursorInitializer(final ArangoCursorInitializer cursorInitializer) { - this.cursorInitializer = cursorInitializer; - return this; - } - - @Override - public ArangoRoute route(final String... path) { - return new ArangoRouteImpl(this, createPath(path), Collections.emptyMap()); - } - - @Override - public Collection getViews() throws ArangoDBException { - return executor.execute(getViewsRequest(), getViewsResponseDeserializer()); - } - - @Override - public ArangoView view(final String name) { - return new ArangoViewImpl(this, name); - } - - @Override - public ArangoSearch arangoSearch(final String name) { - return new ArangoSearchImpl(this, name); - } - - @Override - public ViewEntity createView(final String name, final ViewType type) throws ArangoDBException { - return executor.execute(createViewRequest(name, type), ViewEntity.class); - } - - @Override - public ViewEntity createArangoSearch(final String name, final ArangoSearchCreateOptions options) - throws ArangoDBException { - return executor.execute(createArangoSearchRequest(name, options), ViewEntity.class); - } - - @Override - public AnalyzerEntity createAnalyzer(AnalyzerEntity options) throws ArangoDBException { - return executor.execute(createAnalyzerRequest(options), AnalyzerEntity.class); - } - - @Override - public AnalyzerEntity getAnalyzer(String name) throws ArangoDBException { - return executor.execute(getAnalyzerRequest(name), AnalyzerEntity.class); - } - - @Override - public Collection getAnalyzers() throws ArangoDBException { - return executor.execute(getAnalyzersRequest(), getAnalyzersResponseDeserializer()); - } - - @Override - public void deleteAnalyzer(String name) throws ArangoDBException { - executor.execute(deleteAnalyzerRequest(name, null), Void.class); - } - - @Override - public void deleteAnalyzer(String name, AnalyzerDeleteOptions options) throws ArangoDBException { - executor.execute(deleteAnalyzerRequest(name, options), Void.class); - } + implements ArangoDatabase { + + private ArangoCursorInitializer cursorInitializer; + + protected ArangoDatabaseImpl(final ArangoDBImpl arangoDB, final String name) { + super(arangoDB, name); + } + + @Override + public ArangoDBVersion getVersion() throws ArangoDBException { + return executor.execute(getVersionRequest(), ArangoDBVersion.class); + } + + @Override + public ArangoDBEngine getEngine() throws ArangoDBException { + return executor.execute(getEngineRequest(), ArangoDBEngine.class); + } + + @Override + public boolean exists() throws ArangoDBException { + try { + getInfo(); + return true; + } catch (final ArangoDBException e) { + if (ArangoErrors.ERROR_ARANGO_DATABASE_NOT_FOUND.equals(e.getErrorNum())) { + return false; + } + throw e; + } + } + + @Override + public Collection getAccessibleDatabases() throws ArangoDBException { + return executor.execute(getAccessibleDatabasesRequest(), getDatabaseResponseDeserializer()); + } + + @Override + public ArangoCollection collection(final String name) { + return new ArangoCollectionImpl(this, name); + } + + @Override + public CollectionEntity createCollection(final String name) throws ArangoDBException { + return executor.execute(createCollectionRequest(name, new CollectionCreateOptions()), CollectionEntity.class); + } + + @Override + public CollectionEntity createCollection(final String name, final CollectionCreateOptions options) + throws ArangoDBException { + return executor.execute(createCollectionRequest(name, options), CollectionEntity.class); + } + + @Override + public Collection getCollections() throws ArangoDBException { + return executor + .execute(getCollectionsRequest(new CollectionsReadOptions()), getCollectionsResponseDeserializer()); + } + + @Override + public Collection getCollections(final CollectionsReadOptions options) throws ArangoDBException { + return executor.execute(getCollectionsRequest(options), getCollectionsResponseDeserializer()); + } + + @Override + public IndexEntity getIndex(final String id) throws ArangoDBException { + DocumentUtil.validateIndexId(id); + final String[] split = id.split("/"); + return collection(split[0]).getIndex(split[1]); + } + + @Override + public String deleteIndex(final String id) throws ArangoDBException { + DocumentUtil.validateIndexId(id); + final String[] split = id.split("/"); + return collection(split[0]).deleteIndex(split[1]); + } + + @Override + public Boolean create() throws ArangoDBException { + return arango().createDatabase(name()); + } + + @Override + public Boolean drop() throws ArangoDBException { + return executor.execute(dropRequest(), createDropResponseDeserializer()); + } + + @Override + public void grantAccess(final String user, final Permissions permissions) throws ArangoDBException { + executor.execute(grantAccessRequest(user, permissions), Void.class); + } + + @Override + public void grantAccess(final String user) throws ArangoDBException { + executor.execute(grantAccessRequest(user, Permissions.RW), Void.class); + } + + @Override + public void revokeAccess(final String user) throws ArangoDBException { + executor.execute(grantAccessRequest(user, Permissions.NONE), Void.class); + } + + @Override + public void resetAccess(final String user) throws ArangoDBException { + executor.execute(resetAccessRequest(user), Void.class); + } + + @Override + public void grantDefaultCollectionAccess(final String user, final Permissions permissions) + throws ArangoDBException { + executor.execute(updateUserDefaultCollectionAccessRequest(user, permissions), Void.class); + } + + @Override + public Permissions getPermissions(final String user) throws ArangoDBException { + return executor.execute(getPermissionsRequest(user), getPermissionsResponseDeserialzer()); + } + + @Override + public ArangoCursor query( + final String query, final Map bindVars, final AqlQueryOptions options, final Class type) + throws ArangoDBException { + + final Request request = queryRequest(query, bindVars, options); + final HostHandle hostHandle = new HostHandle(); + final CursorEntity result = executor.execute(request, CursorEntity.class, hostHandle); + + return createCursor(result, type, options, hostHandle); + + } + + @Override + public ArangoCursor query( + final String query, final Map bindVars, final Class type) throws ArangoDBException { + return query(query, bindVars, null, type); + } + + @Override + public ArangoCursor query(final String query, final AqlQueryOptions options, final Class type) + throws ArangoDBException { + return query(query, null, options, type); + } + + @Override + public ArangoCursor query(final String query, final Class type) throws ArangoDBException { + return query(query, null, null, type); + } + + @Override + public ArangoCursor cursor(final String cursorId, final Class type) throws ArangoDBException { + final HostHandle hostHandle = new HostHandle(); + final CursorEntity result = executor + .execute(queryNextRequest(cursorId, null, null), CursorEntity.class, hostHandle); + return createCursor(result, type, null, hostHandle); + } + + private ArangoCursor createCursor( + final CursorEntity result, + final Class type, + final AqlQueryOptions options, + final HostHandle hostHandle) { + + final ArangoCursorExecute execute = new ArangoCursorExecute() { + @Override + public CursorEntity next(final String id, Map meta) { + return executor.execute(queryNextRequest(id, options, meta), CursorEntity.class, hostHandle); + } + + @Override + public void close(final String id, Map meta) { + executor.execute(queryCloseRequest(id, options, meta), Void.class, hostHandle); + } + }; + + return cursorInitializer != null ? + cursorInitializer.createInstance(this, execute, type, result) : + new ArangoCursorImpl<>(this, execute, type, result); + } + + @Override + public AqlExecutionExplainEntity explainQuery( + final String query, final Map bindVars, final AqlQueryExplainOptions options) + throws ArangoDBException { + return executor.execute(explainQueryRequest(query, bindVars, options), AqlExecutionExplainEntity.class); + } + + @Override + public AqlParseEntity parseQuery(final String query) throws ArangoDBException { + return executor.execute(parseQueryRequest(query), AqlParseEntity.class); + } + + @Override + public void clearQueryCache() throws ArangoDBException { + executor.execute(clearQueryCacheRequest(), Void.class); + } + + @Override + public QueryCachePropertiesEntity getQueryCacheProperties() throws ArangoDBException { + return executor.execute(getQueryCachePropertiesRequest(), QueryCachePropertiesEntity.class); + } + + @Override + public QueryCachePropertiesEntity setQueryCacheProperties(final QueryCachePropertiesEntity properties) + throws ArangoDBException { + return executor.execute(setQueryCachePropertiesRequest(properties), QueryCachePropertiesEntity.class); + } + + @Override + public QueryTrackingPropertiesEntity getQueryTrackingProperties() throws ArangoDBException { + return executor.execute(getQueryTrackingPropertiesRequest(), QueryTrackingPropertiesEntity.class); + } + + @Override + public QueryTrackingPropertiesEntity setQueryTrackingProperties(final QueryTrackingPropertiesEntity properties) + throws ArangoDBException { + return executor.execute(setQueryTrackingPropertiesRequest(properties), QueryTrackingPropertiesEntity.class); + } + + @Override + public Collection getCurrentlyRunningQueries() throws ArangoDBException { + return executor.execute(getCurrentlyRunningQueriesRequest(), new Type>() { + }.getType()); + } + + @Override + public Collection getSlowQueries() throws ArangoDBException { + return executor.execute(getSlowQueriesRequest(), new Type>() { + }.getType()); + } + + @Override + public void clearSlowQueries() throws ArangoDBException { + executor.execute(clearSlowQueriesRequest(), Void.class); + } + + @Override + public void killQuery(final String id) throws ArangoDBException { + executor.execute(killQueryRequest(id), Void.class); + } + + @Override + public void createAqlFunction( + final String name, final String code, final AqlFunctionCreateOptions options) throws ArangoDBException { + executor.execute(createAqlFunctionRequest(name, code, options), Void.class); + } + + @Override + public Integer deleteAqlFunction(final String name, final AqlFunctionDeleteOptions options) + throws ArangoDBException { + return executor.execute(deleteAqlFunctionRequest(name, options), deleteAqlFunctionResponseDeserializer()); + } + + @Override + public Collection getAqlFunctions(final AqlFunctionGetOptions options) throws ArangoDBException { + return executor.execute(getAqlFunctionsRequest(options), getAqlFunctionsResponseDeserializer()); + } + + @Override + public ArangoGraph graph(final String name) { + return new ArangoGraphImpl(this, name); + } + + @Override + public GraphEntity createGraph(final String name, final Collection edgeDefinitions) + throws ArangoDBException { + return executor.execute(createGraphRequest(name, edgeDefinitions, new GraphCreateOptions()), + createGraphResponseDeserializer()); + } + + @Override + public GraphEntity createGraph( + final String name, final Collection edgeDefinitions, final GraphCreateOptions options) + throws ArangoDBException { + return executor.execute(createGraphRequest(name, edgeDefinitions, options), createGraphResponseDeserializer()); + } + + @Override + public Collection getGraphs() throws ArangoDBException { + return executor.execute(getGraphsRequest(), getGraphsResponseDeserializer()); + } + + @Override + public T transaction(final String action, final Class type, final TransactionOptions options) + throws ArangoDBException { + return executor.execute(transactionRequest(action, options), transactionResponseDeserializer(type)); + } + + @Override + public StreamTransactionEntity beginStreamTransaction(StreamTransactionOptions options) throws ArangoDBException { + return executor.execute(beginStreamTransactionRequest(options), streamTransactionResponseDeserializer()); + } + + @Override + public StreamTransactionEntity abortStreamTransaction(String id) throws ArangoDBException { + return executor.execute(abortStreamTransactionRequest(id), streamTransactionResponseDeserializer()); + } + + @Override + public StreamTransactionEntity getStreamTransaction(String id) throws ArangoDBException { + return executor.execute(getStreamTransactionRequest(id), streamTransactionResponseDeserializer()); + } + + @Override + public Collection getStreamTransactions() throws ArangoDBException { + return executor.execute(getStreamTransactionsRequest(), transactionsResponseDeserializer()); + } + + @Override + public StreamTransactionEntity commitStreamTransaction(String id) throws ArangoDBException { + return executor.execute(commitStreamTransactionRequest(id), streamTransactionResponseDeserializer()); + } + + @Override + public DatabaseEntity getInfo() throws ArangoDBException { + return executor.execute(getInfoRequest(), getInfoResponseDeserializer()); + } + + @Override + public TraversalEntity executeTraversal( + final Class vertexClass, final Class edgeClass, final TraversalOptions options) + throws ArangoDBException { + final Request request = executeTraversalRequest(options); + return executor.execute(request, executeTraversalResponseDeserializer(vertexClass, edgeClass)); + } + + @Override + public T getDocument(final String id, final Class type) throws ArangoDBException { + DocumentUtil.validateDocumentId(id); + final String[] split = id.split("/"); + return collection(split[0]).getDocument(split[1], type); + } + + @Override + public T getDocument(final String id, final Class type, final DocumentReadOptions options) + throws ArangoDBException { + DocumentUtil.validateDocumentId(id); + final String[] split = id.split("/"); + return collection(split[0]).getDocument(split[1], type, options); + } + + @Override + public void reloadRouting() throws ArangoDBException { + executor.execute(reloadRoutingRequest(), Void.class); + } + + protected ArangoDatabaseImpl setCursorInitializer(final ArangoCursorInitializer cursorInitializer) { + this.cursorInitializer = cursorInitializer; + return this; + } + + @Override + public ArangoRoute route(final String... path) { + return new ArangoRouteImpl(this, createPath(path), Collections.emptyMap()); + } + + @Override + public Collection getViews() throws ArangoDBException { + return executor.execute(getViewsRequest(), getViewsResponseDeserializer()); + } + + @Override + public ArangoView view(final String name) { + return new ArangoViewImpl(this, name); + } + + @Override + public ArangoSearch arangoSearch(final String name) { + return new ArangoSearchImpl(this, name); + } + + @Override + public ViewEntity createView(final String name, final ViewType type) throws ArangoDBException { + return executor.execute(createViewRequest(name, type), ViewEntity.class); + } + + @Override + public ViewEntity createArangoSearch(final String name, final ArangoSearchCreateOptions options) + throws ArangoDBException { + return executor.execute(createArangoSearchRequest(name, options), ViewEntity.class); + } + + @Override + public AnalyzerEntity createAnalyzer(AnalyzerEntity options) throws ArangoDBException { + return executor.execute(createAnalyzerRequest(options), AnalyzerEntity.class); + } + + @Override + public AnalyzerEntity getAnalyzer(String name) throws ArangoDBException { + return executor.execute(getAnalyzerRequest(name), AnalyzerEntity.class); + } + + @Override + public Collection getAnalyzers() throws ArangoDBException { + return executor.execute(getAnalyzersRequest(), getAnalyzersResponseDeserializer()); + } + + @Override + public void deleteAnalyzer(String name) throws ArangoDBException { + executor.execute(deleteAnalyzerRequest(name, null), Void.class); + } + + @Override + public void deleteAnalyzer(String name, AnalyzerDeleteOptions options) throws ArangoDBException { + executor.execute(deleteAnalyzerRequest(name, options), Void.class); + } } diff --git a/src/main/java/com/arangodb/internal/ArangoDefaults.java b/src/main/java/com/arangodb/internal/ArangoDefaults.java index 194028c80..b81626fa5 100644 --- a/src/main/java/com/arangodb/internal/ArangoDefaults.java +++ b/src/main/java/com/arangodb/internal/ArangoDefaults.java @@ -25,31 +25,30 @@ /** * @author Mark Vollmary - * */ public final class ArangoDefaults { - private ArangoDefaults() { - super(); - } + private ArangoDefaults() { + super(); + } - public static final int INTEGER_BYTES = Integer.SIZE / Byte.SIZE; - public static final int LONG_BYTES = Long.SIZE / Byte.SIZE; + public static final int INTEGER_BYTES = Integer.SIZE / Byte.SIZE; + public static final int LONG_BYTES = Long.SIZE / Byte.SIZE; - public static final String DEFAULT_HOST = "127.0.0.1"; - public static final Integer DEFAULT_PORT = 8529; - public static final Integer DEFAULT_TIMEOUT = 0; - public static final String DEFAULT_USER = "root"; - public static final Boolean DEFAULT_USE_SSL = false; - public static final int CHUNK_MIN_HEADER_SIZE = INTEGER_BYTES + INTEGER_BYTES + LONG_BYTES; - public static final int CHUNK_MAX_HEADER_SIZE = CHUNK_MIN_HEADER_SIZE + LONG_BYTES; - public static final int CHUNK_DEFAULT_CONTENT_SIZE = 30000; - public static final int MAX_CONNECTIONS_VST_DEFAULT = 1; - public static final Integer CONNECTION_TTL_VST_DEFAULT = null; - public static final int MAX_CONNECTIONS_HTTP_DEFAULT = 20; - public static final Protocol DEFAULT_NETWORK_PROTOCOL = Protocol.VST; - public static final boolean DEFAULT_ACQUIRE_HOST_LIST = false; - public static final int DEFAULT_ACQUIRE_HOST_LIST_INTERVAL = 60 * 60 * 1000; // hour - public static final LoadBalancingStrategy DEFAULT_LOAD_BALANCING_STRATEGY = LoadBalancingStrategy.NONE; + public static final String DEFAULT_HOST = "127.0.0.1"; + public static final Integer DEFAULT_PORT = 8529; + public static final Integer DEFAULT_TIMEOUT = 0; + public static final String DEFAULT_USER = "root"; + public static final Boolean DEFAULT_USE_SSL = false; + public static final int CHUNK_MIN_HEADER_SIZE = INTEGER_BYTES + INTEGER_BYTES + LONG_BYTES; + public static final int CHUNK_MAX_HEADER_SIZE = CHUNK_MIN_HEADER_SIZE + LONG_BYTES; + public static final int CHUNK_DEFAULT_CONTENT_SIZE = 30000; + public static final int MAX_CONNECTIONS_VST_DEFAULT = 1; + public static final Integer CONNECTION_TTL_VST_DEFAULT = null; + public static final int MAX_CONNECTIONS_HTTP_DEFAULT = 20; + public static final Protocol DEFAULT_NETWORK_PROTOCOL = Protocol.VST; + public static final boolean DEFAULT_ACQUIRE_HOST_LIST = false; + public static final int DEFAULT_ACQUIRE_HOST_LIST_INTERVAL = 60 * 60 * 1000; // hour + public static final LoadBalancingStrategy DEFAULT_LOAD_BALANCING_STRATEGY = LoadBalancingStrategy.NONE; } diff --git a/src/main/java/com/arangodb/internal/ArangoEdgeCollectionImpl.java b/src/main/java/com/arangodb/internal/ArangoEdgeCollectionImpl.java index b8a894ef2..5c84bb556 100644 --- a/src/main/java/com/arangodb/internal/ArangoEdgeCollectionImpl.java +++ b/src/main/java/com/arangodb/internal/ArangoEdgeCollectionImpl.java @@ -20,97 +20,95 @@ package com.arangodb.internal; -import com.arangodb.model.*; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import com.arangodb.ArangoDBException; import com.arangodb.ArangoEdgeCollection; import com.arangodb.entity.EdgeEntity; import com.arangodb.entity.EdgeUpdateEntity; +import com.arangodb.model.*; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * @author Mark Vollmary - * */ public class ArangoEdgeCollectionImpl - extends InternalArangoEdgeCollection - implements ArangoEdgeCollection { - - private static final Logger LOGGER = LoggerFactory.getLogger(ArangoEdgeCollectionImpl.class); - - protected ArangoEdgeCollectionImpl(final ArangoGraphImpl graph, final String name) { - super(graph, name); - } - - @Override - public EdgeEntity insertEdge(final T value) throws ArangoDBException { - return executor.execute(insertEdgeRequest(value, new EdgeCreateOptions()), - insertEdgeResponseDeserializer(value)); - } - - @Override - public EdgeEntity insertEdge(final T value, final EdgeCreateOptions options) throws ArangoDBException { - return executor.execute(insertEdgeRequest(value, options), insertEdgeResponseDeserializer(value)); - } - - @Override - public T getEdge(final String key, final Class type) throws ArangoDBException { - try { - return executor.execute(getEdgeRequest(key, new GraphDocumentReadOptions()), getEdgeResponseDeserializer(type)); - } catch (final ArangoDBException e) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug(e.getMessage(), e); - } - return null; - } - } - - @Override - public T getEdge(final String key, final Class type, final GraphDocumentReadOptions options) - throws ArangoDBException { - try { - return executor.execute(getEdgeRequest(key, options), getEdgeResponseDeserializer(type)); - } catch (final ArangoDBException e) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug(e.getMessage(), e); - } - return null; - } - } - - @Override - public EdgeUpdateEntity replaceEdge(final String key, final T value) throws ArangoDBException { - return executor.execute(replaceEdgeRequest(key, value, new EdgeReplaceOptions()), - replaceEdgeResponseDeserializer(value)); - } - - @Override - public EdgeUpdateEntity replaceEdge(final String key, final T value, final EdgeReplaceOptions options) - throws ArangoDBException { - return executor.execute(replaceEdgeRequest(key, value, options), replaceEdgeResponseDeserializer(value)); - } - - @Override - public EdgeUpdateEntity updateEdge(final String key, final T value) throws ArangoDBException { - return executor.execute(updateEdgeRequest(key, value, new EdgeUpdateOptions()), - updateEdgeResponseDeserializer(value)); - } - - @Override - public EdgeUpdateEntity updateEdge(final String key, final T value, final EdgeUpdateOptions options) - throws ArangoDBException { - return executor.execute(updateEdgeRequest(key, value, options), updateEdgeResponseDeserializer(value)); - } - - @Override - public void deleteEdge(final String key) throws ArangoDBException { - executor.execute(deleteEdgeRequest(key, new EdgeDeleteOptions()), Void.class); - } - - @Override - public void deleteEdge(final String key, final EdgeDeleteOptions options) throws ArangoDBException { - executor.execute(deleteEdgeRequest(key, options), Void.class); - } + extends InternalArangoEdgeCollection + implements ArangoEdgeCollection { + + private static final Logger LOGGER = LoggerFactory.getLogger(ArangoEdgeCollectionImpl.class); + + protected ArangoEdgeCollectionImpl(final ArangoGraphImpl graph, final String name) { + super(graph, name); + } + + @Override + public EdgeEntity insertEdge(final T value) throws ArangoDBException { + return executor.execute(insertEdgeRequest(value, new EdgeCreateOptions()), + insertEdgeResponseDeserializer(value)); + } + + @Override + public EdgeEntity insertEdge(final T value, final EdgeCreateOptions options) throws ArangoDBException { + return executor.execute(insertEdgeRequest(value, options), insertEdgeResponseDeserializer(value)); + } + + @Override + public T getEdge(final String key, final Class type) throws ArangoDBException { + try { + return executor.execute(getEdgeRequest(key, new GraphDocumentReadOptions()), getEdgeResponseDeserializer(type)); + } catch (final ArangoDBException e) { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug(e.getMessage(), e); + } + return null; + } + } + + @Override + public T getEdge(final String key, final Class type, final GraphDocumentReadOptions options) + throws ArangoDBException { + try { + return executor.execute(getEdgeRequest(key, options), getEdgeResponseDeserializer(type)); + } catch (final ArangoDBException e) { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug(e.getMessage(), e); + } + return null; + } + } + + @Override + public EdgeUpdateEntity replaceEdge(final String key, final T value) throws ArangoDBException { + return executor.execute(replaceEdgeRequest(key, value, new EdgeReplaceOptions()), + replaceEdgeResponseDeserializer(value)); + } + + @Override + public EdgeUpdateEntity replaceEdge(final String key, final T value, final EdgeReplaceOptions options) + throws ArangoDBException { + return executor.execute(replaceEdgeRequest(key, value, options), replaceEdgeResponseDeserializer(value)); + } + + @Override + public EdgeUpdateEntity updateEdge(final String key, final T value) throws ArangoDBException { + return executor.execute(updateEdgeRequest(key, value, new EdgeUpdateOptions()), + updateEdgeResponseDeserializer(value)); + } + + @Override + public EdgeUpdateEntity updateEdge(final String key, final T value, final EdgeUpdateOptions options) + throws ArangoDBException { + return executor.execute(updateEdgeRequest(key, value, options), updateEdgeResponseDeserializer(value)); + } + + @Override + public void deleteEdge(final String key) throws ArangoDBException { + executor.execute(deleteEdgeRequest(key, new EdgeDeleteOptions()), Void.class); + } + + @Override + public void deleteEdge(final String key, final EdgeDeleteOptions options) throws ArangoDBException { + executor.execute(deleteEdgeRequest(key, options), Void.class); + } } diff --git a/src/main/java/com/arangodb/internal/ArangoErrors.java b/src/main/java/com/arangodb/internal/ArangoErrors.java index 7fbee359f..c3d71ce6f 100644 --- a/src/main/java/com/arangodb/internal/ArangoErrors.java +++ b/src/main/java/com/arangodb/internal/ArangoErrors.java @@ -22,16 +22,15 @@ /** * @author Mark Vollmary - * */ public final class ArangoErrors { - private ArangoErrors() { - super(); - } + private ArangoErrors() { + super(); + } - public static final Integer ERROR_ARANGO_DATA_SOURCE_NOT_FOUND = 1203; - public static final Integer ERROR_ARANGO_DATABASE_NOT_FOUND = 1228; - public static final Integer ERROR_GRAPH_NOT_FOUND = 1924; + public static final Integer ERROR_ARANGO_DATA_SOURCE_NOT_FOUND = 1203; + public static final Integer ERROR_ARANGO_DATABASE_NOT_FOUND = 1228; + public static final Integer ERROR_GRAPH_NOT_FOUND = 1924; } diff --git a/src/main/java/com/arangodb/internal/ArangoExecuteable.java b/src/main/java/com/arangodb/internal/ArangoExecuteable.java index 40c549c91..4644aa288 100644 --- a/src/main/java/com/arangodb/internal/ArangoExecuteable.java +++ b/src/main/java/com/arangodb/internal/ArangoExecuteable.java @@ -20,9 +20,6 @@ package com.arangodb.internal; -import java.io.UnsupportedEncodingException; -import java.util.Map.Entry; - import com.arangodb.ArangoDBException; import com.arangodb.internal.util.ArangoSerializationFactory; import com.arangodb.internal.util.ArangoSerializationFactory.Serializer; @@ -31,64 +28,66 @@ import com.arangodb.velocystream.Request; import com.arangodb.velocystream.RequestType; +import java.io.UnsupportedEncodingException; +import java.util.Map.Entry; + /** * @author Mark Vollmary - * */ public abstract class ArangoExecuteable { - private static final String SLASH = "/"; + private static final String SLASH = "/"; - protected final E executor; - protected final ArangoSerializationFactory util; - protected final ArangoContext context; + protected final E executor; + protected final ArangoSerializationFactory util; + protected final ArangoContext context; - protected ArangoExecuteable(final E executor, final ArangoSerializationFactory util, final ArangoContext context) { - super(); - this.executor = executor; - this.util = util; - this.context = context; - } + protected ArangoExecuteable(final E executor, final ArangoSerializationFactory util, final ArangoContext context) { + super(); + this.executor = executor; + this.util = util; + this.context = context; + } - protected E executor() { - return executor; - } + protected E executor() { + return executor; + } - public ArangoSerialization util() { - return util.get(Serializer.INTERNAL); - } + public ArangoSerialization util() { + return util.get(Serializer.INTERNAL); + } - public ArangoSerialization util(final Serializer serializer) { - return util.get(serializer); - } + public ArangoSerialization util(final Serializer serializer) { + return util.get(serializer); + } - protected Request request(final String database, final RequestType requestType, final String... path) { - final Request request = new Request(database, requestType, createPath(path)); - for (final Entry header : context.getHeaderParam().entrySet()) { - request.putHeaderParam(header.getKey(), header.getValue()); - } - return request; - } + protected Request request(final String database, final RequestType requestType, final String... path) { + final Request request = new Request(database, requestType, createPath(path)); + for (final Entry header : context.getHeaderParam().entrySet()) { + request.putHeaderParam(header.getKey(), header.getValue()); + } + return request; + } - protected static String createPath(final String... params) { - final StringBuilder sb = new StringBuilder(); - for (int i = 0; i < params.length; i++) { - if (i > 0) { - sb.append(SLASH); - } - try { - final String param; - if (params[i].contains(SLASH)) { - param = createPath(params[i].split(SLASH)); - } else { - param = EncodeUtils.encodeURL(params[i]); - } - sb.append(param); - } catch (final UnsupportedEncodingException e) { - throw new ArangoDBException(e); - } - } - return sb.toString(); - } + protected static String createPath(final String... params) { + final StringBuilder sb = new StringBuilder(); + for (int i = 0; i < params.length; i++) { + if (i > 0) { + sb.append(SLASH); + } + try { + final String param; + if (params[i].contains(SLASH)) { + param = createPath(params[i].split(SLASH)); + } else { + param = EncodeUtils.encodeURL(params[i]); + } + sb.append(param); + } catch (final UnsupportedEncodingException e) { + throw new ArangoDBException(e); + } + } + return sb.toString(); + } } diff --git a/src/main/java/com/arangodb/internal/ArangoExecutor.java b/src/main/java/com/arangodb/internal/ArangoExecutor.java index ff311a1ef..6d8b34197 100644 --- a/src/main/java/com/arangodb/internal/ArangoExecutor.java +++ b/src/main/java/com/arangodb/internal/ArangoExecutor.java @@ -36,7 +36,7 @@ public abstract class ArangoExecutor { @SuppressWarnings("unchecked") protected T createResult(final Type type, final Response response) { if (type != Void.class && response.getBody() != null) { - if (type instanceof Class && Entity.class.isAssignableFrom((Class) type) ) { + if (type instanceof Class && Entity.class.isAssignableFrom((Class) type)) { return (T) util.get(Serializer.INTERNAL).deserialize(response.getBody(), type); } else { return (T) util.get(Serializer.CUSTOM).deserialize(response.getBody(), type); diff --git a/src/main/java/com/arangodb/internal/ArangoExecutorSync.java b/src/main/java/com/arangodb/internal/ArangoExecutorSync.java index 469c2b973..20143fc8c 100644 --- a/src/main/java/com/arangodb/internal/ArangoExecutorSync.java +++ b/src/main/java/com/arangodb/internal/ArangoExecutorSync.java @@ -36,59 +36,58 @@ /** * @author Mark Vollmary - * */ public class ArangoExecutorSync extends ArangoExecutor { - - private static final Logger LOG = LoggerFactory.getLogger(ArangoExecutorSync.class); - - private final CommunicationProtocol protocol; - - public ArangoExecutorSync(final CommunicationProtocol protocol, final ArangoSerializationFactory util, - final DocumentCache documentCache) { - super(util, documentCache); - this.protocol = protocol; - } - - public T execute(final Request request, final Type type) throws ArangoDBException { - return execute(request, type, null); - } - - public T execute(final Request request, final Type type, final HostHandle hostHandle) throws ArangoDBException { - return execute(request, response -> createResult(type, response), hostHandle); - } - - public T execute(final Request request, final ResponseDeserializer responseDeserializer) throws ArangoDBException { - return execute(request, responseDeserializer, null); - } - - public T execute( - final Request request, - final ResponseDeserializer responseDeserializer, - final HostHandle hostHandle) throws ArangoDBException { - - try { - - final Response response = protocol.execute(request, hostHandle); - T deserialize = responseDeserializer.deserialize(response); - - if(deserialize instanceof MetaAware) { - LOG.debug("Response is MetaAware " + deserialize.getClass().getName()); - ((MetaAware) deserialize).setMeta(response.getMeta()); - } - - return deserialize; - - } catch (final VPackException e) { - throw new ArangoDBException(e); - } - } - - public void disconnect() { - try { - protocol.close(); - } catch (final IOException e) { - throw new ArangoDBException(e); - } - } + + private static final Logger LOG = LoggerFactory.getLogger(ArangoExecutorSync.class); + + private final CommunicationProtocol protocol; + + public ArangoExecutorSync(final CommunicationProtocol protocol, final ArangoSerializationFactory util, + final DocumentCache documentCache) { + super(util, documentCache); + this.protocol = protocol; + } + + public T execute(final Request request, final Type type) throws ArangoDBException { + return execute(request, type, null); + } + + public T execute(final Request request, final Type type, final HostHandle hostHandle) throws ArangoDBException { + return execute(request, response -> createResult(type, response), hostHandle); + } + + public T execute(final Request request, final ResponseDeserializer responseDeserializer) throws ArangoDBException { + return execute(request, responseDeserializer, null); + } + + public T execute( + final Request request, + final ResponseDeserializer responseDeserializer, + final HostHandle hostHandle) throws ArangoDBException { + + try { + + final Response response = protocol.execute(request, hostHandle); + T deserialize = responseDeserializer.deserialize(response); + + if (deserialize instanceof MetaAware) { + LOG.debug("Response is MetaAware " + deserialize.getClass().getName()); + ((MetaAware) deserialize).setMeta(response.getMeta()); + } + + return deserialize; + + } catch (final VPackException e) { + throw new ArangoDBException(e); + } + } + + public void disconnect() { + try { + protocol.close(); + } catch (final IOException e) { + throw new ArangoDBException(e); + } + } } diff --git a/src/main/java/com/arangodb/internal/ArangoGraphImpl.java b/src/main/java/com/arangodb/internal/ArangoGraphImpl.java index 7af6e3efc..7c9a79ba4 100644 --- a/src/main/java/com/arangodb/internal/ArangoGraphImpl.java +++ b/src/main/java/com/arangodb/internal/ArangoGraphImpl.java @@ -20,8 +20,6 @@ package com.arangodb.internal; -import java.util.Collection; - import com.arangodb.ArangoDBException; import com.arangodb.ArangoEdgeCollection; import com.arangodb.ArangoGraph; @@ -30,95 +28,96 @@ import com.arangodb.entity.GraphEntity; import com.arangodb.model.GraphCreateOptions; +import java.util.Collection; + /** * @author Mark Vollmary - * */ public class ArangoGraphImpl extends InternalArangoGraph - implements ArangoGraph { - - protected ArangoGraphImpl(final ArangoDatabaseImpl db, final String name) { - super(db, name); - } - - @Override - public boolean exists() throws ArangoDBException { - try { - getInfo(); - return true; - } catch (final ArangoDBException e) { - if (ArangoErrors.ERROR_GRAPH_NOT_FOUND.equals(e.getErrorNum())) { - return false; - } - throw e; - } - } - - @Override - public GraphEntity create(final Collection edgeDefinitions) throws ArangoDBException { - return db().createGraph(name(), edgeDefinitions); - } - - @Override - public GraphEntity create(final Collection edgeDefinitions, final GraphCreateOptions options) - throws ArangoDBException { - return db().createGraph(name(), edgeDefinitions, options); - } - - @Override - public void drop() throws ArangoDBException { - executor.execute(dropRequest(), Void.class); - } - - @Override - public void drop(final boolean dropCollections) throws ArangoDBException { - executor.execute(dropRequest(dropCollections), Void.class); - } - - @Override - public GraphEntity getInfo() throws ArangoDBException { - return executor.execute(getInfoRequest(), getInfoResponseDeserializer()); - } - - @Override - public Collection getVertexCollections() throws ArangoDBException { - return executor.execute(getVertexCollectionsRequest(), getVertexCollectionsResponseDeserializer()); - } - - @Override - public GraphEntity addVertexCollection(final String name) throws ArangoDBException { - return executor.execute(addVertexCollectionRequest(name), addVertexCollectionResponseDeserializer()); - } - - @Override - public ArangoVertexCollection vertexCollection(final String name) { - return new ArangoVertexCollectionImpl(this, name); - } - - @Override - public ArangoEdgeCollection edgeCollection(final String name) { - return new ArangoEdgeCollectionImpl(this, name); - } - - @Override - public Collection getEdgeDefinitions() throws ArangoDBException { - return executor.execute(getEdgeDefinitionsRequest(), getEdgeDefinitionsDeserializer()); - } - - @Override - public GraphEntity addEdgeDefinition(final EdgeDefinition definition) throws ArangoDBException { - return executor.execute(addEdgeDefinitionRequest(definition), addEdgeDefinitionResponseDeserializer()); - } - - @Override - public GraphEntity replaceEdgeDefinition(final EdgeDefinition definition) throws ArangoDBException { - return executor.execute(replaceEdgeDefinitionRequest(definition), replaceEdgeDefinitionResponseDeserializer()); - } - - @Override - public GraphEntity removeEdgeDefinition(final String definitionName) throws ArangoDBException { - return executor.execute(removeEdgeDefinitionRequest(definitionName), - removeEdgeDefinitionResponseDeserializer()); - } + implements ArangoGraph { + + protected ArangoGraphImpl(final ArangoDatabaseImpl db, final String name) { + super(db, name); + } + + @Override + public boolean exists() throws ArangoDBException { + try { + getInfo(); + return true; + } catch (final ArangoDBException e) { + if (ArangoErrors.ERROR_GRAPH_NOT_FOUND.equals(e.getErrorNum())) { + return false; + } + throw e; + } + } + + @Override + public GraphEntity create(final Collection edgeDefinitions) throws ArangoDBException { + return db().createGraph(name(), edgeDefinitions); + } + + @Override + public GraphEntity create(final Collection edgeDefinitions, final GraphCreateOptions options) + throws ArangoDBException { + return db().createGraph(name(), edgeDefinitions, options); + } + + @Override + public void drop() throws ArangoDBException { + executor.execute(dropRequest(), Void.class); + } + + @Override + public void drop(final boolean dropCollections) throws ArangoDBException { + executor.execute(dropRequest(dropCollections), Void.class); + } + + @Override + public GraphEntity getInfo() throws ArangoDBException { + return executor.execute(getInfoRequest(), getInfoResponseDeserializer()); + } + + @Override + public Collection getVertexCollections() throws ArangoDBException { + return executor.execute(getVertexCollectionsRequest(), getVertexCollectionsResponseDeserializer()); + } + + @Override + public GraphEntity addVertexCollection(final String name) throws ArangoDBException { + return executor.execute(addVertexCollectionRequest(name), addVertexCollectionResponseDeserializer()); + } + + @Override + public ArangoVertexCollection vertexCollection(final String name) { + return new ArangoVertexCollectionImpl(this, name); + } + + @Override + public ArangoEdgeCollection edgeCollection(final String name) { + return new ArangoEdgeCollectionImpl(this, name); + } + + @Override + public Collection getEdgeDefinitions() throws ArangoDBException { + return executor.execute(getEdgeDefinitionsRequest(), getEdgeDefinitionsDeserializer()); + } + + @Override + public GraphEntity addEdgeDefinition(final EdgeDefinition definition) throws ArangoDBException { + return executor.execute(addEdgeDefinitionRequest(definition), addEdgeDefinitionResponseDeserializer()); + } + + @Override + public GraphEntity replaceEdgeDefinition(final EdgeDefinition definition) throws ArangoDBException { + return executor.execute(replaceEdgeDefinitionRequest(definition), replaceEdgeDefinitionResponseDeserializer()); + } + + @Override + public GraphEntity removeEdgeDefinition(final String definitionName) throws ArangoDBException { + return executor.execute(removeEdgeDefinitionRequest(definitionName), + removeEdgeDefinitionResponseDeserializer()); + } } diff --git a/src/main/java/com/arangodb/internal/ArangoRequestParam.java b/src/main/java/com/arangodb/internal/ArangoRequestParam.java index b1384af0c..62c9be370 100644 --- a/src/main/java/com/arangodb/internal/ArangoRequestParam.java +++ b/src/main/java/com/arangodb/internal/ArangoRequestParam.java @@ -22,19 +22,18 @@ /** * @author Mark Vollmary - * */ public final class ArangoRequestParam { - private ArangoRequestParam() { - super(); - } + private ArangoRequestParam() { + super(); + } - public static final String SYSTEM = "_system"; - public static final String DATABASE = "database"; - public static final String WAIT_FOR_SYNC = "waitForSync"; - public static final String IF_NONE_MATCH = "If-None-Match"; - public static final String IF_MATCH = "If-Match"; - public static final String KEEP_NULL = "keepNull"; + public static final String SYSTEM = "_system"; + public static final String DATABASE = "database"; + public static final String WAIT_FOR_SYNC = "waitForSync"; + public static final String IF_NONE_MATCH = "If-None-Match"; + public static final String IF_MATCH = "If-Match"; + public static final String KEEP_NULL = "keepNull"; } diff --git a/src/main/java/com/arangodb/internal/ArangoResponseField.java b/src/main/java/com/arangodb/internal/ArangoResponseField.java index eda8b6da2..846774a3e 100644 --- a/src/main/java/com/arangodb/internal/ArangoResponseField.java +++ b/src/main/java/com/arangodb/internal/ArangoResponseField.java @@ -22,15 +22,14 @@ /** * @author Mark Vollmary - * */ public final class ArangoResponseField { - private ArangoResponseField() { - super(); - } + private ArangoResponseField() { + super(); + } - public static final String ERROR = "error"; - public static final String RESULT = "result"; + public static final String ERROR = "error"; + public static final String RESULT = "result"; } diff --git a/src/main/java/com/arangodb/internal/ArangoRouteImpl.java b/src/main/java/com/arangodb/internal/ArangoRouteImpl.java index fd6f86702..a2ae40f05 100644 --- a/src/main/java/com/arangodb/internal/ArangoRouteImpl.java +++ b/src/main/java/com/arangodb/internal/ArangoRouteImpl.java @@ -29,70 +29,69 @@ /** * @author Mark Vollmary - * */ public class ArangoRouteImpl extends InternalArangoRoute - implements ArangoRoute { - - protected ArangoRouteImpl(final ArangoDatabaseImpl db, final String path, final Map headerParam) { - super(db, path, headerParam); - } - - @Override - public ArangoRoute route(final String... path) { - return new ArangoRouteImpl(db, createPath(this.path, createPath(path)), headerParam); - } - - @Override - public ArangoRoute withHeader(final String key, final Object value) { - _withHeader(key, value); - return this; - } - - @Override - public ArangoRoute withQueryParam(final String key, final Object value) { - _withQueryParam(key, value); - return this; - } - - @Override - public ArangoRoute withBody(final Object body) { - _withBody(body); - return this; - } - - private Response request(final RequestType requestType) { + implements ArangoRoute { + + protected ArangoRouteImpl(final ArangoDatabaseImpl db, final String path, final Map headerParam) { + super(db, path, headerParam); + } + + @Override + public ArangoRoute route(final String... path) { + return new ArangoRouteImpl(db, createPath(this.path, createPath(path)), headerParam); + } + + @Override + public ArangoRoute withHeader(final String key, final Object value) { + _withHeader(key, value); + return this; + } + + @Override + public ArangoRoute withQueryParam(final String key, final Object value) { + _withQueryParam(key, value); + return this; + } + + @Override + public ArangoRoute withBody(final Object body) { + _withBody(body); + return this; + } + + private Response request(final RequestType requestType) { return executor.execute(createRequest(requestType), response -> response); - } - - @Override - public Response delete() throws ArangoDBException { - return request(RequestType.DELETE); - } - - @Override - public Response get() throws ArangoDBException { - return request(RequestType.GET); - } - - @Override - public Response head() throws ArangoDBException { - return request(RequestType.HEAD); - } - - @Override - public Response patch() throws ArangoDBException { - return request(RequestType.PATCH); - } - - @Override - public Response post() throws ArangoDBException { - return request(RequestType.POST); - } - - @Override - public Response put() throws ArangoDBException { - return request(RequestType.PUT); - } + } + + @Override + public Response delete() throws ArangoDBException { + return request(RequestType.DELETE); + } + + @Override + public Response get() throws ArangoDBException { + return request(RequestType.GET); + } + + @Override + public Response head() throws ArangoDBException { + return request(RequestType.HEAD); + } + + @Override + public Response patch() throws ArangoDBException { + return request(RequestType.PATCH); + } + + @Override + public Response post() throws ArangoDBException { + return request(RequestType.POST); + } + + @Override + public Response put() throws ArangoDBException { + return request(RequestType.PUT); + } } diff --git a/src/main/java/com/arangodb/internal/ArangoSearchImpl.java b/src/main/java/com/arangodb/internal/ArangoSearchImpl.java index 854569194..286a34787 100644 --- a/src/main/java/com/arangodb/internal/ArangoSearchImpl.java +++ b/src/main/java/com/arangodb/internal/ArangoSearchImpl.java @@ -29,70 +29,69 @@ /** * @author Mark Vollmary - * */ public class ArangoSearchImpl extends InternalArangoSearch - implements ArangoSearch { + implements ArangoSearch { - protected ArangoSearchImpl(final ArangoDatabaseImpl db, final String name) { - super(db, name); - } + protected ArangoSearchImpl(final ArangoDatabaseImpl db, final String name) { + super(db, name); + } - @Override - public boolean exists() throws ArangoDBException { - try { - getInfo(); - return true; - } catch (final ArangoDBException e) { - if (ArangoErrors.ERROR_ARANGO_DATA_SOURCE_NOT_FOUND.equals(e.getErrorNum())) { - return false; - } - throw e; - } - } + @Override + public boolean exists() throws ArangoDBException { + try { + getInfo(); + return true; + } catch (final ArangoDBException e) { + if (ArangoErrors.ERROR_ARANGO_DATA_SOURCE_NOT_FOUND.equals(e.getErrorNum())) { + return false; + } + throw e; + } + } - @Override - public void drop() throws ArangoDBException { - executor.execute(dropRequest(), Void.class); - } + @Override + public void drop() throws ArangoDBException { + executor.execute(dropRequest(), Void.class); + } - @Override - public synchronized ViewEntity rename(final String newName) throws ArangoDBException { - final ViewEntity result = executor.execute(renameRequest(newName), ViewEntity.class); - name = result.getName(); - return result; - } + @Override + public synchronized ViewEntity rename(final String newName) throws ArangoDBException { + final ViewEntity result = executor.execute(renameRequest(newName), ViewEntity.class); + name = result.getName(); + return result; + } - @Override - public ViewEntity getInfo() throws ArangoDBException { - return executor.execute(getInfoRequest(), ViewEntity.class); - } + @Override + public ViewEntity getInfo() throws ArangoDBException { + return executor.execute(getInfoRequest(), ViewEntity.class); + } - @Override - public ViewEntity create() throws ArangoDBException { - return create(new ArangoSearchCreateOptions()); - } + @Override + public ViewEntity create() throws ArangoDBException { + return create(new ArangoSearchCreateOptions()); + } - @Override - public ViewEntity create(final ArangoSearchCreateOptions options) throws ArangoDBException { - return db().createArangoSearch(name(), options); - } + @Override + public ViewEntity create(final ArangoSearchCreateOptions options) throws ArangoDBException { + return db().createArangoSearch(name(), options); + } - @Override - public ArangoSearchPropertiesEntity getProperties() throws ArangoDBException { - return executor.execute(getPropertiesRequest(), ArangoSearchPropertiesEntity.class); - } + @Override + public ArangoSearchPropertiesEntity getProperties() throws ArangoDBException { + return executor.execute(getPropertiesRequest(), ArangoSearchPropertiesEntity.class); + } - @Override - public ArangoSearchPropertiesEntity updateProperties(final ArangoSearchPropertiesOptions options) - throws ArangoDBException { - return executor.execute(updatePropertiesRequest(options), ArangoSearchPropertiesEntity.class); - } + @Override + public ArangoSearchPropertiesEntity updateProperties(final ArangoSearchPropertiesOptions options) + throws ArangoDBException { + return executor.execute(updatePropertiesRequest(options), ArangoSearchPropertiesEntity.class); + } - @Override - public ArangoSearchPropertiesEntity replaceProperties(final ArangoSearchPropertiesOptions options) - throws ArangoDBException { - return executor.execute(replacePropertiesRequest(options), ArangoSearchPropertiesEntity.class); - } + @Override + public ArangoSearchPropertiesEntity replaceProperties(final ArangoSearchPropertiesOptions options) + throws ArangoDBException { + return executor.execute(replacePropertiesRequest(options), ArangoSearchPropertiesEntity.class); + } } diff --git a/src/main/java/com/arangodb/internal/ArangoVertexCollectionImpl.java b/src/main/java/com/arangodb/internal/ArangoVertexCollectionImpl.java index a8d41f862..399ec2321 100644 --- a/src/main/java/com/arangodb/internal/ArangoVertexCollectionImpl.java +++ b/src/main/java/com/arangodb/internal/ArangoVertexCollectionImpl.java @@ -20,103 +20,101 @@ package com.arangodb.internal; -import com.arangodb.model.*; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import com.arangodb.ArangoDBException; import com.arangodb.ArangoVertexCollection; import com.arangodb.entity.VertexEntity; import com.arangodb.entity.VertexUpdateEntity; +import com.arangodb.model.*; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * @author Mark Vollmary - * */ public class ArangoVertexCollectionImpl - extends InternalArangoVertexCollection - implements ArangoVertexCollection { - - private static final Logger LOGGER = LoggerFactory.getLogger(ArangoVertexCollectionImpl.class); - - protected ArangoVertexCollectionImpl(final ArangoGraphImpl graph, final String name) { - super(graph, name); - } - - @Override - public void drop() throws ArangoDBException { - executor.execute(dropRequest(), Void.class); - } - - @Override - public VertexEntity insertVertex(final T value) throws ArangoDBException { - return executor.execute(insertVertexRequest(value, new VertexCreateOptions()), - insertVertexResponseDeserializer(value)); - } - - @Override - public VertexEntity insertVertex(final T value, final VertexCreateOptions options) throws ArangoDBException { - return executor.execute(insertVertexRequest(value, options), insertVertexResponseDeserializer(value)); - } - - @Override - public T getVertex(final String key, final Class type) throws ArangoDBException { - try { - return executor.execute(getVertexRequest(key, new GraphDocumentReadOptions()), - getVertexResponseDeserializer(type)); - } catch (final ArangoDBException e) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug(e.getMessage(), e); - } - return null; - } - } - - @Override - public T getVertex(final String key, final Class type, final GraphDocumentReadOptions options) - throws ArangoDBException { - try { - return executor.execute(getVertexRequest(key, options), getVertexResponseDeserializer(type)); - } catch (final ArangoDBException e) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug(e.getMessage(), e); - } - return null; - } - } - - @Override - public VertexUpdateEntity replaceVertex(final String key, final T value) throws ArangoDBException { - return executor.execute(replaceVertexRequest(key, value, new VertexReplaceOptions()), - replaceVertexResponseDeserializer(value)); - } - - @Override - public VertexUpdateEntity replaceVertex(final String key, final T value, final VertexReplaceOptions options) - throws ArangoDBException { - return executor.execute(replaceVertexRequest(key, value, options), replaceVertexResponseDeserializer(value)); - } - - @Override - public VertexUpdateEntity updateVertex(final String key, final T value) throws ArangoDBException { - return executor.execute(updateVertexRequest(key, value, new VertexUpdateOptions()), - updateVertexResponseDeserializer(value)); - } - - @Override - public VertexUpdateEntity updateVertex(final String key, final T value, final VertexUpdateOptions options) - throws ArangoDBException { - return executor.execute(updateVertexRequest(key, value, options), updateVertexResponseDeserializer(value)); - } - - @Override - public void deleteVertex(final String key) throws ArangoDBException { - executor.execute(deleteVertexRequest(key, new VertexDeleteOptions()), Void.class); - } - - @Override - public void deleteVertex(final String key, final VertexDeleteOptions options) throws ArangoDBException { - executor.execute(deleteVertexRequest(key, options), Void.class); - } + extends InternalArangoVertexCollection + implements ArangoVertexCollection { + + private static final Logger LOGGER = LoggerFactory.getLogger(ArangoVertexCollectionImpl.class); + + protected ArangoVertexCollectionImpl(final ArangoGraphImpl graph, final String name) { + super(graph, name); + } + + @Override + public void drop() throws ArangoDBException { + executor.execute(dropRequest(), Void.class); + } + + @Override + public VertexEntity insertVertex(final T value) throws ArangoDBException { + return executor.execute(insertVertexRequest(value, new VertexCreateOptions()), + insertVertexResponseDeserializer(value)); + } + + @Override + public VertexEntity insertVertex(final T value, final VertexCreateOptions options) throws ArangoDBException { + return executor.execute(insertVertexRequest(value, options), insertVertexResponseDeserializer(value)); + } + + @Override + public T getVertex(final String key, final Class type) throws ArangoDBException { + try { + return executor.execute(getVertexRequest(key, new GraphDocumentReadOptions()), + getVertexResponseDeserializer(type)); + } catch (final ArangoDBException e) { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug(e.getMessage(), e); + } + return null; + } + } + + @Override + public T getVertex(final String key, final Class type, final GraphDocumentReadOptions options) + throws ArangoDBException { + try { + return executor.execute(getVertexRequest(key, options), getVertexResponseDeserializer(type)); + } catch (final ArangoDBException e) { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug(e.getMessage(), e); + } + return null; + } + } + + @Override + public VertexUpdateEntity replaceVertex(final String key, final T value) throws ArangoDBException { + return executor.execute(replaceVertexRequest(key, value, new VertexReplaceOptions()), + replaceVertexResponseDeserializer(value)); + } + + @Override + public VertexUpdateEntity replaceVertex(final String key, final T value, final VertexReplaceOptions options) + throws ArangoDBException { + return executor.execute(replaceVertexRequest(key, value, options), replaceVertexResponseDeserializer(value)); + } + + @Override + public VertexUpdateEntity updateVertex(final String key, final T value) throws ArangoDBException { + return executor.execute(updateVertexRequest(key, value, new VertexUpdateOptions()), + updateVertexResponseDeserializer(value)); + } + + @Override + public VertexUpdateEntity updateVertex(final String key, final T value, final VertexUpdateOptions options) + throws ArangoDBException { + return executor.execute(updateVertexRequest(key, value, options), updateVertexResponseDeserializer(value)); + } + + @Override + public void deleteVertex(final String key) throws ArangoDBException { + executor.execute(deleteVertexRequest(key, new VertexDeleteOptions()), Void.class); + } + + @Override + public void deleteVertex(final String key, final VertexDeleteOptions options) throws ArangoDBException { + executor.execute(deleteVertexRequest(key, options), Void.class); + } } diff --git a/src/main/java/com/arangodb/internal/ArangoViewImpl.java b/src/main/java/com/arangodb/internal/ArangoViewImpl.java index 00ff45f1e..60faebd7e 100644 --- a/src/main/java/com/arangodb/internal/ArangoViewImpl.java +++ b/src/main/java/com/arangodb/internal/ArangoViewImpl.java @@ -26,43 +26,42 @@ /** * @author Mark Vollmary - * */ public class ArangoViewImpl extends InternalArangoView - implements ArangoView { + implements ArangoView { - protected ArangoViewImpl(final ArangoDatabaseImpl db, final String name) { - super(db, name); - } + protected ArangoViewImpl(final ArangoDatabaseImpl db, final String name) { + super(db, name); + } - @Override - public boolean exists() throws ArangoDBException { - try { - getInfo(); - return true; - } catch (final ArangoDBException e) { - if (ArangoErrors.ERROR_ARANGO_DATA_SOURCE_NOT_FOUND.equals(e.getErrorNum())) { - return false; - } - throw e; - } - } + @Override + public boolean exists() throws ArangoDBException { + try { + getInfo(); + return true; + } catch (final ArangoDBException e) { + if (ArangoErrors.ERROR_ARANGO_DATA_SOURCE_NOT_FOUND.equals(e.getErrorNum())) { + return false; + } + throw e; + } + } - @Override - public void drop() throws ArangoDBException { - executor.execute(dropRequest(), Void.class); - } + @Override + public void drop() throws ArangoDBException { + executor.execute(dropRequest(), Void.class); + } - @Override - public synchronized ViewEntity rename(final String newName) throws ArangoDBException { - final ViewEntity result = executor.execute(renameRequest(newName), ViewEntity.class); - name = result.getName(); - return result; - } + @Override + public synchronized ViewEntity rename(final String newName) throws ArangoDBException { + final ViewEntity result = executor.execute(renameRequest(newName), ViewEntity.class); + name = result.getName(); + return result; + } - @Override - public ViewEntity getInfo() throws ArangoDBException { - return executor.execute(getInfoRequest(), ViewEntity.class); - } + @Override + public ViewEntity getInfo() throws ArangoDBException { + return executor.execute(getInfoRequest(), ViewEntity.class); + } } diff --git a/src/main/java/com/arangodb/internal/DocumentCache.java b/src/main/java/com/arangodb/internal/DocumentCache.java index 2ed95e532..c4de2f44c 100644 --- a/src/main/java/com/arangodb/internal/DocumentCache.java +++ b/src/main/java/com/arangodb/internal/DocumentCache.java @@ -31,75 +31,74 @@ /** * @author Mark Vollmary - * */ public class DocumentCache { - private final Map, Map> cache; + private final Map, Map> cache; - public DocumentCache() { - super(); - cache = new HashMap<>(); - } + public DocumentCache() { + super(); + cache = new HashMap<>(); + } - public void setValues(final Object doc, final Map values) throws ArangoDBException { - try { - final Map fields = getFields(doc.getClass()); - for (final Entry value : values.entrySet()) { - final Field field = fields.get(value.getKey()); - if (field != null) { - field.set(doc, value.getValue()); - } - } - } catch (final IllegalArgumentException | IllegalAccessException e) { - throw new ArangoDBException(e); - } - } + public void setValues(final Object doc, final Map values) throws ArangoDBException { + try { + final Map fields = getFields(doc.getClass()); + for (final Entry value : values.entrySet()) { + final Field field = fields.get(value.getKey()); + if (field != null) { + field.set(doc, value.getValue()); + } + } + } catch (final IllegalArgumentException | IllegalAccessException e) { + throw new ArangoDBException(e); + } + } - private Map getFields(final Class clazz) { - Map fields = new HashMap<>(); - if (!isTypeRestricted(clazz)) { - fields = cache.get(clazz); - if (fields == null) { - fields = createFields(clazz); - cache.put(clazz, fields); - } - } - return fields; - } + private Map getFields(final Class clazz) { + Map fields = new HashMap<>(); + if (!isTypeRestricted(clazz)) { + fields = cache.get(clazz); + if (fields == null) { + fields = createFields(clazz); + cache.put(clazz, fields); + } + } + return fields; + } - private boolean isTypeRestricted(final Class type) { - return Map.class.isAssignableFrom(type) || Collection.class.isAssignableFrom(type); - } + private boolean isTypeRestricted(final Class type) { + return Map.class.isAssignableFrom(type) || Collection.class.isAssignableFrom(type); + } - private Map createFields(final Class clazz) { - final Map fields = new HashMap<>(); - Class tmp = clazz; - final Collection values = new ArrayList<>( - Arrays.asList(DocumentField.Type.values())); - while (tmp != null && tmp != Object.class && values.size() > 0) { - final Field[] declaredFields = tmp.getDeclaredFields(); - for (int i = 0; i < declaredFields.length && values.size() > 0; i++) { - findAnnotation(values, fields, declaredFields[i]); - } - tmp = tmp.getSuperclass(); - } - return fields; - } + private Map createFields(final Class clazz) { + final Map fields = new HashMap<>(); + Class tmp = clazz; + final Collection values = new ArrayList<>( + Arrays.asList(DocumentField.Type.values())); + while (tmp != null && tmp != Object.class && values.size() > 0) { + final Field[] declaredFields = tmp.getDeclaredFields(); + for (int i = 0; i < declaredFields.length && values.size() > 0; i++) { + findAnnotation(values, fields, declaredFields[i]); + } + tmp = tmp.getSuperclass(); + } + return fields; + } - private void findAnnotation( - final Collection values, - final Map fields, - final Field field) { - final DocumentField annotation = field.getAnnotation(DocumentField.class); - if (annotation != null && !field.isSynthetic() && !Modifier.isStatic(field.getModifiers()) - && String.class.isAssignableFrom(field.getType())) { - final Type value = annotation.value(); - if (values.contains(value)) { - field.setAccessible(true); - fields.put(value, field); - values.remove(value); - } - } - } + private void findAnnotation( + final Collection values, + final Map fields, + final Field field) { + final DocumentField annotation = field.getAnnotation(DocumentField.class); + if (annotation != null && !field.isSynthetic() && !Modifier.isStatic(field.getModifiers()) + && String.class.isAssignableFrom(field.getType())) { + final Type value = annotation.value(); + if (values.contains(value)) { + field.setAccessible(true); + fields.put(value, field); + values.remove(value); + } + } + } } diff --git a/src/main/java/com/arangodb/internal/InternalArangoCollection.java b/src/main/java/com/arangodb/internal/InternalArangoCollection.java index cc9677c65..bffa80ee3 100644 --- a/src/main/java/com/arangodb/internal/InternalArangoCollection.java +++ b/src/main/java/com/arangodb/internal/InternalArangoCollection.java @@ -40,59 +40,59 @@ * @author Michele Rastelli */ public abstract class InternalArangoCollection, D extends InternalArangoDatabase, E extends ArangoExecutor> - extends ArangoExecuteable { - - private static final String COLLECTION = "collection"; - - protected static final String PATH_API_COLLECTION = "/_api/collection"; - private static final String PATH_API_DOCUMENT = "/_api/document"; - private static final String PATH_API_INDEX = "/_api/index"; - private static final String PATH_API_IMPORT = "/_api/import"; - private static final String PATH_API_USER = "/_api/user"; - - private static final String MERGE_OBJECTS = "mergeObjects"; - private static final String IGNORE_REVS = "ignoreRevs"; - private static final String RETURN_NEW = "returnNew"; - private static final String NEW = "new"; - private static final String RETURN_OLD = "returnOld"; - private static final String OVERWRITE = "overwrite"; - private static final String OLD = "old"; - private static final String SILENT = "silent"; - - private static final String TRANSACTION_ID = "x-arango-trx-id"; - - private final D db; - protected volatile String name; - - protected InternalArangoCollection(final D db, final String name) { - super(db.executor, db.util, db.context); - this.db = db; - this.name = name; - } - - public D db() { - return db; - } - - public String name() { - return name; - } - - protected Request insertDocumentRequest(final T value, final DocumentCreateOptions options) { - final Request request = request(db.name(), RequestType.POST, PATH_API_DOCUMENT, name); - final DocumentCreateOptions params = (options != null ? options : new DocumentCreateOptions()); - request.putQueryParam(ArangoRequestParam.WAIT_FOR_SYNC, params.getWaitForSync()); - request.putQueryParam(RETURN_NEW, params.getReturnNew()); - request.putQueryParam(RETURN_OLD, params.getReturnOld()); - request.putQueryParam(SILENT, params.getSilent()); - request.putQueryParam(OVERWRITE, params.getOverwrite()); - request.putHeaderParam(TRANSACTION_ID, params.getStreamTransactionId()); - request.setBody(util(Serializer.CUSTOM).serialize(value)); - return request; - } - - protected ResponseDeserializer> insertDocumentResponseDeserializer( - final T value, final DocumentCreateOptions options) { + extends ArangoExecuteable { + + private static final String COLLECTION = "collection"; + + protected static final String PATH_API_COLLECTION = "/_api/collection"; + private static final String PATH_API_DOCUMENT = "/_api/document"; + private static final String PATH_API_INDEX = "/_api/index"; + private static final String PATH_API_IMPORT = "/_api/import"; + private static final String PATH_API_USER = "/_api/user"; + + private static final String MERGE_OBJECTS = "mergeObjects"; + private static final String IGNORE_REVS = "ignoreRevs"; + private static final String RETURN_NEW = "returnNew"; + private static final String NEW = "new"; + private static final String RETURN_OLD = "returnOld"; + private static final String OVERWRITE = "overwrite"; + private static final String OLD = "old"; + private static final String SILENT = "silent"; + + private static final String TRANSACTION_ID = "x-arango-trx-id"; + + private final D db; + protected volatile String name; + + protected InternalArangoCollection(final D db, final String name) { + super(db.executor, db.util, db.context); + this.db = db; + this.name = name; + } + + public D db() { + return db; + } + + public String name() { + return name; + } + + protected Request insertDocumentRequest(final T value, final DocumentCreateOptions options) { + final Request request = request(db.name(), RequestType.POST, PATH_API_DOCUMENT, name); + final DocumentCreateOptions params = (options != null ? options : new DocumentCreateOptions()); + request.putQueryParam(ArangoRequestParam.WAIT_FOR_SYNC, params.getWaitForSync()); + request.putQueryParam(RETURN_NEW, params.getReturnNew()); + request.putQueryParam(RETURN_OLD, params.getReturnOld()); + request.putQueryParam(SILENT, params.getSilent()); + request.putQueryParam(OVERWRITE, params.getOverwrite()); + request.putHeaderParam(TRANSACTION_ID, params.getStreamTransactionId()); + request.setBody(util(Serializer.CUSTOM).serialize(value)); + return request; + } + + protected ResponseDeserializer> insertDocumentResponseDeserializer( + final T value, final DocumentCreateOptions options) { return response -> { final VPackSlice body = response.getBody(); final DocumentCreateEntity doc = util().deserialize(body, DocumentCreateEntity.class); @@ -113,24 +113,24 @@ protected ResponseDeserializer> insertDocumentRespon } return doc; }; - } - - protected Request insertDocumentsRequest(final Collection values, final DocumentCreateOptions params) { - final Request request = request(db.name(), RequestType.POST, PATH_API_DOCUMENT, name); - request.putQueryParam(ArangoRequestParam.WAIT_FOR_SYNC, params.getWaitForSync()); - request.putQueryParam(RETURN_NEW, params.getReturnNew()); - request.putQueryParam(RETURN_OLD, params.getReturnOld()); - request.putQueryParam(SILENT, params.getSilent()); - request.putQueryParam(OVERWRITE, params.getOverwrite()); - request.putHeaderParam(TRANSACTION_ID, params.getStreamTransactionId()); - request.setBody(util(Serializer.CUSTOM) - .serialize(values, new ArangoSerializer.Options().serializeNullValues(false).stringAsJson(true))); - return request; - } - - @SuppressWarnings("unchecked") - protected ResponseDeserializer>> insertDocumentsResponseDeserializer( - final Collection values, final DocumentCreateOptions params) { + } + + protected Request insertDocumentsRequest(final Collection values, final DocumentCreateOptions params) { + final Request request = request(db.name(), RequestType.POST, PATH_API_DOCUMENT, name); + request.putQueryParam(ArangoRequestParam.WAIT_FOR_SYNC, params.getWaitForSync()); + request.putQueryParam(RETURN_NEW, params.getReturnNew()); + request.putQueryParam(RETURN_OLD, params.getReturnOld()); + request.putQueryParam(SILENT, params.getSilent()); + request.putQueryParam(OVERWRITE, params.getOverwrite()); + request.putHeaderParam(TRANSACTION_ID, params.getStreamTransactionId()); + request.setBody(util(Serializer.CUSTOM) + .serialize(values, new ArangoSerializer.Options().serializeNullValues(false).stringAsJson(true))); + return request; + } + + @SuppressWarnings("unchecked") + protected ResponseDeserializer>> insertDocumentsResponseDeserializer( + final Collection values, final DocumentCreateOptions params) { return response -> { Class type = null; if (Boolean.TRUE == params.getReturnNew()) { @@ -170,54 +170,54 @@ protected ResponseDeserializer>> multiDocument.setDocumentsAndErrors(documentsAndErrors); return multiDocument; }; - } - - protected Request importDocumentsRequest(final String values, final DocumentImportOptions options) { - return importDocumentsRequest(options).putQueryParam("type", ImportType.auto).setBody(util().serialize(values)); - } - - protected Request importDocumentsRequest(final Collection values, final DocumentImportOptions options) { - return importDocumentsRequest(options).putQueryParam("type", ImportType.list).setBody(util(Serializer.CUSTOM) - .serialize(values, new ArangoSerializer.Options().serializeNullValues(false).stringAsJson(true))); - } - - protected Request importDocumentsRequest(final DocumentImportOptions options) { - final DocumentImportOptions params = options != null ? options : new DocumentImportOptions(); - return request(db.name(), RequestType.POST, PATH_API_IMPORT).putQueryParam(COLLECTION, name) - .putQueryParam(ArangoRequestParam.WAIT_FOR_SYNC, params.getWaitForSync()) - .putQueryParam("fromPrefix", params.getFromPrefix()).putQueryParam("toPrefix", params.getToPrefix()) - .putQueryParam(OVERWRITE, params.getOverwrite()).putQueryParam("onDuplicate", params.getOnDuplicate()) - .putQueryParam("complete", params.getComplete()).putQueryParam("details", params.getDetails()); - } - - protected Request getDocumentRequest(final String key, final DocumentReadOptions options) { - final Request request = request(db.name(), RequestType.GET, PATH_API_DOCUMENT, - DocumentUtil.createDocumentHandle(name, key)); - final DocumentReadOptions params = (options != null ? options : new DocumentReadOptions()); - request.putHeaderParam(ArangoRequestParam.IF_NONE_MATCH, params.getIfNoneMatch()); - request.putHeaderParam(ArangoRequestParam.IF_MATCH, params.getIfMatch()); - request.putHeaderParam(TRANSACTION_ID, params.getStreamTransactionId()); - if (params.getAllowDirtyRead() == Boolean.TRUE) { - RequestUtils.allowDirtyRead(request); - } - return request; - } - - protected Request getDocumentsRequest(final Collection keys, final DocumentReadOptions options) { - final DocumentReadOptions params = (options != null ? options : new DocumentReadOptions()); - final Request request = request(db.name(), RequestType.PUT, PATH_API_DOCUMENT, name) - .putQueryParam("onlyget", true) - .putHeaderParam(ArangoRequestParam.IF_NONE_MATCH, params.getIfNoneMatch()) - .putHeaderParam(ArangoRequestParam.IF_MATCH, params.getIfMatch()).setBody(util().serialize(keys)) - .putHeaderParam(TRANSACTION_ID, params.getStreamTransactionId()); - if (params.getAllowDirtyRead() == Boolean.TRUE) { - RequestUtils.allowDirtyRead(request); - } - return request; - } - - protected ResponseDeserializer> getDocumentsResponseDeserializer( - final Class type, final DocumentReadOptions options) { + } + + protected Request importDocumentsRequest(final String values, final DocumentImportOptions options) { + return importDocumentsRequest(options).putQueryParam("type", ImportType.auto).setBody(util().serialize(values)); + } + + protected Request importDocumentsRequest(final Collection values, final DocumentImportOptions options) { + return importDocumentsRequest(options).putQueryParam("type", ImportType.list).setBody(util(Serializer.CUSTOM) + .serialize(values, new ArangoSerializer.Options().serializeNullValues(false).stringAsJson(true))); + } + + protected Request importDocumentsRequest(final DocumentImportOptions options) { + final DocumentImportOptions params = options != null ? options : new DocumentImportOptions(); + return request(db.name(), RequestType.POST, PATH_API_IMPORT).putQueryParam(COLLECTION, name) + .putQueryParam(ArangoRequestParam.WAIT_FOR_SYNC, params.getWaitForSync()) + .putQueryParam("fromPrefix", params.getFromPrefix()).putQueryParam("toPrefix", params.getToPrefix()) + .putQueryParam(OVERWRITE, params.getOverwrite()).putQueryParam("onDuplicate", params.getOnDuplicate()) + .putQueryParam("complete", params.getComplete()).putQueryParam("details", params.getDetails()); + } + + protected Request getDocumentRequest(final String key, final DocumentReadOptions options) { + final Request request = request(db.name(), RequestType.GET, PATH_API_DOCUMENT, + DocumentUtil.createDocumentHandle(name, key)); + final DocumentReadOptions params = (options != null ? options : new DocumentReadOptions()); + request.putHeaderParam(ArangoRequestParam.IF_NONE_MATCH, params.getIfNoneMatch()); + request.putHeaderParam(ArangoRequestParam.IF_MATCH, params.getIfMatch()); + request.putHeaderParam(TRANSACTION_ID, params.getStreamTransactionId()); + if (params.getAllowDirtyRead() == Boolean.TRUE) { + RequestUtils.allowDirtyRead(request); + } + return request; + } + + protected Request getDocumentsRequest(final Collection keys, final DocumentReadOptions options) { + final DocumentReadOptions params = (options != null ? options : new DocumentReadOptions()); + final Request request = request(db.name(), RequestType.PUT, PATH_API_DOCUMENT, name) + .putQueryParam("onlyget", true) + .putHeaderParam(ArangoRequestParam.IF_NONE_MATCH, params.getIfNoneMatch()) + .putHeaderParam(ArangoRequestParam.IF_MATCH, params.getIfMatch()).setBody(util().serialize(keys)) + .putHeaderParam(TRANSACTION_ID, params.getStreamTransactionId()); + if (params.getAllowDirtyRead() == Boolean.TRUE) { + RequestUtils.allowDirtyRead(request); + } + return request; + } + + protected ResponseDeserializer> getDocumentsResponseDeserializer( + final Class type, final DocumentReadOptions options) { return response -> { final MultiDocumentEntity multiDocument = new MultiDocumentEntity<>(); final Collection docs = new ArrayList<>(); @@ -241,26 +241,26 @@ protected ResponseDeserializer> getDocumentsResponseD multiDocument.setDocumentsAndErrors(documentsAndErrors); return multiDocument; }; - } - - protected Request replaceDocumentRequest( - final String key, final T value, final DocumentReplaceOptions options) { - final Request request = request(db.name(), RequestType.PUT, PATH_API_DOCUMENT, - DocumentUtil.createDocumentHandle(name, key)); - final DocumentReplaceOptions params = (options != null ? options : new DocumentReplaceOptions()); - request.putHeaderParam(ArangoRequestParam.IF_MATCH, params.getIfMatch()); - request.putHeaderParam(TRANSACTION_ID, params.getStreamTransactionId()); - request.putQueryParam(ArangoRequestParam.WAIT_FOR_SYNC, params.getWaitForSync()); - request.putQueryParam(IGNORE_REVS, params.getIgnoreRevs()); - request.putQueryParam(RETURN_NEW, params.getReturnNew()); - request.putQueryParam(RETURN_OLD, params.getReturnOld()); - request.putQueryParam(SILENT, params.getSilent()); - request.setBody(util(Serializer.CUSTOM).serialize(value)); - return request; - } - - protected ResponseDeserializer> replaceDocumentResponseDeserializer( - final T value, final DocumentReplaceOptions options) { + } + + protected Request replaceDocumentRequest( + final String key, final T value, final DocumentReplaceOptions options) { + final Request request = request(db.name(), RequestType.PUT, PATH_API_DOCUMENT, + DocumentUtil.createDocumentHandle(name, key)); + final DocumentReplaceOptions params = (options != null ? options : new DocumentReplaceOptions()); + request.putHeaderParam(ArangoRequestParam.IF_MATCH, params.getIfMatch()); + request.putHeaderParam(TRANSACTION_ID, params.getStreamTransactionId()); + request.putQueryParam(ArangoRequestParam.WAIT_FOR_SYNC, params.getWaitForSync()); + request.putQueryParam(IGNORE_REVS, params.getIgnoreRevs()); + request.putQueryParam(RETURN_NEW, params.getReturnNew()); + request.putQueryParam(RETURN_OLD, params.getReturnOld()); + request.putQueryParam(SILENT, params.getSilent()); + request.setBody(util(Serializer.CUSTOM).serialize(value)); + return request; + } + + protected ResponseDeserializer> replaceDocumentResponseDeserializer( + final T value, final DocumentReplaceOptions options) { return response -> { final VPackSlice body = response.getBody(); final DocumentUpdateEntity doc = util().deserialize(body, DocumentUpdateEntity.class); @@ -279,25 +279,25 @@ protected ResponseDeserializer> replaceDocumentRespo } return doc; }; - } - - protected Request replaceDocumentsRequest(final Collection values, final DocumentReplaceOptions params) { - final Request request = request(db.name(), RequestType.PUT, PATH_API_DOCUMENT, name); - request.putHeaderParam(ArangoRequestParam.IF_MATCH, params.getIfMatch()); - request.putHeaderParam(TRANSACTION_ID, params.getStreamTransactionId()); - request.putQueryParam(ArangoRequestParam.WAIT_FOR_SYNC, params.getWaitForSync()); - request.putQueryParam(IGNORE_REVS, params.getIgnoreRevs()); - request.putQueryParam(RETURN_NEW, params.getReturnNew()); - request.putQueryParam(RETURN_OLD, params.getReturnOld()); - request.putQueryParam(SILENT, params.getSilent()); - request.setBody(util(Serializer.CUSTOM) - .serialize(values, new ArangoSerializer.Options().serializeNullValues(false).stringAsJson(true))); - return request; - } - - @SuppressWarnings("unchecked") - protected ResponseDeserializer>> replaceDocumentsResponseDeserializer( - final Collection values, final DocumentReplaceOptions params) { + } + + protected Request replaceDocumentsRequest(final Collection values, final DocumentReplaceOptions params) { + final Request request = request(db.name(), RequestType.PUT, PATH_API_DOCUMENT, name); + request.putHeaderParam(ArangoRequestParam.IF_MATCH, params.getIfMatch()); + request.putHeaderParam(TRANSACTION_ID, params.getStreamTransactionId()); + request.putQueryParam(ArangoRequestParam.WAIT_FOR_SYNC, params.getWaitForSync()); + request.putQueryParam(IGNORE_REVS, params.getIgnoreRevs()); + request.putQueryParam(RETURN_NEW, params.getReturnNew()); + request.putQueryParam(RETURN_OLD, params.getReturnOld()); + request.putQueryParam(SILENT, params.getSilent()); + request.setBody(util(Serializer.CUSTOM) + .serialize(values, new ArangoSerializer.Options().serializeNullValues(false).stringAsJson(true))); + return request; + } + + @SuppressWarnings("unchecked") + protected ResponseDeserializer>> replaceDocumentsResponseDeserializer( + final Collection values, final DocumentReplaceOptions params) { return response -> { Class type = null; if (Boolean.TRUE == params.getReturnNew() || Boolean.TRUE == params.getReturnOld()) { @@ -337,28 +337,28 @@ protected ResponseDeserializer>> multiDocument.setDocumentsAndErrors(documentsAndErrors); return multiDocument; }; - } - - protected Request updateDocumentRequest(final String key, final T value, final DocumentUpdateOptions options) { - final Request request = request(db.name(), RequestType.PATCH, PATH_API_DOCUMENT, - DocumentUtil.createDocumentHandle(name, key)); - final DocumentUpdateOptions params = (options != null ? options : new DocumentUpdateOptions()); - request.putHeaderParam(ArangoRequestParam.IF_MATCH, params.getIfMatch()); - request.putHeaderParam(TRANSACTION_ID, params.getStreamTransactionId()); - request.putQueryParam(ArangoRequestParam.KEEP_NULL, params.getKeepNull()); - request.putQueryParam(ArangoRequestParam.WAIT_FOR_SYNC, params.getWaitForSync()); - request.putQueryParam(MERGE_OBJECTS, params.getMergeObjects()); - request.putQueryParam(IGNORE_REVS, params.getIgnoreRevs()); - request.putQueryParam(RETURN_NEW, params.getReturnNew()); - request.putQueryParam(RETURN_OLD, params.getReturnOld()); - request.putQueryParam(SILENT, params.getSilent()); - request.setBody(util(Serializer.CUSTOM).serialize(value, new ArangoSerializer.Options() - .serializeNullValues(params.getSerializeNull() == null || params.getSerializeNull()))); - return request; - } - - protected ResponseDeserializer> updateDocumentResponseDeserializer( - final T value, final DocumentUpdateOptions options) { + } + + protected Request updateDocumentRequest(final String key, final T value, final DocumentUpdateOptions options) { + final Request request = request(db.name(), RequestType.PATCH, PATH_API_DOCUMENT, + DocumentUtil.createDocumentHandle(name, key)); + final DocumentUpdateOptions params = (options != null ? options : new DocumentUpdateOptions()); + request.putHeaderParam(ArangoRequestParam.IF_MATCH, params.getIfMatch()); + request.putHeaderParam(TRANSACTION_ID, params.getStreamTransactionId()); + request.putQueryParam(ArangoRequestParam.KEEP_NULL, params.getKeepNull()); + request.putQueryParam(ArangoRequestParam.WAIT_FOR_SYNC, params.getWaitForSync()); + request.putQueryParam(MERGE_OBJECTS, params.getMergeObjects()); + request.putQueryParam(IGNORE_REVS, params.getIgnoreRevs()); + request.putQueryParam(RETURN_NEW, params.getReturnNew()); + request.putQueryParam(RETURN_OLD, params.getReturnOld()); + request.putQueryParam(SILENT, params.getSilent()); + request.setBody(util(Serializer.CUSTOM).serialize(value, new ArangoSerializer.Options() + .serializeNullValues(params.getSerializeNull() == null || params.getSerializeNull()))); + return request; + } + + protected ResponseDeserializer> updateDocumentResponseDeserializer( + final T value, final DocumentUpdateOptions options) { return response -> { final VPackSlice body = response.getBody(); final DocumentUpdateEntity doc = util().deserialize(body, DocumentUpdateEntity.class); @@ -377,29 +377,29 @@ protected ResponseDeserializer> updateDocumentRespon } return doc; }; - } - - protected Request updateDocumentsRequest(final Collection values, final DocumentUpdateOptions params) { - final Request request = request(db.name(), RequestType.PATCH, PATH_API_DOCUMENT, name); - final Boolean keepNull = params.getKeepNull(); - request.putHeaderParam(ArangoRequestParam.IF_MATCH, params.getIfMatch()); - request.putHeaderParam(TRANSACTION_ID, params.getStreamTransactionId()); - request.putQueryParam(ArangoRequestParam.KEEP_NULL, keepNull); - request.putQueryParam(ArangoRequestParam.WAIT_FOR_SYNC, params.getWaitForSync()); - request.putQueryParam(MERGE_OBJECTS, params.getMergeObjects()); - request.putQueryParam(IGNORE_REVS, params.getIgnoreRevs()); - request.putQueryParam(RETURN_NEW, params.getReturnNew()); - request.putQueryParam(RETURN_OLD, params.getReturnOld()); - request.putQueryParam(SILENT, params.getSilent()); - request.setBody(util(Serializer.CUSTOM).serialize(values, new ArangoSerializer.Options() - .serializeNullValues(params.getSerializeNull() == null || params.getSerializeNull()) - .stringAsJson(true))); - return request; - } - - @SuppressWarnings("unchecked") - protected ResponseDeserializer>> updateDocumentsResponseDeserializer( - final Collection values, final DocumentUpdateOptions params) { + } + + protected Request updateDocumentsRequest(final Collection values, final DocumentUpdateOptions params) { + final Request request = request(db.name(), RequestType.PATCH, PATH_API_DOCUMENT, name); + final Boolean keepNull = params.getKeepNull(); + request.putHeaderParam(ArangoRequestParam.IF_MATCH, params.getIfMatch()); + request.putHeaderParam(TRANSACTION_ID, params.getStreamTransactionId()); + request.putQueryParam(ArangoRequestParam.KEEP_NULL, keepNull); + request.putQueryParam(ArangoRequestParam.WAIT_FOR_SYNC, params.getWaitForSync()); + request.putQueryParam(MERGE_OBJECTS, params.getMergeObjects()); + request.putQueryParam(IGNORE_REVS, params.getIgnoreRevs()); + request.putQueryParam(RETURN_NEW, params.getReturnNew()); + request.putQueryParam(RETURN_OLD, params.getReturnOld()); + request.putQueryParam(SILENT, params.getSilent()); + request.setBody(util(Serializer.CUSTOM).serialize(values, new ArangoSerializer.Options() + .serializeNullValues(params.getSerializeNull() == null || params.getSerializeNull()) + .stringAsJson(true))); + return request; + } + + @SuppressWarnings("unchecked") + protected ResponseDeserializer>> updateDocumentsResponseDeserializer( + final Collection values, final DocumentUpdateOptions params) { return response -> { Class type = null; if (Boolean.TRUE == params.getReturnNew() || Boolean.TRUE == params.getReturnOld()) { @@ -439,22 +439,22 @@ protected ResponseDeserializer>> multiDocument.setDocumentsAndErrors(documentsAndErrors); return multiDocument; }; - } - - protected Request deleteDocumentRequest(final String key, final DocumentDeleteOptions options) { - final Request request = request(db.name(), RequestType.DELETE, PATH_API_DOCUMENT, - DocumentUtil.createDocumentHandle(name, key)); - final DocumentDeleteOptions params = (options != null ? options : new DocumentDeleteOptions()); - request.putHeaderParam(ArangoRequestParam.IF_MATCH, params.getIfMatch()); - request.putHeaderParam(TRANSACTION_ID, params.getStreamTransactionId()); - request.putQueryParam(ArangoRequestParam.WAIT_FOR_SYNC, params.getWaitForSync()); - request.putQueryParam(RETURN_OLD, params.getReturnOld()); - request.putQueryParam(SILENT, params.getSilent()); - return request; - } - - protected ResponseDeserializer> deleteDocumentResponseDeserializer( - final Class type) { + } + + protected Request deleteDocumentRequest(final String key, final DocumentDeleteOptions options) { + final Request request = request(db.name(), RequestType.DELETE, PATH_API_DOCUMENT, + DocumentUtil.createDocumentHandle(name, key)); + final DocumentDeleteOptions params = (options != null ? options : new DocumentDeleteOptions()); + request.putHeaderParam(ArangoRequestParam.IF_MATCH, params.getIfMatch()); + request.putHeaderParam(TRANSACTION_ID, params.getStreamTransactionId()); + request.putQueryParam(ArangoRequestParam.WAIT_FOR_SYNC, params.getWaitForSync()); + request.putQueryParam(RETURN_OLD, params.getReturnOld()); + request.putQueryParam(SILENT, params.getSilent()); + return request; + } + + protected ResponseDeserializer> deleteDocumentResponseDeserializer( + final Class type) { return response -> { final VPackSlice body = response.getBody(); final DocumentDeleteEntity doc = util().deserialize(body, DocumentDeleteEntity.class); @@ -464,21 +464,21 @@ protected ResponseDeserializer> deleteDocumentRespon } return doc; }; - } - - protected Request deleteDocumentsRequest(final Collection keys, final DocumentDeleteOptions options) { - final Request request = request(db.name(), RequestType.DELETE, PATH_API_DOCUMENT, name); - final DocumentDeleteOptions params = (options != null ? options : new DocumentDeleteOptions()); - request.putHeaderParam(TRANSACTION_ID, params.getStreamTransactionId()); - request.putQueryParam(ArangoRequestParam.WAIT_FOR_SYNC, params.getWaitForSync()); - request.putQueryParam(RETURN_OLD, params.getReturnOld()); - request.putQueryParam(SILENT, params.getSilent()); - request.setBody(util().serialize(keys)); - return request; - } - - protected ResponseDeserializer>> deleteDocumentsResponseDeserializer( - final Class type) { + } + + protected Request deleteDocumentsRequest(final Collection keys, final DocumentDeleteOptions options) { + final Request request = request(db.name(), RequestType.DELETE, PATH_API_DOCUMENT, name); + final DocumentDeleteOptions params = (options != null ? options : new DocumentDeleteOptions()); + request.putHeaderParam(TRANSACTION_ID, params.getStreamTransactionId()); + request.putQueryParam(ArangoRequestParam.WAIT_FOR_SYNC, params.getWaitForSync()); + request.putQueryParam(RETURN_OLD, params.getReturnOld()); + request.putQueryParam(SILENT, params.getSilent()); + request.setBody(util().serialize(keys)); + return request; + } + + protected ResponseDeserializer>> deleteDocumentsResponseDeserializer( + final Class type) { return response -> { final MultiDocumentEntity> multiDocument = new MultiDocumentEntity<>(); final Collection> docs = new ArrayList<>(); @@ -508,174 +508,174 @@ protected ResponseDeserializer>> multiDocument.setDocumentsAndErrors(documentsAndErrors); return multiDocument; }; - } - - protected Request documentExistsRequest(final String key, final DocumentExistsOptions options) { - final Request request = request(db.name(), RequestType.HEAD, PATH_API_DOCUMENT, - DocumentUtil.createDocumentHandle(name, key)); - final DocumentExistsOptions params = (options != null ? options : new DocumentExistsOptions()); - request.putHeaderParam(TRANSACTION_ID, params.getStreamTransactionId()); - request.putHeaderParam(ArangoRequestParam.IF_MATCH, params.getIfMatch()); - request.putHeaderParam(ArangoRequestParam.IF_NONE_MATCH, params.getIfNoneMatch()); - return request; - } - - protected Request getIndexRequest(final String id) { - return request(db.name(), RequestType.GET, PATH_API_INDEX, createIndexId(id)); - } - - protected Request deleteIndexRequest(final String id) { - return request(db.name(), RequestType.DELETE, PATH_API_INDEX, createIndexId(id)); - } - - protected ResponseDeserializer deleteIndexResponseDeserializer() { + } + + protected Request documentExistsRequest(final String key, final DocumentExistsOptions options) { + final Request request = request(db.name(), RequestType.HEAD, PATH_API_DOCUMENT, + DocumentUtil.createDocumentHandle(name, key)); + final DocumentExistsOptions params = (options != null ? options : new DocumentExistsOptions()); + request.putHeaderParam(TRANSACTION_ID, params.getStreamTransactionId()); + request.putHeaderParam(ArangoRequestParam.IF_MATCH, params.getIfMatch()); + request.putHeaderParam(ArangoRequestParam.IF_NONE_MATCH, params.getIfNoneMatch()); + return request; + } + + protected Request getIndexRequest(final String id) { + return request(db.name(), RequestType.GET, PATH_API_INDEX, createIndexId(id)); + } + + protected Request deleteIndexRequest(final String id) { + return request(db.name(), RequestType.DELETE, PATH_API_INDEX, createIndexId(id)); + } + + protected ResponseDeserializer deleteIndexResponseDeserializer() { return response -> response.getBody().get("id").getAsString(); - } - - private String createIndexId(final String id) { - final String index; - if (id.matches(DocumentUtil.REGEX_ID)) { - index = id; - } else if (id.matches(DocumentUtil.REGEX_KEY)) { - index = name + "/" + id; - } else { - throw new ArangoDBException(String.format("index id %s is not valid.", id)); - } - return index; - } - - protected Request createHashIndexRequest(final Iterable fields, final HashIndexOptions options) { - final Request request = request(db.name(), RequestType.POST, PATH_API_INDEX); - request.putQueryParam(COLLECTION, name); - request.setBody( - util().serialize(OptionsBuilder.build(options != null ? options : new HashIndexOptions(), fields))); - return request; - } - - protected Request createSkiplistIndexRequest(final Iterable fields, final SkiplistIndexOptions options) { - final Request request = request(db.name(), RequestType.POST, PATH_API_INDEX); - request.putQueryParam(COLLECTION, name); - request.setBody( - util().serialize(OptionsBuilder.build(options != null ? options : new SkiplistIndexOptions(), fields))); - return request; - } - - protected Request createPersistentIndexRequest( - final Iterable fields, final PersistentIndexOptions options) { - final Request request = request(db.name(), RequestType.POST, PATH_API_INDEX); - request.putQueryParam(COLLECTION, name); - request.setBody(util().serialize( - OptionsBuilder.build(options != null ? options : new PersistentIndexOptions(), fields))); - return request; - } - - protected Request createGeoIndexRequest(final Iterable fields, final GeoIndexOptions options) { - final Request request = request(db.name(), RequestType.POST, PATH_API_INDEX); - request.putQueryParam(COLLECTION, name); - request.setBody( - util().serialize(OptionsBuilder.build(options != null ? options : new GeoIndexOptions(), fields))); - return request; - } - - protected Request createFulltextIndexRequest(final Iterable fields, final FulltextIndexOptions options) { - final Request request = request(db.name(), RequestType.POST, PATH_API_INDEX); - request.putQueryParam(COLLECTION, name); - request.setBody( - util().serialize(OptionsBuilder.build(options != null ? options : new FulltextIndexOptions(), fields))); - return request; - } - - protected Request createTtlIndexRequest(final Iterable fields, final TtlIndexOptions options) { - final Request request = request(db.name(), RequestType.POST, PATH_API_INDEX); - request.putQueryParam(COLLECTION, name); - request.setBody( - util().serialize(OptionsBuilder.build(options != null ? options : new TtlIndexOptions(), fields))); - return request; - } - - protected Request getIndexesRequest() { - final Request request = request(db.name(), RequestType.GET, PATH_API_INDEX); - request.putQueryParam(COLLECTION, name); - return request; - } - - protected ResponseDeserializer> getIndexesResponseDeserializer() { + } + + private String createIndexId(final String id) { + final String index; + if (id.matches(DocumentUtil.REGEX_ID)) { + index = id; + } else if (id.matches(DocumentUtil.REGEX_KEY)) { + index = name + "/" + id; + } else { + throw new ArangoDBException(String.format("index id %s is not valid.", id)); + } + return index; + } + + protected Request createHashIndexRequest(final Iterable fields, final HashIndexOptions options) { + final Request request = request(db.name(), RequestType.POST, PATH_API_INDEX); + request.putQueryParam(COLLECTION, name); + request.setBody( + util().serialize(OptionsBuilder.build(options != null ? options : new HashIndexOptions(), fields))); + return request; + } + + protected Request createSkiplistIndexRequest(final Iterable fields, final SkiplistIndexOptions options) { + final Request request = request(db.name(), RequestType.POST, PATH_API_INDEX); + request.putQueryParam(COLLECTION, name); + request.setBody( + util().serialize(OptionsBuilder.build(options != null ? options : new SkiplistIndexOptions(), fields))); + return request; + } + + protected Request createPersistentIndexRequest( + final Iterable fields, final PersistentIndexOptions options) { + final Request request = request(db.name(), RequestType.POST, PATH_API_INDEX); + request.putQueryParam(COLLECTION, name); + request.setBody(util().serialize( + OptionsBuilder.build(options != null ? options : new PersistentIndexOptions(), fields))); + return request; + } + + protected Request createGeoIndexRequest(final Iterable fields, final GeoIndexOptions options) { + final Request request = request(db.name(), RequestType.POST, PATH_API_INDEX); + request.putQueryParam(COLLECTION, name); + request.setBody( + util().serialize(OptionsBuilder.build(options != null ? options : new GeoIndexOptions(), fields))); + return request; + } + + protected Request createFulltextIndexRequest(final Iterable fields, final FulltextIndexOptions options) { + final Request request = request(db.name(), RequestType.POST, PATH_API_INDEX); + request.putQueryParam(COLLECTION, name); + request.setBody( + util().serialize(OptionsBuilder.build(options != null ? options : new FulltextIndexOptions(), fields))); + return request; + } + + protected Request createTtlIndexRequest(final Iterable fields, final TtlIndexOptions options) { + final Request request = request(db.name(), RequestType.POST, PATH_API_INDEX); + request.putQueryParam(COLLECTION, name); + request.setBody( + util().serialize(OptionsBuilder.build(options != null ? options : new TtlIndexOptions(), fields))); + return request; + } + + protected Request getIndexesRequest() { + final Request request = request(db.name(), RequestType.GET, PATH_API_INDEX); + request.putQueryParam(COLLECTION, name); + return request; + } + + protected ResponseDeserializer> getIndexesResponseDeserializer() { return response -> util().deserialize(response.getBody().get("indexes"), new Type>() { }.getType()); - } - - protected Request truncateRequest(final CollectionTruncateOptions options) { - final Request request = request(db.name(), RequestType.PUT, PATH_API_COLLECTION, name, "truncate"); - final CollectionTruncateOptions params = (options != null ? options : new CollectionTruncateOptions()); - request.putHeaderParam(TRANSACTION_ID, params.getStreamTransactionId()); - return request; - } - - protected Request countRequest(final CollectionCountOptions options) { - final Request request = request(db.name(), RequestType.GET, PATH_API_COLLECTION, name, "count"); - final CollectionCountOptions params = (options != null ? options : new CollectionCountOptions()); - request.putHeaderParam(TRANSACTION_ID, params.getStreamTransactionId()); - return request; - } - - protected Request dropRequest(final Boolean isSystem) { - return request(db.name(), RequestType.DELETE, PATH_API_COLLECTION, name).putQueryParam("isSystem", isSystem); - } - - protected Request loadRequest() { - return request(db.name(), RequestType.PUT, PATH_API_COLLECTION, name, "load"); - } - - protected Request unloadRequest() { - return request(db.name(), RequestType.PUT, PATH_API_COLLECTION, name, "unload"); - } - - protected Request getInfoRequest() { - return request(db.name(), RequestType.GET, PATH_API_COLLECTION, name); - } - - protected Request getPropertiesRequest() { - return request(db.name(), RequestType.GET, PATH_API_COLLECTION, name, "properties"); - } - - protected Request changePropertiesRequest(final CollectionPropertiesOptions options) { - final Request request = request(db.name(), RequestType.PUT, PATH_API_COLLECTION, name, "properties"); - request.setBody(util().serialize(options != null ? options : new CollectionPropertiesOptions())); - return request; - } - - protected Request renameRequest(final String newName) { - final Request request = request(db.name(), RequestType.PUT, PATH_API_COLLECTION, name, "rename"); - request.setBody(util().serialize(OptionsBuilder.build(new CollectionRenameOptions(), newName))); - return request; - } - - protected Request responsibleShardRequest(final T value) { - final Request request = request(db.name(), RequestType.PUT, PATH_API_COLLECTION, name, "responsibleShard"); - request.setBody(util(Serializer.CUSTOM).serialize(value)); - return request; - } - - protected Request getRevisionRequest() { - return request(db.name(), RequestType.GET, PATH_API_COLLECTION, name, "revision"); - } - - protected Request grantAccessRequest(final String user, final Permissions permissions) { - return request(ArangoRequestParam.SYSTEM, RequestType.PUT, PATH_API_USER, user, ArangoRequestParam.DATABASE, - db.name(), name).setBody(util().serialize(OptionsBuilder.build(new UserAccessOptions(), permissions))); - } - - protected Request resetAccessRequest(final String user) { - return request(ArangoRequestParam.SYSTEM, RequestType.DELETE, PATH_API_USER, user, ArangoRequestParam.DATABASE, - db.name(), name); - } - - protected Request getPermissionsRequest(final String user) { - return request(ArangoRequestParam.SYSTEM, RequestType.GET, PATH_API_USER, user, ArangoRequestParam.DATABASE, - db.name(), name); - } - - protected ResponseDeserializer getPermissionsResponseDeserialzer() { + } + + protected Request truncateRequest(final CollectionTruncateOptions options) { + final Request request = request(db.name(), RequestType.PUT, PATH_API_COLLECTION, name, "truncate"); + final CollectionTruncateOptions params = (options != null ? options : new CollectionTruncateOptions()); + request.putHeaderParam(TRANSACTION_ID, params.getStreamTransactionId()); + return request; + } + + protected Request countRequest(final CollectionCountOptions options) { + final Request request = request(db.name(), RequestType.GET, PATH_API_COLLECTION, name, "count"); + final CollectionCountOptions params = (options != null ? options : new CollectionCountOptions()); + request.putHeaderParam(TRANSACTION_ID, params.getStreamTransactionId()); + return request; + } + + protected Request dropRequest(final Boolean isSystem) { + return request(db.name(), RequestType.DELETE, PATH_API_COLLECTION, name).putQueryParam("isSystem", isSystem); + } + + protected Request loadRequest() { + return request(db.name(), RequestType.PUT, PATH_API_COLLECTION, name, "load"); + } + + protected Request unloadRequest() { + return request(db.name(), RequestType.PUT, PATH_API_COLLECTION, name, "unload"); + } + + protected Request getInfoRequest() { + return request(db.name(), RequestType.GET, PATH_API_COLLECTION, name); + } + + protected Request getPropertiesRequest() { + return request(db.name(), RequestType.GET, PATH_API_COLLECTION, name, "properties"); + } + + protected Request changePropertiesRequest(final CollectionPropertiesOptions options) { + final Request request = request(db.name(), RequestType.PUT, PATH_API_COLLECTION, name, "properties"); + request.setBody(util().serialize(options != null ? options : new CollectionPropertiesOptions())); + return request; + } + + protected Request renameRequest(final String newName) { + final Request request = request(db.name(), RequestType.PUT, PATH_API_COLLECTION, name, "rename"); + request.setBody(util().serialize(OptionsBuilder.build(new CollectionRenameOptions(), newName))); + return request; + } + + protected Request responsibleShardRequest(final T value) { + final Request request = request(db.name(), RequestType.PUT, PATH_API_COLLECTION, name, "responsibleShard"); + request.setBody(util(Serializer.CUSTOM).serialize(value)); + return request; + } + + protected Request getRevisionRequest() { + return request(db.name(), RequestType.GET, PATH_API_COLLECTION, name, "revision"); + } + + protected Request grantAccessRequest(final String user, final Permissions permissions) { + return request(ArangoRequestParam.SYSTEM, RequestType.PUT, PATH_API_USER, user, ArangoRequestParam.DATABASE, + db.name(), name).setBody(util().serialize(OptionsBuilder.build(new UserAccessOptions(), permissions))); + } + + protected Request resetAccessRequest(final String user) { + return request(ArangoRequestParam.SYSTEM, RequestType.DELETE, PATH_API_USER, user, ArangoRequestParam.DATABASE, + db.name(), name); + } + + protected Request getPermissionsRequest(final String user) { + return request(ArangoRequestParam.SYSTEM, RequestType.GET, PATH_API_USER, user, ArangoRequestParam.DATABASE, + db.name(), name); + } + + protected ResponseDeserializer getPermissionsResponseDeserialzer() { return response -> { final VPackSlice body = response.getBody(); if (body != null) { @@ -686,6 +686,6 @@ protected ResponseDeserializer getPermissionsResponseDeserialzer() } return null; }; - } + } } diff --git a/src/main/java/com/arangodb/internal/InternalArangoDB.java b/src/main/java/com/arangodb/internal/InternalArangoDB.java index 44014703d..905eccda7 100644 --- a/src/main/java/com/arangodb/internal/InternalArangoDB.java +++ b/src/main/java/com/arangodb/internal/InternalArangoDB.java @@ -40,142 +40,141 @@ /** * @author Mark Vollmary * @author Heiko Kernbach - * */ public abstract class InternalArangoDB extends ArangoExecuteable { - private static final String PATH_API_ADMIN_LOG = "/_admin/log"; - private static final String PATH_API_ADMIN_LOG_LEVEL = "/_admin/log/level"; - private static final String PATH_API_ROLE = "/_admin/server/role"; - private static final String PATH_ENDPOINTS = "/_api/cluster/endpoints"; - private static final String PATH_API_USER = "/_api/user"; - - protected InternalArangoDB(final E executor, final ArangoSerializationFactory util, final ArangoContext context) { - super(executor, util, context); - } - - protected Request getRoleRequest() { - return request(ArangoRequestParam.SYSTEM, RequestType.GET, PATH_API_ROLE); - } - - protected ResponseDeserializer getRoleResponseDeserializer() { - return response -> util().deserialize(response.getBody().get("role"), ServerRole.class); - } - - protected Request createDatabaseRequest(final DBCreateOptions options) { - final Request request = request(ArangoRequestParam.SYSTEM, RequestType.POST, - InternalArangoDatabase.PATH_API_DATABASE); - request.setBody(util().serialize(options)); - return request; - } - - protected ResponseDeserializer createDatabaseResponseDeserializer() { - return response -> response.getBody().get(ArangoResponseField.RESULT).getAsBoolean(); - } - - protected Request getDatabasesRequest(final String database) { - return request(database, RequestType.GET, InternalArangoDatabase.PATH_API_DATABASE); - } - - protected ResponseDeserializer> getDatabaseResponseDeserializer() { - return response -> { - final VPackSlice result = response.getBody().get(ArangoResponseField.RESULT); - return util().deserialize(result, new Type>() { - }.getType()); - }; - } - - protected Request getAccessibleDatabasesForRequest(final String database, final String user) { - return request(database, RequestType.GET, PATH_API_USER, user, ArangoRequestParam.DATABASE); - } - - protected ResponseDeserializer> getAccessibleDatabasesForResponseDeserializer() { - return response -> { - final VPackSlice result = response.getBody().get(ArangoResponseField.RESULT); - final Collection dbs = new ArrayList<>(); - for (final Iterator> iterator = result.objectIterator(); iterator - .hasNext(); ) { - dbs.add(iterator.next().getKey()); - } - return dbs; - }; - } - - protected Request createUserRequest( - final String database, - final String user, - final String passwd, - final UserCreateOptions options) { - final Request request; - request = request(database, RequestType.POST, PATH_API_USER); - request.setBody( - util().serialize(OptionsBuilder.build(options != null ? options : new UserCreateOptions(), user, passwd))); - return request; - } - - protected Request deleteUserRequest(final String database, final String user) { - return request(database, RequestType.DELETE, PATH_API_USER, user); - } - - protected Request getUsersRequest(final String database) { - return request(database, RequestType.GET, PATH_API_USER); - } - - protected Request getUserRequest(final String database, final String user) { - return request(database, RequestType.GET, PATH_API_USER, user); - } - - protected ResponseDeserializer> getUsersResponseDeserializer() { - return response -> { - final VPackSlice result = response.getBody().get(ArangoResponseField.RESULT); - return util().deserialize(result, new Type>() { - }.getType()); - }; - } - - protected Request updateUserRequest(final String database, final String user, final UserUpdateOptions options) { - final Request request; - request = request(database, RequestType.PATCH, PATH_API_USER, user); - request.setBody(util().serialize(options != null ? options : new UserUpdateOptions())); - return request; - } - - protected Request replaceUserRequest(final String database, final String user, final UserUpdateOptions options) { - final Request request; - request = request(database, RequestType.PUT, PATH_API_USER, user); - request.setBody(util().serialize(options != null ? options : new UserUpdateOptions())); - return request; - } - - protected Request updateUserDefaultDatabaseAccessRequest(final String user, final Permissions permissions) { - return request(ArangoRequestParam.SYSTEM, RequestType.PUT, PATH_API_USER, user, ArangoRequestParam.DATABASE, - "*").setBody(util().serialize(OptionsBuilder.build(new UserAccessOptions(), permissions))); - } - - protected Request updateUserDefaultCollectionAccessRequest(final String user, final Permissions permissions) { - return request(ArangoRequestParam.SYSTEM, RequestType.PUT, PATH_API_USER, user, ArangoRequestParam.DATABASE, - "*", "*").setBody(util().serialize(OptionsBuilder.build(new UserAccessOptions(), permissions))); - } - - protected Request getLogsRequest(final LogOptions options) { - final LogOptions params = options != null ? options : new LogOptions(); - return request(ArangoRequestParam.SYSTEM, RequestType.GET, PATH_API_ADMIN_LOG) - .putQueryParam(LogOptions.PROPERTY_UPTO, params.getUpto()) - .putQueryParam(LogOptions.PROPERTY_LEVEL, params.getLevel()) - .putQueryParam(LogOptions.PROPERTY_START, params.getStart()) - .putQueryParam(LogOptions.PROPERTY_SIZE, params.getSize()) - .putQueryParam(LogOptions.PROPERTY_OFFSET, params.getOffset()) - .putQueryParam(LogOptions.PROPERTY_SEARCH, params.getSearch()) - .putQueryParam(LogOptions.PROPERTY_SORT, params.getSort()); - } - - protected Request getLogLevelRequest() { - return request(ArangoRequestParam.SYSTEM, RequestType.GET, PATH_API_ADMIN_LOG_LEVEL); - } - - protected Request setLogLevelRequest(final LogLevelEntity entity) { - return request(ArangoRequestParam.SYSTEM, RequestType.PUT, PATH_API_ADMIN_LOG_LEVEL) - .setBody(util().serialize(entity)); - } + private static final String PATH_API_ADMIN_LOG = "/_admin/log"; + private static final String PATH_API_ADMIN_LOG_LEVEL = "/_admin/log/level"; + private static final String PATH_API_ROLE = "/_admin/server/role"; + private static final String PATH_ENDPOINTS = "/_api/cluster/endpoints"; + private static final String PATH_API_USER = "/_api/user"; + + protected InternalArangoDB(final E executor, final ArangoSerializationFactory util, final ArangoContext context) { + super(executor, util, context); + } + + protected Request getRoleRequest() { + return request(ArangoRequestParam.SYSTEM, RequestType.GET, PATH_API_ROLE); + } + + protected ResponseDeserializer getRoleResponseDeserializer() { + return response -> util().deserialize(response.getBody().get("role"), ServerRole.class); + } + + protected Request createDatabaseRequest(final DBCreateOptions options) { + final Request request = request(ArangoRequestParam.SYSTEM, RequestType.POST, + InternalArangoDatabase.PATH_API_DATABASE); + request.setBody(util().serialize(options)); + return request; + } + + protected ResponseDeserializer createDatabaseResponseDeserializer() { + return response -> response.getBody().get(ArangoResponseField.RESULT).getAsBoolean(); + } + + protected Request getDatabasesRequest(final String database) { + return request(database, RequestType.GET, InternalArangoDatabase.PATH_API_DATABASE); + } + + protected ResponseDeserializer> getDatabaseResponseDeserializer() { + return response -> { + final VPackSlice result = response.getBody().get(ArangoResponseField.RESULT); + return util().deserialize(result, new Type>() { + }.getType()); + }; + } + + protected Request getAccessibleDatabasesForRequest(final String database, final String user) { + return request(database, RequestType.GET, PATH_API_USER, user, ArangoRequestParam.DATABASE); + } + + protected ResponseDeserializer> getAccessibleDatabasesForResponseDeserializer() { + return response -> { + final VPackSlice result = response.getBody().get(ArangoResponseField.RESULT); + final Collection dbs = new ArrayList<>(); + for (final Iterator> iterator = result.objectIterator(); iterator + .hasNext(); ) { + dbs.add(iterator.next().getKey()); + } + return dbs; + }; + } + + protected Request createUserRequest( + final String database, + final String user, + final String passwd, + final UserCreateOptions options) { + final Request request; + request = request(database, RequestType.POST, PATH_API_USER); + request.setBody( + util().serialize(OptionsBuilder.build(options != null ? options : new UserCreateOptions(), user, passwd))); + return request; + } + + protected Request deleteUserRequest(final String database, final String user) { + return request(database, RequestType.DELETE, PATH_API_USER, user); + } + + protected Request getUsersRequest(final String database) { + return request(database, RequestType.GET, PATH_API_USER); + } + + protected Request getUserRequest(final String database, final String user) { + return request(database, RequestType.GET, PATH_API_USER, user); + } + + protected ResponseDeserializer> getUsersResponseDeserializer() { + return response -> { + final VPackSlice result = response.getBody().get(ArangoResponseField.RESULT); + return util().deserialize(result, new Type>() { + }.getType()); + }; + } + + protected Request updateUserRequest(final String database, final String user, final UserUpdateOptions options) { + final Request request; + request = request(database, RequestType.PATCH, PATH_API_USER, user); + request.setBody(util().serialize(options != null ? options : new UserUpdateOptions())); + return request; + } + + protected Request replaceUserRequest(final String database, final String user, final UserUpdateOptions options) { + final Request request; + request = request(database, RequestType.PUT, PATH_API_USER, user); + request.setBody(util().serialize(options != null ? options : new UserUpdateOptions())); + return request; + } + + protected Request updateUserDefaultDatabaseAccessRequest(final String user, final Permissions permissions) { + return request(ArangoRequestParam.SYSTEM, RequestType.PUT, PATH_API_USER, user, ArangoRequestParam.DATABASE, + "*").setBody(util().serialize(OptionsBuilder.build(new UserAccessOptions(), permissions))); + } + + protected Request updateUserDefaultCollectionAccessRequest(final String user, final Permissions permissions) { + return request(ArangoRequestParam.SYSTEM, RequestType.PUT, PATH_API_USER, user, ArangoRequestParam.DATABASE, + "*", "*").setBody(util().serialize(OptionsBuilder.build(new UserAccessOptions(), permissions))); + } + + protected Request getLogsRequest(final LogOptions options) { + final LogOptions params = options != null ? options : new LogOptions(); + return request(ArangoRequestParam.SYSTEM, RequestType.GET, PATH_API_ADMIN_LOG) + .putQueryParam(LogOptions.PROPERTY_UPTO, params.getUpto()) + .putQueryParam(LogOptions.PROPERTY_LEVEL, params.getLevel()) + .putQueryParam(LogOptions.PROPERTY_START, params.getStart()) + .putQueryParam(LogOptions.PROPERTY_SIZE, params.getSize()) + .putQueryParam(LogOptions.PROPERTY_OFFSET, params.getOffset()) + .putQueryParam(LogOptions.PROPERTY_SEARCH, params.getSearch()) + .putQueryParam(LogOptions.PROPERTY_SORT, params.getSort()); + } + + protected Request getLogLevelRequest() { + return request(ArangoRequestParam.SYSTEM, RequestType.GET, PATH_API_ADMIN_LOG_LEVEL); + } + + protected Request setLogLevelRequest(final LogLevelEntity entity) { + return request(ArangoRequestParam.SYSTEM, RequestType.PUT, PATH_API_ADMIN_LOG_LEVEL) + .setBody(util().serialize(entity)); + } } diff --git a/src/main/java/com/arangodb/internal/InternalArangoDBBuilder.java b/src/main/java/com/arangodb/internal/InternalArangoDBBuilder.java index 6e84e0714..75e3bdfab 100644 --- a/src/main/java/com/arangodb/internal/InternalArangoDBBuilder.java +++ b/src/main/java/com/arangodb/internal/InternalArangoDBBuilder.java @@ -45,307 +45,305 @@ /** * @author Mark Vollmary - * */ public abstract class InternalArangoDBBuilder { - - private static final Logger LOG = LoggerFactory.getLogger(InternalArangoDBBuilder.class); - - private static final String PROPERTY_KEY_HOSTS = "arangodb.hosts"; - private static final String PROPERTY_KEY_HOST = "arangodb.host"; - private static final String PROPERTY_KEY_PORT = "arangodb.port"; - private static final String PROPERTY_KEY_TIMEOUT = "arangodb.timeout"; - private static final String PROPERTY_KEY_USER = "arangodb.user"; - private static final String PROPERTY_KEY_PASSWORD = "arangodb.password"; - private static final String PROPERTY_KEY_USE_SSL = "arangodb.usessl"; - private static final String PROPERTY_KEY_COOKIE_SPEC = "arangodb.httpCookieSpec"; - private static final String PROPERTY_KEY_V_STREAM_CHUNK_CONTENT_SIZE = "arangodb.chunksize"; - private static final String PROPERTY_KEY_MAX_CONNECTIONS = "arangodb.connections.max"; - private static final String PROPERTY_KEY_CONNECTION_TTL = "arangodb.connections.ttl"; - private static final String PROPERTY_KEY_ACQUIRE_HOST_LIST = "arangodb.acquireHostList"; - private static final String PROPERTY_KEY_ACQUIRE_HOST_LIST_INTERVAL = "arangodb.acquireHostList.interval"; - private static final String PROPERTY_KEY_LOAD_BALANCING_STRATEGY = "arangodb.loadBalancingStrategy"; - private static final String DEFAULT_PROPERTY_FILE = "/arangodb.properties"; - - protected final List hosts; - protected HostDescription host; - protected Integer timeout; - protected String user; - protected String password; - protected Boolean useSsl; - protected String httpCookieSpec; - protected SSLContext sslContext; - protected Integer chunksize; - protected Integer maxConnections; - protected Long connectionTtl; - protected final VPack.Builder vpackBuilder; - protected final VPackParser.Builder vpackParserBuilder; - protected ArangoSerializer serializer; - protected ArangoDeserializer deserializer; - protected Boolean acquireHostList; - protected Integer acquireHostListInterval; - protected LoadBalancingStrategy loadBalancingStrategy; - protected ArangoSerialization customSerializer; - - - - public InternalArangoDBBuilder() { - super(); - vpackBuilder = new VPack.Builder(); - vpackParserBuilder = new VPackParser.Builder(); - vpackBuilder.registerModule(new VPackDriverModule()); - vpackParserBuilder.registerModule(new VPackDriverModule()); - host = new HostDescription(ArangoDefaults.DEFAULT_HOST, ArangoDefaults.DEFAULT_PORT); - hosts = new ArrayList<>(); - user = ArangoDefaults.DEFAULT_USER; - loadProperties(ArangoDB.class.getResourceAsStream(DEFAULT_PROPERTY_FILE)); - } - - public InternalArangoDBBuilder loadProperties(final InputStream in) throws ArangoDBException { - - final Properties properties = new Properties(); - - if (in != null) { - - try { - properties.load(in); - } catch (final IOException e) { - throw new ArangoDBException(e); - } - } - - loadProperties(properties); - - return this; - - } - - protected void loadProperties(final Properties properties) { - loadHosts(properties, this.hosts); - final String host = loadHost(properties, this.host.getHost()); - final int port = loadPort(properties, this.host.getPort()); - this.host = new HostDescription(host, port); - timeout = loadTimeout(properties, timeout); - user = loadUser(properties, user); - password = loadPassword(properties, password); - useSsl = loadUseSsl(properties, useSsl); - httpCookieSpec = loadhttpCookieSpec(properties, httpCookieSpec); - chunksize = loadChunkSize(properties, chunksize); - maxConnections = loadMaxConnections(properties, maxConnections); - connectionTtl = loadConnectionTtl(properties, connectionTtl); - acquireHostList = loadAcquireHostList(properties, acquireHostList); - acquireHostListInterval = loadAcquireHostListInterval(properties, acquireHostListInterval); - loadBalancingStrategy = loadLoadBalancingStrategy(properties, loadBalancingStrategy); - } - - protected void setHost(final String host, final int port) { - hosts.add(new HostDescription(host, port)); - } - - protected void setTimeout(final Integer timeout) { - this.timeout = timeout; - } - - protected void setUser(final String user) { - this.user = user; - } - - protected void setPassword(final String password) { - this.password = password; - } - - protected void setUseSsl(final Boolean useSsl) { - this.useSsl = useSsl; - } - - protected void setSslContext(final SSLContext sslContext) { - this.sslContext = sslContext; - } - - protected void setChunksize(final Integer chunksize) { - this.chunksize = chunksize; - } - - protected void setMaxConnections(final Integer maxConnections) { - this.maxConnections = maxConnections; - } - - protected void setConnectionTtl(final Long connectionTtl) { - this.connectionTtl = connectionTtl; - } - - protected void setAcquireHostList(final Boolean acquireHostList) { - this.acquireHostList = acquireHostList; - } - - protected void setAcquireHostListInterval(final Integer acquireHostListInterval) { - this.acquireHostListInterval = acquireHostListInterval; - } - - protected void setLoadBalancingStrategy(final LoadBalancingStrategy loadBalancingStrategy) { - this.loadBalancingStrategy = loadBalancingStrategy; - } - - protected void serializer(final ArangoSerializer serializer) { - this.serializer = serializer; - } - - protected void deserializer(final ArangoDeserializer deserializer) { - this.deserializer = deserializer; - } - - protected void setSerializer(final ArangoSerialization serializer) { - this.customSerializer = serializer; - } - - private static void loadHosts(final Properties properties, final Collection hosts) { - final String hostsProp = properties.getProperty(PROPERTY_KEY_HOSTS); - if (hostsProp != null) { - final String[] hostsSplit = hostsProp.split(","); - for (final String host : hostsSplit) { - final String[] split = host.split(":"); - if (split.length != 2 || !split[1].matches("[0-9]+")) { - throw new ArangoDBException(String.format( - "Could not load property-value arangodb.hosts=%s. Expected format ip:port,ip:port,...", - hostsProp)); - } else { - hosts.add(new HostDescription(split[0], Integer.parseInt(split[1]))); - } - } - } - } - - protected HostHandler createHostHandler(final HostResolver hostResolver) { - - final HostHandler hostHandler; - - if (loadBalancingStrategy != null) { - switch (loadBalancingStrategy) { - case ONE_RANDOM: - hostHandler = new RandomHostHandler(hostResolver, new FallbackHostHandler(hostResolver)); - break; - case ROUND_ROBIN: - hostHandler = new RoundRobinHostHandler(hostResolver); - break; - case NONE: - default: - hostHandler = new FallbackHostHandler(hostResolver); - break; - } - } else { - hostHandler = new FallbackHostHandler(hostResolver); - } - - LOG.debug("HostHandler is " + hostHandler.getClass().getSimpleName()); - - return new DirtyReadHostHandler(hostHandler, new RoundRobinHostHandler(hostResolver)); - } - - protected HostResolver createHostResolver(final Collection hosts, final int maxConnections, final ConnectionFactory connectionFactory) { - - if (acquireHostList != null && acquireHostList) { - LOG.debug("acquireHostList -> Use ExtendedHostResolver"); - return new ExtendedHostResolver(new ArrayList<>(hosts), maxConnections, connectionFactory, acquireHostListInterval); - } else { - LOG.debug("Use SimpleHostResolver"); - return new SimpleHostResolver(new ArrayList<>(hosts)); - } - - } - - private static String loadHost(final Properties properties, final String currentValue) { - final String host = getProperty(properties, PROPERTY_KEY_HOST, currentValue, ArangoDefaults.DEFAULT_HOST); - if (host.contains(":")) { - throw new ArangoDBException(String.format( - "Could not load property-value arangodb.host=%s. Expect only ip. Do you mean arangodb.hosts=ip:port ?", - host)); - } - return host; - } - - private static Integer loadPort(final Properties properties, final int currentValue) { - return Integer.parseInt(getProperty(properties, PROPERTY_KEY_PORT, currentValue, ArangoDefaults.DEFAULT_PORT)); - } - - private static Integer loadTimeout(final Properties properties, final Integer currentValue) { - return Integer - .parseInt(getProperty(properties, PROPERTY_KEY_TIMEOUT, currentValue, ArangoDefaults.DEFAULT_TIMEOUT)); - } - - private static String loadUser(final Properties properties, final String currentValue) { - return getProperty(properties, PROPERTY_KEY_USER, currentValue, ArangoDefaults.DEFAULT_USER); - } - - private static String loadPassword(final Properties properties, final String currentValue) { - return getProperty(properties, PROPERTY_KEY_PASSWORD, currentValue, null); - } - - private static Boolean loadUseSsl(final Properties properties, final Boolean currentValue) { - return Boolean.parseBoolean( - getProperty(properties, PROPERTY_KEY_USE_SSL, currentValue, ArangoDefaults.DEFAULT_USE_SSL)); - } - - private static String loadhttpCookieSpec(final Properties properties, final String currentValue) { - return getProperty(properties, PROPERTY_KEY_COOKIE_SPEC, currentValue, ""); - } - - private static Integer loadChunkSize(final Properties properties, final Integer currentValue) { - return Integer.parseInt(getProperty(properties, PROPERTY_KEY_V_STREAM_CHUNK_CONTENT_SIZE, currentValue, - ArangoDefaults.CHUNK_DEFAULT_CONTENT_SIZE)); - } - - private static Integer loadMaxConnections(final Properties properties, final Integer currentValue) { - return Integer.parseInt(getProperty(properties, PROPERTY_KEY_MAX_CONNECTIONS, currentValue, - ArangoDefaults.MAX_CONNECTIONS_VST_DEFAULT)); - } - - private static Long loadConnectionTtl(final Properties properties, final Long currentValue) { - final String ttl = getProperty(properties, PROPERTY_KEY_CONNECTION_TTL, currentValue, - ArangoDefaults.CONNECTION_TTL_VST_DEFAULT); - return ttl != null ? Long.parseLong(ttl) : null; - } - - private static Boolean loadAcquireHostList(final Properties properties, final Boolean currentValue) { - return Boolean.parseBoolean(getProperty(properties, PROPERTY_KEY_ACQUIRE_HOST_LIST, currentValue, - ArangoDefaults.DEFAULT_ACQUIRE_HOST_LIST)); - } - - private static int loadAcquireHostListInterval(final Properties properties, final Integer currentValue) { - return Integer.parseInt(getProperty(properties, PROPERTY_KEY_ACQUIRE_HOST_LIST_INTERVAL, currentValue, - ArangoDefaults.DEFAULT_ACQUIRE_HOST_LIST_INTERVAL)); - } - - private static LoadBalancingStrategy loadLoadBalancingStrategy( - final Properties properties, - final LoadBalancingStrategy currentValue) { - return LoadBalancingStrategy.valueOf(getProperty(properties, PROPERTY_KEY_LOAD_BALANCING_STRATEGY, currentValue, - ArangoDefaults.DEFAULT_LOAD_BALANCING_STRATEGY).toUpperCase()); - } - - protected static String getProperty( - final Properties properties, - final String key, - final T currentValue, - final T defaultValue) { - - String overrideDefaultValue = null; - - if(currentValue != null) { - overrideDefaultValue = currentValue.toString(); - } else if(defaultValue != null) { - overrideDefaultValue = defaultValue.toString(); - } - - return properties.getProperty(key, overrideDefaultValue); - } - - protected Collection createHostList( - final int maxConnections, - final ConnectionFactory connectionFactory) { - final Collection hostList = new ArrayList<>(); - for (final HostDescription host : hosts) { - hostList.add(HostUtils.createHost(host, maxConnections, connectionFactory)); - } - return hostList; - } + + private static final Logger LOG = LoggerFactory.getLogger(InternalArangoDBBuilder.class); + + private static final String PROPERTY_KEY_HOSTS = "arangodb.hosts"; + private static final String PROPERTY_KEY_HOST = "arangodb.host"; + private static final String PROPERTY_KEY_PORT = "arangodb.port"; + private static final String PROPERTY_KEY_TIMEOUT = "arangodb.timeout"; + private static final String PROPERTY_KEY_USER = "arangodb.user"; + private static final String PROPERTY_KEY_PASSWORD = "arangodb.password"; + private static final String PROPERTY_KEY_USE_SSL = "arangodb.usessl"; + private static final String PROPERTY_KEY_COOKIE_SPEC = "arangodb.httpCookieSpec"; + private static final String PROPERTY_KEY_V_STREAM_CHUNK_CONTENT_SIZE = "arangodb.chunksize"; + private static final String PROPERTY_KEY_MAX_CONNECTIONS = "arangodb.connections.max"; + private static final String PROPERTY_KEY_CONNECTION_TTL = "arangodb.connections.ttl"; + private static final String PROPERTY_KEY_ACQUIRE_HOST_LIST = "arangodb.acquireHostList"; + private static final String PROPERTY_KEY_ACQUIRE_HOST_LIST_INTERVAL = "arangodb.acquireHostList.interval"; + private static final String PROPERTY_KEY_LOAD_BALANCING_STRATEGY = "arangodb.loadBalancingStrategy"; + private static final String DEFAULT_PROPERTY_FILE = "/arangodb.properties"; + + protected final List hosts; + protected HostDescription host; + protected Integer timeout; + protected String user; + protected String password; + protected Boolean useSsl; + protected String httpCookieSpec; + protected SSLContext sslContext; + protected Integer chunksize; + protected Integer maxConnections; + protected Long connectionTtl; + protected final VPack.Builder vpackBuilder; + protected final VPackParser.Builder vpackParserBuilder; + protected ArangoSerializer serializer; + protected ArangoDeserializer deserializer; + protected Boolean acquireHostList; + protected Integer acquireHostListInterval; + protected LoadBalancingStrategy loadBalancingStrategy; + protected ArangoSerialization customSerializer; + + + public InternalArangoDBBuilder() { + super(); + vpackBuilder = new VPack.Builder(); + vpackParserBuilder = new VPackParser.Builder(); + vpackBuilder.registerModule(new VPackDriverModule()); + vpackParserBuilder.registerModule(new VPackDriverModule()); + host = new HostDescription(ArangoDefaults.DEFAULT_HOST, ArangoDefaults.DEFAULT_PORT); + hosts = new ArrayList<>(); + user = ArangoDefaults.DEFAULT_USER; + loadProperties(ArangoDB.class.getResourceAsStream(DEFAULT_PROPERTY_FILE)); + } + + public InternalArangoDBBuilder loadProperties(final InputStream in) throws ArangoDBException { + + final Properties properties = new Properties(); + + if (in != null) { + + try { + properties.load(in); + } catch (final IOException e) { + throw new ArangoDBException(e); + } + } + + loadProperties(properties); + + return this; + + } + + protected void loadProperties(final Properties properties) { + loadHosts(properties, this.hosts); + final String host = loadHost(properties, this.host.getHost()); + final int port = loadPort(properties, this.host.getPort()); + this.host = new HostDescription(host, port); + timeout = loadTimeout(properties, timeout); + user = loadUser(properties, user); + password = loadPassword(properties, password); + useSsl = loadUseSsl(properties, useSsl); + httpCookieSpec = loadhttpCookieSpec(properties, httpCookieSpec); + chunksize = loadChunkSize(properties, chunksize); + maxConnections = loadMaxConnections(properties, maxConnections); + connectionTtl = loadConnectionTtl(properties, connectionTtl); + acquireHostList = loadAcquireHostList(properties, acquireHostList); + acquireHostListInterval = loadAcquireHostListInterval(properties, acquireHostListInterval); + loadBalancingStrategy = loadLoadBalancingStrategy(properties, loadBalancingStrategy); + } + + protected void setHost(final String host, final int port) { + hosts.add(new HostDescription(host, port)); + } + + protected void setTimeout(final Integer timeout) { + this.timeout = timeout; + } + + protected void setUser(final String user) { + this.user = user; + } + + protected void setPassword(final String password) { + this.password = password; + } + + protected void setUseSsl(final Boolean useSsl) { + this.useSsl = useSsl; + } + + protected void setSslContext(final SSLContext sslContext) { + this.sslContext = sslContext; + } + + protected void setChunksize(final Integer chunksize) { + this.chunksize = chunksize; + } + + protected void setMaxConnections(final Integer maxConnections) { + this.maxConnections = maxConnections; + } + + protected void setConnectionTtl(final Long connectionTtl) { + this.connectionTtl = connectionTtl; + } + + protected void setAcquireHostList(final Boolean acquireHostList) { + this.acquireHostList = acquireHostList; + } + + protected void setAcquireHostListInterval(final Integer acquireHostListInterval) { + this.acquireHostListInterval = acquireHostListInterval; + } + + protected void setLoadBalancingStrategy(final LoadBalancingStrategy loadBalancingStrategy) { + this.loadBalancingStrategy = loadBalancingStrategy; + } + + protected void serializer(final ArangoSerializer serializer) { + this.serializer = serializer; + } + + protected void deserializer(final ArangoDeserializer deserializer) { + this.deserializer = deserializer; + } + + protected void setSerializer(final ArangoSerialization serializer) { + this.customSerializer = serializer; + } + + private static void loadHosts(final Properties properties, final Collection hosts) { + final String hostsProp = properties.getProperty(PROPERTY_KEY_HOSTS); + if (hostsProp != null) { + final String[] hostsSplit = hostsProp.split(","); + for (final String host : hostsSplit) { + final String[] split = host.split(":"); + if (split.length != 2 || !split[1].matches("[0-9]+")) { + throw new ArangoDBException(String.format( + "Could not load property-value arangodb.hosts=%s. Expected format ip:port,ip:port,...", + hostsProp)); + } else { + hosts.add(new HostDescription(split[0], Integer.parseInt(split[1]))); + } + } + } + } + + protected HostHandler createHostHandler(final HostResolver hostResolver) { + + final HostHandler hostHandler; + + if (loadBalancingStrategy != null) { + switch (loadBalancingStrategy) { + case ONE_RANDOM: + hostHandler = new RandomHostHandler(hostResolver, new FallbackHostHandler(hostResolver)); + break; + case ROUND_ROBIN: + hostHandler = new RoundRobinHostHandler(hostResolver); + break; + case NONE: + default: + hostHandler = new FallbackHostHandler(hostResolver); + break; + } + } else { + hostHandler = new FallbackHostHandler(hostResolver); + } + + LOG.debug("HostHandler is " + hostHandler.getClass().getSimpleName()); + + return new DirtyReadHostHandler(hostHandler, new RoundRobinHostHandler(hostResolver)); + } + + protected HostResolver createHostResolver(final Collection hosts, final int maxConnections, final ConnectionFactory connectionFactory) { + + if (acquireHostList != null && acquireHostList) { + LOG.debug("acquireHostList -> Use ExtendedHostResolver"); + return new ExtendedHostResolver(new ArrayList<>(hosts), maxConnections, connectionFactory, acquireHostListInterval); + } else { + LOG.debug("Use SimpleHostResolver"); + return new SimpleHostResolver(new ArrayList<>(hosts)); + } + + } + + private static String loadHost(final Properties properties, final String currentValue) { + final String host = getProperty(properties, PROPERTY_KEY_HOST, currentValue, ArangoDefaults.DEFAULT_HOST); + if (host.contains(":")) { + throw new ArangoDBException(String.format( + "Could not load property-value arangodb.host=%s. Expect only ip. Do you mean arangodb.hosts=ip:port ?", + host)); + } + return host; + } + + private static Integer loadPort(final Properties properties, final int currentValue) { + return Integer.parseInt(getProperty(properties, PROPERTY_KEY_PORT, currentValue, ArangoDefaults.DEFAULT_PORT)); + } + + private static Integer loadTimeout(final Properties properties, final Integer currentValue) { + return Integer + .parseInt(getProperty(properties, PROPERTY_KEY_TIMEOUT, currentValue, ArangoDefaults.DEFAULT_TIMEOUT)); + } + + private static String loadUser(final Properties properties, final String currentValue) { + return getProperty(properties, PROPERTY_KEY_USER, currentValue, ArangoDefaults.DEFAULT_USER); + } + + private static String loadPassword(final Properties properties, final String currentValue) { + return getProperty(properties, PROPERTY_KEY_PASSWORD, currentValue, null); + } + + private static Boolean loadUseSsl(final Properties properties, final Boolean currentValue) { + return Boolean.parseBoolean( + getProperty(properties, PROPERTY_KEY_USE_SSL, currentValue, ArangoDefaults.DEFAULT_USE_SSL)); + } + + private static String loadhttpCookieSpec(final Properties properties, final String currentValue) { + return getProperty(properties, PROPERTY_KEY_COOKIE_SPEC, currentValue, ""); + } + + private static Integer loadChunkSize(final Properties properties, final Integer currentValue) { + return Integer.parseInt(getProperty(properties, PROPERTY_KEY_V_STREAM_CHUNK_CONTENT_SIZE, currentValue, + ArangoDefaults.CHUNK_DEFAULT_CONTENT_SIZE)); + } + + private static Integer loadMaxConnections(final Properties properties, final Integer currentValue) { + return Integer.parseInt(getProperty(properties, PROPERTY_KEY_MAX_CONNECTIONS, currentValue, + ArangoDefaults.MAX_CONNECTIONS_VST_DEFAULT)); + } + + private static Long loadConnectionTtl(final Properties properties, final Long currentValue) { + final String ttl = getProperty(properties, PROPERTY_KEY_CONNECTION_TTL, currentValue, + ArangoDefaults.CONNECTION_TTL_VST_DEFAULT); + return ttl != null ? Long.parseLong(ttl) : null; + } + + private static Boolean loadAcquireHostList(final Properties properties, final Boolean currentValue) { + return Boolean.parseBoolean(getProperty(properties, PROPERTY_KEY_ACQUIRE_HOST_LIST, currentValue, + ArangoDefaults.DEFAULT_ACQUIRE_HOST_LIST)); + } + + private static int loadAcquireHostListInterval(final Properties properties, final Integer currentValue) { + return Integer.parseInt(getProperty(properties, PROPERTY_KEY_ACQUIRE_HOST_LIST_INTERVAL, currentValue, + ArangoDefaults.DEFAULT_ACQUIRE_HOST_LIST_INTERVAL)); + } + + private static LoadBalancingStrategy loadLoadBalancingStrategy( + final Properties properties, + final LoadBalancingStrategy currentValue) { + return LoadBalancingStrategy.valueOf(getProperty(properties, PROPERTY_KEY_LOAD_BALANCING_STRATEGY, currentValue, + ArangoDefaults.DEFAULT_LOAD_BALANCING_STRATEGY).toUpperCase()); + } + + protected static String getProperty( + final Properties properties, + final String key, + final T currentValue, + final T defaultValue) { + + String overrideDefaultValue = null; + + if (currentValue != null) { + overrideDefaultValue = currentValue.toString(); + } else if (defaultValue != null) { + overrideDefaultValue = defaultValue.toString(); + } + + return properties.getProperty(key, overrideDefaultValue); + } + + protected Collection createHostList( + final int maxConnections, + final ConnectionFactory connectionFactory) { + final Collection hostList = new ArrayList<>(); + for (final HostDescription host : hosts) { + hostList.add(HostUtils.createHost(host, maxConnections, connectionFactory)); + } + return hostList; + } } diff --git a/src/main/java/com/arangodb/internal/InternalArangoEdgeCollection.java b/src/main/java/com/arangodb/internal/InternalArangoEdgeCollection.java index c9fb9a903..a901e9f2d 100644 --- a/src/main/java/com/arangodb/internal/InternalArangoEdgeCollection.java +++ b/src/main/java/com/arangodb/internal/InternalArangoEdgeCollection.java @@ -38,128 +38,127 @@ /** * @author Mark Vollmary - * */ public abstract class InternalArangoEdgeCollection, D extends InternalArangoDatabase, G extends InternalArangoGraph, E extends ArangoExecutor> - extends ArangoExecuteable { + extends ArangoExecuteable { - private static final String PATH_API_GHARIAL = "/_api/gharial"; - private static final String EDGE = "edge"; + private static final String PATH_API_GHARIAL = "/_api/gharial"; + private static final String EDGE = "edge"; private static final String TRANSACTION_ID = "x-arango-trx-id"; - private final G graph; - private final String name; + private final G graph; + private final String name; - protected InternalArangoEdgeCollection(final G graph, final String name) { - super(graph.executor, graph.util, graph.context); - this.graph = graph; - this.name = name; - } + protected InternalArangoEdgeCollection(final G graph, final String name) { + super(graph.executor, graph.util, graph.context); + this.graph = graph; + this.name = name; + } - public G graph() { - return graph; - } + public G graph() { + return graph; + } - public String name() { - return name; - } + public String name() { + return name; + } - protected Request insertEdgeRequest(final T value, final EdgeCreateOptions options) { - final Request request = request(graph.db().name(), RequestType.POST, PATH_API_GHARIAL, graph.name(), EDGE, - name); - final EdgeCreateOptions params = (options != null ? options : new EdgeCreateOptions()); + protected Request insertEdgeRequest(final T value, final EdgeCreateOptions options) { + final Request request = request(graph.db().name(), RequestType.POST, PATH_API_GHARIAL, graph.name(), EDGE, + name); + final EdgeCreateOptions params = (options != null ? options : new EdgeCreateOptions()); request.putHeaderParam(TRANSACTION_ID, params.getStreamTransactionId()); - request.putQueryParam(ArangoRequestParam.WAIT_FOR_SYNC, params.getWaitForSync()); - request.setBody(util(Serializer.CUSTOM).serialize(value)); - return request; - } - - protected ResponseDeserializer insertEdgeResponseDeserializer(final T value) { - return response -> { - final VPackSlice body = response.getBody().get(EDGE); - final EdgeEntity doc = util().deserialize(body, EdgeEntity.class); - final Map values = new HashMap<>(); - values.put(DocumentField.Type.ID, doc.getId()); - values.put(DocumentField.Type.KEY, doc.getKey()); - values.put(DocumentField.Type.REV, doc.getRev()); - executor.documentCache().setValues(value, values); - return doc; - }; - } - - protected Request getEdgeRequest(final String key, final GraphDocumentReadOptions options) { - final Request request = request(graph.db().name(), RequestType.GET, PATH_API_GHARIAL, graph.name(), EDGE, - DocumentUtil.createDocumentHandle(name, key)); - final GraphDocumentReadOptions params = (options != null ? options : new GraphDocumentReadOptions()); + request.putQueryParam(ArangoRequestParam.WAIT_FOR_SYNC, params.getWaitForSync()); + request.setBody(util(Serializer.CUSTOM).serialize(value)); + return request; + } + + protected ResponseDeserializer insertEdgeResponseDeserializer(final T value) { + return response -> { + final VPackSlice body = response.getBody().get(EDGE); + final EdgeEntity doc = util().deserialize(body, EdgeEntity.class); + final Map values = new HashMap<>(); + values.put(DocumentField.Type.ID, doc.getId()); + values.put(DocumentField.Type.KEY, doc.getKey()); + values.put(DocumentField.Type.REV, doc.getRev()); + executor.documentCache().setValues(value, values); + return doc; + }; + } + + protected Request getEdgeRequest(final String key, final GraphDocumentReadOptions options) { + final Request request = request(graph.db().name(), RequestType.GET, PATH_API_GHARIAL, graph.name(), EDGE, + DocumentUtil.createDocumentHandle(name, key)); + final GraphDocumentReadOptions params = (options != null ? options : new GraphDocumentReadOptions()); request.putHeaderParam(TRANSACTION_ID, params.getStreamTransactionId()); - request.putHeaderParam(ArangoRequestParam.IF_NONE_MATCH, params.getIfNoneMatch()); - request.putHeaderParam(ArangoRequestParam.IF_MATCH, params.getIfMatch()); - if (params.getAllowDirtyRead() == Boolean.TRUE) { - RequestUtils.allowDirtyRead(request); - } - return request; - } - - protected ResponseDeserializer getEdgeResponseDeserializer(final Class type) { - return response -> util(Serializer.CUSTOM).deserialize(response.getBody().get(EDGE), type); - } - - protected Request replaceEdgeRequest(final String key, final T value, final EdgeReplaceOptions options) { - final Request request = request(graph.db().name(), RequestType.PUT, PATH_API_GHARIAL, graph.name(), EDGE, - DocumentUtil.createDocumentHandle(name, key)); - final EdgeReplaceOptions params = (options != null ? options : new EdgeReplaceOptions()); + request.putHeaderParam(ArangoRequestParam.IF_NONE_MATCH, params.getIfNoneMatch()); + request.putHeaderParam(ArangoRequestParam.IF_MATCH, params.getIfMatch()); + if (params.getAllowDirtyRead() == Boolean.TRUE) { + RequestUtils.allowDirtyRead(request); + } + return request; + } + + protected ResponseDeserializer getEdgeResponseDeserializer(final Class type) { + return response -> util(Serializer.CUSTOM).deserialize(response.getBody().get(EDGE), type); + } + + protected Request replaceEdgeRequest(final String key, final T value, final EdgeReplaceOptions options) { + final Request request = request(graph.db().name(), RequestType.PUT, PATH_API_GHARIAL, graph.name(), EDGE, + DocumentUtil.createDocumentHandle(name, key)); + final EdgeReplaceOptions params = (options != null ? options : new EdgeReplaceOptions()); request.putHeaderParam(TRANSACTION_ID, params.getStreamTransactionId()); - request.putQueryParam(ArangoRequestParam.WAIT_FOR_SYNC, params.getWaitForSync()); - request.putHeaderParam(ArangoRequestParam.IF_MATCH, params.getIfMatch()); - request.setBody(util(Serializer.CUSTOM).serialize(value)); - return request; - } - - protected ResponseDeserializer replaceEdgeResponseDeserializer(final T value) { - return response -> { - final VPackSlice body = response.getBody().get(EDGE); - final EdgeUpdateEntity doc = util().deserialize(body, EdgeUpdateEntity.class); - final Map values = new HashMap<>(); - values.put(DocumentField.Type.REV, doc.getRev()); - executor.documentCache().setValues(value, values); - return doc; - }; - } - - protected Request updateEdgeRequest(final String key, final T value, final EdgeUpdateOptions options) { - final Request request; - request = request(graph.db().name(), RequestType.PATCH, PATH_API_GHARIAL, graph.name(), EDGE, - DocumentUtil.createDocumentHandle(name, key)); - final EdgeUpdateOptions params = (options != null ? options : new EdgeUpdateOptions()); + request.putQueryParam(ArangoRequestParam.WAIT_FOR_SYNC, params.getWaitForSync()); + request.putHeaderParam(ArangoRequestParam.IF_MATCH, params.getIfMatch()); + request.setBody(util(Serializer.CUSTOM).serialize(value)); + return request; + } + + protected ResponseDeserializer replaceEdgeResponseDeserializer(final T value) { + return response -> { + final VPackSlice body = response.getBody().get(EDGE); + final EdgeUpdateEntity doc = util().deserialize(body, EdgeUpdateEntity.class); + final Map values = new HashMap<>(); + values.put(DocumentField.Type.REV, doc.getRev()); + executor.documentCache().setValues(value, values); + return doc; + }; + } + + protected Request updateEdgeRequest(final String key, final T value, final EdgeUpdateOptions options) { + final Request request; + request = request(graph.db().name(), RequestType.PATCH, PATH_API_GHARIAL, graph.name(), EDGE, + DocumentUtil.createDocumentHandle(name, key)); + final EdgeUpdateOptions params = (options != null ? options : new EdgeUpdateOptions()); request.putHeaderParam(TRANSACTION_ID, params.getStreamTransactionId()); - request.putQueryParam(ArangoRequestParam.KEEP_NULL, params.getKeepNull()); - request.putQueryParam(ArangoRequestParam.WAIT_FOR_SYNC, params.getWaitForSync()); - request.putHeaderParam(ArangoRequestParam.IF_MATCH, params.getIfMatch()); - request.setBody( - util(Serializer.CUSTOM).serialize(value, new ArangoSerializer.Options().serializeNullValues(true))); - return request; - } - - protected ResponseDeserializer updateEdgeResponseDeserializer(final T value) { - return response -> { - final VPackSlice body = response.getBody().get(EDGE); - final EdgeUpdateEntity doc = util().deserialize(body, EdgeUpdateEntity.class); - final Map values = new HashMap<>(); - values.put(DocumentField.Type.REV, doc.getRev()); - executor.documentCache().setValues(value, values); - return doc; - }; - } - - protected Request deleteEdgeRequest(final String key, final EdgeDeleteOptions options) { - final Request request = request(graph.db().name(), RequestType.DELETE, PATH_API_GHARIAL, graph.name(), EDGE, - DocumentUtil.createDocumentHandle(name, key)); - final EdgeDeleteOptions params = (options != null ? options : new EdgeDeleteOptions()); + request.putQueryParam(ArangoRequestParam.KEEP_NULL, params.getKeepNull()); + request.putQueryParam(ArangoRequestParam.WAIT_FOR_SYNC, params.getWaitForSync()); + request.putHeaderParam(ArangoRequestParam.IF_MATCH, params.getIfMatch()); + request.setBody( + util(Serializer.CUSTOM).serialize(value, new ArangoSerializer.Options().serializeNullValues(true))); + return request; + } + + protected ResponseDeserializer updateEdgeResponseDeserializer(final T value) { + return response -> { + final VPackSlice body = response.getBody().get(EDGE); + final EdgeUpdateEntity doc = util().deserialize(body, EdgeUpdateEntity.class); + final Map values = new HashMap<>(); + values.put(DocumentField.Type.REV, doc.getRev()); + executor.documentCache().setValues(value, values); + return doc; + }; + } + + protected Request deleteEdgeRequest(final String key, final EdgeDeleteOptions options) { + final Request request = request(graph.db().name(), RequestType.DELETE, PATH_API_GHARIAL, graph.name(), EDGE, + DocumentUtil.createDocumentHandle(name, key)); + final EdgeDeleteOptions params = (options != null ? options : new EdgeDeleteOptions()); request.putHeaderParam(TRANSACTION_ID, params.getStreamTransactionId()); - request.putQueryParam(ArangoRequestParam.WAIT_FOR_SYNC, params.getWaitForSync()); - request.putHeaderParam(ArangoRequestParam.IF_MATCH, params.getIfMatch()); - return request; - } + request.putQueryParam(ArangoRequestParam.WAIT_FOR_SYNC, params.getWaitForSync()); + request.putHeaderParam(ArangoRequestParam.IF_MATCH, params.getIfMatch()); + return request; + } } diff --git a/src/main/java/com/arangodb/internal/InternalArangoGraph.java b/src/main/java/com/arangodb/internal/InternalArangoGraph.java index 998c56fee..59300ef29 100644 --- a/src/main/java/com/arangodb/internal/InternalArangoGraph.java +++ b/src/main/java/com/arangodb/internal/InternalArangoGraph.java @@ -33,108 +33,107 @@ /** * @author Mark Vollmary - * */ public abstract class InternalArangoGraph, D extends InternalArangoDatabase, E extends ArangoExecutor> - extends ArangoExecuteable { - - protected static final String PATH_API_GHARIAL = "/_api/gharial"; - private static final String GRAPH = "graph"; - private static final String VERTEX = "vertex"; - private static final String EDGE = "edge"; - - private final D db; - private final String name; - - protected InternalArangoGraph(final D db, final String name) { - super(db.executor, db.util, db.context); - this.db = db; - this.name = name; - } - - public D db() { - return db; - } - - public String name() { - return name; - } - - protected Request dropRequest() { - return dropRequest(false); - } - - protected Request dropRequest(final boolean dropCollections) { - final Request request = request(db.name(), RequestType.DELETE, PATH_API_GHARIAL, name); - if (dropCollections) { - request.putQueryParam("dropCollections", true); - } - return request; - } - - protected Request getInfoRequest() { - return request(db.name(), RequestType.GET, PATH_API_GHARIAL, name); - } - - protected ResponseDeserializer getInfoResponseDeserializer() { - return addVertexCollectionResponseDeserializer(); - } - - protected Request getVertexCollectionsRequest() { - return request(db.name(), RequestType.GET, PATH_API_GHARIAL, name, VERTEX); - } - - protected ResponseDeserializer> getVertexCollectionsResponseDeserializer() { - return response -> util().deserialize(response.getBody().get("collections"), new Type>() { - }.getType()); - } - - protected Request addVertexCollectionRequest(final String name) { - final Request request = request(db.name(), RequestType.POST, PATH_API_GHARIAL, name(), VERTEX); - request.setBody(util().serialize(OptionsBuilder.build(new VertexCollectionCreateOptions(), name))); - return request; - } - - protected ResponseDeserializer addVertexCollectionResponseDeserializer() { - return addEdgeDefinitionResponseDeserializer(); - } - - protected Request getEdgeDefinitionsRequest() { - return request(db.name(), RequestType.GET, PATH_API_GHARIAL, name, EDGE); - } - - protected ResponseDeserializer> getEdgeDefinitionsDeserializer() { - return response -> util().deserialize(response.getBody().get("collections"), new Type>() { - }.getType()); - } - - protected Request addEdgeDefinitionRequest(final EdgeDefinition definition) { - final Request request = request(db.name(), RequestType.POST, PATH_API_GHARIAL, name, EDGE); - request.setBody(util().serialize(definition)); - return request; - } - - protected ResponseDeserializer addEdgeDefinitionResponseDeserializer() { - return response -> util().deserialize(response.getBody().get(GRAPH), GraphEntity.class); - } - - protected Request replaceEdgeDefinitionRequest(final EdgeDefinition definition) { - final Request request = request(db.name(), RequestType.PUT, PATH_API_GHARIAL, name, EDGE, - definition.getCollection()); - request.setBody(util().serialize(definition)); - return request; - } - - protected ResponseDeserializer replaceEdgeDefinitionResponseDeserializer() { - return response -> util().deserialize(response.getBody().get(GRAPH), GraphEntity.class); - } - - protected Request removeEdgeDefinitionRequest(final String definitionName) { - return request(db.name(), RequestType.DELETE, PATH_API_GHARIAL, name, EDGE, definitionName); - } - - protected ResponseDeserializer removeEdgeDefinitionResponseDeserializer() { - return response -> util().deserialize(response.getBody().get(GRAPH), GraphEntity.class); - } + extends ArangoExecuteable { + + protected static final String PATH_API_GHARIAL = "/_api/gharial"; + private static final String GRAPH = "graph"; + private static final String VERTEX = "vertex"; + private static final String EDGE = "edge"; + + private final D db; + private final String name; + + protected InternalArangoGraph(final D db, final String name) { + super(db.executor, db.util, db.context); + this.db = db; + this.name = name; + } + + public D db() { + return db; + } + + public String name() { + return name; + } + + protected Request dropRequest() { + return dropRequest(false); + } + + protected Request dropRequest(final boolean dropCollections) { + final Request request = request(db.name(), RequestType.DELETE, PATH_API_GHARIAL, name); + if (dropCollections) { + request.putQueryParam("dropCollections", true); + } + return request; + } + + protected Request getInfoRequest() { + return request(db.name(), RequestType.GET, PATH_API_GHARIAL, name); + } + + protected ResponseDeserializer getInfoResponseDeserializer() { + return addVertexCollectionResponseDeserializer(); + } + + protected Request getVertexCollectionsRequest() { + return request(db.name(), RequestType.GET, PATH_API_GHARIAL, name, VERTEX); + } + + protected ResponseDeserializer> getVertexCollectionsResponseDeserializer() { + return response -> util().deserialize(response.getBody().get("collections"), new Type>() { + }.getType()); + } + + protected Request addVertexCollectionRequest(final String name) { + final Request request = request(db.name(), RequestType.POST, PATH_API_GHARIAL, name(), VERTEX); + request.setBody(util().serialize(OptionsBuilder.build(new VertexCollectionCreateOptions(), name))); + return request; + } + + protected ResponseDeserializer addVertexCollectionResponseDeserializer() { + return addEdgeDefinitionResponseDeserializer(); + } + + protected Request getEdgeDefinitionsRequest() { + return request(db.name(), RequestType.GET, PATH_API_GHARIAL, name, EDGE); + } + + protected ResponseDeserializer> getEdgeDefinitionsDeserializer() { + return response -> util().deserialize(response.getBody().get("collections"), new Type>() { + }.getType()); + } + + protected Request addEdgeDefinitionRequest(final EdgeDefinition definition) { + final Request request = request(db.name(), RequestType.POST, PATH_API_GHARIAL, name, EDGE); + request.setBody(util().serialize(definition)); + return request; + } + + protected ResponseDeserializer addEdgeDefinitionResponseDeserializer() { + return response -> util().deserialize(response.getBody().get(GRAPH), GraphEntity.class); + } + + protected Request replaceEdgeDefinitionRequest(final EdgeDefinition definition) { + final Request request = request(db.name(), RequestType.PUT, PATH_API_GHARIAL, name, EDGE, + definition.getCollection()); + request.setBody(util().serialize(definition)); + return request; + } + + protected ResponseDeserializer replaceEdgeDefinitionResponseDeserializer() { + return response -> util().deserialize(response.getBody().get(GRAPH), GraphEntity.class); + } + + protected Request removeEdgeDefinitionRequest(final String definitionName) { + return request(db.name(), RequestType.DELETE, PATH_API_GHARIAL, name, EDGE, definitionName); + } + + protected ResponseDeserializer removeEdgeDefinitionResponseDeserializer() { + return response -> util().deserialize(response.getBody().get(GRAPH), GraphEntity.class); + } } diff --git a/src/main/java/com/arangodb/internal/InternalArangoRoute.java b/src/main/java/com/arangodb/internal/InternalArangoRoute.java index 2194d6d54..c73bc665a 100644 --- a/src/main/java/com/arangodb/internal/InternalArangoRoute.java +++ b/src/main/java/com/arangodb/internal/InternalArangoRoute.java @@ -29,54 +29,53 @@ /** * @author Mark Vollmary - * */ public abstract class InternalArangoRoute, D extends InternalArangoDatabase, E extends ArangoExecutor> - extends ArangoExecuteable { + extends ArangoExecuteable { - protected final D db; - protected final String path; + protected final D db; + protected final String path; - protected final Map queryParam; - protected final Map headerParam; - protected Object body; + protected final Map queryParam; + protected final Map headerParam; + protected Object body; - protected InternalArangoRoute(final D db, final String path, final Map headerParam) { - super(db.executor, db.util, db.context); - this.db = db; - this.path = path; + protected InternalArangoRoute(final D db, final String path, final Map headerParam) { + super(db.executor, db.util, db.context); + this.db = db; + this.path = path; this.queryParam = new HashMap<>(); this.headerParam = new HashMap<>(); - this.headerParam.putAll(headerParam); - } + this.headerParam.putAll(headerParam); + } - public void _withHeader(final String key, final Object value) { - if (value != null) { - headerParam.put(key, value.toString()); - } - } + public void _withHeader(final String key, final Object value) { + if (value != null) { + headerParam.put(key, value.toString()); + } + } - public void _withQueryParam(final String key, final Object value) { - if (value != null) { - queryParam.put(key, value.toString()); - } - } + public void _withQueryParam(final String key, final Object value) { + if (value != null) { + queryParam.put(key, value.toString()); + } + } - public void _withBody(final Object body) { - this.body = body; - } + public void _withBody(final Object body) { + this.body = body; + } - protected Request createRequest(final RequestType requestType) { - final Request request = request(db.name(), requestType, path); - for (final Entry param : headerParam.entrySet()) { - request.putHeaderParam(param.getKey(), param.getValue()); - } - for (final Entry param : queryParam.entrySet()) { - request.putQueryParam(param.getKey(), param.getValue()); - } - if (body != null) { - request.setBody(util().serialize(body)); - } - return request; - } + protected Request createRequest(final RequestType requestType) { + final Request request = request(db.name(), requestType, path); + for (final Entry param : headerParam.entrySet()) { + request.putHeaderParam(param.getKey(), param.getValue()); + } + for (final Entry param : queryParam.entrySet()) { + request.putQueryParam(param.getKey(), param.getValue()); + } + if (body != null) { + request.setBody(util().serialize(body)); + } + return request; + } } diff --git a/src/main/java/com/arangodb/internal/InternalArangoSearch.java b/src/main/java/com/arangodb/internal/InternalArangoSearch.java index 63ad01f89..00e7f5c71 100644 --- a/src/main/java/com/arangodb/internal/InternalArangoSearch.java +++ b/src/main/java/com/arangodb/internal/InternalArangoSearch.java @@ -26,29 +26,28 @@ /** * @author Mark Vollmary - * */ public class InternalArangoSearch, D extends InternalArangoDatabase, E extends ArangoExecutor> - extends InternalArangoView { - - protected InternalArangoSearch(final D db, final String name) { - super(db, name); - } - - protected Request getPropertiesRequest() { - return request(db.name(), RequestType.GET, PATH_API_VIEW, name, "properties"); - } - - protected Request replacePropertiesRequest(final ArangoSearchPropertiesOptions options) { - final Request request = request(db.name(), RequestType.PUT, PATH_API_VIEW, name, "properties"); - request.setBody(util().serialize(options != null ? options : new ArangoSearchPropertiesOptions())); - return request; - } - - protected Request updatePropertiesRequest(final ArangoSearchPropertiesOptions options) { - final Request request = request(db.name(), RequestType.PATCH, PATH_API_VIEW, name, "properties"); - request.setBody(util().serialize(options != null ? options : new ArangoSearchPropertiesOptions())); - return request; - } + extends InternalArangoView { + + protected InternalArangoSearch(final D db, final String name) { + super(db, name); + } + + protected Request getPropertiesRequest() { + return request(db.name(), RequestType.GET, PATH_API_VIEW, name, "properties"); + } + + protected Request replacePropertiesRequest(final ArangoSearchPropertiesOptions options) { + final Request request = request(db.name(), RequestType.PUT, PATH_API_VIEW, name, "properties"); + request.setBody(util().serialize(options != null ? options : new ArangoSearchPropertiesOptions())); + return request; + } + + protected Request updatePropertiesRequest(final ArangoSearchPropertiesOptions options) { + final Request request = request(db.name(), RequestType.PATCH, PATH_API_VIEW, name, "properties"); + request.setBody(util().serialize(options != null ? options : new ArangoSearchPropertiesOptions())); + return request; + } } diff --git a/src/main/java/com/arangodb/internal/InternalArangoVertexCollection.java b/src/main/java/com/arangodb/internal/InternalArangoVertexCollection.java index d0a6f9412..722afe09c 100644 --- a/src/main/java/com/arangodb/internal/InternalArangoVertexCollection.java +++ b/src/main/java/com/arangodb/internal/InternalArangoVertexCollection.java @@ -38,132 +38,131 @@ /** * @author Mark Vollmary - * */ public abstract class InternalArangoVertexCollection, D extends InternalArangoDatabase, G extends InternalArangoGraph, E extends ArangoExecutor> - extends ArangoExecuteable { + extends ArangoExecuteable { - private static final String PATH_API_GHARIAL = "/_api/gharial"; - private static final String VERTEX = "vertex"; + private static final String PATH_API_GHARIAL = "/_api/gharial"; + private static final String VERTEX = "vertex"; private static final String TRANSACTION_ID = "x-arango-trx-id"; - private final G graph; - private final String name; + private final G graph; + private final String name; - protected InternalArangoVertexCollection(final G graph, final String name) { - super(graph.executor, graph.util, graph.context); - this.graph = graph; - this.name = name; - } + protected InternalArangoVertexCollection(final G graph, final String name) { + super(graph.executor, graph.util, graph.context); + this.graph = graph; + this.name = name; + } - public G graph() { - return graph; - } + public G graph() { + return graph; + } - public String name() { - return name; - } + public String name() { + return name; + } - protected Request dropRequest() { - return request(graph.db().name(), RequestType.DELETE, PATH_API_GHARIAL, graph.name(), VERTEX, name); - } + protected Request dropRequest() { + return request(graph.db().name(), RequestType.DELETE, PATH_API_GHARIAL, graph.name(), VERTEX, name); + } - protected Request insertVertexRequest(final T value, final VertexCreateOptions options) { - final Request request = request(graph.db().name(), RequestType.POST, PATH_API_GHARIAL, graph.name(), VERTEX, - name); - final VertexCreateOptions params = (options != null ? options : new VertexCreateOptions()); + protected Request insertVertexRequest(final T value, final VertexCreateOptions options) { + final Request request = request(graph.db().name(), RequestType.POST, PATH_API_GHARIAL, graph.name(), VERTEX, + name); + final VertexCreateOptions params = (options != null ? options : new VertexCreateOptions()); + request.putHeaderParam(TRANSACTION_ID, params.getStreamTransactionId()); + request.putQueryParam(ArangoRequestParam.WAIT_FOR_SYNC, params.getWaitForSync()); + request.setBody(util(Serializer.CUSTOM).serialize(value)); + return request; + } + + protected ResponseDeserializer insertVertexResponseDeserializer(final T value) { + return response -> { + final VPackSlice body = response.getBody().get(VERTEX); + final VertexEntity doc = util().deserialize(body, VertexEntity.class); + final Map values = new HashMap<>(); + values.put(DocumentField.Type.ID, doc.getId()); + values.put(DocumentField.Type.KEY, doc.getKey()); + values.put(DocumentField.Type.REV, doc.getRev()); + executor.documentCache().setValues(value, values); + return doc; + }; + } + + protected Request getVertexRequest(final String key, final GraphDocumentReadOptions options) { + final Request request = request(graph.db().name(), RequestType.GET, PATH_API_GHARIAL, graph.name(), VERTEX, + DocumentUtil.createDocumentHandle(name, key)); + final GraphDocumentReadOptions params = (options != null ? options : new GraphDocumentReadOptions()); + request.putHeaderParam(TRANSACTION_ID, params.getStreamTransactionId()); + request.putHeaderParam(ArangoRequestParam.IF_NONE_MATCH, params.getIfNoneMatch()); + request.putHeaderParam(ArangoRequestParam.IF_MATCH, params.getIfMatch()); + if (params.getAllowDirtyRead() == Boolean.TRUE) { + RequestUtils.allowDirtyRead(request); + } + return request; + } + + protected ResponseDeserializer getVertexResponseDeserializer(final Class type) { + return response -> util(Serializer.CUSTOM).deserialize(response.getBody().get(VERTEX), type); + } + + protected Request replaceVertexRequest(final String key, final T value, final VertexReplaceOptions options) { + final Request request = request(graph.db().name(), RequestType.PUT, PATH_API_GHARIAL, graph.name(), VERTEX, + DocumentUtil.createDocumentHandle(name, key)); + final VertexReplaceOptions params = (options != null ? options : new VertexReplaceOptions()); + request.putHeaderParam(TRANSACTION_ID, params.getStreamTransactionId()); + request.putQueryParam(ArangoRequestParam.WAIT_FOR_SYNC, params.getWaitForSync()); + request.putHeaderParam(ArangoRequestParam.IF_MATCH, params.getIfMatch()); + request.setBody(util(Serializer.CUSTOM).serialize(value)); + return request; + } + + protected ResponseDeserializer replaceVertexResponseDeserializer(final T value) { + return response -> { + final VPackSlice body = response.getBody().get(VERTEX); + final VertexUpdateEntity doc = util().deserialize(body, VertexUpdateEntity.class); + final Map values = new HashMap<>(); + values.put(DocumentField.Type.REV, doc.getRev()); + executor.documentCache().setValues(value, values); + return doc; + }; + } + + protected Request updateVertexRequest(final String key, final T value, final VertexUpdateOptions options) { + final Request request; + request = request(graph.db().name(), RequestType.PATCH, PATH_API_GHARIAL, graph.name(), VERTEX, + DocumentUtil.createDocumentHandle(name, key)); + final VertexUpdateOptions params = (options != null ? options : new VertexUpdateOptions()); request.putHeaderParam(TRANSACTION_ID, params.getStreamTransactionId()); - request.putQueryParam(ArangoRequestParam.WAIT_FOR_SYNC, params.getWaitForSync()); - request.setBody(util(Serializer.CUSTOM).serialize(value)); - return request; - } - - protected ResponseDeserializer insertVertexResponseDeserializer(final T value) { - return response -> { - final VPackSlice body = response.getBody().get(VERTEX); - final VertexEntity doc = util().deserialize(body, VertexEntity.class); - final Map values = new HashMap<>(); - values.put(DocumentField.Type.ID, doc.getId()); - values.put(DocumentField.Type.KEY, doc.getKey()); - values.put(DocumentField.Type.REV, doc.getRev()); - executor.documentCache().setValues(value, values); - return doc; - }; - } - - protected Request getVertexRequest(final String key, final GraphDocumentReadOptions options) { - final Request request = request(graph.db().name(), RequestType.GET, PATH_API_GHARIAL, graph.name(), VERTEX, - DocumentUtil.createDocumentHandle(name, key)); - final GraphDocumentReadOptions params = (options != null ? options : new GraphDocumentReadOptions()); + request.putQueryParam(ArangoRequestParam.KEEP_NULL, params.getKeepNull()); + request.putQueryParam(ArangoRequestParam.WAIT_FOR_SYNC, params.getWaitForSync()); + request.putHeaderParam(ArangoRequestParam.IF_MATCH, params.getIfMatch()); + request.setBody( + util(Serializer.CUSTOM).serialize(value, new ArangoSerializer.Options().serializeNullValues(true))); + return request; + } + + protected ResponseDeserializer updateVertexResponseDeserializer(final T value) { + return response -> { + final VPackSlice body = response.getBody().get(VERTEX); + final VertexUpdateEntity doc = util().deserialize(body, VertexUpdateEntity.class); + final Map values = new HashMap<>(); + values.put(DocumentField.Type.REV, doc.getRev()); + executor.documentCache().setValues(value, values); + return doc; + }; + } + + protected Request deleteVertexRequest(final String key, final VertexDeleteOptions options) { + final Request request = request(graph.db().name(), RequestType.DELETE, PATH_API_GHARIAL, graph.name(), VERTEX, + DocumentUtil.createDocumentHandle(name, key)); + final VertexDeleteOptions params = (options != null ? options : new VertexDeleteOptions()); request.putHeaderParam(TRANSACTION_ID, params.getStreamTransactionId()); - request.putHeaderParam(ArangoRequestParam.IF_NONE_MATCH, params.getIfNoneMatch()); - request.putHeaderParam(ArangoRequestParam.IF_MATCH, params.getIfMatch()); - if (params.getAllowDirtyRead() == Boolean.TRUE) { - RequestUtils.allowDirtyRead(request); - } - return request; - } - - protected ResponseDeserializer getVertexResponseDeserializer(final Class type) { - return response -> util(Serializer.CUSTOM).deserialize(response.getBody().get(VERTEX), type); - } - - protected Request replaceVertexRequest(final String key, final T value, final VertexReplaceOptions options) { - final Request request = request(graph.db().name(), RequestType.PUT, PATH_API_GHARIAL, graph.name(), VERTEX, - DocumentUtil.createDocumentHandle(name, key)); - final VertexReplaceOptions params = (options != null ? options : new VertexReplaceOptions()); - request.putHeaderParam(TRANSACTION_ID, params.getStreamTransactionId()); - request.putQueryParam(ArangoRequestParam.WAIT_FOR_SYNC, params.getWaitForSync()); - request.putHeaderParam(ArangoRequestParam.IF_MATCH, params.getIfMatch()); - request.setBody(util(Serializer.CUSTOM).serialize(value)); - return request; - } - - protected ResponseDeserializer replaceVertexResponseDeserializer(final T value) { - return response -> { - final VPackSlice body = response.getBody().get(VERTEX); - final VertexUpdateEntity doc = util().deserialize(body, VertexUpdateEntity.class); - final Map values = new HashMap<>(); - values.put(DocumentField.Type.REV, doc.getRev()); - executor.documentCache().setValues(value, values); - return doc; - }; - } - - protected Request updateVertexRequest(final String key, final T value, final VertexUpdateOptions options) { - final Request request; - request = request(graph.db().name(), RequestType.PATCH, PATH_API_GHARIAL, graph.name(), VERTEX, - DocumentUtil.createDocumentHandle(name, key)); - final VertexUpdateOptions params = (options != null ? options : new VertexUpdateOptions()); - request.putHeaderParam(TRANSACTION_ID, params.getStreamTransactionId()); - request.putQueryParam(ArangoRequestParam.KEEP_NULL, params.getKeepNull()); - request.putQueryParam(ArangoRequestParam.WAIT_FOR_SYNC, params.getWaitForSync()); - request.putHeaderParam(ArangoRequestParam.IF_MATCH, params.getIfMatch()); - request.setBody( - util(Serializer.CUSTOM).serialize(value, new ArangoSerializer.Options().serializeNullValues(true))); - return request; - } - - protected ResponseDeserializer updateVertexResponseDeserializer(final T value) { - return response -> { - final VPackSlice body = response.getBody().get(VERTEX); - final VertexUpdateEntity doc = util().deserialize(body, VertexUpdateEntity.class); - final Map values = new HashMap<>(); - values.put(DocumentField.Type.REV, doc.getRev()); - executor.documentCache().setValues(value, values); - return doc; - }; - } - - protected Request deleteVertexRequest(final String key, final VertexDeleteOptions options) { - final Request request = request(graph.db().name(), RequestType.DELETE, PATH_API_GHARIAL, graph.name(), VERTEX, - DocumentUtil.createDocumentHandle(name, key)); - final VertexDeleteOptions params = (options != null ? options : new VertexDeleteOptions()); - request.putHeaderParam(TRANSACTION_ID, params.getStreamTransactionId()); - request.putQueryParam(ArangoRequestParam.WAIT_FOR_SYNC, params.getWaitForSync()); - request.putHeaderParam(ArangoRequestParam.IF_MATCH, params.getIfMatch()); - return request; - } + request.putQueryParam(ArangoRequestParam.WAIT_FOR_SYNC, params.getWaitForSync()); + request.putHeaderParam(ArangoRequestParam.IF_MATCH, params.getIfMatch()); + return request; + } } diff --git a/src/main/java/com/arangodb/internal/InternalArangoView.java b/src/main/java/com/arangodb/internal/InternalArangoView.java index a30671e62..0c1e19ed3 100644 --- a/src/main/java/com/arangodb/internal/InternalArangoView.java +++ b/src/main/java/com/arangodb/internal/InternalArangoView.java @@ -28,43 +28,42 @@ /** * @author Mark Vollmary * @author Michele Rastelli - * */ public abstract class InternalArangoView, D extends InternalArangoDatabase, E extends ArangoExecutor> - extends ArangoExecuteable { + extends ArangoExecuteable { - protected static final String PATH_API_VIEW = "/_api/view"; - protected static final String PATH_API_ANALYZER = "/_api/analyzer"; + protected static final String PATH_API_VIEW = "/_api/view"; + protected static final String PATH_API_ANALYZER = "/_api/analyzer"; - protected final D db; - protected volatile String name; + protected final D db; + protected volatile String name; - protected InternalArangoView(final D db, final String name) { - super(db.executor, db.util, db.context); - this.db = db; - this.name = name; - } + protected InternalArangoView(final D db, final String name) { + super(db.executor, db.util, db.context); + this.db = db; + this.name = name; + } - public D db() { - return db; - } + public D db() { + return db; + } - public String name() { - return name; - } + public String name() { + return name; + } - protected Request dropRequest() { - return request(db.name(), RequestType.DELETE, PATH_API_VIEW, name); - } + protected Request dropRequest() { + return request(db.name(), RequestType.DELETE, PATH_API_VIEW, name); + } - protected Request renameRequest(final String newName) { - final Request request = request(db.name(), RequestType.PUT, PATH_API_VIEW, name, "rename"); - request.setBody(util().serialize(OptionsBuilder.build(new ViewRenameOptions(), newName))); - return request; - } + protected Request renameRequest(final String newName) { + final Request request = request(db.name(), RequestType.PUT, PATH_API_VIEW, name, "rename"); + request.setBody(util().serialize(OptionsBuilder.build(new ViewRenameOptions(), newName))); + return request; + } - protected Request getInfoRequest() { - return request(db.name(), RequestType.GET, PATH_API_VIEW, name); - } + protected Request getInfoRequest() { + return request(db.name(), RequestType.GET, PATH_API_VIEW, name); + } } diff --git a/src/main/java/com/arangodb/internal/cursor/AbstractArangoIterable.java b/src/main/java/com/arangodb/internal/cursor/AbstractArangoIterable.java index 36f89b036..e0c0c0565 100644 --- a/src/main/java/com/arangodb/internal/cursor/AbstractArangoIterable.java +++ b/src/main/java/com/arangodb/internal/cursor/AbstractArangoIterable.java @@ -30,77 +30,76 @@ /** * @author Mark Vollmary - * */ public abstract class AbstractArangoIterable implements ArangoIterable { - @Override - public ArangoIterable map(final Function mapper) { - return new ArangoMappingIterable<>(this, mapper); - } + @Override + public ArangoIterable map(final Function mapper) { + return new ArangoMappingIterable<>(this, mapper); + } - @Override - public ArangoIterable filter(final Predicate predicate) { - return new ArangoFilterIterable<>(this, predicate); - } + @Override + public ArangoIterable filter(final Predicate predicate) { + return new ArangoFilterIterable<>(this, predicate); + } - @Override - public T first() { - final ArangoIterator iterator = iterator(); - return iterator.hasNext() ? iterator.next() : null; - } + @Override + public T first() { + final ArangoIterator iterator = iterator(); + return iterator.hasNext() ? iterator.next() : null; + } - @Override - public long count() { - long count = 0L; - for (final Iterator iterator = iterator(); iterator.hasNext(); iterator.next()) { - count++; - } - return count; - } + @Override + public long count() { + long count = 0L; + for (final Iterator iterator = iterator(); iterator.hasNext(); iterator.next()) { + count++; + } + return count; + } - @Override - public boolean anyMatch(final Predicate predicate) { - boolean match = false; - for (final T t : this) { - if (predicate.test(t)) { - match = true; - break; - } - } - return match; - } + @Override + public boolean anyMatch(final Predicate predicate) { + boolean match = false; + for (final T t : this) { + if (predicate.test(t)) { + match = true; + break; + } + } + return match; + } - @Override - public boolean allMatch(final Predicate predicate) { - boolean match = false; - for (final T t : this) { - match = predicate.test(t); - if (!match) { - break; - } - } - return match; - } + @Override + public boolean allMatch(final Predicate predicate) { + boolean match = false; + for (final T t : this) { + match = predicate.test(t); + if (!match) { + break; + } + } + return match; + } - @Override - public boolean noneMatch(final Predicate predicate) { - boolean match = false; - for (final T t : this) { - match = !predicate.test(t); - if (!match) { - break; - } - } - return match; - } + @Override + public boolean noneMatch(final Predicate predicate) { + boolean match = false; + for (final T t : this) { + match = !predicate.test(t); + if (!match) { + break; + } + } + return match; + } - @Override - public > R collectInto(final R target) { - for (final T t : this) { - target.add(t); - } - return target; - } + @Override + public > R collectInto(final R target) { + for (final T t : this) { + target.add(t); + } + return target; + } } diff --git a/src/main/java/com/arangodb/internal/cursor/ArangoCursorImpl.java b/src/main/java/com/arangodb/internal/cursor/ArangoCursorImpl.java index aa95e642b..228989657 100644 --- a/src/main/java/com/arangodb/internal/cursor/ArangoCursorImpl.java +++ b/src/main/java/com/arangodb/internal/cursor/ArangoCursorImpl.java @@ -36,106 +36,105 @@ /** * @author Mark Vollmary - * */ public class ArangoCursorImpl extends AbstractArangoIterable implements ArangoCursor { - private final Class type; - protected final ArangoCursorIterator iterator; - private final String id; - private final ArangoCursorExecute execute; - - public ArangoCursorImpl(final InternalArangoDatabase db, final ArangoCursorExecute execute, - final Class type, final CursorEntity result) { - super(); - this.execute = execute; - this.type = type; - iterator = createIterator(this, db, execute, result); - id = result.getId(); - } - - protected ArangoCursorIterator createIterator( - final ArangoCursor cursor, - final InternalArangoDatabase db, - final ArangoCursorExecute execute, - final CursorEntity result) { - return new ArangoCursorIterator<>(cursor, execute, db, result); - } - - @Override - public String getId() { - return id; - } - - @Override - public Class getType() { - return type; - } - - @Override - public Integer getCount() { - return iterator.getResult().getCount(); - } - - @Override - public Stats getStats() { - final Extras extra = iterator.getResult().getExtra(); - return extra != null ? extra.getStats() : null; - } - - @Override - public Collection getWarnings() { - final Extras extra = iterator.getResult().getExtra(); - return extra != null ? extra.getWarnings() : null; - } - - @Override - public boolean isCached() { - final Boolean cached = iterator.getResult().getCached(); - return Boolean.TRUE == cached; - } - - @Override - public void close() { - if (id != null && hasNext()) { - execute.close(id, iterator.getResult().getMeta()); - } - } - - @Override - public boolean hasNext() { - return iterator.hasNext(); - } - - @Override - public T next() { - return iterator.next(); - } - - @Override - public List asListRemaining() { - final List remaining = new ArrayList<>(); - while (hasNext()) { - remaining.add(next()); - } - return remaining; - } - - @Override - public void remove() { - throw new UnsupportedOperationException(); - } - - @Override - public ArangoIterator iterator() { - return iterator; - } - - @Override - public void foreach(final Consumer action) { - while (hasNext()) { - action.accept(next()); - } - } + private final Class type; + protected final ArangoCursorIterator iterator; + private final String id; + private final ArangoCursorExecute execute; + + public ArangoCursorImpl(final InternalArangoDatabase db, final ArangoCursorExecute execute, + final Class type, final CursorEntity result) { + super(); + this.execute = execute; + this.type = type; + iterator = createIterator(this, db, execute, result); + id = result.getId(); + } + + protected ArangoCursorIterator createIterator( + final ArangoCursor cursor, + final InternalArangoDatabase db, + final ArangoCursorExecute execute, + final CursorEntity result) { + return new ArangoCursorIterator<>(cursor, execute, db, result); + } + + @Override + public String getId() { + return id; + } + + @Override + public Class getType() { + return type; + } + + @Override + public Integer getCount() { + return iterator.getResult().getCount(); + } + + @Override + public Stats getStats() { + final Extras extra = iterator.getResult().getExtra(); + return extra != null ? extra.getStats() : null; + } + + @Override + public Collection getWarnings() { + final Extras extra = iterator.getResult().getExtra(); + return extra != null ? extra.getWarnings() : null; + } + + @Override + public boolean isCached() { + final Boolean cached = iterator.getResult().getCached(); + return Boolean.TRUE == cached; + } + + @Override + public void close() { + if (id != null && hasNext()) { + execute.close(id, iterator.getResult().getMeta()); + } + } + + @Override + public boolean hasNext() { + return iterator.hasNext(); + } + + @Override + public T next() { + return iterator.next(); + } + + @Override + public List asListRemaining() { + final List remaining = new ArrayList<>(); + while (hasNext()) { + remaining.add(next()); + } + return remaining; + } + + @Override + public void remove() { + throw new UnsupportedOperationException(); + } + + @Override + public ArangoIterator iterator() { + return iterator; + } + + @Override + public void foreach(final Consumer action) { + while (hasNext()) { + action.accept(next()); + } + } } diff --git a/src/main/java/com/arangodb/internal/cursor/ArangoCursorIterator.java b/src/main/java/com/arangodb/internal/cursor/ArangoCursorIterator.java index 1ffeb03b4..52a61595e 100644 --- a/src/main/java/com/arangodb/internal/cursor/ArangoCursorIterator.java +++ b/src/main/java/com/arangodb/internal/cursor/ArangoCursorIterator.java @@ -20,8 +20,6 @@ package com.arangodb.internal.cursor; -import java.util.NoSuchElementException; - import com.arangodb.ArangoCursor; import com.arangodb.ArangoIterator; import com.arangodb.entity.CursorEntity; @@ -30,58 +28,59 @@ import com.arangodb.internal.util.ArangoSerializationFactory.Serializer; import com.arangodb.velocypack.VPackSlice; +import java.util.NoSuchElementException; + /** - * @author Mark Vollmary * @param - * + * @author Mark Vollmary */ public class ArangoCursorIterator implements ArangoIterator { - private CursorEntity result; - private int pos; + private CursorEntity result; + private int pos; - private final ArangoCursor cursor; - private final InternalArangoDatabase db; - private final ArangoCursorExecute execute; + private final ArangoCursor cursor; + private final InternalArangoDatabase db; + private final ArangoCursorExecute execute; - protected ArangoCursorIterator(final ArangoCursor cursor, final ArangoCursorExecute execute, - final InternalArangoDatabase db, final CursorEntity result) { - super(); - this.cursor = cursor; - this.execute = execute; - this.db = db; - this.result = result; - pos = 0; - } + protected ArangoCursorIterator(final ArangoCursor cursor, final ArangoCursorExecute execute, + final InternalArangoDatabase db, final CursorEntity result) { + super(); + this.cursor = cursor; + this.execute = execute; + this.db = db; + this.result = result; + pos = 0; + } - public CursorEntity getResult() { - return result; - } + public CursorEntity getResult() { + return result; + } - @Override - public boolean hasNext() { - return pos < result.getResult().size() || result.getHasMore(); - } + @Override + public boolean hasNext() { + return pos < result.getResult().size() || result.getHasMore(); + } - @Override - public T next() { - if (pos >= result.getResult().size() && result.getHasMore()) { - result = execute.next(cursor.getId(), result.getMeta()); - pos = 0; - } - if (!hasNext()) { - throw new NoSuchElementException(); - } - return deserialize(result.getResult().get(pos++), cursor.getType()); - } + @Override + public T next() { + if (pos >= result.getResult().size() && result.getHasMore()) { + result = execute.next(cursor.getId(), result.getMeta()); + pos = 0; + } + if (!hasNext()) { + throw new NoSuchElementException(); + } + return deserialize(result.getResult().get(pos++), cursor.getType()); + } - protected R deserialize(final VPackSlice result, final Class type) { - return db.util(Serializer.CUSTOM).deserialize(result, type); - } + protected R deserialize(final VPackSlice result, final Class type) { + return db.util(Serializer.CUSTOM).deserialize(result, type); + } - @Override - public void remove() { - throw new UnsupportedOperationException(); - } + @Override + public void remove() { + throw new UnsupportedOperationException(); + } } diff --git a/src/main/java/com/arangodb/internal/cursor/ArangoFilterIterable.java b/src/main/java/com/arangodb/internal/cursor/ArangoFilterIterable.java index c58be0e4e..9d26affe7 100644 --- a/src/main/java/com/arangodb/internal/cursor/ArangoFilterIterable.java +++ b/src/main/java/com/arangodb/internal/cursor/ArangoFilterIterable.java @@ -27,31 +27,30 @@ /** * @author Mark Vollmary - * */ public class ArangoFilterIterable extends AbstractArangoIterable implements ArangoIterable { - private final ArangoIterable iterable; - private final Predicate predicate; + private final ArangoIterable iterable; + private final Predicate predicate; - protected ArangoFilterIterable(final ArangoIterable iterable, final Predicate predicate) { - super(); - this.iterable = iterable; - this.predicate = predicate; - } + protected ArangoFilterIterable(final ArangoIterable iterable, final Predicate predicate) { + super(); + this.iterable = iterable; + this.predicate = predicate; + } - @Override - public ArangoIterator iterator() { + @Override + public ArangoIterator iterator() { return new ArangoFilterIterator<>(iterable.iterator(), predicate); - } - - @Override - public void foreach(final Consumer action) { - for (final T t : iterable) { - if (predicate.test(t)) { - action.accept(t); - } - } - } + } + + @Override + public void foreach(final Consumer action) { + for (final T t : iterable) { + if (predicate.test(t)) { + action.accept(t); + } + } + } } diff --git a/src/main/java/com/arangodb/internal/cursor/ArangoFilterIterator.java b/src/main/java/com/arangodb/internal/cursor/ArangoFilterIterator.java index 78f947f45..7c65f9d22 100644 --- a/src/main/java/com/arangodb/internal/cursor/ArangoFilterIterator.java +++ b/src/main/java/com/arangodb/internal/cursor/ArangoFilterIterator.java @@ -20,55 +20,54 @@ package com.arangodb.internal.cursor; -import java.util.NoSuchElementException; - import com.arangodb.ArangoIterator; import com.arangodb.Predicate; +import java.util.NoSuchElementException; + /** * @author Mark Vollmary - * */ public class ArangoFilterIterator implements ArangoIterator { - private final ArangoIterator iterator; - private final Predicate predicate; - private T next; + private final ArangoIterator iterator; + private final Predicate predicate; + private T next; - protected ArangoFilterIterator(final ArangoIterator iterator, final Predicate predicate) { - super(); - this.iterator = iterator; - this.predicate = predicate; - next = null; - } + protected ArangoFilterIterator(final ArangoIterator iterator, final Predicate predicate) { + super(); + this.iterator = iterator; + this.predicate = predicate; + next = null; + } - @Override - public boolean hasNext() { - if (next != null) { - return true; - } - while (iterator.hasNext()) { - next = iterator.next(); - if (predicate.test(next)) { - return true; - } - } - next = null; - return false; - } + @Override + public boolean hasNext() { + if (next != null) { + return true; + } + while (iterator.hasNext()) { + next = iterator.next(); + if (predicate.test(next)) { + return true; + } + } + next = null; + return false; + } - @Override - public T next() { - if (next == null && !hasNext()) { - throw new NoSuchElementException(); - } - final T tmp = next; - next = null; - return tmp; - } + @Override + public T next() { + if (next == null && !hasNext()) { + throw new NoSuchElementException(); + } + final T tmp = next; + next = null; + return tmp; + } - @Override - public void remove() { - throw new UnsupportedOperationException(); - } + @Override + public void remove() { + throw new UnsupportedOperationException(); + } } diff --git a/src/main/java/com/arangodb/internal/cursor/ArangoMappingIterable.java b/src/main/java/com/arangodb/internal/cursor/ArangoMappingIterable.java index eb30244b7..0b0141576 100644 --- a/src/main/java/com/arangodb/internal/cursor/ArangoMappingIterable.java +++ b/src/main/java/com/arangodb/internal/cursor/ArangoMappingIterable.java @@ -27,29 +27,28 @@ /** * @author Mark Vollmary - * */ public class ArangoMappingIterable extends AbstractArangoIterable implements ArangoIterable { - private final ArangoIterable iterable; - private final Function mapper; + private final ArangoIterable iterable; + private final Function mapper; - protected ArangoMappingIterable(final ArangoIterable iterable, final Function mapper) { - super(); - this.iterable = iterable; - this.mapper = mapper; - } + protected ArangoMappingIterable(final ArangoIterable iterable, final Function mapper) { + super(); + this.iterable = iterable; + this.mapper = mapper; + } - @Override - public ArangoIterator iterator() { + @Override + public ArangoIterator iterator() { return new ArangoMappingIterator<>(iterable.iterator(), mapper); - } - - @Override - public void foreach(final Consumer action) { - for (final R t : iterable) { - action.accept(mapper.apply(t)); - } - } + } + + @Override + public void foreach(final Consumer action) { + for (final R t : iterable) { + action.accept(mapper.apply(t)); + } + } } diff --git a/src/main/java/com/arangodb/internal/cursor/ArangoMappingIterator.java b/src/main/java/com/arangodb/internal/cursor/ArangoMappingIterator.java index 5575068e0..e3594a1cc 100644 --- a/src/main/java/com/arangodb/internal/cursor/ArangoMappingIterator.java +++ b/src/main/java/com/arangodb/internal/cursor/ArangoMappingIterator.java @@ -25,32 +25,31 @@ /** * @author Mark Vollmary - * */ public class ArangoMappingIterator implements ArangoIterator { - private final ArangoIterator iterator; - private final Function mapper; - - public ArangoMappingIterator(final ArangoIterator iterator, final Function mapper) { - super(); - this.iterator = iterator; - this.mapper = mapper; - } - - @Override - public boolean hasNext() { - return iterator.hasNext(); - } - - @Override - public T next() { - return mapper.apply(iterator.next()); - } - - @Override - public void remove() { - throw new UnsupportedOperationException(); - } + private final ArangoIterator iterator; + private final Function mapper; + + public ArangoMappingIterator(final ArangoIterator iterator, final Function mapper) { + super(); + this.iterator = iterator; + this.mapper = mapper; + } + + @Override + public boolean hasNext() { + return iterator.hasNext(); + } + + @Override + public T next() { + return mapper.apply(iterator.next()); + } + + @Override + public void remove() { + throw new UnsupportedOperationException(); + } } diff --git a/src/main/java/com/arangodb/internal/http/HttpCommunication.java b/src/main/java/com/arangodb/internal/http/HttpCommunication.java index 5416333b7..7bf942d3b 100644 --- a/src/main/java/com/arangodb/internal/http/HttpCommunication.java +++ b/src/main/java/com/arangodb/internal/http/HttpCommunication.java @@ -36,79 +36,78 @@ /** * @author Mark Vollmary - * */ public class HttpCommunication implements Closeable { - private static final Logger LOGGER = LoggerFactory.getLogger(HttpCommunication.class); + private static final Logger LOGGER = LoggerFactory.getLogger(HttpCommunication.class); - public static class Builder { + public static class Builder { - private final HostHandler hostHandler; + private final HostHandler hostHandler; - public Builder(final HostHandler hostHandler) { - super(); - this.hostHandler = hostHandler; - } + public Builder(final HostHandler hostHandler) { + super(); + this.hostHandler = hostHandler; + } - public Builder(final Builder builder) { - this(builder.hostHandler); - } + public Builder(final Builder builder) { + this(builder.hostHandler); + } - public HttpCommunication build(final ArangoSerialization util) { - return new HttpCommunication(hostHandler); - } - } + public HttpCommunication build(final ArangoSerialization util) { + return new HttpCommunication(hostHandler); + } + } - private final HostHandler hostHandler; + private final HostHandler hostHandler; - private HttpCommunication(final HostHandler hostHandler) { - super(); - this.hostHandler = hostHandler; - } + private HttpCommunication(final HostHandler hostHandler) { + super(); + this.hostHandler = hostHandler; + } - @Override - public void close() throws IOException { - hostHandler.close(); - } + @Override + public void close() throws IOException { + hostHandler.close(); + } - public Response execute(final Request request, final HostHandle hostHandle) throws ArangoDBException, IOException { - final AccessType accessType = RequestUtils.determineAccessType(request); - Host host = hostHandler.get(hostHandle, accessType); - try { - while (true) { - try { - final HttpConnection connection = (HttpConnection) host.connection(); - final Response response = connection.execute(request); - hostHandler.success(); - hostHandler.confirm(); - return response; - } catch (final SocketException se) { - hostHandler.fail(); - if (hostHandle != null && hostHandle.getHost() != null) { - hostHandle.setHost(null); - } - final Host failedHost = host; - host = hostHandler.get(hostHandle, accessType); - if (host != null) { - LOGGER.warn(String.format("Could not connect to %s. Try connecting to %s", - failedHost.getDescription(), host.getDescription())); - } else { - throw se; - } - } - } - } catch (final ArangoDBException e) { - if (e instanceof ArangoDBRedirectException) { + public Response execute(final Request request, final HostHandle hostHandle) throws ArangoDBException, IOException { + final AccessType accessType = RequestUtils.determineAccessType(request); + Host host = hostHandler.get(hostHandle, accessType); + try { + while (true) { + try { + final HttpConnection connection = (HttpConnection) host.connection(); + final Response response = connection.execute(request); + hostHandler.success(); + hostHandler.confirm(); + return response; + } catch (final SocketException se) { + hostHandler.fail(); + if (hostHandle != null && hostHandle.getHost() != null) { + hostHandle.setHost(null); + } + final Host failedHost = host; + host = hostHandler.get(hostHandle, accessType); + if (host != null) { + LOGGER.warn(String.format("Could not connect to %s. Try connecting to %s", + failedHost.getDescription(), host.getDescription())); + } else { + throw se; + } + } + } + } catch (final ArangoDBException e) { + if (e instanceof ArangoDBRedirectException) { final String location = ((ArangoDBRedirectException) e).getLocation(); - final HostDescription redirectHost = HostUtils.createFromLocation(location); - hostHandler.closeCurrentOnError(); - hostHandler.fail(); - return execute(request, new HostHandle().setHost(redirectHost)); - } else { - throw e; - } - } - } + final HostDescription redirectHost = HostUtils.createFromLocation(location); + hostHandler.closeCurrentOnError(); + hostHandler.fail(); + return execute(request, new HostHandle().setHost(redirectHost)); + } else { + throw e; + } + } + } } diff --git a/src/main/java/com/arangodb/internal/http/HttpConnection.java b/src/main/java/com/arangodb/internal/http/HttpConnection.java index c93625479..cbbb25d06 100644 --- a/src/main/java/com/arangodb/internal/http/HttpConnection.java +++ b/src/main/java/com/arangodb/internal/http/HttpConnection.java @@ -70,297 +70,296 @@ /** * @author Mark Vollmary - * */ public class HttpConnection implements Connection { - private static final Logger LOGGER = LoggerFactory.getLogger(HttpCommunication.class); - private static final ContentType CONTENT_TYPE_APPLICATION_JSON_UTF8 = ContentType.create("application/json", - "utf-8"); - private static final ContentType CONTENT_TYPE_VPACK = ContentType.create("application/x-velocypack"); - - public static class Builder { - private String user; - private String password; - private ArangoSerialization util; - private Boolean useSsl; - private String httpCookieSpec; - private Protocol contentType; - private HostDescription host; - private Long ttl; - private SSLContext sslContext; - private Integer timeout; - - public Builder user(final String user) { - this.user = user; - return this; - } - - public Builder password(final String password) { - this.password = password; - return this; - } - - public Builder serializationUtil(final ArangoSerialization util) { - this.util = util; - return this; - } - - public Builder useSsl(final Boolean useSsl) { - this.useSsl = useSsl; - return this; - } - - public Builder httpCookieSpec(String httpCookieSpec) { - this.httpCookieSpec = httpCookieSpec; - return this; - } - - public Builder contentType(final Protocol contentType) { - this.contentType = contentType; - return this; - } - - public Builder host(final HostDescription host) { - this.host = host; - return this; - } - - public Builder ttl(final Long ttl) { - this.ttl = ttl; - return this; - } - - public Builder sslContext(final SSLContext sslContext) { - this.sslContext = sslContext; - return this; - } - - public Builder timeout(final Integer timeout) { - this.timeout = timeout; - return this; - } - - public HttpConnection build() { - return new HttpConnection(host, timeout, user, password, useSsl, sslContext, util, contentType, ttl, httpCookieSpec); - } - } - - private final PoolingHttpClientConnectionManager cm; - private final CloseableHttpClient client; - private final String user; - private final String password; - private final ArangoSerialization util; - private final Boolean useSsl; - private final Protocol contentType; - private final HostDescription host; - - private HttpConnection(final HostDescription host, final Integer timeout, final String user, final String password, - final Boolean useSsl, final SSLContext sslContext, final ArangoSerialization util, final Protocol contentType, - final Long ttl, final String httpCookieSpec) { - super(); - this.host = host; - this.user = user; - this.password = password; - this.useSsl = useSsl; - this.util = util; - this.contentType = contentType; - final RegistryBuilder registryBuilder = RegistryBuilder - .create(); - if (Boolean.TRUE == useSsl) { - if (sslContext != null) { - registryBuilder.register("https", new SSLConnectionSocketFactory(sslContext)); - } else { - registryBuilder.register("https", new SSLConnectionSocketFactory(SSLContexts.createSystemDefault())); - } - } else { - registryBuilder.register("http", new PlainConnectionSocketFactory()); - } - cm = new PoolingHttpClientConnectionManager(registryBuilder.build()); - cm.setDefaultMaxPerRoute(1); - cm.setMaxTotal(1); - final RequestConfig.Builder requestConfig = RequestConfig.custom(); - if (timeout != null && timeout >= 0) { - requestConfig.setConnectTimeout(timeout); - requestConfig.setConnectionRequestTimeout(timeout); - requestConfig.setSocketTimeout(timeout); - } - - if (httpCookieSpec != null && httpCookieSpec.length() > 1) { - requestConfig.setCookieSpec(httpCookieSpec); - } - - final ConnectionKeepAliveStrategy keepAliveStrategy = (response, context) -> HttpConnection.this.getKeepAliveDuration(response); - final HttpClientBuilder builder = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig.build()) - .setConnectionManager(cm).setKeepAliveStrategy(keepAliveStrategy) - .setRetryHandler(new DefaultHttpRequestRetryHandler()); - if (ttl != null) { - builder.setConnectionTimeToLive(ttl, TimeUnit.MILLISECONDS); - } - client = builder.build(); - } - - private long getKeepAliveDuration(final HttpResponse response) { - final HeaderElementIterator it = new BasicHeaderElementIterator(response.headerIterator(HTTP.CONN_KEEP_ALIVE)); - while (it.hasNext()) { - final HeaderElement he = it.nextElement(); - final String param = he.getName(); - final String value = he.getValue(); - if (value != null && "timeout".equalsIgnoreCase(param)) { - try { - return Long.parseLong(value) * 1000L; - } catch (final NumberFormatException ignore) { - } - } - } - return 30L * 1000L; - } - - @Override - public void close() throws IOException { - cm.shutdown(); - client.close(); - } - - private static String buildUrl(final String baseUrl, final Request request) { - final StringBuilder sb = new StringBuilder().append(baseUrl); - final String database = request.getDatabase(); - if (database != null && !database.isEmpty()) { - sb.append("/_db/").append(database); - } - sb.append(request.getRequest()); - if (!request.getQueryParam().isEmpty()) { - if (request.getRequest().contains("?")) { - sb.append("&"); - } else { - sb.append("?"); - } - final String paramString = URLEncodedUtils.format(toList(request.getQueryParam()), "utf-8"); - sb.append(paramString); - } - return sb.toString(); - } - - private HttpRequestBase buildHttpRequestBase(final Request request, final String url) { - final HttpRequestBase httpRequest; - switch (request.getRequestType()) { - case POST: - httpRequest = requestWithBody(new HttpPost(url), request); - break; - case PUT: - httpRequest = requestWithBody(new HttpPut(url), request); - break; - case PATCH: - httpRequest = requestWithBody(new HttpPatch(url), request); - break; - case DELETE: - httpRequest = requestWithBody(new HttpDeleteWithBody(url), request); - break; - case HEAD: - httpRequest = new HttpHead(url); - break; - case GET: - default: - httpRequest = new HttpGet(url); - break; - } - return httpRequest; - } - - private HttpRequestBase requestWithBody(final HttpEntityEnclosingRequestBase httpRequest, final Request request) { - final VPackSlice body = request.getBody(); - if (body != null) { - if (contentType == Protocol.HTTP_VPACK) { - httpRequest.setEntity(new ByteArrayEntity( - Arrays.copyOfRange(body.getBuffer(), body.getStart(), body.getStart() + body.getByteSize()), - CONTENT_TYPE_VPACK)); - } else { - httpRequest.setEntity(new StringEntity(body.toString(), CONTENT_TYPE_APPLICATION_JSON_UTF8)); - } - } - return httpRequest; - } - - private String buildBaseUrl(final HostDescription host) { - return (Boolean.TRUE == useSsl ? "https://" : "http://") + host.getHost() + ":" + host.getPort(); - } - - private static List toList(final Map parameters) { - final ArrayList paramList = new ArrayList<>(parameters.size()); - for (final Entry param : parameters.entrySet()) { - if (param.getValue() != null) { - paramList.add(new BasicNameValuePair(param.getKey(), param.getValue())); - } - } - return paramList; - } - - public Response execute(final Request request) throws ArangoDBException, IOException { - final String url = buildUrl(buildBaseUrl(host), request); - final HttpRequestBase httpRequest = buildHttpRequestBase(request, url); - httpRequest.setHeader("User-Agent", "Mozilla/5.0 (compatible; ArangoDB-JavaDriver/1.1; +http://mt.orz.at/)"); - if (contentType == Protocol.HTTP_VPACK) { - httpRequest.setHeader("Accept", "application/x-velocypack"); - } - addHeader(request, httpRequest); - final Credentials credentials = addCredentials(httpRequest); - if (LOGGER.isDebugEnabled()) { - CURLLogger.log(url, request, credentials, util); - } - Response response; - response = buildResponse(client.execute(httpRequest)); - checkError(response); - return response; - } - - private static void addHeader(final Request request, final HttpRequestBase httpRequest) { - for (final Entry header : request.getHeaderParam().entrySet()) { - httpRequest.addHeader(header.getKey(), header.getValue()); - } - } - - public Credentials addCredentials(final HttpRequestBase httpRequest) { - Credentials credentials = null; - if (user != null) { - credentials = new UsernamePasswordCredentials(user, password != null ? password : ""); - try { - httpRequest.addHeader(new BasicScheme().authenticate(credentials, httpRequest, null)); - } catch (final AuthenticationException e) { - throw new ArangoDBException(e); - } - } - return credentials; - } - - public Response buildResponse(final CloseableHttpResponse httpResponse) - throws UnsupportedOperationException, IOException { - final Response response = new Response(); - response.setResponseCode(httpResponse.getStatusLine().getStatusCode()); - final HttpEntity entity = httpResponse.getEntity(); - if (entity != null && entity.getContent() != null) { - if (contentType == Protocol.HTTP_VPACK) { - final byte[] content = IOUtils.toByteArray(entity.getContent()); - if (content.length > 0) { - response.setBody(new VPackSlice(content)); - } - } else { - final String content = IOUtils.toString(entity.getContent()); - if (!content.isEmpty()) { - response.setBody( - util.serialize(content, new Options().stringAsJson(true).serializeNullValues(true))); - } - } - } - final Header[] headers = httpResponse.getAllHeaders(); - final Map meta = response.getMeta(); - for (final Header header : headers) { - meta.put(header.getName(), header.getValue()); - } - return response; - } - - protected void checkError(final Response response) throws ArangoDBException { - ResponseUtils.checkError(util, response); - } + private static final Logger LOGGER = LoggerFactory.getLogger(HttpCommunication.class); + private static final ContentType CONTENT_TYPE_APPLICATION_JSON_UTF8 = ContentType.create("application/json", + "utf-8"); + private static final ContentType CONTENT_TYPE_VPACK = ContentType.create("application/x-velocypack"); + + public static class Builder { + private String user; + private String password; + private ArangoSerialization util; + private Boolean useSsl; + private String httpCookieSpec; + private Protocol contentType; + private HostDescription host; + private Long ttl; + private SSLContext sslContext; + private Integer timeout; + + public Builder user(final String user) { + this.user = user; + return this; + } + + public Builder password(final String password) { + this.password = password; + return this; + } + + public Builder serializationUtil(final ArangoSerialization util) { + this.util = util; + return this; + } + + public Builder useSsl(final Boolean useSsl) { + this.useSsl = useSsl; + return this; + } + + public Builder httpCookieSpec(String httpCookieSpec) { + this.httpCookieSpec = httpCookieSpec; + return this; + } + + public Builder contentType(final Protocol contentType) { + this.contentType = contentType; + return this; + } + + public Builder host(final HostDescription host) { + this.host = host; + return this; + } + + public Builder ttl(final Long ttl) { + this.ttl = ttl; + return this; + } + + public Builder sslContext(final SSLContext sslContext) { + this.sslContext = sslContext; + return this; + } + + public Builder timeout(final Integer timeout) { + this.timeout = timeout; + return this; + } + + public HttpConnection build() { + return new HttpConnection(host, timeout, user, password, useSsl, sslContext, util, contentType, ttl, httpCookieSpec); + } + } + + private final PoolingHttpClientConnectionManager cm; + private final CloseableHttpClient client; + private final String user; + private final String password; + private final ArangoSerialization util; + private final Boolean useSsl; + private final Protocol contentType; + private final HostDescription host; + + private HttpConnection(final HostDescription host, final Integer timeout, final String user, final String password, + final Boolean useSsl, final SSLContext sslContext, final ArangoSerialization util, final Protocol contentType, + final Long ttl, final String httpCookieSpec) { + super(); + this.host = host; + this.user = user; + this.password = password; + this.useSsl = useSsl; + this.util = util; + this.contentType = contentType; + final RegistryBuilder registryBuilder = RegistryBuilder + .create(); + if (Boolean.TRUE == useSsl) { + if (sslContext != null) { + registryBuilder.register("https", new SSLConnectionSocketFactory(sslContext)); + } else { + registryBuilder.register("https", new SSLConnectionSocketFactory(SSLContexts.createSystemDefault())); + } + } else { + registryBuilder.register("http", new PlainConnectionSocketFactory()); + } + cm = new PoolingHttpClientConnectionManager(registryBuilder.build()); + cm.setDefaultMaxPerRoute(1); + cm.setMaxTotal(1); + final RequestConfig.Builder requestConfig = RequestConfig.custom(); + if (timeout != null && timeout >= 0) { + requestConfig.setConnectTimeout(timeout); + requestConfig.setConnectionRequestTimeout(timeout); + requestConfig.setSocketTimeout(timeout); + } + + if (httpCookieSpec != null && httpCookieSpec.length() > 1) { + requestConfig.setCookieSpec(httpCookieSpec); + } + + final ConnectionKeepAliveStrategy keepAliveStrategy = (response, context) -> HttpConnection.this.getKeepAliveDuration(response); + final HttpClientBuilder builder = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig.build()) + .setConnectionManager(cm).setKeepAliveStrategy(keepAliveStrategy) + .setRetryHandler(new DefaultHttpRequestRetryHandler()); + if (ttl != null) { + builder.setConnectionTimeToLive(ttl, TimeUnit.MILLISECONDS); + } + client = builder.build(); + } + + private long getKeepAliveDuration(final HttpResponse response) { + final HeaderElementIterator it = new BasicHeaderElementIterator(response.headerIterator(HTTP.CONN_KEEP_ALIVE)); + while (it.hasNext()) { + final HeaderElement he = it.nextElement(); + final String param = he.getName(); + final String value = he.getValue(); + if (value != null && "timeout".equalsIgnoreCase(param)) { + try { + return Long.parseLong(value) * 1000L; + } catch (final NumberFormatException ignore) { + } + } + } + return 30L * 1000L; + } + + @Override + public void close() throws IOException { + cm.shutdown(); + client.close(); + } + + private static String buildUrl(final String baseUrl, final Request request) { + final StringBuilder sb = new StringBuilder().append(baseUrl); + final String database = request.getDatabase(); + if (database != null && !database.isEmpty()) { + sb.append("/_db/").append(database); + } + sb.append(request.getRequest()); + if (!request.getQueryParam().isEmpty()) { + if (request.getRequest().contains("?")) { + sb.append("&"); + } else { + sb.append("?"); + } + final String paramString = URLEncodedUtils.format(toList(request.getQueryParam()), "utf-8"); + sb.append(paramString); + } + return sb.toString(); + } + + private HttpRequestBase buildHttpRequestBase(final Request request, final String url) { + final HttpRequestBase httpRequest; + switch (request.getRequestType()) { + case POST: + httpRequest = requestWithBody(new HttpPost(url), request); + break; + case PUT: + httpRequest = requestWithBody(new HttpPut(url), request); + break; + case PATCH: + httpRequest = requestWithBody(new HttpPatch(url), request); + break; + case DELETE: + httpRequest = requestWithBody(new HttpDeleteWithBody(url), request); + break; + case HEAD: + httpRequest = new HttpHead(url); + break; + case GET: + default: + httpRequest = new HttpGet(url); + break; + } + return httpRequest; + } + + private HttpRequestBase requestWithBody(final HttpEntityEnclosingRequestBase httpRequest, final Request request) { + final VPackSlice body = request.getBody(); + if (body != null) { + if (contentType == Protocol.HTTP_VPACK) { + httpRequest.setEntity(new ByteArrayEntity( + Arrays.copyOfRange(body.getBuffer(), body.getStart(), body.getStart() + body.getByteSize()), + CONTENT_TYPE_VPACK)); + } else { + httpRequest.setEntity(new StringEntity(body.toString(), CONTENT_TYPE_APPLICATION_JSON_UTF8)); + } + } + return httpRequest; + } + + private String buildBaseUrl(final HostDescription host) { + return (Boolean.TRUE == useSsl ? "https://" : "http://") + host.getHost() + ":" + host.getPort(); + } + + private static List toList(final Map parameters) { + final ArrayList paramList = new ArrayList<>(parameters.size()); + for (final Entry param : parameters.entrySet()) { + if (param.getValue() != null) { + paramList.add(new BasicNameValuePair(param.getKey(), param.getValue())); + } + } + return paramList; + } + + public Response execute(final Request request) throws ArangoDBException, IOException { + final String url = buildUrl(buildBaseUrl(host), request); + final HttpRequestBase httpRequest = buildHttpRequestBase(request, url); + httpRequest.setHeader("User-Agent", "Mozilla/5.0 (compatible; ArangoDB-JavaDriver/1.1; +http://mt.orz.at/)"); + if (contentType == Protocol.HTTP_VPACK) { + httpRequest.setHeader("Accept", "application/x-velocypack"); + } + addHeader(request, httpRequest); + final Credentials credentials = addCredentials(httpRequest); + if (LOGGER.isDebugEnabled()) { + CURLLogger.log(url, request, credentials, util); + } + Response response; + response = buildResponse(client.execute(httpRequest)); + checkError(response); + return response; + } + + private static void addHeader(final Request request, final HttpRequestBase httpRequest) { + for (final Entry header : request.getHeaderParam().entrySet()) { + httpRequest.addHeader(header.getKey(), header.getValue()); + } + } + + public Credentials addCredentials(final HttpRequestBase httpRequest) { + Credentials credentials = null; + if (user != null) { + credentials = new UsernamePasswordCredentials(user, password != null ? password : ""); + try { + httpRequest.addHeader(new BasicScheme().authenticate(credentials, httpRequest, null)); + } catch (final AuthenticationException e) { + throw new ArangoDBException(e); + } + } + return credentials; + } + + public Response buildResponse(final CloseableHttpResponse httpResponse) + throws UnsupportedOperationException, IOException { + final Response response = new Response(); + response.setResponseCode(httpResponse.getStatusLine().getStatusCode()); + final HttpEntity entity = httpResponse.getEntity(); + if (entity != null && entity.getContent() != null) { + if (contentType == Protocol.HTTP_VPACK) { + final byte[] content = IOUtils.toByteArray(entity.getContent()); + if (content.length > 0) { + response.setBody(new VPackSlice(content)); + } + } else { + final String content = IOUtils.toString(entity.getContent()); + if (!content.isEmpty()) { + response.setBody( + util.serialize(content, new Options().stringAsJson(true).serializeNullValues(true))); + } + } + } + final Header[] headers = httpResponse.getAllHeaders(); + final Map meta = response.getMeta(); + for (final Header header : headers) { + meta.put(header.getName(), header.getValue()); + } + return response; + } + + protected void checkError(final Response response) throws ArangoDBException { + ResponseUtils.checkError(util, response); + } } diff --git a/src/main/java/com/arangodb/internal/http/HttpConnectionFactory.java b/src/main/java/com/arangodb/internal/http/HttpConnectionFactory.java index 71e09446d..efd42ce23 100644 --- a/src/main/java/com/arangodb/internal/http/HttpConnectionFactory.java +++ b/src/main/java/com/arangodb/internal/http/HttpConnectionFactory.java @@ -20,34 +20,33 @@ package com.arangodb.internal.http; -import javax.net.ssl.SSLContext; - import com.arangodb.Protocol; import com.arangodb.internal.net.Connection; import com.arangodb.internal.net.ConnectionFactory; import com.arangodb.internal.net.HostDescription; import com.arangodb.util.ArangoSerialization; +import javax.net.ssl.SSLContext; + /** * @author Mark Vollmary - * */ public class HttpConnectionFactory implements ConnectionFactory { - private final HttpConnection.Builder builder; + private final HttpConnection.Builder builder; - public HttpConnectionFactory(final Integer timeout, final String user, final String password, final Boolean useSsl, - final SSLContext sslContext, final ArangoSerialization util, final Protocol protocol, - final Long connectionTtl, String httpCookieSpec) { - super(); - builder = new HttpConnection.Builder().timeout(timeout).user(user).password(password).useSsl(useSsl) - .sslContext(sslContext).serializationUtil(util).contentType(protocol).ttl(connectionTtl).httpCookieSpec(httpCookieSpec); + public HttpConnectionFactory(final Integer timeout, final String user, final String password, final Boolean useSsl, + final SSLContext sslContext, final ArangoSerialization util, final Protocol protocol, + final Long connectionTtl, String httpCookieSpec) { + super(); + builder = new HttpConnection.Builder().timeout(timeout).user(user).password(password).useSsl(useSsl) + .sslContext(sslContext).serializationUtil(util).contentType(protocol).ttl(connectionTtl).httpCookieSpec(httpCookieSpec); - } + } - @Override - public Connection create(final HostDescription host) { - return builder.host(host).build(); - } + @Override + public Connection create(final HostDescription host) { + return builder.host(host).build(); + } } diff --git a/src/main/java/com/arangodb/internal/http/HttpDeleteWithBody.java b/src/main/java/com/arangodb/internal/http/HttpDeleteWithBody.java index 483a21925..080e01974 100644 --- a/src/main/java/com/arangodb/internal/http/HttpDeleteWithBody.java +++ b/src/main/java/com/arangodb/internal/http/HttpDeleteWithBody.java @@ -20,25 +20,24 @@ package com.arangodb.internal.http; -import java.net.URI; - import org.apache.http.client.methods.HttpEntityEnclosingRequestBase; +import java.net.URI; + /** * @author Mark Vollmary - * */ public class HttpDeleteWithBody extends HttpEntityEnclosingRequestBase { - public final static String METHOD_NAME = "DELETE"; + public final static String METHOD_NAME = "DELETE"; - public HttpDeleteWithBody(final String uri) { - super(); - setURI(URI.create(uri)); - } + public HttpDeleteWithBody(final String uri) { + super(); + setURI(URI.create(uri)); + } - @Override - public String getMethod() { - return METHOD_NAME; - } + @Override + public String getMethod() { + return METHOD_NAME; + } } diff --git a/src/main/java/com/arangodb/internal/http/HttpProtocol.java b/src/main/java/com/arangodb/internal/http/HttpProtocol.java index a964d65ac..d946a5306 100644 --- a/src/main/java/com/arangodb/internal/http/HttpProtocol.java +++ b/src/main/java/com/arangodb/internal/http/HttpProtocol.java @@ -30,29 +30,28 @@ /** * @author Mark Vollmary - * */ public class HttpProtocol implements CommunicationProtocol { - private final HttpCommunication httpCommunitaction; - - public HttpProtocol(final HttpCommunication httpCommunitaction) { - super(); - this.httpCommunitaction = httpCommunitaction; - } - - @Override - public Response execute(final Request request, final HostHandle hostHandle) throws ArangoDBException { - try { - return httpCommunitaction.execute(request, hostHandle); - } catch (final IOException e) { - throw new ArangoDBException(e); - } - } - - @Override - public void close() throws IOException { - httpCommunitaction.close(); - } + private final HttpCommunication httpCommunitaction; + + public HttpProtocol(final HttpCommunication httpCommunitaction) { + super(); + this.httpCommunitaction = httpCommunitaction; + } + + @Override + public Response execute(final Request request, final HostHandle hostHandle) throws ArangoDBException { + try { + return httpCommunitaction.execute(request, hostHandle); + } catch (final IOException e) { + throw new ArangoDBException(e); + } + } + + @Override + public void close() throws IOException { + httpCommunitaction.close(); + } } diff --git a/src/main/java/com/arangodb/internal/net/AccessType.java b/src/main/java/com/arangodb/internal/net/AccessType.java index 39f302300..c228074c5 100644 --- a/src/main/java/com/arangodb/internal/net/AccessType.java +++ b/src/main/java/com/arangodb/internal/net/AccessType.java @@ -22,10 +22,9 @@ /** * @author Mark Vollmary - * */ public enum AccessType { - WRITE, READ, DIRTY_READ + WRITE, READ, DIRTY_READ } diff --git a/src/main/java/com/arangodb/internal/net/ArangoDBRedirectException.java b/src/main/java/com/arangodb/internal/net/ArangoDBRedirectException.java index a8461572c..8b7c37010 100644 --- a/src/main/java/com/arangodb/internal/net/ArangoDBRedirectException.java +++ b/src/main/java/com/arangodb/internal/net/ArangoDBRedirectException.java @@ -24,20 +24,19 @@ /** * @author Mark Vollmary - * */ public class ArangoDBRedirectException extends ArangoDBException { - private static final long serialVersionUID = -94810262465567613L; - private final String location; + private static final long serialVersionUID = -94810262465567613L; + private final String location; - public ArangoDBRedirectException(final String message, final String location) { - super(message); - this.location = location; - } + public ArangoDBRedirectException(final String message, final String location) { + super(message); + this.location = location; + } - public String getLocation() { - return location; - } + public String getLocation() { + return location; + } } diff --git a/src/main/java/com/arangodb/internal/net/CommunicationProtocol.java b/src/main/java/com/arangodb/internal/net/CommunicationProtocol.java index 10540b932..fbec7116b 100644 --- a/src/main/java/com/arangodb/internal/net/CommunicationProtocol.java +++ b/src/main/java/com/arangodb/internal/net/CommunicationProtocol.java @@ -20,18 +20,17 @@ package com.arangodb.internal.net; -import java.io.Closeable; - import com.arangodb.ArangoDBException; import com.arangodb.velocystream.Request; import com.arangodb.velocystream.Response; +import java.io.Closeable; + /** * @author Mark Vollmary - * */ public interface CommunicationProtocol extends Closeable { - Response execute(final Request request, HostHandle hostHandle) throws ArangoDBException; + Response execute(final Request request, HostHandle hostHandle) throws ArangoDBException; } diff --git a/src/main/java/com/arangodb/internal/net/Connection.java b/src/main/java/com/arangodb/internal/net/Connection.java index 404cc7780..a71a253ae 100644 --- a/src/main/java/com/arangodb/internal/net/Connection.java +++ b/src/main/java/com/arangodb/internal/net/Connection.java @@ -24,7 +24,6 @@ /** * @author Mark Vollmary - * */ public interface Connection extends Closeable { diff --git a/src/main/java/com/arangodb/internal/net/ConnectionFactory.java b/src/main/java/com/arangodb/internal/net/ConnectionFactory.java index 6caca6248..4987a40cb 100644 --- a/src/main/java/com/arangodb/internal/net/ConnectionFactory.java +++ b/src/main/java/com/arangodb/internal/net/ConnectionFactory.java @@ -22,10 +22,9 @@ /** * @author Mark Vollmary - * */ public interface ConnectionFactory { - Connection create(final HostDescription host); + Connection create(final HostDescription host); } diff --git a/src/main/java/com/arangodb/internal/net/ConnectionPool.java b/src/main/java/com/arangodb/internal/net/ConnectionPool.java index 3518ef922..38341490e 100644 --- a/src/main/java/com/arangodb/internal/net/ConnectionPool.java +++ b/src/main/java/com/arangodb/internal/net/ConnectionPool.java @@ -24,12 +24,11 @@ /** * @author Mark Vollmary - * */ public interface ConnectionPool extends Closeable { - Connection createConnection(final HostDescription host); + Connection createConnection(final HostDescription host); - Connection connection(); + Connection connection(); } diff --git a/src/main/java/com/arangodb/internal/net/ConnectionPoolImpl.java b/src/main/java/com/arangodb/internal/net/ConnectionPoolImpl.java index 6fc633022..f71ff6da7 100644 --- a/src/main/java/com/arangodb/internal/net/ConnectionPoolImpl.java +++ b/src/main/java/com/arangodb/internal/net/ConnectionPoolImpl.java @@ -49,7 +49,7 @@ public ConnectionPoolImpl(final HostDescription host, final Integer maxConnectio this.maxConnections = maxConnections; this.factory = factory; connections = new ArrayList<>(); - current = 0; + current = 0; } @Override diff --git a/src/main/java/com/arangodb/internal/net/DirtyReadHostHandler.java b/src/main/java/com/arangodb/internal/net/DirtyReadHostHandler.java index 186034417..47feda2f6 100644 --- a/src/main/java/com/arangodb/internal/net/DirtyReadHostHandler.java +++ b/src/main/java/com/arangodb/internal/net/DirtyReadHostHandler.java @@ -24,62 +24,61 @@ /** * @author Mark Vollmary - * */ public class DirtyReadHostHandler implements HostHandler { - private final HostHandler master; - private final HostHandler follower; - private AccessType currentAccessType; + private final HostHandler master; + private final HostHandler follower; + private AccessType currentAccessType; - public DirtyReadHostHandler(final HostHandler master, final HostHandler follower) { - super(); - this.master = master; - this.follower = follower; - } + public DirtyReadHostHandler(final HostHandler master, final HostHandler follower) { + super(); + this.master = master; + this.follower = follower; + } - private HostHandler determineHostHandler() { - if (currentAccessType == AccessType.DIRTY_READ) { - return follower; - } - return master; - } + private HostHandler determineHostHandler() { + if (currentAccessType == AccessType.DIRTY_READ) { + return follower; + } + return master; + } - @Override - public Host get(final HostHandle hostHandle, final AccessType accessType) { - this.currentAccessType = accessType; - return determineHostHandler().get(hostHandle, accessType); - } + @Override + public Host get(final HostHandle hostHandle, final AccessType accessType) { + this.currentAccessType = accessType; + return determineHostHandler().get(hostHandle, accessType); + } - @Override - public void success() { - determineHostHandler().success(); - } + @Override + public void success() { + determineHostHandler().success(); + } - @Override - public void fail() { - determineHostHandler().fail(); - } + @Override + public void fail() { + determineHostHandler().fail(); + } - @Override - public void reset() { - determineHostHandler().reset(); - } + @Override + public void reset() { + determineHostHandler().reset(); + } - @Override - public void confirm() { - determineHostHandler().confirm(); - } + @Override + public void confirm() { + determineHostHandler().confirm(); + } - @Override - public void close() throws IOException { - master.close(); - follower.close(); - } + @Override + public void close() throws IOException { + master.close(); + follower.close(); + } - @Override - public void closeCurrentOnError() { - determineHostHandler().closeCurrentOnError(); - } + @Override + public void closeCurrentOnError() { + determineHostHandler().closeCurrentOnError(); + } } diff --git a/src/main/java/com/arangodb/internal/net/ExtendedHostResolver.java b/src/main/java/com/arangodb/internal/net/ExtendedHostResolver.java index f2b28b2da..c77899be9 100644 --- a/src/main/java/com/arangodb/internal/net/ExtendedHostResolver.java +++ b/src/main/java/com/arangodb/internal/net/ExtendedHostResolver.java @@ -35,121 +35,120 @@ /** * @author Mark Vollmary - * */ public class ExtendedHostResolver implements HostResolver { - private static final Logger LOGGER = LoggerFactory.getLogger(ExtendedHostResolver.class); - - private final HostSet hosts; - - private final Integer maxConnections; - private final ConnectionFactory connectionFactory; - - private long lastUpdate; - private final Integer acquireHostListInterval; - - private ArangoExecutorSync executor; - private ArangoSerialization arangoSerialization; - - - public ExtendedHostResolver(final List hosts, final Integer maxConnections, - final ConnectionFactory connectionFactory, Integer acquireHostListInterval) { - - this.acquireHostListInterval = acquireHostListInterval; - this.hosts = new HostSet(hosts); - this.maxConnections = maxConnections; - this.connectionFactory = connectionFactory; - - lastUpdate = 0; - } - - @Override - public void init(ArangoExecutorSync executor, ArangoSerialization arangoSerialization) { - this.executor = executor; - this.arangoSerialization = arangoSerialization; - } - - @Override - - public HostSet resolve(boolean initial, boolean closeConnections) { - - if (!initial && isExpired()) { - - lastUpdate = System.currentTimeMillis(); - - final Collection endpoints = resolveFromServer(); - LOGGER.debug("Resolve " + endpoints.size() + " Endpoints"); - LOGGER.debug("Endpoints " + Arrays.deepToString(endpoints.toArray())); - - if (!endpoints.isEmpty()) { - hosts.markAllForDeletion(); - } - - for (final String endpoint : endpoints) { - LOGGER.debug("Create HOST from " + endpoint); - - if (endpoint.matches(".*://.+:[0-9]+")) { - - final String[] s = endpoint.replaceAll(".*://", "").split(":"); - if (s.length == 2) { - final HostDescription description = new HostDescription(s[0], Integer.parseInt(s[1])); - hosts.addHost(HostUtils.createHost(description, maxConnections, connectionFactory)); - } else if (s.length == 4) { - // IPV6 Address - TODO: we need a proper function to resolve AND support IPV4 & IPV6 functions - // globally - final HostDescription description = new HostDescription("127.0.0.1", Integer.parseInt(s[3])); - hosts.addHost(HostUtils.createHost(description, maxConnections, connectionFactory)); - } else { - LOGGER.warn("Skip Endpoint (Missing Port)" + endpoint); - } - - } else { - LOGGER.warn("Skip Endpoint (Format)" + endpoint); - } - } - hosts.clearAllMarkedForDeletion(); - } - - return hosts; - } - - private Collection resolveFromServer() throws ArangoDBException { - - Collection response; - - try { - - response = executor.execute( - new Request(ArangoRequestParam.SYSTEM, RequestType.GET, "/_api/cluster/endpoints"), - response1 -> { - final VPackSlice field = response1.getBody().get("endpoints"); - Collection endpoints; - if (field.isNone()) { - endpoints = Collections.emptyList(); - } else { - final Collection> tmp = arangoSerialization.deserialize(field, Collection.class); - endpoints = new ArrayList<>(); - for (final Map map : tmp) { - endpoints.addAll(map.values()); - } - } - return endpoints; - }, null); - } catch (final ArangoDBException e) { - final Integer responseCode = e.getResponseCode(); - if (responseCode != null && responseCode == 403) { - response = Collections.emptyList(); - } else { - throw e; - } - } - - return response; - } - - private boolean isExpired() { - return System.currentTimeMillis() > (lastUpdate + acquireHostListInterval); - } - + private static final Logger LOGGER = LoggerFactory.getLogger(ExtendedHostResolver.class); + + private final HostSet hosts; + + private final Integer maxConnections; + private final ConnectionFactory connectionFactory; + + private long lastUpdate; + private final Integer acquireHostListInterval; + + private ArangoExecutorSync executor; + private ArangoSerialization arangoSerialization; + + + public ExtendedHostResolver(final List hosts, final Integer maxConnections, + final ConnectionFactory connectionFactory, Integer acquireHostListInterval) { + + this.acquireHostListInterval = acquireHostListInterval; + this.hosts = new HostSet(hosts); + this.maxConnections = maxConnections; + this.connectionFactory = connectionFactory; + + lastUpdate = 0; + } + + @Override + public void init(ArangoExecutorSync executor, ArangoSerialization arangoSerialization) { + this.executor = executor; + this.arangoSerialization = arangoSerialization; + } + + @Override + + public HostSet resolve(boolean initial, boolean closeConnections) { + + if (!initial && isExpired()) { + + lastUpdate = System.currentTimeMillis(); + + final Collection endpoints = resolveFromServer(); + LOGGER.debug("Resolve " + endpoints.size() + " Endpoints"); + LOGGER.debug("Endpoints " + Arrays.deepToString(endpoints.toArray())); + + if (!endpoints.isEmpty()) { + hosts.markAllForDeletion(); + } + + for (final String endpoint : endpoints) { + LOGGER.debug("Create HOST from " + endpoint); + + if (endpoint.matches(".*://.+:[0-9]+")) { + + final String[] s = endpoint.replaceAll(".*://", "").split(":"); + if (s.length == 2) { + final HostDescription description = new HostDescription(s[0], Integer.parseInt(s[1])); + hosts.addHost(HostUtils.createHost(description, maxConnections, connectionFactory)); + } else if (s.length == 4) { + // IPV6 Address - TODO: we need a proper function to resolve AND support IPV4 & IPV6 functions + // globally + final HostDescription description = new HostDescription("127.0.0.1", Integer.parseInt(s[3])); + hosts.addHost(HostUtils.createHost(description, maxConnections, connectionFactory)); + } else { + LOGGER.warn("Skip Endpoint (Missing Port)" + endpoint); + } + + } else { + LOGGER.warn("Skip Endpoint (Format)" + endpoint); + } + } + hosts.clearAllMarkedForDeletion(); + } + + return hosts; + } + + private Collection resolveFromServer() throws ArangoDBException { + + Collection response; + + try { + + response = executor.execute( + new Request(ArangoRequestParam.SYSTEM, RequestType.GET, "/_api/cluster/endpoints"), + response1 -> { + final VPackSlice field = response1.getBody().get("endpoints"); + Collection endpoints; + if (field.isNone()) { + endpoints = Collections.emptyList(); + } else { + final Collection> tmp = arangoSerialization.deserialize(field, Collection.class); + endpoints = new ArrayList<>(); + for (final Map map : tmp) { + endpoints.addAll(map.values()); + } + } + return endpoints; + }, null); + } catch (final ArangoDBException e) { + final Integer responseCode = e.getResponseCode(); + if (responseCode != null && responseCode == 403) { + response = Collections.emptyList(); + } else { + throw e; + } + } + + return response; + } + + private boolean isExpired() { + return System.currentTimeMillis() > (lastUpdate + acquireHostListInterval); + } + } diff --git a/src/main/java/com/arangodb/internal/net/Host.java b/src/main/java/com/arangodb/internal/net/Host.java index da8580e38..c3e7514ba 100644 --- a/src/main/java/com/arangodb/internal/net/Host.java +++ b/src/main/java/com/arangodb/internal/net/Host.java @@ -24,19 +24,18 @@ /** * @author Mark Vollmary - * */ public interface Host { - HostDescription getDescription(); + HostDescription getDescription(); - Connection connection(); + Connection connection(); - void closeOnError(); + void closeOnError(); - void close() throws IOException; + void close() throws IOException; - void setMarkforDeletion(boolean markforDeletion); + void setMarkforDeletion(boolean markforDeletion); - boolean isMarkforDeletion(); + boolean isMarkforDeletion(); } diff --git a/src/main/java/com/arangodb/internal/net/HostDescription.java b/src/main/java/com/arangodb/internal/net/HostDescription.java index a53ce4026..53d54b10b 100644 --- a/src/main/java/com/arangodb/internal/net/HostDescription.java +++ b/src/main/java/com/arangodb/internal/net/HostDescription.java @@ -22,61 +22,60 @@ /** * @author Mark Vollmary - * */ public class HostDescription { - private final String host; - private final int port; + private final String host; + private final int port; - public HostDescription(final String host, final int port) { - super(); - this.host = host; - this.port = port; - } + public HostDescription(final String host, final int port) { + super(); + this.host = host; + this.port = port; + } - public String getHost() { - return host; - } + public String getHost() { + return host; + } - public int getPort() { - return port; - } + public int getPort() { + return port; + } - @Override - public String toString() { - return String.format("host[addr=%s,port=%s]", host, port); - } + @Override + public String toString() { + return String.format("host[addr=%s,port=%s]", host, port); + } - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((host == null) ? 0 : host.hashCode()); - result = prime * result + port; - return result; - } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((host == null) ? 0 : host.hashCode()); + result = prime * result + port; + 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 HostDescription other = (HostDescription) obj; - if (host == null) { - if (other.host != null) { - return false; - } - } else if (!host.equals(other.host)) { - return false; - } - return port == other.port; - } + @Override + public boolean equals(final Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final HostDescription other = (HostDescription) obj; + if (host == null) { + if (other.host != null) { + return false; + } + } else if (!host.equals(other.host)) { + return false; + } + return port == other.port; + } } diff --git a/src/main/java/com/arangodb/internal/net/HostHandle.java b/src/main/java/com/arangodb/internal/net/HostHandle.java index 691ec11ae..c26b184d3 100644 --- a/src/main/java/com/arangodb/internal/net/HostHandle.java +++ b/src/main/java/com/arangodb/internal/net/HostHandle.java @@ -22,23 +22,22 @@ /** * @author Mark Vollmary - * */ public class HostHandle { - private HostDescription host; + private HostDescription host; - public HostHandle() { - super(); - } + public HostHandle() { + super(); + } - public HostDescription getHost() { - return host; - } + public HostDescription getHost() { + return host; + } - public HostHandle setHost(final HostDescription host) { - this.host = host; - return this; - } + public HostHandle setHost(final HostDescription host) { + this.host = host; + return this; + } } diff --git a/src/main/java/com/arangodb/internal/net/HostHandler.java b/src/main/java/com/arangodb/internal/net/HostHandler.java index 6577e5821..dacd801f7 100644 --- a/src/main/java/com/arangodb/internal/net/HostHandler.java +++ b/src/main/java/com/arangodb/internal/net/HostHandler.java @@ -24,21 +24,20 @@ /** * @author Mark Vollmary - * */ public interface HostHandler { - Host get(HostHandle hostHandle, AccessType accessType); + Host get(HostHandle hostHandle, AccessType accessType); - void success(); + void success(); - void fail(); + void fail(); - void reset(); + void reset(); - void confirm(); + void confirm(); - void close() throws IOException; + void close() throws IOException; - void closeCurrentOnError(); + void closeCurrentOnError(); } diff --git a/src/main/java/com/arangodb/internal/net/HostImpl.java b/src/main/java/com/arangodb/internal/net/HostImpl.java index 6dfe9660f..a9839c911 100644 --- a/src/main/java/com/arangodb/internal/net/HostImpl.java +++ b/src/main/java/com/arangodb/internal/net/HostImpl.java @@ -26,80 +26,78 @@ /** * @author Mark Vollmary - * */ public class HostImpl implements Host { - private final ConnectionPool connectionPool; - private final HostDescription description; - private boolean markforDeletion = false; - - public HostImpl(final ConnectionPool connectionPool, final HostDescription description) { - super(); - this.connectionPool = connectionPool; - this.description = description; - } - - @Override - public void close() throws IOException { - connectionPool.close(); - } - - @Override - public HostDescription getDescription() { - return description; - } - - @Override - public Connection connection() { - return connectionPool.connection(); - } - - @Override - public void closeOnError() { - try { - connectionPool.close(); - } catch (final IOException e) { - throw new ArangoDBException(e); - } - } - - @Override - public String toString() { - return "HostImpl [connectionPool=" + connectionPool + ", description=" + description + ", markforDeletion=" - + markforDeletion + "]"; - } - - public boolean isMarkforDeletion() { - return markforDeletion; - } - - public void setMarkforDeletion(boolean markforDeletion) { - this.markforDeletion = markforDeletion; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((description == null) ? 0 : description.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - HostImpl other = (HostImpl) obj; - if (description == null) { - return other.description == null; - } else return description.equals(other.description); - } - - - + private final ConnectionPool connectionPool; + private final HostDescription description; + private boolean markforDeletion = false; + + public HostImpl(final ConnectionPool connectionPool, final HostDescription description) { + super(); + this.connectionPool = connectionPool; + this.description = description; + } + + @Override + public void close() throws IOException { + connectionPool.close(); + } + + @Override + public HostDescription getDescription() { + return description; + } + + @Override + public Connection connection() { + return connectionPool.connection(); + } + + @Override + public void closeOnError() { + try { + connectionPool.close(); + } catch (final IOException e) { + throw new ArangoDBException(e); + } + } + + @Override + public String toString() { + return "HostImpl [connectionPool=" + connectionPool + ", description=" + description + ", markforDeletion=" + + markforDeletion + "]"; + } + + public boolean isMarkforDeletion() { + return markforDeletion; + } + + public void setMarkforDeletion(boolean markforDeletion) { + this.markforDeletion = markforDeletion; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((description == null) ? 0 : description.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + HostImpl other = (HostImpl) obj; + if (description == null) { + return other.description == null; + } else return description.equals(other.description); + } + + } diff --git a/src/main/java/com/arangodb/internal/net/HostResolver.java b/src/main/java/com/arangodb/internal/net/HostResolver.java index 8f1477101..85bdd2038 100644 --- a/src/main/java/com/arangodb/internal/net/HostResolver.java +++ b/src/main/java/com/arangodb/internal/net/HostResolver.java @@ -25,12 +25,11 @@ /** * @author Mark Vollmary - * */ public interface HostResolver { - void init(ArangoExecutorSync executorSync, ArangoSerialization arangoSerialization); + void init(ArangoExecutorSync executorSync, ArangoSerialization arangoSerialization); - HostSet resolve(boolean initial, boolean closeConnections); + HostSet resolve(boolean initial, boolean closeConnections); } diff --git a/src/main/java/com/arangodb/internal/net/HostSet.java b/src/main/java/com/arangodb/internal/net/HostSet.java index 675e9c7cf..6645659a3 100644 --- a/src/main/java/com/arangodb/internal/net/HostSet.java +++ b/src/main/java/com/arangodb/internal/net/HostSet.java @@ -9,91 +9,91 @@ import java.util.List; public class HostSet { - private static final Logger LOGGER = LoggerFactory.getLogger(HostSet.class); - - private final ArrayList hosts = new ArrayList<>(); - - public HostSet() { - super(); - } - - public HostSet(List hosts) { - super(); - - for (Host host : hosts) { - addHost(host); - } - - } - - public List getHostsList() { - return Collections.unmodifiableList(hosts); - } - - public void addHost(Host newHost) { - - if(hosts.contains(newHost)) { - LOGGER.debug("Host" + newHost + " already in Set"); - - for (Host host : hosts) { - if(host.equals(newHost)) { - host.setMarkforDeletion(false); - } - } - - } else { - hosts.add(newHost); - LOGGER.debug("Added Host " + newHost + " - now " + hosts.size() + " Hosts in List"); - } - - } - - public void close() { - LOGGER.debug("Close all Hosts in Set"); - - for (Host host : hosts) { - try { - - LOGGER.debug("Try to close Host " + host); - host.close(); - - } catch (IOException e) { - LOGGER.warn("Error during closing the Host " + host, e); - } - } - } - - public void markAllForDeletion() { - - for (Host host : hosts) { - host.setMarkforDeletion(true); - } - - } - - public void clearAllMarkedForDeletion() { - - LOGGER.debug("Clear all Hosts in Set with markForDeletion"); - - for (Host host : hosts) { - if(host.isMarkforDeletion()) { - try { - - LOGGER.debug("Try to close Host " + host); - host.close(); - - } catch (IOException e) { - LOGGER.warn("Error during closing the Host " + host, e); - } - } - } - - } - - public void clear() { - LOGGER.debug("Clear all Hosts in Set"); - - close(); - hosts.clear(); - } + private static final Logger LOGGER = LoggerFactory.getLogger(HostSet.class); + + private final ArrayList hosts = new ArrayList<>(); + + public HostSet() { + super(); + } + + public HostSet(List hosts) { + super(); + + for (Host host : hosts) { + addHost(host); + } + + } + + public List getHostsList() { + return Collections.unmodifiableList(hosts); + } + + public void addHost(Host newHost) { + + if (hosts.contains(newHost)) { + LOGGER.debug("Host" + newHost + " already in Set"); + + for (Host host : hosts) { + if (host.equals(newHost)) { + host.setMarkforDeletion(false); + } + } + + } else { + hosts.add(newHost); + LOGGER.debug("Added Host " + newHost + " - now " + hosts.size() + " Hosts in List"); + } + + } + + public void close() { + LOGGER.debug("Close all Hosts in Set"); + + for (Host host : hosts) { + try { + + LOGGER.debug("Try to close Host " + host); + host.close(); + + } catch (IOException e) { + LOGGER.warn("Error during closing the Host " + host, e); + } + } + } + + public void markAllForDeletion() { + + for (Host host : hosts) { + host.setMarkforDeletion(true); + } + + } + + public void clearAllMarkedForDeletion() { + + LOGGER.debug("Clear all Hosts in Set with markForDeletion"); + + for (Host host : hosts) { + if (host.isMarkforDeletion()) { + try { + + LOGGER.debug("Try to close Host " + host); + host.close(); + + } catch (IOException e) { + LOGGER.warn("Error during closing the Host " + host, e); + } + } + } + + } + + public void clear() { + LOGGER.debug("Clear all Hosts in Set"); + + close(); + hosts.clear(); + } } diff --git a/src/main/java/com/arangodb/internal/net/RandomHostHandler.java b/src/main/java/com/arangodb/internal/net/RandomHostHandler.java index 3a2f3eb0f..f1359abd2 100644 --- a/src/main/java/com/arangodb/internal/net/RandomHostHandler.java +++ b/src/main/java/com/arangodb/internal/net/RandomHostHandler.java @@ -25,66 +25,65 @@ /** * @author Mark Vollmary - * */ public class RandomHostHandler implements HostHandler { - private final HostResolver resolver; - private final HostHandler fallback; - private Host origin; - private Host current; + private final HostResolver resolver; + private final HostHandler fallback; + private Host origin; + private Host current; - public RandomHostHandler(final HostResolver resolver, final HostHandler fallback) { - super(); - this.resolver = resolver; - this.fallback = fallback; - origin = current = getRandomHost(true, false); - } + public RandomHostHandler(final HostResolver resolver, final HostHandler fallback) { + super(); + this.resolver = resolver; + this.fallback = fallback; + origin = current = getRandomHost(true, false); + } - @Override - public Host get(final HostHandle hostHandle, AccessType accessType) { - if (current == null) { - origin = current = getRandomHost(false, true); - } - return current; - } + @Override + public Host get(final HostHandle hostHandle, AccessType accessType) { + if (current == null) { + origin = current = getRandomHost(false, true); + } + return current; + } - @Override - public void success() { - current = origin; - } + @Override + public void success() { + current = origin; + } - @Override - public void fail() { - fallback.fail(); - current = fallback.get(null, null); - } + @Override + public void fail() { + fallback.fail(); + current = fallback.get(null, null); + } - private Host getRandomHost(final boolean initial, final boolean closeConnections) { + private Host getRandomHost(final boolean initial, final boolean closeConnections) { - final ArrayList hosts = new ArrayList<>(resolver.resolve(initial, closeConnections).getHostsList()); - Collections.shuffle(hosts); - return hosts.get(0); - } + final ArrayList hosts = new ArrayList<>(resolver.resolve(initial, closeConnections).getHostsList()); + Collections.shuffle(hosts); + return hosts.get(0); + } - @Override - public void reset() { - fallback.reset(); - } + @Override + public void reset() { + fallback.reset(); + } - @Override - public void confirm() { - } + @Override + public void confirm() { + } - @Override - public void close() { - final HostSet hosts = resolver.resolve(false, false); - hosts.close(); - } + @Override + public void close() { + final HostSet hosts = resolver.resolve(false, false); + hosts.close(); + } - @Override - public void closeCurrentOnError() { - current.closeOnError(); - } + @Override + public void closeCurrentOnError() { + current.closeOnError(); + } } diff --git a/src/main/java/com/arangodb/internal/net/RoundRobinHostHandler.java b/src/main/java/com/arangodb/internal/net/RoundRobinHostHandler.java index 86ff07715..8b71b9ce2 100644 --- a/src/main/java/com/arangodb/internal/net/RoundRobinHostHandler.java +++ b/src/main/java/com/arangodb/internal/net/RoundRobinHostHandler.java @@ -24,82 +24,81 @@ /** * @author Mark Vollmary - * */ public class RoundRobinHostHandler implements HostHandler { - private final HostResolver resolver; - - private int current; - private int fails; - private Host currentHost; - - public RoundRobinHostHandler(final HostResolver resolver) { - super(); - this.resolver = resolver; - resolver.resolve(true, false); - current = 0; - fails = 0; - } - - @Override - public Host get(final HostHandle hostHandle, AccessType accessType) { - - final HostSet hosts = resolver.resolve(false, false); - final int size = hosts.getHostsList().size(); - - if (fails > size) { - reset(); - throw new ArangoDBException("Cannot contact any host!"); - } - - final int index = (current++) % size; - Host host = hosts.getHostsList().get(index); - if (hostHandle != null) { - final HostDescription hostDescription = hostHandle.getHost(); - if (hostDescription != null) { - for (int i = index; i < index + size; i++) { - host = hosts.getHostsList().get(i % size); - if (hostDescription.equals(host.getDescription())) { - break; - } - } - } else { - hostHandle.setHost(host.getDescription()); - } - } - currentHost = host; - return host; - } - - @Override - public void success() { - fails = 0; - } - - @Override - public void fail() { - fails++; - } - - @Override - public void reset() { - fails = 0; - } - - @Override - public void confirm() { - } - - @Override - public void close() { - final HostSet hosts = resolver.resolve(false, false); - hosts.close(); - } - - @Override - public void closeCurrentOnError() { - currentHost.closeOnError(); - } + private final HostResolver resolver; + + private int current; + private int fails; + private Host currentHost; + + public RoundRobinHostHandler(final HostResolver resolver) { + super(); + this.resolver = resolver; + resolver.resolve(true, false); + current = 0; + fails = 0; + } + + @Override + public Host get(final HostHandle hostHandle, AccessType accessType) { + + final HostSet hosts = resolver.resolve(false, false); + final int size = hosts.getHostsList().size(); + + if (fails > size) { + reset(); + throw new ArangoDBException("Cannot contact any host!"); + } + + final int index = (current++) % size; + Host host = hosts.getHostsList().get(index); + if (hostHandle != null) { + final HostDescription hostDescription = hostHandle.getHost(); + if (hostDescription != null) { + for (int i = index; i < index + size; i++) { + host = hosts.getHostsList().get(i % size); + if (hostDescription.equals(host.getDescription())) { + break; + } + } + } else { + hostHandle.setHost(host.getDescription()); + } + } + currentHost = host; + return host; + } + + @Override + public void success() { + fails = 0; + } + + @Override + public void fail() { + fails++; + } + + @Override + public void reset() { + fails = 0; + } + + @Override + public void confirm() { + } + + @Override + public void close() { + final HostSet hosts = resolver.resolve(false, false); + hosts.close(); + } + + @Override + public void closeCurrentOnError() { + currentHost.closeOnError(); + } } diff --git a/src/main/java/com/arangodb/internal/net/SimpleHostResolver.java b/src/main/java/com/arangodb/internal/net/SimpleHostResolver.java index dc47987f9..e139e3866 100644 --- a/src/main/java/com/arangodb/internal/net/SimpleHostResolver.java +++ b/src/main/java/com/arangodb/internal/net/SimpleHostResolver.java @@ -20,32 +20,31 @@ package com.arangodb.internal.net; -import java.util.List; - import com.arangodb.internal.ArangoExecutorSync; import com.arangodb.util.ArangoSerialization; +import java.util.List; + /** * @author Mark Vollmary - * */ public class SimpleHostResolver implements HostResolver { - private final List hosts; - - public SimpleHostResolver(final List hosts) { - super(); - this.hosts = hosts; - } - - @Override - public void init(ArangoExecutorSync executor, ArangoSerialization arangoSerialization) { - - } - - @Override - public HostSet resolve(final boolean initial, final boolean closeConnections) { - return new HostSet(hosts); - } + private final List hosts; + + public SimpleHostResolver(final List hosts) { + super(); + this.hosts = hosts; + } + + @Override + public void init(ArangoExecutorSync executor, ArangoSerialization arangoSerialization) { + + } + + @Override + public HostSet resolve(final boolean initial, final boolean closeConnections) { + return new HostSet(hosts); + } } diff --git a/src/main/java/com/arangodb/internal/util/ArangoDeserializerImpl.java b/src/main/java/com/arangodb/internal/util/ArangoDeserializerImpl.java index 416dcbdb8..9b6dc3c91 100644 --- a/src/main/java/com/arangodb/internal/util/ArangoDeserializerImpl.java +++ b/src/main/java/com/arangodb/internal/util/ArangoDeserializerImpl.java @@ -20,8 +20,6 @@ package com.arangodb.internal.util; -import java.lang.reflect.Type; - import com.arangodb.ArangoDBException; import com.arangodb.util.ArangoDeserializer; import com.arangodb.velocypack.VPack; @@ -29,34 +27,35 @@ import com.arangodb.velocypack.VPackSlice; import com.arangodb.velocypack.exception.VPackException; +import java.lang.reflect.Type; + /** * @author Mark Vollmary - * */ public class ArangoDeserializerImpl implements ArangoDeserializer { - private final VPack vpacker; - private final VPackParser vpackParser; + private final VPack vpacker; + private final VPackParser vpackParser; - public ArangoDeserializerImpl(final VPack vpacker, final VPackParser vpackParser) { - super(); - this.vpacker = vpacker; - this.vpackParser = vpackParser; - } + public ArangoDeserializerImpl(final VPack vpacker, final VPackParser vpackParser) { + super(); + this.vpacker = vpacker; + this.vpackParser = vpackParser; + } - @Override - @SuppressWarnings("unchecked") - public T deserialize(final VPackSlice vpack, final Type type) throws ArangoDBException { - try { - final T doc; - if (type == String.class && !vpack.isString()) { - doc = (T) vpackParser.toJson(vpack, true); - } else { - doc = vpacker.deserialize(vpack, type); - } - return doc; - } catch (final VPackException e) { - throw new ArangoDBException(e); - } - } + @Override + @SuppressWarnings("unchecked") + public T deserialize(final VPackSlice vpack, final Type type) throws ArangoDBException { + try { + final T doc; + if (type == String.class && !vpack.isString()) { + doc = (T) vpackParser.toJson(vpack, true); + } else { + doc = vpacker.deserialize(vpack, type); + } + return doc; + } catch (final VPackException e) { + throw new ArangoDBException(e); + } + } } diff --git a/src/main/java/com/arangodb/internal/util/ArangoSerializationFactory.java b/src/main/java/com/arangodb/internal/util/ArangoSerializationFactory.java index e4cc7e085..035c2dc92 100644 --- a/src/main/java/com/arangodb/internal/util/ArangoSerializationFactory.java +++ b/src/main/java/com/arangodb/internal/util/ArangoSerializationFactory.java @@ -24,31 +24,30 @@ /** * @author Mark Vollmary - * */ public class ArangoSerializationFactory { - public enum Serializer { - INTERNAL, CUSTOM - } - - private final ArangoSerialization interal; - private final ArangoSerialization custom; - - public ArangoSerializationFactory(final ArangoSerialization interal, final ArangoSerialization custom) { - super(); - this.interal = interal; - this.custom = custom; - } - - public ArangoSerialization get(final Serializer serializer) { - switch (serializer) { - case CUSTOM: - return custom; - case INTERNAL: - default: - return interal; - } - } + public enum Serializer { + INTERNAL, CUSTOM + } + + private final ArangoSerialization interal; + private final ArangoSerialization custom; + + public ArangoSerializationFactory(final ArangoSerialization interal, final ArangoSerialization custom) { + super(); + this.interal = interal; + this.custom = custom; + } + + public ArangoSerialization get(final Serializer serializer) { + switch (serializer) { + case CUSTOM: + return custom; + case INTERNAL: + default: + return interal; + } + } } diff --git a/src/main/java/com/arangodb/internal/util/ArangoSerializerImpl.java b/src/main/java/com/arangodb/internal/util/ArangoSerializerImpl.java index 70803d9eb..7561622ce 100644 --- a/src/main/java/com/arangodb/internal/util/ArangoSerializerImpl.java +++ b/src/main/java/com/arangodb/internal/util/ArangoSerializerImpl.java @@ -32,56 +32,55 @@ /** * @author Mark Vollmary - * */ public class ArangoSerializerImpl implements ArangoSerializer { - private final VPack vpacker; - private final VPack vpackerNull; - private final VPackParser vpackParser; + private final VPack vpacker; + private final VPack vpackerNull; + private final VPackParser vpackParser; - public ArangoSerializerImpl(final VPack vpacker, final VPack vpackerNull, final VPackParser vpackParser) { - super(); - this.vpacker = vpacker; - this.vpackerNull = vpackerNull; - this.vpackParser = vpackParser; - } + public ArangoSerializerImpl(final VPack vpacker, final VPack vpackerNull, final VPackParser vpackParser) { + super(); + this.vpacker = vpacker; + this.vpackerNull = vpackerNull; + this.vpackParser = vpackParser; + } - @Override - public VPackSlice serialize(final Object entity) throws ArangoDBException { - return serialize(entity, new ArangoSerializer.Options()); - } + @Override + public VPackSlice serialize(final Object entity) throws ArangoDBException { + return serialize(entity, new ArangoSerializer.Options()); + } - @SuppressWarnings("unchecked") - @Override - public VPackSlice serialize(final Object entity, final Options options) throws ArangoDBException { - if (options.getType() == null) { - options.type(entity.getClass()); - } - try { - final VPackSlice vpack; + @SuppressWarnings("unchecked") + @Override + public VPackSlice serialize(final Object entity, final Options options) throws ArangoDBException { + if (options.getType() == null) { + options.type(entity.getClass()); + } + try { + final VPackSlice vpack; final Class type = entity.getClass(); - final boolean serializeNullValues = options.isSerializeNullValues(); - if (String.class.isAssignableFrom(type)) { - vpack = vpackParser.fromJson((String) entity, serializeNullValues); - } else if (options.isStringAsJson() && Iterable.class.isAssignableFrom(type)) { + final boolean serializeNullValues = options.isSerializeNullValues(); + if (String.class.isAssignableFrom(type)) { + vpack = vpackParser.fromJson((String) entity, serializeNullValues); + } else if (options.isStringAsJson() && Iterable.class.isAssignableFrom(type)) { final Iterator iterator = ((Iterable) entity).iterator(); - if (iterator.hasNext() && String.class.isAssignableFrom(iterator.next().getClass())) { - vpack = vpackParser.fromJson((Iterable) entity, serializeNullValues); - } else { - final VPack vp = serializeNullValues ? vpackerNull : vpacker; - vpack = vp.serialize(entity, - new SerializeOptions().type(options.getType()).additionalFields(options.getAdditionalFields())); - } - } else { - final VPack vp = serializeNullValues ? vpackerNull : vpacker; - vpack = vp.serialize(entity, - new SerializeOptions().type(options.getType()).additionalFields(options.getAdditionalFields())); - } - return vpack; - } catch (final VPackException e) { - throw new ArangoDBException(e); - } - } + if (iterator.hasNext() && String.class.isAssignableFrom(iterator.next().getClass())) { + vpack = vpackParser.fromJson((Iterable) entity, serializeNullValues); + } else { + final VPack vp = serializeNullValues ? vpackerNull : vpacker; + vpack = vp.serialize(entity, + new SerializeOptions().type(options.getType()).additionalFields(options.getAdditionalFields())); + } + } else { + final VPack vp = serializeNullValues ? vpackerNull : vpacker; + vpack = vp.serialize(entity, + new SerializeOptions().type(options.getType()).additionalFields(options.getAdditionalFields())); + } + return vpack; + } catch (final VPackException e) { + throw new ArangoDBException(e); + } + } } diff --git a/src/main/java/com/arangodb/internal/util/CURLLogger.java b/src/main/java/com/arangodb/internal/util/CURLLogger.java index 926e69c2b..a95d1a710 100644 --- a/src/main/java/com/arangodb/internal/util/CURLLogger.java +++ b/src/main/java/com/arangodb/internal/util/CURLLogger.java @@ -31,49 +31,48 @@ /** * @author Mark Vollmary - * */ public final class CURLLogger { - private static final Logger LOGGER = LoggerFactory.getLogger(CURLLogger.class); + private static final Logger LOGGER = LoggerFactory.getLogger(CURLLogger.class); - private CURLLogger() { - } + private CURLLogger() { + } - public static void log( - final String url, - final Request request, - final Credentials credencials, - final ArangoSerialization util) { - final RequestType requestType = request.getRequestType(); - final boolean includeBody = (requestType == RequestType.POST || requestType == RequestType.PUT - || requestType == RequestType.PATCH || requestType == RequestType.DELETE) && request.getBody() != null; - final StringBuilder buffer = new StringBuilder(); - if (includeBody) { - buffer.append("\n"); - buffer.append("cat <<-___EOB___ | "); - } - buffer.append("curl -X ").append(requestType); - buffer.append(" --dump -"); - if (request.getHeaderParam().size() > 0) { - for (final Entry header : request.getHeaderParam().entrySet()) { - buffer.append(" -H '").append(header.getKey()).append(":").append(header.getValue()).append("'"); - } - } - if (credencials != null) { - buffer.append(" -u ").append(credencials.getUserPrincipal().getName()).append(":") - .append(credencials.getPassword()); - } - if (includeBody) { - buffer.append(" -d @-"); - } - buffer.append(" '").append(url).append("'"); - if (includeBody) { - buffer.append("\n"); - buffer.append((String) util.deserialize(request.getBody(), String.class)); - buffer.append("\n"); - buffer.append("___EOB___"); - } - LOGGER.debug("[CURL] {}", buffer); - } + public static void log( + final String url, + final Request request, + final Credentials credencials, + final ArangoSerialization util) { + final RequestType requestType = request.getRequestType(); + final boolean includeBody = (requestType == RequestType.POST || requestType == RequestType.PUT + || requestType == RequestType.PATCH || requestType == RequestType.DELETE) && request.getBody() != null; + final StringBuilder buffer = new StringBuilder(); + if (includeBody) { + buffer.append("\n"); + buffer.append("cat <<-___EOB___ | "); + } + buffer.append("curl -X ").append(requestType); + buffer.append(" --dump -"); + if (request.getHeaderParam().size() > 0) { + for (final Entry header : request.getHeaderParam().entrySet()) { + buffer.append(" -H '").append(header.getKey()).append(":").append(header.getValue()).append("'"); + } + } + if (credencials != null) { + buffer.append(" -u ").append(credencials.getUserPrincipal().getName()).append(":") + .append(credencials.getPassword()); + } + if (includeBody) { + buffer.append(" -d @-"); + } + buffer.append(" '").append(url).append("'"); + if (includeBody) { + buffer.append("\n"); + buffer.append((String) util.deserialize(request.getBody(), String.class)); + buffer.append("\n"); + buffer.append("___EOB___"); + } + LOGGER.debug("[CURL] {}", buffer); + } } diff --git a/src/main/java/com/arangodb/internal/util/DefaultArangoSerialization.java b/src/main/java/com/arangodb/internal/util/DefaultArangoSerialization.java index 450251c4d..f77f2ee49 100644 --- a/src/main/java/com/arangodb/internal/util/DefaultArangoSerialization.java +++ b/src/main/java/com/arangodb/internal/util/DefaultArangoSerialization.java @@ -20,42 +20,41 @@ package com.arangodb.internal.util; -import java.lang.reflect.Type; - import com.arangodb.ArangoDBException; import com.arangodb.util.ArangoDeserializer; import com.arangodb.util.ArangoSerialization; import com.arangodb.util.ArangoSerializer; import com.arangodb.velocypack.VPackSlice; +import java.lang.reflect.Type; + /** * @author Mark Vollmary - * */ public class DefaultArangoSerialization implements ArangoSerialization { - private final ArangoSerializer serializer; - private final ArangoDeserializer deserializer; - - public DefaultArangoSerialization(final ArangoSerializer serializer, final ArangoDeserializer deserializer) { - super(); - this.serializer = serializer; - this.deserializer = deserializer; - } - - @Override - public VPackSlice serialize(final Object entity) throws ArangoDBException { - return serializer.serialize(entity); - } - - @Override - public VPackSlice serialize(final Object entity, final Options options) throws ArangoDBException { - return serializer.serialize(entity, options); - } - - @Override - public T deserialize(final VPackSlice vpack, final Type type) throws ArangoDBException { - return deserializer.deserialize(vpack, type); - } + private final ArangoSerializer serializer; + private final ArangoDeserializer deserializer; + + public DefaultArangoSerialization(final ArangoSerializer serializer, final ArangoDeserializer deserializer) { + super(); + this.serializer = serializer; + this.deserializer = deserializer; + } + + @Override + public VPackSlice serialize(final Object entity) throws ArangoDBException { + return serializer.serialize(entity); + } + + @Override + public VPackSlice serialize(final Object entity, final Options options) throws ArangoDBException { + return serializer.serialize(entity, options); + } + + @Override + public T deserialize(final VPackSlice vpack, final Type type) throws ArangoDBException { + return deserializer.deserialize(vpack, type); + } } diff --git a/src/main/java/com/arangodb/internal/util/DocumentUtil.java b/src/main/java/com/arangodb/internal/util/DocumentUtil.java index d2c13defd..fb108d91c 100644 --- a/src/main/java/com/arangodb/internal/util/DocumentUtil.java +++ b/src/main/java/com/arangodb/internal/util/DocumentUtil.java @@ -26,39 +26,38 @@ /** * @author Mark Vollmary - * */ public final class DocumentUtil { - private static final String SLASH = "/"; - public static final String REGEX_KEY = "[^/]+"; - public static final String REGEX_ID = "[^/]+/[^/]+"; - - private DocumentUtil() { - super(); - } - - public static void validateIndexId(final String id) { - validateName("index id", REGEX_ID, id); - } - - public static void validateDocumentKey(final String key) throws ArangoDBException { - validateName("document key", REGEX_KEY, key); - } - - public static void validateDocumentId(final String id) throws ArangoDBException { - validateName("document id", REGEX_ID, id); - } - - public static String createDocumentHandle(final String collection, final String key) { - validateDocumentKey(key); - return collection + SLASH + key; - } - - private static void validateName(final String type, final String regex, final CharSequence name) - throws ArangoDBException { - if (!Pattern.matches(regex, name)) { - throw new ArangoDBException(String.format("%s %s is not valid.", type, name)); - } - } + private static final String SLASH = "/"; + public static final String REGEX_KEY = "[^/]+"; + public static final String REGEX_ID = "[^/]+/[^/]+"; + + private DocumentUtil() { + super(); + } + + public static void validateIndexId(final String id) { + validateName("index id", REGEX_ID, id); + } + + public static void validateDocumentKey(final String key) throws ArangoDBException { + validateName("document key", REGEX_KEY, key); + } + + public static void validateDocumentId(final String id) throws ArangoDBException { + validateName("document id", REGEX_ID, id); + } + + public static String createDocumentHandle(final String collection, final String key) { + validateDocumentKey(key); + return collection + SLASH + key; + } + + private static void validateName(final String type, final String regex, final CharSequence name) + throws ArangoDBException { + if (!Pattern.matches(regex, name)) { + throw new ArangoDBException(String.format("%s %s is not valid.", type, name)); + } + } } diff --git a/src/main/java/com/arangodb/internal/util/EncodeUtils.java b/src/main/java/com/arangodb/internal/util/EncodeUtils.java index 4c8015403..9696c30fc 100644 --- a/src/main/java/com/arangodb/internal/util/EncodeUtils.java +++ b/src/main/java/com/arangodb/internal/util/EncodeUtils.java @@ -25,16 +25,15 @@ /** * @author Mark Vollmary - * */ public final class EncodeUtils { - private EncodeUtils() { - } + private EncodeUtils() { + } - public static String encodeURL(final String value) throws UnsupportedEncodingException { - return URLEncoder.encode(value, "UTF-8").replaceAll("\\+", "%20").replaceAll("\\%21", "!") - .replaceAll("\\%27", "'").replaceAll("\\%28", "(").replaceAll("\\%29", ")").replaceAll("\\%7E", "~"); - } + public static String encodeURL(final String value) throws UnsupportedEncodingException { + return URLEncoder.encode(value, "UTF-8").replaceAll("\\+", "%20").replaceAll("\\%21", "!") + .replaceAll("\\%27", "'").replaceAll("\\%28", "(").replaceAll("\\%29", ")").replaceAll("\\%7E", "~"); + } } diff --git a/src/main/java/com/arangodb/internal/util/HostUtils.java b/src/main/java/com/arangodb/internal/util/HostUtils.java index 885e13178..094830f5f 100644 --- a/src/main/java/com/arangodb/internal/util/HostUtils.java +++ b/src/main/java/com/arangodb/internal/util/HostUtils.java @@ -24,29 +24,28 @@ /** * @author Mark Vollmary - * */ public final class HostUtils { - private HostUtils() { - super(); - } + private HostUtils() { + super(); + } - public static HostDescription createFromLocation(final String location) { - final HostDescription host; - if (location != null) { - final String[] tmp = location.replaceAll(".*://", "").replaceAll("/.*", "").split(":"); - host = tmp.length == 2 ? new HostDescription(tmp[0], Integer.parseInt(tmp[1])) : null; - } else { - host = null; - } - return host; - } + public static HostDescription createFromLocation(final String location) { + final HostDescription host; + if (location != null) { + final String[] tmp = location.replaceAll(".*://", "").replaceAll("/.*", "").split(":"); + host = tmp.length == 2 ? new HostDescription(tmp[0], Integer.parseInt(tmp[1])) : null; + } else { + host = null; + } + return host; + } - public static Host createHost( - final HostDescription description, - final int maxConnections, - final ConnectionFactory factory) { - return new HostImpl(new ConnectionPoolImpl(description, maxConnections, factory), description); - } + public static Host createHost( + final HostDescription description, + final int maxConnections, + final ConnectionFactory factory) { + return new HostImpl(new ConnectionPoolImpl(description, maxConnections, factory), description); + } } diff --git a/src/main/java/com/arangodb/internal/util/IOUtils.java b/src/main/java/com/arangodb/internal/util/IOUtils.java index 072cd0c8e..c2985c4f6 100644 --- a/src/main/java/com/arangodb/internal/util/IOUtils.java +++ b/src/main/java/com/arangodb/internal/util/IOUtils.java @@ -27,51 +27,50 @@ /** * @author Mark Vollmary - * */ public final class IOUtils { - - private static final Logger LOGGER = LoggerFactory.getLogger(IOUtils.class); - private IOUtils() { - } + private static final Logger LOGGER = LoggerFactory.getLogger(IOUtils.class); + + private IOUtils() { + } - public static String toString(final InputStream input) throws IOException { - return toString(input, "utf-8"); - } + public static String toString(final InputStream input) throws IOException { + return toString(input, "utf-8"); + } - public static String toString(final InputStream input, final String encode) throws IOException { - try { - final StringBuilder buffer = new StringBuilder(8012); - final InputStreamReader in = new InputStreamReader(new BufferedInputStream(input), encode); - final char[] cbuf = new char[8012]; - int len; - while ((len = in.read(cbuf)) != -1) { - buffer.append(cbuf, 0, len); - } - return buffer.toString(); - } catch (final UnsupportedEncodingException e) { - throw new RuntimeException(e); - } finally { - if (input != null) { - try { - input.close(); - } catch (final IOException e) { - // TODO - } - } - } - } + public static String toString(final InputStream input, final String encode) throws IOException { + try { + final StringBuilder buffer = new StringBuilder(8012); + final InputStreamReader in = new InputStreamReader(new BufferedInputStream(input), encode); + final char[] cbuf = new char[8012]; + int len; + while ((len = in.read(cbuf)) != -1) { + buffer.append(cbuf, 0, len); + } + return buffer.toString(); + } catch (final UnsupportedEncodingException e) { + throw new RuntimeException(e); + } finally { + if (input != null) { + try { + input.close(); + } catch (final IOException e) { + // TODO + } + } + } + } - public static byte[] toByteArray(final InputStream input) throws IOException { - final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); - int nRead; - final byte[] data = new byte[8012]; - while ((nRead = input.read(data, 0, data.length)) != -1) { - buffer.write(data, 0, nRead); - } - buffer.flush(); - return buffer.toByteArray(); - } + public static byte[] toByteArray(final InputStream input) throws IOException { + final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + int nRead; + final byte[] data = new byte[8012]; + while ((nRead = input.read(data, 0, data.length)) != -1) { + buffer.write(data, 0, nRead); + } + buffer.flush(); + return buffer.toByteArray(); + } } diff --git a/src/main/java/com/arangodb/internal/util/RequestUtils.java b/src/main/java/com/arangodb/internal/util/RequestUtils.java index 9cfe0d057..2b5f56b47 100644 --- a/src/main/java/com/arangodb/internal/util/RequestUtils.java +++ b/src/main/java/com/arangodb/internal/util/RequestUtils.java @@ -26,28 +26,27 @@ /** * @author Mark Vollmary - * */ public final class RequestUtils { - public static final String HEADER_ALLOW_DIRTY_READ = "X-Arango-Allow-Dirty-Read"; - - private RequestUtils() { - super(); - } - - public static Request allowDirtyRead(final Request request) { - return request.putHeaderParam(HEADER_ALLOW_DIRTY_READ, "true"); - } - - public static AccessType determineAccessType(final Request request) { - if (request.getHeaderParam().containsKey(HEADER_ALLOW_DIRTY_READ)) { - return AccessType.DIRTY_READ; - } - if (request.getRequestType() == RequestType.GET) { - return AccessType.READ; - } - return AccessType.WRITE; - } + public static final String HEADER_ALLOW_DIRTY_READ = "X-Arango-Allow-Dirty-Read"; + + private RequestUtils() { + super(); + } + + public static Request allowDirtyRead(final Request request) { + return request.putHeaderParam(HEADER_ALLOW_DIRTY_READ, "true"); + } + + public static AccessType determineAccessType(final Request request) { + if (request.getHeaderParam().containsKey(HEADER_ALLOW_DIRTY_READ)) { + return AccessType.DIRTY_READ; + } + if (request.getRequestType() == RequestType.GET) { + return AccessType.READ; + } + return AccessType.WRITE; + } } diff --git a/src/main/java/com/arangodb/internal/util/ResponseUtils.java b/src/main/java/com/arangodb/internal/util/ResponseUtils.java index 016ecc806..a7edaa179 100644 --- a/src/main/java/com/arangodb/internal/util/ResponseUtils.java +++ b/src/main/java/com/arangodb/internal/util/ResponseUtils.java @@ -29,34 +29,33 @@ /** * @author Mark Vollmary - * */ public final class ResponseUtils { - private static final int ERROR_STATUS = 300; - private static final int ERROR_INTERNAL = 503; - private static final String HEADER_ENDPOINT = "X-Arango-Endpoint"; + private static final int ERROR_STATUS = 300; + private static final int ERROR_INTERNAL = 503; + private static final String HEADER_ENDPOINT = "X-Arango-Endpoint"; - private ResponseUtils() { - super(); - } + private ResponseUtils() { + super(); + } - public static void checkError(final ArangoSerialization util, final Response response) throws ArangoDBException { - try { - final int responseCode = response.getResponseCode(); - if (responseCode >= ERROR_STATUS) { - if (responseCode == ERROR_INTERNAL && response.getMeta().containsKey(HEADER_ENDPOINT)) { - throw new ArangoDBRedirectException(String.format("Response Code: %s", responseCode), - response.getMeta().get(HEADER_ENDPOINT)); - } else if (response.getBody() != null) { - final ErrorEntity errorEntity = util.deserialize(response.getBody(), ErrorEntity.class); - throw new ArangoDBException(errorEntity); - } else { - throw new ArangoDBException(String.format("Response Code: %s", responseCode), responseCode); - } - } - } catch (final VPackParserException e) { - throw new ArangoDBException(e); - } - } + public static void checkError(final ArangoSerialization util, final Response response) throws ArangoDBException { + try { + final int responseCode = response.getResponseCode(); + if (responseCode >= ERROR_STATUS) { + if (responseCode == ERROR_INTERNAL && response.getMeta().containsKey(HEADER_ENDPOINT)) { + throw new ArangoDBRedirectException(String.format("Response Code: %s", responseCode), + response.getMeta().get(HEADER_ENDPOINT)); + } else if (response.getBody() != null) { + final ErrorEntity errorEntity = util.deserialize(response.getBody(), ErrorEntity.class); + throw new ArangoDBException(errorEntity); + } else { + throw new ArangoDBException(String.format("Response Code: %s", responseCode), responseCode); + } + } + } catch (final VPackParserException e) { + throw new ArangoDBException(e); + } + } } diff --git a/src/main/java/com/arangodb/internal/velocypack/VPackDeserializers.java b/src/main/java/com/arangodb/internal/velocypack/VPackDeserializers.java index 2c376bb60..def5c441b 100644 --- a/src/main/java/com/arangodb/internal/velocypack/VPackDeserializers.java +++ b/src/main/java/com/arangodb/internal/velocypack/VPackDeserializers.java @@ -37,205 +37,204 @@ /** * @author Mark Vollmary - * */ public class VPackDeserializers { - private static final Logger LOGGER = LoggerFactory.getLogger(VPackDeserializers.class); - private static final String DATE_TIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"; - - public static final VPackDeserializer RESPONSE = (parent, vpack, context) -> { - final Response response = new Response(); - response.setVersion(vpack.get(0).getAsInt()); - response.setType(vpack.get(1).getAsInt()); - response.setResponseCode(vpack.get(2).getAsInt()); - if (vpack.size() > 3) { - response.setMeta(context.deserialize(vpack.get(3), Map.class)); - } - return response; - }; - - public static final VPackDeserializer COLLECTION_TYPE = (parent, vpack, context) -> CollectionType.fromType(vpack.getAsInt()); - - public static final VPackDeserializer COLLECTION_STATUS = (parent, vpack, context) -> CollectionStatus.fromStatus(vpack.getAsInt()); - - @SuppressWarnings("unchecked") - public static final VPackDeserializer BASE_DOCUMENT = (parent, vpack, context) -> new BaseDocument((Map) context.deserialize(vpack, Map.class)); - - @SuppressWarnings("unchecked") - public static final VPackDeserializer BASE_EDGE_DOCUMENT = (parent, vpack, context) -> new BaseEdgeDocument((Map) context.deserialize(vpack, Map.class)); - - public static final VPackDeserializer DATE_STRING = (parent, vpack, context) -> { - try { - return new SimpleDateFormat(DATE_TIME_FORMAT).parse(vpack.getAsString()); - } catch (final ParseException e) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("got ParseException for date string: " + vpack.getAsString()); - } - } - return null; - }; - - public static final VPackDeserializer LOG_LEVEL = (parent, vpack, context) -> LogLevel.fromLevel(vpack.getAsInt()); - - public static final VPackDeserializer LICENSE = (parent, vpack, context) -> License.valueOf(vpack.getAsString().toUpperCase()); - - public static final VPackDeserializer PERMISSIONS = (parent, vpack, context) -> Permissions.valueOf(vpack.getAsString().toUpperCase()); - - public static final VPackDeserializer QUERY_EXECUTION_STATE = (parent, vpack, context) -> QueryExecutionState.valueOf(vpack.getAsString().toUpperCase().replaceAll(" ", "_")); - - public static final VPackDeserializer REPLICATION_FACTOR = (parent, vpack, context) -> { - final ReplicationFactor replicationFactor = new ReplicationFactor(); - if (vpack.isString() && vpack.getAsString().equals("satellite")) { - replicationFactor.setSatellite(true); - } else { - replicationFactor.setReplicationFactor(vpack.getAsInt()); - } - return replicationFactor; - }; - - public static final VPackDeserializer MIN_REPLICATION_FACTOR = (parent, vpack, context) -> { - final MinReplicationFactor minReplicationFactor = new MinReplicationFactor(); - minReplicationFactor.setMinReplicationFactor(vpack.getAsInt()); - return minReplicationFactor; - }; - - public static final VPackDeserializer VIEW_TYPE = (parent, vpack, context) -> "arangosearch".equals(vpack.getAsString()) ? ViewType.ARANGO_SEARCH - : ViewType.valueOf(vpack.getAsString().toUpperCase()); - - public static final VPackDeserializer ARANGO_SEARCH_PROPERTIES = (parent, vpack, context) -> { - final ArangoSearchProperties properties = new ArangoSearchProperties(); - final VPackSlice consolidationIntervalMsec = vpack.get("consolidationIntervalMsec"); - if (consolidationIntervalMsec.isInteger()) { - properties.setConsolidationIntervalMsec(consolidationIntervalMsec.getAsLong()); - } - - final VPackSlice commitIntervalMsec = vpack.get("commitIntervalMsec"); - if (commitIntervalMsec.isInteger()) { - properties.setCommitIntervalMsec(commitIntervalMsec.getAsLong()); - } - - final VPackSlice cleanupIntervalStep = vpack.get("cleanupIntervalStep"); - if (cleanupIntervalStep.isInteger()) { - properties.setCleanupIntervalStep(cleanupIntervalStep.getAsLong()); - } - - final VPackSlice consolidationPolicy = vpack.get("consolidationPolicy"); - if (consolidationPolicy.isObject()) { - properties.setConsolidationPolicy( - context.deserialize(consolidationPolicy, ConsolidationPolicy.class)); - } - - final VPackSlice links = vpack.get("links"); - if (links.isObject()) { - final Iterator> collectionIterator = links.objectIterator(); - for (; collectionIterator.hasNext(); ) { - final Entry entry = collectionIterator.next(); - final VPackSlice value = entry.getValue(); - final CollectionLink link = CollectionLink.on(entry.getKey()); - final VPackSlice analyzers = value.get("analyzers"); - if (analyzers.isArray()) { - final Iterator analyzerIterator = analyzers.arrayIterator(); - for (; analyzerIterator.hasNext(); ) { - link.analyzers(analyzerIterator.next().getAsString()); - } - } - final VPackSlice includeAllFields = value.get("includeAllFields"); - if (includeAllFields.isBoolean()) { - link.includeAllFields(includeAllFields.getAsBoolean()); - } - final VPackSlice trackListPositions = value.get("trackListPositions"); - if (trackListPositions.isBoolean()) { - link.trackListPositions(trackListPositions.getAsBoolean()); - } - final VPackSlice storeValues = value.get("storeValues"); - if (storeValues.isString()) { - link.storeValues(StoreValuesType.valueOf(storeValues.getAsString().toUpperCase())); - } - final VPackSlice fields = value.get("fields"); - if (fields.isObject()) { - final Iterator> fieldsIterator = fields.objectIterator(); - for (; fieldsIterator.hasNext(); ) { - link.fields(deserializeField(fieldsIterator.next())); - } - } - properties.addLink(link); - } - } - - final VPackSlice primarySorts = vpack.get("primarySort"); - if (primarySorts.isArray()) { - final Iterator primarySortsIterator = primarySorts.arrayIterator(); - for (; primarySortsIterator.hasNext(); ) { - final VPackSlice entry = primarySortsIterator.next(); - if (entry.isObject()) { - if (entry.get("field").isString() && entry.get("asc").isBoolean()) { - final PrimarySort primarySort = PrimarySort.on(entry.get("field").getAsString()); - primarySort.ascending(entry.get("asc").getAsBoolean()); - properties.addPrimarySort(primarySort); - } - } - } - } - - return properties; - }; - - protected static FieldLink deserializeField(final Entry field) { - final VPackSlice value = field.getValue(); - final FieldLink link = FieldLink.on(field.getKey()); - final VPackSlice analyzers = value.get("analyzers"); - if (analyzers.isArray()) { - final Iterator analyzerIterator = analyzers.arrayIterator(); - for (; analyzerIterator.hasNext();) { - link.analyzers(analyzerIterator.next().getAsString()); - } - } - final VPackSlice includeAllFields = value.get("includeAllFields"); - if (includeAllFields.isBoolean()) { - link.includeAllFields(includeAllFields.getAsBoolean()); - } - final VPackSlice trackListPositions = value.get("trackListPositions"); - if (trackListPositions.isBoolean()) { - link.trackListPositions(trackListPositions.getAsBoolean()); - } - final VPackSlice storeValues = value.get("storeValues"); - if (storeValues.isString()) { - link.storeValues(StoreValuesType.valueOf(storeValues.getAsString().toUpperCase())); - } - final VPackSlice fields = value.get("fields"); - if (fields.isObject()) { - final Iterator> fieldsIterator = fields.objectIterator(); - for (; fieldsIterator.hasNext();) { - link.fields(deserializeField(fieldsIterator.next())); - } - } - return link; - } - - public static final VPackDeserializer ARANGO_SEARCH_PROPERTIES_ENTITY = (parent, vpack, context) -> { - final ViewEntity entity = context.deserialize(vpack, ViewEntity.class); - final ArangoSearchProperties properties = context.deserialize(vpack, ArangoSearchProperties.class); - return new ArangoSearchPropertiesEntity(entity.getId(), - entity.getName(), entity.getType(), properties); - }; - - public static final VPackDeserializer CONSOLIDATE = (parent, vpack, context) -> { - final VPackSlice type = vpack.get("type"); - if (type.isString()) { - final ConsolidationPolicy consolidate = ConsolidationPolicy - .of(ConsolidationType.valueOf(type.getAsString().toUpperCase())); - final VPackSlice threshold = vpack.get("threshold"); - if (threshold.isNumber()) { - consolidate.threshold(threshold.getAsDouble()); - } - final VPackSlice segmentThreshold = vpack.get("segmentThreshold"); - if (segmentThreshold.isInteger()) { - consolidate.segmentThreshold(segmentThreshold.getAsLong()); - } - return consolidate; - } - return null; - }; + private static final Logger LOGGER = LoggerFactory.getLogger(VPackDeserializers.class); + private static final String DATE_TIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"; + + public static final VPackDeserializer RESPONSE = (parent, vpack, context) -> { + final Response response = new Response(); + response.setVersion(vpack.get(0).getAsInt()); + response.setType(vpack.get(1).getAsInt()); + response.setResponseCode(vpack.get(2).getAsInt()); + if (vpack.size() > 3) { + response.setMeta(context.deserialize(vpack.get(3), Map.class)); + } + return response; + }; + + public static final VPackDeserializer COLLECTION_TYPE = (parent, vpack, context) -> CollectionType.fromType(vpack.getAsInt()); + + public static final VPackDeserializer COLLECTION_STATUS = (parent, vpack, context) -> CollectionStatus.fromStatus(vpack.getAsInt()); + + @SuppressWarnings("unchecked") + public static final VPackDeserializer BASE_DOCUMENT = (parent, vpack, context) -> new BaseDocument((Map) context.deserialize(vpack, Map.class)); + + @SuppressWarnings("unchecked") + public static final VPackDeserializer BASE_EDGE_DOCUMENT = (parent, vpack, context) -> new BaseEdgeDocument((Map) context.deserialize(vpack, Map.class)); + + public static final VPackDeserializer DATE_STRING = (parent, vpack, context) -> { + try { + return new SimpleDateFormat(DATE_TIME_FORMAT).parse(vpack.getAsString()); + } catch (final ParseException e) { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("got ParseException for date string: " + vpack.getAsString()); + } + } + return null; + }; + + public static final VPackDeserializer LOG_LEVEL = (parent, vpack, context) -> LogLevel.fromLevel(vpack.getAsInt()); + + public static final VPackDeserializer LICENSE = (parent, vpack, context) -> License.valueOf(vpack.getAsString().toUpperCase()); + + public static final VPackDeserializer PERMISSIONS = (parent, vpack, context) -> Permissions.valueOf(vpack.getAsString().toUpperCase()); + + public static final VPackDeserializer QUERY_EXECUTION_STATE = (parent, vpack, context) -> QueryExecutionState.valueOf(vpack.getAsString().toUpperCase().replaceAll(" ", "_")); + + public static final VPackDeserializer REPLICATION_FACTOR = (parent, vpack, context) -> { + final ReplicationFactor replicationFactor = new ReplicationFactor(); + if (vpack.isString() && vpack.getAsString().equals("satellite")) { + replicationFactor.setSatellite(true); + } else { + replicationFactor.setReplicationFactor(vpack.getAsInt()); + } + return replicationFactor; + }; + + public static final VPackDeserializer MIN_REPLICATION_FACTOR = (parent, vpack, context) -> { + final MinReplicationFactor minReplicationFactor = new MinReplicationFactor(); + minReplicationFactor.setMinReplicationFactor(vpack.getAsInt()); + return minReplicationFactor; + }; + + public static final VPackDeserializer VIEW_TYPE = (parent, vpack, context) -> "arangosearch".equals(vpack.getAsString()) ? ViewType.ARANGO_SEARCH + : ViewType.valueOf(vpack.getAsString().toUpperCase()); + + public static final VPackDeserializer ARANGO_SEARCH_PROPERTIES = (parent, vpack, context) -> { + final ArangoSearchProperties properties = new ArangoSearchProperties(); + final VPackSlice consolidationIntervalMsec = vpack.get("consolidationIntervalMsec"); + if (consolidationIntervalMsec.isInteger()) { + properties.setConsolidationIntervalMsec(consolidationIntervalMsec.getAsLong()); + } + + final VPackSlice commitIntervalMsec = vpack.get("commitIntervalMsec"); + if (commitIntervalMsec.isInteger()) { + properties.setCommitIntervalMsec(commitIntervalMsec.getAsLong()); + } + + final VPackSlice cleanupIntervalStep = vpack.get("cleanupIntervalStep"); + if (cleanupIntervalStep.isInteger()) { + properties.setCleanupIntervalStep(cleanupIntervalStep.getAsLong()); + } + + final VPackSlice consolidationPolicy = vpack.get("consolidationPolicy"); + if (consolidationPolicy.isObject()) { + properties.setConsolidationPolicy( + context.deserialize(consolidationPolicy, ConsolidationPolicy.class)); + } + + final VPackSlice links = vpack.get("links"); + if (links.isObject()) { + final Iterator> collectionIterator = links.objectIterator(); + for (; collectionIterator.hasNext(); ) { + final Entry entry = collectionIterator.next(); + final VPackSlice value = entry.getValue(); + final CollectionLink link = CollectionLink.on(entry.getKey()); + final VPackSlice analyzers = value.get("analyzers"); + if (analyzers.isArray()) { + final Iterator analyzerIterator = analyzers.arrayIterator(); + for (; analyzerIterator.hasNext(); ) { + link.analyzers(analyzerIterator.next().getAsString()); + } + } + final VPackSlice includeAllFields = value.get("includeAllFields"); + if (includeAllFields.isBoolean()) { + link.includeAllFields(includeAllFields.getAsBoolean()); + } + final VPackSlice trackListPositions = value.get("trackListPositions"); + if (trackListPositions.isBoolean()) { + link.trackListPositions(trackListPositions.getAsBoolean()); + } + final VPackSlice storeValues = value.get("storeValues"); + if (storeValues.isString()) { + link.storeValues(StoreValuesType.valueOf(storeValues.getAsString().toUpperCase())); + } + final VPackSlice fields = value.get("fields"); + if (fields.isObject()) { + final Iterator> fieldsIterator = fields.objectIterator(); + for (; fieldsIterator.hasNext(); ) { + link.fields(deserializeField(fieldsIterator.next())); + } + } + properties.addLink(link); + } + } + + final VPackSlice primarySorts = vpack.get("primarySort"); + if (primarySorts.isArray()) { + final Iterator primarySortsIterator = primarySorts.arrayIterator(); + for (; primarySortsIterator.hasNext(); ) { + final VPackSlice entry = primarySortsIterator.next(); + if (entry.isObject()) { + if (entry.get("field").isString() && entry.get("asc").isBoolean()) { + final PrimarySort primarySort = PrimarySort.on(entry.get("field").getAsString()); + primarySort.ascending(entry.get("asc").getAsBoolean()); + properties.addPrimarySort(primarySort); + } + } + } + } + + return properties; + }; + + protected static FieldLink deserializeField(final Entry field) { + final VPackSlice value = field.getValue(); + final FieldLink link = FieldLink.on(field.getKey()); + final VPackSlice analyzers = value.get("analyzers"); + if (analyzers.isArray()) { + final Iterator analyzerIterator = analyzers.arrayIterator(); + for (; analyzerIterator.hasNext(); ) { + link.analyzers(analyzerIterator.next().getAsString()); + } + } + final VPackSlice includeAllFields = value.get("includeAllFields"); + if (includeAllFields.isBoolean()) { + link.includeAllFields(includeAllFields.getAsBoolean()); + } + final VPackSlice trackListPositions = value.get("trackListPositions"); + if (trackListPositions.isBoolean()) { + link.trackListPositions(trackListPositions.getAsBoolean()); + } + final VPackSlice storeValues = value.get("storeValues"); + if (storeValues.isString()) { + link.storeValues(StoreValuesType.valueOf(storeValues.getAsString().toUpperCase())); + } + final VPackSlice fields = value.get("fields"); + if (fields.isObject()) { + final Iterator> fieldsIterator = fields.objectIterator(); + for (; fieldsIterator.hasNext(); ) { + link.fields(deserializeField(fieldsIterator.next())); + } + } + return link; + } + + public static final VPackDeserializer ARANGO_SEARCH_PROPERTIES_ENTITY = (parent, vpack, context) -> { + final ViewEntity entity = context.deserialize(vpack, ViewEntity.class); + final ArangoSearchProperties properties = context.deserialize(vpack, ArangoSearchProperties.class); + return new ArangoSearchPropertiesEntity(entity.getId(), + entity.getName(), entity.getType(), properties); + }; + + public static final VPackDeserializer CONSOLIDATE = (parent, vpack, context) -> { + final VPackSlice type = vpack.get("type"); + if (type.isString()) { + final ConsolidationPolicy consolidate = ConsolidationPolicy + .of(ConsolidationType.valueOf(type.getAsString().toUpperCase())); + final VPackSlice threshold = vpack.get("threshold"); + if (threshold.isNumber()) { + consolidate.threshold(threshold.getAsDouble()); + } + final VPackSlice segmentThreshold = vpack.get("segmentThreshold"); + if (segmentThreshold.isInteger()) { + consolidate.segmentThreshold(segmentThreshold.getAsLong()); + } + return consolidate; + } + return null; + }; } diff --git a/src/main/java/com/arangodb/internal/velocypack/VPackDriverModule.java b/src/main/java/com/arangodb/internal/velocypack/VPackDriverModule.java index 23a0a9796..3a3e5aa7b 100644 --- a/src/main/java/com/arangodb/internal/velocypack/VPackDriverModule.java +++ b/src/main/java/com/arangodb/internal/velocypack/VPackDriverModule.java @@ -39,55 +39,54 @@ /** * @author Mark Vollmary - * */ public class VPackDriverModule implements VPackModule, VPackParserModule { - @Override - public > void setup(final C context) { - context.fieldNamingStrategy(field -> { - final DocumentField annotation = field.getAnnotation(DocumentField.class); - if (annotation != null) { - return annotation.value().getSerializeName(); - } - return field.getName(); - }); - context.registerSerializer(Request.class, VPackSerializers.REQUEST); - context.registerSerializer(AuthenticationRequest.class, VPackSerializers.AUTH_REQUEST); - context.registerSerializer(CollectionType.class, VPackSerializers.COLLECTION_TYPE); - context.registerSerializer(BaseDocument.class, VPackSerializers.BASE_DOCUMENT); - context.registerSerializer(BaseEdgeDocument.class, VPackSerializers.BASE_EDGE_DOCUMENT); - context.registerSerializer(TraversalOptions.Order.class, VPackSerializers.TRAVERSAL_ORDER); - context.registerSerializer(LogLevel.class, VPackSerializers.LOG_LEVEL); - context.registerSerializer(Permissions.class, VPackSerializers.PERMISSIONS); - context.registerSerializer(ReplicationFactor.class, VPackSerializers.REPLICATION_FACTOR); - context.registerSerializer(MinReplicationFactor.class, VPackSerializers.MIN_REPLICATION_FACTOR); - context.registerSerializer(ViewType.class, VPackSerializers.VIEW_TYPE); - context.registerSerializer(ArangoSearchPropertiesOptions.class, VPackSerializers.ARANGO_SEARCH_PROPERTIES_OPTIONS); - context.registerSerializer(ArangoSearchProperties.class, VPackSerializers.ARANGO_SEARCH_PROPERTIES); - context.registerSerializer(ConsolidationType.class, VPackSerializers.CONSOLIDATE_TYPE); + @Override + public > void setup(final C context) { + context.fieldNamingStrategy(field -> { + final DocumentField annotation = field.getAnnotation(DocumentField.class); + if (annotation != null) { + return annotation.value().getSerializeName(); + } + return field.getName(); + }); + context.registerSerializer(Request.class, VPackSerializers.REQUEST); + context.registerSerializer(AuthenticationRequest.class, VPackSerializers.AUTH_REQUEST); + context.registerSerializer(CollectionType.class, VPackSerializers.COLLECTION_TYPE); + context.registerSerializer(BaseDocument.class, VPackSerializers.BASE_DOCUMENT); + context.registerSerializer(BaseEdgeDocument.class, VPackSerializers.BASE_EDGE_DOCUMENT); + context.registerSerializer(TraversalOptions.Order.class, VPackSerializers.TRAVERSAL_ORDER); + context.registerSerializer(LogLevel.class, VPackSerializers.LOG_LEVEL); + context.registerSerializer(Permissions.class, VPackSerializers.PERMISSIONS); + context.registerSerializer(ReplicationFactor.class, VPackSerializers.REPLICATION_FACTOR); + context.registerSerializer(MinReplicationFactor.class, VPackSerializers.MIN_REPLICATION_FACTOR); + context.registerSerializer(ViewType.class, VPackSerializers.VIEW_TYPE); + context.registerSerializer(ArangoSearchPropertiesOptions.class, VPackSerializers.ARANGO_SEARCH_PROPERTIES_OPTIONS); + context.registerSerializer(ArangoSearchProperties.class, VPackSerializers.ARANGO_SEARCH_PROPERTIES); + context.registerSerializer(ConsolidationType.class, VPackSerializers.CONSOLIDATE_TYPE); - context.registerDeserializer(Response.class, VPackDeserializers.RESPONSE); - context.registerDeserializer(CollectionType.class, VPackDeserializers.COLLECTION_TYPE); - context.registerDeserializer(CollectionStatus.class, VPackDeserializers.COLLECTION_STATUS); - context.registerDeserializer(BaseDocument.class, VPackDeserializers.BASE_DOCUMENT); - context.registerDeserializer(BaseEdgeDocument.class, VPackDeserializers.BASE_EDGE_DOCUMENT); - context.registerDeserializer(QueryEntity.PROPERTY_STARTED, Date.class, VPackDeserializers.DATE_STRING); - context.registerDeserializer(LogLevel.class, VPackDeserializers.LOG_LEVEL); - context.registerDeserializer(License.class, VPackDeserializers.LICENSE); - context.registerDeserializer(Permissions.class, VPackDeserializers.PERMISSIONS); - context.registerDeserializer(QueryExecutionState.class, VPackDeserializers.QUERY_EXECUTION_STATE); - context.registerDeserializer(ReplicationFactor.class, VPackDeserializers.REPLICATION_FACTOR); - context.registerDeserializer(MinReplicationFactor.class, VPackDeserializers.MIN_REPLICATION_FACTOR); - context.registerDeserializer(ViewType.class, VPackDeserializers.VIEW_TYPE); - context.registerDeserializer(ArangoSearchProperties.class, VPackDeserializers.ARANGO_SEARCH_PROPERTIES); - context.registerDeserializer(ArangoSearchPropertiesEntity.class, VPackDeserializers.ARANGO_SEARCH_PROPERTIES_ENTITY); - context.registerDeserializer(ConsolidationPolicy.class, VPackDeserializers.CONSOLIDATE); - } + context.registerDeserializer(Response.class, VPackDeserializers.RESPONSE); + context.registerDeserializer(CollectionType.class, VPackDeserializers.COLLECTION_TYPE); + context.registerDeserializer(CollectionStatus.class, VPackDeserializers.COLLECTION_STATUS); + context.registerDeserializer(BaseDocument.class, VPackDeserializers.BASE_DOCUMENT); + context.registerDeserializer(BaseEdgeDocument.class, VPackDeserializers.BASE_EDGE_DOCUMENT); + context.registerDeserializer(QueryEntity.PROPERTY_STARTED, Date.class, VPackDeserializers.DATE_STRING); + context.registerDeserializer(LogLevel.class, VPackDeserializers.LOG_LEVEL); + context.registerDeserializer(License.class, VPackDeserializers.LICENSE); + context.registerDeserializer(Permissions.class, VPackDeserializers.PERMISSIONS); + context.registerDeserializer(QueryExecutionState.class, VPackDeserializers.QUERY_EXECUTION_STATE); + context.registerDeserializer(ReplicationFactor.class, VPackDeserializers.REPLICATION_FACTOR); + context.registerDeserializer(MinReplicationFactor.class, VPackDeserializers.MIN_REPLICATION_FACTOR); + context.registerDeserializer(ViewType.class, VPackDeserializers.VIEW_TYPE); + context.registerDeserializer(ArangoSearchProperties.class, VPackDeserializers.ARANGO_SEARCH_PROPERTIES); + context.registerDeserializer(ArangoSearchPropertiesEntity.class, VPackDeserializers.ARANGO_SEARCH_PROPERTIES_ENTITY); + context.registerDeserializer(ConsolidationPolicy.class, VPackDeserializers.CONSOLIDATE); + } - @Override - public > void setup(final C context) { + @Override + public > void setup(final C context) { - } + } } diff --git a/src/main/java/com/arangodb/internal/velocystream/VstCommunication.java b/src/main/java/com/arangodb/internal/velocystream/VstCommunication.java index 5e8436ca5..b83257fd3 100644 --- a/src/main/java/com/arangodb/internal/velocystream/VstCommunication.java +++ b/src/main/java/com/arangodb/internal/velocystream/VstCommunication.java @@ -46,135 +46,134 @@ /** * @author Mark Vollmary - * */ public abstract class VstCommunication implements Closeable { - protected static final String ENCRYPTION_PLAIN = "plain"; - private static final Logger LOGGER = LoggerFactory.getLogger(VstCommunication.class); - - protected static final AtomicLong mId = new AtomicLong(0L); - protected final ArangoSerialization util; - - protected final String user; - protected final String password; - - protected final Integer chunksize; - private final HostHandler hostHandler; - - protected VstCommunication(final Integer timeout, final String user, final String password, final Boolean useSsl, - final SSLContext sslContext, final ArangoSerialization util, final Integer chunksize, - final HostHandler hostHandler) { - this.user = user; - this.password = password; - this.util = util; - this.hostHandler = hostHandler; - this.chunksize = chunksize != null ? chunksize : ArangoDefaults.CHUNK_DEFAULT_CONTENT_SIZE; - } - - @SuppressWarnings("unchecked") - protected synchronized C connect(final HostHandle hostHandle, final AccessType accessType) { - Host host = hostHandler.get(hostHandle, accessType); - while (true) { - if (host == null) { - hostHandler.reset(); - throw new ArangoDBException("Was not able to connect to any host"); - } - final C connection = (C) host.connection(); - if (connection.isOpen()) { - return connection; - } else { - try { - connection.open(); - hostHandler.success(); - if (user != null) { - authenticate(connection); - } - hostHandler.confirm(); - return connection; - } catch (final IOException e) { - hostHandler.fail(); - if (hostHandle != null && hostHandle.getHost() != null) { - hostHandle.setHost(null); - } - final Host failedHost = host; - host = hostHandler.get(hostHandle, accessType); - if (host != null) { - LOGGER.warn( - String.format("Could not connect to %s or SSL Handshake failed. Try connecting to %s", - failedHost.getDescription(), host.getDescription())); - } else { - LOGGER.error(e.getMessage(), e); - throw new ArangoDBException(e); - } - } - } - } - } - - protected abstract void authenticate(final C connection); - - @Override - public void close() throws IOException { - hostHandler.close(); - } - - public R execute(final Request request, final HostHandle hostHandle) throws ArangoDBException { - try { - final C connection = connect(hostHandle, RequestUtils.determineAccessType(request)); - return execute(request, connection); - } catch (final ArangoDBException e) { - if (e instanceof ArangoDBRedirectException) { + protected static final String ENCRYPTION_PLAIN = "plain"; + private static final Logger LOGGER = LoggerFactory.getLogger(VstCommunication.class); + + protected static final AtomicLong mId = new AtomicLong(0L); + protected final ArangoSerialization util; + + protected final String user; + protected final String password; + + protected final Integer chunksize; + private final HostHandler hostHandler; + + protected VstCommunication(final Integer timeout, final String user, final String password, final Boolean useSsl, + final SSLContext sslContext, final ArangoSerialization util, final Integer chunksize, + final HostHandler hostHandler) { + this.user = user; + this.password = password; + this.util = util; + this.hostHandler = hostHandler; + this.chunksize = chunksize != null ? chunksize : ArangoDefaults.CHUNK_DEFAULT_CONTENT_SIZE; + } + + @SuppressWarnings("unchecked") + protected synchronized C connect(final HostHandle hostHandle, final AccessType accessType) { + Host host = hostHandler.get(hostHandle, accessType); + while (true) { + if (host == null) { + hostHandler.reset(); + throw new ArangoDBException("Was not able to connect to any host"); + } + final C connection = (C) host.connection(); + if (connection.isOpen()) { + return connection; + } else { + try { + connection.open(); + hostHandler.success(); + if (user != null) { + authenticate(connection); + } + hostHandler.confirm(); + return connection; + } catch (final IOException e) { + hostHandler.fail(); + if (hostHandle != null && hostHandle.getHost() != null) { + hostHandle.setHost(null); + } + final Host failedHost = host; + host = hostHandler.get(hostHandle, accessType); + if (host != null) { + LOGGER.warn( + String.format("Could not connect to %s or SSL Handshake failed. Try connecting to %s", + failedHost.getDescription(), host.getDescription())); + } else { + LOGGER.error(e.getMessage(), e); + throw new ArangoDBException(e); + } + } + } + } + } + + protected abstract void authenticate(final C connection); + + @Override + public void close() throws IOException { + hostHandler.close(); + } + + public R execute(final Request request, final HostHandle hostHandle) throws ArangoDBException { + try { + final C connection = connect(hostHandle, RequestUtils.determineAccessType(request)); + return execute(request, connection); + } catch (final ArangoDBException e) { + if (e instanceof ArangoDBRedirectException) { final String location = ((ArangoDBRedirectException) e).getLocation(); - final HostDescription redirectHost = HostUtils.createFromLocation(location); - hostHandler.closeCurrentOnError(); - hostHandler.fail(); - return execute(request, new HostHandle().setHost(redirectHost)); - } else { - throw e; - } - } - } - - protected abstract R execute(final Request request, C connection) throws ArangoDBException; - - protected void checkError(final Response response) throws ArangoDBException { - ResponseUtils.checkError(util, response); - } - - protected Response createResponse(final Message message) throws VPackParserException { - final Response response = util.deserialize(message.getHead(), Response.class); - if (message.getBody() != null) { - response.setBody(message.getBody()); - } - return response; - } - - protected Message createMessage(final Request request) throws VPackParserException { - final long id = mId.incrementAndGet(); - return new Message(id, util.serialize(request), request.getBody()); - } - - protected Collection buildChunks(final Message message) { + final HostDescription redirectHost = HostUtils.createFromLocation(location); + hostHandler.closeCurrentOnError(); + hostHandler.fail(); + return execute(request, new HostHandle().setHost(redirectHost)); + } else { + throw e; + } + } + } + + protected abstract R execute(final Request request, C connection) throws ArangoDBException; + + protected void checkError(final Response response) throws ArangoDBException { + ResponseUtils.checkError(util, response); + } + + protected Response createResponse(final Message message) throws VPackParserException { + final Response response = util.deserialize(message.getHead(), Response.class); + if (message.getBody() != null) { + response.setBody(message.getBody()); + } + return response; + } + + protected Message createMessage(final Request request) throws VPackParserException { + final long id = mId.incrementAndGet(); + return new Message(id, util.serialize(request), request.getBody()); + } + + protected Collection buildChunks(final Message message) { final Collection chunks = new ArrayList<>(); - final VPackSlice head = message.getHead(); - int size = head.getByteSize(); - final VPackSlice body = message.getBody(); - if (body != null) { - size += body.getByteSize(); - } - final int n = size / chunksize; - final int numberOfChunks = (size % chunksize != 0) ? (n + 1) : n; - int off = 0; - for (int i = 0; size > 0; i++) { - final int len = Math.min(chunksize, size); - final long messageLength = (i == 0 && numberOfChunks > 1) ? size : -1L; - final Chunk chunk = new Chunk(message.getId(), i, numberOfChunks, messageLength, off, len); - size -= len; - off += len; - chunks.add(chunk); - } - return chunks; - } + final VPackSlice head = message.getHead(); + int size = head.getByteSize(); + final VPackSlice body = message.getBody(); + if (body != null) { + size += body.getByteSize(); + } + final int n = size / chunksize; + final int numberOfChunks = (size % chunksize != 0) ? (n + 1) : n; + int off = 0; + for (int i = 0; size > 0; i++) { + final int len = Math.min(chunksize, size); + final long messageLength = (i == 0 && numberOfChunks > 1) ? size : -1L; + final Chunk chunk = new Chunk(message.getId(), i, numberOfChunks, messageLength, off, len); + size -= len; + off += len; + chunks.add(chunk); + } + return chunks; + } } diff --git a/src/main/java/com/arangodb/internal/velocystream/VstCommunicationSync.java b/src/main/java/com/arangodb/internal/velocystream/VstCommunicationSync.java index 04c4536cd..9cb8472df 100644 --- a/src/main/java/com/arangodb/internal/velocystream/VstCommunicationSync.java +++ b/src/main/java/com/arangodb/internal/velocystream/VstCommunicationSync.java @@ -20,131 +20,129 @@ package com.arangodb.internal.velocystream; -import javax.net.ssl.SSLContext; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import com.arangodb.ArangoDBException; import com.arangodb.internal.net.HostHandler; import com.arangodb.internal.velocystream.internal.AuthenticationRequest; -import com.arangodb.internal.velocystream.internal.VstConnectionSync; import com.arangodb.internal.velocystream.internal.Message; +import com.arangodb.internal.velocystream.internal.VstConnectionSync; import com.arangodb.util.ArangoSerialization; import com.arangodb.velocypack.exception.VPackParserException; import com.arangodb.velocystream.Request; import com.arangodb.velocystream.Response; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.net.ssl.SSLContext; /** * @author Mark Vollmary - * */ public class VstCommunicationSync extends VstCommunication { - private static final Logger LOGGER = LoggerFactory.getLogger(VstCommunicationSync.class); - - public static class Builder { - - private final HostHandler hostHandler; - private Integer timeout; - private Long connectionTtl; - private String user; - private String password; - private Boolean useSsl; - private SSLContext sslContext; - private Integer chunksize; - private Integer maxConnections; - - public Builder(final HostHandler hostHandler) { - super(); - this.hostHandler = hostHandler; - } - - public Builder(final Builder builder) { - this(builder.hostHandler); - timeout(builder.timeout).user(builder.user).password(builder.password).useSsl(builder.useSsl) - .sslContext(builder.sslContext).chunksize(builder.chunksize).maxConnections(builder.maxConnections); - } - - public Builder timeout(final Integer timeout) { - this.timeout = timeout; - return this; - } - - public Builder user(final String user) { - this.user = user; - return this; - } - - public Builder password(final String password) { - this.password = password; - return this; - } - - public Builder useSsl(final Boolean useSsl) { - this.useSsl = useSsl; - return this; - } - - public Builder sslContext(final SSLContext sslContext) { - this.sslContext = sslContext; - return this; - } - - public Builder chunksize(final Integer chunksize) { - this.chunksize = chunksize; - return this; - } - - public Builder maxConnections(final Integer maxConnections) { - this.maxConnections = maxConnections; - return this; - } - - public Builder connectionTtl(final Long connectionTtl) { - this.connectionTtl = connectionTtl; - return this; - } - - public VstCommunication build(final ArangoSerialization util) { - return new VstCommunicationSync(hostHandler, timeout, user, password, useSsl, sslContext, util, chunksize, - maxConnections, connectionTtl); - } - - } - - protected VstCommunicationSync(final HostHandler hostHandler, final Integer timeout, final String user, - final String password, final Boolean useSsl, final SSLContext sslContext, final ArangoSerialization util, - final Integer chunksize, final Integer maxConnections, final Long ttl) { - super(timeout, user, password, useSsl, sslContext, util, chunksize, hostHandler); - } - - @Override - protected Response execute(final Request request, final VstConnectionSync connection) throws ArangoDBException { - try { - final Message requestMessage = createMessage(request); - final Message responseMessage = send(requestMessage, connection); - final Response response = createResponse(responseMessage); - checkError(response); - return response; - } catch (final VPackParserException e) { - throw new ArangoDBException(e); - } - } - - private Message send(final Message message, final VstConnectionSync connection) throws ArangoDBException { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug(String.format("Send Message (id=%s, head=%s, body=%s)", message.getId(), message.getHead(), - message.getBody() != null ? message.getBody() : "{}")); - } - return connection.write(message, buildChunks(message)); - } - - @Override - protected void authenticate(final VstConnectionSync connection) { - final Response response = execute( - new AuthenticationRequest(user, password != null ? password : "", ENCRYPTION_PLAIN), connection); - checkError(response); - } + private static final Logger LOGGER = LoggerFactory.getLogger(VstCommunicationSync.class); + + public static class Builder { + + private final HostHandler hostHandler; + private Integer timeout; + private Long connectionTtl; + private String user; + private String password; + private Boolean useSsl; + private SSLContext sslContext; + private Integer chunksize; + private Integer maxConnections; + + public Builder(final HostHandler hostHandler) { + super(); + this.hostHandler = hostHandler; + } + + public Builder(final Builder builder) { + this(builder.hostHandler); + timeout(builder.timeout).user(builder.user).password(builder.password).useSsl(builder.useSsl) + .sslContext(builder.sslContext).chunksize(builder.chunksize).maxConnections(builder.maxConnections); + } + + public Builder timeout(final Integer timeout) { + this.timeout = timeout; + return this; + } + + public Builder user(final String user) { + this.user = user; + return this; + } + + public Builder password(final String password) { + this.password = password; + return this; + } + + public Builder useSsl(final Boolean useSsl) { + this.useSsl = useSsl; + return this; + } + + public Builder sslContext(final SSLContext sslContext) { + this.sslContext = sslContext; + return this; + } + + public Builder chunksize(final Integer chunksize) { + this.chunksize = chunksize; + return this; + } + + public Builder maxConnections(final Integer maxConnections) { + this.maxConnections = maxConnections; + return this; + } + + public Builder connectionTtl(final Long connectionTtl) { + this.connectionTtl = connectionTtl; + return this; + } + + public VstCommunication build(final ArangoSerialization util) { + return new VstCommunicationSync(hostHandler, timeout, user, password, useSsl, sslContext, util, chunksize, + maxConnections, connectionTtl); + } + + } + + protected VstCommunicationSync(final HostHandler hostHandler, final Integer timeout, final String user, + final String password, final Boolean useSsl, final SSLContext sslContext, final ArangoSerialization util, + final Integer chunksize, final Integer maxConnections, final Long ttl) { + super(timeout, user, password, useSsl, sslContext, util, chunksize, hostHandler); + } + + @Override + protected Response execute(final Request request, final VstConnectionSync connection) throws ArangoDBException { + try { + final Message requestMessage = createMessage(request); + final Message responseMessage = send(requestMessage, connection); + final Response response = createResponse(responseMessage); + checkError(response); + return response; + } catch (final VPackParserException e) { + throw new ArangoDBException(e); + } + } + + private Message send(final Message message, final VstConnectionSync connection) throws ArangoDBException { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug(String.format("Send Message (id=%s, head=%s, body=%s)", message.getId(), message.getHead(), + message.getBody() != null ? message.getBody() : "{}")); + } + return connection.write(message, buildChunks(message)); + } + + @Override + protected void authenticate(final VstConnectionSync connection) { + final Response response = execute( + new AuthenticationRequest(user, password != null ? password : "", ENCRYPTION_PLAIN), connection); + checkError(response); + } } diff --git a/src/main/java/com/arangodb/internal/velocystream/VstConnectionFactorySync.java b/src/main/java/com/arangodb/internal/velocystream/VstConnectionFactorySync.java index 022edac2d..2f6a279da 100644 --- a/src/main/java/com/arangodb/internal/velocystream/VstConnectionFactorySync.java +++ b/src/main/java/com/arangodb/internal/velocystream/VstConnectionFactorySync.java @@ -20,32 +20,31 @@ package com.arangodb.internal.velocystream; -import javax.net.ssl.SSLContext; - import com.arangodb.internal.net.Connection; import com.arangodb.internal.net.ConnectionFactory; import com.arangodb.internal.net.HostDescription; import com.arangodb.internal.velocystream.internal.MessageStore; import com.arangodb.internal.velocystream.internal.VstConnectionSync; +import javax.net.ssl.SSLContext; + /** * @author Mark Vollmary - * */ public class VstConnectionFactorySync implements ConnectionFactory { - private final VstConnectionSync.Builder builder; + private final VstConnectionSync.Builder builder; - public VstConnectionFactorySync(final HostDescription host, final Integer timeout, final Long connectionTtl, - final Boolean useSsl, final SSLContext sslContext) { - super(); - builder = new VstConnectionSync.Builder().timeout(timeout).ttl(connectionTtl).useSsl(useSsl) - .sslContext(sslContext); - } + public VstConnectionFactorySync(final HostDescription host, final Integer timeout, final Long connectionTtl, + final Boolean useSsl, final SSLContext sslContext) { + super(); + builder = new VstConnectionSync.Builder().timeout(timeout).ttl(connectionTtl).useSsl(useSsl) + .sslContext(sslContext); + } - @Override - public Connection create(final HostDescription host) { - return builder.messageStore(new MessageStore()).host(host).build(); - } + @Override + public Connection create(final HostDescription host) { + return builder.messageStore(new MessageStore()).host(host).build(); + } } diff --git a/src/main/java/com/arangodb/internal/velocystream/VstProtocol.java b/src/main/java/com/arangodb/internal/velocystream/VstProtocol.java index b33b24373..3a5d67352 100644 --- a/src/main/java/com/arangodb/internal/velocystream/VstProtocol.java +++ b/src/main/java/com/arangodb/internal/velocystream/VstProtocol.java @@ -20,8 +20,6 @@ package com.arangodb.internal.velocystream; -import java.io.IOException; - import com.arangodb.ArangoDBException; import com.arangodb.internal.net.CommunicationProtocol; import com.arangodb.internal.net.HostHandle; @@ -29,27 +27,28 @@ import com.arangodb.velocystream.Request; import com.arangodb.velocystream.Response; +import java.io.IOException; + /** * @author Mark Vollmary - * */ public class VstProtocol implements CommunicationProtocol { - private final VstCommunication communication; + private final VstCommunication communication; - public VstProtocol(final VstCommunication communication) { - super(); - this.communication = communication; - } + public VstProtocol(final VstCommunication communication) { + super(); + this.communication = communication; + } - @Override - public Response execute(final Request request, final HostHandle hostHandle) throws ArangoDBException { - return communication.execute(request, hostHandle); - } + @Override + public Response execute(final Request request, final HostHandle hostHandle) throws ArangoDBException { + return communication.execute(request, hostHandle); + } - @Override - public void close() throws IOException { - communication.close(); - } + @Override + public void close() throws IOException { + communication.close(); + } } diff --git a/src/main/java/com/arangodb/internal/velocystream/internal/AuthenticationRequest.java b/src/main/java/com/arangodb/internal/velocystream/internal/AuthenticationRequest.java index 536c85626..550329d32 100644 --- a/src/main/java/com/arangodb/internal/velocystream/internal/AuthenticationRequest.java +++ b/src/main/java/com/arangodb/internal/velocystream/internal/AuthenticationRequest.java @@ -24,32 +24,31 @@ /** * @author Mark Vollmary - * */ public class AuthenticationRequest extends Request { - private final String user; - private final String password; - private final String encryption;// "plain" - - public AuthenticationRequest(final String user, final String password, final String encryption) { - super(null, null, null); - this.user = user; - this.password = password; - this.encryption = encryption; - setType(1000); - } - - public String getUser() { - return user; - } - - public String getPassword() { - return password; - } - - public String getEncryption() { - return encryption; - } + private final String user; + private final String password; + private final String encryption;// "plain" + + public AuthenticationRequest(final String user, final String password, final String encryption) { + super(null, null, null); + this.user = user; + this.password = password; + this.encryption = encryption; + setType(1000); + } + + public String getUser() { + return user; + } + + public String getPassword() { + return password; + } + + public String getEncryption() { + return encryption; + } } diff --git a/src/main/java/com/arangodb/internal/velocystream/internal/Chunk.java b/src/main/java/com/arangodb/internal/velocystream/internal/Chunk.java index 814362893..4b0689e93 100644 --- a/src/main/java/com/arangodb/internal/velocystream/internal/Chunk.java +++ b/src/main/java/com/arangodb/internal/velocystream/internal/Chunk.java @@ -22,68 +22,67 @@ /** * @author Mark Vollmary - * */ public class Chunk { - private final long messageId; - private final long messageLength; - private final int chunkX; - private final int contentOffset; - private final int contentLength; + private final long messageId; + private final long messageLength; + private final int chunkX; + private final int contentOffset; + private final int contentLength; - public Chunk(final long messageId, final int chunkX, final long messageLength, final int contentOffset, - final int contentLength) { - this.messageId = messageId; - this.chunkX = chunkX; - this.messageLength = messageLength; - this.contentOffset = contentOffset; - this.contentLength = contentLength; - } + public Chunk(final long messageId, final int chunkX, final long messageLength, final int contentOffset, + final int contentLength) { + this.messageId = messageId; + this.chunkX = chunkX; + this.messageLength = messageLength; + this.contentOffset = contentOffset; + this.contentLength = contentLength; + } - public Chunk(final long messageId, final int chunkIndex, final int numberOfChunks, final long messageLength, - final int contentOffset, final int contentLength) { - this(messageId, chunkX(chunkIndex, numberOfChunks), messageLength, contentOffset, contentLength); - } + public Chunk(final long messageId, final int chunkIndex, final int numberOfChunks, final long messageLength, + final int contentOffset, final int contentLength) { + this(messageId, chunkX(chunkIndex, numberOfChunks), messageLength, contentOffset, contentLength); + } - private static int chunkX(final int chunkIndex, final int numberOfChunks) { - int chunkX; - if (numberOfChunks == 1) { - chunkX = 3;// last byte: 0000 0011 - } else if (chunkIndex == 0) { - chunkX = (numberOfChunks << 1) + 1; - } else { - chunkX = chunkIndex << 1; - } - return chunkX; - } + private static int chunkX(final int chunkIndex, final int numberOfChunks) { + int chunkX; + if (numberOfChunks == 1) { + chunkX = 3;// last byte: 0000 0011 + } else if (chunkIndex == 0) { + chunkX = (numberOfChunks << 1) + 1; + } else { + chunkX = chunkIndex << 1; + } + return chunkX; + } - public long getMessageId() { - return messageId; - } + public long getMessageId() { + return messageId; + } - public long getMessageLength() { - return messageLength; - } + public long getMessageLength() { + return messageLength; + } - public boolean isFirstChunk() { - return 1 == (chunkX & 0x1); - } + public boolean isFirstChunk() { + return 1 == (chunkX & 0x1); + } - public int getChunk() { - return chunkX >> 1; - } + public int getChunk() { + return chunkX >> 1; + } - public int getChunkX() { - return chunkX; - } + public int getChunkX() { + return chunkX; + } - public int getContentOffset() { - return contentOffset; - } + public int getContentOffset() { + return contentOffset; + } - public int getContentLength() { - return contentLength; - } + public int getContentLength() { + return contentLength; + } } diff --git a/src/main/java/com/arangodb/internal/velocystream/internal/ChunkStore.java b/src/main/java/com/arangodb/internal/velocystream/internal/ChunkStore.java index 0b78fe5eb..e636b9e68 100644 --- a/src/main/java/com/arangodb/internal/velocystream/internal/ChunkStore.java +++ b/src/main/java/com/arangodb/internal/velocystream/internal/ChunkStore.java @@ -27,45 +27,44 @@ /** * @author Mark Vollmary - * */ public class ChunkStore { - private final MessageStore messageStore; - private final Map data; + private final MessageStore messageStore; + private final Map data; - public ChunkStore(final MessageStore messageStore) { - super(); - this.messageStore = messageStore; - data = new HashMap<>(); - } + public ChunkStore(final MessageStore messageStore) { + super(); + this.messageStore = messageStore; + data = new HashMap<>(); + } - public ByteBuffer storeChunk(final Chunk chunk) throws BufferUnderflowException, IndexOutOfBoundsException { - final long messageId = chunk.getMessageId(); - ByteBuffer chunkBuffer = data.get(messageId); - if (chunkBuffer == null) { - if (!chunk.isFirstChunk()) { - messageStore.cancel(messageId); - return null; - } - final int length = (int) (chunk.getMessageLength() > 0 ? chunk.getMessageLength() - : chunk.getContentLength()); - chunkBuffer = ByteBuffer.allocate(length); - data.put(messageId, chunkBuffer); - } - return chunkBuffer; - } + public ByteBuffer storeChunk(final Chunk chunk) throws BufferUnderflowException, IndexOutOfBoundsException { + final long messageId = chunk.getMessageId(); + ByteBuffer chunkBuffer = data.get(messageId); + if (chunkBuffer == null) { + if (!chunk.isFirstChunk()) { + messageStore.cancel(messageId); + return null; + } + final int length = (int) (chunk.getMessageLength() > 0 ? chunk.getMessageLength() + : chunk.getContentLength()); + chunkBuffer = ByteBuffer.allocate(length); + data.put(messageId, chunkBuffer); + } + return chunkBuffer; + } - public void checkCompleteness(final long messageId) { - checkCompleteness(messageId, data.get(messageId)); - } + public void checkCompleteness(final long messageId) { + checkCompleteness(messageId, data.get(messageId)); + } - private void checkCompleteness(final long messageId, final ByteBuffer chunkBuffer) - throws BufferUnderflowException, IndexOutOfBoundsException { - if (chunkBuffer.position() == chunkBuffer.limit()) { - messageStore.consume(new Message(messageId, chunkBuffer.array())); - data.remove(messageId); - } - } + private void checkCompleteness(final long messageId, final ByteBuffer chunkBuffer) + throws BufferUnderflowException, IndexOutOfBoundsException { + if (chunkBuffer.position() == chunkBuffer.limit()) { + messageStore.consume(new Message(messageId, chunkBuffer.array())); + data.remove(messageId); + } + } } diff --git a/src/main/java/com/arangodb/internal/velocystream/internal/Message.java b/src/main/java/com/arangodb/internal/velocystream/internal/Message.java index d0a5cac99..6ad13259c 100644 --- a/src/main/java/com/arangodb/internal/velocystream/internal/Message.java +++ b/src/main/java/com/arangodb/internal/velocystream/internal/Message.java @@ -20,49 +20,48 @@ package com.arangodb.internal.velocystream.internal; -import java.nio.BufferUnderflowException; - import com.arangodb.velocypack.VPackSlice; +import java.nio.BufferUnderflowException; + /** * @author Mark Vollmary - * */ public class Message { - private final long id; - private final VPackSlice head; - private final VPackSlice body; + private final long id; + private final VPackSlice head; + private final VPackSlice body; - public Message(final long id, final byte[] chunkBuffer) throws BufferUnderflowException, IndexOutOfBoundsException { - super(); - this.id = id; - head = new VPackSlice(chunkBuffer); - final int headSize = head.getByteSize(); - if (chunkBuffer.length > headSize) { - body = new VPackSlice(chunkBuffer, headSize); - } else { - body = null; - } - } + public Message(final long id, final byte[] chunkBuffer) throws BufferUnderflowException, IndexOutOfBoundsException { + super(); + this.id = id; + head = new VPackSlice(chunkBuffer); + final int headSize = head.getByteSize(); + if (chunkBuffer.length > headSize) { + body = new VPackSlice(chunkBuffer, headSize); + } else { + body = null; + } + } - public Message(final long id, final VPackSlice head, final VPackSlice body) { - super(); - this.id = id; - this.head = head; - this.body = body; - } + public Message(final long id, final VPackSlice head, final VPackSlice body) { + super(); + this.id = id; + this.head = head; + this.body = body; + } - public long getId() { - return id; - } + public long getId() { + return id; + } - public VPackSlice getHead() { - return head; - } + public VPackSlice getHead() { + return head; + } - public VPackSlice getBody() { - return body; - } + public VPackSlice getBody() { + return body; + } } diff --git a/src/main/java/com/arangodb/internal/velocystream/internal/MessageStore.java b/src/main/java/com/arangodb/internal/velocystream/internal/MessageStore.java index ef965d4d4..74948b484 100644 --- a/src/main/java/com/arangodb/internal/velocystream/internal/MessageStore.java +++ b/src/main/java/com/arangodb/internal/velocystream/internal/MessageStore.java @@ -31,83 +31,82 @@ /** * @author Mark Vollmary - * */ public class MessageStore { - private static final Logger LOGGER = LoggerFactory.getLogger(MessageStore.class); + private static final Logger LOGGER = LoggerFactory.getLogger(MessageStore.class); - private final Map> task; - private final Map response; - private final Map error; + private final Map> task; + private final Map response; + private final Map error; - public MessageStore() { - super(); + public MessageStore() { + super(); task = new ConcurrentHashMap<>(); response = new ConcurrentHashMap<>(); error = new ConcurrentHashMap<>(); - } + } - public void storeMessage(final long messageId, final FutureTask future) { - task.put(messageId, future); - } + public void storeMessage(final long messageId, final FutureTask future) { + task.put(messageId, future); + } - public void consume(final Message message) { - final FutureTask future = task.remove(message.getId()); - if (future != null) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug(String.format("Received Message (id=%s, head=%s, body=%s)", message.getId(), - message.getHead(), message.getBody() != null ? message.getBody() : "{}")); - } - response.put(message.getId(), message); - future.run(); - } - } + public void consume(final Message message) { + final FutureTask future = task.remove(message.getId()); + if (future != null) { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug(String.format("Received Message (id=%s, head=%s, body=%s)", message.getId(), + message.getHead(), message.getBody() != null ? message.getBody() : "{}")); + } + response.put(message.getId(), message); + future.run(); + } + } - public Message get(final long messageId) throws ArangoDBException { - final Message result = response.remove(messageId); - if (result == null) { - final Exception e = error.remove(messageId); - if (e != null) { - throw new ArangoDBException(e); - } - } - return result; - } + public Message get(final long messageId) throws ArangoDBException { + final Message result = response.remove(messageId); + if (result == null) { + final Exception e = error.remove(messageId); + if (e != null) { + throw new ArangoDBException(e); + } + } + return result; + } - public void cancel(final long messageId) { - final FutureTask future = task.remove(messageId); - if (future != null) { - LOGGER.error(String.format("Cancel Message unexpected (id=%s).", messageId)); - future.cancel(true); - } - } + public void cancel(final long messageId) { + final FutureTask future = task.remove(messageId); + if (future != null) { + LOGGER.error(String.format("Cancel Message unexpected (id=%s).", messageId)); + future.cancel(true); + } + } - public void clear(final Exception e) { - if (!task.isEmpty()) { - LOGGER.error(e.getMessage(), e); - } - for (final Entry> entry : task.entrySet()) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug(String.format("Exceptionally complete Message (id=%s).", entry.getKey())); - } - error.put(entry.getKey(), e); - entry.getValue().run(); - } - task.clear(); - } + public void clear(final Exception e) { + if (!task.isEmpty()) { + LOGGER.error(e.getMessage(), e); + } + for (final Entry> entry : task.entrySet()) { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug(String.format("Exceptionally complete Message (id=%s).", entry.getKey())); + } + error.put(entry.getKey(), e); + entry.getValue().run(); + } + task.clear(); + } - public void clear() { - for (final Entry> entry : task.entrySet()) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug(String.format("Cancel Message (id=%s).", entry.getKey())); - } - entry.getValue().cancel(true); - } - task.clear(); - } + public void clear() { + for (final Entry> entry : task.entrySet()) { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug(String.format("Cancel Message (id=%s).", entry.getKey())); + } + entry.getValue().cancel(true); + } + task.clear(); + } - public boolean isEmpty() { - return task.isEmpty(); - } + public boolean isEmpty() { + return task.isEmpty(); + } } diff --git a/src/main/java/com/arangodb/internal/velocystream/internal/VstConnection.java b/src/main/java/com/arangodb/internal/velocystream/internal/VstConnection.java index 1ef950c9d..26391ecdf 100644 --- a/src/main/java/com/arangodb/internal/velocystream/internal/VstConnection.java +++ b/src/main/java/com/arangodb/internal/velocystream/internal/VstConnection.java @@ -49,237 +49,236 @@ /** * @author Mark Vollmary - * */ public abstract class VstConnection implements Connection { - private static final Logger LOGGER = LoggerFactory.getLogger(VstConnection.class); - private static final byte[] PROTOCOL_HEADER = "VST/1.0\r\n\r\n".getBytes(); - - private ExecutorService executor; - protected final MessageStore messageStore; - - protected final Integer timeout; - private final Long ttl; - private final Boolean useSsl; - private final SSLContext sslContext; - - private Socket socket; - private OutputStream outputStream; - private InputStream inputStream; - - private final HostDescription host; - - private final HashMap sendTimestamps = new HashMap<>(); - - private final String connectionName; - - protected VstConnection(final HostDescription host, final Integer timeout, final Long ttl, final Boolean useSsl, - final SSLContext sslContext, final MessageStore messageStore) { - super(); - this.host = host; - this.timeout = timeout; - this.ttl = ttl; - this.useSsl = useSsl; - this.sslContext = sslContext; - this.messageStore = messageStore; - - connectionName = "connection_" + System.currentTimeMillis() + "_" + Math.random(); - LOGGER.debug("Connection " + connectionName + " created"); - } - - public boolean isOpen() { - return socket != null && socket.isConnected() && !socket.isClosed(); - } - - public synchronized void open() throws IOException { - if (isOpen()) { - return; - } - if (LOGGER.isDebugEnabled()) { - LOGGER.debug(String.format("Open connection to %s", host)); - } - if (Boolean.TRUE == useSsl) { - if (sslContext != null) { - socket = sslContext.getSocketFactory().createSocket(); - } else { - socket = SSLSocketFactory.getDefault().createSocket(); - } - } else { - socket = SocketFactory.getDefault().createSocket(); - } - socket.connect(new InetSocketAddress(host.getHost(), host.getPort()), timeout != null ? timeout : ArangoDefaults.DEFAULT_TIMEOUT); - socket.setKeepAlive(true); - socket.setTcpNoDelay(true); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug(String.format("Connected to %s", socket)); - } - - outputStream = new BufferedOutputStream(socket.getOutputStream()); - inputStream = socket.getInputStream(); - - if (Boolean.TRUE == useSsl) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug(String.format("Start Handshake on %s", socket)); - } - ((SSLSocket) socket).startHandshake(); - } - sendProtocolHeader(); - - executor = Executors.newSingleThreadExecutor(); - executor.submit((Callable) () -> { - LOGGER.debug("Start Callable for " + connectionName); - - final long openTime = new Date().getTime(); - final Long ttlTime = ttl != null ? openTime + ttl : null; - final ChunkStore chunkStore = new ChunkStore(messageStore); - while (true) { - if (ttlTime != null && new Date().getTime() > ttlTime && messageStore.isEmpty()) { - close(); - break; - } - if (!isOpen()) { - messageStore.clear(new IOException("The socket is closed.")); - close(); - break; - } - try { - final Chunk chunk = readChunk(); - final ByteBuffer chunkBuffer = chunkStore.storeChunk(chunk); - if (chunkBuffer != null) { - final byte[] buf = new byte[chunk.getContentLength()]; - readBytesIntoBuffer(buf, 0, buf.length); - chunkBuffer.put(buf); - chunkStore.checkCompleteness(chunk.getMessageId()); - } - } catch (final Exception e) { - messageStore.clear(e); - close(); - break; - } - } - - LOGGER.debug("Stop Callable for " + connectionName); - - return null; - }); - } - - @Override - public synchronized void close() { - messageStore.clear(); - if (executor != null && !executor.isShutdown()) { - executor.shutdown(); - } - if (socket != null && !socket.isClosed()) { - try { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug(String.format("Close connection %s", socket)); - } - socket.close(); - } catch (final IOException e) { - throw new ArangoDBException(e); - } - } - } - - private synchronized void sendProtocolHeader() throws IOException { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug(String.format("Send velocystream protocol header to %s", socket)); - } - outputStream.write(PROTOCOL_HEADER); - outputStream.flush(); - } - - protected synchronized void writeIntern(final Message message, final Collection chunks) - throws ArangoDBException { - for (final Chunk chunk : chunks) { - try { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug(String.format("Send chunk %s:%s from message %s", chunk.getChunk(), - chunk.isFirstChunk() ? 1 : 0, chunk.getMessageId())); - sendTimestamps.put(chunk.getMessageId(), System.currentTimeMillis()); - } - writeChunkHead(chunk); - final int contentOffset = chunk.getContentOffset(); - final int contentLength = chunk.getContentLength(); - final VPackSlice head = message.getHead(); - final int headLength = head.getByteSize(); - int written = 0; - if (contentOffset < headLength) { - written = Math.min(contentLength, headLength - contentOffset); - outputStream.write(head.getBuffer(), contentOffset, written); - } - if (written < contentLength) { - final VPackSlice body = message.getBody(); - outputStream.write(body.getBuffer(), contentOffset + written - headLength, contentLength - written); - } - outputStream.flush(); - } catch (final IOException e) { - LOGGER.error("Error on Connection " + connectionName); - throw new ArangoDBException(e); - } - } - } - - private synchronized void writeChunkHead(final Chunk chunk) throws IOException { - final long messageLength = chunk.getMessageLength(); - final int headLength = messageLength > -1L ? ArangoDefaults.CHUNK_MAX_HEADER_SIZE - : ArangoDefaults.CHUNK_MIN_HEADER_SIZE; - final int length = chunk.getContentLength() + headLength; - final ByteBuffer buffer = ByteBuffer.allocate(headLength).order(ByteOrder.LITTLE_ENDIAN); - buffer.putInt(length); - buffer.putInt(chunk.getChunkX()); - buffer.putLong(chunk.getMessageId()); - if (messageLength > -1L) { - buffer.putLong(messageLength); - } - outputStream.write(buffer.array()); - } - - protected Chunk readChunk() throws IOException { - final ByteBuffer chunkHeadBuffer = readBytes(ArangoDefaults.CHUNK_MIN_HEADER_SIZE); - final int length = chunkHeadBuffer.getInt(); - final int chunkX = chunkHeadBuffer.getInt(); - final long messageId = chunkHeadBuffer.getLong(); - final long messageLength; - final int contentLength; - if ((1 == (chunkX & 0x1)) && ((chunkX >> 1) > 1)) { - messageLength = readBytes(ArangoDefaults.LONG_BYTES).getLong(); - contentLength = length - ArangoDefaults.CHUNK_MAX_HEADER_SIZE; - } else { - messageLength = -1L; - contentLength = length - ArangoDefaults.CHUNK_MIN_HEADER_SIZE; - } - final Chunk chunk = new Chunk(messageId, chunkX, messageLength, 0, contentLength); - - if (LOGGER.isDebugEnabled()) { - - LOGGER.debug(String.format("Received chunk %s:%s from message %s", chunk.getChunk(), chunk.isFirstChunk() ? 1 : 0, chunk.getMessageId())); - LOGGER.debug("Responsetime for Message " + chunk.getMessageId() + " is " + (sendTimestamps.get(chunk.getMessageId())-System.currentTimeMillis())); - } - - return chunk; - } - - private ByteBuffer readBytes(final int len) throws IOException { - final byte[] buf = new byte[len]; - readBytesIntoBuffer(buf, 0, len); - return ByteBuffer.wrap(buf).order(ByteOrder.LITTLE_ENDIAN); - } - - protected void readBytesIntoBuffer(final byte[] buf, final int off, final int len) throws IOException { - for (int readed = 0; readed < len;) { - final int read = inputStream.read(buf, off + readed, len - readed); - if (read == -1) { - throw new IOException("Reached the end of the stream."); - } else { - readed += read; - } - } - } - - public String getConnectionName() { - return this.connectionName; - } + private static final Logger LOGGER = LoggerFactory.getLogger(VstConnection.class); + private static final byte[] PROTOCOL_HEADER = "VST/1.0\r\n\r\n".getBytes(); + + private ExecutorService executor; + protected final MessageStore messageStore; + + protected final Integer timeout; + private final Long ttl; + private final Boolean useSsl; + private final SSLContext sslContext; + + private Socket socket; + private OutputStream outputStream; + private InputStream inputStream; + + private final HostDescription host; + + private final HashMap sendTimestamps = new HashMap<>(); + + private final String connectionName; + + protected VstConnection(final HostDescription host, final Integer timeout, final Long ttl, final Boolean useSsl, + final SSLContext sslContext, final MessageStore messageStore) { + super(); + this.host = host; + this.timeout = timeout; + this.ttl = ttl; + this.useSsl = useSsl; + this.sslContext = sslContext; + this.messageStore = messageStore; + + connectionName = "connection_" + System.currentTimeMillis() + "_" + Math.random(); + LOGGER.debug("Connection " + connectionName + " created"); + } + + public boolean isOpen() { + return socket != null && socket.isConnected() && !socket.isClosed(); + } + + public synchronized void open() throws IOException { + if (isOpen()) { + return; + } + if (LOGGER.isDebugEnabled()) { + LOGGER.debug(String.format("Open connection to %s", host)); + } + if (Boolean.TRUE == useSsl) { + if (sslContext != null) { + socket = sslContext.getSocketFactory().createSocket(); + } else { + socket = SSLSocketFactory.getDefault().createSocket(); + } + } else { + socket = SocketFactory.getDefault().createSocket(); + } + socket.connect(new InetSocketAddress(host.getHost(), host.getPort()), timeout != null ? timeout : ArangoDefaults.DEFAULT_TIMEOUT); + socket.setKeepAlive(true); + socket.setTcpNoDelay(true); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug(String.format("Connected to %s", socket)); + } + + outputStream = new BufferedOutputStream(socket.getOutputStream()); + inputStream = socket.getInputStream(); + + if (Boolean.TRUE == useSsl) { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug(String.format("Start Handshake on %s", socket)); + } + ((SSLSocket) socket).startHandshake(); + } + sendProtocolHeader(); + + executor = Executors.newSingleThreadExecutor(); + executor.submit((Callable) () -> { + LOGGER.debug("Start Callable for " + connectionName); + + final long openTime = new Date().getTime(); + final Long ttlTime = ttl != null ? openTime + ttl : null; + final ChunkStore chunkStore = new ChunkStore(messageStore); + while (true) { + if (ttlTime != null && new Date().getTime() > ttlTime && messageStore.isEmpty()) { + close(); + break; + } + if (!isOpen()) { + messageStore.clear(new IOException("The socket is closed.")); + close(); + break; + } + try { + final Chunk chunk = readChunk(); + final ByteBuffer chunkBuffer = chunkStore.storeChunk(chunk); + if (chunkBuffer != null) { + final byte[] buf = new byte[chunk.getContentLength()]; + readBytesIntoBuffer(buf, 0, buf.length); + chunkBuffer.put(buf); + chunkStore.checkCompleteness(chunk.getMessageId()); + } + } catch (final Exception e) { + messageStore.clear(e); + close(); + break; + } + } + + LOGGER.debug("Stop Callable for " + connectionName); + + return null; + }); + } + + @Override + public synchronized void close() { + messageStore.clear(); + if (executor != null && !executor.isShutdown()) { + executor.shutdown(); + } + if (socket != null && !socket.isClosed()) { + try { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug(String.format("Close connection %s", socket)); + } + socket.close(); + } catch (final IOException e) { + throw new ArangoDBException(e); + } + } + } + + private synchronized void sendProtocolHeader() throws IOException { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug(String.format("Send velocystream protocol header to %s", socket)); + } + outputStream.write(PROTOCOL_HEADER); + outputStream.flush(); + } + + protected synchronized void writeIntern(final Message message, final Collection chunks) + throws ArangoDBException { + for (final Chunk chunk : chunks) { + try { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug(String.format("Send chunk %s:%s from message %s", chunk.getChunk(), + chunk.isFirstChunk() ? 1 : 0, chunk.getMessageId())); + sendTimestamps.put(chunk.getMessageId(), System.currentTimeMillis()); + } + writeChunkHead(chunk); + final int contentOffset = chunk.getContentOffset(); + final int contentLength = chunk.getContentLength(); + final VPackSlice head = message.getHead(); + final int headLength = head.getByteSize(); + int written = 0; + if (contentOffset < headLength) { + written = Math.min(contentLength, headLength - contentOffset); + outputStream.write(head.getBuffer(), contentOffset, written); + } + if (written < contentLength) { + final VPackSlice body = message.getBody(); + outputStream.write(body.getBuffer(), contentOffset + written - headLength, contentLength - written); + } + outputStream.flush(); + } catch (final IOException e) { + LOGGER.error("Error on Connection " + connectionName); + throw new ArangoDBException(e); + } + } + } + + private synchronized void writeChunkHead(final Chunk chunk) throws IOException { + final long messageLength = chunk.getMessageLength(); + final int headLength = messageLength > -1L ? ArangoDefaults.CHUNK_MAX_HEADER_SIZE + : ArangoDefaults.CHUNK_MIN_HEADER_SIZE; + final int length = chunk.getContentLength() + headLength; + final ByteBuffer buffer = ByteBuffer.allocate(headLength).order(ByteOrder.LITTLE_ENDIAN); + buffer.putInt(length); + buffer.putInt(chunk.getChunkX()); + buffer.putLong(chunk.getMessageId()); + if (messageLength > -1L) { + buffer.putLong(messageLength); + } + outputStream.write(buffer.array()); + } + + protected Chunk readChunk() throws IOException { + final ByteBuffer chunkHeadBuffer = readBytes(ArangoDefaults.CHUNK_MIN_HEADER_SIZE); + final int length = chunkHeadBuffer.getInt(); + final int chunkX = chunkHeadBuffer.getInt(); + final long messageId = chunkHeadBuffer.getLong(); + final long messageLength; + final int contentLength; + if ((1 == (chunkX & 0x1)) && ((chunkX >> 1) > 1)) { + messageLength = readBytes(ArangoDefaults.LONG_BYTES).getLong(); + contentLength = length - ArangoDefaults.CHUNK_MAX_HEADER_SIZE; + } else { + messageLength = -1L; + contentLength = length - ArangoDefaults.CHUNK_MIN_HEADER_SIZE; + } + final Chunk chunk = new Chunk(messageId, chunkX, messageLength, 0, contentLength); + + if (LOGGER.isDebugEnabled()) { + + LOGGER.debug(String.format("Received chunk %s:%s from message %s", chunk.getChunk(), chunk.isFirstChunk() ? 1 : 0, chunk.getMessageId())); + LOGGER.debug("Responsetime for Message " + chunk.getMessageId() + " is " + (sendTimestamps.get(chunk.getMessageId()) - System.currentTimeMillis())); + } + + return chunk; + } + + private ByteBuffer readBytes(final int len) throws IOException { + final byte[] buf = new byte[len]; + readBytesIntoBuffer(buf, 0, len); + return ByteBuffer.wrap(buf).order(ByteOrder.LITTLE_ENDIAN); + } + + protected void readBytesIntoBuffer(final byte[] buf, final int off, final int len) throws IOException { + for (int readed = 0; readed < len; ) { + final int read = inputStream.read(buf, off + readed, len - readed); + if (read == -1) { + throw new IOException("Reached the end of the stream."); + } else { + readed += read; + } + } + } + + public String getConnectionName() { + return this.connectionName; + } } diff --git a/src/main/java/com/arangodb/internal/velocystream/internal/VstConnectionSync.java b/src/main/java/com/arangodb/internal/velocystream/internal/VstConnectionSync.java index eb652b1d0..54d2ffbfe 100644 --- a/src/main/java/com/arangodb/internal/velocystream/internal/VstConnectionSync.java +++ b/src/main/java/com/arangodb/internal/velocystream/internal/VstConnectionSync.java @@ -30,68 +30,67 @@ /** * @author Mark Vollmary - * */ public class VstConnectionSync extends VstConnection { - public static class Builder { - - private HostDescription host; - private MessageStore messageStore; - private Integer timeout; - private Long ttl; - private Boolean useSsl; - private SSLContext sslContext; - - public Builder host(final HostDescription host) { - this.host = host; - return this; - } - - public Builder messageStore(final MessageStore messageStore) { - this.messageStore = messageStore; - return this; - } - - public Builder timeout(final Integer timeout) { - this.timeout = timeout; - return this; - } - - public Builder useSsl(final Boolean useSsl) { - this.useSsl = useSsl; - return this; - } - - public Builder sslContext(final SSLContext sslContext) { - this.sslContext = sslContext; - return this; - } - - public Builder ttl(final Long ttl) { - this.ttl = ttl; - return this; - } - - public VstConnectionSync build() { - return new VstConnectionSync(host, timeout, ttl, useSsl, sslContext, messageStore); - } - } - - private VstConnectionSync(final HostDescription host, final Integer timeout, final Long ttl, final Boolean useSsl, - final SSLContext sslContext, final MessageStore messageStore) { - super(host, timeout, ttl, useSsl, sslContext, messageStore); - } - - public Message write(final Message message, final Collection chunks) throws ArangoDBException { - final FutureTask task = new FutureTask<>(() -> messageStore.get(message.getId())); - messageStore.storeMessage(message.getId(), task); - super.writeIntern(message, chunks); - try { - return timeout == null || timeout == 0L ? task.get() : task.get(timeout, TimeUnit.MILLISECONDS); - } catch (final Exception e) { - throw new ArangoDBException(e); - } - } + public static class Builder { + + private HostDescription host; + private MessageStore messageStore; + private Integer timeout; + private Long ttl; + private Boolean useSsl; + private SSLContext sslContext; + + public Builder host(final HostDescription host) { + this.host = host; + return this; + } + + public Builder messageStore(final MessageStore messageStore) { + this.messageStore = messageStore; + return this; + } + + public Builder timeout(final Integer timeout) { + this.timeout = timeout; + return this; + } + + public Builder useSsl(final Boolean useSsl) { + this.useSsl = useSsl; + return this; + } + + public Builder sslContext(final SSLContext sslContext) { + this.sslContext = sslContext; + return this; + } + + public Builder ttl(final Long ttl) { + this.ttl = ttl; + return this; + } + + public VstConnectionSync build() { + return new VstConnectionSync(host, timeout, ttl, useSsl, sslContext, messageStore); + } + } + + private VstConnectionSync(final HostDescription host, final Integer timeout, final Long ttl, final Boolean useSsl, + final SSLContext sslContext, final MessageStore messageStore) { + super(host, timeout, ttl, useSsl, sslContext, messageStore); + } + + public Message write(final Message message, final Collection chunks) throws ArangoDBException { + final FutureTask task = new FutureTask<>(() -> messageStore.get(message.getId())); + messageStore.storeMessage(message.getId(), task); + super.writeIntern(message, chunks); + try { + return timeout == null || timeout == 0L ? task.get() : task.get(timeout, TimeUnit.MILLISECONDS); + } catch (final Exception e) { + throw new ArangoDBException(e); + } + } } diff --git a/src/main/java/com/arangodb/model/AqlFunctionCreateOptions.java b/src/main/java/com/arangodb/model/AqlFunctionCreateOptions.java index 1802cc8b5..a1897c491 100644 --- a/src/main/java/com/arangodb/model/AqlFunctionCreateOptions.java +++ b/src/main/java/com/arangodb/model/AqlFunctionCreateOptions.java @@ -22,62 +22,58 @@ /** * @author Mark Vollmary - * * @see API - * Documentation + * Documentation */ public class AqlFunctionCreateOptions { - private String name; - private String code; - private Boolean isDeterministic; + private String name; + private String code; + private Boolean isDeterministic; - public AqlFunctionCreateOptions() { - super(); - } + public AqlFunctionCreateOptions() { + super(); + } - /** - * @param name - * the fully qualified name of the user functions - * @return options - */ - protected AqlFunctionCreateOptions name(final String name) { - this.name = name; - return this; - } + /** + * @param name the fully qualified name of the user functions + * @return options + */ + protected AqlFunctionCreateOptions name(final String name) { + this.name = name; + return this; + } - protected String getName() { - return name; - } + protected String getName() { + return name; + } - /** - * @param code - * a string representation of the function body - * @return options - */ - protected AqlFunctionCreateOptions code(final String code) { - this.code = code; - return this; - } + /** + * @param code a string representation of the function body + * @return options + */ + protected AqlFunctionCreateOptions code(final String code) { + this.code = code; + return this; + } - protected String getCode() { - return code; - } + protected String getCode() { + return code; + } - /** - * @param isDeterministic - * an optional boolean value to indicate that the function results are fully deterministic (function - * return value solely depends on the input value and return value is the same for repeated calls with - * same input) - * @return options - */ - public AqlFunctionCreateOptions isDeterministic(final Boolean isDeterministic) { - this.isDeterministic = isDeterministic; - return this; - } + /** + * @param isDeterministic an optional boolean value to indicate that the function results are fully deterministic (function + * return value solely depends on the input value and return value is the same for repeated calls with + * same input) + * @return options + */ + public AqlFunctionCreateOptions isDeterministic(final Boolean isDeterministic) { + this.isDeterministic = isDeterministic; + return this; + } - public Boolean getIsDeterministic() { - return isDeterministic; - } + public Boolean getIsDeterministic() { + return isDeterministic; + } } diff --git a/src/main/java/com/arangodb/model/AqlFunctionDeleteOptions.java b/src/main/java/com/arangodb/model/AqlFunctionDeleteOptions.java index 4b763da35..dd3cd2901 100644 --- a/src/main/java/com/arangodb/model/AqlFunctionDeleteOptions.java +++ b/src/main/java/com/arangodb/model/AqlFunctionDeleteOptions.java @@ -22,33 +22,31 @@ /** * @author Mark Vollmary - * * @see API - * Documentation + * "https://www.arangodb.com/docs/stable/http/aql-user-functions.html#remove-existing-aql-user-function">API + * Documentation */ public class AqlFunctionDeleteOptions { - private Boolean group; + private Boolean group; - public AqlFunctionDeleteOptions() { - super(); - } + public AqlFunctionDeleteOptions() { + super(); + } - public Boolean getGroup() { - return group; - } + public Boolean getGroup() { + return group; + } - /** - * @param group - * If set to true, then the function name provided in name is treated as a namespace prefix, and all - * functions in the specified namespace will be deleted. If set to false, the function name provided in - * name must be fully qualified, including any namespaces. - * @return options - */ - public AqlFunctionDeleteOptions group(final Boolean group) { - this.group = group; - return this; - } + /** + * @param group If set to true, then the function name provided in name is treated as a namespace prefix, and all + * functions in the specified namespace will be deleted. If set to false, the function name provided in + * name must be fully qualified, including any namespaces. + * @return options + */ + public AqlFunctionDeleteOptions group(final Boolean group) { + this.group = group; + return this; + } } diff --git a/src/main/java/com/arangodb/model/AqlFunctionGetOptions.java b/src/main/java/com/arangodb/model/AqlFunctionGetOptions.java index 67e82b7a8..2b4713ddb 100644 --- a/src/main/java/com/arangodb/model/AqlFunctionGetOptions.java +++ b/src/main/java/com/arangodb/model/AqlFunctionGetOptions.java @@ -22,31 +22,29 @@ /** * @author Mark Vollmary - * * @see API - * Documentation + * "https://www.arangodb.com/docs/stable/http/aql-user-functions.html#return-registered-aql-user-functions">API + * Documentation */ public class AqlFunctionGetOptions { - private String namespace; + private String namespace; - public AqlFunctionGetOptions() { - super(); - } + public AqlFunctionGetOptions() { + super(); + } - public String getNamespace() { - return namespace; - } + public String getNamespace() { + return namespace; + } - /** - * @param namespace - * Returns all registered AQL user functions from namespace namespace - * @return options - */ - public AqlFunctionGetOptions namespace(final String namespace) { - this.namespace = namespace; - return this; - } + /** + * @param namespace Returns all registered AQL user functions from namespace namespace + * @return options + */ + public AqlFunctionGetOptions namespace(final String namespace) { + this.namespace = namespace; + return this; + } } diff --git a/src/main/java/com/arangodb/model/AqlQueryExplainOptions.java b/src/main/java/com/arangodb/model/AqlQueryExplainOptions.java index 0509533e3..29b8351c6 100644 --- a/src/main/java/com/arangodb/model/AqlQueryExplainOptions.java +++ b/src/main/java/com/arangodb/model/AqlQueryExplainOptions.java @@ -27,113 +27,107 @@ /** * @author Mark Vollmary * @author Michele Rastelli - * * @see API Documentation */ public class AqlQueryExplainOptions { - private VPackSlice bindVars; - private String query; - private Options options; - - public AqlQueryExplainOptions() { - super(); - } - - protected VPackSlice getBindVars() { - return bindVars; - } - - /** - * @param bindVars - * key/value pairs representing the bind parameters - * @return options - */ - protected AqlQueryExplainOptions bindVars(final VPackSlice bindVars) { - this.bindVars = bindVars; - return this; - } - - protected String getQuery() { - return query; - } - - /** - * @param query - * the query which you want explained - * @return options - */ - protected AqlQueryExplainOptions query(final String query) { - this.query = query; - return this; - } - - public Integer getMaxNumberOfPlans() { - return getOptions().maxNumberOfPlans; - } - - /** - * @param maxNumberOfPlans - * an optional maximum number of plans that the optimizer is allowed to generate. Setting this attribute - * to a low value allows to put a cap on the amount of work the optimizer does. - * @return options - */ - public AqlQueryExplainOptions maxNumberOfPlans(final Integer maxNumberOfPlans) { - getOptions().maxNumberOfPlans = maxNumberOfPlans; - return this; - } - - public Boolean getAllPlans() { - return getOptions().allPlans; - } - - /** - * @param allPlans - * if set to true, all possible execution plans will be returned. The default is false, meaning only the - * optimal plan will be returned. - * @return options - */ - public AqlQueryExplainOptions allPlans(final Boolean allPlans) { - getOptions().allPlans = allPlans; - return this; - } - - public Collection getRules() { - return getOptions().getOptimizer().rules; - } - - /** - * @param rules - * an array of to-be-included or to-be-excluded optimizer rules can be put into this attribute, telling - * the optimizer to include or exclude specific rules. - * @return options - */ - public AqlQueryExplainOptions rules(final Collection rules) { - getOptions().getOptimizer().rules = rules; - return this; - } - - private Options getOptions() { - if (options == null) { - options = new Options(); - } - return options; - } - - private static class Options { - private Optimizer optimizer; - private Integer maxNumberOfPlans; - private Boolean allPlans; - - protected Optimizer getOptimizer() { - if (optimizer == null) { - optimizer = new Optimizer(); - } - return optimizer; - } - } - - private static class Optimizer { - private Collection rules; - } + private VPackSlice bindVars; + private String query; + private Options options; + + public AqlQueryExplainOptions() { + super(); + } + + protected VPackSlice getBindVars() { + return bindVars; + } + + /** + * @param bindVars key/value pairs representing the bind parameters + * @return options + */ + protected AqlQueryExplainOptions bindVars(final VPackSlice bindVars) { + this.bindVars = bindVars; + return this; + } + + protected String getQuery() { + return query; + } + + /** + * @param query the query which you want explained + * @return options + */ + protected AqlQueryExplainOptions query(final String query) { + this.query = query; + return this; + } + + public Integer getMaxNumberOfPlans() { + return getOptions().maxNumberOfPlans; + } + + /** + * @param maxNumberOfPlans an optional maximum number of plans that the optimizer is allowed to generate. Setting this attribute + * to a low value allows to put a cap on the amount of work the optimizer does. + * @return options + */ + public AqlQueryExplainOptions maxNumberOfPlans(final Integer maxNumberOfPlans) { + getOptions().maxNumberOfPlans = maxNumberOfPlans; + return this; + } + + public Boolean getAllPlans() { + return getOptions().allPlans; + } + + /** + * @param allPlans if set to true, all possible execution plans will be returned. The default is false, meaning only the + * optimal plan will be returned. + * @return options + */ + public AqlQueryExplainOptions allPlans(final Boolean allPlans) { + getOptions().allPlans = allPlans; + return this; + } + + public Collection getRules() { + return getOptions().getOptimizer().rules; + } + + /** + * @param rules an array of to-be-included or to-be-excluded optimizer rules can be put into this attribute, telling + * the optimizer to include or exclude specific rules. + * @return options + */ + public AqlQueryExplainOptions rules(final Collection rules) { + getOptions().getOptimizer().rules = rules; + return this; + } + + private Options getOptions() { + if (options == null) { + options = new Options(); + } + return options; + } + + private static class Options { + private Optimizer optimizer; + private Integer maxNumberOfPlans; + private Boolean allPlans; + + protected Optimizer getOptimizer() { + if (optimizer == null) { + optimizer = new Optimizer(); + } + return optimizer; + } + } + + private static class Optimizer { + private Collection rules; + } } diff --git a/src/main/java/com/arangodb/model/AqlQueryOptions.java b/src/main/java/com/arangodb/model/AqlQueryOptions.java index 76df371b6..1c3679ba7 100644 --- a/src/main/java/com/arangodb/model/AqlQueryOptions.java +++ b/src/main/java/com/arangodb/model/AqlQueryOptions.java @@ -36,147 +36,147 @@ */ public class AqlQueryOptions implements Serializable { - private static final long serialVersionUID = 1L; - - private Boolean count; - private Integer ttl; - private Integer batchSize; - private Boolean cache; - private Long memoryLimit; - private VPackSlice bindVars; - private String query; - private Options options; - @Expose(serialize = false) - private Boolean allowDirtyRead; - private String streamTransactionId; - - public AqlQueryOptions() { - super(); - } - - public Boolean getCount() { - return count; - } - - /** - * @param count indicates whether the number of documents in the result set should be returned in the "count" - * attribute of the result. Calculating the "count" attribute might have a performance impact for some - * queries in the future so this option is turned off by default, and "count" is only returned when - * requested. - * @return options - */ - public AqlQueryOptions count(final Boolean count) { - this.count = count; - return this; - } - - public Integer getTtl() { - return ttl; - } - - /** - * @param ttl The time-to-live for the cursor (in seconds). The cursor will be removed on the server automatically - * after the specified amount of time. This is useful to ensure garbage collection of cursors that are - * not fully fetched by clients. If not set, a server-defined value will be used. - * @return options - */ - public AqlQueryOptions ttl(final Integer ttl) { - this.ttl = ttl; - return this; - } - - public Integer getBatchSize() { - return batchSize; - } - - /** - * @param batchSize maximum number of result documents to be transferred from the server to the client in one roundtrip. - * If this attribute is not set, a server-controlled default value will be used. A batchSize value of 0 - * is disallowed. - * @return options - */ - public AqlQueryOptions batchSize(final Integer batchSize) { - this.batchSize = batchSize; - return this; - } - - public Long getMemoryLimit() { - return memoryLimit; - } - - /** - * @param memoryLimit the maximum number of memory (measured in bytes) that the query is allowed to use. If set, then the - * query will fail with error "resource limit exceeded" in case it allocates too much memory. A value of - * 0 indicates that there is no memory limit. - * @return options - * @since ArangoDB 3.1.0 - */ - public AqlQueryOptions memoryLimit(final Long memoryLimit) { - this.memoryLimit = memoryLimit; - return this; - } - - public Boolean getCache() { - return cache; - } - - /** - * @param cache flag to determine whether the AQL query cache shall be used. If set to false, then any query cache - * lookup will be skipped for the query. If set to true, it will lead to the query cache being checked - * for the query if the query cache mode is either on or demand. - * @return options - */ - public AqlQueryOptions cache(final Boolean cache) { - this.cache = cache; - return this; - } - - protected VPackSlice getBindVars() { - return bindVars; - } - - /** - * @param bindVars key/value pairs representing the bind parameters - * @return options - */ - protected AqlQueryOptions bindVars(final VPackSlice bindVars) { - this.bindVars = bindVars; - return this; - } - - protected String getQuery() { - return query; - } - - /** - * @param query the query which you want parse - * @return options - */ - protected AqlQueryOptions query(final String query) { - this.query = query; - return this; - } - - public Boolean getFailOnWarning() { - return options != null ? options.failOnWarning : null; - } - - /** - * @param failOnWarning When set to true, the query will throw an exception and abort instead of producing a warning. This - * option should be used during development to catch potential issues early. When the attribute is set to - * false, warnings will not be propagated to exceptions and will be returned with the query result. There - * is also a server configuration option --query.fail-on-warning for setting the default value for - * failOnWarning so it does not need to be set on a per-query level. - * @return options - */ - public AqlQueryOptions failOnWarning(final Boolean failOnWarning) { - getOptions().failOnWarning = failOnWarning; - return this; - } + private static final long serialVersionUID = 1L; + + private Boolean count; + private Integer ttl; + private Integer batchSize; + private Boolean cache; + private Long memoryLimit; + private VPackSlice bindVars; + private String query; + private Options options; + @Expose(serialize = false) + private Boolean allowDirtyRead; + private String streamTransactionId; + + public AqlQueryOptions() { + super(); + } + + public Boolean getCount() { + return count; + } + + /** + * @param count indicates whether the number of documents in the result set should be returned in the "count" + * attribute of the result. Calculating the "count" attribute might have a performance impact for some + * queries in the future so this option is turned off by default, and "count" is only returned when + * requested. + * @return options + */ + public AqlQueryOptions count(final Boolean count) { + this.count = count; + return this; + } + + public Integer getTtl() { + return ttl; + } + + /** + * @param ttl The time-to-live for the cursor (in seconds). The cursor will be removed on the server automatically + * after the specified amount of time. This is useful to ensure garbage collection of cursors that are + * not fully fetched by clients. If not set, a server-defined value will be used. + * @return options + */ + public AqlQueryOptions ttl(final Integer ttl) { + this.ttl = ttl; + return this; + } + + public Integer getBatchSize() { + return batchSize; + } + + /** + * @param batchSize maximum number of result documents to be transferred from the server to the client in one roundtrip. + * If this attribute is not set, a server-controlled default value will be used. A batchSize value of 0 + * is disallowed. + * @return options + */ + public AqlQueryOptions batchSize(final Integer batchSize) { + this.batchSize = batchSize; + return this; + } + + public Long getMemoryLimit() { + return memoryLimit; + } + + /** + * @param memoryLimit the maximum number of memory (measured in bytes) that the query is allowed to use. If set, then the + * query will fail with error "resource limit exceeded" in case it allocates too much memory. A value of + * 0 indicates that there is no memory limit. + * @return options + * @since ArangoDB 3.1.0 + */ + public AqlQueryOptions memoryLimit(final Long memoryLimit) { + this.memoryLimit = memoryLimit; + return this; + } + + public Boolean getCache() { + return cache; + } + + /** + * @param cache flag to determine whether the AQL query cache shall be used. If set to false, then any query cache + * lookup will be skipped for the query. If set to true, it will lead to the query cache being checked + * for the query if the query cache mode is either on or demand. + * @return options + */ + public AqlQueryOptions cache(final Boolean cache) { + this.cache = cache; + return this; + } + + protected VPackSlice getBindVars() { + return bindVars; + } + + /** + * @param bindVars key/value pairs representing the bind parameters + * @return options + */ + protected AqlQueryOptions bindVars(final VPackSlice bindVars) { + this.bindVars = bindVars; + return this; + } + + protected String getQuery() { + return query; + } + + /** + * @param query the query which you want parse + * @return options + */ + protected AqlQueryOptions query(final String query) { + this.query = query; + return this; + } + + public Boolean getFailOnWarning() { + return options != null ? options.failOnWarning : null; + } + + /** + * @param failOnWarning When set to true, the query will throw an exception and abort instead of producing a warning. This + * option should be used during development to catch potential issues early. When the attribute is set to + * false, warnings will not be propagated to exceptions and will be returned with the query result. There + * is also a server configuration option --query.fail-on-warning for setting the default value for + * failOnWarning so it does not need to be set on a per-query level. + * @return options + */ + public AqlQueryOptions failOnWarning(final Boolean failOnWarning) { + getOptions().failOnWarning = failOnWarning; + return this; + } /** * @param timeout The query has to be executed within the given runtime or it will be killed. The value is specified - * in seconds. The default value is 0.0 (no timeout). + * in seconds. The default value is 0.0 (no timeout). * @return options */ public AqlQueryOptions maxRuntime(final Double timeout) { @@ -184,278 +184,278 @@ public AqlQueryOptions maxRuntime(final Double timeout) { return this; } - /** - * @return If set to true, then the additional query profiling information will be returned in the sub-attribute - * profile of the extra return attribute if the query result is not served from the query cache. - */ - public Boolean getProfile() { - return options != null ? options.profile : null; - } - - /** - * @param profile If set to true, then the additional query profiling information will be returned in the sub-attribute - * profile of the extra return attribute if the query result is not served from the query cache. - * @return options - */ - public AqlQueryOptions profile(final Boolean profile) { - getOptions().profile = profile; - return this; - } - - public Long getMaxTransactionSize() { - return options != null ? options.maxTransactionSize : null; - } - - /** - * @param maxTransactionSize Transaction size limit in bytes. Honored by the RocksDB storage engine only. - * @return options - * @since ArangoDB 3.2.0 - */ - public AqlQueryOptions maxTransactionSize(final Long maxTransactionSize) { - getOptions().maxTransactionSize = maxTransactionSize; - return this; - } - - public Long getMaxWarningCount() { - return options != null ? options.maxWarningCount : null; - } - - /** - * @param maxWarningCount Limits the maximum number of warnings a query will return. The number of warnings a query will return - * is limited to 10 by default, but that number can be increased or decreased by setting this attribute. - * @return options - * @since ArangoDB 3.2.0 - */ - public AqlQueryOptions maxWarningCount(final Long maxWarningCount) { - getOptions().maxWarningCount = maxWarningCount; - return this; - } - - public Long getIntermediateCommitCount() { - return options != null ? options.intermediateCommitCount : null; - } - - /** - * @param intermediateCommitCount Maximum number of operations after which an intermediate commit is performed automatically. Honored by - * the RocksDB storage engine only. - * @return options - * @since ArangoDB 3.2.0 - */ - public AqlQueryOptions intermediateCommitCount(final Long intermediateCommitCount) { - getOptions().intermediateCommitCount = intermediateCommitCount; - return this; - } - - public Long getIntermediateCommitSize() { - return options != null ? options.intermediateCommitSize : null; - } - - /** - * @param intermediateCommitSize Maximum total size of operations after which an intermediate commit is performed automatically. - * Honored by the RocksDB storage engine only. - * @return options - * @since ArangoDB 3.2.0 - */ - public AqlQueryOptions intermediateCommitSize(final Long intermediateCommitSize) { - getOptions().intermediateCommitSize = intermediateCommitSize; - return this; - } - - public Double getSatelliteSyncWait() { - return options != null ? options.satelliteSyncWait : null; - } - - /** - * @param satelliteSyncWait This enterprise parameter allows to configure how long a DBServer will have time to bring the - * satellite collections involved in the query into sync. The default value is 60.0 (seconds). When the - * max time has been reached the query will be stopped. - * @return options - * @since ArangoDB 3.2.0 - */ - public AqlQueryOptions satelliteSyncWait(final Double satelliteSyncWait) { - getOptions().satelliteSyncWait = satelliteSyncWait; - return this; - } - - public Boolean getSkipInaccessibleCollections() { - return options != null ? options.skipInaccessibleCollections : null; - } - - /** - * @param skipInaccessibleCollections AQL queries (especially graph traversals) will treat collection to which a user has no access rights - * as if these collections were empty. Instead of returning a forbidden access error, your queries will - * execute normally. This is intended to help with certain use-cases: A graph contains several - * collections and different users execute AQL queries on that graph. You can now naturally limit the - * accessible results by changing the access rights of users on collections. This feature is only - * available in the Enterprise Edition. - * @return options - * @since ArangoDB 3.2.0 - */ - public AqlQueryOptions skipInaccessibleCollections(final Boolean skipInaccessibleCollections) { - getOptions().skipInaccessibleCollections = skipInaccessibleCollections; - return this; - } - - public Boolean getFullCount() { - return options != null ? options.fullCount : null; - } - - /** - * @param fullCount if set to true and the query contains a LIMIT clause, then the result will have an extra attribute - * with the sub-attributes stats and fullCount, { ... , "extra": { "stats": { "fullCount": 123 } } }. The - * fullCount attribute will contain the number of documents in the result before the last LIMIT in the - * query was applied. It can be used to count the number of documents that match certain filter criteria, - * but only return a subset of them, in one go. It is thus similar to MySQL's SQL_CALC_FOUND_ROWS hint. - * Note that setting the option will disable a few LIMIT optimizations and may lead to more documents - * being processed, and thus make queries run longer. Note that the fullCount attribute will only be - * present in the result if the query has a LIMIT clause and the LIMIT clause is actually used in the - * query. - * @return options - */ - public AqlQueryOptions fullCount(final Boolean fullCount) { - getOptions().fullCount = fullCount; - return this; - } - - public Integer getMaxPlans() { - return options != null ? options.maxPlans : null; - } - - /** - * @param maxPlans Limits the maximum number of plans that are created by the AQL query optimizer. - * @return options - */ - public AqlQueryOptions maxPlans(final Integer maxPlans) { - getOptions().maxPlans = maxPlans; - return this; - } - - public Collection getRules() { - return options != null ? options.optimizer != null ? options.optimizer.rules : null : null; - } - - /** - * @param rules A list of to-be-included or to-be-excluded optimizer rules can be put into this attribute, telling the - * optimizer to include or exclude specific rules. To disable a rule, prefix its name with a -, to enable - * a rule, prefix it with a +. There is also a pseudo-rule all, which will match all optimizer rules - * @return options - */ - public AqlQueryOptions rules(final Collection rules) { - getOptions().getOptimizer().rules = rules; - return this; - } - - public Boolean getStream() { - return options != null ? options.stream : null; - } - - /** - * @param stream Specify true and the query will be executed in a streaming fashion. The query result is not stored on - * the server, but calculated on the fly. Beware: long-running queries will need to hold the collection - * locks for as long as the query cursor exists. When set to false a query will be executed right away in - * its entirety. In that case query results are either returned right away (if the resultset is small - * enough), or stored on the arangod instance and accessible via the cursor API (with respect to the - * ttl). It is advisable to only use this option on short-running queries or without exclusive locks - * (write-locks on MMFiles). Please note that the query options cache, count and fullCount will not work - * on streaming queries. Additionally query statistics, warnings and profiling data will only be - * available after the query is finished. The default value is false - * @return options - * @since ArangoDB 3.4.0 - */ - public AqlQueryOptions stream(final Boolean stream) { - getOptions().stream = stream; - return this; - } - - public Collection getShardIds() { - return options != null ? options.shardIds : null; - } - - /** - * Restrict query to shards by given ids. This is an internal option. Use at your own risk. - * - * @param shardIds - * @return options - */ - public AqlQueryOptions shardIds(final String... shardIds) { - getOptions().getShardIds().addAll(Arrays.asList(shardIds)); - return this; - } - - private Options getOptions() { - if (options == null) { - options = new Options(); - } - return options; - } - - private static class Options implements Serializable { - - private static final long serialVersionUID = 1L; - - private Boolean failOnWarning; - private Boolean profile; - private Long maxTransactionSize; - private Long maxWarningCount; - private Long intermediateCommitCount; - private Long intermediateCommitSize; - private Double satelliteSyncWait; - private Boolean skipInaccessibleCollections; - private Optimizer optimizer; - private Boolean fullCount; - private Integer maxPlans; - private Boolean stream; - private Collection shardIds; - private Double maxRuntime; - - protected Optimizer getOptimizer() { - if (optimizer == null) { - optimizer = new Optimizer(); - } - return optimizer; - } - - protected Collection getShardIds() { - if (shardIds == null) { + /** + * @return If set to true, then the additional query profiling information will be returned in the sub-attribute + * profile of the extra return attribute if the query result is not served from the query cache. + */ + public Boolean getProfile() { + return options != null ? options.profile : null; + } + + /** + * @param profile If set to true, then the additional query profiling information will be returned in the sub-attribute + * profile of the extra return attribute if the query result is not served from the query cache. + * @return options + */ + public AqlQueryOptions profile(final Boolean profile) { + getOptions().profile = profile; + return this; + } + + public Long getMaxTransactionSize() { + return options != null ? options.maxTransactionSize : null; + } + + /** + * @param maxTransactionSize Transaction size limit in bytes. Honored by the RocksDB storage engine only. + * @return options + * @since ArangoDB 3.2.0 + */ + public AqlQueryOptions maxTransactionSize(final Long maxTransactionSize) { + getOptions().maxTransactionSize = maxTransactionSize; + return this; + } + + public Long getMaxWarningCount() { + return options != null ? options.maxWarningCount : null; + } + + /** + * @param maxWarningCount Limits the maximum number of warnings a query will return. The number of warnings a query will return + * is limited to 10 by default, but that number can be increased or decreased by setting this attribute. + * @return options + * @since ArangoDB 3.2.0 + */ + public AqlQueryOptions maxWarningCount(final Long maxWarningCount) { + getOptions().maxWarningCount = maxWarningCount; + return this; + } + + public Long getIntermediateCommitCount() { + return options != null ? options.intermediateCommitCount : null; + } + + /** + * @param intermediateCommitCount Maximum number of operations after which an intermediate commit is performed automatically. Honored by + * the RocksDB storage engine only. + * @return options + * @since ArangoDB 3.2.0 + */ + public AqlQueryOptions intermediateCommitCount(final Long intermediateCommitCount) { + getOptions().intermediateCommitCount = intermediateCommitCount; + return this; + } + + public Long getIntermediateCommitSize() { + return options != null ? options.intermediateCommitSize : null; + } + + /** + * @param intermediateCommitSize Maximum total size of operations after which an intermediate commit is performed automatically. + * Honored by the RocksDB storage engine only. + * @return options + * @since ArangoDB 3.2.0 + */ + public AqlQueryOptions intermediateCommitSize(final Long intermediateCommitSize) { + getOptions().intermediateCommitSize = intermediateCommitSize; + return this; + } + + public Double getSatelliteSyncWait() { + return options != null ? options.satelliteSyncWait : null; + } + + /** + * @param satelliteSyncWait This enterprise parameter allows to configure how long a DBServer will have time to bring the + * satellite collections involved in the query into sync. The default value is 60.0 (seconds). When the + * max time has been reached the query will be stopped. + * @return options + * @since ArangoDB 3.2.0 + */ + public AqlQueryOptions satelliteSyncWait(final Double satelliteSyncWait) { + getOptions().satelliteSyncWait = satelliteSyncWait; + return this; + } + + public Boolean getSkipInaccessibleCollections() { + return options != null ? options.skipInaccessibleCollections : null; + } + + /** + * @param skipInaccessibleCollections AQL queries (especially graph traversals) will treat collection to which a user has no access rights + * as if these collections were empty. Instead of returning a forbidden access error, your queries will + * execute normally. This is intended to help with certain use-cases: A graph contains several + * collections and different users execute AQL queries on that graph. You can now naturally limit the + * accessible results by changing the access rights of users on collections. This feature is only + * available in the Enterprise Edition. + * @return options + * @since ArangoDB 3.2.0 + */ + public AqlQueryOptions skipInaccessibleCollections(final Boolean skipInaccessibleCollections) { + getOptions().skipInaccessibleCollections = skipInaccessibleCollections; + return this; + } + + public Boolean getFullCount() { + return options != null ? options.fullCount : null; + } + + /** + * @param fullCount if set to true and the query contains a LIMIT clause, then the result will have an extra attribute + * with the sub-attributes stats and fullCount, { ... , "extra": { "stats": { "fullCount": 123 } } }. The + * fullCount attribute will contain the number of documents in the result before the last LIMIT in the + * query was applied. It can be used to count the number of documents that match certain filter criteria, + * but only return a subset of them, in one go. It is thus similar to MySQL's SQL_CALC_FOUND_ROWS hint. + * Note that setting the option will disable a few LIMIT optimizations and may lead to more documents + * being processed, and thus make queries run longer. Note that the fullCount attribute will only be + * present in the result if the query has a LIMIT clause and the LIMIT clause is actually used in the + * query. + * @return options + */ + public AqlQueryOptions fullCount(final Boolean fullCount) { + getOptions().fullCount = fullCount; + return this; + } + + public Integer getMaxPlans() { + return options != null ? options.maxPlans : null; + } + + /** + * @param maxPlans Limits the maximum number of plans that are created by the AQL query optimizer. + * @return options + */ + public AqlQueryOptions maxPlans(final Integer maxPlans) { + getOptions().maxPlans = maxPlans; + return this; + } + + public Collection getRules() { + return options != null ? options.optimizer != null ? options.optimizer.rules : null : null; + } + + /** + * @param rules A list of to-be-included or to-be-excluded optimizer rules can be put into this attribute, telling the + * optimizer to include or exclude specific rules. To disable a rule, prefix its name with a -, to enable + * a rule, prefix it with a +. There is also a pseudo-rule all, which will match all optimizer rules + * @return options + */ + public AqlQueryOptions rules(final Collection rules) { + getOptions().getOptimizer().rules = rules; + return this; + } + + public Boolean getStream() { + return options != null ? options.stream : null; + } + + /** + * @param stream Specify true and the query will be executed in a streaming fashion. The query result is not stored on + * the server, but calculated on the fly. Beware: long-running queries will need to hold the collection + * locks for as long as the query cursor exists. When set to false a query will be executed right away in + * its entirety. In that case query results are either returned right away (if the resultset is small + * enough), or stored on the arangod instance and accessible via the cursor API (with respect to the + * ttl). It is advisable to only use this option on short-running queries or without exclusive locks + * (write-locks on MMFiles). Please note that the query options cache, count and fullCount will not work + * on streaming queries. Additionally query statistics, warnings and profiling data will only be + * available after the query is finished. The default value is false + * @return options + * @since ArangoDB 3.4.0 + */ + public AqlQueryOptions stream(final Boolean stream) { + getOptions().stream = stream; + return this; + } + + public Collection getShardIds() { + return options != null ? options.shardIds : null; + } + + /** + * Restrict query to shards by given ids. This is an internal option. Use at your own risk. + * + * @param shardIds + * @return options + */ + public AqlQueryOptions shardIds(final String... shardIds) { + getOptions().getShardIds().addAll(Arrays.asList(shardIds)); + return this; + } + + private Options getOptions() { + if (options == null) { + options = new Options(); + } + return options; + } + + private static class Options implements Serializable { + + private static final long serialVersionUID = 1L; + + private Boolean failOnWarning; + private Boolean profile; + private Long maxTransactionSize; + private Long maxWarningCount; + private Long intermediateCommitCount; + private Long intermediateCommitSize; + private Double satelliteSyncWait; + private Boolean skipInaccessibleCollections; + private Optimizer optimizer; + private Boolean fullCount; + private Integer maxPlans; + private Boolean stream; + private Collection shardIds; + private Double maxRuntime; + + protected Optimizer getOptimizer() { + if (optimizer == null) { + optimizer = new Optimizer(); + } + return optimizer; + } + + protected Collection getShardIds() { + if (shardIds == null) { shardIds = new ArrayList<>(); - } - return shardIds; - } - - } - - private static class Optimizer { - private Collection rules; - } - - /** - * @param allowDirtyRead Set to {@code true} allows reading from followers in an active-failover setup. - * @return options - * @see API - * Documentation - * @since ArangoDB 3.4.0 - */ - public AqlQueryOptions allowDirtyRead(final Boolean allowDirtyRead) { - this.allowDirtyRead = allowDirtyRead; - return this; - } - - public Boolean getAllowDirtyRead() { - return allowDirtyRead; - } - - public String getStreamTransactionId() { - return streamTransactionId; - } - - /** - * @param streamTransactionId If set, the operation will be executed within the transaction. - * @return options - * @since ArangoDB 3.5.0 - */ - public AqlQueryOptions streamTransactionId(final String streamTransactionId) { - this.streamTransactionId = streamTransactionId; - return this; - } + } + return shardIds; + } + + } + + private static class Optimizer { + private Collection rules; + } + + /** + * @param allowDirtyRead Set to {@code true} allows reading from followers in an active-failover setup. + * @return options + * @see API + * Documentation + * @since ArangoDB 3.4.0 + */ + public AqlQueryOptions allowDirtyRead(final Boolean allowDirtyRead) { + this.allowDirtyRead = allowDirtyRead; + return this; + } + + public Boolean getAllowDirtyRead() { + return allowDirtyRead; + } + + public String getStreamTransactionId() { + return streamTransactionId; + } + + /** + * @param streamTransactionId If set, the operation will be executed within the transaction. + * @return options + * @since ArangoDB 3.5.0 + */ + public AqlQueryOptions streamTransactionId(final String streamTransactionId) { + this.streamTransactionId = streamTransactionId; + return this; + } } diff --git a/src/main/java/com/arangodb/model/AqlQueryParseOptions.java b/src/main/java/com/arangodb/model/AqlQueryParseOptions.java index b883b5659..b2194779c 100644 --- a/src/main/java/com/arangodb/model/AqlQueryParseOptions.java +++ b/src/main/java/com/arangodb/model/AqlQueryParseOptions.java @@ -22,29 +22,27 @@ /** * @author Mark Vollmary - * * @see API Documentation */ public class AqlQueryParseOptions { - private String query; + private String query; - public AqlQueryParseOptions() { - super(); - } + public AqlQueryParseOptions() { + super(); + } - protected String getQuery() { - return query; - } + protected String getQuery() { + return query; + } - /** - * @param query - * the query which you want parse - * @return options - */ - protected AqlQueryParseOptions query(final String query) { - this.query = query; - return this; - } + /** + * @param query the query which you want parse + * @return options + */ + protected AqlQueryParseOptions query(final String query) { + this.query = query; + return this; + } } diff --git a/src/main/java/com/arangodb/model/CollectionCountOptions.java b/src/main/java/com/arangodb/model/CollectionCountOptions.java index 0104de3f5..6030f1db8 100644 --- a/src/main/java/com/arangodb/model/CollectionCountOptions.java +++ b/src/main/java/com/arangodb/model/CollectionCountOptions.java @@ -25,24 +25,24 @@ */ public class CollectionCountOptions { - private String streamTransactionId; + private String streamTransactionId; - public CollectionCountOptions() { - super(); - } + public CollectionCountOptions() { + super(); + } - public String getStreamTransactionId() { - return streamTransactionId; - } + public String getStreamTransactionId() { + return streamTransactionId; + } - /** - * @param streamTransactionId If set, the operation will be executed within the transaction. - * @return options - * @since ArangoDB 3.5.0 - */ - public CollectionCountOptions streamTransactionId(final String streamTransactionId) { - this.streamTransactionId = streamTransactionId; - return this; - } + /** + * @param streamTransactionId If set, the operation will be executed within the transaction. + * @return options + * @since ArangoDB 3.5.0 + */ + public CollectionCountOptions streamTransactionId(final String streamTransactionId) { + this.streamTransactionId = streamTransactionId; + return this; + } } diff --git a/src/main/java/com/arangodb/model/CollectionCreateOptions.java b/src/main/java/com/arangodb/model/CollectionCreateOptions.java index 8ea85e7a3..a8f2837e8 100644 --- a/src/main/java/com/arangodb/model/CollectionCreateOptions.java +++ b/src/main/java/com/arangodb/model/CollectionCreateOptions.java @@ -20,331 +20,307 @@ package com.arangodb.model; -import com.arangodb.entity.CollectionType; -import com.arangodb.entity.KeyOptions; -import com.arangodb.entity.KeyType; -import com.arangodb.entity.ReplicationFactor; -import com.arangodb.entity.MinReplicationFactor; +import com.arangodb.entity.*; /** * @author Mark Vollmary - * * @see API - * Documentation + * Documentation */ public class CollectionCreateOptions { - private String name; - private Long journalSize; - private final ReplicationFactor replicationFactor; - private final MinReplicationFactor minReplicationFactor; - private KeyOptions keyOptions; - private Boolean waitForSync; - private Boolean doCompact; - private Boolean isVolatile; - private String[] shardKeys; - private Integer numberOfShards; - private Boolean isSystem; - private CollectionType type; - private Integer indexBuckets; - private String distributeShardsLike; - - private String shardingStrategy; // cluster option - private String smartJoinAttribute; // enterprise option - - public CollectionCreateOptions() { - super(); - replicationFactor = new ReplicationFactor(); - minReplicationFactor = new MinReplicationFactor(); - } - - protected String getName() { - return name; - } - - /** - * @param name - * The name of the collection - * @return options - */ - protected CollectionCreateOptions name(final String name) { - this.name = name; - return this; - } - - public Long getJournalSize() { - return journalSize; - } - - /** - * @param journalSize - * The maximal size of a journal or datafile in bytes. The value must be at least 1048576 (1 MiB). - * @return options - */ - public CollectionCreateOptions journalSize(final Long journalSize) { - this.journalSize = journalSize; - return this; - } - - public Integer getReplicationFactor() { - return replicationFactor.getReplicationFactor(); - } - - public Integer getMinReplicationFactor() { - return minReplicationFactor.getMinReplicationFactor(); - } - - /** - * @param replicationFactor - * (The default is 1): in a cluster, this attribute determines how many copies of each shard are kept on - * different DBServers. The value 1 means that only one copy (no synchronous replication) is kept. A - * value of k means that k-1 replicas are kept. Any two copies reside on different DBServers. Replication - * between them is synchronous, that is, every write operation to the "leader" copy will be replicated to - * all "follower" replicas, before the write operation is reported successful. If a server fails, this is - * detected automatically and one of the servers holding copies take over, usually without an error being - * reported. - * @return options - */ - public CollectionCreateOptions replicationFactor(final Integer replicationFactor) { - this.replicationFactor.setReplicationFactor(replicationFactor); - return this; - } - - /** - * @param minReplicationFactor - * (optional, default is 1): in a cluster, this attribute determines how many desired copies of each - * shard are kept on different DBServers. The value 1 means that only one copy (no synchronous - * replication) is kept. A value of k means that desired k-1 replicas are kept. If in a failover scenario - * a shard of a collection has less than minReplicationFactor many insync followers it will go into - * "read-only" mode and will reject writes until enough followers are insync again. In more detail: - * Having `minReplicationFactor == 1` means as soon as a "master-copy" is available of the data writes - * are allowed. Having `minReplicationFactor > 1` requires additional insync copies on follower servers - * to allow writes. - * - * @return options - */ - public CollectionCreateOptions minReplicationFactor(final Integer minReplicationFactor) { - this.minReplicationFactor.setMinReplicationFactor(minReplicationFactor); - return this; - } - - public Boolean getSatellite() { - return replicationFactor.getSatellite(); - } - - /** - * @param satellite - * If the true the collection is created as a satellite collection. In this case - * {@link #replicationFactor(Integer)} is ignored. - * @return options - */ - public CollectionCreateOptions satellite(final Boolean satellite) { - this.replicationFactor.setSatellite(satellite); - return this; - } - - public KeyOptions getKeyOptions() { - return keyOptions; - } - - /** - * @param allowUserKeys - * if set to true, then it is allowed to supply own key values in the _key attribute of a document. If - * set to false, then the key generator will solely be responsible for generating keys and supplying own - * key values in the _key attribute of documents is considered an error. - * @param type - * specifies the type of the key generator. The currently available generators are traditional and - * autoincrement. - * @param increment - * increment value for autoincrement key generator. Not used for other key generator types. - * @param offset - * Initial offset value for autoincrement key generator. Not used for other key generator types. - * @return options - */ - public CollectionCreateOptions keyOptions( - final Boolean allowUserKeys, - final KeyType type, - final Integer increment, - final Integer offset) { - this.keyOptions = new KeyOptions(allowUserKeys, type, increment, offset); - return this; - } - - public Boolean getWaitForSync() { - return waitForSync; - } - - /** - * @param waitForSync - * If true then the data is synchronized to disk before returning from a document create, update, replace - * or removal operation. (default: false) - * @return options - */ - public CollectionCreateOptions waitForSync(final Boolean waitForSync) { - this.waitForSync = waitForSync; - return this; - } - - public Boolean getDoCompact() { - return doCompact; - } - - /** - * @param doCompact - * whether or not the collection will be compacted (default is true) - * @return options - */ - public CollectionCreateOptions doCompact(final Boolean doCompact) { - this.doCompact = doCompact; - return this; - } - - public Boolean getIsVolatile() { - return isVolatile; - } - - /** - * @param isVolatile - * If true then the collection data is kept in-memory only and not made persistent. Unloading the - * collection will cause the collection data to be discarded. Stopping or re-starting the server will - * also cause full loss of data in the collection. Setting this option will make the resulting collection - * be slightly faster than regular collections because ArangoDB does not enforce any synchronization to - * disk and does not calculate any CRC checksums for datafiles (as there are no datafiles). This option - * should therefore be used for cache-type collections only, and not for data that cannot be re-created - * otherwise. (The default is false) - * @return options - */ - public CollectionCreateOptions isVolatile(final Boolean isVolatile) { - this.isVolatile = isVolatile; - return this; - } - - public String[] getShardKeys() { - return shardKeys; - } - - /** - * @param shardKeys - * (The default is [ "_key" ]): in a cluster, this attribute determines which document attributes are - * used to determine the target shard for documents. Documents are sent to shards based on the values of - * their shard key attributes. The values of all shard key attributes in a document are hashed, and the - * hash value is used to determine the target shard. Note: Values of shard key attributes cannot be - * changed once set. This option is meaningless in a single server setup. - * @return options - */ - public CollectionCreateOptions shardKeys(final String... shardKeys) { - this.shardKeys = shardKeys; - return this; - } - - /** - * @param smartJoinAttribute - * @return options - */ - public CollectionCreateOptions smartJoinAttribute(final String smartJoinAttribute) { - this.smartJoinAttribute = smartJoinAttribute; - return this; - } - - public String getSmartJoinAttribute() { - return smartJoinAttribute; - } - - /** - * @param shardingStrategy - * @return options - */ - public CollectionCreateOptions shardingStrategy(final String shardingStrategy) { - this.shardingStrategy = shardingStrategy; - return this; - } - - public String getShardingStrategy() { - return shardingStrategy; - } - - /** - * @param numberOfShards - * (The default is 1): in a cluster, this value determines the number of shards to create for the - * collection. In a single server setup, this option is meaningless. - * @return options - */ - public CollectionCreateOptions numberOfShards(final Integer numberOfShards) { - this.numberOfShards = numberOfShards; - return this; - } - - public Integer getNumberOfShards() { - return numberOfShards; - } - - public Boolean getIsSystem() { - return isSystem; - } - - /** - * @param isSystem - * If true, create a system collection. In this case collection-name should start with an underscore. End - * users should normally create non-system collections only. API implementors may be required to create - * system collections in very special occasions, but normally a regular collection will do. (The default - * is false) - * @return options - */ - public CollectionCreateOptions isSystem(final Boolean isSystem) { - this.isSystem = isSystem; - return this; - } - - public CollectionType getType() { - return type; - } - - /** - * @param type - * (The default is {@link CollectionType#DOCUMENT}): the type of the collection to create. - * @return options - */ - public CollectionCreateOptions type(final CollectionType type) { - this.type = type; - return this; - } - - public Integer getIndexBuckets() { - return indexBuckets; - } - - /** - * @param indexBuckets - * The number of buckets into which indexes using a hash table are split. The default is 16 and this - * number has to be a power of 2 and less than or equal to 1024. For very large collections one should - * increase this to avoid long pauses when the hash table has to be initially built or resized, since - * buckets are resized individually and can be initially built in parallel. For example, 64 might be a - * sensible value for a collection with 100 000 000 documents. Currently, only the edge index respects - * this value, but other index types might follow in future ArangoDB versions. Changes (see below) are - * applied when the collection is loaded the next time. - * @return options - */ - public CollectionCreateOptions indexBuckets(final Integer indexBuckets) { - this.indexBuckets = indexBuckets; - return this; - } - - public String getDistributeShardsLike() { - return distributeShardsLike; - } - - /** - * @param distributeShardsLike - * (The default is ""): in an enterprise cluster, this attribute binds the specifics of sharding for the - * newly created collection to follow that of a specified existing collection. Note: Using this parameter - * has consequences for the prototype collection. It can no longer be dropped, before sharding imitating - * collections are dropped. Equally, backups and restores of imitating collections alone will generate - * warnings, which can be overridden, about missing sharding prototype. - * @return options - */ - public CollectionCreateOptions distributeShardsLike(final String distributeShardsLike) { - this.distributeShardsLike = distributeShardsLike; - return this; - } + private String name; + private Long journalSize; + private final ReplicationFactor replicationFactor; + private final MinReplicationFactor minReplicationFactor; + private KeyOptions keyOptions; + private Boolean waitForSync; + private Boolean doCompact; + private Boolean isVolatile; + private String[] shardKeys; + private Integer numberOfShards; + private Boolean isSystem; + private CollectionType type; + private Integer indexBuckets; + private String distributeShardsLike; + + private String shardingStrategy; // cluster option + private String smartJoinAttribute; // enterprise option + + public CollectionCreateOptions() { + super(); + replicationFactor = new ReplicationFactor(); + minReplicationFactor = new MinReplicationFactor(); + } + + protected String getName() { + return name; + } + + /** + * @param name The name of the collection + * @return options + */ + protected CollectionCreateOptions name(final String name) { + this.name = name; + return this; + } + + public Long getJournalSize() { + return journalSize; + } + + /** + * @param journalSize The maximal size of a journal or datafile in bytes. The value must be at least 1048576 (1 MiB). + * @return options + */ + public CollectionCreateOptions journalSize(final Long journalSize) { + this.journalSize = journalSize; + return this; + } + + public Integer getReplicationFactor() { + return replicationFactor.getReplicationFactor(); + } + + public Integer getMinReplicationFactor() { + return minReplicationFactor.getMinReplicationFactor(); + } + + /** + * @param replicationFactor (The default is 1): in a cluster, this attribute determines how many copies of each shard are kept on + * different DBServers. The value 1 means that only one copy (no synchronous replication) is kept. A + * value of k means that k-1 replicas are kept. Any two copies reside on different DBServers. Replication + * between them is synchronous, that is, every write operation to the "leader" copy will be replicated to + * all "follower" replicas, before the write operation is reported successful. If a server fails, this is + * detected automatically and one of the servers holding copies take over, usually without an error being + * reported. + * @return options + */ + public CollectionCreateOptions replicationFactor(final Integer replicationFactor) { + this.replicationFactor.setReplicationFactor(replicationFactor); + return this; + } + + /** + * @param minReplicationFactor (optional, default is 1): in a cluster, this attribute determines how many desired copies of each + * shard are kept on different DBServers. The value 1 means that only one copy (no synchronous + * replication) is kept. A value of k means that desired k-1 replicas are kept. If in a failover scenario + * a shard of a collection has less than minReplicationFactor many insync followers it will go into + * "read-only" mode and will reject writes until enough followers are insync again. In more detail: + * Having `minReplicationFactor == 1` means as soon as a "master-copy" is available of the data writes + * are allowed. Having `minReplicationFactor > 1` requires additional insync copies on follower servers + * to allow writes. + * @return options + */ + public CollectionCreateOptions minReplicationFactor(final Integer minReplicationFactor) { + this.minReplicationFactor.setMinReplicationFactor(minReplicationFactor); + return this; + } + + public Boolean getSatellite() { + return replicationFactor.getSatellite(); + } + + /** + * @param satellite If the true the collection is created as a satellite collection. In this case + * {@link #replicationFactor(Integer)} is ignored. + * @return options + */ + public CollectionCreateOptions satellite(final Boolean satellite) { + this.replicationFactor.setSatellite(satellite); + return this; + } + + public KeyOptions getKeyOptions() { + return keyOptions; + } + + /** + * @param allowUserKeys if set to true, then it is allowed to supply own key values in the _key attribute of a document. If + * set to false, then the key generator will solely be responsible for generating keys and supplying own + * key values in the _key attribute of documents is considered an error. + * @param type specifies the type of the key generator. The currently available generators are traditional and + * autoincrement. + * @param increment increment value for autoincrement key generator. Not used for other key generator types. + * @param offset Initial offset value for autoincrement key generator. Not used for other key generator types. + * @return options + */ + public CollectionCreateOptions keyOptions( + final Boolean allowUserKeys, + final KeyType type, + final Integer increment, + final Integer offset) { + this.keyOptions = new KeyOptions(allowUserKeys, type, increment, offset); + return this; + } + + public Boolean getWaitForSync() { + return waitForSync; + } + + /** + * @param waitForSync If true then the data is synchronized to disk before returning from a document create, update, replace + * or removal operation. (default: false) + * @return options + */ + public CollectionCreateOptions waitForSync(final Boolean waitForSync) { + this.waitForSync = waitForSync; + return this; + } + + public Boolean getDoCompact() { + return doCompact; + } + + /** + * @param doCompact whether or not the collection will be compacted (default is true) + * @return options + */ + public CollectionCreateOptions doCompact(final Boolean doCompact) { + this.doCompact = doCompact; + return this; + } + + public Boolean getIsVolatile() { + return isVolatile; + } + + /** + * @param isVolatile If true then the collection data is kept in-memory only and not made persistent. Unloading the + * collection will cause the collection data to be discarded. Stopping or re-starting the server will + * also cause full loss of data in the collection. Setting this option will make the resulting collection + * be slightly faster than regular collections because ArangoDB does not enforce any synchronization to + * disk and does not calculate any CRC checksums for datafiles (as there are no datafiles). This option + * should therefore be used for cache-type collections only, and not for data that cannot be re-created + * otherwise. (The default is false) + * @return options + */ + public CollectionCreateOptions isVolatile(final Boolean isVolatile) { + this.isVolatile = isVolatile; + return this; + } + + public String[] getShardKeys() { + return shardKeys; + } + + /** + * @param shardKeys (The default is [ "_key" ]): in a cluster, this attribute determines which document attributes are + * used to determine the target shard for documents. Documents are sent to shards based on the values of + * their shard key attributes. The values of all shard key attributes in a document are hashed, and the + * hash value is used to determine the target shard. Note: Values of shard key attributes cannot be + * changed once set. This option is meaningless in a single server setup. + * @return options + */ + public CollectionCreateOptions shardKeys(final String... shardKeys) { + this.shardKeys = shardKeys; + return this; + } + + /** + * @param smartJoinAttribute + * @return options + */ + public CollectionCreateOptions smartJoinAttribute(final String smartJoinAttribute) { + this.smartJoinAttribute = smartJoinAttribute; + return this; + } + + public String getSmartJoinAttribute() { + return smartJoinAttribute; + } + + /** + * @param shardingStrategy + * @return options + */ + public CollectionCreateOptions shardingStrategy(final String shardingStrategy) { + this.shardingStrategy = shardingStrategy; + return this; + } + + public String getShardingStrategy() { + return shardingStrategy; + } + + /** + * @param numberOfShards (The default is 1): in a cluster, this value determines the number of shards to create for the + * collection. In a single server setup, this option is meaningless. + * @return options + */ + public CollectionCreateOptions numberOfShards(final Integer numberOfShards) { + this.numberOfShards = numberOfShards; + return this; + } + + public Integer getNumberOfShards() { + return numberOfShards; + } + + public Boolean getIsSystem() { + return isSystem; + } + + /** + * @param isSystem If true, create a system collection. In this case collection-name should start with an underscore. End + * users should normally create non-system collections only. API implementors may be required to create + * system collections in very special occasions, but normally a regular collection will do. (The default + * is false) + * @return options + */ + public CollectionCreateOptions isSystem(final Boolean isSystem) { + this.isSystem = isSystem; + return this; + } + + public CollectionType getType() { + return type; + } + + /** + * @param type (The default is {@link CollectionType#DOCUMENT}): the type of the collection to create. + * @return options + */ + public CollectionCreateOptions type(final CollectionType type) { + this.type = type; + return this; + } + + public Integer getIndexBuckets() { + return indexBuckets; + } + + /** + * @param indexBuckets The number of buckets into which indexes using a hash table are split. The default is 16 and this + * number has to be a power of 2 and less than or equal to 1024. For very large collections one should + * increase this to avoid long pauses when the hash table has to be initially built or resized, since + * buckets are resized individually and can be initially built in parallel. For example, 64 might be a + * sensible value for a collection with 100 000 000 documents. Currently, only the edge index respects + * this value, but other index types might follow in future ArangoDB versions. Changes (see below) are + * applied when the collection is loaded the next time. + * @return options + */ + public CollectionCreateOptions indexBuckets(final Integer indexBuckets) { + this.indexBuckets = indexBuckets; + return this; + } + + public String getDistributeShardsLike() { + return distributeShardsLike; + } + + /** + * @param distributeShardsLike (The default is ""): in an enterprise cluster, this attribute binds the specifics of sharding for the + * newly created collection to follow that of a specified existing collection. Note: Using this parameter + * has consequences for the prototype collection. It can no longer be dropped, before sharding imitating + * collections are dropped. Equally, backups and restores of imitating collections alone will generate + * warnings, which can be overridden, about missing sharding prototype. + * @return options + */ + public CollectionCreateOptions distributeShardsLike(final String distributeShardsLike) { + this.distributeShardsLike = distributeShardsLike; + return this; + } } diff --git a/src/main/java/com/arangodb/model/CollectionPropertiesOptions.java b/src/main/java/com/arangodb/model/CollectionPropertiesOptions.java index 0419d3fbd..31bd459e8 100644 --- a/src/main/java/com/arangodb/model/CollectionPropertiesOptions.java +++ b/src/main/java/com/arangodb/model/CollectionPropertiesOptions.java @@ -22,47 +22,44 @@ /** * @author Mark Vollmary - * * @see API - * Documentation + * Documentation */ public class CollectionPropertiesOptions { - private Boolean waitForSync; - private Long journalSize; + private Boolean waitForSync; + private Long journalSize; - public CollectionPropertiesOptions() { - super(); - } + public CollectionPropertiesOptions() { + super(); + } - public Boolean getWaitForSync() { - return waitForSync; - } + public Boolean getWaitForSync() { + return waitForSync; + } - /** - * @param waitForSync - * If true then creating or changing a document will wait until the data has been synchronized to disk. - * @return options - */ - public CollectionPropertiesOptions waitForSync(final Boolean waitForSync) { - this.waitForSync = waitForSync; - return this; - } + /** + * @param waitForSync If true then creating or changing a document will wait until the data has been synchronized to disk. + * @return options + */ + public CollectionPropertiesOptions waitForSync(final Boolean waitForSync) { + this.waitForSync = waitForSync; + return this; + } - public Long getJournalSize() { - return journalSize; - } + public Long getJournalSize() { + return journalSize; + } - /** - * @param journalSize - * The maximal size of a journal or datafile in bytes. The value must be at least 1048576 (1 MB). Note - * that when changing the journalSize value, it will only have an effect for additional journals or - * datafiles that are created. Already existing journals or datafiles will not be affected. - * @return options - */ - public CollectionPropertiesOptions journalSize(final Long journalSize) { - this.journalSize = journalSize; - return this; - } + /** + * @param journalSize The maximal size of a journal or datafile in bytes. The value must be at least 1048576 (1 MB). Note + * that when changing the journalSize value, it will only have an effect for additional journals or + * datafiles that are created. Already existing journals or datafiles will not be affected. + * @return options + */ + public CollectionPropertiesOptions journalSize(final Long journalSize) { + this.journalSize = journalSize; + return this; + } } diff --git a/src/main/java/com/arangodb/model/CollectionRenameOptions.java b/src/main/java/com/arangodb/model/CollectionRenameOptions.java index 96fc50080..1c7896c79 100644 --- a/src/main/java/com/arangodb/model/CollectionRenameOptions.java +++ b/src/main/java/com/arangodb/model/CollectionRenameOptions.java @@ -22,28 +22,26 @@ /** * @author Mark Vollmary - * */ public class CollectionRenameOptions { - private String name; + private String name; - public CollectionRenameOptions() { - super(); - } + public CollectionRenameOptions() { + super(); + } - public String getName() { - return name; - } + public String getName() { + return name; + } - /** - * @param name - * The new name - * @return options - */ - protected CollectionRenameOptions name(final String name) { - this.name = name; - return this; - } + /** + * @param name The new name + * @return options + */ + protected CollectionRenameOptions name(final String name) { + this.name = name; + return this; + } } diff --git a/src/main/java/com/arangodb/model/CollectionTruncateOptions.java b/src/main/java/com/arangodb/model/CollectionTruncateOptions.java index c2f203220..dff681273 100644 --- a/src/main/java/com/arangodb/model/CollectionTruncateOptions.java +++ b/src/main/java/com/arangodb/model/CollectionTruncateOptions.java @@ -25,24 +25,24 @@ */ public class CollectionTruncateOptions { - private String streamTransactionId; + private String streamTransactionId; - public CollectionTruncateOptions() { - super(); - } + public CollectionTruncateOptions() { + super(); + } - public String getStreamTransactionId() { - return streamTransactionId; - } + public String getStreamTransactionId() { + return streamTransactionId; + } - /** - * @param streamTransactionId If set, the operation will be executed within the transaction. - * @return options - * @since ArangoDB 3.5.0 - */ - public CollectionTruncateOptions streamTransactionId(final String streamTransactionId) { - this.streamTransactionId = streamTransactionId; - return this; - } + /** + * @param streamTransactionId If set, the operation will be executed within the transaction. + * @return options + * @since ArangoDB 3.5.0 + */ + public CollectionTruncateOptions streamTransactionId(final String streamTransactionId) { + this.streamTransactionId = streamTransactionId; + return this; + } } diff --git a/src/main/java/com/arangodb/model/CollectionsReadOptions.java b/src/main/java/com/arangodb/model/CollectionsReadOptions.java index ba2293f93..cea7750d0 100644 --- a/src/main/java/com/arangodb/model/CollectionsReadOptions.java +++ b/src/main/java/com/arangodb/model/CollectionsReadOptions.java @@ -22,30 +22,28 @@ /** * @author Mark Vollmary - * * @see API - * Documentation + * Documentation */ public class CollectionsReadOptions { - private Boolean excludeSystem; + private Boolean excludeSystem; - public CollectionsReadOptions() { - super(); - } + public CollectionsReadOptions() { + super(); + } - public Boolean getExcludeSystem() { - return excludeSystem; - } + public Boolean getExcludeSystem() { + return excludeSystem; + } - /** - * @param excludeSystem - * Whether or not system collections should be excluded from the result. - * @return options - */ - public CollectionsReadOptions excludeSystem(final Boolean excludeSystem) { - this.excludeSystem = excludeSystem; - return this; - } + /** + * @param excludeSystem Whether or not system collections should be excluded from the result. + * @return options + */ + public CollectionsReadOptions excludeSystem(final Boolean excludeSystem) { + this.excludeSystem = excludeSystem; + return this; + } } diff --git a/src/main/java/com/arangodb/model/DocumentCreateOptions.java b/src/main/java/com/arangodb/model/DocumentCreateOptions.java index 1e94c3356..0b0c7957f 100644 --- a/src/main/java/com/arangodb/model/DocumentCreateOptions.java +++ b/src/main/java/com/arangodb/model/DocumentCreateOptions.java @@ -28,100 +28,100 @@ */ public class DocumentCreateOptions { - private Boolean waitForSync; - private Boolean returnNew; - private Boolean returnOld; - private Boolean overwrite; - private Boolean silent; - private String streamTransactionId; - - public DocumentCreateOptions() { - super(); - } - - public Boolean getWaitForSync() { - return waitForSync; - } - - /** - * @param waitForSync Wait until document has been synced to disk. - * @return options - */ - public DocumentCreateOptions waitForSync(final Boolean waitForSync) { - this.waitForSync = waitForSync; - return this; - } - - public Boolean getReturnNew() { - return returnNew; - } - - /** - * @param returnNew Return additionally the complete new document under the attribute new in the result. - * @return options - */ - public DocumentCreateOptions returnNew(final Boolean returnNew) { - this.returnNew = returnNew; - return this; - } - - public Boolean getReturnOld() { - return returnOld; - } - - /** - * @param returnOld Additionally return the complete old document under the attribute old in the result. Only - * available if the {@code overwrite} option is used. - * @return options - * @since ArangoDB 3.4 - */ - public DocumentCreateOptions returnOld(final Boolean returnOld) { - this.returnOld = returnOld; - return this; - } - - public Boolean getOverwrite() { - return overwrite; - } - - /** - * @param overwrite If set to true, the insert becomes a replace-insert. If a document with the same {@code _key} - * already exists the new document is not rejected with unique constraint violated but will replace - * the old document. - * @return options - * @since ArangoDB 3.4 - */ - public DocumentCreateOptions overwrite(final Boolean overwrite) { - this.overwrite = overwrite; - return this; - } - - public Boolean getSilent() { - return silent; - } - - /** - * @param silent If set to true, an empty object will be returned as response. No meta-data will be returned for the - * created document. This option can be used to save some network traffic. - * @return options - */ - public DocumentCreateOptions silent(final Boolean silent) { - this.silent = silent; - return this; - } - - public String getStreamTransactionId() { - return streamTransactionId; - } - - /** - * @param streamTransactionId If set, the operation will be executed within the transaction. - * @return options - * @since ArangoDB 3.5.0 - */ - public DocumentCreateOptions streamTransactionId(final String streamTransactionId) { - this.streamTransactionId = streamTransactionId; - return this; - } + private Boolean waitForSync; + private Boolean returnNew; + private Boolean returnOld; + private Boolean overwrite; + private Boolean silent; + private String streamTransactionId; + + public DocumentCreateOptions() { + super(); + } + + public Boolean getWaitForSync() { + return waitForSync; + } + + /** + * @param waitForSync Wait until document has been synced to disk. + * @return options + */ + public DocumentCreateOptions waitForSync(final Boolean waitForSync) { + this.waitForSync = waitForSync; + return this; + } + + public Boolean getReturnNew() { + return returnNew; + } + + /** + * @param returnNew Return additionally the complete new document under the attribute new in the result. + * @return options + */ + public DocumentCreateOptions returnNew(final Boolean returnNew) { + this.returnNew = returnNew; + return this; + } + + public Boolean getReturnOld() { + return returnOld; + } + + /** + * @param returnOld Additionally return the complete old document under the attribute old in the result. Only + * available if the {@code overwrite} option is used. + * @return options + * @since ArangoDB 3.4 + */ + public DocumentCreateOptions returnOld(final Boolean returnOld) { + this.returnOld = returnOld; + return this; + } + + public Boolean getOverwrite() { + return overwrite; + } + + /** + * @param overwrite If set to true, the insert becomes a replace-insert. If a document with the same {@code _key} + * already exists the new document is not rejected with unique constraint violated but will replace + * the old document. + * @return options + * @since ArangoDB 3.4 + */ + public DocumentCreateOptions overwrite(final Boolean overwrite) { + this.overwrite = overwrite; + return this; + } + + public Boolean getSilent() { + return silent; + } + + /** + * @param silent If set to true, an empty object will be returned as response. No meta-data will be returned for the + * created document. This option can be used to save some network traffic. + * @return options + */ + public DocumentCreateOptions silent(final Boolean silent) { + this.silent = silent; + return this; + } + + public String getStreamTransactionId() { + return streamTransactionId; + } + + /** + * @param streamTransactionId If set, the operation will be executed within the transaction. + * @return options + * @since ArangoDB 3.5.0 + */ + public DocumentCreateOptions streamTransactionId(final String streamTransactionId) { + this.streamTransactionId = streamTransactionId; + return this; + } } diff --git a/src/main/java/com/arangodb/model/DocumentDeleteOptions.java b/src/main/java/com/arangodb/model/DocumentDeleteOptions.java index fb11f13c2..e0e566952 100644 --- a/src/main/java/com/arangodb/model/DocumentDeleteOptions.java +++ b/src/main/java/com/arangodb/model/DocumentDeleteOptions.java @@ -28,82 +28,82 @@ */ public class DocumentDeleteOptions { - private Boolean waitForSync; - private String ifMatch; - private Boolean returnOld; - private Boolean silent; - private String streamTransactionId; + private Boolean waitForSync; + private String ifMatch; + private Boolean returnOld; + private Boolean silent; + private String streamTransactionId; - public DocumentDeleteOptions() { - super(); - } + public DocumentDeleteOptions() { + super(); + } - public Boolean getWaitForSync() { - return waitForSync; - } + public Boolean getWaitForSync() { + return waitForSync; + } - /** - * @param waitForSync Wait until deletion operation has been synced to disk. - * @return options - */ - public DocumentDeleteOptions waitForSync(final Boolean waitForSync) { - this.waitForSync = waitForSync; - return this; - } + /** + * @param waitForSync Wait until deletion operation has been synced to disk. + * @return options + */ + public DocumentDeleteOptions waitForSync(final Boolean waitForSync) { + this.waitForSync = waitForSync; + return this; + } - public String getIfMatch() { - return ifMatch; - } + public String getIfMatch() { + return ifMatch; + } - /** - * @param ifMatch remove a document based on a target revision - * @return options - */ - public DocumentDeleteOptions ifMatch(final String ifMatch) { - this.ifMatch = ifMatch; - return this; - } + /** + * @param ifMatch remove a document based on a target revision + * @return options + */ + public DocumentDeleteOptions ifMatch(final String ifMatch) { + this.ifMatch = ifMatch; + return this; + } - public Boolean getReturnOld() { - return returnOld; - } + public Boolean getReturnOld() { + return returnOld; + } - /** - * @param returnOld Return additionally the complete previous revision of the changed document under the attribute old in - * the result. - * @return options - */ - public DocumentDeleteOptions returnOld(final Boolean returnOld) { - this.returnOld = returnOld; - return this; - } + /** + * @param returnOld Return additionally the complete previous revision of the changed document under the attribute old in + * the result. + * @return options + */ + public DocumentDeleteOptions returnOld(final Boolean returnOld) { + this.returnOld = returnOld; + return this; + } - public Boolean getSilent() { - return silent; - } + public Boolean getSilent() { + return silent; + } - /** - * @param silent If set to true, an empty object will be returned as response. No meta-data will be returned for the - * created document. This option can be used to save some network traffic. - * @return options - */ - public DocumentDeleteOptions silent(final Boolean silent) { - this.silent = silent; - return this; - } + /** + * @param silent If set to true, an empty object will be returned as response. No meta-data will be returned for the + * created document. This option can be used to save some network traffic. + * @return options + */ + public DocumentDeleteOptions silent(final Boolean silent) { + this.silent = silent; + return this; + } - public String getStreamTransactionId() { - return streamTransactionId; - } + public String getStreamTransactionId() { + return streamTransactionId; + } - /** - * @param streamTransactionId If set, the operation will be executed within the transaction. - * @return options - * @since ArangoDB 3.5.0 - */ - public DocumentDeleteOptions streamTransactionId(final String streamTransactionId) { - this.streamTransactionId = streamTransactionId; - return this; - } + /** + * @param streamTransactionId If set, the operation will be executed within the transaction. + * @return options + * @since ArangoDB 3.5.0 + */ + public DocumentDeleteOptions streamTransactionId(final String streamTransactionId) { + this.streamTransactionId = streamTransactionId; + return this; + } } diff --git a/src/main/java/com/arangodb/model/DocumentExistsOptions.java b/src/main/java/com/arangodb/model/DocumentExistsOptions.java index 29b07dbc4..a790bf201 100644 --- a/src/main/java/com/arangodb/model/DocumentExistsOptions.java +++ b/src/main/java/com/arangodb/model/DocumentExistsOptions.java @@ -28,67 +28,67 @@ */ public class DocumentExistsOptions { - private String ifNoneMatch; - private String ifMatch; - private boolean catchException; - private String streamTransactionId; + private String ifNoneMatch; + private String ifMatch; + private boolean catchException; + private String streamTransactionId; - public DocumentExistsOptions() { - super(); - catchException = true; - } + public DocumentExistsOptions() { + super(); + catchException = true; + } - public String getIfNoneMatch() { - return ifNoneMatch; - } + public String getIfNoneMatch() { + return ifNoneMatch; + } - /** - * @param ifNoneMatch document revision must not contain If-None-Match - * @return options - */ - public DocumentExistsOptions ifNoneMatch(final String ifNoneMatch) { - this.ifNoneMatch = ifNoneMatch; - return this; - } + /** + * @param ifNoneMatch document revision must not contain If-None-Match + * @return options + */ + public DocumentExistsOptions ifNoneMatch(final String ifNoneMatch) { + this.ifNoneMatch = ifNoneMatch; + return this; + } - public String getIfMatch() { - return ifMatch; - } + public String getIfMatch() { + return ifMatch; + } - /** - * @param ifMatch document revision must contain If-Match - * @return options - */ - public DocumentExistsOptions ifMatch(final String ifMatch) { - this.ifMatch = ifMatch; - return this; - } + /** + * @param ifMatch document revision must contain If-Match + * @return options + */ + public DocumentExistsOptions ifMatch(final String ifMatch) { + this.ifMatch = ifMatch; + return this; + } - public boolean isCatchException() { - return catchException; - } + public boolean isCatchException() { + return catchException; + } - /** - * @param catchException whether or not catch possible thrown exceptions - * @return options - */ - public DocumentExistsOptions catchException(final boolean catchException) { - this.catchException = catchException; - return this; - } + /** + * @param catchException whether or not catch possible thrown exceptions + * @return options + */ + public DocumentExistsOptions catchException(final boolean catchException) { + this.catchException = catchException; + return this; + } - public String getStreamTransactionId() { - return streamTransactionId; - } + public String getStreamTransactionId() { + return streamTransactionId; + } - /** - * @param streamTransactionId If set, the operation will be executed within the transaction. - * @return options - * @since ArangoDB 3.5.0 - */ - public DocumentExistsOptions streamTransactionId(final String streamTransactionId) { - this.streamTransactionId = streamTransactionId; - return this; - } + /** + * @param streamTransactionId If set, the operation will be executed within the transaction. + * @return options + * @since ArangoDB 3.5.0 + */ + public DocumentExistsOptions streamTransactionId(final String streamTransactionId) { + this.streamTransactionId = streamTransactionId; + return this; + } } diff --git a/src/main/java/com/arangodb/model/DocumentImportOptions.java b/src/main/java/com/arangodb/model/DocumentImportOptions.java index 5695826ce..b8a55e3ed 100644 --- a/src/main/java/com/arangodb/model/DocumentImportOptions.java +++ b/src/main/java/com/arangodb/model/DocumentImportOptions.java @@ -22,140 +22,132 @@ /** * @author Mark Vollmary - * */ public class DocumentImportOptions { - public enum OnDuplicate { - error, update, replace, ignore - } - - private String fromPrefix; - private String toPrefix; - private Boolean overwrite; - private Boolean waitForSync; - private OnDuplicate onDuplicate; - private Boolean complete; - private Boolean details; - - public DocumentImportOptions() { - super(); - } - - public String getFromPrefix() { - return fromPrefix; - } - - /** - * @param fromPrefix - * An optional prefix for the values in _from attributes. If specified, the value is automatically - * prepended to each _from input value. This allows specifying just the keys for _from. - * @return options - */ - public DocumentImportOptions fromPrefix(final String fromPrefix) { - this.fromPrefix = fromPrefix; - return this; - } - - public String getToPrefix() { - return toPrefix; - } - - /** - * @param toPrefix - * An optional prefix for the values in _to attributes. If specified, the value is automatically - * prepended to each _to input value. This allows specifying just the keys for _to. - * @return options - */ - public DocumentImportOptions toPrefix(final String toPrefix) { - this.toPrefix = toPrefix; - return this; - } - - public Boolean getOverwrite() { - return overwrite; - } - - /** - * @param overwrite - * If this parameter has a value of true, then all data in the collection will be removed prior to the - * import. Note that any existing index definitions will be preserved. - * @return options - */ - public DocumentImportOptions overwrite(final Boolean overwrite) { - this.overwrite = overwrite; - return this; - } - - public Boolean getWaitForSync() { - return waitForSync; - } - - /** - * @param waitForSync - * Wait until documents have been synced to disk before returning. - * @return options - */ - public DocumentImportOptions waitForSync(final Boolean waitForSync) { - this.waitForSync = waitForSync; - return this; - } - - public OnDuplicate getOnDuplicate() { - return onDuplicate; - } - - /** - * @param onDuplicate - * Controls what action is carried out in case of a unique key constraint violation. Possible values are: - *
    - *
  • error: this will not import the current document because of the unique key constraint violation. - * This is the default setting.
  • - *
  • update: this will update an existing document in the database with the data specified in the - * request. Attributes of the existing document that are not present in the request will be - * preserved.
  • - *
  • replace: this will replace an existing document in the database with the data specified in the - * request.
  • - *
  • ignore: this will not update an existing document and simply ignore the error caused by the unique - * key constraint violation. Note that update, replace and ignore will only work when the import document - * in the request contains the _key attribute. update and replace may also fail because of secondary - * unique key constraint violations.
  • - *
- * @return options - */ - public DocumentImportOptions onDuplicate(final OnDuplicate onDuplicate) { - this.onDuplicate = onDuplicate; - return this; - } - - public Boolean getComplete() { - return complete; - } - - /** - * @param complete - * If set to true, it will make the whole import fail if any error occurs. Otherwise the import will - * continue even if some documents cannot be imported. - * @return options - */ - public DocumentImportOptions complete(final Boolean complete) { - this.complete = complete; - return this; - } - - public Boolean getDetails() { - return details; - } - - /** - * @param details - * If set to true, the result will include an attribute details with details about documents that could - * not be imported. - * @return options - */ - public DocumentImportOptions details(final Boolean details) { - this.details = details; - return this; - } + public enum OnDuplicate { + error, update, replace, ignore + } + + private String fromPrefix; + private String toPrefix; + private Boolean overwrite; + private Boolean waitForSync; + private OnDuplicate onDuplicate; + private Boolean complete; + private Boolean details; + + public DocumentImportOptions() { + super(); + } + + public String getFromPrefix() { + return fromPrefix; + } + + /** + * @param fromPrefix An optional prefix for the values in _from attributes. If specified, the value is automatically + * prepended to each _from input value. This allows specifying just the keys for _from. + * @return options + */ + public DocumentImportOptions fromPrefix(final String fromPrefix) { + this.fromPrefix = fromPrefix; + return this; + } + + public String getToPrefix() { + return toPrefix; + } + + /** + * @param toPrefix An optional prefix for the values in _to attributes. If specified, the value is automatically + * prepended to each _to input value. This allows specifying just the keys for _to. + * @return options + */ + public DocumentImportOptions toPrefix(final String toPrefix) { + this.toPrefix = toPrefix; + return this; + } + + public Boolean getOverwrite() { + return overwrite; + } + + /** + * @param overwrite If this parameter has a value of true, then all data in the collection will be removed prior to the + * import. Note that any existing index definitions will be preserved. + * @return options + */ + public DocumentImportOptions overwrite(final Boolean overwrite) { + this.overwrite = overwrite; + return this; + } + + public Boolean getWaitForSync() { + return waitForSync; + } + + /** + * @param waitForSync Wait until documents have been synced to disk before returning. + * @return options + */ + public DocumentImportOptions waitForSync(final Boolean waitForSync) { + this.waitForSync = waitForSync; + return this; + } + + public OnDuplicate getOnDuplicate() { + return onDuplicate; + } + + /** + * @param onDuplicate Controls what action is carried out in case of a unique key constraint violation. Possible values are: + *
    + *
  • error: this will not import the current document because of the unique key constraint violation. + * This is the default setting.
  • + *
  • update: this will update an existing document in the database with the data specified in the + * request. Attributes of the existing document that are not present in the request will be + * preserved.
  • + *
  • replace: this will replace an existing document in the database with the data specified in the + * request.
  • + *
  • ignore: this will not update an existing document and simply ignore the error caused by the unique + * key constraint violation. Note that update, replace and ignore will only work when the import document + * in the request contains the _key attribute. update and replace may also fail because of secondary + * unique key constraint violations.
  • + *
+ * @return options + */ + public DocumentImportOptions onDuplicate(final OnDuplicate onDuplicate) { + this.onDuplicate = onDuplicate; + return this; + } + + public Boolean getComplete() { + return complete; + } + + /** + * @param complete If set to true, it will make the whole import fail if any error occurs. Otherwise the import will + * continue even if some documents cannot be imported. + * @return options + */ + public DocumentImportOptions complete(final Boolean complete) { + this.complete = complete; + return this; + } + + public Boolean getDetails() { + return details; + } + + /** + * @param details If set to true, the result will include an attribute details with details about documents that could + * not be imported. + * @return options + */ + public DocumentImportOptions details(final Boolean details) { + this.details = details; + return this; + } } diff --git a/src/main/java/com/arangodb/model/DocumentReadOptions.java b/src/main/java/com/arangodb/model/DocumentReadOptions.java index 2fc0a5aa8..b808f6ed4 100644 --- a/src/main/java/com/arangodb/model/DocumentReadOptions.java +++ b/src/main/java/com/arangodb/model/DocumentReadOptions.java @@ -25,95 +25,90 @@ /** * @author Mark Vollmary * @author Michele Rastelli - * * @see API - * Documentation + * Documentation */ public class DocumentReadOptions { - private String ifNoneMatch; - private String ifMatch; - private boolean catchException; - @Expose(serialize = false) - private Boolean allowDirtyRead; - private String streamTransactionId; - - public DocumentReadOptions() { - super(); - catchException = true; - } - - public String getIfNoneMatch() { - return ifNoneMatch; - } - - /** - * @param ifNoneMatch - * document revision must not contain If-None-Match - * @return options - */ - public DocumentReadOptions ifNoneMatch(final String ifNoneMatch) { - this.ifNoneMatch = ifNoneMatch; - return this; - } - - public String getIfMatch() { - return ifMatch; - } - - /** - * @param ifMatch - * document revision must contain If-Match - * @return options - */ - public DocumentReadOptions ifMatch(final String ifMatch) { - this.ifMatch = ifMatch; - return this; - } - - public boolean isCatchException() { - return catchException; - } - - /** - * @param catchException - * whether or not catch possible thrown exceptions - * @return options - */ - public DocumentReadOptions catchException(final boolean catchException) { - this.catchException = catchException; - return this; - } - - /** - * @see API - * Documentation - * @param allowDirtyRead - * Set to {@code true} allows reading from followers in an active-failover setup. - * @since ArangoDB 3.4.0 - * @return options - */ - public DocumentReadOptions allowDirtyRead(final Boolean allowDirtyRead) { - this.allowDirtyRead = allowDirtyRead; - return this; - } - - public Boolean getAllowDirtyRead() { - return allowDirtyRead; - } - - public String getStreamTransactionId() { - return streamTransactionId; - } - - /** - * @param streamTransactionId If set, the operation will be executed within the transaction. - * @return options - * @since ArangoDB 3.5.0 - */ - public DocumentReadOptions streamTransactionId(final String streamTransactionId) { - this.streamTransactionId = streamTransactionId; - return this; - } + private String ifNoneMatch; + private String ifMatch; + private boolean catchException; + @Expose(serialize = false) + private Boolean allowDirtyRead; + private String streamTransactionId; + + public DocumentReadOptions() { + super(); + catchException = true; + } + + public String getIfNoneMatch() { + return ifNoneMatch; + } + + /** + * @param ifNoneMatch document revision must not contain If-None-Match + * @return options + */ + public DocumentReadOptions ifNoneMatch(final String ifNoneMatch) { + this.ifNoneMatch = ifNoneMatch; + return this; + } + + public String getIfMatch() { + return ifMatch; + } + + /** + * @param ifMatch document revision must contain If-Match + * @return options + */ + public DocumentReadOptions ifMatch(final String ifMatch) { + this.ifMatch = ifMatch; + return this; + } + + public boolean isCatchException() { + return catchException; + } + + /** + * @param catchException whether or not catch possible thrown exceptions + * @return options + */ + public DocumentReadOptions catchException(final boolean catchException) { + this.catchException = catchException; + return this; + } + + /** + * @param allowDirtyRead Set to {@code true} allows reading from followers in an active-failover setup. + * @return options + * @see API + * Documentation + * @since ArangoDB 3.4.0 + */ + public DocumentReadOptions allowDirtyRead(final Boolean allowDirtyRead) { + this.allowDirtyRead = allowDirtyRead; + return this; + } + + public Boolean getAllowDirtyRead() { + return allowDirtyRead; + } + + public String getStreamTransactionId() { + return streamTransactionId; + } + + /** + * @param streamTransactionId If set, the operation will be executed within the transaction. + * @return options + * @since ArangoDB 3.5.0 + */ + public DocumentReadOptions streamTransactionId(final String streamTransactionId) { + this.streamTransactionId = streamTransactionId; + return this; + } } diff --git a/src/main/java/com/arangodb/model/DocumentReplaceOptions.java b/src/main/java/com/arangodb/model/DocumentReplaceOptions.java index c816708f0..2646f847d 100644 --- a/src/main/java/com/arangodb/model/DocumentReplaceOptions.java +++ b/src/main/java/com/arangodb/model/DocumentReplaceOptions.java @@ -23,124 +23,117 @@ /** * @author Mark Vollmary * @author Michele Rastelli - * * @see API - * Documentation + * Documentation */ public class DocumentReplaceOptions { - private Boolean waitForSync; - private Boolean ignoreRevs; - private String ifMatch; - private Boolean returnNew; - private Boolean returnOld; - private Boolean silent; - private String streamTransactionId; - - public DocumentReplaceOptions() { - super(); - } - - public Boolean getWaitForSync() { - return waitForSync; - } - - /** - * @param waitForSync - * Wait until document has been synced to disk. - * @return options - */ - public DocumentReplaceOptions waitForSync(final Boolean waitForSync) { - this.waitForSync = waitForSync; - return this; - } - - public Boolean getIgnoreRevs() { - return ignoreRevs; - } - - /** - * @param ignoreRevs - * By default, or if this is set to true, the _rev attributes in the given document is ignored. If this - * is set to false, then the _rev attribute given in the body document is taken as a precondition. The - * document is only replaced if the current revision is the one specified. - * @return options - */ - public DocumentReplaceOptions ignoreRevs(final Boolean ignoreRevs) { - this.ignoreRevs = ignoreRevs; - return this; - } - - public String getIfMatch() { - return ifMatch; - } - - /** - * @param ifMatch - * replace a document based on target revision - * @return options - */ - public DocumentReplaceOptions ifMatch(final String ifMatch) { - this.ifMatch = ifMatch; - return this; - } - - public Boolean getReturnNew() { - return returnNew; - } - - /** - * @param returnNew - * Return additionally the complete new document under the attribute new in the result. - * @return options - */ - public DocumentReplaceOptions returnNew(final Boolean returnNew) { - this.returnNew = returnNew; - return this; - } - - public Boolean getReturnOld() { - return returnOld; - } - - /** - * @param returnOld - * Return additionally the complete previous revision of the changed document under the attribute old in - * the result. - * @return options - */ - public DocumentReplaceOptions returnOld(final Boolean returnOld) { - this.returnOld = returnOld; - return this; - } - - public Boolean getSilent() { - return silent; - } - - /** - * @param silent - * If set to true, an empty object will be returned as response. No meta-data will be returned for the - * created document. This option can be used to save some network traffic. - * @return options - */ - public DocumentReplaceOptions silent(final Boolean silent) { - this.silent = silent; - return this; - } - - public String getStreamTransactionId() { - return streamTransactionId; - } - - /** - * @param streamTransactionId If set, the operation will be executed within the transaction. - * @return options - * @since ArangoDB 3.5.0 - */ - public DocumentReplaceOptions streamTransactionId(final String streamTransactionId) { - this.streamTransactionId = streamTransactionId; - return this; - } + private Boolean waitForSync; + private Boolean ignoreRevs; + private String ifMatch; + private Boolean returnNew; + private Boolean returnOld; + private Boolean silent; + private String streamTransactionId; + + public DocumentReplaceOptions() { + super(); + } + + public Boolean getWaitForSync() { + return waitForSync; + } + + /** + * @param waitForSync Wait until document has been synced to disk. + * @return options + */ + public DocumentReplaceOptions waitForSync(final Boolean waitForSync) { + this.waitForSync = waitForSync; + return this; + } + + public Boolean getIgnoreRevs() { + return ignoreRevs; + } + + /** + * @param ignoreRevs By default, or if this is set to true, the _rev attributes in the given document is ignored. If this + * is set to false, then the _rev attribute given in the body document is taken as a precondition. The + * document is only replaced if the current revision is the one specified. + * @return options + */ + public DocumentReplaceOptions ignoreRevs(final Boolean ignoreRevs) { + this.ignoreRevs = ignoreRevs; + return this; + } + + public String getIfMatch() { + return ifMatch; + } + + /** + * @param ifMatch replace a document based on target revision + * @return options + */ + public DocumentReplaceOptions ifMatch(final String ifMatch) { + this.ifMatch = ifMatch; + return this; + } + + public Boolean getReturnNew() { + return returnNew; + } + + /** + * @param returnNew Return additionally the complete new document under the attribute new in the result. + * @return options + */ + public DocumentReplaceOptions returnNew(final Boolean returnNew) { + this.returnNew = returnNew; + return this; + } + + public Boolean getReturnOld() { + return returnOld; + } + + /** + * @param returnOld Return additionally the complete previous revision of the changed document under the attribute old in + * the result. + * @return options + */ + public DocumentReplaceOptions returnOld(final Boolean returnOld) { + this.returnOld = returnOld; + return this; + } + + public Boolean getSilent() { + return silent; + } + + /** + * @param silent If set to true, an empty object will be returned as response. No meta-data will be returned for the + * created document. This option can be used to save some network traffic. + * @return options + */ + public DocumentReplaceOptions silent(final Boolean silent) { + this.silent = silent; + return this; + } + + public String getStreamTransactionId() { + return streamTransactionId; + } + + /** + * @param streamTransactionId If set, the operation will be executed within the transaction. + * @return options + * @since ArangoDB 3.5.0 + */ + public DocumentReplaceOptions streamTransactionId(final String streamTransactionId) { + this.streamTransactionId = streamTransactionId; + return this; + } } diff --git a/src/main/java/com/arangodb/model/DocumentUpdateOptions.java b/src/main/java/com/arangodb/model/DocumentUpdateOptions.java index 127ecc0a8..20d7b8cca 100644 --- a/src/main/java/com/arangodb/model/DocumentUpdateOptions.java +++ b/src/main/java/com/arangodb/model/DocumentUpdateOptions.java @@ -28,161 +28,161 @@ */ public class DocumentUpdateOptions { - private Boolean keepNull; - private Boolean mergeObjects; - private Boolean waitForSync; - private Boolean ignoreRevs; - private String ifMatch; - private Boolean returnNew; - private Boolean returnOld; - private Boolean serializeNull; - private Boolean silent; - private String streamTransactionId; - - public DocumentUpdateOptions() { - super(); - } - - public Boolean getKeepNull() { - return keepNull; - } - - /** - * @param keepNull If the intention is to delete existing attributes with the patch command, the URL query parameter - * keepNull can be used with a value of false. This will modify the behavior of the patch command to - * remove any attributes from the existing document that are contained in the patch document with an - * attribute value of null. - * @return options - */ - public DocumentUpdateOptions keepNull(final Boolean keepNull) { - this.keepNull = keepNull; - return this; - } - - public Boolean getMergeObjects() { - return mergeObjects; - } - - /** - * @param mergeObjects Controls whether objects (not arrays) will be merged if present in both the existing and the patch - * document. If set to false, the value in the patch document will overwrite the existing document's - * value. If set to true, objects will be merged. The default is true. - * @return options - */ - public DocumentUpdateOptions mergeObjects(final Boolean mergeObjects) { - this.mergeObjects = mergeObjects; - return this; - } - - public Boolean getWaitForSync() { - return waitForSync; - } - - /** - * @param waitForSync Wait until document has been synced to disk. - * @return options - */ - public DocumentUpdateOptions waitForSync(final Boolean waitForSync) { - this.waitForSync = waitForSync; - return this; - } - - public Boolean getIgnoreRevs() { - return ignoreRevs; - } - - /** - * @param ignoreRevs By default, or if this is set to true, the _rev attributes in the given document is ignored. If this - * is set to false, then the _rev attribute given in the body document is taken as a precondition. The - * document is only updated if the current revision is the one specified. - * @return options - */ - public DocumentUpdateOptions ignoreRevs(final Boolean ignoreRevs) { - this.ignoreRevs = ignoreRevs; - return this; - } - - public String getIfMatch() { - return ifMatch; - } - - /** - * @param ifMatch update a document based on target revision - * @return options - */ - public DocumentUpdateOptions ifMatch(final String ifMatch) { - this.ifMatch = ifMatch; - return this; - } - - public Boolean getReturnNew() { - return returnNew; - } - - /** - * @param returnNew Return additionally the complete new document under the attribute new in the result. - * @return options - */ - public DocumentUpdateOptions returnNew(final Boolean returnNew) { - this.returnNew = returnNew; - return this; - } - - public Boolean getReturnOld() { - return returnOld; - } - - /** - * @param returnOld Return additionally the complete previous revision of the changed document under the attribute old in - * the result. - * @return options - */ - public DocumentUpdateOptions returnOld(final Boolean returnOld) { - this.returnOld = returnOld; - return this; - } - - public Boolean getSerializeNull() { - return serializeNull; - } - - /** - * @param serializeNull By default, or if this is set to true, all fields of the document which have null values are - * serialized to VelocyPack otherwise they are excluded from serialization. Use this to update single - * fields from a stored document. - * @return options - */ - public DocumentUpdateOptions serializeNull(final Boolean serializeNull) { - this.serializeNull = serializeNull; - return this; - } - - public Boolean getSilent() { - return silent; - } - - /** - * @param silent If set to true, an empty object will be returned as response. No meta-data will be returned for the - * created document. This option can be used to save some network traffic. - * @return options - */ - public DocumentUpdateOptions silent(final Boolean silent) { - this.silent = silent; - return this; - } - - public String getStreamTransactionId() { - return streamTransactionId; - } - - /** - * @param streamTransactionId If set, the operation will be executed within the transaction. - * @return options - * @since ArangoDB 3.5.0 - */ - public DocumentUpdateOptions streamTransactionId(final String streamTransactionId) { - this.streamTransactionId = streamTransactionId; - return this; - } + private Boolean keepNull; + private Boolean mergeObjects; + private Boolean waitForSync; + private Boolean ignoreRevs; + private String ifMatch; + private Boolean returnNew; + private Boolean returnOld; + private Boolean serializeNull; + private Boolean silent; + private String streamTransactionId; + + public DocumentUpdateOptions() { + super(); + } + + public Boolean getKeepNull() { + return keepNull; + } + + /** + * @param keepNull If the intention is to delete existing attributes with the patch command, the URL query parameter + * keepNull can be used with a value of false. This will modify the behavior of the patch command to + * remove any attributes from the existing document that are contained in the patch document with an + * attribute value of null. + * @return options + */ + public DocumentUpdateOptions keepNull(final Boolean keepNull) { + this.keepNull = keepNull; + return this; + } + + public Boolean getMergeObjects() { + return mergeObjects; + } + + /** + * @param mergeObjects Controls whether objects (not arrays) will be merged if present in both the existing and the patch + * document. If set to false, the value in the patch document will overwrite the existing document's + * value. If set to true, objects will be merged. The default is true. + * @return options + */ + public DocumentUpdateOptions mergeObjects(final Boolean mergeObjects) { + this.mergeObjects = mergeObjects; + return this; + } + + public Boolean getWaitForSync() { + return waitForSync; + } + + /** + * @param waitForSync Wait until document has been synced to disk. + * @return options + */ + public DocumentUpdateOptions waitForSync(final Boolean waitForSync) { + this.waitForSync = waitForSync; + return this; + } + + public Boolean getIgnoreRevs() { + return ignoreRevs; + } + + /** + * @param ignoreRevs By default, or if this is set to true, the _rev attributes in the given document is ignored. If this + * is set to false, then the _rev attribute given in the body document is taken as a precondition. The + * document is only updated if the current revision is the one specified. + * @return options + */ + public DocumentUpdateOptions ignoreRevs(final Boolean ignoreRevs) { + this.ignoreRevs = ignoreRevs; + return this; + } + + public String getIfMatch() { + return ifMatch; + } + + /** + * @param ifMatch update a document based on target revision + * @return options + */ + public DocumentUpdateOptions ifMatch(final String ifMatch) { + this.ifMatch = ifMatch; + return this; + } + + public Boolean getReturnNew() { + return returnNew; + } + + /** + * @param returnNew Return additionally the complete new document under the attribute new in the result. + * @return options + */ + public DocumentUpdateOptions returnNew(final Boolean returnNew) { + this.returnNew = returnNew; + return this; + } + + public Boolean getReturnOld() { + return returnOld; + } + + /** + * @param returnOld Return additionally the complete previous revision of the changed document under the attribute old in + * the result. + * @return options + */ + public DocumentUpdateOptions returnOld(final Boolean returnOld) { + this.returnOld = returnOld; + return this; + } + + public Boolean getSerializeNull() { + return serializeNull; + } + + /** + * @param serializeNull By default, or if this is set to true, all fields of the document which have null values are + * serialized to VelocyPack otherwise they are excluded from serialization. Use this to update single + * fields from a stored document. + * @return options + */ + public DocumentUpdateOptions serializeNull(final Boolean serializeNull) { + this.serializeNull = serializeNull; + return this; + } + + public Boolean getSilent() { + return silent; + } + + /** + * @param silent If set to true, an empty object will be returned as response. No meta-data will be returned for the + * created document. This option can be used to save some network traffic. + * @return options + */ + public DocumentUpdateOptions silent(final Boolean silent) { + this.silent = silent; + return this; + } + + public String getStreamTransactionId() { + return streamTransactionId; + } + + /** + * @param streamTransactionId If set, the operation will be executed within the transaction. + * @return options + * @since ArangoDB 3.5.0 + */ + public DocumentUpdateOptions streamTransactionId(final String streamTransactionId) { + this.streamTransactionId = streamTransactionId; + return this; + } } diff --git a/src/main/java/com/arangodb/model/EdgeDeleteOptions.java b/src/main/java/com/arangodb/model/EdgeDeleteOptions.java index b7c600760..30d13c117 100644 --- a/src/main/java/com/arangodb/model/EdgeDeleteOptions.java +++ b/src/main/java/com/arangodb/model/EdgeDeleteOptions.java @@ -22,46 +22,43 @@ /** * @author Mark Vollmary - * * @see API Documentation */ public class EdgeDeleteOptions { - private Boolean waitForSync; - private String ifMatch; + private Boolean waitForSync; + private String ifMatch; private String streamTransactionId; - public EdgeDeleteOptions() { - super(); - } + public EdgeDeleteOptions() { + super(); + } - public Boolean getWaitForSync() { - return waitForSync; - } + public Boolean getWaitForSync() { + return waitForSync; + } - /** - * @param waitForSync - * Wait until deletion operation has been synced to disk. - * @return options - */ - public EdgeDeleteOptions waitForSync(final Boolean waitForSync) { - this.waitForSync = waitForSync; - return this; - } + /** + * @param waitForSync Wait until deletion operation has been synced to disk. + * @return options + */ + public EdgeDeleteOptions waitForSync(final Boolean waitForSync) { + this.waitForSync = waitForSync; + return this; + } - public String getIfMatch() { - return ifMatch; - } + public String getIfMatch() { + return ifMatch; + } - /** - * @param ifMatch - * remove a document based on a target revision - * @return options - */ - public EdgeDeleteOptions ifMatch(final String ifMatch) { - this.ifMatch = ifMatch; - return this; - } + /** + * @param ifMatch remove a document based on a target revision + * @return options + */ + public EdgeDeleteOptions ifMatch(final String ifMatch) { + this.ifMatch = ifMatch; + return this; + } public String getStreamTransactionId() { return streamTransactionId; diff --git a/src/main/java/com/arangodb/model/EdgeReplaceOptions.java b/src/main/java/com/arangodb/model/EdgeReplaceOptions.java index 47f553159..81f021ea0 100644 --- a/src/main/java/com/arangodb/model/EdgeReplaceOptions.java +++ b/src/main/java/com/arangodb/model/EdgeReplaceOptions.java @@ -22,46 +22,43 @@ /** * @author Mark Vollmary - * * @see API Documentation */ public class EdgeReplaceOptions { - private Boolean waitForSync; - private String ifMatch; + private Boolean waitForSync; + private String ifMatch; private String streamTransactionId; - public EdgeReplaceOptions() { - super(); - } + public EdgeReplaceOptions() { + super(); + } - public Boolean getWaitForSync() { - return waitForSync; - } + public Boolean getWaitForSync() { + return waitForSync; + } - /** - * @param waitForSync - * Wait until document has been synced to disk. - * @return options - */ - public EdgeReplaceOptions waitForSync(final Boolean waitForSync) { - this.waitForSync = waitForSync; - return this; - } + /** + * @param waitForSync Wait until document has been synced to disk. + * @return options + */ + public EdgeReplaceOptions waitForSync(final Boolean waitForSync) { + this.waitForSync = waitForSync; + return this; + } - public String getIfMatch() { - return ifMatch; - } + public String getIfMatch() { + return ifMatch; + } - /** - * @param ifMatch - * replace a document based on target revision - * @return options - */ - public EdgeReplaceOptions ifMatch(final String ifMatch) { - this.ifMatch = ifMatch; - return this; - } + /** + * @param ifMatch replace a document based on target revision + * @return options + */ + public EdgeReplaceOptions ifMatch(final String ifMatch) { + this.ifMatch = ifMatch; + return this; + } public String getStreamTransactionId() { return streamTransactionId; diff --git a/src/main/java/com/arangodb/model/EdgeUpdateOptions.java b/src/main/java/com/arangodb/model/EdgeUpdateOptions.java index f3f97c5c5..cb95ddd85 100644 --- a/src/main/java/com/arangodb/model/EdgeUpdateOptions.java +++ b/src/main/java/com/arangodb/model/EdgeUpdateOptions.java @@ -22,64 +22,60 @@ /** * @author Mark Vollmary - * * @see API Documentation */ public class EdgeUpdateOptions { - private Boolean keepNull; - private Boolean waitForSync; - private String ifMatch; + private Boolean keepNull; + private Boolean waitForSync; + private String ifMatch; private String streamTransactionId; - public EdgeUpdateOptions() { - super(); - } + public EdgeUpdateOptions() { + super(); + } - public Boolean getKeepNull() { - return keepNull; - } + public Boolean getKeepNull() { + return keepNull; + } - /** - * @param keepNull - * If the intention is to delete existing attributes with the patch command, the URL query parameter - * keepNull can be used with a value of false. This will modify the behavior of the patch command to - * remove any attributes from the existing document that are contained in the patch document with an - * attribute value of null. - * @return options - */ - public EdgeUpdateOptions keepNull(final Boolean keepNull) { - this.keepNull = keepNull; - return this; - } + /** + * @param keepNull If the intention is to delete existing attributes with the patch command, the URL query parameter + * keepNull can be used with a value of false. This will modify the behavior of the patch command to + * remove any attributes from the existing document that are contained in the patch document with an + * attribute value of null. + * @return options + */ + public EdgeUpdateOptions keepNull(final Boolean keepNull) { + this.keepNull = keepNull; + return this; + } - public Boolean getWaitForSync() { - return waitForSync; - } + public Boolean getWaitForSync() { + return waitForSync; + } - /** - * @param waitForSync - * Wait until document has been synced to disk. - * @return options - */ - public EdgeUpdateOptions waitForSync(final Boolean waitForSync) { - this.waitForSync = waitForSync; - return this; - } + /** + * @param waitForSync Wait until document has been synced to disk. + * @return options + */ + public EdgeUpdateOptions waitForSync(final Boolean waitForSync) { + this.waitForSync = waitForSync; + return this; + } - public String getIfMatch() { - return ifMatch; - } + public String getIfMatch() { + return ifMatch; + } - /** - * @param ifMatch - * replace a document based on target revision - * @return options - */ - public EdgeUpdateOptions ifMatch(final String ifMatch) { - this.ifMatch = ifMatch; - return this; - } + /** + * @param ifMatch replace a document based on target revision + * @return options + */ + public EdgeUpdateOptions ifMatch(final String ifMatch) { + this.ifMatch = ifMatch; + return this; + } public String getStreamTransactionId() { return streamTransactionId; diff --git a/src/main/java/com/arangodb/model/FulltextIndexOptions.java b/src/main/java/com/arangodb/model/FulltextIndexOptions.java index 4cb51e73d..9bf8f82a5 100644 --- a/src/main/java/com/arangodb/model/FulltextIndexOptions.java +++ b/src/main/java/com/arangodb/model/FulltextIndexOptions.java @@ -24,56 +24,53 @@ /** * @author Mark Vollmary - * * @see API - * Documentation + * Documentation */ public class FulltextIndexOptions extends IndexOptions { - private Iterable fields; - private final IndexType type = IndexType.fulltext; - private Integer minLength; + private Iterable fields; + private final IndexType type = IndexType.fulltext; + private Integer minLength; - public FulltextIndexOptions() { - super(); - } + public FulltextIndexOptions() { + super(); + } @Override protected FulltextIndexOptions getThis() { return this; } - protected Iterable getFields() { - return fields; - } + protected Iterable getFields() { + return fields; + } - /** - * @param fields - * A list of attribute paths - * @return options - */ - protected FulltextIndexOptions fields(final Iterable fields) { - this.fields = fields; - return this; - } + /** + * @param fields A list of attribute paths + * @return options + */ + protected FulltextIndexOptions fields(final Iterable fields) { + this.fields = fields; + return this; + } - protected IndexType getType() { - return type; - } + protected IndexType getType() { + return type; + } - public Integer getMinLength() { - return minLength; - } + public Integer getMinLength() { + return minLength; + } - /** - * @param minLength - * Minimum character length of words to index. Will default to a server-defined value if unspecified. It - * is thus recommended to set this value explicitly when creating the index. - * @return options - */ - public FulltextIndexOptions minLength(final Integer minLength) { - this.minLength = minLength; - return this; - } + /** + * @param minLength Minimum character length of words to index. Will default to a server-defined value if unspecified. It + * is thus recommended to set this value explicitly when creating the index. + * @return options + */ + public FulltextIndexOptions minLength(final Integer minLength) { + this.minLength = minLength; + return this; + } } diff --git a/src/main/java/com/arangodb/model/GeoIndexOptions.java b/src/main/java/com/arangodb/model/GeoIndexOptions.java index 912c2283c..691ed0ec2 100644 --- a/src/main/java/com/arangodb/model/GeoIndexOptions.java +++ b/src/main/java/com/arangodb/model/GeoIndexOptions.java @@ -24,55 +24,52 @@ /** * @author Mark Vollmary - * * @see API Documentation */ public class GeoIndexOptions extends IndexOptions { - private Iterable fields; - private final IndexType type = IndexType.geo; - private Boolean geoJson; + private Iterable fields; + private final IndexType type = IndexType.geo; + private Boolean geoJson; - public GeoIndexOptions() { - super(); - } + public GeoIndexOptions() { + super(); + } @Override protected GeoIndexOptions getThis() { return this; } - protected Iterable getFields() { - return fields; - } + protected Iterable getFields() { + return fields; + } - /** - * @param fields - * A list of attribute paths - * @return options - */ - protected GeoIndexOptions fields(final Iterable fields) { - this.fields = fields; - return this; - } + /** + * @param fields A list of attribute paths + * @return options + */ + protected GeoIndexOptions fields(final Iterable fields) { + this.fields = fields; + return this; + } - protected IndexType getType() { - return type; - } + protected IndexType getType() { + return type; + } - public Boolean getGeoJson() { - return geoJson; - } + public Boolean getGeoJson() { + return geoJson; + } - /** - * @param geoJson - * If a geo-spatial index on a location is constructed and geoJson is true, then the order within the - * array is longitude followed by latitude. This corresponds to the format described in - * @return options - */ - public GeoIndexOptions geoJson(final Boolean geoJson) { - this.geoJson = geoJson; - return this; - } + /** + * @param geoJson If a geo-spatial index on a location is constructed and geoJson is true, then the order within the + * array is longitude followed by latitude. This corresponds to the format described in + * @return options + */ + public GeoIndexOptions geoJson(final Boolean geoJson) { + this.geoJson = geoJson; + return this; + } } diff --git a/src/main/java/com/arangodb/model/GraphCreateOptions.java b/src/main/java/com/arangodb/model/GraphCreateOptions.java index ae74b93e8..76c48705f 100644 --- a/src/main/java/com/arangodb/model/GraphCreateOptions.java +++ b/src/main/java/com/arangodb/model/GraphCreateOptions.java @@ -20,205 +20,194 @@ package com.arangodb.model; +import com.arangodb.entity.EdgeDefinition; + import java.util.Arrays; import java.util.Collection; -import com.arangodb.entity.EdgeDefinition; - /** * @author Mark Vollmary - * * @see API Documentation */ public class GraphCreateOptions { - private String name; - private Collection edgeDefinitions; - private Collection orphanCollections; - private Boolean isSmart; - private SmartOptions options; - - public GraphCreateOptions() { - super(); - } - - protected String getName() { - return name; - } - - /** - * @param name - * Name of the graph - * @return options - */ - protected GraphCreateOptions name(final String name) { - this.name = name; - return this; - } - - public Collection getEdgeDefinitions() { - return edgeDefinitions; - } - - /** - * @param edgeDefinitions - * An array of definitions for the edge - * @return options - */ - protected GraphCreateOptions edgeDefinitions(final Collection edgeDefinitions) { - this.edgeDefinitions = edgeDefinitions; - return this; - } - - public Collection getOrphanCollections() { - return orphanCollections; - } - - /** - * @param orphanCollections - * Additional vertex collections - * @return options - */ - public GraphCreateOptions orphanCollections(final String... orphanCollections) { - this.orphanCollections = Arrays.asList(orphanCollections); - return this; - } - - public Boolean getIsSmart() { - return isSmart; - } - - /** - * - * @param isSmart - * Define if the created graph should be smart. This only has effect in Enterprise version. - * @return options - */ - public GraphCreateOptions isSmart(final Boolean isSmart) { - this.isSmart = isSmart; - return this; - } - - public Integer getReplicationFactor() { - return getOptions().getReplicationFactor(); - } - - /** - * @param replicationFactor - * (The default is 1): in a cluster, this attribute determines how many copies of each shard are kept on - * different DBServers. The value 1 means that only one copy (no synchronous replication) is kept. A - * value of k means that k-1 replicas are kept. Any two copies reside on different DBServers. Replication - * between them is synchronous, that is, every write operation to the "leader" copy will be replicated to - * all "follower" replicas, before the write operation is reported successful. If a server fails, this is - * detected automatically and one of the servers holding copies take over, usually without an error being - * reported. - * @return options - */ - public GraphCreateOptions replicationFactor(final Integer replicationFactor) { - getOptions().setReplicationFactor(replicationFactor); - return this; - } - - public Integer getMinReplicationFactor() { - return getOptions().getMinReplicationFactor(); - } - - /** - * @param minReplicationFactor - * (optional, default is 1): in a cluster, this attribute determines how many desired copies of each - * shard are kept on different DBServers. The value 1 means that only one copy (no synchronous - * replication) is kept. A value of k means that desired k-1 replicas are kept. If in a failover scenario - * a shard of a collection has less than minReplicationFactor many insync followers it will go into - * "read-only" mode and will reject writes until enough followers are insync again. In more detail: - * Having `minReplicationFactor == 1` means as soon as a "master-copy" is available of the data writes - * are allowed. Having `minReplicationFactor > 1` requires additional insync copies on follower servers - * to allow writes. - * - * @return options - */ - public GraphCreateOptions minReplicationFactor(final Integer minReplicationFactor) { - getOptions().setMinReplicationFactor(minReplicationFactor); - return this; - } - - public Integer getNumberOfShards() { - return getOptions().getNumberOfShards(); - } - - /** - * @param numberOfShards - * The number of shards that is used for every collection within this graph. Cannot be modified later. - * @return options - */ - public GraphCreateOptions numberOfShards(final Integer numberOfShards) { - getOptions().setNumberOfShards(numberOfShards); - return this; - } - - public String getSmartGraphAttribute() { - return getOptions().getSmartGraphAttribute(); - } - - /** - * @param smartGraphAttribute - * The attribute name that is used to smartly shard the vertices of a graph. Every vertex in this Graph - * has to have this attribute. Cannot be modified later. - * @return options - */ - public GraphCreateOptions smartGraphAttribute(final String smartGraphAttribute) { - getOptions().setSmartGraphAttribute(smartGraphAttribute); - return this; - } - - private SmartOptions getOptions() { - if (options == null) { - options = new SmartOptions(); - } - return options; - } - - public static class SmartOptions { - private Integer replicationFactor; - private Integer minReplicationFactor; - private Integer numberOfShards; - private String smartGraphAttribute; - - public SmartOptions() { - super(); - } - - public Integer getReplicationFactor() { - return replicationFactor; - } - - public void setReplicationFactor(final Integer replicationFactor) { - this.replicationFactor = replicationFactor; - } - - public Integer getMinReplicationFactor() { - return minReplicationFactor; - } - - public void setMinReplicationFactor(final Integer minReplicationFactor) { - this.minReplicationFactor = minReplicationFactor; - } - - public Integer getNumberOfShards() { - return numberOfShards; - } - - public void setNumberOfShards(final Integer numberOfShards) { - this.numberOfShards = numberOfShards; - } - - public String getSmartGraphAttribute() { - return smartGraphAttribute; - } - - public void setSmartGraphAttribute(final String smartGraphAttribute) { - this.smartGraphAttribute = smartGraphAttribute; - } - - } + private String name; + private Collection edgeDefinitions; + private Collection orphanCollections; + private Boolean isSmart; + private SmartOptions options; + + public GraphCreateOptions() { + super(); + } + + protected String getName() { + return name; + } + + /** + * @param name Name of the graph + * @return options + */ + protected GraphCreateOptions name(final String name) { + this.name = name; + return this; + } + + public Collection getEdgeDefinitions() { + return edgeDefinitions; + } + + /** + * @param edgeDefinitions An array of definitions for the edge + * @return options + */ + protected GraphCreateOptions edgeDefinitions(final Collection edgeDefinitions) { + this.edgeDefinitions = edgeDefinitions; + return this; + } + + public Collection getOrphanCollections() { + return orphanCollections; + } + + /** + * @param orphanCollections Additional vertex collections + * @return options + */ + public GraphCreateOptions orphanCollections(final String... orphanCollections) { + this.orphanCollections = Arrays.asList(orphanCollections); + return this; + } + + public Boolean getIsSmart() { + return isSmart; + } + + /** + * @param isSmart Define if the created graph should be smart. This only has effect in Enterprise version. + * @return options + */ + public GraphCreateOptions isSmart(final Boolean isSmart) { + this.isSmart = isSmart; + return this; + } + + public Integer getReplicationFactor() { + return getOptions().getReplicationFactor(); + } + + /** + * @param replicationFactor (The default is 1): in a cluster, this attribute determines how many copies of each shard are kept on + * different DBServers. The value 1 means that only one copy (no synchronous replication) is kept. A + * value of k means that k-1 replicas are kept. Any two copies reside on different DBServers. Replication + * between them is synchronous, that is, every write operation to the "leader" copy will be replicated to + * all "follower" replicas, before the write operation is reported successful. If a server fails, this is + * detected automatically and one of the servers holding copies take over, usually without an error being + * reported. + * @return options + */ + public GraphCreateOptions replicationFactor(final Integer replicationFactor) { + getOptions().setReplicationFactor(replicationFactor); + return this; + } + + public Integer getMinReplicationFactor() { + return getOptions().getMinReplicationFactor(); + } + + /** + * @param minReplicationFactor (optional, default is 1): in a cluster, this attribute determines how many desired copies of each + * shard are kept on different DBServers. The value 1 means that only one copy (no synchronous + * replication) is kept. A value of k means that desired k-1 replicas are kept. If in a failover scenario + * a shard of a collection has less than minReplicationFactor many insync followers it will go into + * "read-only" mode and will reject writes until enough followers are insync again. In more detail: + * Having `minReplicationFactor == 1` means as soon as a "master-copy" is available of the data writes + * are allowed. Having `minReplicationFactor > 1` requires additional insync copies on follower servers + * to allow writes. + * @return options + */ + public GraphCreateOptions minReplicationFactor(final Integer minReplicationFactor) { + getOptions().setMinReplicationFactor(minReplicationFactor); + return this; + } + + public Integer getNumberOfShards() { + return getOptions().getNumberOfShards(); + } + + /** + * @param numberOfShards The number of shards that is used for every collection within this graph. Cannot be modified later. + * @return options + */ + public GraphCreateOptions numberOfShards(final Integer numberOfShards) { + getOptions().setNumberOfShards(numberOfShards); + return this; + } + + public String getSmartGraphAttribute() { + return getOptions().getSmartGraphAttribute(); + } + + /** + * @param smartGraphAttribute The attribute name that is used to smartly shard the vertices of a graph. Every vertex in this Graph + * has to have this attribute. Cannot be modified later. + * @return options + */ + public GraphCreateOptions smartGraphAttribute(final String smartGraphAttribute) { + getOptions().setSmartGraphAttribute(smartGraphAttribute); + return this; + } + + private SmartOptions getOptions() { + if (options == null) { + options = new SmartOptions(); + } + return options; + } + + public static class SmartOptions { + private Integer replicationFactor; + private Integer minReplicationFactor; + private Integer numberOfShards; + private String smartGraphAttribute; + + public SmartOptions() { + super(); + } + + public Integer getReplicationFactor() { + return replicationFactor; + } + + public void setReplicationFactor(final Integer replicationFactor) { + this.replicationFactor = replicationFactor; + } + + public Integer getMinReplicationFactor() { + return minReplicationFactor; + } + + public void setMinReplicationFactor(final Integer minReplicationFactor) { + this.minReplicationFactor = minReplicationFactor; + } + + public Integer getNumberOfShards() { + return numberOfShards; + } + + public void setNumberOfShards(final Integer numberOfShards) { + this.numberOfShards = numberOfShards; + } + + public String getSmartGraphAttribute() { + return smartGraphAttribute; + } + + public void setSmartGraphAttribute(final String smartGraphAttribute) { + this.smartGraphAttribute = smartGraphAttribute; + } + + } } diff --git a/src/main/java/com/arangodb/model/GraphDocumentReadOptions.java b/src/main/java/com/arangodb/model/GraphDocumentReadOptions.java index a43a49e6f..1e661f64d 100644 --- a/src/main/java/com/arangodb/model/GraphDocumentReadOptions.java +++ b/src/main/java/com/arangodb/model/GraphDocumentReadOptions.java @@ -27,72 +27,72 @@ */ public class GraphDocumentReadOptions { - private String ifNoneMatch; - private String ifMatch; - private boolean catchException; - @Expose(serialize = false) - private Boolean allowDirtyRead; + private String ifNoneMatch; + private String ifMatch; + private boolean catchException; + @Expose(serialize = false) + private Boolean allowDirtyRead; private String streamTransactionId; - public GraphDocumentReadOptions() { - super(); - catchException = true; - } - - public String getIfNoneMatch() { - return ifNoneMatch; - } - - /** - * @param ifNoneMatch document revision must not contain If-None-Match - * @return options - */ - public GraphDocumentReadOptions ifNoneMatch(final String ifNoneMatch) { - this.ifNoneMatch = ifNoneMatch; - return this; - } - - public String getIfMatch() { - return ifMatch; - } - - /** - * @param ifMatch document revision must contain If-Match - * @return options - */ - public GraphDocumentReadOptions ifMatch(final String ifMatch) { - this.ifMatch = ifMatch; - return this; - } - - public boolean isCatchException() { - return catchException; - } - - /** - * @param catchException whether or not catch possible thrown exceptions - * @return options - */ - public GraphDocumentReadOptions catchException(final boolean catchException) { - this.catchException = catchException; - return this; - } - - /** - * @param allowDirtyRead Set to {@code true} allows reading from followers in an active-failover setup. - * @return options - * @see API - * Documentation - * @since ArangoDB 3.4.0 - */ - public GraphDocumentReadOptions allowDirtyRead(final Boolean allowDirtyRead) { - this.allowDirtyRead = allowDirtyRead; - return this; - } - - public Boolean getAllowDirtyRead() { - return allowDirtyRead; - } + public GraphDocumentReadOptions() { + super(); + catchException = true; + } + + public String getIfNoneMatch() { + return ifNoneMatch; + } + + /** + * @param ifNoneMatch document revision must not contain If-None-Match + * @return options + */ + public GraphDocumentReadOptions ifNoneMatch(final String ifNoneMatch) { + this.ifNoneMatch = ifNoneMatch; + return this; + } + + public String getIfMatch() { + return ifMatch; + } + + /** + * @param ifMatch document revision must contain If-Match + * @return options + */ + public GraphDocumentReadOptions ifMatch(final String ifMatch) { + this.ifMatch = ifMatch; + return this; + } + + public boolean isCatchException() { + return catchException; + } + + /** + * @param catchException whether or not catch possible thrown exceptions + * @return options + */ + public GraphDocumentReadOptions catchException(final boolean catchException) { + this.catchException = catchException; + return this; + } + + /** + * @param allowDirtyRead Set to {@code true} allows reading from followers in an active-failover setup. + * @return options + * @see API + * Documentation + * @since ArangoDB 3.4.0 + */ + public GraphDocumentReadOptions allowDirtyRead(final Boolean allowDirtyRead) { + this.allowDirtyRead = allowDirtyRead; + return this; + } + + public Boolean getAllowDirtyRead() { + return allowDirtyRead; + } public String getStreamTransactionId() { return streamTransactionId; diff --git a/src/main/java/com/arangodb/model/HashIndexOptions.java b/src/main/java/com/arangodb/model/HashIndexOptions.java index e5e80a8aa..992c79281 100644 --- a/src/main/java/com/arangodb/model/HashIndexOptions.java +++ b/src/main/java/com/arangodb/model/HashIndexOptions.java @@ -24,83 +24,78 @@ /** * @author Mark Vollmary - * * @see API Documentation */ public class HashIndexOptions extends IndexOptions { - private Iterable fields; - private final IndexType type = IndexType.hash; - private Boolean unique; - private Boolean sparse; - private Boolean deduplicate; + private Iterable fields; + private final IndexType type = IndexType.hash; + private Boolean unique; + private Boolean sparse; + private Boolean deduplicate; - public HashIndexOptions() { - super(); - } + public HashIndexOptions() { + super(); + } @Override protected HashIndexOptions getThis() { return this; } - protected Iterable getFields() { - return fields; - } + protected Iterable getFields() { + return fields; + } - /** - * @param fields - * A list of attribute paths - * @return options - */ - protected HashIndexOptions fields(final Iterable fields) { - this.fields = fields; - return this; - } + /** + * @param fields A list of attribute paths + * @return options + */ + protected HashIndexOptions fields(final Iterable fields) { + this.fields = fields; + return this; + } - protected IndexType getType() { - return type; - } + protected IndexType getType() { + return type; + } - public Boolean getUnique() { - return unique; - } + public Boolean getUnique() { + return unique; + } - /** - * @param unique - * if true, then create a unique index - * @return options - */ - public HashIndexOptions unique(final Boolean unique) { - this.unique = unique; - return this; - } + /** + * @param unique if true, then create a unique index + * @return options + */ + public HashIndexOptions unique(final Boolean unique) { + this.unique = unique; + return this; + } - public Boolean getSparse() { - return sparse; - } + public Boolean getSparse() { + return sparse; + } - /** - * @param sparse - * if true, then create a sparse index - * @return options - */ - public HashIndexOptions sparse(final Boolean sparse) { - this.sparse = sparse; - return this; - } + /** + * @param sparse if true, then create a sparse index + * @return options + */ + public HashIndexOptions sparse(final Boolean sparse) { + this.sparse = sparse; + return this; + } - public Boolean getDeduplicate() { - return deduplicate; - } + public Boolean getDeduplicate() { + return deduplicate; + } - /** - * @param deduplicate - * if false, the deduplication of array values is turned off. - * @return options - */ - public HashIndexOptions deduplicate(final Boolean deduplicate) { - this.deduplicate = deduplicate; - return this; - } + /** + * @param deduplicate if false, the deduplication of array values is turned off. + * @return options + */ + public HashIndexOptions deduplicate(final Boolean deduplicate) { + this.deduplicate = deduplicate; + return this; + } } diff --git a/src/main/java/com/arangodb/model/ImportType.java b/src/main/java/com/arangodb/model/ImportType.java index 3d7c82c1c..17e4d5573 100644 --- a/src/main/java/com/arangodb/model/ImportType.java +++ b/src/main/java/com/arangodb/model/ImportType.java @@ -22,8 +22,7 @@ /** * @author Mark Vollmary - * */ public enum ImportType { - documents, list, auto + documents, list, auto } diff --git a/src/main/java/com/arangodb/model/IndexOptions.java b/src/main/java/com/arangodb/model/IndexOptions.java index 512f7d2b6..1132e1c8e 100644 --- a/src/main/java/com/arangodb/model/IndexOptions.java +++ b/src/main/java/com/arangodb/model/IndexOptions.java @@ -31,7 +31,7 @@ public abstract class IndexOptions { private String name; public IndexOptions() { - super(); + super(); } protected abstract T getThis(); diff --git a/src/main/java/com/arangodb/model/LogOptions.java b/src/main/java/com/arangodb/model/LogOptions.java index 47eddb890..9a37cdf08 100644 --- a/src/main/java/com/arangodb/model/LogOptions.java +++ b/src/main/java/com/arangodb/model/LogOptions.java @@ -24,136 +24,128 @@ /** * @author Mark Vollmary - * * @see API - * Documentation + * "https://www.arangodb.com/docs/stable/http/administration-and-monitoring.html#read-global-logs-from-the-server">API + * Documentation */ public class LogOptions { - public static final String PROPERTY_UPTO = "upto"; - public static final String PROPERTY_LEVEL = "level"; - public static final String PROPERTY_START = "start"; - public static final String PROPERTY_SIZE = "size"; - public static final String PROPERTY_OFFSET = "offset"; - public static final String PROPERTY_SEARCH = "search"; - public static final String PROPERTY_SORT = "sort"; - - public enum SortOrder { - asc, desc - } - - private LogLevel upto; - private LogLevel level; - private Long start; - private Integer size; - private Integer offset; - private String search; - private SortOrder sort; - - public LogOptions() { - super(); - } - - public LogLevel getUpto() { - return upto; - } - - /** - * @param upto - * Returns all log entries up to log level upto - * @return options - */ - public LogOptions upto(final LogLevel upto) { - this.upto = upto; - return this; - } - - public LogLevel getLevel() { - return level; - } - - /** - * @param level - * Returns all log entries of log level level. Note that the query parameters upto and level are mutually - * exclusive - * @return options - */ - public LogOptions level(final LogLevel level) { - this.level = level; - return this; - } - - public Long getStart() { - return start; - } - - /** - * @param start - * Returns all log entries such that their log entry identifier (lid value) is greater or equal to start - * @return options - */ - public LogOptions start(final Long start) { - this.start = start; - return this; - } - - public Integer getSize() { - return size; - } - - /** - * @param size - * Restricts the result to at most size log entries - * @return options - */ - public LogOptions size(final Integer size) { - this.size = size; - return this; - } - - public Integer getOffset() { - return offset; - } - - /** - * @param offset - * Starts to return log entries skipping the first offset log entries. offset and size can be used for - * pagination - * @return options - */ - public LogOptions offset(final Integer offset) { - this.offset = offset; - return this; - } - - public String getSearch() { - return search; - } - - /** - * @param search - * Only return the log entries containing the text specified in search - * @return options - */ - public LogOptions search(final String search) { - this.search = search; - return this; - } - - public SortOrder getSort() { - return sort; - } - - /** - * @param sort - * Sort the log entries either ascending (if sort is asc) or descending (if sort is desc) according to - * their lid values. Note that the lid imposes a chronological order. The default value is asc - * @return options - */ - public LogOptions sort(final SortOrder sort) { - this.sort = sort; - return this; - } + public static final String PROPERTY_UPTO = "upto"; + public static final String PROPERTY_LEVEL = "level"; + public static final String PROPERTY_START = "start"; + public static final String PROPERTY_SIZE = "size"; + public static final String PROPERTY_OFFSET = "offset"; + public static final String PROPERTY_SEARCH = "search"; + public static final String PROPERTY_SORT = "sort"; + + public enum SortOrder { + asc, desc + } + + private LogLevel upto; + private LogLevel level; + private Long start; + private Integer size; + private Integer offset; + private String search; + private SortOrder sort; + + public LogOptions() { + super(); + } + + public LogLevel getUpto() { + return upto; + } + + /** + * @param upto Returns all log entries up to log level upto + * @return options + */ + public LogOptions upto(final LogLevel upto) { + this.upto = upto; + return this; + } + + public LogLevel getLevel() { + return level; + } + + /** + * @param level Returns all log entries of log level level. Note that the query parameters upto and level are mutually + * exclusive + * @return options + */ + public LogOptions level(final LogLevel level) { + this.level = level; + return this; + } + + public Long getStart() { + return start; + } + + /** + * @param start Returns all log entries such that their log entry identifier (lid value) is greater or equal to start + * @return options + */ + public LogOptions start(final Long start) { + this.start = start; + return this; + } + + public Integer getSize() { + return size; + } + + /** + * @param size Restricts the result to at most size log entries + * @return options + */ + public LogOptions size(final Integer size) { + this.size = size; + return this; + } + + public Integer getOffset() { + return offset; + } + + /** + * @param offset Starts to return log entries skipping the first offset log entries. offset and size can be used for + * pagination + * @return options + */ + public LogOptions offset(final Integer offset) { + this.offset = offset; + return this; + } + + public String getSearch() { + return search; + } + + /** + * @param search Only return the log entries containing the text specified in search + * @return options + */ + public LogOptions search(final String search) { + this.search = search; + return this; + } + + public SortOrder getSort() { + return sort; + } + + /** + * @param sort Sort the log entries either ascending (if sort is asc) or descending (if sort is desc) according to + * their lid values. Note that the lid imposes a chronological order. The default value is asc + * @return options + */ + public LogOptions sort(final SortOrder sort) { + this.sort = sort; + return this; + } } diff --git a/src/main/java/com/arangodb/model/OptionsBuilder.java b/src/main/java/com/arangodb/model/OptionsBuilder.java index 5b2832699..6533bfa0d 100644 --- a/src/main/java/com/arangodb/model/OptionsBuilder.java +++ b/src/main/java/com/arangodb/model/OptionsBuilder.java @@ -30,99 +30,98 @@ /** * @author Mark Vollmary * @author Michele Rastelli - * */ public class OptionsBuilder { - private OptionsBuilder() { - super(); - } - - public static UserCreateOptions build(final UserCreateOptions options, final String user, final String passwd) { - return options.user(user).passwd(passwd); - } - - public static HashIndexOptions build(final HashIndexOptions options, final Iterable fields) { - return options.fields(fields); - } - - public static SkiplistIndexOptions build(final SkiplistIndexOptions options, final Iterable fields) { - return options.fields(fields); - } - - public static PersistentIndexOptions build(final PersistentIndexOptions options, final Iterable fields) { - return options.fields(fields); - } - - public static GeoIndexOptions build(final GeoIndexOptions options, final Iterable fields) { - return options.fields(fields); - } - - public static FulltextIndexOptions build(final FulltextIndexOptions options, final Iterable fields) { - return options.fields(fields); - } - - public static TtlIndexOptions build(final TtlIndexOptions options, final Iterable fields) { - return options.fields(fields); - } - - public static CollectionCreateOptions build(final CollectionCreateOptions options, final String name) { - return options.name(name); - } - - public static AqlQueryOptions build(final AqlQueryOptions options, final String query, final VPackSlice bindVars) { - return options.query(query).bindVars(bindVars); - } - - public static AqlQueryExplainOptions build( - final AqlQueryExplainOptions options, - final String query, - final VPackSlice bindVars) { - return options.query(query).bindVars(bindVars); - } - - public static AqlQueryParseOptions build(final AqlQueryParseOptions options, final String query) { - return options.query(query); - } - - public static GraphCreateOptions build( - final GraphCreateOptions options, - final String name, - final Collection edgeDefinitions) { - return options.name(name).edgeDefinitions(edgeDefinitions); - } - - public static TransactionOptions build(final TransactionOptions options, final String action) { - return options.action(action); - } - - public static CollectionRenameOptions build(final CollectionRenameOptions options, final String name) { - return options.name(name); - } - - public static UserAccessOptions build(final UserAccessOptions options, final Permissions grant) { - return options.grant(grant); - } - - public static AqlFunctionCreateOptions build( - final AqlFunctionCreateOptions options, - final String name, - final String code) { - return options.name(name).code(code); - } - - public static VertexCollectionCreateOptions build( - final VertexCollectionCreateOptions options, - final String collection) { - return options.collection(collection); - } - - public static ViewCreateOptions build(final ViewCreateOptions options, final String name, final ViewType type) { - return options.name(name).type(type); - } - - public static ViewRenameOptions build(final ViewRenameOptions options, final String name) { - return options.name(name); - } + private OptionsBuilder() { + super(); + } + + public static UserCreateOptions build(final UserCreateOptions options, final String user, final String passwd) { + return options.user(user).passwd(passwd); + } + + public static HashIndexOptions build(final HashIndexOptions options, final Iterable fields) { + return options.fields(fields); + } + + public static SkiplistIndexOptions build(final SkiplistIndexOptions options, final Iterable fields) { + return options.fields(fields); + } + + public static PersistentIndexOptions build(final PersistentIndexOptions options, final Iterable fields) { + return options.fields(fields); + } + + public static GeoIndexOptions build(final GeoIndexOptions options, final Iterable fields) { + return options.fields(fields); + } + + public static FulltextIndexOptions build(final FulltextIndexOptions options, final Iterable fields) { + return options.fields(fields); + } + + public static TtlIndexOptions build(final TtlIndexOptions options, final Iterable fields) { + return options.fields(fields); + } + + public static CollectionCreateOptions build(final CollectionCreateOptions options, final String name) { + return options.name(name); + } + + public static AqlQueryOptions build(final AqlQueryOptions options, final String query, final VPackSlice bindVars) { + return options.query(query).bindVars(bindVars); + } + + public static AqlQueryExplainOptions build( + final AqlQueryExplainOptions options, + final String query, + final VPackSlice bindVars) { + return options.query(query).bindVars(bindVars); + } + + public static AqlQueryParseOptions build(final AqlQueryParseOptions options, final String query) { + return options.query(query); + } + + public static GraphCreateOptions build( + final GraphCreateOptions options, + final String name, + final Collection edgeDefinitions) { + return options.name(name).edgeDefinitions(edgeDefinitions); + } + + public static TransactionOptions build(final TransactionOptions options, final String action) { + return options.action(action); + } + + public static CollectionRenameOptions build(final CollectionRenameOptions options, final String name) { + return options.name(name); + } + + public static UserAccessOptions build(final UserAccessOptions options, final Permissions grant) { + return options.grant(grant); + } + + public static AqlFunctionCreateOptions build( + final AqlFunctionCreateOptions options, + final String name, + final String code) { + return options.name(name).code(code); + } + + public static VertexCollectionCreateOptions build( + final VertexCollectionCreateOptions options, + final String collection) { + return options.collection(collection); + } + + public static ViewCreateOptions build(final ViewCreateOptions options, final String name, final ViewType type) { + return options.name(name).type(type); + } + + public static ViewRenameOptions build(final ViewRenameOptions options, final String name) { + return options.name(name); + } } diff --git a/src/main/java/com/arangodb/model/PersistentIndexOptions.java b/src/main/java/com/arangodb/model/PersistentIndexOptions.java index e72c47294..75ab9fa9c 100644 --- a/src/main/java/com/arangodb/model/PersistentIndexOptions.java +++ b/src/main/java/com/arangodb/model/PersistentIndexOptions.java @@ -24,70 +24,66 @@ /** * @author Mark Vollmary - * * @see API - * Documentation + * Documentation */ public class PersistentIndexOptions extends IndexOptions { - private Iterable fields; - protected final IndexType type = IndexType.persistent; - private Boolean unique; - private Boolean sparse; + private Iterable fields; + protected final IndexType type = IndexType.persistent; + private Boolean unique; + private Boolean sparse; - public PersistentIndexOptions() { - super(); - } + public PersistentIndexOptions() { + super(); + } @Override protected PersistentIndexOptions getThis() { return this; } - protected Iterable getFields() { - return fields; - } + protected Iterable getFields() { + return fields; + } - /** - * @param fields - * A list of attribute paths - * @return options - */ - protected PersistentIndexOptions fields(final Iterable fields) { - this.fields = fields; - return this; - } + /** + * @param fields A list of attribute paths + * @return options + */ + protected PersistentIndexOptions fields(final Iterable fields) { + this.fields = fields; + return this; + } - protected IndexType getType() { - return type; - } + protected IndexType getType() { + return type; + } - public Boolean getUnique() { - return unique; - } + public Boolean getUnique() { + return unique; + } - /** - * @param unique - * if true, then create a unique index - * @return options - */ - public PersistentIndexOptions unique(final Boolean unique) { - this.unique = unique; - return this; - } + /** + * @param unique if true, then create a unique index + * @return options + */ + public PersistentIndexOptions unique(final Boolean unique) { + this.unique = unique; + return this; + } - public Boolean getSparse() { - return sparse; - } + public Boolean getSparse() { + return sparse; + } - /** - * @param sparse - * if true, then create a sparse index - * @return options - */ - public PersistentIndexOptions sparse(final Boolean sparse) { - this.sparse = sparse; - return this; - } + /** + * @param sparse if true, then create a sparse index + * @return options + */ + public PersistentIndexOptions sparse(final Boolean sparse) { + this.sparse = sparse; + return this; + } } diff --git a/src/main/java/com/arangodb/model/SkiplistIndexOptions.java b/src/main/java/com/arangodb/model/SkiplistIndexOptions.java index 7e5a9e92f..f99676d2f 100644 --- a/src/main/java/com/arangodb/model/SkiplistIndexOptions.java +++ b/src/main/java/com/arangodb/model/SkiplistIndexOptions.java @@ -24,83 +24,78 @@ /** * @author Mark Vollmary - * * @see API Documentation */ public class SkiplistIndexOptions extends IndexOptions { - private Iterable fields; - private final IndexType type = IndexType.skiplist; - private Boolean unique; - private Boolean sparse; - private Boolean deduplicate; + private Iterable fields; + private final IndexType type = IndexType.skiplist; + private Boolean unique; + private Boolean sparse; + private Boolean deduplicate; - public SkiplistIndexOptions() { - super(); - } + public SkiplistIndexOptions() { + super(); + } - @Override - protected SkiplistIndexOptions getThis() { - return this; - } + @Override + protected SkiplistIndexOptions getThis() { + return this; + } - protected Iterable getFields() { - return fields; - } + protected Iterable getFields() { + return fields; + } - /** - * @param fields - * A list of attribute paths - * @return options - */ - protected SkiplistIndexOptions fields(final Iterable fields) { - this.fields = fields; - return this; - } + /** + * @param fields A list of attribute paths + * @return options + */ + protected SkiplistIndexOptions fields(final Iterable fields) { + this.fields = fields; + return this; + } - protected IndexType getType() { - return type; - } + protected IndexType getType() { + return type; + } - public Boolean getUnique() { - return unique; - } + public Boolean getUnique() { + return unique; + } - /** - * @param unique - * if true, then create a unique index - * @return options - */ - public SkiplistIndexOptions unique(final Boolean unique) { - this.unique = unique; - return this; - } + /** + * @param unique if true, then create a unique index + * @return options + */ + public SkiplistIndexOptions unique(final Boolean unique) { + this.unique = unique; + return this; + } - public Boolean getSparse() { - return sparse; - } + public Boolean getSparse() { + return sparse; + } - /** - * @param sparse - * if true, then create a sparse index - * @return options - */ - public SkiplistIndexOptions sparse(final Boolean sparse) { - this.sparse = sparse; - return this; - } + /** + * @param sparse if true, then create a sparse index + * @return options + */ + public SkiplistIndexOptions sparse(final Boolean sparse) { + this.sparse = sparse; + return this; + } - public Boolean getDeduplicate() { - return deduplicate; - } + public Boolean getDeduplicate() { + return deduplicate; + } - /** - * @param deduplicate - * if false, the deduplication of array values is turned off. - * @return options - */ - public SkiplistIndexOptions deduplicate(final Boolean deduplicate) { - this.deduplicate = deduplicate; - return this; - } + /** + * @param deduplicate if false, the deduplication of array values is turned off. + * @return options + */ + public SkiplistIndexOptions deduplicate(final Boolean deduplicate) { + this.deduplicate = deduplicate; + return this; + } } diff --git a/src/main/java/com/arangodb/model/StreamTransactionOptions.java b/src/main/java/com/arangodb/model/StreamTransactionOptions.java index fc80951c9..ec4f782f8 100644 --- a/src/main/java/com/arangodb/model/StreamTransactionOptions.java +++ b/src/main/java/com/arangodb/model/StreamTransactionOptions.java @@ -28,96 +28,96 @@ */ public class StreamTransactionOptions { - private final TransactionCollectionOptions collections; - private Integer lockTimeout; - private Boolean waitForSync; - private Long maxTransactionSize; + private final TransactionCollectionOptions collections; + private Integer lockTimeout; + private Boolean waitForSync; + private Long maxTransactionSize; - public StreamTransactionOptions() { - super(); - collections = new TransactionCollectionOptions(); - } + public StreamTransactionOptions() { + super(); + collections = new TransactionCollectionOptions(); + } - public Integer getLockTimeout() { - return lockTimeout; - } + public Integer getLockTimeout() { + return lockTimeout; + } - /** - * @param lockTimeout an optional numeric value that can be used to set a timeout for waiting on collection locks. If not - * specified, a default value will be used. Setting lockTimeout to 0 will make ArangoDB not time out - * waiting for a lock. - * @return options - */ - public StreamTransactionOptions lockTimeout(final Integer lockTimeout) { - this.lockTimeout = lockTimeout; - return this; - } + /** + * @param lockTimeout an optional numeric value that can be used to set a timeout for waiting on collection locks. If not + * specified, a default value will be used. Setting lockTimeout to 0 will make ArangoDB not time out + * waiting for a lock. + * @return options + */ + public StreamTransactionOptions lockTimeout(final Integer lockTimeout) { + this.lockTimeout = lockTimeout; + return this; + } - public Boolean getWaitForSync() { - return waitForSync; - } + public Boolean getWaitForSync() { + return waitForSync; + } - /** - * @param waitForSync an optional boolean flag that, if set, will force the transaction to write all data to disk before - * returning - * @return options - */ - public StreamTransactionOptions waitForSync(final Boolean waitForSync) { - this.waitForSync = waitForSync; - return this; - } + /** + * @param waitForSync an optional boolean flag that, if set, will force the transaction to write all data to disk before + * returning + * @return options + */ + public StreamTransactionOptions waitForSync(final Boolean waitForSync) { + this.waitForSync = waitForSync; + return this; + } - /** - * @param read contains the array of collection-names to be used in the transaction (mandatory) for read - * @return options - */ - public StreamTransactionOptions readCollections(final String... read) { - collections.read(read); - return this; - } + /** + * @param read contains the array of collection-names to be used in the transaction (mandatory) for read + * @return options + */ + public StreamTransactionOptions readCollections(final String... read) { + collections.read(read); + return this; + } - /** - * @param write contains the array of collection-names to be used in the transaction (mandatory) for write - * @return options - */ - public StreamTransactionOptions writeCollections(final String... write) { - collections.write(write); - return this; - } + /** + * @param write contains the array of collection-names to be used in the transaction (mandatory) for write + * @return options + */ + public StreamTransactionOptions writeCollections(final String... write) { + collections.write(write); + return this; + } - /** - * @param exclusive contains the array of collection-names to be used in the transaction (mandatory) for exclusive write - * @return options - */ - public StreamTransactionOptions exclusiveCollections(final String... exclusive) { - collections.exclusive(exclusive); - return this; - } + /** + * @param exclusive contains the array of collection-names to be used in the transaction (mandatory) for exclusive write + * @return options + */ + public StreamTransactionOptions exclusiveCollections(final String... exclusive) { + collections.exclusive(exclusive); + return this; + } - /** - * @param allowImplicit Collections that will be written to in the transaction must be declared with the write attribute or it - * will fail, whereas non-declared collections from which is solely read will be added lazily. The - * optional attribute allowImplicit can be set to false to let transactions fail in case of undeclared - * collections for reading. Collections for reading should be fully declared if possible, to avoid - * deadlocks. - * @return options - */ - public StreamTransactionOptions allowImplicit(final Boolean allowImplicit) { - collections.allowImplicit(allowImplicit); - return this; - } + /** + * @param allowImplicit Collections that will be written to in the transaction must be declared with the write attribute or it + * will fail, whereas non-declared collections from which is solely read will be added lazily. The + * optional attribute allowImplicit can be set to false to let transactions fail in case of undeclared + * collections for reading. Collections for reading should be fully declared if possible, to avoid + * deadlocks. + * @return options + */ + public StreamTransactionOptions allowImplicit(final Boolean allowImplicit) { + collections.allowImplicit(allowImplicit); + return this; + } - public Long getMaxTransactionSize() { - return maxTransactionSize; - } + public Long getMaxTransactionSize() { + return maxTransactionSize; + } - /** - * @param maxTransactionSize Transaction size limit in bytes. Honored by the RocksDB storage engine only. - * @return options - */ - public StreamTransactionOptions maxTransactionSize(final Long maxTransactionSize) { - this.maxTransactionSize = maxTransactionSize; - return this; - } + /** + * @param maxTransactionSize Transaction size limit in bytes. Honored by the RocksDB storage engine only. + * @return options + */ + public StreamTransactionOptions maxTransactionSize(final Long maxTransactionSize) { + this.maxTransactionSize = maxTransactionSize; + return this; + } } diff --git a/src/main/java/com/arangodb/model/TransactionCollectionOptions.java b/src/main/java/com/arangodb/model/TransactionCollectionOptions.java index 551b87698..d11d14220 100644 --- a/src/main/java/com/arangodb/model/TransactionCollectionOptions.java +++ b/src/main/java/com/arangodb/model/TransactionCollectionOptions.java @@ -29,45 +29,45 @@ */ public class TransactionCollectionOptions { - private Collection read; - private Collection write; - private Collection exclusive; - private Boolean allowImplicit; + private Collection read; + private Collection write; + private Collection exclusive; + private Boolean allowImplicit; - public Collection getRead() { - return read; - } + public Collection getRead() { + return read; + } - public TransactionCollectionOptions read(final String... read) { - this.read = Arrays.asList(read); - return this; - } + public TransactionCollectionOptions read(final String... read) { + this.read = Arrays.asList(read); + return this; + } - public Collection getWrite() { - return write; - } + public Collection getWrite() { + return write; + } - public TransactionCollectionOptions write(final String... write) { - this.write = Arrays.asList(write); - return this; - } + public TransactionCollectionOptions write(final String... write) { + this.write = Arrays.asList(write); + return this; + } - public Collection getExclusive() { - return exclusive; - } + public Collection getExclusive() { + return exclusive; + } - public TransactionCollectionOptions exclusive(final String... exclusive) { - this.exclusive = Arrays.asList(exclusive); - return this; - } + public TransactionCollectionOptions exclusive(final String... exclusive) { + this.exclusive = Arrays.asList(exclusive); + return this; + } - public Boolean getAllowImplicit() { - return allowImplicit; - } + public Boolean getAllowImplicit() { + return allowImplicit; + } - public TransactionCollectionOptions allowImplicit(final Boolean allowImplicit) { - this.allowImplicit = allowImplicit; - return this; - } + public TransactionCollectionOptions allowImplicit(final Boolean allowImplicit) { + this.allowImplicit = allowImplicit; + return this; + } } diff --git a/src/main/java/com/arangodb/model/TransactionOptions.java b/src/main/java/com/arangodb/model/TransactionOptions.java index c17cecb77..bbe481b1b 100644 --- a/src/main/java/com/arangodb/model/TransactionOptions.java +++ b/src/main/java/com/arangodb/model/TransactionOptions.java @@ -28,126 +28,126 @@ */ public class TransactionOptions { - private String action; - private Object params; - private final TransactionCollectionOptions collections; - private Integer lockTimeout; - private Boolean waitForSync; - private Long maxTransactionSize; - - public TransactionOptions() { - super(); - collections = new TransactionCollectionOptions(); - } - - protected String getAction() { - return action; - } - - /** - * @param action the actual transaction operations to be executed, in the form of stringified JavaScript code - * @return options - */ - protected TransactionOptions action(final String action) { - this.action = action; - return this; - } - - public Object getParams() { - return params; - } - - /** - * @param params optional arguments passed to action - * @return options - */ - public TransactionOptions params(final Object params) { - this.params = params; - return this; - } - - public Integer getLockTimeout() { - return lockTimeout; - } - - /** - * @param lockTimeout an optional numeric value that can be used to set a timeout for waiting on collection locks. If not - * specified, a default value will be used. Setting lockTimeout to 0 will make ArangoDB not time out - * waiting for a lock. - * @return options - */ - public TransactionOptions lockTimeout(final Integer lockTimeout) { - this.lockTimeout = lockTimeout; - return this; - } - - public Boolean getWaitForSync() { - return waitForSync; - } - - /** - * @param waitForSync an optional boolean flag that, if set, will force the transaction to write all data to disk before - * returning - * @return options - */ - public TransactionOptions waitForSync(final Boolean waitForSync) { - this.waitForSync = waitForSync; - return this; - } - - /** - * @param read contains the array of collection-names to be used in the transaction (mandatory) for read - * @return options - */ - public TransactionOptions readCollections(final String... read) { - collections.read(read); - return this; - } - - /** - * @param write contains the array of collection-names to be used in the transaction (mandatory) for write - * @return options - */ - public TransactionOptions writeCollections(final String... write) { - collections.write(write); - return this; - } - - /** - * @param exclusive contains the array of collection-names to be used in the transaction (mandatory) for exclusive write - * @return options - * @since ArangoDB 3.4.0 - */ - public TransactionOptions exclusiveCollections(final String... exclusive) { - collections.exclusive(exclusive); - return this; - } - - /** - * @param allowImplicit Collections that will be written to in the transaction must be declared with the write attribute or it - * will fail, whereas non-declared collections from which is solely read will be added lazily. The - * optional attribute allowImplicit can be set to false to let transactions fail in case of undeclared - * collections for reading. Collections for reading should be fully declared if possible, to avoid - * deadlocks. - * @return options - */ - public TransactionOptions allowImplicit(final Boolean allowImplicit) { - collections.allowImplicit(allowImplicit); - return this; - } - - public Long getMaxTransactionSize() { - return maxTransactionSize; - } - - /** - * @param maxTransactionSize Transaction size limit in bytes. Honored by the RocksDB storage engine only. - * @return options - * @since ArangoDB 3.2.0 - */ - public TransactionOptions maxTransactionSize(final Long maxTransactionSize) { - this.maxTransactionSize = maxTransactionSize; - return this; - } + private String action; + private Object params; + private final TransactionCollectionOptions collections; + private Integer lockTimeout; + private Boolean waitForSync; + private Long maxTransactionSize; + + public TransactionOptions() { + super(); + collections = new TransactionCollectionOptions(); + } + + protected String getAction() { + return action; + } + + /** + * @param action the actual transaction operations to be executed, in the form of stringified JavaScript code + * @return options + */ + protected TransactionOptions action(final String action) { + this.action = action; + return this; + } + + public Object getParams() { + return params; + } + + /** + * @param params optional arguments passed to action + * @return options + */ + public TransactionOptions params(final Object params) { + this.params = params; + return this; + } + + public Integer getLockTimeout() { + return lockTimeout; + } + + /** + * @param lockTimeout an optional numeric value that can be used to set a timeout for waiting on collection locks. If not + * specified, a default value will be used. Setting lockTimeout to 0 will make ArangoDB not time out + * waiting for a lock. + * @return options + */ + public TransactionOptions lockTimeout(final Integer lockTimeout) { + this.lockTimeout = lockTimeout; + return this; + } + + public Boolean getWaitForSync() { + return waitForSync; + } + + /** + * @param waitForSync an optional boolean flag that, if set, will force the transaction to write all data to disk before + * returning + * @return options + */ + public TransactionOptions waitForSync(final Boolean waitForSync) { + this.waitForSync = waitForSync; + return this; + } + + /** + * @param read contains the array of collection-names to be used in the transaction (mandatory) for read + * @return options + */ + public TransactionOptions readCollections(final String... read) { + collections.read(read); + return this; + } + + /** + * @param write contains the array of collection-names to be used in the transaction (mandatory) for write + * @return options + */ + public TransactionOptions writeCollections(final String... write) { + collections.write(write); + return this; + } + + /** + * @param exclusive contains the array of collection-names to be used in the transaction (mandatory) for exclusive write + * @return options + * @since ArangoDB 3.4.0 + */ + public TransactionOptions exclusiveCollections(final String... exclusive) { + collections.exclusive(exclusive); + return this; + } + + /** + * @param allowImplicit Collections that will be written to in the transaction must be declared with the write attribute or it + * will fail, whereas non-declared collections from which is solely read will be added lazily. The + * optional attribute allowImplicit can be set to false to let transactions fail in case of undeclared + * collections for reading. Collections for reading should be fully declared if possible, to avoid + * deadlocks. + * @return options + */ + public TransactionOptions allowImplicit(final Boolean allowImplicit) { + collections.allowImplicit(allowImplicit); + return this; + } + + public Long getMaxTransactionSize() { + return maxTransactionSize; + } + + /** + * @param maxTransactionSize Transaction size limit in bytes. Honored by the RocksDB storage engine only. + * @return options + * @since ArangoDB 3.2.0 + */ + public TransactionOptions maxTransactionSize(final Long maxTransactionSize) { + this.maxTransactionSize = maxTransactionSize; + return this; + } } diff --git a/src/main/java/com/arangodb/model/TraversalOptions.java b/src/main/java/com/arangodb/model/TraversalOptions.java index 5d53bd994..d54a2aa53 100644 --- a/src/main/java/com/arangodb/model/TraversalOptions.java +++ b/src/main/java/com/arangodb/model/TraversalOptions.java @@ -22,366 +22,331 @@ /** * @author Mark Vollmary - * * @see API Documentation */ public class TraversalOptions { - public enum Direction { - outbound, inbound, any - } - - public enum ItemOrder { - forward, backward - } - - public enum Strategy { - depthfirst, breadthfirst - } - - public enum UniquenessType { - none, global, path - } - - public enum Order { - preorder, postorder, preorder_expander - } - - private String sort; - private Direction direction; - private Integer minDepth; - private String startVertex; - private String visitor; - private ItemOrder itemOrder; - private Strategy strategy; - private String filter; - private String init; - private Integer maxIterations; - private Integer maxDepth; - private Uniqueness uniqueness; - private Order order; - private String graphName; - private String expander; - private String edgeCollection; - - public String getSort() { - return sort; - } - - /** - * - * @param sort - * JavaScript code of a custom comparison function for the edges. The signature of this function is (l, - * r) -> integer (where l and r are edges) and must return -1 if l is smaller than, +1 if l is greater - * than, and 0 if l and r are equal. The reason for this is the following: The order of edges returned - * for a certain vertex is undefined. This is because there is no natural order of edges for a vertex - * with multiple connected edges. To explicitly define the order in which edges on the vertex are - * followed, you can specify an edge comparator function with this attribute. Note that the value here - * has to be a string to conform to the JSON standard, which in turn is parsed as function body on the - * server side. Furthermore note that this attribute is only used for the standard expanders. If you use - * your custom expander you have to do the sorting yourself within the expander code. - * @return options - */ - public TraversalOptions sort(final String sort) { - this.sort = sort; - return this; - } - - public Direction getDirection() { - return direction; - } - - /** - * - * @param direction - * direction for traversal - * - * if set, must be either "outbound", "inbound", or "any" - * - * if not set, the expander attribute must be specified - * @return options - */ - public TraversalOptions direction(final Direction direction) { - this.direction = direction; - return this; - } - - public Integer getMinDepth() { - return minDepth; - } - - /** - * - * @param minDepth - * ANDed with any existing filters): visits only nodes in at least the given depth - * @return options - */ - public TraversalOptions minDepth(final Integer minDepth) { - this.minDepth = minDepth; - return this; - } - - public String getStartVertex() { - return startVertex; - } - - /** - * - * @param startVertex - * The id of the startVertex, e.g. "users/foo". - * @return options - */ - public TraversalOptions startVertex(final String startVertex) { - this.startVertex = startVertex; - return this; - } - - public String getVisitor() { - return visitor; - } - - /** - * - * @param visitor - * JavaScript code of custom visitor function function signature: (config, result, vertex, path, - * connected) -> void The visitor function can do anything, but its return value is ignored. To populate - * a result, use the result variable by reference. Note that the connected argument is only populated - * when the order attribute is set to "preorder-expander". - * @return options - */ - public TraversalOptions visitor(final String visitor) { - this.visitor = visitor; - return this; - } - - public ItemOrder getItemOrder() { - return itemOrder; - } - - /** - * - * @param itemOrder - * The item iteration order can be "forward" or "backward" - * @return options - */ - public TraversalOptions itemOrder(final ItemOrder itemOrder) { - this.itemOrder = itemOrder; - return this; - } - - public Strategy getStrategy() { - return strategy; - } - - /** - * - * @param strategy - * The traversal strategy can be "depthfirst" or "breadthfirst" - * @return options - */ - public TraversalOptions strategy(final Strategy strategy) { - this.strategy = strategy; - return this; - } - - public String getFilter() { - return filter; - } - - /** - * - * @param filter - * default is to include all nodes: body (JavaScript code) of custom filter function function signature: - * (config, vertex, path) -> mixed can return four different string values: - * - * "exclude" -> this vertex will not be visited. - * - * "prune" -> the edges of this vertex will not be followed. - * - * "" or undefined -> visit the vertex and follow it's edges. - * - * Array -> containing any combination of the above. - * - * If there is at least one "exclude" or "prune" respectivly is contained, it's effect will occur. - * @return options - */ - public TraversalOptions filter(final String filter) { - this.filter = filter; - return this; - } - - public String getInit() { - return init; - } - - /** - * - * @param init - * JavaScript code of custom result initialization function function signature: (config, result) -> void - * initialize any values in result with what is required - * @return options - */ - public TraversalOptions init(final String init) { - this.init = init; - return this; - } - - public Integer getMaxIterations() { - return maxIterations; - } - - /** - * - * @param maxIterations - * Maximum number of iterations in each traversal. This number can be set to prevent endless loops in - * traversal of cyclic graphs. When a traversal performs as many iterations as the maxIterations value, - * the traversal will abort with an error. If maxIterations is not set, a server-defined value may be - * used. - * @return options - */ - public TraversalOptions maxIterations(final Integer maxIterations) { - this.maxIterations = maxIterations; - return this; - } - - public Integer getMaxDepth() { - return maxDepth; - } - - /** - * - * @param maxDepth - * ANDed with any existing filters visits only nodes in at most the given depth. - * @return options - */ - public TraversalOptions maxDepth(final Integer maxDepth) { - this.maxDepth = maxDepth; - return this; - } - - public UniquenessType getVerticesUniqueness() { - return uniqueness != null ? uniqueness.vertices : null; - } - - /** - * - * @param vertices - * Specifies uniqueness for vertices can be "none", "global" or "path" - * @return options - */ - public TraversalOptions verticesUniqueness(final UniquenessType vertices) { - getUniqueness().setVertices(vertices); - return this; - } - - public UniquenessType getEdgesUniqueness() { - return uniqueness != null ? uniqueness.edges : null; - } - - /** - * - * @param edges - * Specifies uniqueness for edges can be "none", "global" or "path" - * @return options - */ - public TraversalOptions edgesUniqueness(final UniquenessType edges) { - getUniqueness().setEdges(edges); - return this; - } - - public Order getOrder() { - return order; - } - - /** - * - * @param order - * The traversal order can be "preorder", "postorder" or "preorder-expander" - * @return options - */ - public TraversalOptions order(final Order order) { - this.order = order; - return this; - } - - public String getGraphName() { - return graphName; - } - - /** - * - * @param graphName - * The name of the graph that contains the edges. Either edgeCollection or graphName has to be given. In - * case both values are set the graphName is prefered. - * @return options - */ - public TraversalOptions graphName(final String graphName) { - this.graphName = graphName; - return this; - } - - public String getExpander() { - return expander; - } - - /** - * - * @param expander - * JavaScript code of custom expander function must be set if direction attribute is not set function - * signature: (config, vertex, path) -> array expander must return an array of the connections for vertex - * each connection is an object with the attributes edge and vertex - * @return options - */ - public TraversalOptions expander(final String expander) { - this.expander = expander; - return this; - } - - public String getEdgeCollection() { - return edgeCollection; - } - - /** - * - * @param edgeCollection - * The name of the collection that contains the edges. - * @return options - */ - public TraversalOptions edgeCollection(final String edgeCollection) { - this.edgeCollection = edgeCollection; - return this; - } - - public static class Uniqueness { - - private UniquenessType vertices; - private UniquenessType edges; - - public UniquenessType getVertices() { - return vertices; - } - - public void setVertices(final UniquenessType vertices) { - this.vertices = vertices; - } - - public UniquenessType getEdges() { - return edges; - } - - public void setEdges(final UniquenessType edges) { - this.edges = edges; - } - } - - private Uniqueness getUniqueness() { - if (uniqueness == null) { - uniqueness = new Uniqueness(); - uniqueness.vertices = UniquenessType.none; - uniqueness.edges = UniquenessType.none; - } - - return uniqueness; - } + public enum Direction { + outbound, inbound, any + } + + public enum ItemOrder { + forward, backward + } + + public enum Strategy { + depthfirst, breadthfirst + } + + public enum UniquenessType { + none, global, path + } + + public enum Order { + preorder, postorder, preorder_expander + } + + private String sort; + private Direction direction; + private Integer minDepth; + private String startVertex; + private String visitor; + private ItemOrder itemOrder; + private Strategy strategy; + private String filter; + private String init; + private Integer maxIterations; + private Integer maxDepth; + private Uniqueness uniqueness; + private Order order; + private String graphName; + private String expander; + private String edgeCollection; + + public String getSort() { + return sort; + } + + /** + * @param sort JavaScript code of a custom comparison function for the edges. The signature of this function is (l, + * r) -> integer (where l and r are edges) and must return -1 if l is smaller than, +1 if l is greater + * than, and 0 if l and r are equal. The reason for this is the following: The order of edges returned + * for a certain vertex is undefined. This is because there is no natural order of edges for a vertex + * with multiple connected edges. To explicitly define the order in which edges on the vertex are + * followed, you can specify an edge comparator function with this attribute. Note that the value here + * has to be a string to conform to the JSON standard, which in turn is parsed as function body on the + * server side. Furthermore note that this attribute is only used for the standard expanders. If you use + * your custom expander you have to do the sorting yourself within the expander code. + * @return options + */ + public TraversalOptions sort(final String sort) { + this.sort = sort; + return this; + } + + public Direction getDirection() { + return direction; + } + + /** + * @param direction direction for traversal + *

+ * if set, must be either "outbound", "inbound", or "any" + *

+ * if not set, the expander attribute must be specified + * @return options + */ + public TraversalOptions direction(final Direction direction) { + this.direction = direction; + return this; + } + + public Integer getMinDepth() { + return minDepth; + } + + /** + * @param minDepth ANDed with any existing filters): visits only nodes in at least the given depth + * @return options + */ + public TraversalOptions minDepth(final Integer minDepth) { + this.minDepth = minDepth; + return this; + } + + public String getStartVertex() { + return startVertex; + } + + /** + * @param startVertex The id of the startVertex, e.g. "users/foo". + * @return options + */ + public TraversalOptions startVertex(final String startVertex) { + this.startVertex = startVertex; + return this; + } + + public String getVisitor() { + return visitor; + } + + /** + * @param visitor JavaScript code of custom visitor function function signature: (config, result, vertex, path, + * connected) -> void The visitor function can do anything, but its return value is ignored. To populate + * a result, use the result variable by reference. Note that the connected argument is only populated + * when the order attribute is set to "preorder-expander". + * @return options + */ + public TraversalOptions visitor(final String visitor) { + this.visitor = visitor; + return this; + } + + public ItemOrder getItemOrder() { + return itemOrder; + } + + /** + * @param itemOrder The item iteration order can be "forward" or "backward" + * @return options + */ + public TraversalOptions itemOrder(final ItemOrder itemOrder) { + this.itemOrder = itemOrder; + return this; + } + + public Strategy getStrategy() { + return strategy; + } + + /** + * @param strategy The traversal strategy can be "depthfirst" or "breadthfirst" + * @return options + */ + public TraversalOptions strategy(final Strategy strategy) { + this.strategy = strategy; + return this; + } + + public String getFilter() { + return filter; + } + + /** + * @param filter default is to include all nodes: body (JavaScript code) of custom filter function function signature: + * (config, vertex, path) -> mixed can return four different string values: + *

+ * "exclude" -> this vertex will not be visited. + *

+ * "prune" -> the edges of this vertex will not be followed. + *

+ * "" or undefined -> visit the vertex and follow it's edges. + *

+ * Array -> containing any combination of the above. + *

+ * If there is at least one "exclude" or "prune" respectivly is contained, it's effect will occur. + * @return options + */ + public TraversalOptions filter(final String filter) { + this.filter = filter; + return this; + } + + public String getInit() { + return init; + } + + /** + * @param init JavaScript code of custom result initialization function function signature: (config, result) -> void + * initialize any values in result with what is required + * @return options + */ + public TraversalOptions init(final String init) { + this.init = init; + return this; + } + + public Integer getMaxIterations() { + return maxIterations; + } + + /** + * @param maxIterations Maximum number of iterations in each traversal. This number can be set to prevent endless loops in + * traversal of cyclic graphs. When a traversal performs as many iterations as the maxIterations value, + * the traversal will abort with an error. If maxIterations is not set, a server-defined value may be + * used. + * @return options + */ + public TraversalOptions maxIterations(final Integer maxIterations) { + this.maxIterations = maxIterations; + return this; + } + + public Integer getMaxDepth() { + return maxDepth; + } + + /** + * @param maxDepth ANDed with any existing filters visits only nodes in at most the given depth. + * @return options + */ + public TraversalOptions maxDepth(final Integer maxDepth) { + this.maxDepth = maxDepth; + return this; + } + + public UniquenessType getVerticesUniqueness() { + return uniqueness != null ? uniqueness.vertices : null; + } + + /** + * @param vertices Specifies uniqueness for vertices can be "none", "global" or "path" + * @return options + */ + public TraversalOptions verticesUniqueness(final UniquenessType vertices) { + getUniqueness().setVertices(vertices); + return this; + } + + public UniquenessType getEdgesUniqueness() { + return uniqueness != null ? uniqueness.edges : null; + } + + /** + * @param edges Specifies uniqueness for edges can be "none", "global" or "path" + * @return options + */ + public TraversalOptions edgesUniqueness(final UniquenessType edges) { + getUniqueness().setEdges(edges); + return this; + } + + public Order getOrder() { + return order; + } + + /** + * @param order The traversal order can be "preorder", "postorder" or "preorder-expander" + * @return options + */ + public TraversalOptions order(final Order order) { + this.order = order; + return this; + } + + public String getGraphName() { + return graphName; + } + + /** + * @param graphName The name of the graph that contains the edges. Either edgeCollection or graphName has to be given. In + * case both values are set the graphName is prefered. + * @return options + */ + public TraversalOptions graphName(final String graphName) { + this.graphName = graphName; + return this; + } + + public String getExpander() { + return expander; + } + + /** + * @param expander JavaScript code of custom expander function must be set if direction attribute is not set function + * signature: (config, vertex, path) -> array expander must return an array of the connections for vertex + * each connection is an object with the attributes edge and vertex + * @return options + */ + public TraversalOptions expander(final String expander) { + this.expander = expander; + return this; + } + + public String getEdgeCollection() { + return edgeCollection; + } + + /** + * @param edgeCollection The name of the collection that contains the edges. + * @return options + */ + public TraversalOptions edgeCollection(final String edgeCollection) { + this.edgeCollection = edgeCollection; + return this; + } + + public static class Uniqueness { + + private UniquenessType vertices; + private UniquenessType edges; + + public UniquenessType getVertices() { + return vertices; + } + + public void setVertices(final UniquenessType vertices) { + this.vertices = vertices; + } + + public UniquenessType getEdges() { + return edges; + } + + public void setEdges(final UniquenessType edges) { + this.edges = edges; + } + } + + private Uniqueness getUniqueness() { + if (uniqueness == null) { + uniqueness = new Uniqueness(); + uniqueness.vertices = UniquenessType.none; + uniqueness.edges = UniquenessType.none; + } + + return uniqueness; + } } diff --git a/src/main/java/com/arangodb/model/UserAccessOptions.java b/src/main/java/com/arangodb/model/UserAccessOptions.java index 46c45fc16..85f86bc66 100644 --- a/src/main/java/com/arangodb/model/UserAccessOptions.java +++ b/src/main/java/com/arangodb/model/UserAccessOptions.java @@ -24,23 +24,22 @@ /** * @author Mark Vollmary - * */ public class UserAccessOptions { - private Permissions grant; + private Permissions grant; - public UserAccessOptions() { - super(); - } + public UserAccessOptions() { + super(); + } - protected Permissions getGrant() { - return grant; - } + protected Permissions getGrant() { + return grant; + } - protected UserAccessOptions grant(final Permissions grant) { - this.grant = grant; - return this; - } + protected UserAccessOptions grant(final Permissions grant) { + this.grant = grant; + return this; + } } diff --git a/src/main/java/com/arangodb/model/UserCreateOptions.java b/src/main/java/com/arangodb/model/UserCreateOptions.java index 19d99dc26..2ac216259 100644 --- a/src/main/java/com/arangodb/model/UserCreateOptions.java +++ b/src/main/java/com/arangodb/model/UserCreateOptions.java @@ -24,75 +24,70 @@ /** * @author Mark Vollmary - * * @see API Documentation */ public class UserCreateOptions { - private String user; - private String passwd; - private Boolean active; - private Map extra; + private String user; + private String passwd; + private Boolean active; + private Map extra; - public UserCreateOptions() { - super(); - } + public UserCreateOptions() { + super(); + } - protected String getUser() { - return user; - } + protected String getUser() { + return user; + } - /** - * @param user - * The name of the user - * @return options - */ - protected UserCreateOptions user(final String user) { - this.user = user; - return this; - } + /** + * @param user The name of the user + * @return options + */ + protected UserCreateOptions user(final String user) { + this.user = user; + return this; + } - protected String getPasswd() { - return passwd; - } + protected String getPasswd() { + return passwd; + } - /** - * @param passwd - * The user password - * @return options - */ - protected UserCreateOptions passwd(final String passwd) { - this.passwd = passwd; - return this; - } + /** + * @param passwd The user password + * @return options + */ + protected UserCreateOptions passwd(final String passwd) { + this.passwd = passwd; + return this; + } - public Boolean getActive() { - return active; - } + public Boolean getActive() { + return active; + } - /** - * @param active - * An optional flag that specifies whether the user is active. If not specified, this will default to - * true - * @return options - */ - public UserCreateOptions active(final Boolean active) { - this.active = active; - return this; - } + /** + * @param active An optional flag that specifies whether the user is active. If not specified, this will default to + * true + * @return options + */ + public UserCreateOptions active(final Boolean active) { + this.active = active; + return this; + } - public Map getExtra() { - return extra; - } + public Map getExtra() { + return extra; + } - /** - * @param extra - * Optional data about the user - * @return options - */ - public UserCreateOptions extra(final Map extra) { - this.extra = extra; - return this; - } + /** + * @param extra Optional data about the user + * @return options + */ + public UserCreateOptions extra(final Map extra) { + this.extra = extra; + return this; + } } diff --git a/src/main/java/com/arangodb/model/UserUpdateOptions.java b/src/main/java/com/arangodb/model/UserUpdateOptions.java index b83057e80..eec7fa2f4 100644 --- a/src/main/java/com/arangodb/model/UserUpdateOptions.java +++ b/src/main/java/com/arangodb/model/UserUpdateOptions.java @@ -24,60 +24,56 @@ /** * @author Mark Vollmary - * * @see API Documentation */ public class UserUpdateOptions { - private String passwd; - private Boolean active; - private Map extra; + private String passwd; + private Boolean active; + private Map extra; - public UserUpdateOptions() { - super(); - } + public UserUpdateOptions() { + super(); + } - public String getPasswd() { - return passwd; - } + public String getPasswd() { + return passwd; + } - /** - * @param passwd - * The user password - * @return options - */ - public UserUpdateOptions passwd(final String passwd) { - this.passwd = passwd; - return this; - } + /** + * @param passwd The user password + * @return options + */ + public UserUpdateOptions passwd(final String passwd) { + this.passwd = passwd; + return this; + } - public Boolean getActive() { - return active; - } + public Boolean getActive() { + return active; + } - /** - * @param active - * An optional flag that specifies whether the user is active. If not specified, this will default to - * true - * @return options - */ - public UserUpdateOptions active(final Boolean active) { - this.active = active; - return this; - } + /** + * @param active An optional flag that specifies whether the user is active. If not specified, this will default to + * true + * @return options + */ + public UserUpdateOptions active(final Boolean active) { + this.active = active; + return this; + } - public Map getExtra() { - return extra; - } + public Map getExtra() { + return extra; + } - /** - * @param extra - * Optional data about the user - * @return options - */ - public UserUpdateOptions extra(final Map extra) { - this.extra = extra; - return this; - } + /** + * @param extra Optional data about the user + * @return options + */ + public UserUpdateOptions extra(final Map extra) { + this.extra = extra; + return this; + } } diff --git a/src/main/java/com/arangodb/model/VertexCollectionCreateOptions.java b/src/main/java/com/arangodb/model/VertexCollectionCreateOptions.java index 819c71aa5..213f6ac2f 100644 --- a/src/main/java/com/arangodb/model/VertexCollectionCreateOptions.java +++ b/src/main/java/com/arangodb/model/VertexCollectionCreateOptions.java @@ -22,28 +22,26 @@ /** * @author Mark Vollmary - * */ public class VertexCollectionCreateOptions { - private String collection; + private String collection; - public VertexCollectionCreateOptions() { - super(); - } + public VertexCollectionCreateOptions() { + super(); + } - protected String getCollection() { - return collection; - } + protected String getCollection() { + return collection; + } - /** - * @param collection - * The name of the collection - * @return options - */ - protected VertexCollectionCreateOptions collection(final String collection) { - this.collection = collection; - return this; - } + /** + * @param collection The name of the collection + * @return options + */ + protected VertexCollectionCreateOptions collection(final String collection) { + this.collection = collection; + return this; + } } diff --git a/src/main/java/com/arangodb/model/VertexCreateOptions.java b/src/main/java/com/arangodb/model/VertexCreateOptions.java index e26140455..d998aa590 100644 --- a/src/main/java/com/arangodb/model/VertexCreateOptions.java +++ b/src/main/java/com/arangodb/model/VertexCreateOptions.java @@ -22,31 +22,29 @@ /** * @author Mark Vollmary - * * @see API Documentation */ public class VertexCreateOptions { - private Boolean waitForSync; + private Boolean waitForSync; private String streamTransactionId; - public VertexCreateOptions() { - super(); - } + public VertexCreateOptions() { + super(); + } - public Boolean getWaitForSync() { - return waitForSync; - } + public Boolean getWaitForSync() { + return waitForSync; + } - /** - * @param waitForSync - * Wait until document has been synced to disk. - * @return options - */ - public VertexCreateOptions waitForSync(final Boolean waitForSync) { - this.waitForSync = waitForSync; - return this; - } + /** + * @param waitForSync Wait until document has been synced to disk. + * @return options + */ + public VertexCreateOptions waitForSync(final Boolean waitForSync) { + this.waitForSync = waitForSync; + return this; + } public String getStreamTransactionId() { return streamTransactionId; diff --git a/src/main/java/com/arangodb/model/VertexDeleteOptions.java b/src/main/java/com/arangodb/model/VertexDeleteOptions.java index 1c301bea1..d52f58347 100644 --- a/src/main/java/com/arangodb/model/VertexDeleteOptions.java +++ b/src/main/java/com/arangodb/model/VertexDeleteOptions.java @@ -22,46 +22,43 @@ /** * @author Mark Vollmary - * * @see API Documentation */ public class VertexDeleteOptions { - private Boolean waitForSync; - private String ifMatch; + private Boolean waitForSync; + private String ifMatch; private String streamTransactionId; - public VertexDeleteOptions() { - super(); - } + public VertexDeleteOptions() { + super(); + } - public Boolean getWaitForSync() { - return waitForSync; - } + public Boolean getWaitForSync() { + return waitForSync; + } - /** - * @param waitForSync - * Wait until deletion operation has been synced to disk. - * @return options - */ - public VertexDeleteOptions waitForSync(final Boolean waitForSync) { - this.waitForSync = waitForSync; - return this; - } + /** + * @param waitForSync Wait until deletion operation has been synced to disk. + * @return options + */ + public VertexDeleteOptions waitForSync(final Boolean waitForSync) { + this.waitForSync = waitForSync; + return this; + } - public String getIfMatch() { - return ifMatch; - } + public String getIfMatch() { + return ifMatch; + } - /** - * @param ifMatch - * remove a document based on a target revision - * @return options - */ - public VertexDeleteOptions ifMatch(final String ifMatch) { - this.ifMatch = ifMatch; - return this; - } + /** + * @param ifMatch remove a document based on a target revision + * @return options + */ + public VertexDeleteOptions ifMatch(final String ifMatch) { + this.ifMatch = ifMatch; + return this; + } public String getStreamTransactionId() { return streamTransactionId; diff --git a/src/main/java/com/arangodb/model/VertexReplaceOptions.java b/src/main/java/com/arangodb/model/VertexReplaceOptions.java index fe53c07e9..5957b7235 100644 --- a/src/main/java/com/arangodb/model/VertexReplaceOptions.java +++ b/src/main/java/com/arangodb/model/VertexReplaceOptions.java @@ -22,46 +22,43 @@ /** * @author Mark Vollmary - * * @see API Documentation */ public class VertexReplaceOptions { - private Boolean waitForSync; - private String ifMatch; + private Boolean waitForSync; + private String ifMatch; private String streamTransactionId; - public VertexReplaceOptions() { - super(); - } + public VertexReplaceOptions() { + super(); + } - public Boolean getWaitForSync() { - return waitForSync; - } + public Boolean getWaitForSync() { + return waitForSync; + } - /** - * @param waitForSync - * Wait until document has been synced to disk. - * @return options - */ - public VertexReplaceOptions waitForSync(final Boolean waitForSync) { - this.waitForSync = waitForSync; - return this; - } + /** + * @param waitForSync Wait until document has been synced to disk. + * @return options + */ + public VertexReplaceOptions waitForSync(final Boolean waitForSync) { + this.waitForSync = waitForSync; + return this; + } - public String getIfMatch() { - return ifMatch; - } + public String getIfMatch() { + return ifMatch; + } - /** - * @param ifMatch - * replace a document based on target revision - * @return options - */ - public VertexReplaceOptions ifMatch(final String ifMatch) { - this.ifMatch = ifMatch; - return this; - } + /** + * @param ifMatch replace a document based on target revision + * @return options + */ + public VertexReplaceOptions ifMatch(final String ifMatch) { + this.ifMatch = ifMatch; + return this; + } public String getStreamTransactionId() { return streamTransactionId; diff --git a/src/main/java/com/arangodb/model/VertexUpdateOptions.java b/src/main/java/com/arangodb/model/VertexUpdateOptions.java index 9117a038a..1e0478692 100644 --- a/src/main/java/com/arangodb/model/VertexUpdateOptions.java +++ b/src/main/java/com/arangodb/model/VertexUpdateOptions.java @@ -22,64 +22,60 @@ /** * @author Mark Vollmary - * * @see API Documentation */ public class VertexUpdateOptions { - private Boolean keepNull; - private Boolean waitForSync; - private String ifMatch; + private Boolean keepNull; + private Boolean waitForSync; + private String ifMatch; private String streamTransactionId; - public VertexUpdateOptions() { - super(); - } + public VertexUpdateOptions() { + super(); + } - public Boolean getKeepNull() { - return keepNull; - } + public Boolean getKeepNull() { + return keepNull; + } - /** - * @param keepNull - * If the intention is to delete existing attributes with the patch command, the URL query parameter - * keepNull can be used with a value of false. This will modify the behavior of the patch command to - * remove any attributes from the existing document that are contained in the patch document with an - * attribute value of null. - * @return options - */ - public VertexUpdateOptions keepNull(final Boolean keepNull) { - this.keepNull = keepNull; - return this; - } + /** + * @param keepNull If the intention is to delete existing attributes with the patch command, the URL query parameter + * keepNull can be used with a value of false. This will modify the behavior of the patch command to + * remove any attributes from the existing document that are contained in the patch document with an + * attribute value of null. + * @return options + */ + public VertexUpdateOptions keepNull(final Boolean keepNull) { + this.keepNull = keepNull; + return this; + } - public Boolean getWaitForSync() { - return waitForSync; - } + public Boolean getWaitForSync() { + return waitForSync; + } - /** - * @param waitForSync - * Wait until document has been synced to disk. - * @return options - */ - public VertexUpdateOptions waitForSync(final Boolean waitForSync) { - this.waitForSync = waitForSync; - return this; - } + /** + * @param waitForSync Wait until document has been synced to disk. + * @return options + */ + public VertexUpdateOptions waitForSync(final Boolean waitForSync) { + this.waitForSync = waitForSync; + return this; + } - public String getIfMatch() { - return ifMatch; - } + public String getIfMatch() { + return ifMatch; + } - /** - * @param ifMatch - * replace a document based on target revision - * @return options - */ - public VertexUpdateOptions ifMatch(final String ifMatch) { - this.ifMatch = ifMatch; - return this; - } + /** + * @param ifMatch replace a document based on target revision + * @return options + */ + public VertexUpdateOptions ifMatch(final String ifMatch) { + this.ifMatch = ifMatch; + return this; + } public String getStreamTransactionId() { return streamTransactionId; diff --git a/src/main/java/com/arangodb/model/ViewCreateOptions.java b/src/main/java/com/arangodb/model/ViewCreateOptions.java index 84c633870..b2287a6de 100644 --- a/src/main/java/com/arangodb/model/ViewCreateOptions.java +++ b/src/main/java/com/arangodb/model/ViewCreateOptions.java @@ -24,27 +24,26 @@ /** * @author Mark Vollmary - * */ public class ViewCreateOptions { - @SuppressWarnings("unused") - private String name; - @SuppressWarnings("unused") - private ViewType type; + @SuppressWarnings("unused") + private String name; + @SuppressWarnings("unused") + private ViewType type; - public ViewCreateOptions() { - super(); - } + public ViewCreateOptions() { + super(); + } - protected ViewCreateOptions name(final String name) { - this.name = name; - return this; - } + protected ViewCreateOptions name(final String name) { + this.name = name; + return this; + } - protected ViewCreateOptions type(final ViewType type) { - this.type = type; - return this; - } + protected ViewCreateOptions type(final ViewType type) { + this.type = type; + return this; + } } diff --git a/src/main/java/com/arangodb/model/ViewRenameOptions.java b/src/main/java/com/arangodb/model/ViewRenameOptions.java index 6c9c4ff2f..d67c5bf54 100644 --- a/src/main/java/com/arangodb/model/ViewRenameOptions.java +++ b/src/main/java/com/arangodb/model/ViewRenameOptions.java @@ -22,28 +22,26 @@ /** * @author Mark Vollmary - * */ public class ViewRenameOptions { - private String name; + private String name; - public ViewRenameOptions() { - super(); - } + public ViewRenameOptions() { + super(); + } - public String getName() { - return name; - } + public String getName() { + return name; + } - /** - * @param name - * The new name - * @return options - */ - protected ViewRenameOptions name(final String name) { - this.name = name; - return this; - } + /** + * @param name The new name + * @return options + */ + protected ViewRenameOptions name(final String name) { + this.name = name; + return this; + } } diff --git a/src/main/java/com/arangodb/model/arangosearch/AnalyzerDeleteOptions.java b/src/main/java/com/arangodb/model/arangosearch/AnalyzerDeleteOptions.java index 09b62e801..62be6902c 100644 --- a/src/main/java/com/arangodb/model/arangosearch/AnalyzerDeleteOptions.java +++ b/src/main/java/com/arangodb/model/arangosearch/AnalyzerDeleteOptions.java @@ -25,16 +25,16 @@ */ public class AnalyzerDeleteOptions { - private Boolean force; + private Boolean force; - public AnalyzerDeleteOptions() { - } + public AnalyzerDeleteOptions() { + } - public Boolean getForce() { - return force; - } + public Boolean getForce() { + return force; + } - public void setForce(Boolean force) { - this.force = force; - } + public void setForce(Boolean force) { + this.force = force; + } } diff --git a/src/main/java/com/arangodb/model/arangosearch/ArangoSearchCreateOptions.java b/src/main/java/com/arangodb/model/arangosearch/ArangoSearchCreateOptions.java index 627f653a4..f26cbae62 100644 --- a/src/main/java/com/arangodb/model/arangosearch/ArangoSearchCreateOptions.java +++ b/src/main/java/com/arangodb/model/arangosearch/ArangoSearchCreateOptions.java @@ -28,104 +28,95 @@ /** * @author Mark Vollmary - * */ public class ArangoSearchCreateOptions { - @SuppressWarnings("unused") - private String name; - @SuppressWarnings("unused") - private final ViewType type; - private final ArangoSearchProperties properties; + @SuppressWarnings("unused") + private String name; + @SuppressWarnings("unused") + private final ViewType type; + private final ArangoSearchProperties properties; - public ArangoSearchCreateOptions() { - super(); - type = ViewType.ARANGO_SEARCH; - properties = new ArangoSearchProperties(); - } + public ArangoSearchCreateOptions() { + super(); + type = ViewType.ARANGO_SEARCH; + properties = new ArangoSearchProperties(); + } - protected ArangoSearchCreateOptions name(final String name) { - this.name = name; - return this; - } + protected ArangoSearchCreateOptions name(final String name) { + this.name = name; + return this; + } - /** - * @param consolidationIntervalMsec - * Wait at least this many milliseconds between committing index data changes and making them visible to - * queries (default: 60000, to disable use: 0). For the case where there are a lot of inserts/updates, a - * lower value, until commit, will cause the index not to account for them and memory usage would - * continue to grow. For the case where there are a few inserts/updates, a higher value will impact - * performance and waste disk space for each commit call without any added benefits. - * @return options - */ - public ArangoSearchCreateOptions consolidationIntervalMsec(final Long consolidationIntervalMsec) { - properties.setConsolidationIntervalMsec(consolidationIntervalMsec); - return this; - } + /** + * @param consolidationIntervalMsec Wait at least this many milliseconds between committing index data changes and making them visible to + * queries (default: 60000, to disable use: 0). For the case where there are a lot of inserts/updates, a + * lower value, until commit, will cause the index not to account for them and memory usage would + * continue to grow. For the case where there are a few inserts/updates, a higher value will impact + * performance and waste disk space for each commit call without any added benefits. + * @return options + */ + public ArangoSearchCreateOptions consolidationIntervalMsec(final Long consolidationIntervalMsec) { + properties.setConsolidationIntervalMsec(consolidationIntervalMsec); + return this; + } - /** - * @param commitIntervalMsec - * - * Wait at least this many milliseconds between committing view data store changes and making documents visible to - * queries (default: 1000, to disable use: 0). For the case where there are a lot of inserts/updates, a lower value, - * until commit, will cause the index not to account for them and memory usage would continue to grow. For the case - * where there are a few inserts/updates, a higher value will impact performance and waste disk space for each - * commit call without any added benefits. Background: For data retrieval ArangoSearch views follow the concept of - * “eventually-consistent”, i.e. eventually all the data in ArangoDB will be matched by corresponding query - * expressions. The concept of ArangoSearch view “commit” operation is introduced to control the upper-bound on the - * time until document addition/removals are actually reflected by corresponding query expressions. Once a “commit” - * operation is complete all documents added/removed prior to the start of the “commit” operation will be reflected - * by queries invoked in subsequent ArangoDB transactions, in-progress ArangoDB transactions will still continue to - * return a repeatable-read state. - * - * @return options - */ - public ArangoSearchCreateOptions commitIntervalMsec(final Long commitIntervalMsec) { - properties.setCommitIntervalMsec(commitIntervalMsec); - return this; - } + /** + * @param commitIntervalMsec Wait at least this many milliseconds between committing view data store changes and making documents visible to + * queries (default: 1000, to disable use: 0). For the case where there are a lot of inserts/updates, a lower value, + * until commit, will cause the index not to account for them and memory usage would continue to grow. For the case + * where there are a few inserts/updates, a higher value will impact performance and waste disk space for each + * commit call without any added benefits. Background: For data retrieval ArangoSearch views follow the concept of + * “eventually-consistent”, i.e. eventually all the data in ArangoDB will be matched by corresponding query + * expressions. The concept of ArangoSearch view “commit” operation is introduced to control the upper-bound on the + * time until document addition/removals are actually reflected by corresponding query expressions. Once a “commit” + * operation is complete all documents added/removed prior to the start of the “commit” operation will be reflected + * by queries invoked in subsequent ArangoDB transactions, in-progress ArangoDB transactions will still continue to + * return a repeatable-read state. + * @return options + */ + public ArangoSearchCreateOptions commitIntervalMsec(final Long commitIntervalMsec) { + properties.setCommitIntervalMsec(commitIntervalMsec); + return this; + } - /** - * @param cleanupIntervalStep - * Wait at least this many commits between removing unused files in data directory (default: 10, to - * disable use: 0). For the case where the consolidation policies merge segments often (i.e. a lot of - * commit+consolidate), a lower value will cause a lot of disk space to be wasted. For the case where the - * consolidation policies rarely merge segments (i.e. few inserts/deletes), a higher value will impact - * performance without any added benefits. - * @return options - */ - public ArangoSearchCreateOptions cleanupIntervalStep(final Long cleanupIntervalStep) { - properties.setCleanupIntervalStep(cleanupIntervalStep); - return this; - } + /** + * @param cleanupIntervalStep Wait at least this many commits between removing unused files in data directory (default: 10, to + * disable use: 0). For the case where the consolidation policies merge segments often (i.e. a lot of + * commit+consolidate), a lower value will cause a lot of disk space to be wasted. For the case where the + * consolidation policies rarely merge segments (i.e. few inserts/deletes), a higher value will impact + * performance without any added benefits. + * @return options + */ + public ArangoSearchCreateOptions cleanupIntervalStep(final Long cleanupIntervalStep) { + properties.setCleanupIntervalStep(cleanupIntervalStep); + return this; + } - /** - * @param consolidationPolicy - * - * @return options - */ - public ArangoSearchCreateOptions consolidationPolicy(final ConsolidationPolicy consolidationPolicy) { - properties.setConsolidationPolicy(consolidationPolicy); - return this; - } + /** + * @param consolidationPolicy + * @return options + */ + public ArangoSearchCreateOptions consolidationPolicy(final ConsolidationPolicy consolidationPolicy) { + properties.setConsolidationPolicy(consolidationPolicy); + return this; + } - /** - * @param links - * A list of linked collections - * @return options - */ - public ArangoSearchCreateOptions link(final CollectionLink... links) { - properties.addLink(links); - return this; - } + /** + * @param links A list of linked collections + * @return options + */ + public ArangoSearchCreateOptions link(final CollectionLink... links) { + properties.addLink(links); + return this; + } - /** - * @param primarySorts - * A list of linked collections - * @return options - */ - public ArangoSearchCreateOptions primarySort(final PrimarySort... primarySorts) { - properties.addPrimarySort(primarySorts); - return this; - } + /** + * @param primarySorts A list of linked collections + * @return options + */ + public ArangoSearchCreateOptions primarySort(final PrimarySort... primarySorts) { + properties.addPrimarySort(primarySorts); + return this; + } } diff --git a/src/main/java/com/arangodb/model/arangosearch/ArangoSearchOptionsBuilder.java b/src/main/java/com/arangodb/model/arangosearch/ArangoSearchOptionsBuilder.java index 05018fa04..2bdf10827 100644 --- a/src/main/java/com/arangodb/model/arangosearch/ArangoSearchOptionsBuilder.java +++ b/src/main/java/com/arangodb/model/arangosearch/ArangoSearchOptionsBuilder.java @@ -22,15 +22,14 @@ /** * @author Mark Vollmary - * */ public abstract class ArangoSearchOptionsBuilder { - private ArangoSearchOptionsBuilder() { - super(); - } + private ArangoSearchOptionsBuilder() { + super(); + } - public static ArangoSearchCreateOptions build(final ArangoSearchCreateOptions options, final String name) { - return options.name(name); - } + public static ArangoSearchCreateOptions build(final ArangoSearchCreateOptions options, final String name) { + return options.name(name); + } } diff --git a/src/main/java/com/arangodb/model/arangosearch/ArangoSearchPropertiesOptions.java b/src/main/java/com/arangodb/model/arangosearch/ArangoSearchPropertiesOptions.java index eb73b942e..a874e6d30 100644 --- a/src/main/java/com/arangodb/model/arangosearch/ArangoSearchPropertiesOptions.java +++ b/src/main/java/com/arangodb/model/arangosearch/ArangoSearchPropertiesOptions.java @@ -27,77 +27,71 @@ /** * @author Mark Vollmary - * */ public class ArangoSearchPropertiesOptions { - private final ArangoSearchProperties properties; + private final ArangoSearchProperties properties; - public ArangoSearchPropertiesOptions() { - super(); - properties = new ArangoSearchProperties(); - } + public ArangoSearchPropertiesOptions() { + super(); + properties = new ArangoSearchProperties(); + } - public ArangoSearchProperties getProperties() { - return properties; - } + public ArangoSearchProperties getProperties() { + return properties; + } - /** - * @param consolidationIntervalMsec - * Wait at least this many milliseconds between committing index data changes and making them visible to - * queries (default: 60000, to disable use: 0). For the case where there are a lot of inserts/updates, a - * lower value, until commit, will cause the index not to account for them and memory usage would - * continue to grow. For the case where there are a few inserts/updates, a higher value will impact - * performance and waste disk space for each commit call without any added benefits. - * @return options - */ - public ArangoSearchPropertiesOptions consolidationIntervalMsec(final Long consolidationIntervalMsec) { - properties.setConsolidationIntervalMsec(consolidationIntervalMsec); - return this; - } + /** + * @param consolidationIntervalMsec Wait at least this many milliseconds between committing index data changes and making them visible to + * queries (default: 60000, to disable use: 0). For the case where there are a lot of inserts/updates, a + * lower value, until commit, will cause the index not to account for them and memory usage would + * continue to grow. For the case where there are a few inserts/updates, a higher value will impact + * performance and waste disk space for each commit call without any added benefits. + * @return options + */ + public ArangoSearchPropertiesOptions consolidationIntervalMsec(final Long consolidationIntervalMsec) { + properties.setConsolidationIntervalMsec(consolidationIntervalMsec); + return this; + } - /** - * @param cleanupIntervalStep - * Wait at least this many commits between removing unused files in data directory (default: 10, to - * disable use: 0). For the case where the consolidation policies merge segments often (i.e. a lot of - * commit+consolidate), a lower value will cause a lot of disk space to be wasted. For the case where the - * consolidation policies rarely merge segments (i.e. few inserts/deletes), a higher value will impact - * performance without any added benefits. - * @return options - */ - public ArangoSearchPropertiesOptions cleanupIntervalStep(final Long cleanupIntervalStep) { - properties.setCleanupIntervalStep(cleanupIntervalStep); - return this; - } + /** + * @param cleanupIntervalStep Wait at least this many commits between removing unused files in data directory (default: 10, to + * disable use: 0). For the case where the consolidation policies merge segments often (i.e. a lot of + * commit+consolidate), a lower value will cause a lot of disk space to be wasted. For the case where the + * consolidation policies rarely merge segments (i.e. few inserts/deletes), a higher value will impact + * performance without any added benefits. + * @return options + */ + public ArangoSearchPropertiesOptions cleanupIntervalStep(final Long cleanupIntervalStep) { + properties.setCleanupIntervalStep(cleanupIntervalStep); + return this; + } - /** - * @param consolidationPolicy - * - * @return options - */ - public ArangoSearchPropertiesOptions consolidationPolicy(final ConsolidationPolicy consolidationPolicy) { - properties.setConsolidationPolicy(consolidationPolicy); - return this; - } + /** + * @param consolidationPolicy + * @return options + */ + public ArangoSearchPropertiesOptions consolidationPolicy(final ConsolidationPolicy consolidationPolicy) { + properties.setConsolidationPolicy(consolidationPolicy); + return this; + } - /** - * @param links - * A list of linked collections - * @return options - */ - public ArangoSearchPropertiesOptions link(final CollectionLink... links) { - properties.addLink(links); - return this; - } + /** + * @param links A list of linked collections + * @return options + */ + public ArangoSearchPropertiesOptions link(final CollectionLink... links) { + properties.addLink(links); + return this; + } - /** - * @param primarySorts - * A list of primarySort objects - * @return options - */ - public ArangoSearchPropertiesOptions primarySort(final PrimarySort... primarySorts) { - properties.addPrimarySort(primarySorts); - return this; - } + /** + * @param primarySorts A list of primarySort objects + * @return options + */ + public ArangoSearchPropertiesOptions primarySort(final PrimarySort... primarySorts) { + properties.addPrimarySort(primarySorts); + return this; + } } diff --git a/src/main/java/com/arangodb/util/ArangoCursorInitializer.java b/src/main/java/com/arangodb/util/ArangoCursorInitializer.java index 321a75c9d..bc2da8378 100644 --- a/src/main/java/com/arangodb/util/ArangoCursorInitializer.java +++ b/src/main/java/com/arangodb/util/ArangoCursorInitializer.java @@ -27,14 +27,13 @@ /** * @author Mark Vollmary - * */ public interface ArangoCursorInitializer { - ArangoCursor createInstance( - final InternalArangoDatabase db, - final ArangoCursorExecute execute, - final Class type, - final CursorEntity result); + ArangoCursor createInstance( + final InternalArangoDatabase db, + final ArangoCursorExecute execute, + final Class type, + final CursorEntity result); } diff --git a/src/main/java/com/arangodb/util/ArangoDeserializer.java b/src/main/java/com/arangodb/util/ArangoDeserializer.java index 437928315..55601faff 100644 --- a/src/main/java/com/arangodb/util/ArangoDeserializer.java +++ b/src/main/java/com/arangodb/util/ArangoDeserializer.java @@ -20,27 +20,24 @@ package com.arangodb.util; -import java.lang.reflect.Type; - import com.arangodb.ArangoDBException; import com.arangodb.velocypack.VPackSlice; +import java.lang.reflect.Type; + /** * @author Mark Vollmary - * */ public interface ArangoDeserializer { - /** - * Deserialize a given VelocyPack to an instance of a given type - * - * @param vpack - * The VelocyPack to deserialize - * @param type - * The target type to deserialize to. Use String for raw JSON. - * @return The deserialized VelocyPack - * @throws ArangoDBException - */ - T deserialize(final VPackSlice vpack, final Type type) throws ArangoDBException; + /** + * Deserialize a given VelocyPack to an instance of a given type + * + * @param vpack The VelocyPack to deserialize + * @param type The target type to deserialize to. Use String for raw JSON. + * @return The deserialized VelocyPack + * @throws ArangoDBException + */ + T deserialize(final VPackSlice vpack, final Type type) throws ArangoDBException; } diff --git a/src/main/java/com/arangodb/util/ArangoSerialization.java b/src/main/java/com/arangodb/util/ArangoSerialization.java index 06314af72..2396d51b2 100644 --- a/src/main/java/com/arangodb/util/ArangoSerialization.java +++ b/src/main/java/com/arangodb/util/ArangoSerialization.java @@ -22,7 +22,6 @@ /** * @author Mark Vollmary - * */ public interface ArangoSerialization extends ArangoSerializer, ArangoDeserializer { diff --git a/src/main/java/com/arangodb/util/ArangoSerializer.java b/src/main/java/com/arangodb/util/ArangoSerializer.java index 7a025a464..ee327d234 100644 --- a/src/main/java/com/arangodb/util/ArangoSerializer.java +++ b/src/main/java/com/arangodb/util/ArangoSerializer.java @@ -29,105 +29,93 @@ /** * @author Mark Vollmary - * */ public interface ArangoSerializer { - class Options { - private Type type; - private boolean serializeNullValues; - private Map additionalFields; - private boolean stringAsJson; - - public Options() { - super(); - serializeNullValues = false; - stringAsJson = false; - additionalFields = Collections.emptyMap(); - } - - /** - * - * @param type - * The source type of the Object. - * @return options - */ - public Options type(final Type type) { - this.type = type; - return this; - } - - /** - * - * @param serializeNullValues - * Whether or not null values should be excluded from serialization. - * @return options - */ - public Options serializeNullValues(final boolean serializeNullValues) { - this.serializeNullValues = serializeNullValues; - return this; - } - - /** - * - * @param additionalFields - * Additional Key/Value pairs to include in the created VelocyPack. - * @return options - */ - public Options additionalFields(final Map additionalFields) { - this.additionalFields = additionalFields; - return this; - } - - /** - * - * @param stringAsJson - * Wheter or not String should be interpreted as json - * @return options - */ - public Options stringAsJson(final boolean stringAsJson) { - this.stringAsJson = stringAsJson; - return this; - } - - public Type getType() { - return type; - } - - public boolean isSerializeNullValues() { - return serializeNullValues; - } - - public Map getAdditionalFields() { - return additionalFields; - } - - public boolean isStringAsJson() { - return stringAsJson; - } - - } - - /** - * Serialize a given Object to VelocyPack - * - * @param entity - * The Object to serialize. If it is from type String, it will be handled as a JSON. - * @return The serialized VelocyPack - * @throws ArangoDBException - */ - VPackSlice serialize(final Object entity) throws ArangoDBException; - - /** - * Serialize a given Object to VelocyPack - * - * @param entity - * The Object to serialize. If it is from type String, it will be handled as a JSON. - * @param options - * Additional options - * @return the serialized VelocyPack - * @throws ArangoDBException - */ - VPackSlice serialize(final Object entity, final Options options) throws ArangoDBException; + class Options { + private Type type; + private boolean serializeNullValues; + private Map additionalFields; + private boolean stringAsJson; + + public Options() { + super(); + serializeNullValues = false; + stringAsJson = false; + additionalFields = Collections.emptyMap(); + } + + /** + * @param type The source type of the Object. + * @return options + */ + public Options type(final Type type) { + this.type = type; + return this; + } + + /** + * @param serializeNullValues Whether or not null values should be excluded from serialization. + * @return options + */ + public Options serializeNullValues(final boolean serializeNullValues) { + this.serializeNullValues = serializeNullValues; + return this; + } + + /** + * @param additionalFields Additional Key/Value pairs to include in the created VelocyPack. + * @return options + */ + public Options additionalFields(final Map additionalFields) { + this.additionalFields = additionalFields; + return this; + } + + /** + * @param stringAsJson Wheter or not String should be interpreted as json + * @return options + */ + public Options stringAsJson(final boolean stringAsJson) { + this.stringAsJson = stringAsJson; + return this; + } + + public Type getType() { + return type; + } + + public boolean isSerializeNullValues() { + return serializeNullValues; + } + + public Map getAdditionalFields() { + return additionalFields; + } + + public boolean isStringAsJson() { + return stringAsJson; + } + + } + + /** + * Serialize a given Object to VelocyPack + * + * @param entity The Object to serialize. If it is from type String, it will be handled as a JSON. + * @return The serialized VelocyPack + * @throws ArangoDBException + */ + VPackSlice serialize(final Object entity) throws ArangoDBException; + + /** + * Serialize a given Object to VelocyPack + * + * @param entity The Object to serialize. If it is from type String, it will be handled as a JSON. + * @param options Additional options + * @return the serialized VelocyPack + * @throws ArangoDBException + */ + VPackSlice serialize(final Object entity, final Options options) throws ArangoDBException; } diff --git a/src/main/java/com/arangodb/util/MapBuilder.java b/src/main/java/com/arangodb/util/MapBuilder.java index faf934ce1..955bbe24e 100644 --- a/src/main/java/com/arangodb/util/MapBuilder.java +++ b/src/main/java/com/arangodb/util/MapBuilder.java @@ -25,23 +25,22 @@ /** * @author Mark Vollmary - * */ public class MapBuilder { - private final Map map; + private final Map map; - public MapBuilder() { - super(); + public MapBuilder() { + super(); map = new LinkedHashMap<>(); - } + } - public MapBuilder put(final String key, final Object value) { - map.put(key, value); - return this; - } + public MapBuilder put(final String key, final Object value) { + map.put(key, value); + return this; + } - public Map get() { - return map; - } + public Map get() { + return map; + } } diff --git a/src/main/java/com/arangodb/velocystream/Request.java b/src/main/java/com/arangodb/velocystream/Request.java index ed813366b..ab470df77 100644 --- a/src/main/java/com/arangodb/velocystream/Request.java +++ b/src/main/java/com/arangodb/velocystream/Request.java @@ -28,89 +28,88 @@ /** * @author Mark Vollmary - * */ public class Request { - private int version = 1; - private int type = 1; - private final String database; - private final RequestType requestType; - private final String request; - private final Map queryParam; - private final Map headerParam; - @Expose(serialize = false) - private VPackSlice body; - - public Request(final String database, final RequestType requestType, final String path) { - super(); - this.database = database; - this.requestType = requestType; - this.request = path; - body = null; + private int version = 1; + private int type = 1; + private final String database; + private final RequestType requestType; + private final String request; + private final Map queryParam; + private final Map headerParam; + @Expose(serialize = false) + private VPackSlice body; + + public Request(final String database, final RequestType requestType, final String path) { + super(); + this.database = database; + this.requestType = requestType; + this.request = path; + body = null; queryParam = new HashMap<>(); headerParam = new HashMap<>(); - } - - public int getVersion() { - return version; - } - - public Request setVersion(final int version) { - this.version = version; - return this; - } - - public int getType() { - return type; - } - - public Request setType(final int type) { - this.type = type; - return this; - } - - public String getDatabase() { - return database; - } - - public RequestType getRequestType() { - return requestType; - } - - public String getRequest() { - return request; - } - - public Map getQueryParam() { - return queryParam; - } - - public Request putQueryParam(final String key, final Object value) { - if (value != null) { - queryParam.put(key, value.toString()); - } - return this; - } - - public Map getHeaderParam() { - return headerParam; - } - - public Request putHeaderParam(final String key, final String value) { - if (value != null) { - headerParam.put(key, value); - } - return this; - } - - public VPackSlice getBody() { - return body; - } - - public Request setBody(final VPackSlice body) { - this.body = body; - return this; - } + } + + public int getVersion() { + return version; + } + + public Request setVersion(final int version) { + this.version = version; + return this; + } + + public int getType() { + return type; + } + + public Request setType(final int type) { + this.type = type; + return this; + } + + public String getDatabase() { + return database; + } + + public RequestType getRequestType() { + return requestType; + } + + public String getRequest() { + return request; + } + + public Map getQueryParam() { + return queryParam; + } + + public Request putQueryParam(final String key, final Object value) { + if (value != null) { + queryParam.put(key, value.toString()); + } + return this; + } + + public Map getHeaderParam() { + return headerParam; + } + + public Request putHeaderParam(final String key, final String value) { + if (value != null) { + headerParam.put(key, value); + } + return this; + } + + public VPackSlice getBody() { + return body; + } + + public Request setBody(final VPackSlice body) { + this.body = body; + return this; + } } diff --git a/src/main/java/com/arangodb/velocystream/RequestType.java b/src/main/java/com/arangodb/velocystream/RequestType.java index faf98fcad..f9f18192f 100644 --- a/src/main/java/com/arangodb/velocystream/RequestType.java +++ b/src/main/java/com/arangodb/velocystream/RequestType.java @@ -22,38 +22,37 @@ /** * @author Mark Vollmary - * */ public enum RequestType { - DELETE(0), - GET(1), - POST(2), - PUT(3), - HEAD(4), - PATCH(5), - OPTIONS(6), - VSTREAM_CRED(7), - VSTREAM_REGISTER(8), - VSTREAM_STATUS(9), - ILLEGAL(10); + DELETE(0), + GET(1), + POST(2), + PUT(3), + HEAD(4), + PATCH(5), + OPTIONS(6), + VSTREAM_CRED(7), + VSTREAM_REGISTER(8), + VSTREAM_STATUS(9), + ILLEGAL(10); - private final int type; + private final int type; - RequestType(final int type) { - this.type = type; - } + RequestType(final int type) { + this.type = type; + } - public int getType() { - return type; - } + public int getType() { + return type; + } - public static RequestType fromType(final int type) { - for (final RequestType rType : RequestType.values()) { - if (rType.type == type) { - return rType; - } - } - return null; - } + public static RequestType fromType(final int type) { + for (final RequestType rType : RequestType.values()) { + if (rType.type == type) { + return rType; + } + } + return null; + } } diff --git a/src/main/java/com/arangodb/velocystream/Response.java b/src/main/java/com/arangodb/velocystream/Response.java index 99da8db10..9e3811793 100644 --- a/src/main/java/com/arangodb/velocystream/Response.java +++ b/src/main/java/com/arangodb/velocystream/Response.java @@ -28,60 +28,59 @@ /** * @author Mark Vollmary - * */ public class Response { - private int version = 1; - private int type = 2; - private int responseCode; - private Map meta; - @Expose(deserialize = false) - private VPackSlice body = null; + private int version = 1; + private int type = 2; + private int responseCode; + private Map meta; + @Expose(deserialize = false) + private VPackSlice body = null; - public Response() { - super(); + public Response() { + super(); meta = new HashMap<>(); - } + } - public int getVersion() { - return version; - } + public int getVersion() { + return version; + } - public void setVersion(final int version) { - this.version = version; - } + public void setVersion(final int version) { + this.version = version; + } - public int getType() { - return type; - } + public int getType() { + return type; + } - public void setType(final int type) { - this.type = type; - } + public void setType(final int type) { + this.type = type; + } - public int getResponseCode() { - return responseCode; - } + public int getResponseCode() { + return responseCode; + } - public void setResponseCode(final int responseCode) { - this.responseCode = responseCode; - } + public void setResponseCode(final int responseCode) { + this.responseCode = responseCode; + } - public Map getMeta() { - return meta; - } + public Map getMeta() { + return meta; + } - public void setMeta(final Map meta) { - this.meta = meta; - } + public void setMeta(final Map meta) { + this.meta = meta; + } - public VPackSlice getBody() { - return body; - } + public VPackSlice getBody() { + return body; + } - public void setBody(final VPackSlice body) { - this.body = body; - } + public void setBody(final VPackSlice body) { + this.body = body; + } } diff --git a/src/test/java/com/arangodb/ArangoCursorTest.java b/src/test/java/com/arangodb/ArangoCursorTest.java index e4288fc48..f7b578eab 100644 --- a/src/test/java/com/arangodb/ArangoCursorTest.java +++ b/src/test/java/com/arangodb/ArangoCursorTest.java @@ -20,10 +20,12 @@ package com.arangodb; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.not; -import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertThat; +import com.arangodb.ArangoDB.Builder; +import com.arangodb.model.AqlQueryOptions; +import com.arangodb.velocypack.VPackSlice; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; import java.util.ArrayList; import java.util.HashSet; @@ -31,177 +33,171 @@ import java.util.Set; import java.util.concurrent.atomic.AtomicLong; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; - -import com.arangodb.ArangoDB.Builder; -import com.arangodb.model.AqlQueryOptions; -import com.arangodb.velocypack.VPackSlice; +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.assertThat; /** * @author Mark Vollmary - * */ @RunWith(Parameterized.class) public class ArangoCursorTest extends BaseTest { - public ArangoCursorTest(final Builder builder) { - super(builder); - } - - @Test - public void first() { - final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); - final VPackSlice first = cursor.first(); - assertThat(first, is(not(nullValue()))); - assertThat(first.isInteger(), is(true)); - assertThat(first.getAsLong(), is(0L)); - } - - @Test - public void next() { - - final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", new AqlQueryOptions().batchSize(5), VPackSlice.class); - - while(cursor.hasNext()) { - cursor.next(); - } - - } - - @Test - public void mapFilterCount() { - final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); - final long count = cursor.map(VPackSlice::getAsLong).filter(t -> t < 50).count(); - assertThat(count, is(50L)); - } - - @Test - public void mapMapFilterCount() { - final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); - final long count = cursor.map(VPackSlice::getAsLong).map(t -> t * 10).filter(t -> t < 500).count(); - assertThat(count, is(50L)); - } - - @Test - public void mapMapFilterFilterCount() { - final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); - final long count = cursor.map(VPackSlice::getAsLong).map(t -> t * 10).filter(t -> t < 500).filter(t -> t < 250).count(); - assertThat(count, is(25L)); - } - - @Test - public void mapFilterNext() { - final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); - final long count = cursor.map(VPackSlice::getAsLong).filter(t -> t < 50).iterator().next(); - assertThat(count, is(0L)); - } - - @Test - public void mapFilterFirst() { - final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); - final long count = cursor.map(VPackSlice::getAsLong).filter(t -> t < 50).first(); - assertThat(count, is(0L)); - } - - @Test - public void mapFilterCollectIntoList() { - final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); - final List target = cursor.map(VPackSlice::getAsLong).filter(t -> t < 50).collectInto(new ArrayList<>()); - assertThat(target, is(not(nullValue()))); - assertThat(target.size(), is(50)); - } - - @Test - public void mapFilterCollectIntoSet() { - final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); - final Set target = cursor.map(VPackSlice::getAsLong).filter(t -> t < 50).collectInto(new HashSet<>()); - assertThat(target, is(not(nullValue()))); - assertThat(target.size(), is(50)); - } - - @Test - public void foreach() { - final AtomicLong i = new AtomicLong(0L); - final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); - cursor.foreach(t -> assertThat(t.getAsLong(), is(i.getAndIncrement()))); - } - - @Test - public void mapForeach() { - final AtomicLong i = new AtomicLong(0L); - final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); - cursor.map(VPackSlice::getAsLong).foreach(t -> assertThat(t, is(i.getAndIncrement()))); - } - - @Test - public void mapFilterForeach() { - final AtomicLong i = new AtomicLong(0L); - final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); - cursor.map(VPackSlice::getAsLong).filter(t -> t < 50).foreach(t -> assertThat(t, is(i.getAndIncrement()))); - } - - @Test - public void anyMatch() { - final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); - final boolean match = cursor.anyMatch(t -> t.getAsLong() == 50L); - assertThat(match, is(true)); - } - - @Test - public void mapAnyMatch() { - final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); - final boolean match = cursor.map(VPackSlice::getAsLong).anyMatch(t -> t == 50L); - assertThat(match, is(true)); - } - - @Test - public void mapFilterAnyMatch() { - final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); - final boolean match = cursor.map(VPackSlice::getAsLong).filter(t -> t < 50).anyMatch(t -> t == 25L); - assertThat(match, is(true)); - } - - @Test - public void noneMatch() { - final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); - final boolean match = cursor.noneMatch(t -> t.getAsLong() == 100L); - assertThat(match, is(true)); - } - - @Test - public void mapNoneMatch() { - final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); - final boolean match = cursor.map(VPackSlice::getAsLong).noneMatch(t -> t == 100L); - assertThat(match, is(true)); - } - - @Test - public void mapFilterNoneMatch() { - final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); - final boolean match = cursor.map(VPackSlice::getAsLong).filter(t -> t < 50).noneMatch(t -> t == 50L); - assertThat(match, is(true)); - } - - @Test - public void allMatch() { - final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); - final boolean match = cursor.allMatch(t -> t.getAsLong() < 100L); - assertThat(match, is(true)); - } - - @Test - public void mapAllMatch() { - final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); - final boolean match = cursor.map(VPackSlice::getAsLong).allMatch(t -> t < 100); - assertThat(match, is(true)); - } - - @Test - public void mapFilterAllMatch() { - final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); - final boolean match = cursor.map(VPackSlice::getAsLong).filter(t -> t < 50).allMatch(t -> t < 50); - assertThat(match, is(true)); - } + public ArangoCursorTest(final Builder builder) { + super(builder); + } + + @Test + public void first() { + final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); + final VPackSlice first = cursor.first(); + assertThat(first, is(not(nullValue()))); + assertThat(first.isInteger(), is(true)); + assertThat(first.getAsLong(), is(0L)); + } + + @Test + public void next() { + + final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", new AqlQueryOptions().batchSize(5), VPackSlice.class); + + while (cursor.hasNext()) { + cursor.next(); + } + + } + + @Test + public void mapFilterCount() { + final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); + final long count = cursor.map(VPackSlice::getAsLong).filter(t -> t < 50).count(); + assertThat(count, is(50L)); + } + + @Test + public void mapMapFilterCount() { + final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); + final long count = cursor.map(VPackSlice::getAsLong).map(t -> t * 10).filter(t -> t < 500).count(); + assertThat(count, is(50L)); + } + + @Test + public void mapMapFilterFilterCount() { + final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); + final long count = cursor.map(VPackSlice::getAsLong).map(t -> t * 10).filter(t -> t < 500).filter(t -> t < 250).count(); + assertThat(count, is(25L)); + } + + @Test + public void mapFilterNext() { + final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); + final long count = cursor.map(VPackSlice::getAsLong).filter(t -> t < 50).iterator().next(); + assertThat(count, is(0L)); + } + + @Test + public void mapFilterFirst() { + final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); + final long count = cursor.map(VPackSlice::getAsLong).filter(t -> t < 50).first(); + assertThat(count, is(0L)); + } + + @Test + public void mapFilterCollectIntoList() { + final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); + final List target = cursor.map(VPackSlice::getAsLong).filter(t -> t < 50).collectInto(new ArrayList<>()); + assertThat(target, is(not(nullValue()))); + assertThat(target.size(), is(50)); + } + + @Test + public void mapFilterCollectIntoSet() { + final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); + final Set target = cursor.map(VPackSlice::getAsLong).filter(t -> t < 50).collectInto(new HashSet<>()); + assertThat(target, is(not(nullValue()))); + assertThat(target.size(), is(50)); + } + + @Test + public void foreach() { + final AtomicLong i = new AtomicLong(0L); + final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); + cursor.foreach(t -> assertThat(t.getAsLong(), is(i.getAndIncrement()))); + } + + @Test + public void mapForeach() { + final AtomicLong i = new AtomicLong(0L); + final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); + cursor.map(VPackSlice::getAsLong).foreach(t -> assertThat(t, is(i.getAndIncrement()))); + } + + @Test + public void mapFilterForeach() { + final AtomicLong i = new AtomicLong(0L); + final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); + cursor.map(VPackSlice::getAsLong).filter(t -> t < 50).foreach(t -> assertThat(t, is(i.getAndIncrement()))); + } + + @Test + public void anyMatch() { + final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); + final boolean match = cursor.anyMatch(t -> t.getAsLong() == 50L); + assertThat(match, is(true)); + } + + @Test + public void mapAnyMatch() { + final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); + final boolean match = cursor.map(VPackSlice::getAsLong).anyMatch(t -> t == 50L); + assertThat(match, is(true)); + } + + @Test + public void mapFilterAnyMatch() { + final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); + final boolean match = cursor.map(VPackSlice::getAsLong).filter(t -> t < 50).anyMatch(t -> t == 25L); + assertThat(match, is(true)); + } + + @Test + public void noneMatch() { + final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); + final boolean match = cursor.noneMatch(t -> t.getAsLong() == 100L); + assertThat(match, is(true)); + } + + @Test + public void mapNoneMatch() { + final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); + final boolean match = cursor.map(VPackSlice::getAsLong).noneMatch(t -> t == 100L); + assertThat(match, is(true)); + } + + @Test + public void mapFilterNoneMatch() { + final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); + final boolean match = cursor.map(VPackSlice::getAsLong).filter(t -> t < 50).noneMatch(t -> t == 50L); + assertThat(match, is(true)); + } + + @Test + public void allMatch() { + final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); + final boolean match = cursor.allMatch(t -> t.getAsLong() < 100L); + assertThat(match, is(true)); + } + + @Test + public void mapAllMatch() { + final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); + final boolean match = cursor.map(VPackSlice::getAsLong).allMatch(t -> t < 100); + assertThat(match, is(true)); + } + + @Test + public void mapFilterAllMatch() { + final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); + final boolean match = cursor.map(VPackSlice::getAsLong).filter(t -> t < 50).allMatch(t -> t < 50); + assertThat(match, is(true)); + } } diff --git a/src/test/java/com/arangodb/ArangoDBTest.java b/src/test/java/com/arangodb/ArangoDBTest.java index 7ae31f5aa..237f23089 100644 --- a/src/test/java/com/arangodb/ArangoDBTest.java +++ b/src/test/java/com/arangodb/ArangoDBTest.java @@ -20,27 +20,26 @@ package com.arangodb; -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; -import static org.junit.Assume.assumeTrue; - -import java.util.*; - +import com.arangodb.ArangoDB.Builder; import com.arangodb.entity.*; import com.arangodb.model.*; +import com.arangodb.model.LogOptions.SortOrder; +import com.arangodb.velocypack.exception.VPackException; +import com.arangodb.velocystream.Request; +import com.arangodb.velocystream.RequestType; +import com.arangodb.velocystream.Response; import org.hamcrest.Matcher; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; -import com.arangodb.ArangoDB.Builder; -import com.arangodb.model.LogOptions.SortOrder; -import com.arangodb.velocypack.exception.VPackException; -import com.arangodb.velocystream.Request; -import com.arangodb.velocystream.RequestType; -import com.arangodb.velocystream.Response; +import java.util.*; + +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.fail; +import static org.junit.Assume.assumeTrue; /** * @author Mark Vollmary diff --git a/src/test/java/com/arangodb/ArangoDocumentUtilTest.java b/src/test/java/com/arangodb/ArangoDocumentUtilTest.java index 21ff12948..d8b5c8dd3 100644 --- a/src/test/java/com/arangodb/ArangoDocumentUtilTest.java +++ b/src/test/java/com/arangodb/ArangoDocumentUtilTest.java @@ -20,59 +20,57 @@ package com.arangodb; -import org.junit.Test; - import com.arangodb.internal.util.DocumentUtil; +import org.junit.Test; /** * @author Mark Vollmary - * */ public class ArangoDocumentUtilTest { - @Test - public void validateDocumentKeyValid() { - checkDocumentKey("1test"); - checkDocumentKey("test1"); - checkDocumentKey("test-1"); - checkDocumentKey("test_1"); - checkDocumentKey("_test"); - } + @Test + public void validateDocumentKeyValid() { + checkDocumentKey("1test"); + checkDocumentKey("test1"); + checkDocumentKey("test-1"); + checkDocumentKey("test_1"); + checkDocumentKey("_test"); + } - @Test(expected = ArangoDBException.class) - public void validateDocumentKeyInvalidSlash() { - checkDocumentKey("test/test"); - } + @Test(expected = ArangoDBException.class) + public void validateDocumentKeyInvalidSlash() { + checkDocumentKey("test/test"); + } - @Test(expected = ArangoDBException.class) - public void validateDocumentKeyEmpty() { - checkDocumentKey(""); - } + @Test(expected = ArangoDBException.class) + public void validateDocumentKeyEmpty() { + checkDocumentKey(""); + } - private void checkDocumentKey(final String key) throws ArangoDBException { - DocumentUtil.validateDocumentKey(key); - } + private void checkDocumentKey(final String key) throws ArangoDBException { + DocumentUtil.validateDocumentKey(key); + } - @Test - public void validateDocumentIdValid() { - checkDocumentId("1test/1test"); - checkDocumentId("test1/test1"); - checkDocumentId("test-1/test-1"); - checkDocumentId("test_1/test_1"); - checkDocumentId("_test/_test"); - } + @Test + public void validateDocumentIdValid() { + checkDocumentId("1test/1test"); + checkDocumentId("test1/test1"); + checkDocumentId("test-1/test-1"); + checkDocumentId("test_1/test_1"); + checkDocumentId("_test/_test"); + } - @Test(expected = ArangoDBException.class) - public void validateDocumentIdInvalidWithoutSlash() { - checkDocumentId("test"); - } + @Test(expected = ArangoDBException.class) + public void validateDocumentIdInvalidWithoutSlash() { + checkDocumentId("test"); + } - @Test(expected = ArangoDBException.class) - public void validateDocumentIdEmpty() { - checkDocumentId(""); - } + @Test(expected = ArangoDBException.class) + public void validateDocumentIdEmpty() { + checkDocumentId(""); + } - private void checkDocumentId(final String id) throws ArangoDBException { - DocumentUtil.validateDocumentId(id); - } + private void checkDocumentId(final String id) throws ArangoDBException { + DocumentUtil.validateDocumentId(id); + } } diff --git a/src/test/java/com/arangodb/ArangoRouteTest.java b/src/test/java/com/arangodb/ArangoRouteTest.java index af50a9968..8e85ec364 100644 --- a/src/test/java/com/arangodb/ArangoRouteTest.java +++ b/src/test/java/com/arangodb/ArangoRouteTest.java @@ -20,68 +20,66 @@ package com.arangodb; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; - import com.arangodb.ArangoDB.Builder; import com.arangodb.entity.BaseDocument; import com.arangodb.internal.ArangoRequestParam; import com.arangodb.velocystream.Response; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; + +import static org.hamcrest.Matchers.is; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.fail; /** * @author Mark Vollmary - * */ @RunWith(Parameterized.class) public class ArangoRouteTest extends BaseTest { - public ArangoRouteTest(final Builder builder) { - super(builder); - } + public ArangoRouteTest(final Builder builder) { + super(builder); + } - @Test - public void get() { - final Response res = db.route("/_api/version").get(); - assertThat(res.getBody().get("version").isString(), is(true)); - } + @Test + public void get() { + final Response res = db.route("/_api/version").get(); + assertThat(res.getBody().get("version").isString(), is(true)); + } - @Test - public void withHeader() { - final ArangoCollection collection = db.collection("route-test-col"); - try { - collection.create(); - final BaseDocument doc = new BaseDocument(); - collection.insertDocument(doc); - db.route("/_api/document", doc.getId()).withHeader(ArangoRequestParam.IF_NONE_MATCH, doc.getRevision()) - .get(); - fail(); - } catch (final ArangoDBException e) { - assertThat(e.getResponseCode(), is(304)); - } finally { - collection.drop(); - } - } + @Test + public void withHeader() { + final ArangoCollection collection = db.collection("route-test-col"); + try { + collection.create(); + final BaseDocument doc = new BaseDocument(); + collection.insertDocument(doc); + db.route("/_api/document", doc.getId()).withHeader(ArangoRequestParam.IF_NONE_MATCH, doc.getRevision()) + .get(); + fail(); + } catch (final ArangoDBException e) { + assertThat(e.getResponseCode(), is(304)); + } finally { + collection.drop(); + } + } - @Test - public void withParentHeader() { - final ArangoCollection collection = db.collection("route-test-col"); - try { - collection.create(); - final BaseDocument doc = new BaseDocument(); - collection.insertDocument(doc); - db.route("/_api/document").withHeader(ArangoRequestParam.IF_NONE_MATCH, doc.getRevision()) - .route(doc.getId()).get(); - fail(); - } catch (final ArangoDBException e) { - assertThat(e.getResponseCode(), is(304)); - } finally { - collection.drop(); - } - } + @Test + public void withParentHeader() { + final ArangoCollection collection = db.collection("route-test-col"); + try { + collection.create(); + final BaseDocument doc = new BaseDocument(); + collection.insertDocument(doc); + db.route("/_api/document").withHeader(ArangoRequestParam.IF_NONE_MATCH, doc.getRevision()) + .route(doc.getId()).get(); + fail(); + } catch (final ArangoDBException e) { + assertThat(e.getResponseCode(), is(304)); + } finally { + collection.drop(); + } + } } diff --git a/src/test/java/com/arangodb/ArangoSslTest.java b/src/test/java/com/arangodb/ArangoSslTest.java index 50ad138b4..a5f99ae7a 100644 --- a/src/test/java/com/arangodb/ArangoSslTest.java +++ b/src/test/java/com/arangodb/ArangoSslTest.java @@ -20,75 +20,72 @@ package com.arangodb; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.notNullValue; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; - -import java.security.KeyStore; +import com.arangodb.entity.ArangoDBVersion; +import org.junit.Ignore; +import org.junit.Test; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLHandshakeException; import javax.net.ssl.TrustManagerFactory; +import java.security.KeyStore; -import org.junit.Ignore; -import org.junit.Test; - -import com.arangodb.entity.ArangoDBVersion; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.fail; /** * @author Mark Vollmary - * */ public class ArangoSslTest { - /*- - * 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"; + /*- + * 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 - @Ignore - public void connect() throws Exception { - final KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); - ks.load(this.getClass().getResourceAsStream(SSL_TRUSTSTORE), SSL_TRUSTSTORE_PASSWORD.toCharArray()); + @Test + @Ignore + public 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 KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); + kmf.init(ks, SSL_TRUSTSTORE_PASSWORD.toCharArray()); - final TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); - tmf.init(ks); + final TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); + tmf.init(ks); - final SSLContext sc = SSLContext.getInstance("TLS"); - sc.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); + final SSLContext sc = SSLContext.getInstance("TLS"); + sc.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); - final ArangoDB arangoDB = new ArangoDB.Builder() - .loadProperties(ArangoSslTest.class.getResourceAsStream("/arangodb-ssl.properties")).useSsl(true) - .sslContext(sc).build(); - final ArangoDBVersion version = arangoDB.getVersion(); - assertThat(version, is(notNullValue())); - } + final ArangoDB arangoDB = new ArangoDB.Builder() + .loadProperties(ArangoSslTest.class.getResourceAsStream("/arangodb-ssl.properties")).useSsl(true) + .sslContext(sc).build(); + final ArangoDBVersion version = arangoDB.getVersion(); + assertThat(version, is(notNullValue())); + } - @Test - @Ignore - public void connectWithoutValidSslContext() { - try { - final ArangoDB arangoDB = new ArangoDB.Builder() - .loadProperties(ArangoSslTest.class.getResourceAsStream("/arangodb-ssl.properties")).useSsl(true) - .build(); - arangoDB.getVersion(); - fail("this should fail"); - } catch (final ArangoDBException ex) { - assertThat(ex.getCause() instanceof SSLHandshakeException, is(true)); - } - } + @Test + @Ignore + public void connectWithoutValidSslContext() { + try { + final ArangoDB arangoDB = new ArangoDB.Builder() + .loadProperties(ArangoSslTest.class.getResourceAsStream("/arangodb-ssl.properties")).useSsl(true) + .build(); + arangoDB.getVersion(); + fail("this should fail"); + } catch (final ArangoDBException ex) { + assertThat(ex.getCause() instanceof SSLHandshakeException, is(true)); + } + } } diff --git a/src/test/java/com/arangodb/ConcurrentStreamTransactionsTest.java b/src/test/java/com/arangodb/ConcurrentStreamTransactionsTest.java index 33ad8035a..fe1d4e73c 100644 --- a/src/test/java/com/arangodb/ConcurrentStreamTransactionsTest.java +++ b/src/test/java/com/arangodb/ConcurrentStreamTransactionsTest.java @@ -120,6 +120,6 @@ public void conflictOnInsertDocumentWithAlreadyCommittedTx() { e.printStackTrace(); } - db.abortStreamTransaction(tx2.getId()); + db.abortStreamTransaction(tx2.getId()); } } diff --git a/src/test/java/com/arangodb/DocumentTest.java b/src/test/java/com/arangodb/DocumentTest.java index 5a70b8611..8f3c7cd71 100644 --- a/src/test/java/com/arangodb/DocumentTest.java +++ b/src/test/java/com/arangodb/DocumentTest.java @@ -20,20 +20,19 @@ package com.arangodb; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.notNullValue; -import static org.junit.Assert.assertThat; - -import java.util.Map; - +import com.arangodb.ArangoDB.Builder; +import com.arangodb.entity.BaseDocument; +import com.arangodb.entity.DocumentCreateEntity; import org.junit.After; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; -import com.arangodb.ArangoDB.Builder; -import com.arangodb.entity.BaseDocument; -import com.arangodb.entity.DocumentCreateEntity; +import java.util.Map; + +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.junit.Assert.assertThat; /** * @author Mark Vollmary diff --git a/src/test/java/com/arangodb/UserAuthTest.java b/src/test/java/com/arangodb/UserAuthTest.java index 3175987dd..ca70d682e 100644 --- a/src/test/java/com/arangodb/UserAuthTest.java +++ b/src/test/java/com/arangodb/UserAuthTest.java @@ -20,25 +20,6 @@ package com.arangodb; -import static org.hamcrest.Matchers.hasItem; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.not; -import static org.hamcrest.Matchers.notNullValue; -import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; - -import org.junit.AfterClass; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; - import com.arangodb.entity.BaseDocument; import com.arangodb.entity.CollectionEntity; import com.arangodb.entity.IndexEntity; @@ -48,6 +29,20 @@ import com.arangodb.model.HashIndexOptions; import com.arangodb.model.UserUpdateOptions; import com.arangodb.util.MapBuilder; +import org.junit.AfterClass; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; +import org.junit.runners.Parameterized.Parameters; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; + +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.fail; /** * @author Mark Vollmary diff --git a/src/test/java/com/arangodb/entity/BaseDocumentTest.java b/src/test/java/com/arangodb/entity/BaseDocumentTest.java index f71c9e565..269a53219 100644 --- a/src/test/java/com/arangodb/entity/BaseDocumentTest.java +++ b/src/test/java/com/arangodb/entity/BaseDocumentTest.java @@ -20,12 +20,6 @@ package com.arangodb.entity; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.notNullValue; -import static org.junit.Assert.assertThat; - -import org.junit.Test; - import com.arangodb.internal.velocypack.VPackDriverModule; import com.arangodb.velocypack.VPack; import com.arangodb.velocypack.VPack.Builder; @@ -33,65 +27,69 @@ import com.arangodb.velocypack.VPackSlice; import com.arangodb.velocypack.ValueType; import com.arangodb.velocypack.exception.VPackException; +import org.junit.Test; + +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.junit.Assert.assertThat; /** * @author Mark Vollmary - * */ public class BaseDocumentTest { - @Test - public void serialize() throws VPackException { - final BaseDocument entity = new BaseDocument(); - entity.setKey("test"); - entity.setRevision("test"); - entity.addAttribute("a", "a"); + @Test + public void serialize() throws VPackException { + final BaseDocument entity = new BaseDocument(); + entity.setKey("test"); + entity.setRevision("test"); + entity.addAttribute("a", "a"); - final Builder builder = new VPack.Builder(); - builder.registerModule(new VPackDriverModule()); - final VPack vpacker = builder.build(); + final Builder builder = new VPack.Builder(); + builder.registerModule(new VPackDriverModule()); + final VPack vpacker = builder.build(); - final VPackSlice vpack = vpacker.serialize(entity); - assertThat(vpack, is(notNullValue())); - assertThat(vpack.isObject(), is(true)); - assertThat(vpack.size(), is(3)); + final VPackSlice vpack = vpacker.serialize(entity); + assertThat(vpack, is(notNullValue())); + assertThat(vpack.isObject(), is(true)); + assertThat(vpack.size(), is(3)); - final VPackSlice key = vpack.get("_key"); - assertThat(key.isString(), is(true)); - assertThat(key.getAsString(), is("test")); + final VPackSlice key = vpack.get("_key"); + assertThat(key.isString(), is(true)); + assertThat(key.getAsString(), is("test")); - final VPackSlice rev = vpack.get("_rev"); - assertThat(rev.isString(), is(true)); - assertThat(rev.getAsString(), is("test")); + final VPackSlice rev = vpack.get("_rev"); + assertThat(rev.isString(), is(true)); + assertThat(rev.getAsString(), is("test")); - final VPackSlice a = vpack.get("a"); - assertThat(a.isString(), is(true)); - assertThat(a.getAsString(), is("a")); - } + final VPackSlice a = vpack.get("a"); + assertThat(a.isString(), is(true)); + assertThat(a.getAsString(), is("a")); + } - @Test - public void deserialize() throws VPackException { - final VPackBuilder builder = new VPackBuilder(); - builder.add(ValueType.OBJECT); - builder.add("_id", "test/test"); - builder.add("_key", "test"); - builder.add("_rev", "test"); - builder.add("a", "a"); - builder.close(); + @Test + public void deserialize() throws VPackException { + final VPackBuilder builder = new VPackBuilder(); + builder.add(ValueType.OBJECT); + builder.add("_id", "test/test"); + builder.add("_key", "test"); + builder.add("_rev", "test"); + builder.add("a", "a"); + builder.close(); - final VPack.Builder vbuilder = new VPack.Builder(); - vbuilder.registerModule(new VPackDriverModule()); - final VPack vpacker = vbuilder.build(); + final VPack.Builder vbuilder = new VPack.Builder(); + vbuilder.registerModule(new VPackDriverModule()); + final VPack vpacker = vbuilder.build(); - final BaseDocument entity = vpacker.deserialize(builder.slice(), BaseDocument.class); - assertThat(entity.getId(), is(notNullValue())); - assertThat(entity.getId(), is("test/test")); - assertThat(entity.getKey(), is(notNullValue())); - assertThat(entity.getKey(), is("test")); - assertThat(entity.getRevision(), is(notNullValue())); - assertThat(entity.getRevision(), is("test")); - assertThat(entity.getProperties().size(), is(1)); - assertThat(String.valueOf(entity.getAttribute("a")), is("a")); - } + final BaseDocument entity = vpacker.deserialize(builder.slice(), BaseDocument.class); + assertThat(entity.getId(), is(notNullValue())); + assertThat(entity.getId(), is("test/test")); + assertThat(entity.getKey(), is(notNullValue())); + assertThat(entity.getKey(), is("test")); + assertThat(entity.getRevision(), is(notNullValue())); + assertThat(entity.getRevision(), is("test")); + assertThat(entity.getProperties().size(), is(1)); + assertThat(String.valueOf(entity.getAttribute("a")), is("a")); + } } diff --git a/src/test/java/com/arangodb/example/ExampleBase.java b/src/test/java/com/arangodb/example/ExampleBase.java index 9f0b611c7..a1fc11363 100644 --- a/src/test/java/com/arangodb/example/ExampleBase.java +++ b/src/test/java/com/arangodb/example/ExampleBase.java @@ -20,12 +20,11 @@ package com.arangodb.example; -import org.junit.AfterClass; -import org.junit.BeforeClass; - import com.arangodb.ArangoCollection; import com.arangodb.ArangoDB; import com.arangodb.ArangoDatabase; +import org.junit.AfterClass; +import org.junit.BeforeClass; /** * @author Mark Vollmary diff --git a/src/test/java/com/arangodb/example/FirstProject.java b/src/test/java/com/arangodb/example/FirstProject.java index dd12053b6..158367ba0 100644 --- a/src/test/java/com/arangodb/example/FirstProject.java +++ b/src/test/java/com/arangodb/example/FirstProject.java @@ -1,7 +1,5 @@ package com.arangodb.example; -import java.util.Map; - import com.arangodb.ArangoCollection; import com.arangodb.ArangoCursor; import com.arangodb.ArangoDB; @@ -11,126 +9,128 @@ import com.arangodb.util.MapBuilder; import com.arangodb.velocypack.VPackSlice; +import java.util.Map; + public class FirstProject { - public static void main(final String[] args) { - final ArangoDB arangoDB = new ArangoDB.Builder().user("root").build(); - - // create database - final String dbName = "mydb"; - try { - arangoDB.createDatabase(dbName); - System.out.println("Database created: " + dbName); - } catch (final ArangoDBException e) { - System.err.println("Failed to create database: " + dbName + "; " + e.getMessage()); - } - - // create collection - final String collectionName = "firstCollection"; - try { - final CollectionEntity myArangoCollection = arangoDB.db(dbName).createCollection(collectionName); - System.out.println("Collection created: " + myArangoCollection.getName()); - } catch (final ArangoDBException e) { - System.err.println("Failed to create collection: " + collectionName + "; " + e.getMessage()); - } - - // creating a document - final BaseDocument myObject = new BaseDocument(); - myObject.setKey("myKey"); - myObject.addAttribute("a", "Foo"); - myObject.addAttribute("b", 42); - try { - arangoDB.db(dbName).collection(collectionName).insertDocument(myObject); - System.out.println("Document created"); - } catch (final ArangoDBException e) { - System.err.println("Failed to create document. " + e.getMessage()); - } - - // read a document - try { - final BaseDocument myDocument = arangoDB.db(dbName).collection(collectionName).getDocument("myKey", - BaseDocument.class); - System.out.println("Key: " + myDocument.getKey()); - System.out.println("Attribute a: " + myDocument.getAttribute("a")); - System.out.println("Attribute b: " + myDocument.getAttribute("b")); - } catch (final ArangoDBException e) { - System.err.println("Failed to get document: myKey; " + e.getMessage()); - } - - // read a document as VPack - try { - final VPackSlice myDocument = arangoDB.db(dbName).collection(collectionName).getDocument("myKey", - VPackSlice.class); - System.out.println("Key: " + myDocument.get("_key").getAsString()); - System.out.println("Attribute a: " + myDocument.get("a").getAsString()); - System.out.println("Attribute b: " + myDocument.get("b").getAsInt()); - } catch (final ArangoDBException e) { - System.err.println("Failed to get document: myKey; " + e.getMessage()); - } - - // update a document - myObject.addAttribute("c", "Bar"); - try { - arangoDB.db(dbName).collection(collectionName).updateDocument("myKey", myObject); - } catch (final ArangoDBException e) { - System.err.println("Failed to update document. " + e.getMessage()); - } - - // read the document again - try { - final BaseDocument myUpdatedDocument = arangoDB.db(dbName).collection(collectionName).getDocument("myKey", - BaseDocument.class); - System.out.println("Key: " + myUpdatedDocument.getKey()); - System.out.println("Attribute a: " + myUpdatedDocument.getAttribute("a")); - System.out.println("Attribute b: " + myUpdatedDocument.getAttribute("b")); - System.out.println("Attribute c: " + myUpdatedDocument.getAttribute("c")); - } catch (final ArangoDBException e) { - System.err.println("Failed to get document: myKey; " + e.getMessage()); - } - - // delete a document - try { - arangoDB.db(dbName).collection(collectionName).deleteDocument("myKey"); - } catch (final ArangoDBException e) { - System.err.println("Failed to delete document. " + e.getMessage()); - } - - // create some documents for the next step - final ArangoCollection collection = arangoDB.db(dbName).collection(collectionName); - for (int i = 0; i < 10; i++) { - final BaseDocument value = new BaseDocument(); - value.setKey(String.valueOf(i)); - value.addAttribute("name", "Homer"); - collection.insertDocument(value); - } - - // execute AQL queries - try { - final String query = "FOR t IN firstCollection FILTER t.name == @name RETURN t"; - final Map bindVars = new MapBuilder().put("name", "Homer").get(); - final ArangoCursor cursor = arangoDB.db(dbName).query(query, bindVars, null, - BaseDocument.class); - for (; cursor.hasNext();) { - System.out.println("Key: " + cursor.next().getKey()); - } - } catch (final ArangoDBException e) { - System.err.println("Failed to execute query. " + e.getMessage()); - } - - // delete a document with AQL - try { - final String query = "FOR t IN firstCollection FILTER t.name == @name " - + "REMOVE t IN firstCollection LET removed = OLD RETURN removed"; - final Map bindVars = new MapBuilder().put("name", "Homer").get(); - final ArangoCursor cursor = arangoDB.db(dbName).query(query, bindVars, null, - BaseDocument.class); - for (; cursor.hasNext();) { - System.out.println("Removed document " + cursor.next().getKey()); - } - } catch (final ArangoDBException e) { - System.err.println("Failed to execute query. " + e.getMessage()); - } - - } + public static void main(final String[] args) { + final ArangoDB arangoDB = new ArangoDB.Builder().user("root").build(); + + // create database + final String dbName = "mydb"; + try { + arangoDB.createDatabase(dbName); + System.out.println("Database created: " + dbName); + } catch (final ArangoDBException e) { + System.err.println("Failed to create database: " + dbName + "; " + e.getMessage()); + } + + // create collection + final String collectionName = "firstCollection"; + try { + final CollectionEntity myArangoCollection = arangoDB.db(dbName).createCollection(collectionName); + System.out.println("Collection created: " + myArangoCollection.getName()); + } catch (final ArangoDBException e) { + System.err.println("Failed to create collection: " + collectionName + "; " + e.getMessage()); + } + + // creating a document + final BaseDocument myObject = new BaseDocument(); + myObject.setKey("myKey"); + myObject.addAttribute("a", "Foo"); + myObject.addAttribute("b", 42); + try { + arangoDB.db(dbName).collection(collectionName).insertDocument(myObject); + System.out.println("Document created"); + } catch (final ArangoDBException e) { + System.err.println("Failed to create document. " + e.getMessage()); + } + + // read a document + try { + final BaseDocument myDocument = arangoDB.db(dbName).collection(collectionName).getDocument("myKey", + BaseDocument.class); + System.out.println("Key: " + myDocument.getKey()); + System.out.println("Attribute a: " + myDocument.getAttribute("a")); + System.out.println("Attribute b: " + myDocument.getAttribute("b")); + } catch (final ArangoDBException e) { + System.err.println("Failed to get document: myKey; " + e.getMessage()); + } + + // read a document as VPack + try { + final VPackSlice myDocument = arangoDB.db(dbName).collection(collectionName).getDocument("myKey", + VPackSlice.class); + System.out.println("Key: " + myDocument.get("_key").getAsString()); + System.out.println("Attribute a: " + myDocument.get("a").getAsString()); + System.out.println("Attribute b: " + myDocument.get("b").getAsInt()); + } catch (final ArangoDBException e) { + System.err.println("Failed to get document: myKey; " + e.getMessage()); + } + + // update a document + myObject.addAttribute("c", "Bar"); + try { + arangoDB.db(dbName).collection(collectionName).updateDocument("myKey", myObject); + } catch (final ArangoDBException e) { + System.err.println("Failed to update document. " + e.getMessage()); + } + + // read the document again + try { + final BaseDocument myUpdatedDocument = arangoDB.db(dbName).collection(collectionName).getDocument("myKey", + BaseDocument.class); + System.out.println("Key: " + myUpdatedDocument.getKey()); + System.out.println("Attribute a: " + myUpdatedDocument.getAttribute("a")); + System.out.println("Attribute b: " + myUpdatedDocument.getAttribute("b")); + System.out.println("Attribute c: " + myUpdatedDocument.getAttribute("c")); + } catch (final ArangoDBException e) { + System.err.println("Failed to get document: myKey; " + e.getMessage()); + } + + // delete a document + try { + arangoDB.db(dbName).collection(collectionName).deleteDocument("myKey"); + } catch (final ArangoDBException e) { + System.err.println("Failed to delete document. " + e.getMessage()); + } + + // create some documents for the next step + final ArangoCollection collection = arangoDB.db(dbName).collection(collectionName); + for (int i = 0; i < 10; i++) { + final BaseDocument value = new BaseDocument(); + value.setKey(String.valueOf(i)); + value.addAttribute("name", "Homer"); + collection.insertDocument(value); + } + + // execute AQL queries + try { + final String query = "FOR t IN firstCollection FILTER t.name == @name RETURN t"; + final Map bindVars = new MapBuilder().put("name", "Homer").get(); + final ArangoCursor cursor = arangoDB.db(dbName).query(query, bindVars, null, + BaseDocument.class); + for (; cursor.hasNext(); ) { + System.out.println("Key: " + cursor.next().getKey()); + } + } catch (final ArangoDBException e) { + System.err.println("Failed to execute query. " + e.getMessage()); + } + + // delete a document with AQL + try { + final String query = "FOR t IN firstCollection FILTER t.name == @name " + + "REMOVE t IN firstCollection LET removed = OLD RETURN removed"; + final Map bindVars = new MapBuilder().put("name", "Homer").get(); + final ArangoCursor cursor = arangoDB.db(dbName).query(query, bindVars, null, + BaseDocument.class); + for (; cursor.hasNext(); ) { + System.out.println("Removed document " + cursor.next().getKey()); + } + } catch (final ArangoDBException e) { + System.err.println("Failed to execute query. " + e.getMessage()); + } + + } } diff --git a/src/test/java/com/arangodb/example/document/AqlQueryWithSpecialReturnTypesExample.java b/src/test/java/com/arangodb/example/document/AqlQueryWithSpecialReturnTypesExample.java index fc5c66fb8..5b2fa1154 100644 --- a/src/test/java/com/arangodb/example/document/AqlQueryWithSpecialReturnTypesExample.java +++ b/src/test/java/com/arangodb/example/document/AqlQueryWithSpecialReturnTypesExample.java @@ -20,22 +20,19 @@ package com.arangodb.example.document; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.isOneOf; -import static org.hamcrest.Matchers.notNullValue; -import static org.junit.Assert.assertThat; - -import java.util.List; -import java.util.Map; - -import org.junit.BeforeClass; -import org.junit.Test; - import com.arangodb.ArangoCursor; import com.arangodb.entity.BaseDocument; import com.arangodb.example.ExampleBase; import com.arangodb.util.MapBuilder; import com.arangodb.velocypack.VPackSlice; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.util.List; +import java.util.Map; + +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.assertThat; /** * @author Mark Vollmary diff --git a/src/test/java/com/arangodb/example/document/GetDocumentExample.java b/src/test/java/com/arangodb/example/document/GetDocumentExample.java index e85304179..ad4843ab6 100644 --- a/src/test/java/com/arangodb/example/document/GetDocumentExample.java +++ b/src/test/java/com/arangodb/example/document/GetDocumentExample.java @@ -20,74 +20,72 @@ package com.arangodb.example.document; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.notNullValue; -import static org.junit.Assert.assertThat; - -import java.util.Map; - -import org.junit.BeforeClass; -import org.junit.Test; - import com.arangodb.entity.BaseDocument; import com.arangodb.entity.DocumentCreateEntity; import com.arangodb.example.ExampleBase; import com.arangodb.velocypack.VPackSlice; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.util.Map; + +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.junit.Assert.assertThat; /** * @author Mark Vollmary - * */ public class GetDocumentExample extends ExampleBase { - private static String key = null; + private static String key = null; - @BeforeClass - public static void before() { - final BaseDocument value = new BaseDocument(); - value.addAttribute("foo", "bar"); - final DocumentCreateEntity doc = collection.insertDocument(value); - key = doc.getKey(); - } + @BeforeClass + public static void before() { + final BaseDocument value = new BaseDocument(); + value.addAttribute("foo", "bar"); + final DocumentCreateEntity doc = collection.insertDocument(value); + key = doc.getKey(); + } - @Test - public void getAsBean() { - final TestEntity doc = collection.getDocument(key, TestEntity.class); - assertThat(doc, is(notNullValue())); - assertThat(doc.getFoo(), is("bar")); - } + @Test + public void getAsBean() { + final TestEntity doc = collection.getDocument(key, TestEntity.class); + assertThat(doc, is(notNullValue())); + assertThat(doc.getFoo(), is("bar")); + } - @Test - public void getAsBaseDocument() { - final BaseDocument doc = collection.getDocument(key, BaseDocument.class); - assertThat(doc, is(notNullValue())); - assertThat(doc.getAttribute("foo"), is(notNullValue())); - assertThat(String.valueOf(doc.getAttribute("foo")), is("bar")); - } + @Test + public void getAsBaseDocument() { + final BaseDocument doc = collection.getDocument(key, BaseDocument.class); + assertThat(doc, is(notNullValue())); + assertThat(doc.getAttribute("foo"), is(notNullValue())); + assertThat(String.valueOf(doc.getAttribute("foo")), is("bar")); + } - @SuppressWarnings("unchecked") - @Test - public void getAsMap() { - final Map doc = collection.getDocument(key, Map.class); - assertThat(doc, is(notNullValue())); - assertThat(doc.get("foo"), is(notNullValue())); - assertThat(String.valueOf(doc.get("foo")), is("bar")); - } + @SuppressWarnings("unchecked") + @Test + public void getAsMap() { + final Map doc = collection.getDocument(key, Map.class); + assertThat(doc, is(notNullValue())); + assertThat(doc.get("foo"), is(notNullValue())); + assertThat(String.valueOf(doc.get("foo")), is("bar")); + } - @Test - public void getAsVPack() { - final VPackSlice doc = collection.getDocument(key, VPackSlice.class); - assertThat(doc, is(notNullValue())); - assertThat(doc.get("foo").isString(), is(true)); - assertThat(doc.get("foo").getAsString(), is("bar")); - } + @Test + public void getAsVPack() { + final VPackSlice doc = collection.getDocument(key, VPackSlice.class); + assertThat(doc, is(notNullValue())); + assertThat(doc.get("foo").isString(), is(true)); + assertThat(doc.get("foo").getAsString(), is("bar")); + } - @Test - public void getAsJson() { - final String doc = collection.getDocument(key, String.class); - assertThat(doc, is(notNullValue())); - assertThat(doc.contains("foo"), is(true)); - assertThat(doc.contains("bar"), is(true)); - } + @Test + public void getAsJson() { + final String doc = collection.getDocument(key, String.class); + assertThat(doc, is(notNullValue())); + assertThat(doc.contains("foo"), is(true)); + assertThat(doc.contains("bar"), is(true)); + } } diff --git a/src/test/java/com/arangodb/example/document/InsertDocumentExample.java b/src/test/java/com/arangodb/example/document/InsertDocumentExample.java index de82bcb33..bfe57c96c 100644 --- a/src/test/java/com/arangodb/example/document/InsertDocumentExample.java +++ b/src/test/java/com/arangodb/example/document/InsertDocumentExample.java @@ -20,51 +20,49 @@ package com.arangodb.example.document; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.notNullValue; -import static org.junit.Assert.assertThat; - -import org.junit.Test; - import com.arangodb.entity.BaseDocument; import com.arangodb.entity.DocumentCreateEntity; import com.arangodb.example.ExampleBase; import com.arangodb.velocypack.VPackBuilder; import com.arangodb.velocypack.VPackSlice; import com.arangodb.velocypack.ValueType; +import org.junit.Test; + +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.junit.Assert.assertThat; /** * @author Mark Vollmary - * */ public class InsertDocumentExample extends ExampleBase { - @Test - public void insertBean() { - final DocumentCreateEntity doc = collection.insertDocument(new TestEntity("bar")); - assertThat(doc.getKey(), is(notNullValue())); - } + @Test + public void insertBean() { + final DocumentCreateEntity doc = collection.insertDocument(new TestEntity("bar")); + assertThat(doc.getKey(), is(notNullValue())); + } - @Test - public void insertBaseDocument() { - final BaseDocument value = new BaseDocument(); - value.addAttribute("foo", "bar"); - final DocumentCreateEntity doc = collection.insertDocument(value); - assertThat(doc.getKey(), is(notNullValue())); - } + @Test + public void insertBaseDocument() { + final BaseDocument value = new BaseDocument(); + value.addAttribute("foo", "bar"); + final DocumentCreateEntity doc = collection.insertDocument(value); + assertThat(doc.getKey(), is(notNullValue())); + } - @Test - public void insertVPack() { - final VPackBuilder builder = new VPackBuilder(); - builder.add(ValueType.OBJECT).add("foo", "bar").close(); - final DocumentCreateEntity doc = collection.insertDocument(builder.slice()); - assertThat(doc.getKey(), is(notNullValue())); - } + @Test + public void insertVPack() { + final VPackBuilder builder = new VPackBuilder(); + builder.add(ValueType.OBJECT).add("foo", "bar").close(); + final DocumentCreateEntity doc = collection.insertDocument(builder.slice()); + assertThat(doc.getKey(), is(notNullValue())); + } - @Test - public void insertJson() { - final DocumentCreateEntity doc = collection.insertDocument("{\"foo\":\"bar\"}"); - assertThat(doc.getKey(), is(notNullValue())); - } + @Test + public void insertJson() { + final DocumentCreateEntity doc = collection.insertDocument("{\"foo\":\"bar\"}"); + assertThat(doc.getKey(), is(notNullValue())); + } } diff --git a/src/test/java/com/arangodb/example/document/TestEntity.java b/src/test/java/com/arangodb/example/document/TestEntity.java index ee9bebaa3..a5c9aaf31 100644 --- a/src/test/java/com/arangodb/example/document/TestEntity.java +++ b/src/test/java/com/arangodb/example/document/TestEntity.java @@ -22,28 +22,27 @@ /** * @author Mark Vollmary - * */ @SuppressWarnings({"WeakerAccess", "unused"}) public class TestEntity { - private String foo; + private String foo; - public TestEntity() { - super(); - } + public TestEntity() { + super(); + } - public TestEntity(final String foo) { - super(); - this.foo = foo; - } + public TestEntity(final String foo) { + super(); + this.foo = foo; + } - public String getFoo() { - return foo; - } + public String getFoo() { + return foo; + } - public void setFoo(final String foo) { - this.foo = foo; - } + public void setFoo(final String foo) { + this.foo = foo; + } } diff --git a/src/test/java/com/arangodb/example/graph/AQLActorsAndMoviesExample.java b/src/test/java/com/arangodb/example/graph/AQLActorsAndMoviesExample.java index e6ec12a9e..c8d4cca54 100644 --- a/src/test/java/com/arangodb/example/graph/AQLActorsAndMoviesExample.java +++ b/src/test/java/com/arangodb/example/graph/AQLActorsAndMoviesExample.java @@ -20,13 +20,6 @@ package com.arangodb.example.graph; -import static org.hamcrest.Matchers.hasItems; -import static org.junit.Assert.assertThat; - -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; - import com.arangodb.ArangoCollection; import com.arangodb.ArangoCursor; import com.arangodb.ArangoDB; @@ -36,6 +29,12 @@ import com.arangodb.entity.CollectionType; import com.arangodb.entity.DocumentCreateEntity; import com.arangodb.model.CollectionCreateOptions; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; + +import static org.hamcrest.Matchers.hasItems; +import static org.junit.Assert.assertThat; /** * @author Mark Vollmary diff --git a/src/test/java/com/arangodb/example/graph/BaseGraphTest.java b/src/test/java/com/arangodb/example/graph/BaseGraphTest.java index 802075f30..ff25732c8 100644 --- a/src/test/java/com/arangodb/example/graph/BaseGraphTest.java +++ b/src/test/java/com/arangodb/example/graph/BaseGraphTest.java @@ -20,17 +20,16 @@ package com.arangodb.example.graph; -import java.util.ArrayList; -import java.util.Collection; - -import org.junit.AfterClass; -import org.junit.BeforeClass; - import com.arangodb.ArangoDB; import com.arangodb.ArangoDBException; import com.arangodb.ArangoDatabase; import com.arangodb.entity.EdgeDefinition; import com.arangodb.entity.VertexEntity; +import org.junit.AfterClass; +import org.junit.BeforeClass; + +import java.util.ArrayList; +import java.util.Collection; /** * @author Mark Vollmary diff --git a/src/test/java/com/arangodb/example/graph/Circle.java b/src/test/java/com/arangodb/example/graph/Circle.java index 6a988b000..88d992a60 100644 --- a/src/test/java/com/arangodb/example/graph/Circle.java +++ b/src/test/java/com/arangodb/example/graph/Circle.java @@ -25,57 +25,56 @@ /** * @author a-brandt - * */ @SuppressWarnings("unused") class Circle { - @DocumentField(Type.ID) - private String id; + @DocumentField(Type.ID) + private String id; - @DocumentField(Type.KEY) - private String key; + @DocumentField(Type.KEY) + private String key; - @DocumentField(Type.REV) - private String revision; + @DocumentField(Type.REV) + private String revision; - private String label; + private String label; - public Circle(String key, String label) { - this.key = key; - this.label = label; - } + public Circle(String key, String label) { + this.key = key; + this.label = label; + } - public String getId() { - return id; - } + public String getId() { + return id; + } - public void setId(String id) { - this.id = id; - } + public void setId(String id) { + this.id = id; + } - public String getKey() { - return key; - } + public String getKey() { + return key; + } - public void setKey(String key) { - this.key = key; - } + public void setKey(String key) { + this.key = key; + } - public String getRevision() { - return revision; - } + public String getRevision() { + return revision; + } - public void setRevision(String revision) { - this.revision = revision; - } + public void setRevision(String revision) { + this.revision = revision; + } - public String getLabel() { - return label; - } + public String getLabel() { + return label; + } - public void setLabel(String label) { - this.label = label; - } + public void setLabel(String label) { + this.label = label; + } } diff --git a/src/test/java/com/arangodb/example/graph/CircleEdge.java b/src/test/java/com/arangodb/example/graph/CircleEdge.java index bb8151abb..b5378dcdf 100644 --- a/src/test/java/com/arangodb/example/graph/CircleEdge.java +++ b/src/test/java/com/arangodb/example/graph/CircleEdge.java @@ -25,101 +25,100 @@ /** * @author a-brandt - * */ @SuppressWarnings("unused") class CircleEdge { - @DocumentField(Type.ID) - private String id; + @DocumentField(Type.ID) + private String id; - @DocumentField(Type.KEY) - private String key; + @DocumentField(Type.KEY) + private String key; - @DocumentField(Type.REV) - private String revision; + @DocumentField(Type.REV) + private String revision; - @DocumentField(Type.FROM) - private String from; + @DocumentField(Type.FROM) + private String from; - @DocumentField(Type.TO) - private String to; + @DocumentField(Type.TO) + private String to; - private Boolean theFalse; - private Boolean theTruth; - private String label; + 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 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; - } + public String getId() { + return id; + } - public void setId(String id) { - this.id = id; - } + public void setId(String id) { + this.id = id; + } - public String getKey() { - return key; - } + public String getKey() { + return key; + } - public void setKey(String key) { - this.key = key; - } + public void setKey(String key) { + this.key = key; + } - public String getRevision() { - return revision; - } + public String getRevision() { + return revision; + } - public void setRevision(String revision) { - this.revision = revision; - } + public void setRevision(String revision) { + this.revision = revision; + } - public String getFrom() { - return from; - } + public String getFrom() { + return from; + } - public void setFrom(String from) { - this.from = from; - } + public void setFrom(String from) { + this.from = from; + } - public String getTo() { - return to; - } + public String getTo() { + return to; + } - public void setTo(String to) { - this.to = to; - } + public void setTo(String to) { + this.to = to; + } - public Boolean getTheFalse() { - return theFalse; - } + public Boolean getTheFalse() { + return theFalse; + } - public void setTheFalse(Boolean theFalse) { - this.theFalse = theFalse; - } + public void setTheFalse(Boolean theFalse) { + this.theFalse = theFalse; + } - public Boolean getTheTruth() { - return theTruth; - } + public Boolean getTheTruth() { + return theTruth; + } - public void setTheTruth(Boolean theTruth) { - this.theTruth = theTruth; - } + public void setTheTruth(Boolean theTruth) { + this.theTruth = theTruth; + } - public String getLabel() { - return label; - } + public String getLabel() { + return label; + } - public void setLabel(String label) { - this.label = label; - } + public void setLabel(String label) { + this.label = label; + } } diff --git a/src/test/java/com/arangodb/example/graph/GraphTraversalsInAQLExample.java b/src/test/java/com/arangodb/example/graph/GraphTraversalsInAQLExample.java index d8f896542..57de9115f 100644 --- a/src/test/java/com/arangodb/example/graph/GraphTraversalsInAQLExample.java +++ b/src/test/java/com/arangodb/example/graph/GraphTraversalsInAQLExample.java @@ -20,103 +20,100 @@ package com.arangodb.example.graph; -import static org.hamcrest.Matchers.hasItems; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; +import com.arangodb.ArangoCursor; +import com.arangodb.ArangoDBException; +import org.junit.Test; import java.util.Collection; -import org.junit.Test; - -import com.arangodb.ArangoCursor; -import com.arangodb.ArangoDBException; +import static org.hamcrest.Matchers.hasItems; +import static org.hamcrest.Matchers.is; +import static org.junit.Assert.assertThat; /** * Graph traversals in AQL - * - * @see Graph traversals in AQL - * - * @author a-brandt * + * @author a-brandt + * @see Graph traversals in AQL */ public class GraphTraversalsInAQLExample extends BaseGraphTest { - @Test - public void queryAllVertices() throws ArangoDBException { - String queryString = "FOR v IN 1..3 OUTBOUND 'circles/A' GRAPH 'traversalGraph' RETURN v._key"; - ArangoCursor cursor = db.query(queryString, null, null, String.class); - Collection result = cursor.asListRemaining(); - assertThat(result.size(), is(10)); - - queryString = "WITH circles FOR v IN 1..3 OUTBOUND 'circles/A' edges RETURN v._key"; - cursor = db.query(queryString, null, null, String.class); - result = cursor.asListRemaining(); - assertThat(result.size(), is(10)); - } - - @Test - public void queryDepthTwo() throws ArangoDBException { - String queryString = "FOR v IN 2..2 OUTBOUND 'circles/A' GRAPH 'traversalGraph' return v._key"; - ArangoCursor cursor = db.query(queryString, null, null, String.class); - Collection result = cursor.asListRemaining(); - assertThat(result.size(), is(4)); - assertThat(result, hasItems("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); - result = cursor.asListRemaining(); - assertThat(result.size(), is(4)); - assertThat(result, hasItems("C", "E", "H", "J")); - } - - @Test - public void queryWithFilter() throws ArangoDBException { - String queryString = "FOR v, e, p IN 1..3 OUTBOUND 'circles/A' GRAPH 'traversalGraph' FILTER p.vertices[1]._key != 'G' RETURN v._key"; - ArangoCursor cursor = db.query(queryString, null, null, String.class); - Collection result = cursor.asListRemaining(); - assertThat(result.size(), is(5)); - assertThat(result, hasItems("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); - result = cursor.asListRemaining(); - assertThat(result.size(), is(5)); - assertThat(result, hasItems("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); - - result = cursor.asListRemaining(); - assertThat(result.size(), is(3)); - assertThat(result, hasItems("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); - result = cursor.asListRemaining(); - assertThat(result.size(), is(3)); - assertThat(result, hasItems("B", "C", "D")); - } - - @Test - public void queryOutboundInbound() throws ArangoDBException { - String queryString = "FOR v IN 1..3 OUTBOUND 'circles/E' GRAPH 'traversalGraph' return v._key"; - ArangoCursor cursor = db.query(queryString, null, null, String.class); - Collection result = cursor.asListRemaining(); - assertThat(result.size(), is(1)); - assertThat(result, hasItems("F")); - - queryString = "FOR v IN 1..3 INBOUND 'circles/E' GRAPH 'traversalGraph' return v._key"; - cursor = db.query(queryString, null, null, String.class); - result = cursor.asListRemaining(); - assertThat(result.size(), is(2)); - assertThat(result, hasItems("B", "A")); - - queryString = "FOR v IN 1..3 ANY 'circles/E' GRAPH 'traversalGraph' return v._key"; - cursor = db.query(queryString, null, null, String.class); - - result = cursor.asListRemaining(); - assertThat(result.size(), is(6)); - assertThat(result, hasItems("F", "B", "C", "D", "A", "G")); - } + @Test + public void queryAllVertices() throws ArangoDBException { + String queryString = "FOR v IN 1..3 OUTBOUND 'circles/A' GRAPH 'traversalGraph' RETURN v._key"; + ArangoCursor cursor = db.query(queryString, null, null, String.class); + Collection result = cursor.asListRemaining(); + assertThat(result.size(), is(10)); + + queryString = "WITH circles FOR v IN 1..3 OUTBOUND 'circles/A' edges RETURN v._key"; + cursor = db.query(queryString, null, null, String.class); + result = cursor.asListRemaining(); + assertThat(result.size(), is(10)); + } + + @Test + public void queryDepthTwo() throws ArangoDBException { + String queryString = "FOR v IN 2..2 OUTBOUND 'circles/A' GRAPH 'traversalGraph' return v._key"; + ArangoCursor cursor = db.query(queryString, null, null, String.class); + Collection result = cursor.asListRemaining(); + assertThat(result.size(), is(4)); + assertThat(result, hasItems("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); + result = cursor.asListRemaining(); + assertThat(result.size(), is(4)); + assertThat(result, hasItems("C", "E", "H", "J")); + } + + @Test + public void queryWithFilter() throws ArangoDBException { + String queryString = "FOR v, e, p IN 1..3 OUTBOUND 'circles/A' GRAPH 'traversalGraph' FILTER p.vertices[1]._key != 'G' RETURN v._key"; + ArangoCursor cursor = db.query(queryString, null, null, String.class); + Collection result = cursor.asListRemaining(); + assertThat(result.size(), is(5)); + assertThat(result, hasItems("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); + result = cursor.asListRemaining(); + assertThat(result.size(), is(5)); + assertThat(result, hasItems("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); + + result = cursor.asListRemaining(); + assertThat(result.size(), is(3)); + assertThat(result, hasItems("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); + result = cursor.asListRemaining(); + assertThat(result.size(), is(3)); + assertThat(result, hasItems("B", "C", "D")); + } + + @Test + public void queryOutboundInbound() throws ArangoDBException { + String queryString = "FOR v IN 1..3 OUTBOUND 'circles/E' GRAPH 'traversalGraph' return v._key"; + ArangoCursor cursor = db.query(queryString, null, null, String.class); + Collection result = cursor.asListRemaining(); + assertThat(result.size(), is(1)); + assertThat(result, hasItems("F")); + + queryString = "FOR v IN 1..3 INBOUND 'circles/E' GRAPH 'traversalGraph' return v._key"; + cursor = db.query(queryString, null, null, String.class); + result = cursor.asListRemaining(); + assertThat(result.size(), is(2)); + assertThat(result, hasItems("B", "A")); + + queryString = "FOR v IN 1..3 ANY 'circles/E' GRAPH 'traversalGraph' return v._key"; + cursor = db.query(queryString, null, null, String.class); + + result = cursor.asListRemaining(); + assertThat(result.size(), is(6)); + assertThat(result, hasItems("F", "B", "C", "D", "A", "G")); + } } diff --git a/src/test/java/com/arangodb/example/graph/ShortestPathInAQLExample.java b/src/test/java/com/arangodb/example/graph/ShortestPathInAQLExample.java index 6c60674c3..a0f641643 100644 --- a/src/test/java/com/arangodb/example/graph/ShortestPathInAQLExample.java +++ b/src/test/java/com/arangodb/example/graph/ShortestPathInAQLExample.java @@ -20,88 +20,85 @@ package com.arangodb.example.graph; -import static org.hamcrest.Matchers.hasItems; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; +import com.arangodb.ArangoCursor; +import com.arangodb.ArangoDBException; +import org.junit.Test; import java.util.ArrayList; import java.util.Collection; import java.util.List; -import org.junit.Test; - -import com.arangodb.ArangoCursor; -import com.arangodb.ArangoDBException; +import static org.hamcrest.Matchers.hasItems; +import static org.hamcrest.Matchers.is; +import static org.junit.Assert.assertThat; /** * Shortest Path in AQL - * - * @see Shortest Path in AQL - * - * @author a-brandt * + * @author a-brandt + * @see Shortest Path in AQL */ public class ShortestPathInAQLExample extends BaseGraphTest { - @SuppressWarnings({"WeakerAccess", "unused"}) - public static class Pair { - - private String vertex; - private String edge; - - public String getVertex() { - return vertex; - } - - public void setVertex(final String vertex) { - this.vertex = vertex; - } - - public String getEdge() { - return edge; - } - - public void setEdge(final String edge) { - this.edge = edge; - } - - } - - @Test - public void queryShortestPathFromAToD() throws ArangoDBException { - String queryString = "FOR v, e IN OUTBOUND SHORTEST_PATH 'circles/A' TO 'circles/D' GRAPH 'traversalGraph' RETURN {'vertex': v._key, 'edge': e._key}"; - ArangoCursor cursor = db.query(queryString, null, null, Pair.class); - final Collection collection = toVertexCollection(cursor); - assertThat(collection.size(), is(4)); - assertThat(collection, hasItems("A", "B", "C", "D")); - - queryString = "WITH circles FOR v, e IN OUTBOUND SHORTEST_PATH 'circles/A' TO 'circles/D' edges RETURN {'vertex': v._key, 'edge': e._key}"; - db.query(queryString, null, null, Pair.class); - assertThat(collection.size(), is(4)); - assertThat(collection, hasItems("A", "B", "C", "D")); - } - - @Test - public void queryShortestPathByFilter() throws ArangoDBException { - 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}"; - ArangoCursor cursor = db.query(queryString, null, null, Pair.class); - final Collection collection = toVertexCollection(cursor); - assertThat(collection.size(), is(4)); - assertThat(collection, hasItems("A", "B", "C", "D")); - - queryString = "FOR a IN circles FILTER a._key == 'A' FOR d IN circles FILTER d._key == 'D' FOR v, e IN OUTBOUND SHORTEST_PATH a TO d edges RETURN {'vertex': v._key, 'edge': e._key}"; - db.query(queryString, null, null, Pair.class); - assertThat(collection.size(), is(4)); - assertThat(collection, hasItems("A", "B", "C", "D")); - } - - private Collection toVertexCollection(final ArangoCursor cursor) { - final List result = new ArrayList<>(); - for (; cursor.hasNext();) { - final Pair pair = cursor.next(); - result.add(pair.getVertex()); - } - return result; - } + @SuppressWarnings({"WeakerAccess", "unused"}) + public static class Pair { + + private String vertex; + private String edge; + + public String getVertex() { + return vertex; + } + + public void setVertex(final String vertex) { + this.vertex = vertex; + } + + public String getEdge() { + return edge; + } + + public void setEdge(final String edge) { + this.edge = edge; + } + + } + + @Test + public void queryShortestPathFromAToD() throws ArangoDBException { + String queryString = "FOR v, e IN OUTBOUND SHORTEST_PATH 'circles/A' TO 'circles/D' GRAPH 'traversalGraph' RETURN {'vertex': v._key, 'edge': e._key}"; + ArangoCursor cursor = db.query(queryString, null, null, Pair.class); + final Collection collection = toVertexCollection(cursor); + assertThat(collection.size(), is(4)); + assertThat(collection, hasItems("A", "B", "C", "D")); + + queryString = "WITH circles FOR v, e IN OUTBOUND SHORTEST_PATH 'circles/A' TO 'circles/D' edges RETURN {'vertex': v._key, 'edge': e._key}"; + db.query(queryString, null, null, Pair.class); + assertThat(collection.size(), is(4)); + assertThat(collection, hasItems("A", "B", "C", "D")); + } + + @Test + public void queryShortestPathByFilter() throws ArangoDBException { + 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}"; + ArangoCursor cursor = db.query(queryString, null, null, Pair.class); + final Collection collection = toVertexCollection(cursor); + assertThat(collection.size(), is(4)); + assertThat(collection, hasItems("A", "B", "C", "D")); + + queryString = "FOR a IN circles FILTER a._key == 'A' FOR d IN circles FILTER d._key == 'D' FOR v, e IN OUTBOUND SHORTEST_PATH a TO d edges RETURN {'vertex': v._key, 'edge': e._key}"; + db.query(queryString, null, null, Pair.class); + assertThat(collection.size(), is(4)); + assertThat(collection, hasItems("A", "B", "C", "D")); + } + + private Collection toVertexCollection(final ArangoCursor cursor) { + final List result = new ArrayList<>(); + for (; cursor.hasNext(); ) { + final Pair pair = cursor.next(); + result.add(pair.getVertex()); + } + return result; + } } diff --git a/src/test/java/com/arangodb/example/ssl/SslExample.java b/src/test/java/com/arangodb/example/ssl/SslExample.java index 84bcc0b8c..9d4d3c0de 100644 --- a/src/test/java/com/arangodb/example/ssl/SslExample.java +++ b/src/test/java/com/arangodb/example/ssl/SslExample.java @@ -53,7 +53,7 @@ public class SslExample { private static final String SSL_TRUSTSTORE_PASSWORD = "12345678"; @Test - @Ignore + @Ignore public void connect() throws Exception { final KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(this.getClass().getResourceAsStream(SSL_TRUSTSTORE), SSL_TRUSTSTORE_PASSWORD.toCharArray()); @@ -72,7 +72,7 @@ public void connect() throws Exception { .host("127.0.0.1", 8529) .password("test") .useSsl(true) - .sslContext(sc) + .sslContext(sc) .useProtocol(Protocol.HTTP_JSON) .build(); final ArangoDBVersion version = arangoDB.getVersion(); diff --git a/src/test/java/com/arangodb/example/velocypack/VPackExample.java b/src/test/java/com/arangodb/example/velocypack/VPackExample.java index b01d711b3..cf8273991 100644 --- a/src/test/java/com/arangodb/example/velocypack/VPackExample.java +++ b/src/test/java/com/arangodb/example/velocypack/VPackExample.java @@ -20,96 +20,94 @@ package com.arangodb.example.velocypack; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; - -import java.util.Iterator; -import java.util.Map.Entry; - -import org.junit.Test; - import com.arangodb.velocypack.VPackBuilder; import com.arangodb.velocypack.VPackSlice; import com.arangodb.velocypack.ValueType; import com.arangodb.velocypack.exception.VPackException; +import org.junit.Test; + +import java.util.Iterator; +import java.util.Map.Entry; + +import static org.hamcrest.Matchers.is; +import static org.junit.Assert.assertThat; /** * @author Mark Vollmary - * */ public class VPackExample { - @Test - public void buildObject() throws VPackException { - final VPackBuilder builder = new VPackBuilder(); - builder.add(ValueType.OBJECT);// object start - builder.add("foo", 1); // add field "foo" with value 1 - builder.add("bar", 2); // add field "bar" with value 2 - builder.close();// object end - - final VPackSlice slice = builder.slice(); // create slice - assertThat(slice.isObject(), is(true)); - assertThat(slice.size(), is(2)); // number of fields - - final VPackSlice foo = slice.get("foo"); // get field "foo" - assertThat(foo.isInteger(), is(true)); - assertThat(foo.getAsInt(), is(1)); - - final VPackSlice bar = slice.get("bar"); // get field "bar" - assertThat(bar.isInteger(), is(true)); - assertThat(bar.getAsInt(), is(2)); - - // iterate over the fields - for (final Iterator> iterator = slice.objectIterator(); iterator.hasNext();) { - final Entry field = iterator.next(); - assertThat(field.getValue().isInteger(), is(true)); - } - } - - @Test - public void buildArray() throws VPackException { - final VPackBuilder builder = new VPackBuilder(); - builder.add(ValueType.ARRAY); // array start - builder.add(1);// add value 1 - builder.add(2);// add value 2 - builder.add(3);// add value 3 - builder.close(); // array end - - final VPackSlice slice = builder.slice();// create slice - assertThat(slice.isArray(), is(true)); - assertThat(slice.size(), is(3));// number of values - - // iterate over values - for (int i = 0; i < slice.size(); i++) { - final VPackSlice value = slice.get(i); - assertThat(value.isInteger(), is(true)); - assertThat(value.getAsInt(), is(i + 1)); - } - - // iterate over values with Iterator - for (final Iterator iterator = slice.arrayIterator(); iterator.hasNext();) { - final VPackSlice value = iterator.next(); - assertThat(value.isInteger(), is(true)); - } - } - - @Test - public void buildObjectInObject() throws VPackException { - final VPackBuilder builder = new VPackBuilder(); - builder.add(ValueType.OBJECT);// object start - builder.add("foo", ValueType.OBJECT); // add object in field "foo" - builder.add("bar", 2); // add field "bar" with value 2 to object "foo" - builder.close();// object "foo" end - builder.close();// object end - - final VPackSlice slice = builder.slice(); // create slice - assertThat(slice.isObject(), is(true)); - - final VPackSlice foo = slice.get("foo"); - assertThat(foo.isObject(), is(true)); - - final VPackSlice bar = foo.get("bar"); // get field "bar" from "foo" - assertThat(bar.isInteger(), is(true)); - } + @Test + public void buildObject() throws VPackException { + final VPackBuilder builder = new VPackBuilder(); + builder.add(ValueType.OBJECT);// object start + builder.add("foo", 1); // add field "foo" with value 1 + builder.add("bar", 2); // add field "bar" with value 2 + builder.close();// object end + + final VPackSlice slice = builder.slice(); // create slice + assertThat(slice.isObject(), is(true)); + assertThat(slice.size(), is(2)); // number of fields + + final VPackSlice foo = slice.get("foo"); // get field "foo" + assertThat(foo.isInteger(), is(true)); + assertThat(foo.getAsInt(), is(1)); + + final VPackSlice bar = slice.get("bar"); // get field "bar" + assertThat(bar.isInteger(), is(true)); + assertThat(bar.getAsInt(), is(2)); + + // iterate over the fields + for (final Iterator> iterator = slice.objectIterator(); iterator.hasNext(); ) { + final Entry field = iterator.next(); + assertThat(field.getValue().isInteger(), is(true)); + } + } + + @Test + public void buildArray() throws VPackException { + final VPackBuilder builder = new VPackBuilder(); + builder.add(ValueType.ARRAY); // array start + builder.add(1);// add value 1 + builder.add(2);// add value 2 + builder.add(3);// add value 3 + builder.close(); // array end + + final VPackSlice slice = builder.slice();// create slice + assertThat(slice.isArray(), is(true)); + assertThat(slice.size(), is(3));// number of values + + // iterate over values + for (int i = 0; i < slice.size(); i++) { + final VPackSlice value = slice.get(i); + assertThat(value.isInteger(), is(true)); + assertThat(value.getAsInt(), is(i + 1)); + } + + // iterate over values with Iterator + for (final Iterator iterator = slice.arrayIterator(); iterator.hasNext(); ) { + final VPackSlice value = iterator.next(); + assertThat(value.isInteger(), is(true)); + } + } + + @Test + public void buildObjectInObject() throws VPackException { + final VPackBuilder builder = new VPackBuilder(); + builder.add(ValueType.OBJECT);// object start + builder.add("foo", ValueType.OBJECT); // add object in field "foo" + builder.add("bar", 2); // add field "bar" with value 2 to object "foo" + builder.close();// object "foo" end + builder.close();// object end + + final VPackSlice slice = builder.slice(); // create slice + assertThat(slice.isObject(), is(true)); + + final VPackSlice foo = slice.get("foo"); + assertThat(foo.isObject(), is(true)); + + final VPackSlice bar = foo.get("bar"); // get field "bar" from "foo" + assertThat(bar.isInteger(), is(true)); + } } diff --git a/src/test/java/com/arangodb/internal/DocumentCacheTest.java b/src/test/java/com/arangodb/internal/DocumentCacheTest.java index 18f981b94..76e3c26bf 100644 --- a/src/test/java/com/arangodb/internal/DocumentCacheTest.java +++ b/src/test/java/com/arangodb/internal/DocumentCacheTest.java @@ -20,55 +20,53 @@ package com.arangodb.internal; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertThat; +import com.arangodb.entity.BaseDocument; +import com.arangodb.entity.DocumentField.Type; +import org.junit.Test; import java.util.HashMap; import java.util.Map; -import org.junit.Test; - -import com.arangodb.entity.BaseDocument; -import com.arangodb.entity.DocumentField.Type; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.nullValue; +import static org.junit.Assert.assertThat; /** * @author Mark Vollmary - * */ public class DocumentCacheTest { - @Test - public void setValues() { - final DocumentCache cache = new DocumentCache(); - final BaseDocument doc = new BaseDocument(); + @Test + public void setValues() { + final DocumentCache cache = new DocumentCache(); + final BaseDocument doc = new BaseDocument(); - assertThat(doc.getId(), is(nullValue())); - assertThat(doc.getKey(), is(nullValue())); - assertThat(doc.getRevision(), is(nullValue())); + assertThat(doc.getId(), is(nullValue())); + assertThat(doc.getKey(), is(nullValue())); + assertThat(doc.getRevision(), is(nullValue())); - final Map values = new HashMap<>(); - values.put(Type.ID, "testId"); - values.put(Type.KEY, "testKey"); - values.put(Type.REV, "testRev"); - cache.setValues(doc, values); + final Map values = new HashMap<>(); + values.put(Type.ID, "testId"); + values.put(Type.KEY, "testKey"); + values.put(Type.REV, "testRev"); + cache.setValues(doc, values); - assertThat(doc.getId(), is("testId")); - assertThat(doc.getKey(), is("testKey")); - assertThat(doc.getRevision(), is("testRev")); - } + assertThat(doc.getId(), is("testId")); + assertThat(doc.getKey(), is("testKey")); + assertThat(doc.getRevision(), is("testRev")); + } - @Test - public void setValuesMap() { - final DocumentCache cache = new DocumentCache(); - final Map map = new HashMap<>(); + @Test + public void setValuesMap() { + final DocumentCache cache = new DocumentCache(); + final Map map = new HashMap<>(); - final Map values = new HashMap<>(); - values.put(Type.ID, "testId"); - values.put(Type.KEY, "testKey"); - values.put(Type.REV, "testRev"); - cache.setValues(map, values); + final Map values = new HashMap<>(); + values.put(Type.ID, "testId"); + values.put(Type.KEY, "testKey"); + values.put(Type.REV, "testRev"); + cache.setValues(map, values); - assertThat(map.isEmpty(), is(true)); - } + assertThat(map.isEmpty(), is(true)); + } } diff --git a/src/test/java/com/arangodb/internal/velocystream/CommunicationTest.java b/src/test/java/com/arangodb/internal/velocystream/CommunicationTest.java index 238ebdea6..b29c0e62a 100644 --- a/src/test/java/com/arangodb/internal/velocystream/CommunicationTest.java +++ b/src/test/java/com/arangodb/internal/velocystream/CommunicationTest.java @@ -20,19 +20,18 @@ package com.arangodb.internal.velocystream; -import static org.hamcrest.CoreMatchers.notNullValue; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; +import com.arangodb.ArangoDB; +import com.arangodb.ArangoDatabase; +import com.arangodb.entity.ArangoDBVersion; +import org.junit.Test; import java.util.Collection; import java.util.Iterator; import java.util.concurrent.ConcurrentLinkedQueue; -import org.junit.Test; - -import com.arangodb.ArangoDB; -import com.arangodb.ArangoDatabase; -import com.arangodb.entity.ArangoDBVersion; +import static org.hamcrest.CoreMatchers.notNullValue; +import static org.hamcrest.Matchers.is; +import static org.junit.Assert.assertThat; /** * @author Mark Vollmary @@ -112,12 +111,12 @@ public void multiThreadMultiDatabases() throws Exception { final Collection result = new ConcurrentLinkedQueue<>(); final Thread t1 = new Thread(() -> { - db1.query("return sleep(1)", null, null, null); - result.add("1"); + db1.query("return sleep(1)", null, null, null); + result.add("1"); }); final Thread t2 = new Thread(() -> { - db2.query("return sleep(1)", null, null, null); - result.add("1"); + db2.query("return sleep(1)", null, null, null); + result.add("1"); }); t2.start(); t1.start(); diff --git a/src/test/java/com/arangodb/util/ArangoSerializationTest.java b/src/test/java/com/arangodb/util/ArangoSerializationTest.java index c624bb7d8..3c528e84a 100644 --- a/src/test/java/com/arangodb/util/ArangoSerializationTest.java +++ b/src/test/java/com/arangodb/util/ArangoSerializationTest.java @@ -20,88 +20,86 @@ package com.arangodb.util; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; - -import org.junit.BeforeClass; -import org.junit.Test; - import com.arangodb.ArangoDB; import com.arangodb.entity.BaseDocument; import com.arangodb.velocypack.Type; import com.arangodb.velocypack.VPackBuilder; import com.arangodb.velocypack.VPackSlice; import com.arangodb.velocypack.ValueType; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; + +import static org.hamcrest.Matchers.is; +import static org.junit.Assert.assertThat; /** * @author Mark Vollmary - * */ public class ArangoSerializationTest { - private static ArangoSerialization util; + private static ArangoSerialization util; - @BeforeClass - public static void setup() { - final ArangoDB arangoDB = new ArangoDB.Builder().build(); - util = arangoDB.util(); - } + @BeforeClass + public static void setup() { + final ArangoDB arangoDB = new ArangoDB.Builder().build(); + util = arangoDB.util(); + } - @Test - public void deseriarlize() { - final VPackBuilder builder = new VPackBuilder().add(ValueType.OBJECT).add("foo", "bar").close(); - final BaseDocument doc = util.deserialize(builder.slice(), BaseDocument.class); - assertThat(doc.getAttribute("foo").toString(), is("bar")); - } + @Test + public void deseriarlize() { + final VPackBuilder builder = new VPackBuilder().add(ValueType.OBJECT).add("foo", "bar").close(); + final BaseDocument doc = util.deserialize(builder.slice(), BaseDocument.class); + assertThat(doc.getAttribute("foo").toString(), is("bar")); + } - @Test - public void serialize() { - final BaseDocument entity = new BaseDocument(); - entity.addAttribute("foo", "bar"); - final VPackSlice vpack = util.serialize(entity); - assertThat(vpack.get("foo").isString(), is(true)); - assertThat(vpack.get("foo").getAsString(), is("bar")); - } + @Test + public void serialize() { + final BaseDocument entity = new BaseDocument(); + entity.addAttribute("foo", "bar"); + final VPackSlice vpack = util.serialize(entity); + assertThat(vpack.get("foo").isString(), is(true)); + assertThat(vpack.get("foo").getAsString(), is("bar")); + } - @Test - public void serializeNullValues() { - final BaseDocument entity = new BaseDocument(); - entity.addAttribute("foo", null); - final VPackSlice vpack = util.serialize(entity, new ArangoSerializer.Options().serializeNullValues(true)); - assertThat(vpack.get("foo").isNull(), is(true)); - } + @Test + public void serializeNullValues() { + final BaseDocument entity = new BaseDocument(); + entity.addAttribute("foo", null); + final VPackSlice vpack = util.serialize(entity, new ArangoSerializer.Options().serializeNullValues(true)); + assertThat(vpack.get("foo").isNull(), is(true)); + } - @Test - public void skipSerializeNullValues() { - final BaseDocument entity = new BaseDocument(); - entity.addAttribute("bar", null); - final VPackSlice vpack = util.serialize(entity); - assertThat(vpack.get("bar").isNone(), is(true)); - } + @Test + public void skipSerializeNullValues() { + final BaseDocument entity = new BaseDocument(); + entity.addAttribute("bar", null); + final VPackSlice vpack = util.serialize(entity); + assertThat(vpack.get("bar").isNone(), is(true)); + } - @Test - public void serializeType() { - final Collection list = new ArrayList<>(); - list.add(new BaseDocument()); - list.add(new BaseDocument()); + @Test + public void serializeType() { + final Collection list = new ArrayList<>(); + list.add(new BaseDocument()); + list.add(new BaseDocument()); - final VPackSlice vpack = util.serialize(list, - new ArangoSerializer.Options().type(new Type>() { - }.getType())); - assertThat(vpack.isArray(), is(true)); - assertThat(vpack.getLength(), is(list.size())); - } + final VPackSlice vpack = util.serialize(list, + new ArangoSerializer.Options().type(new Type>() { + }.getType())); + assertThat(vpack.isArray(), is(true)); + assertThat(vpack.getLength(), is(list.size())); + } - @Test - public void parseJsonIncludeNull() { - final Map entity = new HashMap<>(); - entity.put("value", new String[] { "test", null }); - final String json = util.deserialize(util.serialize(entity, new ArangoSerializer.Options()), String.class); - assertThat(json, is("{\"value\":[\"test\",null]}")); - } + @Test + public void parseJsonIncludeNull() { + final Map entity = new HashMap<>(); + entity.put("value", new String[]{"test", null}); + final String json = util.deserialize(util.serialize(entity, new ArangoSerializer.Options()), String.class); + assertThat(json, is("{\"value\":[\"test\",null]}")); + } } diff --git a/src/test/java/com/arangodb/util/MapBuilderTest.java b/src/test/java/com/arangodb/util/MapBuilderTest.java index 246202f12..5a3465dbf 100644 --- a/src/test/java/com/arangodb/util/MapBuilderTest.java +++ b/src/test/java/com/arangodb/util/MapBuilderTest.java @@ -20,25 +20,24 @@ package com.arangodb.util; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.notNullValue; -import static org.junit.Assert.assertThat; +import org.junit.Test; import java.util.Map; -import org.junit.Test; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.junit.Assert.assertThat; /** * @author Mark Vollmary - * */ public class MapBuilderTest { - @Test - public void build() { - final Map map = new MapBuilder().put("foo", "bar").get(); - assertThat(map.size(), is(1)); - assertThat(map.get("foo"), is(notNullValue())); - assertThat(map.get("foo").toString(), is("bar")); - } + @Test + public void build() { + final Map map = new MapBuilder().put("foo", "bar").get(); + assertThat(map.size(), is(1)); + assertThat(map.get("foo"), is(notNullValue())); + assertThat(map.get("foo").toString(), is("bar")); + } } diff --git a/src/test/resources/logback-test.xml b/src/test/resources/logback-test.xml index 645d34624..c89126ca5 100644 --- a/src/test/resources/logback-test.xml +++ b/src/test/resources/logback-test.xml @@ -1,14 +1,14 @@ - - - - %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - + + + + %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + - - - + + + diff --git a/tests/travis/setup_arangodb.sh b/tests/travis/setup_arangodb.sh index 01a736e57..5613ad035 100755 --- a/tests/travis/setup_arangodb.sh +++ b/tests/travis/setup_arangodb.sh @@ -1,6 +1,6 @@ #!/bin/bash -DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" +DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" cd $DIR VERSION=devel @@ -27,14 +27,14 @@ mkdir ${TMP_DIR} echo "Starting ArangoDB '${ARANGOD}'" ${ARANGOD} \ - --database.directory ${TMP_DIR} \ - --configuration none \ - --server.endpoint tcp://127.0.0.1:8529 \ - --server.endpoint ssl://127.0.0.1:8530 \ - --ssl.keyfile ./server.pem \ - --javascript.app-path ${ARANGODB_DIR}/js/apps \ - --javascript.startup-directory ${ARANGODB_DIR}/js \ - --server.authentication=true & + --database.directory ${TMP_DIR} \ + --configuration none \ + --server.endpoint tcp://127.0.0.1:8529 \ + --server.endpoint ssl://127.0.0.1:8530 \ + --ssl.keyfile ./server.pem \ + --javascript.app-path ${ARANGODB_DIR}/js/apps \ + --javascript.startup-directory ${ARANGODB_DIR}/js \ + --server.authentication=true & sleep 2 @@ -48,7 +48,7 @@ if [ "x$process" == "x" ]; then fi echo "Waiting until ArangoDB is ready on port 8529" -while [[ -z `curl -uroot: -s 'http://127.0.0.1:8529/_api/version' ` ]] ; do +while [[ -z $(curl -uroot: -s 'http://127.0.0.1:8529/_api/version') ]]; do echo -n "." sleep 2s done