diff --git a/.travis.yml b/.travis.yml index b43f50859..64249c6cf 100644 --- a/.travis.yml +++ b/.travis.yml @@ -7,7 +7,6 @@ before_script: install: mvn install -DskipTests=true -Dgpg.skip=true -Dmaven.javadoc.skip=true -B -V jdk: - - oraclejdk7 - oraclejdk8 sudo: false diff --git a/ChangeLog b/ChangeLog index 8f299418b..44adbc2b8 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,11 +1,18 @@ -v3.1.0 (2016-XX-XX) +v4.0.0 (2016-10-17) +--------------------------- +* replaced API +* replaced protocol http with VelocyStream +* added VelocyPack support +* added multi document operations (insert, delete, update, replace) + +v3.1.0 (2016-10-17) --------------------------- * removed Methods with collectionId (long) from ArangoDriver (Id is only for internal usage) * changed Revision from long to String * removed Methods with documentId (long) from ArangoDriver * added profile flag to AqlQueryOptions (issue #47) -v3.0.4 (2016-XX-XX) +v3.0.4 (2016-10-17) --------------------------- * fixed edges deserializer (issue #50) diff --git a/LICENSE b/LICENSE index 267b169b0..8dada3eda 100644 --- a/LICENSE +++ b/LICENSE @@ -1,4 +1,4 @@ -Apache License + Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ @@ -186,7 +186,7 @@ Apache License same "printed page" as the copyright notice for easier identification within third-party archives. - Copyright 2015 ArangoDB GmbH + Copyright {yyyy} {name of copyright owner} Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/README.md b/README.md index cab20aa8a..a8798a6b3 100644 --- a/README.md +++ b/README.md @@ -6,21 +6,18 @@ 2.7: [![Build Status](https://secure.travis-ci.org/arangodb/arangodb-java-driver.svg?branch=2.7)](https://travis-ci.org/arangodb/arangodb-java-driver) 3.0: [![Build Status](https://secure.travis-ci.org/arangodb/arangodb-java-driver.svg?branch=3.0)](https://travis-ci.org/arangodb/arangodb-java-driver) 3.1: [![Build Status](https://secure.travis-ci.org/arangodb/arangodb-java-driver.svg?branch=3.1)](https://travis-ci.org/arangodb/arangodb-java-driver) - +4.0: [![Build Status](https://secure.travis-ci.org/arangodb/arangodb-java-driver.svg?branch=4.0)](https://travis-ci.org/arangodb/arangodb-java-driver) master: [![Build Status](https://secure.travis-ci.org/arangodb/arangodb-java-driver.svg?branch=master)](https://travis-ci.org/arangodb/arangodb-java-driver) -This library is a Java driver for ArangoDB. - -Supported version: ArangoDB 3.1.X - -(Use ```arangodb-java-driver 2.7.4``` for ArangoDB 2.7.x and ArangoDB 2.8.x) +## Supported versions -# Required - -* [ArangoDB](https://github.com/arangodb/arangodb) version 3.1.X -* Java 1.6 later - -# Basics + + + + + + +
arangodb-java-driverArangoDBnetwork protocolJava version
4.0.x3.1.xVelocyStream1.6+
3.1.x3.1.xHTTP1.6+
3.0.x3.0.xHTTP1.6+
2.7.42.7.x and 2.8.xHTTP1.6+
## Maven @@ -33,25 +30,13 @@ ArangoDB 3.1.X com.arangodb arangodb-java-driver - 3.0.0 - - .... - -``` - -ArangoDB 2.7.x and ArangoDB 2.8.x: -```XML - - - com.arangodb - arangodb-java-driver - 2.7.4 + 4.0.0 .... ``` -If you want to test with a snapshot version (e.g. 3.1.0-SNAPSHOT), add the staging repository of oss.sonatype.org to your pom.xml: +If you want to test with a snapshot version (e.g. 4.0.0-SNAPSHOT), add the staging repository of oss.sonatype.org to your pom.xml: ```XML @@ -62,332 +47,16 @@ If you want to test with a snapshot version (e.g. 3.1.0-SNAPSHOT), add the stagi ``` +## Compile java driver -## Driver Setup - -Setup with default configuration: - -``` Java - // Initialize configure - ArangoConfigure configure = new ArangoConfigure(); - configure.init(); - - // Create Driver (this instance is thread-safe) - ArangoDriver arangoDriver = new ArangoDriver(configure); - -``` - - -The driver is configured with some default values: - - - - - - - - - - - - - - - - - - - - -
property-keydescriptiondefault value
hostArangoDB host127.0.0.1
portArangoDB port8529
maxPerConnectionMax http connection per host.20
maxTotalConnectionMax http connection per configure.20
userBasic Authentication User
passwordBasic Authentication Password
proxy.hostproxy host
proxy.portproxy port
connectionTimeoutsocket connect timeout(millisecond)-1
timeoutsocket read timeout(millisecond)-1
retryCounthttp retry count3
defaultDatabasedefault database
enableCURLLoggerlogging flag by curl format for debugfalse
useSsluse HTTPS connectionfalse
property-keydescriptiondefault value
arangoHostArangoDB host and port 127.0.0.1:8529
fallbackArangoHostfallback ArangoDB host and port
- -To customize the configuration the parameters can be changed in the code... - -``` Java - // Initialize configure - ArangoConfigure configure = new ArangoConfigure(); - configure.setArangoHost(new ArangoHost("192.168.182.50", 8888)); - configure.init(); - - // Create Driver (this instance is thread-safe) - ArangoDriver arangoDriver = new ArangoDriver(configure); - -``` -... or with a properties file (arangodb.properties) - -``` Java - // Initialize configure - ArangoConfigure configure = new ArangoConfigure(); - configure.loadProperties(); - configure.init(); - - // Create Driver (this instance is thread-safe) - ArangoDriver arangoDriver = new ArangoDriver(configure); - -``` - -Example for arangodb.properties: -``` Java -arangoHost=192.168.182.50:8888 -user=root -password= -enableCURLLogger=true - -``` - - -# Basic database operations -## create database -``` Java - // create database - arangoDriver.createDatabase("myDatabase"); - // and set as default - arangoDriver.setDefaultDatabase("myDatabase"); - -``` - -## changing the database -This ArangoDB driver is thread-safe. Unfortunately the ArangoDriver#setDefaultDatabase() is not (yet). So its recommended to create a new driver instance, if you want to change the database. - -``` Java - //Driver instance to database "_system" (default database) - ArangoDriver driverSystem = new ArangoDriver(configure); - //Driver instance to database "mydb2" - ArangoDriver driverMyDB = new ArangoDriver(configure, "mydb2"); - -``` - -## drop database -``` Java - // drop database - arangoDriver.deleteDatabase("myDatabase"); - -``` - -# Basic collection operations -## create collection -``` Java - // create collection - CollectionEntity myArangoCollection = ArangoCollectionarangoDriver.createCollection("myCollection"); - -``` - -## delete collection by name -``` Java - // delete database - arangoDriver.deleteCollection("myCollection"); - -``` - -## delete collection by id -``` Java - // delete database - arangoDriver.deleteCollection(myArangoCollection.getId()); - -``` - -# Basic document operations - -For the next examples we use a small object: - -``` Java -public class MyObject { - - private String name; - private int age; - - public MyObject(String name, int age) { - this.name = name; - this.age = age; - } - - /* - * + getter and setter - */ - - -} -``` - -## create document -``` Java - // create document - MyObject myObject = new MyObject("Homer", 38); - DocumentEntity myDocument = arangoDriver.createDocument("myCollection", myObject); - -``` - -When creating a document, the attributes of the object will be stored as key-value pair -E.g. in the previous example the object was stored as follows: -``` properties -"name" : "Homer" -"age" : "38" -``` - - -## delete document -``` Java - // delete document - arangoDriver.deleteDocument(myDocument.getDocumentHandle()); - -``` - -# AQL -## Executing an AQL statement - -E.g. get all Simpsons aged 3 or older in ascending order: - -``` Java - arangoDriver.deleteDatabase("myDatabase"); - arangoDriver.createDatabase("myDatabase"); - arangoDriver.setDefaultDatabase("myDatabase"); - CollectionEntity myArangoCollection = arangoDriver.createCollection("myCollection"); - - arangoDriver.createDocument("myCollection", new MyObject("Homer", 38)); - arangoDriver.createDocument("myCollection", new MyObject("Marge", 36)); - arangoDriver.createDocument("myCollection", new MyObject("Bart", 10)); - arangoDriver.createDocument("myCollection", new MyObject("Lisa", 8)); - arangoDriver.createDocument("myCollection", new MyObject("Maggie", 2)); - - String query = "FOR t IN myCollection FILTER t.age >= @age SORT t.age RETURN t"; - Map bindVars = new MapBuilder().put("age", 3).get(); - - DocumentCursor documentCursor = arangoDriver.executeDocumentQuery( - query, bindVars, driver.getDefaultAqlQueryOptions(), MyObject.class); - - for (DocumentEntity documentEntity : documentCursor.asList()) { - MyObject obj = documentEntity.getEntity(); - System.out.println(obj.getName()); - } -``` - -instead of using a ```for``` statement you can also use an DocumentEntitiy or an entity iterator: -``` Java - Iterator> iterator = documentCursor.iterator(); - while (iterator.hasNext()) { - DocumentEntity documentEntity = iterator.next(); - MyObject obj = documentEntity.getEntity(); - System.out.println(obj.getName()); - } - - Iterator iterator = documentCursor.entityIterator(); - while (iterator.hasNext()) { - MyObject obj = iterator.next(); - System.out.println(obj.getName()); - } -``` - -#User Management -If you are using [authentication] (https://docs.arangodb.com/Manual/GettingStarted/Authentication.html) you can manage users with the driver. - -##add user -``` Java - //username, password, active, extras - arangoDriver.createUser("myUser", "myPassword", true, null); -``` - -##list users -``` Java - List users = arangoDriver.getUsers(); - for(UserEntity user : users) { - System.out.println(user.getName()) - } -``` - - -##DELETE user -``` Java - arangoDriver.deleteUser("myUser"); -``` - - -#Graphs -This driver supports the new [graph api](https://docs.arangodb.com/HTTP/Gharial/index.html). - -Some of the basic graph operations are described in the following: - -##add graph -A graph consists of vertices and edges (stored in collections). Which collections are used within a graph is defined via edge definitions. A graph can contain more than one edge definition, at least one is needed. - -``` Java - List edgeDefinitions = new ArrayList(); - EdgeDefinitionEntity edgeDefinition = new EdgeDefinitionEntity(); - // define the edgeCollection to store the edges - edgeDefinition.setCollection("myEdgeCollection"); - // define a set of collections where an edge is going out... - List from = new ArrayList(); - // and add one or more collections - from.add("myCollection1"); - from.add("myCollection2"); - edgeDefinition.setFrom(from); - - // repeat this for the collections where an edge is going into - List to = new ArrayList(); - to.add("myCollection1"); - to.add("myCollection3"); - edgeDefinition.setTo(to); - - edgeDefinitions.add(edgeDefinition); - - // A graph can contain additional vertex collections, defined in the set of orphan collections - List orphanCollections = new ArrayList(); - orphanCollections.add("myCollection4"); - orphanCollections.add("myCollection5"); - - // now it's possible to create a graph (the last parameter is the waitForSync option) - GraphEntity graph = arangoDriver.createGraph("myGraph", edgeDefinitions, orphanCollections, true); -``` - -##delete graph - -A graph can be deleted by its name - -``` Java - arangoDriver.deleteGraph("myGraph"); -``` - -##add vertex - -Vertices are stored in the vertex collections defined above. - -``` Java - MyObject myObject1 = new MyObject("Homer", 38); - MyObject myObject2 = new MyObject("Marge", 36); - DocumentEntity vertexFrom = arangoDriver.graphCreateVertex( - "myGraph", - "collection1", - myObject1, - true); - - DocumentEntity vertexTo = arangoDriver.graphCreateVertex( - "myGraph", - "collection3", - myObject2, - true); -``` - -## add edge - -Now an edge can be created to set a relation between vertices - -``` Java - EdgeEntity edge = arangoDriver.graphCreateEdge( - "myGraph", - "myEdgeCollection", - null, - vertexFrom.getDocumentHandle(), - vertexTo.getDocumentHandle(), - null, - null); -``` -# Compile java driver ``` - mvn clean install -DskipTests=true -Dgpg.skip=true -Dmaven.javadoc.skip=true -B +mvn clean install -DskipTests=true -Dgpg.skip=true -Dmaven.javadoc.skip=true -B ``` # Learn more * [ArangoDB](https://www.arangodb.com/) * [ChangeLog](ChangeLog) +* [Documentation](docs/documentation.md) * [Examples](src/test/java/com/arangodb/example) * [Tutorial](https://www.arangodb.com/tutorial-java/) -* [JavaDoc](http://arangodb.github.io/arangodb-java-driver/javadoc-3_1/index.html) +* [JavaDoc](http://arangodb.github.io/arangodb-java-driver/javadoc-4_0/index.html) diff --git a/docs/aql.md b/docs/aql.md new file mode 100644 index 000000000..d6a9ee28c --- /dev/null +++ b/docs/aql.md @@ -0,0 +1,41 @@ +# AQL +## Executing an AQL statement + +Every AQL operations works with POJOs (e.g. MyObject), VelocyPack (VPackSlice) and Json (String). + +E.g. get all Simpsons aged 3 or older in ascending order: + +``` Java + arangoDB.createDatabase("myDatabase"); + ArangoDatabase db = arangoDB.db("myDatabase"); + + db.createCollection("myCollection"); + ArangoCollection collection = db.collection("myCollection"); + + collection.insertDocument(new MyObject("Homer", 38)); + collection.insertDocument(new MyObject("Marge", 36)); + collection.insertDocument(new MyObject("Bart", 10)); + collection.insertDocument(new MyObject("Lisa", 8)); + collection.insertDocument(new MyObject("Maggie", 2)); + + Map bindVars = new HashMap<>(); + bindVars.put("age", 3); + + ArangoCursor cursor = db.query(query, bindVars, null, MyObject.class); + + for(; cursor.hasNext;) { + MyObject obj = cursor.next(); + System.out.println(obj.getName()); + } +``` + +or return the AQL result as VelocyPack: + +``` Java + ArangoCursor cursor = db.query(query, bindVars, null, VPackSlice.class); + + for(; cursor.hasNext;) { + VPackSlice obj = cursor.next(); + System.out.println(obj.get("name").getAsString()); + } +``` diff --git a/docs/basic_operations.md b/docs/basic_operations.md new file mode 100644 index 000000000..0e3f568db --- /dev/null +++ b/docs/basic_operations.md @@ -0,0 +1,125 @@ +# Basic database operations +## create database +``` Java + // create database + arangoDB.createDatabase("myDatabase"); + +``` + +## drop database +``` Java + // drop database + arangoDB.db("myDatabase").drop(); + +``` + +# Basic collection operations +## create collection +``` Java + // create collection + arangoDB.db("myDatabase").createCollection("myCollection", null); + +``` + +## delete collection by name +``` Java + // delete collection + arangoDB.db("myDatabase").collection("myCollection").drop(); + +``` + +## delete all documents in the collection +``` Java + arangoDB.db("myDatabase").collection("myCollection").truncate(); +``` + +# Basic document operations + +Every document operations works with POJOs (e.g. MyObject), VelocyPack (VPackSlice) and Json (String). + +For the next examples we use a small object: + +``` Java + public class MyObject { + + private String key; + private String name; + private int age; + + public MyObject(String name, int age) { + this(); + this.name = name; + this.age = age; + } + + public MyObject() { + super(); + } + + /* + * + getter and setter + */ + + } +``` + +## insert document +``` Java + MyObject myObject = new MyObject("Homer", 38); + arangoDB.db("myDatabase").collection("myCollection").insertDocument(myObject); + +``` + +When creating a document, the attributes of the object will be stored as key-value pair +E.g. in the previous example the object was stored as follows: +``` properties + "name" : "Homer" + "age" : "38" +``` + + +## delete document +``` Java + arangoDB.db("myDatabase").collection("myCollection").deleteDocument(myObject.getKey); + +``` + +## update document +``` Java + arangoDB.db("myDatabase").collection("myCollection").updateDocument(myObject.getKey, myUpdatedObject); + +``` + +## replace document +``` Java + arangoDB.db("myDatabase").collection("myCollection").replaceDocument(myObject.getKey, myObject2); + +``` + +## read document by key (as JavaBean) +``` Java + MyObject document = arangoDB.db("myDatabase").collection("myCollection").getDocument(myObject.getKey, MyObject.class); + document.getName(); + document.getAge(); + +``` + +## read document (as VelocyPack) +``` Java + VPackSlice document = arangoDB.db("myDatabase").collection("myCollection").getDocument(myObject.getKey, VPackSlice.class); + document.get("name").getAsString(); + document.get("age").getAsInt(); + +``` + +## read document (as Json) +``` Java + arangoDB.db("myDatabase").collection("myCollection").getDocument(myObject.getKey, String.class); + +``` + +## read document by id +``` Java + arangoDB.db("myDatabase").getDocument("myCollection/myKey", MyObject.class); + +``` diff --git a/docs/documentation.md b/docs/documentation.md new file mode 100644 index 000000000..1cc0e48a7 --- /dev/null +++ b/docs/documentation.md @@ -0,0 +1,10 @@ +#Documentation overview + +* [Driver Setup](setup.md) +* [Basic database operations](basic_operations.md) +* [Multi document operations](multi_operations.md) +* [serialization/deserialization](serialization.md) +* [User Management](user_management.md) +* [AQL](aql.md) +* [Graphs](graphs.md) +* [Foxx](foxx.md) \ No newline at end of file diff --git a/docs/foxx.md b/docs/foxx.md new file mode 100644 index 000000000..060ebb7c8 --- /dev/null +++ b/docs/foxx.md @@ -0,0 +1,14 @@ +# Foxx +##execute a service +``` Java + Request request = new Request("mydb", RequestType.GET, "/my/foxx/service") + Response response = arangoDB.execute(request); + +``` + +##execute a service (async) +``` Java + Request request = new Request("mydb", RequestType.GET, "/my/foxx/service") + CompletableFuture response = arangoDB.executeAsync(request); + +``` \ No newline at end of file diff --git a/docs/graphs.md b/docs/graphs.md new file mode 100644 index 000000000..682db27d5 --- /dev/null +++ b/docs/graphs.md @@ -0,0 +1,58 @@ +#Graphs +This driver supports the [graph api](https://docs.arangodb.com/HTTP/Gharial/index.html). + +Some of the basic graph operations are described in the following: + +##add graph +A graph consists of vertices and edges (stored in collections). Which collections are used within a graph is defined via edge definitions. A graph can contain more than one edge definition, at least one is needed. + +``` Java + Collection edgeDefinitions = new ArrayList<>(); + EdgeDefinition edgeDefinition = new EdgeDefinition(); + // define the edgeCollection to store the edges + edgeDefinition.collection("myEdgeCollection"); + // define a set of collections where an edge is going out... + edgeDefinition.from("myCollection1", "myCollection2"); + + // repeat this for the collections where an edge is going into + edgeDefinition.to("myCollection1", "myCollection3"); + + edgeDefinitions.add(edgeDefinition); + + // A graph can contain additional vertex collections, defined in the set of orphan collections + GraphCreateOptions options = new GraphCreateOptions(); + options.orphanCollections("myCollection4", "myCollection5"); + + // now it's possible to create a graph + arangoDB.db("myDatabase").createGraph("myGraph", edgeDefinitions, options); + +``` + +##delete graph + +A graph can be deleted by its name + +``` Java + arangoDB.db("myDatabase").graph("myGraph").drop(); +``` + +##add vertex + +Vertices are stored in the vertex collections defined above. + +``` Java + MyObject myObject1 = new MyObject("Homer", 38); + MyObject myObject2 = new MyObject("Marge", 36); + arangoDB.db("myDatabase").graph("myGraph").vertexCollection("collection1").insertVertex(myObject1, null); + arangoDB.db("myDatabase").graph("myGraph").vertexCollection("collection3").insertVertex(myObject2, null); + +``` + +## add edge + +Now an edge can be created to set a relation between vertices + +``` Java + arangoDB.db("myDatabase").graph("myGraph").edgeCollection("myEdgeCollection").insertEdge(myEdgeObject, null); + +``` diff --git a/docs/multi_operations.md b/docs/multi_operations.md new file mode 100644 index 000000000..95aab7b69 --- /dev/null +++ b/docs/multi_operations.md @@ -0,0 +1,41 @@ +# Multi document operations + +## insert documents +``` Java + Collection documents = new ArrayList<>; + documents.add(myObject1); + documents.add(myObject2); + documents.add(myObject3); + arangoDB.db("myDatabase").collection("myCollection").insertDocuments(documents); + +``` + +## delete documents +``` Java + Collection keys = new ArrayList<>; + keys.add(myObject1.getKey()); + keys.add(myObject2.getKey()); + keys.add(myObject3.getKey()); + arangoDB.db("myDatabase").collection("myCollection").deleteDocuments(keys); + +``` + +## update documents +``` Java + Collection documents = new ArrayList<>; + documents.add(myObject1); + documents.add(myObject2); + documents.add(myObject3); + arangoDB.db("myDatabase").collection("myCollection").updateDocuments(documents); + +``` + +## replace documents +``` Java + Collection documents = new ArrayList<>; + documents.add(myObject1); + documents.add(myObject2); + documents.add(myObject3); + arangoDB.db("myDatabase").collection("myCollection").replaceDocuments(documents); + +``` diff --git a/docs/serialization.md b/docs/serialization.md new file mode 100644 index 000000000..28705ed41 --- /dev/null +++ b/docs/serialization.md @@ -0,0 +1,75 @@ +# serialization / deserialization +## JavaBeans +The driver can serialize/deserialize JavaBeans. They need at least a constructor without parameter. + +``` Java + public class MyObject { + + private String name; + private Gender gender; + private int age; + + public MyObject() { + super(); + } + + } +``` + +## internal fields +To use Arango-internal fields (like _id, _key, _rev, _from, _to) in your JavaBeans, use the annotation `DocumentField`. + +``` Java + public class MyObject { + + @DocumentField(Type.KEY) + private String key; + + private String name; + private Gender gender; + private int age; + + public MyObject() { + super(); + } + + } +``` + +## serialized fieldnames +To use a different serialized name for a field, use the annotation `SerializedName`. + +``` Java + public class MyObject { + + @SerializedName("title") + private String name; + + private Gender gender; + private int age; + + public MyObject() { + super(); + } + + } +``` + +## ignore fields +To ignore fields at serialization/deserialization, use the annotation `Expose` + +``` Java + public class MyObject { + + @Expose + private String name; + @Expose(serialize = true, deserialize = false) + private Gender gender; + private int age; + + public MyObject() { + super(); + } + + } +``` diff --git a/docs/setup.md b/docs/setup.md new file mode 100644 index 000000000..b2252d874 --- /dev/null +++ b/docs/setup.md @@ -0,0 +1,46 @@ +# Driver Setup + +Setup with default configuration, this automatically loads a properties file arangodb.properties if exists in the classpath: + +``` Java + // this instance is thread-safe + ArangoDB arangoDB = new ArangoDB.Builder().build(); + +``` + + +The driver is configured with some default values: + + + + + + + + + + +
property-keydescriptiondefault value
arangodb.hostArangoDB host127.0.0.1
arangodb.portArangoDB port8529
arangodb.timeoutsocket connect timeout(millisecond)0
arangodb.userBasic Authentication User
arangodb.passwordBasic Authentication Password
arangodb.useSsluse SSL connectionfalse
harangodb.chunksizeVelocyStream Chunk content-size(bytes)30000
+ +To customize the configuration the parameters can be changed in the code... + +``` Java + ArangoDB arangoDB = new ArangoDB.Builder().host("192.168.182.50").port(8888).build(); + +``` +... or with a custom properties file (my.properties) + +``` Java + InputStream in = MyClass.class.getResourceAsStream("my.properties"); + ArangoDB arangoDB = new ArangoDB.Builder().loadProperties(in).build(); + +``` + +Example for arangodb.properties: +``` Java + arangodb.host=127.0.0.1 + arangodb.port=8529 + arangodb.user=root + arangodb.password= + +``` \ No newline at end of file diff --git a/docs/user_management.md b/docs/user_management.md new file mode 100644 index 000000000..96d8a4ddc --- /dev/null +++ b/docs/user_management.md @@ -0,0 +1,31 @@ +#User Management +If you are using [authentication] (https://docs.arangodb.com/Manual/GettingStarted/Authentication.html) you can manage users with the driver. + +##add user +``` Java + //username, password + arangoDB.createUser("myUser", "myPassword"); +``` + +##grant user access to database +``` Java + arangoDB.db("myDatabase").grantAccess("myUser"); +```` + +##revoke user access to database +``` Java + arangoDB.db("myDatabase").revokeAccess("myUser"); +```` + +##list users +``` Java + Collection users = arangoDB.getUsers(); + for(UserResult user : users) { + System.out.println(user.getUser()) + } +``` + +##delete user +``` Java + arangoDB.deleteUser("myUser"); +``` diff --git a/pom.xml b/pom.xml index 1f0a192a6..549d31afd 100644 --- a/pom.xml +++ b/pom.xml @@ -4,8 +4,8 @@ com.arangodb arangodb-java-driver - 3.1.0 - 2012 + 4.0.0 + 2016 jar arangodb-java-driver @@ -20,22 +20,15 @@ + + UTF-8 + 1.7.13 + 1.1.3 + 1.3 + 4.12 + + - - tamtam180 - tamtam180 - http://mt.orz.at/ - - - gschwab - gschwab - https://github.com/gschwab - - - scottashton - scottashton - https://github.com/scottashton - a-brandt a-brandt @@ -165,9 +158,9 @@ maven-surefire-plugin 2.19.1 - 0 - com/arangodb/ArangoTestSuite.java + **/*Test.java + **/*Example.java @@ -200,66 +193,61 @@ - - UTF-8 - 4.1 - 2.5 - 4.5.1 - 1.7.13 - 1.1.3 - 1.3 - 4.12 - - - - com.google.code.gson - gson - ${gson.version} - compile - - - org.apache.httpcomponents - httpclient - ${httpclient.version} - jar - compile - org.slf4j slf4j-api - ${slf4j-api.version} - jar - compile + + + com.googlecode.json-simple + json-simple ch.qos.logback logback-classic - ${logback-classic.version} - jar - provided + test junit junit - ${junit.version} test org.hamcrest hamcrest-all - ${hamcrest-all.version} test - - org.json - json - 20140107 - test - - - + + + + + org.slf4j + slf4j-api + ${slf4j-api.version} + + + com.googlecode.json-simple + json-simple + 1.1.1 + + + 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 diff --git a/src/main/java/com/arangodb/ArangoClient.java b/src/main/java/com/arangodb/ArangoClient.java deleted file mode 100644 index 4735c98e2..000000000 --- a/src/main/java/com/arangodb/ArangoClient.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Copyright (C) 2012 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import com.arangodb.entity.ImportResultEntity; - -/** - * @author tamtam180 - kirscheless at gmail.com - * - */ -public class ArangoClient { - - public static final int DEFAULT_IMPORT_BUFFER_SIZE = 1000; - - protected ArangoDriver driver; - - public ArangoClient(ArangoConfigure configure) { - driver = new ArangoDriver(configure); - } - - private void importDocumentsImpl(String collectionName, List values, ImportResultEntity total) - throws ArangoException { - ImportResultEntity result = driver.importDocuments(collectionName, values); - total.setCreated(total.getCreated() + result.getCreated()); - total.setErrors(total.getErrors() + result.getErrors()); - total.setEmpty(total.getEmpty() + result.getEmpty()); - total.setUpdated(total.getUpdated() + result.getUpdated()); - total.setIgnored(total.getIgnored() + result.getIgnored()); - total.getDetails().addAll(result.getDetails()); - } - - public ImportResultEntity importRawJsonDocuments(String collectionName, Iterator itr, int bufferCount) - throws ArangoException { - - int tmpBufferCount = bufferCount; - if (tmpBufferCount <= 0) { - tmpBufferCount = DEFAULT_IMPORT_BUFFER_SIZE; - } - - ImportResultEntity total = new ImportResultEntity(); - - ArrayList buffers = new ArrayList(tmpBufferCount); - while (itr.hasNext()) { - buffers.add(itr.next()); - if (buffers.size() % tmpBufferCount == 0) { - importDocumentsImpl(collectionName, buffers, total); - buffers.clear(); - } - } - if (!buffers.isEmpty()) { - importDocumentsImpl(collectionName, buffers, total); - } - - return total; - - } - -} diff --git a/src/main/java/com/arangodb/ArangoCollection.java b/src/main/java/com/arangodb/ArangoCollection.java new file mode 100644 index 000000000..e7bd5809c --- /dev/null +++ b/src/main/java/com/arangodb/ArangoCollection.java @@ -0,0 +1,700 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb; + +import java.util.Collection; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.arangodb.entity.CollectionEntity; +import com.arangodb.entity.CollectionPropertiesEntity; +import com.arangodb.entity.CollectionRevisionEntity; +import com.arangodb.entity.DocumentCreateEntity; +import com.arangodb.entity.DocumentDeleteEntity; +import com.arangodb.entity.DocumentUpdateEntity; +import com.arangodb.entity.IndexEntity; +import com.arangodb.entity.MultiDocumentEntity; +import com.arangodb.internal.InternalArangoCollection; +import com.arangodb.internal.ArangoExecutorSync; +import com.arangodb.internal.velocystream.ConnectionSync; +import com.arangodb.model.CollectionPropertiesOptions; +import com.arangodb.model.DocumentCreateOptions; +import com.arangodb.model.DocumentDeleteOptions; +import com.arangodb.model.DocumentExistsOptions; +import com.arangodb.model.DocumentReadOptions; +import com.arangodb.model.DocumentReplaceOptions; +import com.arangodb.model.DocumentUpdateOptions; +import com.arangodb.model.FulltextIndexOptions; +import com.arangodb.model.GeoIndexOptions; +import com.arangodb.model.HashIndexOptions; +import com.arangodb.model.PersistentIndexOptions; +import com.arangodb.model.SkiplistIndexOptions; +import com.arangodb.velocystream.Response; + +/** + * @author Mark - mark at arangodb.com + * + */ +public class ArangoCollection extends InternalArangoCollection { + + private static final Logger LOGGER = LoggerFactory.getLogger(ArangoCollection.class); + + protected ArangoCollection(final ArangoDatabase db, final String name) { + super(db.executor(), db.name(), 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. + * + * @see API + * Documentation + * @param value + * A representation of a single document (POJO, VPackSlice or String for Json) + * @return information about the document + * @throws ArangoDBException + */ + public DocumentCreateEntity insertDocument(final T value) throws ArangoDBException { + return executor.execute(insertDocumentRequest(value, new DocumentCreateOptions()), + insertDocumentResponseDeserializer(value)); + } + + /** + * Creates a new document from the given document, unless there is already a document with the _key given. If no + * _key is given, a new unique _key is generated automatically. + * + * @see API + * Documentation + * @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 + */ + public DocumentCreateEntity insertDocument(final T value, final DocumentCreateOptions options) + throws ArangoDBException { + return executor.execute(insertDocumentRequest(value, options), insertDocumentResponseDeserializer(value)); + } + + /** + * 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. + * + * @see API + * Documentation + * @param values + * A List of documents (POJO, VPackSlice or String for Json) + * @return information about the documents + * @throws ArangoDBException + */ + public MultiDocumentEntity> insertDocuments(final Collection values) + throws ArangoDBException { + final DocumentCreateOptions params = new DocumentCreateOptions(); + return executor.execute(insertDocumentsRequest(values, params), + insertDocumentsResponseDeserializer(values, params)); + } + + /** + * 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. + * + * @see API + * Documentation + * @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 + */ + 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)); + } + + /** + * Reads a single document + * + * @see API + * Documentation + * @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 + */ + public T getDocument(final String key, final Class type) { + executor.validateDocumentKey(key); + try { + return executor.execute(getDocumentRequest(key, new DocumentReadOptions()), type); + } catch (final ArangoDBException e) { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug(e.getMessage(), e); + } + return null; + } + } + + /** + * Reads a single document + * + * @see API + * Documentation + * @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 + */ + public T getDocument(final String key, final Class type, final DocumentReadOptions options) + throws ArangoDBException { + executor.validateDocumentKey(key); + try { + return executor.execute(getDocumentRequest(key, options), type); + } catch (final ArangoDBException e) { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug(e.getMessage(), e); + } + return null; + } + } + + /** + * Replaces the document with key with the one in the body, provided there is such a document and no precondition is + * violated + * + * @see API + * Documentation + * @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 + */ + public DocumentUpdateEntity replaceDocument(final String key, final T value) throws ArangoDBException { + return executor.execute(replaceDocumentRequest(key, value, new DocumentReplaceOptions()), + replaceDocumentResponseDeserializer(value)); + } + + /** + * Replaces the document with key with the one in the body, provided there is such a document and no precondition is + * violated + * + * @see API + * Documentation + * @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 + */ + public DocumentUpdateEntity replaceDocument( + final String key, + final T value, + final DocumentReplaceOptions options) throws ArangoDBException { + return executor.execute(replaceDocumentRequest(key, value, options), + replaceDocumentResponseDeserializer(value)); + } + + /** + * 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. + * + * @see API + * Documentation + * @param values + * A List of documents (POJO, VPackSlice or String for Json) + * @return information about the documents + * @throws ArangoDBException + */ + public MultiDocumentEntity> replaceDocuments(final Collection values) + throws ArangoDBException { + final DocumentReplaceOptions params = new DocumentReplaceOptions(); + return executor.execute(replaceDocumentsRequest(values, params), + replaceDocumentsResponseDeserializer(values, params)); + } + + /** + * 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. + * + * @see API + * Documentation + * @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 + */ + 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)); + } + + /** + * 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. + * + * @see API + * Documentation + * @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 + */ + public DocumentUpdateEntity updateDocument(final String key, final T value) throws ArangoDBException { + return executor.execute(updateDocumentRequest(key, value, new DocumentUpdateOptions()), + updateDocumentResponseDeserializer(value)); + } + + /** + * Partially updates the document identified by document-key. The value must contain a document with the attributes + * to patch (the patch document). All attributes from the patch document will be added to the existing document if + * they do not yet exist, and overwritten in the existing document if they do exist there. + * + * @see API + * Documentation + * @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 + */ + public DocumentUpdateEntity updateDocument( + final String key, + final T value, + final DocumentUpdateOptions options) throws ArangoDBException { + return executor.execute(updateDocumentRequest(key, value, options), updateDocumentResponseDeserializer(value)); + } + + /** + * 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. + * + * @see API + * Documentation + * @param values + * A list of documents (POJO, VPackSlice or String for Json) + * @return information about the documents + * @throws ArangoDBException + */ + public MultiDocumentEntity> updateDocuments(final Collection values) + throws ArangoDBException { + final DocumentUpdateOptions params = new DocumentUpdateOptions(); + return executor.execute(updateDocumentsRequest(values, params), + updateDocumentsResponseDeserializer(values, params)); + } + + /** + * 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. + * + * @see API + * Documentation + * @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 + */ + 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)); + } + + /** + * Removes a document + * + * @see API + * Documentation + * @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 + */ + public DocumentDeleteEntity deleteDocument(final String key) throws ArangoDBException { + return executor.execute(deleteDocumentRequest(key, new DocumentDeleteOptions()), + deleteDocumentResponseDeserializer(Void.class)); + } + + /** + * Removes a document + * + * @see API + * Documentation + * @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 + */ + public DocumentDeleteEntity deleteDocument( + final String key, + final Class type, + final DocumentDeleteOptions options) throws ArangoDBException { + return executor.execute(deleteDocumentRequest(key, options), deleteDocumentResponseDeserializer(type)); + } + + /** + * Removes multiple document + * + * @see API + * Documentation + * @param keys + * The keys of the documents + * @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. + * @return information about the documents + * @throws ArangoDBException + */ + public MultiDocumentEntity> deleteDocuments(final Collection keys) + throws ArangoDBException { + return executor.execute(deleteDocumentsRequest(keys, new DocumentDeleteOptions()), + deleteDocumentsResponseDeserializer(Void.class)); + } + + /** + * Removes multiple document + * + * @see API + * Documentation + * @param keys + * The keys of the documents + * @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 + */ + public MultiDocumentEntity> deleteDocuments( + final Collection keys, + final Class type, + final DocumentDeleteOptions options) throws ArangoDBException { + return executor.execute(deleteDocumentsRequest(keys, options), deleteDocumentsResponseDeserializer(type)); + } + + /** + * Checks if the document exists by reading a single document head + * + * @see API + * Documentation + * @param key + * The key of the document + * @return true if the document was found, otherwise false + */ + public Boolean documentExists(final String key) { + return documentExists(key, new DocumentExistsOptions()); + } + + /** + * Checks if the document exists by reading a single document head + * + * @see API + * Documentation + * @param key + * The key of the document + * @param options + * Additional options, can be null + * @return true if the document was found, otherwise false + */ + public Boolean documentExists(final String key, final DocumentExistsOptions options) { + try { + executor.communication().execute(documentExistsRequest(key, options)); + return true; + } catch (final ArangoDBException e) { + return false; + } + } + + /** + * Creates a hash index for the collection if it does not already exist. + * + * @see API Documentation + * @param fields + * A list of attribute paths + * @param options + * Additional options, can be null + * @return information about the index + * @throws ArangoDBException + */ + public IndexEntity createHashIndex(final Collection fields, final HashIndexOptions options) + throws ArangoDBException { + return executor.execute(createHashIndexRequest(fields, options), IndexEntity.class); + } + + /** + * Creates a skip-list index for the collection, if it does not already exist. + * + * @see API + * Documentation + * @param fields + * A list of attribute paths + * @param options + * Additional options, can be null + * @return information about the index + * @throws ArangoDBException + */ + public IndexEntity createSkiplistIndex(final Collection fields, final SkiplistIndexOptions options) + throws ArangoDBException { + return executor.execute(createSkiplistIndexRequest(fields, options), IndexEntity.class); + } + + /** + * Creates a persistent index for the collection, if it does not already exist. + * + * @see API + * Documentation + * @param fields + * A list of attribute paths + * @param options + * Additional options, can be null + * @return information about the index + * @throws ArangoDBException + */ + public IndexEntity createPersistentIndex(final Collection fields, final PersistentIndexOptions options) + throws ArangoDBException { + return executor.execute(createPersistentIndexRequest(fields, options), IndexEntity.class); + } + + /** + * Creates a geo-spatial index for the collection, if it does not already exist. + * + * @see API + * Documentation + * @param fields + * A list of attribute paths + * @param options + * Additional options, can be null + * @return information about the index + * @throws ArangoDBException + */ + public IndexEntity createGeoIndex(final Collection fields, final GeoIndexOptions options) + throws ArangoDBException { + return executor.execute(createGeoIndexRequest(fields, options), IndexEntity.class); + } + + /** + * Creates a fulltext index for the collection, if it does not already exist. + * + * @see API + * Documentation + * @param fields + * A list of attribute paths + * @param options + * Additional options, can be null + * @return information about the index + * @throws ArangoDBException + */ + public IndexEntity createFulltextIndex(final Collection fields, final FulltextIndexOptions options) + throws ArangoDBException { + return executor.execute(createFulltextIndexRequest(fields, options), IndexEntity.class); + } + + /** + * Returns all indexes of the collection + * + * @see API + * Documentation + * @return information about the indexes + * @throws ArangoDBException + */ + public Collection getIndexes() throws ArangoDBException { + return executor.execute(getIndexesRequest(), getIndexesResponseDeserializer()); + } + + /** + * Removes all documents from the collection, but leaves the indexes intact + * + * @see API + * Documentation + * @return information about the collection + * @throws ArangoDBException + */ + public CollectionEntity truncate() throws ArangoDBException { + return executor.execute(truncateRequest(), CollectionEntity.class); + } + + /** + * Counts the documents in a collection + * + * @see API + * Documentation + * @return information about the collection, including the number of documents + * @throws ArangoDBException + */ + public CollectionPropertiesEntity count() throws ArangoDBException { + return executor.execute(countRequest(), CollectionPropertiesEntity.class); + } + + /** + * Drops the collection + * + * @see API + * Documentation + * @throws ArangoDBException + */ + public void drop() throws ArangoDBException { + executor.execute(dropRequest(), Void.class); + } + + /** + * Loads a collection into memory. + * + * @see API + * Documentation + * @return information about the collection + * @throws ArangoDBException + */ + public CollectionEntity load() throws ArangoDBException { + return executor.execute(loadRequest(), CollectionEntity.class); + } + + /** + * Removes a 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. + * + * @see API + * Documentation + * @return information about the collection + * @throws ArangoDBException + */ + public CollectionEntity unload() throws ArangoDBException { + return executor.execute(unloadRequest(), CollectionEntity.class); + } + + /** + * Returns information about the collection + * + * @see API + * Documentation + * @return information about the collection + * @throws ArangoDBException + */ + public CollectionEntity getInfo() throws ArangoDBException { + return executor.execute(getInfoRequest(), CollectionEntity.class); + } + + /** + * Reads the properties of the specified collection + * + * @see API + * Documentation + * @return properties of the collection + * @throws ArangoDBException + */ + public CollectionPropertiesEntity getProperties() throws ArangoDBException { + return executor.execute(getPropertiesRequest(), CollectionPropertiesEntity.class); + } + + /** + * Changes the properties of a collection + * + * @see API + * Documentation + * @param options + * Additional options, can be null + * @return properties of the collection + * @throws ArangoDBException + */ + public CollectionPropertiesEntity changeProperties(final CollectionPropertiesOptions options) + throws ArangoDBException { + return executor.execute(changePropertiesRequest(options), CollectionPropertiesEntity.class); + } + + /** + * Renames a collection + * + * @see API + * Documentation + * @param newName + * The new name + * @return information about the collection + * @throws ArangoDBException + */ + public CollectionEntity rename(final String newName) throws ArangoDBException { + return executor.execute(renameRequest(newName), CollectionEntity.class); + } + + /** + * Retrieve the collections revision + * + * @see API + * Documentation + * @return information about the collection, including the collections revision + * @throws ArangoDBException + */ + public CollectionRevisionEntity getRevision() throws ArangoDBException { + return executor.execute(getRevisionRequest(), CollectionRevisionEntity.class); + } + +} diff --git a/src/main/java/com/arangodb/ArangoConfigure.java b/src/main/java/com/arangodb/ArangoConfigure.java deleted file mode 100644 index e96ca73e3..000000000 --- a/src/main/java/com/arangodb/ArangoConfigure.java +++ /dev/null @@ -1,546 +0,0 @@ -/* - * Copyright (C) 2012 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb; - -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.List; -import java.util.Properties; - -import javax.net.ssl.SSLContext; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.arangodb.http.BatchHttpManager; -import com.arangodb.util.IOUtils; - -/** - * Configure of ArangoDB. - * - * @author tamtam180 - kirscheless at gmail.com - * @author a-brandt - * - */ -public class ArangoConfigure { - - private static Logger logger = LoggerFactory.getLogger(ArangoConfigure.class); - - /** default host of ArangoDB */ - private static final String DEFAULT_HOST = "127.0.0.1"; - /** default port of ArangoDB */ - private static final int DEFAULT_PORT = 8529; - - /** default */ - private static final int DEFAULT_MAX_PER_CONNECTION = 20; - /** default maximum conections */ - private static final int DEFAULT_MAX_CONNECTION = 20; - - /** default property file */ - private static final String DEFAULT_PROPERTY_FILE = "/arangodb.properties"; - - private List arangoHosts; - private int currentArangoHost; - - /** connection timeout(ms) */ - private int connectionTimeout = -1; - /** socket read timeout(ms) */ - private int timeout = -1; - - /** max connection per configure */ - private int maxTotalConnection; - /** max connection per host */ - private int maxPerConnection; - - /** Basic auth user */ - private String user; - /** Basic auth password */ - private String password; - - /** proxy-host */ - private String proxyHost; - /** proxy-port */ - private int proxyPort; - - /** http retry count */ - private int retryCount = 3; - - /** - * number of connect retries (0 means infinite) - */ - private int connectRetryCount = 3; - - /** - * milliseconds - */ - private int connectRetryWait = 1000; - - /** Default Database */ - String defaultDatabase; - - private boolean enableCURLLogger = false; - - private int validateAfterInactivity = -1; - - private boolean useSsl = false; - - private SSLContext sslContext = null; - - /** - * the default ArangoDB cursor batch size - */ - private int batchSize = 20; - - BatchHttpManager httpManager; - - public ArangoConfigure() { - init(DEFAULT_PROPERTY_FILE); - } - - public ArangoConfigure(final String propertyPath) { - init(propertyPath); - } - - private void init(final String propertyPath) { - arangoHosts = new ArrayList(); - final ArangoHost defaultHost = new ArangoHost(DEFAULT_HOST, DEFAULT_PORT); - arangoHosts.add(defaultHost); - currentArangoHost = 0; - - this.maxPerConnection = DEFAULT_MAX_PER_CONNECTION; - this.maxTotalConnection = DEFAULT_MAX_CONNECTION; - loadProperties(propertyPath); - } - - /** - * Load configure from arangodb.properties in classpath, if exists. - */ - public void loadProperties() { - loadProperties(DEFAULT_PROPERTY_FILE); - } - - /** - * Load configure from "propertyPath" in classpath, if exists. - * - * @param propertyPath - */ - public void loadProperties(final String propertyPath) { - InputStream in = null; - try { - in = getClass().getResourceAsStream(propertyPath); - if (in != null) { - logger.debug("load property: file={}", propertyPath); - - loadProperties(in); - } - } catch (final IOException e) { - logger.warn("load property error", e); - } finally { - if (in != null) { - IOUtils.close(in); - } - } - } - - private void loadProperties(final InputStream in) throws IOException { - - final Properties prop = new Properties(); - prop.load(in); - - // - final String port = prop.getProperty("port"); - if (port != null) { - arangoHosts.get(0).setPort(Integer.parseInt(port)); - } - - final String host = prop.getProperty("host"); - if (host != null) { - arangoHosts.get(0).setHost(host); - } - - final String arangoHost = prop.getProperty("arangoHost"); - if (arangoHost != null) { - final ArangoHost ah = parseArangoHost(arangoHost); - if (ah != null) { - arangoHosts.get(0).setHost(ah.getHost()); - arangoHosts.get(0).setPort(ah.getPort()); - } - } - - final String fallbackArangoHost = prop.getProperty("fallbackArangoHost"); - if (fallbackArangoHost != null) { - final ArangoHost ah = parseArangoHost(fallbackArangoHost); - if (ah != null) { - addFallbackArangoHost(ah); - } - } - - final String timeoutProperty = prop.getProperty("timeout"); - if (timeoutProperty != null) { - setTimeout(Integer.parseInt(timeoutProperty)); - } - - final String connectionTimeoutProperty = prop.getProperty("connectionTimeout"); - if (connectionTimeoutProperty != null) { - setConnectionTimeout(Integer.parseInt(connectionTimeoutProperty)); - } - - final String proxyHostProperty = prop.getProperty("proxy.host"); - if (proxyHostProperty != null) { - setProxyHost(proxyHostProperty); - } - - final String proxyPortProperty = prop.getProperty("proxy.port"); - if (proxyPortProperty != null) { - setProxyPort(Integer.parseInt(proxyPortProperty)); - } - - final String maxPerConnectionProperty = prop.getProperty("maxPerConnection"); - if (maxPerConnectionProperty != null) { - setMaxPerConnection(Integer.parseInt(maxPerConnectionProperty)); - } - - final String maxTotalConnectionProperty = prop.getProperty("maxTotalConnection"); - if (maxTotalConnectionProperty != null) { - setMaxTotalConnection(Integer.parseInt(maxTotalConnectionProperty)); - } - - final String retryCountProperty = prop.getProperty("retryCount"); - if (retryCountProperty != null) { - setRetryCount(Integer.parseInt(retryCountProperty)); - } - - final String connnectRetryCount = prop.getProperty("connnectRetryCount"); - if (connnectRetryCount != null) { - setConnectRetryCount(Integer.parseInt(connnectRetryCount)); - } - - final String connectRetryWaitProperty = prop.getProperty("connectRetryWait"); - if (connectRetryWaitProperty != null) { - setConnectRetryWait(Integer.parseInt(connectRetryWaitProperty)); - } - - final String userProperty = prop.getProperty("user"); - if (userProperty != null) { - setUser(userProperty); - } - - final String passwordProperty = prop.getProperty("password"); - if (passwordProperty != null) { - setPassword(passwordProperty); - } - - final String defaultDatabaseProperty = prop.getProperty("defaultDatabase"); - if (defaultDatabaseProperty != null) { - setDefaultDatabase(defaultDatabaseProperty); - } - - final String enableCURLLoggerProperty = prop.getProperty("enableCURLLogger"); - if (enableCURLLoggerProperty != null) { - setEnableCURLLogger(Boolean.parseBoolean(enableCURLLoggerProperty)); - } - - final String validateAfterInactivityProperty = prop.getProperty("validateAfterInactivity"); - if (validateAfterInactivityProperty != null) { - setValidateAfterInactivity(Integer.parseInt(validateAfterInactivityProperty)); - } - - final String batchSizeProperty = prop.getProperty("batchSize"); - if (batchSizeProperty != null) { - setBatchSize(Integer.parseInt(batchSizeProperty)); - } - - final String useSslProperty = prop.getProperty("useSsl"); - if (useSslProperty != null) { - setUseSsl(Boolean.parseBoolean(useSslProperty)); - } - } - - private ArangoHost parseArangoHost(final String str) { - if (str == null) { - return null; - } - - final String[] split = str.split(":", 2); - if (split.length != 2) { - return null; - } - - return new ArangoHost(split[0], Integer.parseInt(split[1])); - } - - public void init() { - this.httpManager = new BatchHttpManager(this); - this.httpManager.init(); - } - - public void shutdown() { - if (httpManager != null) { - httpManager.destroy(); - httpManager = null; - } - } - - public String getBaseUrl() { - final ArangoHost currentHost = getCurrentHost(); - - return (useSsl ? "https://" : "http://") + currentHost.getHost() + ":" + currentHost.getPort(); - } - - public String getEndpoint() { - final ArangoHost currentHost = getCurrentHost(); - - return (useSsl ? "ssl://" : "tcp://") + currentHost.getHost() + ":" + currentHost.getPort(); - } - - private ArangoHost getCurrentHost() { - return arangoHosts.get(currentArangoHost); - } - - public boolean hasFallbackHost() { - return arangoHosts.size() > 1; - } - - public ArangoHost changeCurrentHost() { - currentArangoHost++; - - if (currentArangoHost >= arangoHosts.size()) { - currentArangoHost = 0; - } - - return getCurrentHost(); - } - - public static String getDefaultHost() { - return DEFAULT_HOST; - } - - public static int getDefaultMaxPerConnection() { - return DEFAULT_MAX_PER_CONNECTION; - } - - public static int getDefaultMaxConnection() { - return DEFAULT_MAX_CONNECTION; - } - - /** - * Get the default database host name and port - * - * @return the host name and port - */ - public ArangoHost getArangoHost() { - return arangoHosts.get(0); - } - - public int getConnectionTimeout() { - return connectionTimeout; - } - - public int getTimeout() { - return timeout; - } - - public int getMaxTotalConnection() { - return maxTotalConnection; - } - - public int getMaxPerConnection() { - return maxPerConnection; - } - - public String getProxyHost() { - return proxyHost; - } - - public int getProxyPort() { - return proxyPort; - } - - /** - * Set the host name and port of the database - * - * @param arangoHost - * the host name and port - */ - public void setArangoHost(final ArangoHost arangoHost) { - final ArangoHost host = arangoHosts.get(0); - host.setHost(arangoHost.getHost()); - host.setPort(arangoHost.getPort()); - } - - /** - * Set the host name and port of the fallback database - * - * @param arangoHost - * the host name and port - */ - public void addFallbackArangoHost(final ArangoHost arangoHost) { - arangoHosts.add(arangoHost); - } - - public void setConnectionTimeout(final int connectionTimeout) { - this.connectionTimeout = connectionTimeout; - } - - public void setTimeout(final int timeout) { - this.timeout = timeout; - } - - public void setMaxTotalConnection(final int maxTotalConnection) { - this.maxTotalConnection = maxTotalConnection; - } - - public void setMaxPerConnection(final int maxPerConnection) { - this.maxPerConnection = maxPerConnection; - } - - public void setProxyHost(final String proxyHost) { - this.proxyHost = proxyHost; - } - - public void setProxyPort(final int proxyPort) { - this.proxyPort = proxyPort; - } - - public int getRetryCount() { - return retryCount; - } - - public void setRetryCount(final int retryCount) { - this.retryCount = retryCount; - } - - public BatchHttpManager getHttpManager() { - return httpManager; - } - - public void setHttpManager(final BatchHttpManager httpManager) { - this.httpManager = httpManager; - } - - public String getUser() { - return user; - } - - public String getPassword() { - return password; - } - - public void setUser(final String user) { - this.user = user; - } - - public void setPassword(final String password) { - this.password = password; - } - - public String getDefaultDatabase() { - return defaultDatabase; - } - - /** - * Set the default database for the driver TODO: _system has to be a valid parameter - * - * @param defaultDatabase - */ - public void setDefaultDatabase(final String defaultDatabase) { - this.defaultDatabase = defaultDatabase; - } - - public boolean isEnableCURLLogger() { - return enableCURLLogger; - } - - public void setEnableCURLLogger(final boolean enableCURLLogger) { - this.enableCURLLogger = enableCURLLogger; - } - - public int getValidateAfterInactivity() { - return validateAfterInactivity; - } - - public void setValidateAfterInactivity(final int validateAfterInactivity) { - this.validateAfterInactivity = validateAfterInactivity; - } - - public int getConnectRetryCount() { - return connectRetryCount; - } - - /** - * Set number of connect retries (0 means infinite) - * - * @param connectRetryCount - * number of connect retries - */ - public void setConnectRetryCount(final int connectRetryCount) { - this.connectRetryCount = connectRetryCount; - } - - public int getConnectRetryWait() { - return connectRetryWait; - } - - /** - * Set wait time for a connect retry - * - * @param connectRetryWait - * milliseconds to wait - */ - public void setConnectRetryWait(final int connectRetryWait) { - this.connectRetryWait = connectRetryWait; - } - - public int getBatchSize() { - return batchSize; - } - - public void setBatchSize(final int batchSize) { - this.batchSize = batchSize; - } - - public boolean getUseSsl() { - return useSsl; - } - - /** - * Configure the client to use HTTPS or HTTP - * - * @param useSsl - * set true to use HTTPS (default false) - */ - public void setUseSsl(final boolean useSsl) { - this.useSsl = useSsl; - } - - public SSLContext getSslContext() { - return sslContext; - } - - /** - * Set SSL contest for HTTPS connections. - * - * (do not use setSslTrustStore() together with setSslContext()) - * - * @param sslContext - */ - public void setSslContext(final SSLContext sslContext) { - this.sslContext = sslContext; - } - -} diff --git a/src/main/java/com/arangodb/ArangoCursor.java b/src/main/java/com/arangodb/ArangoCursor.java new file mode 100644 index 000000000..bda830f0a --- /dev/null +++ b/src/main/java/com/arangodb/ArangoCursor.java @@ -0,0 +1,126 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb; + +import java.io.Closeable; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Iterator; +import java.util.List; + +import com.arangodb.entity.CursorEntity; +import com.arangodb.entity.CursorEntity.Extras; +import com.arangodb.entity.CursorEntity.Stats; +import com.arangodb.entity.CursorEntity.Warning; +import com.arangodb.internal.ArangoCursorExecute; +import com.arangodb.internal.ArangoCursorIterator; +import com.arangodb.internal.InternalArangoDatabase; + +/** + * @author Mark - mark at arangodb.com + * + */ +public class ArangoCursor implements Iterator, Closeable { + + private final Class type; + protected final ArangoCursorIterator iterator; + private final String id; + private final Integer count; + private final Extras extra; + private final boolean cached; + private final ArangoCursorExecute execute; + + public ArangoCursor(final InternalArangoDatabase db, final ArangoCursorExecute execute, + final Class type, final CursorEntity result) { + super(); + this.execute = execute; + this.type = type; + count = result.getCount(); + extra = result.getExtra(); + cached = result.getCached().booleanValue(); + iterator = new ArangoCursorIterator(this, execute, db, result); + id = result.getId(); + } + + /** + * @return id of temporary cursor created on the server + */ + public String getId() { + return id; + } + + public Class getType() { + return type; + } + + /** + * @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; + } + + public Stats getStats() { + return extra != null ? extra.getStats() : null; + } + + public Collection getWarnings() { + return extra != null ? extra.getWarnings() : null; + } + + /** + * @return indicating whether the query result was served from the query cache or not + */ + public boolean isCached() { + return cached; + } + + @Override + public void close() throws IOException { + execute.close(id); + } + + @Override + public boolean hasNext() { + return iterator.hasNext(); + } + + @Override + public T next() { + return iterator.next(); + } + + public List asListRemaining() { + final List remaining = new ArrayList(); + while (hasNext()) { + remaining.add(next()); + } + return remaining; + } + + @Override + public void remove() { + throw new UnsupportedOperationException(); + } + +} diff --git a/src/main/java/com/arangodb/ArangoDB.java b/src/main/java/com/arangodb/ArangoDB.java new file mode 100644 index 000000000..48ef297a7 --- /dev/null +++ b/src/main/java/com/arangodb/ArangoDB.java @@ -0,0 +1,418 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Collection; +import java.util.Properties; + +import javax.net.ssl.SSLContext; + +import com.arangodb.entity.ArangoDBVersion; +import com.arangodb.entity.LogEntity; +import com.arangodb.entity.UserEntity; +import com.arangodb.internal.ArangoDBConstants; +import com.arangodb.internal.ArangoExecutor.ResponseDeserializer; +import com.arangodb.internal.ArangoExecutorSync; +import com.arangodb.internal.CollectionCache; +import com.arangodb.internal.CollectionCache.DBAccess; +import com.arangodb.internal.DocumentCache; +import com.arangodb.internal.InternalArangoDB; +import com.arangodb.internal.velocypack.VPackConfigure; +import com.arangodb.internal.velocystream.Communication; +import com.arangodb.internal.velocystream.CommunicationSync; +import com.arangodb.internal.velocystream.ConnectionSync; +import com.arangodb.model.LogOptions; +import com.arangodb.model.UserCreateOptions; +import com.arangodb.model.UserUpdateOptions; +import com.arangodb.velocypack.VPack; +import com.arangodb.velocypack.VPackDeserializer; +import com.arangodb.velocypack.VPackInstanceCreator; +import com.arangodb.velocypack.VPackParser; +import com.arangodb.velocypack.VPackSerializer; +import com.arangodb.velocypack.exception.VPackException; +import com.arangodb.velocystream.Request; +import com.arangodb.velocystream.Response; + +/** + * @author Mark - mark at arangodb.com + * + */ +public class ArangoDB extends InternalArangoDB { + + public static class Builder { + + 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_V_STREAM_CHUNK_CONTENT_SIZE = "arangodb.chunksize"; + private static final String DEFAULT_PROPERTY_FILE = "/arangodb.properties"; + + private String host; + private Integer port; + private Integer timeout; + private String user; + private String password; + private Boolean useSsl; + private SSLContext sslContext; + private Integer chunksize; + private final VPack.Builder vpackBuilder; + private final CollectionCache collectionCache; + private final VPackParser vpackParser; + + public Builder() { + super(); + vpackBuilder = new VPack.Builder(); + collectionCache = new CollectionCache(); + vpackParser = new VPackParser(); + VPackConfigure.configure(vpackBuilder, vpackParser, collectionCache); + loadProperties(ArangoDB.class.getResourceAsStream(DEFAULT_PROPERTY_FILE)); + } + + public Builder loadProperties(final InputStream in) { + if (in != null) { + final Properties properties = new Properties(); + try { + properties.load(in); + host = getProperty(properties, PROPERTY_KEY_HOST, host, ArangoDBConstants.DEFAULT_HOST); + port = Integer + .parseInt(getProperty(properties, PROPERTY_KEY_PORT, port, ArangoDBConstants.DEFAULT_PORT)); + timeout = Integer.parseInt( + getProperty(properties, PROPERTY_KEY_TIMEOUT, timeout, ArangoDBConstants.DEFAULT_TIMEOUT)); + user = getProperty(properties, PROPERTY_KEY_USER, user, null); + password = getProperty(properties, PROPERTY_KEY_PASSWORD, password, null); + useSsl = Boolean.parseBoolean( + getProperty(properties, PROPERTY_KEY_USE_SSL, useSsl, ArangoDBConstants.DEFAULT_USE_SSL)); + chunksize = Integer.parseInt(getProperty(properties, PROPERTY_KEY_V_STREAM_CHUNK_CONTENT_SIZE, + chunksize, ArangoDBConstants.CHUNK_DEFAULT_CONTENT_SIZE)); + } catch (final IOException e) { + throw new ArangoDBException(e); + } + } + return this; + } + + private String getProperty( + final Properties properties, + final String key, + final T currentValue, + final T defaultValue) { + return properties.getProperty(key, + currentValue != null ? currentValue.toString() : defaultValue != null ? defaultValue.toString() : null); + } + + public Builder host(final String host) { + this.host = host; + return this; + } + + public Builder port(final Integer port) { + this.port = port; + return this; + } + + 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 registerSerializer(final Class clazz, final VPackSerializer serializer) { + vpackBuilder.registerSerializer(clazz, serializer); + return this; + } + + public Builder registerDeserializer(final Class clazz, final VPackDeserializer deserializer) { + vpackBuilder.registerDeserializer(clazz, deserializer); + return this; + } + + public Builder regitserInstanceCreator(final Class clazz, final VPackInstanceCreator creator) { + vpackBuilder.regitserInstanceCreator(clazz, creator); + return this; + } + + public ArangoDB build() { + return new ArangoDB( + new CommunicationSync.Builder().host(host).port(port).timeout(timeout).user(user).password(password) + .useSsl(useSsl).sslContext(sslContext).chunksize(chunksize), + vpackBuilder.build(), vpackBuilder.serializeNullValues(true).build(), vpackParser, collectionCache); + } + + } + + public ArangoDB(final CommunicationSync.Builder commBuilder, final VPack vpack, final VPack vpackNull, + final VPackParser vpackParser, final CollectionCache collectionCache) { + super(new ArangoExecutorSync(commBuilder.build(vpack, collectionCache), vpack, vpackNull, vpackParser, + new DocumentCache(), collectionCache)); + final Communication cacheCom = commBuilder.build(vpack, collectionCache); + collectionCache.init(new DBAccess() { + @Override + public ArangoDatabase db(final String name) { + return new ArangoDatabase(cacheCom, vpackNull, vpack, vpackParser, executor.documentCache(), null, + name); + } + }); + } + + protected ArangoExecutorSync executor() { + return executor; + } + + public void shutdown() { + executor.communication().disconnect(); + } + + /** + * Returns a handler of the system database + * + * @return database handler + */ + public ArangoDatabase db() { + return db(ArangoDBConstants.SYSTEM); + } + + /** + * Returns a handler of the database by the given name + * + * @param name + * Name of the database + * @return database handler + */ + public ArangoDatabase db(final String name) { + return new ArangoDatabase(this, name); + } + + /** + * creates a new database + * + * @see API + * Documentation + * @param name + * Has to contain a valid database name + * @return true if the database was created successfully. + * @throws ArangoDBException + */ + public Boolean createDatabase(final String name) throws ArangoDBException { + return executor.execute(createDatabaseRequest(name), createDatabaseResponseDeserializer()); + } + + /** + * @see API + * Documentation + * @return a list of all existing databases + * @throws ArangoDBException + */ + public Collection getDatabases() throws ArangoDBException { + return executor.execute(getDatabasesRequest(db().name()), getDatabaseResponseDeserializer()); + } + + /** + * @see API + * Documentation + * @return a list of all databases the current user can access + * @throws ArangoDBException + */ + public Collection getAccessibleDatabases() throws ArangoDBException { + return executor.execute(getAccessibleDatabasesRequest(db().name()), getDatabaseResponseDeserializer()); + } + + /** + * Returns the server name and version number. + * + * @see API + * Documentation + * @return the server version, number + * @throws ArangoDBException + */ + public ArangoDBVersion getVersion() throws ArangoDBException { + return executor.execute(getVersionRequest(), ArangoDBVersion.class); + } + + /** + * 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 + */ + public UserEntity createUser(final String user, final String passwd) throws ArangoDBException { + return executor.execute(createUserRequest(db().name(), user, passwd, new UserCreateOptions()), + UserEntity.class); + } + + /** + * 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 + */ + 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); + } + + /** + * 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 + */ + public void deleteUser(final String user) throws ArangoDBException { + executor.execute(deleteUserRequest(db().name(), user), Void.class); + } + + /** + * 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 + */ + public UserEntity getUser(final String user) throws ArangoDBException { + return executor.execute(getUserRequest(db().name(), user), UserEntity.class); + } + + /** + * 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 + */ + public Collection getUsers() throws ArangoDBException { + return executor.execute(getUsersRequest(db().name()), getUsersResponseDeserializer()); + } + + /** + * 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 + */ + public UserEntity updateUser(final String user, final UserUpdateOptions options) throws ArangoDBException { + return executor.execute(updateUserRequest(db().name(), user, options), UserEntity.class); + } + + /** + * 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 + */ + public UserEntity replaceUser(final String user, final UserUpdateOptions options) throws ArangoDBException { + return executor.execute(replaceUserRequest(db().name(), user, options), UserEntity.class); + } + + /** + * Generic Execute. Use this method to execute custom FOXX services. + * + * @param request + * VelocyStream request + * @return VelocyStream response + * @throws ArangoDBException + */ + public Response execute(final Request request) throws ArangoDBException { + return executor.execute(request, new ResponseDeserializer() { + @Override + public Response deserialize(final Response response) throws VPackException { + return response; + } + }); + } + + /** + * 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 + */ + public LogEntity getLogs(final LogOptions options) throws ArangoDBException { + return executor.execute(getLogsRequest(options), LogEntity.class); + } + +} diff --git a/src/test/java/com/arangodb/TestInterfaceInstanceCreator.java b/src/main/java/com/arangodb/ArangoDBException.java similarity index 51% rename from src/test/java/com/arangodb/TestInterfaceInstanceCreator.java rename to src/main/java/com/arangodb/ArangoDBException.java index 3ef2b9206..4339e3f3b 100644 --- a/src/test/java/com/arangodb/TestInterfaceInstanceCreator.java +++ b/src/main/java/com/arangodb/ArangoDBException.java @@ -1,42 +1,39 @@ -/* - * Copyright (C) 2015 tporadowski - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb; - -import java.lang.reflect.Type; - -import com.google.gson.InstanceCreator; - -/** - * @author tporadowski - tomasz at poradowski.com - */ -public class TestInterfaceInstanceCreator implements - InstanceCreator { - - private int counter; - - @Override - public TestInterface createInstance(Type type) { - return new TestInterfaceImpl("name " + counter++); - } - - /** - * @return the counter - */ - public int getCounter() { - return counter; - } -} +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb; + +/** + * @author Mark - mark at arangodb.com + * + */ +public class ArangoDBException extends RuntimeException { + + private static final long serialVersionUID = 6165638002614173801L; + + public ArangoDBException(final String message) { + super(message); + } + + public ArangoDBException(final Throwable cause) { + super(cause); + } + +} diff --git a/src/main/java/com/arangodb/ArangoDatabase.java b/src/main/java/com/arangodb/ArangoDatabase.java new file mode 100644 index 000000000..0ba0cc288 --- /dev/null +++ b/src/main/java/com/arangodb/ArangoDatabase.java @@ -0,0 +1,634 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb; + +import java.util.Collection; +import java.util.Map; + +import com.arangodb.entity.AqlExecutionExplainEntity; +import com.arangodb.entity.AqlFunctionEntity; +import com.arangodb.entity.AqlParseEntity; +import com.arangodb.entity.CollectionEntity; +import com.arangodb.entity.CursorEntity; +import com.arangodb.entity.DatabaseEntity; +import com.arangodb.entity.EdgeDefinition; +import com.arangodb.entity.GraphEntity; +import com.arangodb.entity.IndexEntity; +import com.arangodb.entity.QueryCachePropertiesEntity; +import com.arangodb.entity.QueryEntity; +import com.arangodb.entity.QueryTrackingPropertiesEntity; +import com.arangodb.entity.TraversalEntity; +import com.arangodb.internal.ArangoCursorExecute; +import com.arangodb.internal.ArangoExecutorSync; +import com.arangodb.internal.CollectionCache; +import com.arangodb.internal.DocumentCache; +import com.arangodb.internal.InternalArangoDatabase; +import com.arangodb.internal.velocystream.Communication; +import com.arangodb.internal.velocystream.ConnectionSync; +import com.arangodb.model.AqlFunctionCreateOptions; +import com.arangodb.model.AqlFunctionDeleteOptions; +import com.arangodb.model.AqlFunctionGetOptions; +import com.arangodb.model.AqlQueryExplainOptions; +import com.arangodb.model.AqlQueryOptions; +import com.arangodb.model.CollectionCreateOptions; +import com.arangodb.model.CollectionsReadOptions; +import com.arangodb.model.DocumentReadOptions; +import com.arangodb.model.GraphCreateOptions; +import com.arangodb.model.TransactionOptions; +import com.arangodb.model.TraversalOptions; +import com.arangodb.velocypack.Type; +import com.arangodb.velocypack.VPack; +import com.arangodb.velocypack.VPackParser; +import com.arangodb.velocystream.Request; +import com.arangodb.velocystream.Response; + +/** + * @author Mark - mark at arangodb.com + * + */ +public class ArangoDatabase extends InternalArangoDatabase { + + protected ArangoDatabase(final ArangoDB arangoDB, final String name) { + super(arangoDB.executor(), name); + } + + protected ArangoDatabase(final Communication communication, final VPack vpacker, + final VPack vpackerNull, final VPackParser vpackParser, final DocumentCache documentCache, + final CollectionCache collectionCache, final String name) { + super(new ArangoExecutorSync(communication, vpacker, vpackerNull, vpackParser, documentCache, collectionCache), + name); + } + + protected ArangoExecutorSync executor() { + return executor; + } + + /** + * Returns a handler of the collection by the given name + * + * @param name + * Name of the collection + * @return collection handler + */ + public ArangoCollection collection(final String name) { + return new ArangoCollection(this, name); + } + + /** + * Creates a collection + * + * @see API + * Documentation + * @param name + * The name of the collection + * @return information about the collection + * @throws ArangoDBException + */ + public CollectionEntity createCollection(final String name) throws ArangoDBException { + return executor.execute(createCollectionRequest(name, new CollectionCreateOptions()), CollectionEntity.class); + } + + /** + * Creates a collection + * + * @see API + * Documentation + * @param name + * The name of the collection + * @param options + * Additional options, can be null + * @return information about the collection + * @throws ArangoDBException + */ + public CollectionEntity createCollection(final String name, final CollectionCreateOptions options) + throws ArangoDBException { + return executor.execute(createCollectionRequest(name, options), CollectionEntity.class); + } + + /** + * Returns all collections + * + * @see API + * Documentation + * @return list of information about all collections + * @throws ArangoDBException + */ + public Collection getCollections() throws ArangoDBException { + return executor.execute(getCollectionsRequest(new CollectionsReadOptions()), + getCollectionsResponseDeserializer()); + } + + /** + * Returns all collections + * + * @see API + * Documentation + * @param options + * Additional options, can be null + * @return list of information about all collections + * @throws ArangoDBException + */ + public Collection getCollections(final CollectionsReadOptions options) throws ArangoDBException { + return executor.execute(getCollectionsRequest(options), getCollectionsResponseDeserializer()); + } + + /** + * Returns an index + * + * @see API Documentation + * @param id + * The index-handle + * @return information about the index + * @throws ArangoDBException + */ + public IndexEntity getIndex(final String id) throws ArangoDBException { + return executor.execute(getIndexRequest(id), IndexEntity.class); + } + + /** + * Deletes an index + * + * @see API Documentation + * @param id + * The index-handle + * @return the id of the index + * @throws ArangoDBException + */ + public String deleteIndex(final String id) throws ArangoDBException { + return executor.execute(deleteIndexRequest(id), deleteIndexResponseDeserializer()); + } + + /** + * Drop an existing database + * + * @see API + * Documentation + * @return true if the database was dropped successfully + * @throws ArangoDBException + */ + public Boolean drop() throws ArangoDBException { + return executor.execute(dropRequest(), createDropResponseDeserializer()); + } + + /** + * Grants access to the database dbname for user user. You need permission to the _system database in order to + * execute this call. + * + * @see + * API Documentation + * @param user + * The name of the user + * @throws ArangoDBException + */ + public void grantAccess(final String user) throws ArangoDBException { + executor.execute(grantAccessRequest(user), Void.class); + } + + /** + * Revokes access to the database dbname for user user. You need permission to the _system database in order to + * execute this call. + * + * @see + * API Documentation + * @param user + * The name of the user + * @throws ArangoDBException + */ + public void revokeAccess(final String user) throws ArangoDBException { + executor.execute(revokeAccessRequest(user), Void.class); + } + + /** + * Create a cursor and return the first results + * + * @see API + * Documentation + * @param query + * contains the query string to be executed + * @param bindVars + * key/value pairs representing the bind parameters + * @param options + * Additional options, can be null + * @param type + * The type of the result (POJO class, VPackSlice, String for Json, or Collection/List/Map) + * @return cursor of the results + * @throws ArangoDBException + */ + 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 CursorEntity result = executor.execute(request, CursorEntity.class); + return new ArangoCursor(this, new ArangoCursorExecute() { + @Override + public CursorEntity next(final String id) { + return executor.execute(queryNextRequest(id), CursorEntity.class); + } + + @Override + public void close(final String id) { + executor.execute(queryCloseRequest(id), Void.class); + } + }, type, result); + } + + /** + * Explain an AQL query and return information about it + * + * @see API + * Documentation + * @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 + */ + public AqlExecutionExplainEntity explainQuery( + final String query, + final Map bindVars, + final AqlQueryExplainOptions options) throws ArangoDBException { + return executor.execute(explainQueryRequest(query, bindVars, options), AqlExecutionExplainEntity.class); + } + + /** + * 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)} + * + * @see API + * Documentation + * @param query + * the query which you want parse + * @return imformation about the query + * @throws ArangoDBException + */ + public AqlParseEntity parseQuery(final String query) throws ArangoDBException { + return executor.execute(parseQueryRequest(query), AqlParseEntity.class); + } + + /** + * Clears the AQL query cache + * + * @see API + * Documentation + * @throws ArangoDBException + */ + public void clearQueryCache() throws ArangoDBException { + executor.execute(clearQueryCacheRequest(), Void.class); + } + + /** + * Returns the global configuration for the AQL query cache + * + * @see API + * Documentation + * @return configuration for the AQL query cache + * @throws ArangoDBException + */ + public QueryCachePropertiesEntity getQueryCacheProperties() throws ArangoDBException { + return executor.execute(getQueryCachePropertiesRequest(), QueryCachePropertiesEntity.class); + } + + /** + * Changes the configuration for the AQL query cache. Note: changing the properties may invalidate all results in + * the cache. + * + * @see API + * Documentation + * @param properties + * properties to be set + * @return current set of properties + * @throws ArangoDBException + */ + public QueryCachePropertiesEntity setQueryCacheProperties(final QueryCachePropertiesEntity properties) + throws ArangoDBException { + return executor.execute(setQueryCachePropertiesRequest(properties), QueryCachePropertiesEntity.class); + } + + /** + * Returns the configuration for the AQL query tracking + * + * @see API + * Documentation + * @return configuration for the AQL query tracking + * @throws ArangoDBException + */ + public QueryTrackingPropertiesEntity getQueryTrackingProperties() throws ArangoDBException { + return executor.execute(getQueryTrackingPropertiesRequest(), QueryTrackingPropertiesEntity.class); + } + + /** + * Changes the configuration for the AQL query tracking + * + * @see API + * Documentation + * @param properties + * properties to be set + * @return current set of properties + * @throws ArangoDBException + */ + public QueryTrackingPropertiesEntity setQueryTrackingProperties(final QueryTrackingPropertiesEntity properties) + throws ArangoDBException { + return executor.execute(setQueryTrackingPropertiesRequest(properties), QueryTrackingPropertiesEntity.class); + } + + /** + * Returns a list of currently running AQL queries + * + * @see API + * Documentation + * @return a list of currently running AQL queries + * @throws ArangoDBException + */ + public Collection getCurrentlyRunningQueries() throws ArangoDBException { + return executor.execute(getCurrentlyRunningQueriesRequest(), new Type>() { + }.getType()); + } + + /** + * Returns a list of slow running AQL queries + * + * @see API + * Documentation + * @return a list of slow running AQL queries + * @throws ArangoDBException + */ + public Collection getSlowQueries() throws ArangoDBException { + return executor.execute(getSlowQueriesRequest(), new Type>() { + }.getType()); + } + + /** + * Clears the list of slow AQL queries + * + * @see API + * Documentation + * @throws ArangoDBException + */ + public void clearSlowQueries() throws ArangoDBException { + executor.execute(clearSlowQueriesRequest(), Void.class); + } + + /** + * Kills a running query. The query will be terminated at the next cancelation point. + * + * @see API + * Documentation + * @param id + * The id of the query + * @throws ArangoDBException + */ + public void killQuery(final String id) throws ArangoDBException { + executor.execute(killQueryRequest(id), Void.class); + } + + /** + * Create a new AQL user function + * + * @see API + * Documentation + * @param name + * the fully qualified name of the user functions + * @param code + * a string representation of the function body + * @param options + * Additional options, can be null + * @throws ArangoDBException + */ + public void createAqlFunction(final String name, final String code, final AqlFunctionCreateOptions options) + throws ArangoDBException { + executor.execute(createAqlFunctionRequest(name, code, options), Void.class); + } + + /** + * Remove an existing AQL user function + * + * @see API + * Documentation + * @param name + * the name of the AQL user function + * @param options + * Additional options, can be null + * @throws ArangoDBException + */ + public void deleteAqlFunction(final String name, final AqlFunctionDeleteOptions options) throws ArangoDBException { + executor.execute(deleteAqlFunctionRequest(name, options), Void.class); + } + + /** + * Gets all reqistered AQL user functions + * + * @see API + * Documentation + * @param options + * Additional options, can be null + * @return all reqistered AQL user functions + * @throws ArangoDBException + */ + public Collection getAqlFunctions(final AqlFunctionGetOptions options) throws ArangoDBException { + return executor.execute(getAqlFunctionsRequest(options), new Type>() { + }.getType()); + } + + /** + * Returns a handler of the graph by the given name + * + * @param name + * Name of the graph + * @return graph handler + */ + public ArangoGraph graph(final String name) { + return new ArangoGraph(this, 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. + * + * @see API + * Documentation + * @param name + * Name of the graph + * @param edgeDefinitions + * An array of definitions for the edge + * @return information about the graph + * @throws ArangoDBException + */ + public GraphEntity createGraph(final String name, final Collection edgeDefinitions) + throws ArangoDBException { + return executor.execute(createGraphRequest(name, edgeDefinitions, new GraphCreateOptions()), + createGraphResponseDeserializer()); + } + + /** + * 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. + * + * @see API + * Documentation + * @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 + */ + public GraphEntity createGraph( + final String name, + final Collection edgeDefinitions, + final GraphCreateOptions options) throws ArangoDBException { + return executor.execute(createGraphRequest(name, edgeDefinitions, options), createGraphResponseDeserializer()); + } + + /** + * Lists all graphs known to the graph module + * + * @see API + * Documentation + * @return graphs stored in this database + * @throws ArangoDBException + */ + public Collection getGraphs() throws ArangoDBException { + return executor.execute(getGraphsRequest(), getGraphsResponseDeserializer()); + } + + /** + * Execute a server-side transaction + * + * @see API + * Documentation + * @param action + * the actual transaction operations to be executed, in the form of stringified JavaScript code + * @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 + */ + public T transaction(final String action, final Class type, final TransactionOptions options) + throws ArangoDBException { + return executor.execute(transactionRequest(action, options), transactionResponseDeserializer(type)); + } + + /** + * Retrieves information about the current database + * + * @see API + * Documentation + * @return information about the current database + * @throws ArangoDBException + */ + public DatabaseEntity getInfo() throws ArangoDBException { + return executor.execute(getInfoRequest(), getInfoResponseDeserializer()); + } + + /** + * Execute a server-side traversal + * + * @see API + * Documentation + * @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 + */ + 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)); + } + + /** + * Reads a single document + * + * @see API + * Documentation + * @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 + */ + public T getDocument(final String id, final Class type) throws ArangoDBException { + executor.validateDocumentId(id); + final String[] split = id.split("/"); + return collection(split[0]).getDocument(split[1], type); + } + + /** + * Reads a single document + * + * @see API + * Documentation + * @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 + */ + public T getDocument(final String id, final Class type, final DocumentReadOptions options) + throws ArangoDBException { + executor.validateDocumentId(id); + final String[] split = id.split("/"); + return collection(split[0]).getDocument(split[1], type, options); + } + + /** + * Reload the routing table. + * + * @see API + * Documentation + * @throws ArangoDBException + */ + public void reloadRouting() throws ArangoDBException { + executor.execute(reloadRoutingRequest(), Void.class); + } + +} diff --git a/src/main/java/com/arangodb/ArangoDriver.java b/src/main/java/com/arangodb/ArangoDriver.java deleted file mode 100644 index 9370d6c0a..000000000 --- a/src/main/java/com/arangodb/ArangoDriver.java +++ /dev/null @@ -1,4183 +0,0 @@ -/* - * Copyright (C) 2012 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package com.arangodb; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Proxy; -import java.util.Collection; -import java.util.List; -import java.util.Map; - -import com.arangodb.entity.AdminLogEntity; -import com.arangodb.entity.AqlFunctionsEntity; -import com.arangodb.entity.ArangoUnixTime; -import com.arangodb.entity.ArangoVersion; -import com.arangodb.entity.BatchResponseEntity; -import com.arangodb.entity.BooleanResultEntity; -import com.arangodb.entity.CollectionEntity; -import com.arangodb.entity.CollectionKeyOption; -import com.arangodb.entity.CollectionOptions; -import com.arangodb.entity.CollectionsEntity; -import com.arangodb.entity.CursorEntity; -import com.arangodb.entity.DatabaseEntity; -import com.arangodb.entity.DefaultEntity; -import com.arangodb.entity.DeletedEntity; -import com.arangodb.entity.DocumentEntity; -import com.arangodb.entity.EdgeDefinitionEntity; -import com.arangodb.entity.EdgeEntity; -import com.arangodb.entity.Endpoint; -import com.arangodb.entity.GraphEntity; -import com.arangodb.entity.GraphsEntity; -import com.arangodb.entity.ImportResultEntity; -import com.arangodb.entity.IndexEntity; -import com.arangodb.entity.IndexType; -import com.arangodb.entity.IndexesEntity; -import com.arangodb.entity.JobsEntity; -import com.arangodb.entity.PlainEdgeEntity; -import com.arangodb.entity.QueriesResultEntity; -import com.arangodb.entity.QueryCachePropertiesEntity; -import com.arangodb.entity.QueryTrackingPropertiesEntity; -import com.arangodb.entity.ReplicationApplierConfigEntity; -import com.arangodb.entity.ReplicationApplierStateEntity; -import com.arangodb.entity.ReplicationInventoryEntity; -import com.arangodb.entity.ReplicationLoggerConfigEntity; -import com.arangodb.entity.ReplicationLoggerStateEntity; -import com.arangodb.entity.ReplicationSyncEntity; -import com.arangodb.entity.RestrictType; -import com.arangodb.entity.ScalarExampleEntity; -import com.arangodb.entity.ShortestPathEntity; -import com.arangodb.entity.SimpleByResultEntity; -import com.arangodb.entity.StatisticsDescriptionEntity; -import com.arangodb.entity.StatisticsEntity; -import com.arangodb.entity.StringsResultEntity; -import com.arangodb.entity.TransactionEntity; -import com.arangodb.entity.TransactionResultEntity; -import com.arangodb.entity.TraversalEntity; -import com.arangodb.entity.UserEntity; -import com.arangodb.entity.marker.VertexEntity; -import com.arangodb.http.BatchHttpManager; -import com.arangodb.http.BatchPart; -import com.arangodb.http.HttpManager; -import com.arangodb.http.HttpResponseEntity; -import com.arangodb.http.InvocationHandlerImpl; -import com.arangodb.impl.ImplFactory; -import com.arangodb.impl.InternalBatchDriverImpl; -import com.arangodb.util.AqlQueryOptions; -import com.arangodb.util.DumpHandler; -import com.arangodb.util.GraphEdgesOptions; -import com.arangodb.util.GraphQueryUtil; -import com.arangodb.util.GraphVerticesOptions; -import com.arangodb.util.ImportOptions; -import com.arangodb.util.ImportOptionsJson; -import com.arangodb.util.ImportOptionsRaw; -import com.arangodb.util.MapBuilder; -import com.arangodb.util.ShortestPathOptions; -import com.arangodb.util.TraversalQueryOptions; - -/** - * ArangoDB driver. All of the functionality to use ArangoDB is provided via - * this class. - * - * @author tamtam180 - kirscheless at gmail.com - * @author gschwab - * @author fbartels - * @author a-brandt - * - * @version 2.2. - * - * @see ArangoDB - * documentation - */ -public class ArangoDriver extends BaseArangoDriver { - - private static final String DATABASE_SYSTEM = "_system"; - private static final String COLLECTION_USERS = "_users"; - private final ArangoConfigure configure; - private final BatchHttpManager httpManager; - - private InternalCursorDriver cursorDriver; - private InternalBatchDriverImpl batchDriver; - private InternalCollectionDriver collectionDriver; - private InternalDocumentDriver documentDriver; - private InternalIndexDriver indexDriver; - private InternalAdminDriver adminDriver; - private InternalJobsDriver jobsDriver; - private InternalAqlFunctionsDriver aqlFunctionsDriver; - private InternalSimpleDriver simpleDriver; - private InternalUsersDriver usersDriver; - private InternalImportDriver importDriver; - private InternalDatabaseDriver databaseDriver; - private InternalEndpointDriver endpointDriver; - private InternalReplicationDriver replicationDriver; - private InternalGraphDriver graphDriver; - private InternalTransactionDriver transactionDriver; - private InternalTraversalDriver traversalDriver; - private InternalQueryCacheDriver queryCacheDriver; - - private String database; - - /** - * Constructor to create an instance of the driver that uses the default - * database. - * - * @param configure - * A configuration object. - */ - public ArangoDriver(final ArangoConfigure configure) { - this(configure, null); - } - - /** - * Constructor to create an instance of the driver that uses the provided - * database. - * - * @param configure - * A configuration object. - * @param database - * the name of the database that will be used. - */ - public ArangoDriver(final ArangoConfigure configure, final String database) { - - this.database = configure.getDefaultDatabase(); - if (database != null) { - this.database = database; - } - - this.configure = configure; - this.httpManager = configure.getHttpManager(); - this.createModuleDrivers(false); - } - - /** - * This method enables batch execution. Until 'cancelBatchMode' or - * 'executeBatch' is called every other call is stacked and will be either - * executed or discarded when the batch mode is canceled. Each call will - * return a 'requestId' in the HTTP response, that can be used to select the - * matching result from the batch execution. - * - * @see com.arangodb.ArangoDriver#cancelBatchMode() - * @see ArangoDriver#executeBatch() - * @see ArangoDriver#getBatchResponseByRequestId(String) - * @throws com.arangodb.ArangoException - */ - public void startBatchMode() throws ArangoException { - if (this.httpManager.isBatchModeActive()) { - throw new ArangoException("BatchMode is already active."); - } - this.httpManager.emptyCallStack(); - this.httpManager.setBatchModeActive(true); - this.createModuleDrivers(true); - - } - - /** - * This method sets the driver to asynchronous execution. If the parameter - * 'fireAndforget' is set to true each call to ArangoDB will be send without - * a return value. If set to false the return value will be the 'job id'. - * Each job result can be received by the method 'getJobResult'. - * - * @param fireAndForget - * if set to true the asynchronous mode is set to 'fire and - * forget'. - * @see ArangoDriver#stopAsyncMode() - * @see com.arangodb.ArangoDriver#getJobResult(String) - * @see com.arangodb.ArangoDriver#getJobs(com.arangodb.entity.JobsEntity.JobState, - * int) - * @see com.arangodb.ArangoDriver#deleteExpiredJobs(int) - * @see ArangoDriver#getLastJobId() - * @throws com.arangodb.ArangoException - */ - public void startAsyncMode(final boolean fireAndForget) throws ArangoException { - if (this.httpManager.getHttpMode().equals(HttpManager.HttpMode.ASYNC) - || this.httpManager.getHttpMode().equals(HttpManager.HttpMode.FIREANDFORGET)) { - throw new ArangoException("Arango driver already set to asynchronous mode."); - } - final HttpManager.HttpMode mode = fireAndForget ? HttpManager.HttpMode.FIREANDFORGET - : HttpManager.HttpMode.ASYNC; - this.httpManager.setHttpMode(mode); - this.createModuleDrivers(true); - this.httpManager.resetJobs(); - } - - /** - * This method sets the driver back to synchronous execution. - * - * @see ArangoDriver#startAsyncMode(boolean) - * @see com.arangodb.ArangoDriver#getJobResult(String) - * @see com.arangodb.ArangoDriver#getJobs(com.arangodb.entity.JobsEntity.JobState, - * int) - * @see com.arangodb.ArangoDriver#deleteExpiredJobs(int) - * @see ArangoDriver#getLastJobId() - * @throws com.arangodb.ArangoException - */ - public void stopAsyncMode() throws ArangoException { - if (this.httpManager.getHttpMode().equals(HttpManager.HttpMode.SYNC)) { - throw new ArangoException("Arango driver already set to synchronous mode."); - } - this.httpManager.setHttpMode(HttpManager.HttpMode.SYNC); - this.createModuleDrivers(false); - } - - /** - * Returns the identifier of the last asynchronous executed job. - * - * @return String the identifier - * @see ArangoDriver#startAsyncMode(boolean) - * @see ArangoDriver#stopAsyncMode() - * @see com.arangodb.ArangoDriver#getJobResult(String) - * @see com.arangodb.ArangoDriver#getJobs(com.arangodb.entity.JobsEntity.JobState, - * int) - * @see com.arangodb.ArangoDriver#deleteExpiredJobs(int) - * @see ArangoDriver#getLastJobId() - */ - public String getLastJobId() { - return this.httpManager.getLastJobId(); - } - - /** - * Returns a list of all job identifiers of asynchronous executed jobs. - * - * @return List the list of all job identifiers - * @see ArangoDriver#startAsyncMode(boolean) - * @see ArangoDriver#stopAsyncMode() - * @see com.arangodb.ArangoDriver#getJobResult(String) - * @see com.arangodb.ArangoDriver#getJobs(com.arangodb.entity.JobsEntity.JobState, - * int) - * @see com.arangodb.ArangoDriver#deleteExpiredJobs(int) - * @see ArangoDriver#getLastJobId() - */ - public List getJobIds() { - return this.httpManager.getJobIds(); - } - - /** - * Returns a list of all job identifiers of asynchronous executed jobs, - * filtered by job state. - * - * @param jobState - * the job state as a filter. - * @param count - * a limit for the result set. - * @return List list of all job identifiers - * @see ArangoDriver#startAsyncMode(boolean) - * @see ArangoDriver#stopAsyncMode() - * @see com.arangodb.ArangoDriver#getJobResult(String) - * @see com.arangodb.ArangoDriver#getJobIds() - * @see com.arangodb.ArangoDriver#deleteExpiredJobs(int) - * @see ArangoDriver#getLastJobId() - */ - public List getJobs(final JobsEntity.JobState jobState, final int count) throws ArangoException { - return this.jobsDriver.getJobs(getDefaultDatabase(), jobState, count); - } - - /** - * Returns a list of all job identifiers of asynchronous executed jobs, - * filtered by job state. - * - * - * @param jobState - * the job state as a filter. - * @return List list of all job identifiers - * @see ArangoDriver#startAsyncMode(boolean) - * @see ArangoDriver#stopAsyncMode() - * @see com.arangodb.ArangoDriver#getJobResult(String) - * @see com.arangodb.ArangoDriver#getJobIds() - * @see com.arangodb.ArangoDriver#deleteExpiredJobs(int) - * @see ArangoDriver#getLastJobId() - */ - public List getJobs(final JobsEntity.JobState jobState) throws ArangoException { - return this.jobsDriver.getJobs(getDefaultDatabase(), jobState); - } - - /** - * Deletes all job from ArangoDB. - * - * @see ArangoDriver#startAsyncMode(boolean) - * @see ArangoDriver#stopAsyncMode() - * @see com.arangodb.ArangoDriver#getJobResult(String) - * @see com.arangodb.ArangoDriver#getJobIds() - * @see com.arangodb.ArangoDriver#deleteExpiredJobs(int) - * @see ArangoDriver#getLastJobId() - */ - public void deleteAllJobs() throws ArangoException { - this.jobsDriver.deleteAllJobs(getDefaultDatabase()); - this.httpManager.resetJobs(); - } - - /** - * Deletes a job from ArangoDB. - * - * @param jobId - * the identifier of the job - * @see ArangoDriver#startAsyncMode(boolean) - * @see ArangoDriver#stopAsyncMode() - * @see com.arangodb.ArangoDriver#getJobResult(String) - * @see com.arangodb.ArangoDriver#getJobIds() - * @see com.arangodb.ArangoDriver#deleteExpiredJobs(int) - * @see ArangoDriver#getLastJobId() - */ - public void deleteJobById(final String jobId) throws ArangoException { - this.jobsDriver.deleteJobById(getDefaultDatabase(), jobId); - } - - /** - * Deletes all jobs by a provided expiration date. - * - * @param timeStamp - * a unix timestamp, every older job is deleted. - * @see ArangoDriver#startAsyncMode(boolean) - * @see ArangoDriver#stopAsyncMode() - * @see com.arangodb.ArangoDriver#getJobResult(String) - * @see com.arangodb.ArangoDriver#getJobIds() - * @see com.arangodb.ArangoDriver#deleteExpiredJobs(int) - * @see ArangoDriver#getLastJobId() - */ - public void deleteExpiredJobs(final int timeStamp) throws ArangoException { - this.jobsDriver.deleteExpiredJobs(getDefaultDatabase(), timeStamp); - } - - /** - * Returns the job result for a given job id. - * - * @param jobId - * the job id. - * @return - A generic return value, containing the job result - * @see ArangoDriver#startAsyncMode(boolean) - * @see ArangoDriver#stopAsyncMode() - * @see com.arangodb.ArangoDriver#getJobResult(String) - * @see com.arangodb.ArangoDriver#getJobIds() - * @see com.arangodb.ArangoDriver#deleteExpiredJobs(int) - * @see ArangoDriver#getLastJobId() - */ - public T getJobResult(final String jobId) throws ArangoException { - return this.jobsDriver.getJobResult(getDefaultDatabase(), jobId); - } - - /** - * This method sends all stacked requests as batch to ArangoDB. - * - * @see ArangoDriver#startBatchMode() - * @see com.arangodb.ArangoDriver#cancelBatchMode() - * @throws com.arangodb.ArangoException - */ - public DefaultEntity executeBatch() throws ArangoException { - if (!this.httpManager.isBatchModeActive()) { - throw new ArangoException("BatchMode is not active."); - } - final List callStack = this.httpManager.getCallStack(); - this.cancelBatchMode(); - return this.batchDriver.executeBatch(callStack, this.getDefaultDatabase()); - } - - /** - * This method returns the result of a call to ArangoDB executed within a - * batch request. - * - * @param requestId - * the id of a request. - * @return - A generic return value, containing the result. - * @see ArangoDriver#startBatchMode() - * @see ArangoDriver#executeBatch() - * @see com.arangodb.ArangoDriver#cancelBatchMode() - * @throws com.arangodb.ArangoException - */ - @SuppressWarnings("unchecked") - public T getBatchResponseByRequestId(final String requestId) throws ArangoException { - final BatchResponseEntity batchResponseEntity = this.batchDriver.getBatchResponseListEntity() - .getResponseFromRequestId(requestId); - try { - this.httpManager.setPreDefinedResponse(batchResponseEntity.getHttpResponseEntity()); - - final T result = (T) batchResponseEntity.getInvocationObject().getMethod().invoke( - batchResponseEntity.getInvocationObject().getArangoDriver(), - batchResponseEntity.getInvocationObject().getArgs()); - this.httpManager.setPreDefinedResponse(null); - return result; - } catch (final InvocationTargetException e) { - this.httpManager.setPreDefinedResponse(null); - - HttpResponseEntity httpResponse = batchResponseEntity.getHttpResponseEntity(); - if (httpResponse.getStatusCode() >= 300) { - DefaultEntity de = new DefaultEntity(); - de.setCode(httpResponse.getStatusCode()); - de.setError(true); - if (httpResponse.getText() != null) { - de.setErrorMessage(httpResponse.getText().trim()); - } - de.setErrorNumber(httpResponse.getStatusCode()); - throw new ArangoException(de); - } - - final T result = (T) createEntity(batchResponseEntity.getHttpResponseEntity(), DefaultEntity.class); - return result; - } catch (final Exception e) { - this.httpManager.setPreDefinedResponse(null); - throw new ArangoException(e); - } - } - - /** - * This method cancels the batch execution mode. All stacked calls are - * discarded. - * - * @see ArangoDriver#startBatchMode() - * @see ArangoDriver#executeBatch() - * @throws com.arangodb.ArangoException - */ - public void cancelBatchMode() throws ArangoException { - if (!this.httpManager.isBatchModeActive()) { - throw new ArangoException("BatchMode is not active."); - } - this.httpManager.setBatchModeActive(false); - this.createModuleDrivers(false); - this.httpManager.emptyCallStack(); - this.httpManager.setPreDefinedResponse(null); - } - - /** - * Returns the default database. - * - * @return String - */ - public String getDefaultDatabase() { - return database; - } - - /** - * Sets the default database. - * - * @param database - */ - public void setDefaultDatabase(final String database) { - this.database = database; - } - - /** - * Creates a new collection. - * - * @param name - * the name of the collection - * @return CollectionEntity - the created collectionEntity. - * @throws ArangoException - */ - public CollectionEntity createCollection(final String name) throws ArangoException { - return collectionDriver.createCollection(getDefaultDatabase(), name, new CollectionOptions()); - } - - /** - * Creates a new collection. - * - * @param name - * the name of the collection - * @param collectionOptions - * an object containing the various options. - * @return CollectionEntity - the created collectionEntity. - * @throws ArangoException - */ - public CollectionEntity createCollection(final String name, final CollectionOptions collectionOptions) - throws ArangoException { - return collectionDriver.createCollection(getDefaultDatabase(), name, collectionOptions); - } - - /** - * Returns a collection from ArangoDB by name - * - * @param name - * the name of the collection. - * @return CollectionEntity - the requested collectionEntity. - * @throws ArangoException - */ - public CollectionEntity getCollection(final String name) throws ArangoException { - return collectionDriver.getCollection(getDefaultDatabase(), name); - } - - /** - * Returns a collection from ArangoDB including all properties by name - * - * @param name - * the name of the collection. - * @return CollectionEntity - the requested collectionEntity. - * @throws ArangoException - */ - public CollectionEntity getCollectionProperties(final String name) throws ArangoException { - return collectionDriver.getCollectionProperties(getDefaultDatabase(), name); - } - - /** - * Returns a collection from ArangoDB by name including the document count - * - * @param name - * the name of the collection. - * @return CollectionEntity - the requested collectionEntity. - * @throws ArangoException - */ - public CollectionEntity getCollectionCount(final String name) throws ArangoException { - return collectionDriver.getCollectionCount(getDefaultDatabase(), name); - } - - /** - * Returns a collection from ArangoDB by name including the collection - * figures - * - * @param name - * the name of the collection. - * @return CollectionEntity - the requested collectionEntity. - * @throws ArangoException - */ - public CollectionEntity getCollectionFigures(final String name) throws ArangoException { - return collectionDriver.getCollectionFigures(getDefaultDatabase(), name); - } - - /** - * Returns a collection from ArangoDB by name including the collection - * checksum - * - * @param name - * the id of the collection. - * @param withRevisions - * includes the revision into the checksum calculation - * @param withData - * includes the collections data into the checksum calculation - * @return CollectionEntity - the requested collectionEntity. - * @throws ArangoException - */ - public CollectionEntity getCollectionChecksum( - final String name, - final Boolean withRevisions, - final Boolean withData) throws ArangoException { - return collectionDriver.getCollectionChecksum(getDefaultDatabase(), name, withRevisions, withData); - } - - /** - * Returns all collections from ArangoDB - * - * @return CollectionsEntity - the CollectionsEntity. - * @throws ArangoException - */ - public CollectionsEntity getCollections() throws ArangoException { - return collectionDriver.getCollections(getDefaultDatabase(), null); - } - - /** - * Returns all collections from ArangoDB - * - * @param excludeSystem - * if set to true system collections will not be added to the - * result - * @return CollectionsEntity - the CollectionsEntity. - * @throws ArangoException - */ - public CollectionsEntity getCollections(final Boolean excludeSystem) throws ArangoException { - return collectionDriver.getCollections(getDefaultDatabase(), excludeSystem); - } - - /** - * Returns the collection and loads it into memory. - * - * @param name - * the name of the collection. - * @return CollectionEntity - the collectionEntity. - * @throws ArangoException - */ - public CollectionEntity loadCollection(final String name) throws ArangoException { - return collectionDriver.loadCollection(getDefaultDatabase(), name, null); - } - - /** - * Returns the collection and loads it into memory. - * - * @param name - * the name of the collection. - * @param count - * if set to true the documents count is returned. - * @return CollectionEntity - the collectionEntity. - * @throws ArangoException - */ - public CollectionEntity loadCollection(final String name, final Boolean count) throws ArangoException { - return collectionDriver.loadCollection(getDefaultDatabase(), name, count); - } - - /** - * Returns the collection and deletes it from memory. - * - * @param name - * the name of the collection. - * @return CollectionEntity - the collectionEntity. - * @throws ArangoException - */ - public CollectionEntity unloadCollection(final String name) throws ArangoException { - return collectionDriver.unloadCollection(getDefaultDatabase(), name); - } - - /** - * Returns the collection and deletes all documents. - * - * @param name - * the name of the collection. - * @return CollectionEntity - the collectionEntity. - * @throws ArangoException - */ - public CollectionEntity truncateCollection(final String name) throws ArangoException { - return collectionDriver.truncateCollection(getDefaultDatabase(), name); - } - - /** - * Returns the collection and changes it's journalSize and waitForSync. - * - * @param name - * the name of the collection. - * @param newWaitForSync - * a new value for the waitForSyncProperty - * @param journalSize - * a new value for the collections journalSize - * @return CollectionEntity - the collectionEntity. - * @throws ArangoException - */ - public CollectionEntity setCollectionProperties( - final String name, - final Boolean newWaitForSync, - final Long journalSize) throws ArangoException { - return collectionDriver.setCollectionProperties(getDefaultDatabase(), name, newWaitForSync, journalSize); - } - - /** - * Returns the collection and changes it's name. - * - * @param name - * the name of the collection. - * @param newName - * the new name for the collection - * @return CollectionEntity - the collectionEntity. - * @throws ArangoException - */ - public CollectionEntity renameCollection(final String name, final String newName) throws ArangoException { - return collectionDriver.renameCollection(getDefaultDatabase(), name, newName); - } - - /** - * Deletes a collection by name. - * - * @param name - * the name of the collection. - * @return CollectionEntity - the collectionEntity. - * @throws ArangoException - */ - public CollectionEntity deleteCollection(final String name) throws ArangoException { - return collectionDriver.deleteCollection(getDefaultDatabase(), name); - } - - /** - * Creates a document in the collection defined by the collection's name - * - * @param collectionName - * The name of the collection - * @param value - * An object containing the documents attributes - * @return DocumentEntity - * @throws ArangoException - */ - public DocumentEntity createDocument(final String collectionName, final T value) throws ArangoException { - return documentDriver.createDocument(getDefaultDatabase(), collectionName, null, value, null); - } - - /** - * Creates a document in the collection defined by the collection's name. - * This method allows to define to documents key. Note that the collection's - * property CollectionKeyOption.allowUserKeys has to be set accordingly. - * - * @param collectionName - * The name of the collection - * @param documentKey - * the desired document key - * @param value - * An object containing the documents attributes - * @return DocumentEntity - * @throws ArangoException - * @see CollectionKeyOption#allowUserKeys - */ - public DocumentEntity createDocument(final String collectionName, final String documentKey, final T value) - throws ArangoException { - return documentDriver.createDocument(getDefaultDatabase(), collectionName, documentKey, value, null); - } - - /** - * Creates a document in the collection defined by the collection's name. - * - * @param collectionName - * The name of the collection - * @param value - * An object containing the documents attributes - * @param waitForSync - * if set to true the response is returned when the server has - * finished. - * @return DocumentEntity - * @throws ArangoException - * @see CollectionKeyOption#allowUserKeys - */ - public DocumentEntity createDocument(final String collectionName, final T value, final Boolean waitForSync) - throws ArangoException { - return documentDriver.createDocument(getDefaultDatabase(), collectionName, null, value, waitForSync); - } - - /** - * Creates a document in the collection defined by the collection's name. - * This method allows to define to documents key. Note that the collection's - * property CollectionKeyOption.allowUserKeys has to be set accordingly. - * - * @param collectionName - * The name of the collection - * @param documentKey - * the desired document key - * @param value - * An object containing the documents attributes - * @param waitForSync - * if set to true the response is returned when the server has - * finished. - * @return DocumentEntity - * @throws ArangoException - * @see CollectionKeyOption#allowUserKeys - */ - public DocumentEntity createDocument( - final String collectionName, - final String documentKey, - final T value, - final Boolean waitForSync) throws ArangoException { - return documentDriver.createDocument(getDefaultDatabase(), collectionName, documentKey, value, waitForSync); - } - - /** - * This method replaces the content of the document defined by documentKey. - * - * @param collectionName - * The collection's name. - * @param documentKey - * The document's key. - * @param value - * An object containing the documents attributes - * @return DocumentEntity - * @throws ArangoException - */ - public DocumentEntity replaceDocument(final String collectionName, final String documentKey, final T value) - throws ArangoException { - return replaceDocument(createDocumentHandle(collectionName, documentKey), value, null, null); - } - - /** - * This method replaces the content of the document defined by - * documentHandle. - * - * @param documentHandle - * The document handle. - * @param value - * An object containing the documents attributes - * @return DocumentEntity - * @throws ArangoException - */ - public DocumentEntity replaceDocument(final String documentHandle, final T value) throws ArangoException { - return documentDriver.replaceDocument(getDefaultDatabase(), documentHandle, value, null, null); - } - - /** - * This method replaces the content of the document defined by documentKey. - * This method offers a parameter rev (revision). If the revision of the - * document on the server does not match the given revision an error is - * thrown. - * - * @param collectionName - * The collection's name. - * @param documentKey - * The document's key. - * @param value - * An object containing the new attributes of the document. - * @param rev - * the desired revision. - * @param waitForSync - * if set to true the response is returned when the server has - * finished. - * @return a DocumentEntity object - * @throws ArangoException - */ - public DocumentEntity replaceDocument( - final String collectionName, - final String documentKey, - final Object value, - final String rev, - final Boolean waitForSync) throws ArangoException { - return replaceDocument(createDocumentHandle(collectionName, documentKey), value, rev, waitForSync); - } - - /** - * This method replaces the content of the document defined by - * documentHandle. This method offers a parameter rev (revision). If the - * revision of the document on the server does not match the given revision - * an error is thrown. - * - * @param documentHandle - * The document's handle. - * @param value - * An object containing the new attributes of the document. - * @param rev - * the desired revision. - * @param waitForSync - * if set to true the response is returned when the server has - * finished. - * @return a DocumentEntity object - * @throws ArangoException - */ - public DocumentEntity replaceDocument( - final String documentHandle, - final T value, - final String rev, - final Boolean waitForSync) throws ArangoException { - return documentDriver.replaceDocument(getDefaultDatabase(), documentHandle, value, rev, waitForSync); - } - - /** - * This method updates a document defined by documentKey. - * - * @param collectionName - * The collection's name. - * @param documentKey - * The document's key. - * @param value - * An object containing the documents attributes - * @return DocumentEntity - * @throws ArangoException - */ - public DocumentEntity updateDocument(final String collectionName, final String documentKey, final Object value) - throws ArangoException { - return updateDocument(createDocumentHandle(collectionName, documentKey), value, null, null, null); - } - - /** - * This method updates a document defined by documentHandle. - * - * @param documentHandle - * The document's handle. - * @param value - * An object containing the documents attributes - * @return DocumentEntity - * @throws ArangoException - */ - public DocumentEntity updateDocument(final String documentHandle, final T value) throws ArangoException { - return documentDriver.updateDocument(getDefaultDatabase(), documentHandle, value, null, null, null); - } - - /** - * This method updates a document defined by documentKey. - * - * @param collectionName - * The collection name. - * @param documentKey - * The document key. - * @param value - * An object containing the documents attributes - * @param keepNull - * If true null values are kept. - * @return DocumentEntity - * @throws ArangoException - */ - public DocumentEntity updateDocument( - final String collectionName, - final String documentKey, - final Object value, - final Boolean keepNull) throws ArangoException { - return updateDocument(createDocumentHandle(collectionName, documentKey), value, null, null, keepNull); - } - - /** - * This method updates a document defined by documentKey. - * - * @param documentHandle - * The document handle. - * @param value - * An object containing the documents attributes - * @param keepNull - * If true null values are kept. - * @return DocumentEntity - * @throws ArangoException - */ - public DocumentEntity updateDocument(final String documentHandle, final T value, final Boolean keepNull) - throws ArangoException { - return documentDriver.updateDocument(getDefaultDatabase(), documentHandle, value, null, null, keepNull); - } - - /** - * This method updates a document defined by documentKey. This method offers - * a parameter rev (revision). If the revision of the document on the server - * does not match the given revision an error is thrown. - * - * @param collectionName - * The collection name. - * @param documentKey - * The document key. - * @param value - * An object containing the documents attributes - * @param rev - * The desired revision - * @param waitForSync - * if set to true the response is returned when the server has - * finished. - * @param keepNull - * If true null values are kept. - * @return a DocumentEntity object - * @throws ArangoException - */ - public DocumentEntity updateDocument( - final String collectionName, - final String documentKey, - final Object value, - final String rev, - final Boolean waitForSync, - final Boolean keepNull) throws ArangoException { - return updateDocument(createDocumentHandle(collectionName, documentKey), value, rev, waitForSync, keepNull); - } - - /** - * This method updates a document defined by documentHandle. This method - * offers a parameter rev (revision). If the revision of the document on the - * server does not match the given revision an error is thrown. - * - * @param documentHandle - * The document handle. - * @param value - * An object containing the documents attributes - * @param rev - * The desired revision - * @param waitForSync - * if set to true the response is returned when the server has - * finished. - * @param keepNull - * If true null values are kept. - * @return DocumentEntity - * @throws ArangoException - */ - public DocumentEntity updateDocument( - final String documentHandle, - final T value, - final String rev, - final Boolean waitForSync, - final Boolean keepNull) throws ArangoException { - return documentDriver.updateDocument(getDefaultDatabase(), documentHandle, value, rev, waitForSync, keepNull); - } - - /** - * This method returns all document handles from a collection. - * - * @param collectionName - * The collection name. - * @return List - The list of document handles - * @throws ArangoException - */ - public List getDocuments(final String collectionName) throws ArangoException { - return documentDriver.getDocuments(getDefaultDatabase(), collectionName); - } - - /** - * The exists method determines whether a document exists given its - * identifier. Instead of returning the found document or an error, this - * method will return either true or false. It can thus be used for easy - * existence checks. - * - * @param collectionName - * The collection name. - * @param documentKey - * The document key - * @return true, if the document exists - * @throws ArangoException - */ - public boolean exists(final String collectionName, final String documentKey) throws ArangoException { - return exists(createDocumentHandle(collectionName, documentKey)); - } - - /** - * The exists method determines whether a document exists given its - * identifier. Instead of returning the found document or an error, this - * method will return either true or false. It can thus be used for easy - * existence checks. - * - * @param documentHandle - * The document handle - * @return true, if the document exists - * @throws ArangoException - */ - public boolean exists(final String documentHandle) throws ArangoException { - try { - documentDriver.checkDocument(getDefaultDatabase(), documentHandle); - } catch (final ArangoException e) { - if (e.getCode() == ErrorNums.ERROR_HTTP_NOT_FOUND) { - return false; - } - throw e; - } - return true; - } - - /** - * This method returns the current revision of a document. - * - * @param collectionName - * The collection name. - * @param documentKey - * The document key - * @return the document revision number - * @throws ArangoException - */ - public String checkDocument(final String collectionName, final String documentKey) throws ArangoException { - return checkDocument(createDocumentHandle(collectionName, documentKey)); - } - - /** - * This method returns the current revision of a document. - * - * @param documentHandle - * The document handle - * @return the document revision number - * @throws ArangoException - */ - public String checkDocument(final String documentHandle) throws ArangoException { - return documentDriver.checkDocument(getDefaultDatabase(), documentHandle); - } - - /** - * Returns a document entity. - * - * @param collectionName - * The collection name. - * @param documentKey - * The document key - * @param clazz - * The expected class, the result from the server request is - * deserialized to an instance of this class. - * @return a DocumentEntity object - * @throws ArangoException - */ - public DocumentEntity getDocument( - final String collectionName, - final String documentKey, - final Class clazz) throws ArangoException { - return getDocument(createDocumentHandle(collectionName, documentKey), clazz); - } - - /** - * Returns a document entity. - * - * @param documentHandle - * The document handle - * @param clazz - * The expected class, the result from the server request is - * deserialized to an instance of this class. - * @return a DocumentEntity object - * @throws ArangoException - */ - public DocumentEntity getDocument(final String documentHandle, final Class clazz) throws ArangoException { - return documentDriver.getDocument(getDefaultDatabase(), documentHandle, clazz, null, null); - } - - /** - * Returns a document entity. Note that the *ifNoneMatchRevision* and - * *ifMatchRevision* can not be used at the same time, one of these two has - * to be null. - * - * @param documentHandle - * The document handle - * @param clazz - * The expected class, the result from the server request is - * deserialized to an instance of this class. - * @param ifNoneMatchRevision - * if set the document is only returned id it has a different - * revision. - * @param ifMatchRevision - * if set the document is only returned id it has the same - * revision. - * @return a DocumentEntity object - * @throws ArangoException - */ - public DocumentEntity getDocument( - final String documentHandle, - final Class clazz, - final String ifNoneMatchRevision, - final String ifMatchRevision) throws ArangoException { - return documentDriver.getDocument(getDefaultDatabase(), documentHandle, clazz, ifNoneMatchRevision, - ifMatchRevision); - } - - /** - * Deletes a document from the database. - * - * @param collectionName - * The collection name. - * @param documentKey - * The document key. - * @return a DocumentEntity object - * @throws ArangoException - */ - public DocumentEntity deleteDocument(final String collectionName, final String documentKey) - throws ArangoException { - return deleteDocument(createDocumentHandle(collectionName, documentKey)); - } - - /** - * Deletes a document from the database. - * - * @param documentHandle - * The document handle. - * @return a DocumentEntity object - * @throws ArangoException - */ - public DocumentEntity deleteDocument(final String documentHandle) throws ArangoException { - return documentDriver.deleteDocument(getDefaultDatabase(), documentHandle, null); - } - - /** - * Deletes a document from the database. This method offers a parameter rev - * (revision). If the revision of the document on the server does not match - * the given revision an error is thrown. - * - * @param collectionName - * The collection name. - * @param documentKey - * The document key. - * @param rev - * The desired revision - * @return a DocumentEntity object - * @throws ArangoException - */ - public DocumentEntity deleteDocument(final String collectionName, final String documentKey, final String rev) - throws ArangoException { - return deleteDocument(createDocumentHandle(collectionName, documentKey), rev); - } - - /** - * This method validates a given AQL query string and returns a CursorEntity - * - * @param query - * an AQL query as string - * @return a CursorEntity object - * @throws ArangoException - */ - public CursorEntity validateQuery(final String query) throws ArangoException { - return cursorDriver.validateQuery(getDefaultDatabase(), query); - } - - /** - * Continues data retrieval for an existing cursor - * - * @param cursorId - * The id of a cursor. - * @param clazz - * the expected class, the result from the server request is - * deserialized to an instance of this class. - * @return a CursorEntity object - * @throws ArangoException - */ - public CursorEntity continueQuery(final long cursorId, final Class... clazz) throws ArangoException { - return cursorDriver.continueQuery(getDefaultDatabase(), cursorId, clazz); - } - - /** - * Deletes a cursor from the database. - * - * @param cursorId - * The id of a cursor. - * @return a DefaultEntity object - * @throws ArangoException - */ - public DefaultEntity finishQuery(final long cursorId) throws ArangoException { - return cursorDriver.finishQuery(getDefaultDatabase(), cursorId); - } - - /** - * This method executes an AQL query and returns a CursorEntity. - * - * @param query - * an AQL query as string - * @param bindVars - * a map containing all bind variables, - * @param clazz - * the expected class, the result from the server request is - * deserialized to an instance of this class. - * @param calcCount - * if set to true the result count is returned - * @param batchSize - * the batch size of the result cursor (The batch size has to be - * greater than 0) - * @param fullCount - * if set to true, then all results before the final LIMIT will - * be counted - * @return a CursorEntity object - * @throws ArangoException - */ - public CursorEntity executeCursorEntityQuery( - final String query, - final Map bindVars, - final Boolean calcCount, - final Integer batchSize, - final Boolean fullCount, - final Class... clazz) throws ArangoException { - - final AqlQueryOptions aqlQueryOptions = new AqlQueryOptions().setCount(calcCount).setBatchSize(batchSize) - .setFullCount(fullCount); - - return cursorDriver.executeCursorEntityQuery(getDefaultDatabase(), query, bindVars, aqlQueryOptions, clazz); - } - - /** - * Creates a default AqlQueryOptions object - * - * @return default AqlQueryOptions object - */ - public AqlQueryOptions getDefaultAqlQueryOptions() { - return new AqlQueryOptions().setBatchSize(configure.getBatchSize()).setCount(false).setFullCount(false); - } - - /** - * This method executes an AQL query and returns a DocumentCursor - * - * @param query - * an AQL query as string - * @param bindVars - * a map containing all bind variables, - * @param aqlQueryOptions - * AQL query options (null for default values) - * @param clazz - * the expected class, the result from the server request is - * deserialized to an instance of this class. - * @return DocumentCursor - * @throws ArangoException - */ - public DocumentCursor executeDocumentQuery( - final String query, - final Map bindVars, - final AqlQueryOptions aqlQueryOptions, - final Class clazz) throws ArangoException { - - @SuppressWarnings("unchecked") - final DocumentCursorResult> baseCursor = cursorDriver.executeBaseCursorQuery( - getDefaultDatabase(), query, bindVars, getAqlQueryOptions(aqlQueryOptions), DocumentEntity.class, clazz); - return new DocumentCursor(baseCursor); - } - - /** - * This method executes an AQL query and returns a CursorResult - * - * @param query - * an AQL query as string - * @param bindVars - * a map containing all bind variables, - * @param aqlQueryOptions - * AQL query options - * @param clazz - * the expected class, the result from the server request is - * deserialized to an instance of this class. - * @return CursorResult - * @throws ArangoException - */ - public CursorResult executeAqlQuery( - final String query, - final Map bindVars, - final AqlQueryOptions aqlQueryOptions, - final Class clazz) throws ArangoException { - - return cursorDriver.executeAqlQuery(getDefaultDatabase(), query, bindVars, getAqlQueryOptions(aqlQueryOptions), - clazz); - } - - /** - * Executes an AQL query and returns the raw JSON response - * - * @param query - * an AQL query as string - * @param bindVars - * a map containing all bind variables, - * @param aqlQueryOptions - * AQL query options - * @return A JSON string with the results from server - * @throws ArangoException - */ - public String executeAqlQueryJSON( - final String query, - final Map bindVars, - final AqlQueryOptions aqlQueryOptions) throws ArangoException { - - return cursorDriver.executeAqlQueryJSON(getDefaultDatabase(), query, bindVars, - getAqlQueryOptions(aqlQueryOptions)); - } - - /** - * This method executes an AQL query and returns a DocumentCursorResult - * - * @param query - * an AQL query as string - * @param bindVars - * a map containing all bind variables, - * @param aqlQueryOptions - * AQL query options - * @param classDocumentEntity - * the class the expected class is wrapped in (the class has to - * extend DocumentEntity) - * @param clazz - * the expected class, the result from the server request is - * deserialized to an instance of this class. - * @return DocumentCursorResult - * @throws ArangoException - */ - public > DocumentCursorResult executeAqlQueryWithDocumentCursorResult( - final String query, - final Map bindVars, - final AqlQueryOptions aqlQueryOptions, - final Class classDocumentEntity, - final Class clazz) throws ArangoException { - - return cursorDriver.executeBaseCursorQuery(getDefaultDatabase(), query, bindVars, - getAqlQueryOptions(aqlQueryOptions), classDocumentEntity, clazz); - } - - /** - * This method creates an index for a collection. - * - * @param collectionName - * The collection name. - * @param type - * the index type. - * @param unique - * if set to true the index will be a unique index - * @param fields - * the fields (document attributes) the index is created on - * @return IndexEntity - * @throws ArangoException - */ - public IndexEntity createIndex( - final String collectionName, - final IndexType type, - final boolean unique, - final String... fields) throws ArangoException { - return indexDriver.createIndex(getDefaultDatabase(), collectionName, type, unique, fields); - } - - /** - * This method creates an index for a collection. - * - * @param collectionName - * The collection name. - * @param type - * the index type. - * @param unique - * if set to true the index will be a unique index - * @param sparse - * if set to true the index will be sparse - * @param fields - * the fields (document attributes) the index is created on - * @return IndexEntity - * @throws ArangoException - */ - public IndexEntity createIndex( - final String collectionName, - final IndexType type, - final boolean unique, - final boolean sparse, - final String... fields) throws ArangoException { - return indexDriver.createIndex(getDefaultDatabase(), collectionName, type, unique, sparse, fields); - } - - /** - * This method creates a hash index for a collection. - * - * @param collectionName - * The collection name. - * @param unique - * if set to true the index will be a unique index - * @param fields - * the fields (document attributes) the index is created on - * @return IndexEntity - * @throws ArangoException - */ - public IndexEntity createHashIndex(final String collectionName, final boolean unique, final String... fields) - throws ArangoException { - return indexDriver.createIndex(getDefaultDatabase(), collectionName, IndexType.HASH, unique, fields); - } - - /** - * This method creates a hash index for a collection. - * - * @param collectionName - * The collection name. - * @param unique - * if set to true the index will be a unique index - * @param sparse - * if set to true the index will be sparse - * @param fields - * the fields (document attributes) the index is created on - * @return IndexEntity - * @throws ArangoException - */ - public IndexEntity createHashIndex( - final String collectionName, - final boolean unique, - final boolean sparse, - final String... fields) throws ArangoException { - return indexDriver.createIndex(getDefaultDatabase(), collectionName, IndexType.HASH, unique, sparse, fields); - } - - /** - * This method creates a geo index for a collection. - * - * @param collectionName - * The collection name. - * @param unique - * if set to true the index will be a unique index - * @param fields - * the fields (document attributes) the index is created on - * @return IndexEntity - * @throws ArangoException - */ - public IndexEntity createGeoIndex(final String collectionName, final boolean unique, final String... fields) - throws ArangoException { - return indexDriver.createIndex(getDefaultDatabase(), collectionName, IndexType.GEO, unique, fields); - } - - /** - * This method creates a skip list index for a collection. - * - * @param collectionName - * The collection name. - * @param unique - * if set to true the index will be a unique index - * @param fields - * the fields (document attributes) the index is created on - * @return IndexEntity - * @throws ArangoException - */ - public IndexEntity createSkipListIndex(final String collectionName, final boolean unique, final String... fields) - throws ArangoException { - return indexDriver.createIndex(getDefaultDatabase(), collectionName, IndexType.SKIPLIST, unique, fields); - } - - /** - * This method creates a skip list index for a collection. - * - * @param collectionName - * The collection name. - * @param unique - * if set to true the index will be a unique index - * @param sparse - * if set to true the index will be sparse - * @param fields - * the fields (document attributes) the index is created on - * @return IndexEntity - * @throws ArangoException - */ - public IndexEntity createSkipListIndex( - final String collectionName, - final boolean unique, - final boolean sparse, - final String... fields) throws ArangoException { - return indexDriver.createIndex(getDefaultDatabase(), collectionName, IndexType.SKIPLIST, unique, sparse, - fields); - } - - /** - * It is possible to define a persistent index on one or more attributes (or - * paths) of documents. The index is then used in queries to locate - * documents within a given range. If the index is declared unique, then no - * two documents are allowed to have the same set of attribute values. - * - * @param collectionName - * The collection name. - * @param unique - * if set to true the index will be a unique index - * @param sparse - * if set to true the index will be sparse - * @param fields - * the fields (document attributes) the index is created on - * @return IndexEntity - * @throws ArangoException - */ - public IndexEntity createPersistentIndex( - final String collectionName, - final boolean unique, - final boolean sparse, - final String... fields) throws ArangoException { - return indexDriver.createIndex(getDefaultDatabase(), collectionName, IndexType.PERSISTENT, unique, sparse, - fields); - } - - /** - * This method creates a full text index for a collection. - * - * @param collectionName - * The collection name. - * @param fields - * the fields (document attributes) the index is created on - * @return IndexEntity - * @throws ArangoException - */ - public IndexEntity createFulltextIndex(final String collectionName, final String... fields) throws ArangoException { - return createFulltextIndex(collectionName, null, fields); - } - - /** - * This method creates a full text index for a collection. - * - * @param collectionName - * The collection name. - * @param minLength - * Minimum character length of words to index. - * @param fields - * the fields (document attributes) the index is created on - * @return IndexEntity - * @throws ArangoException - */ - public IndexEntity createFulltextIndex(final String collectionName, final Integer minLength, final String... fields) - throws ArangoException { - return indexDriver.createFulltextIndex(getDefaultDatabase(), collectionName, minLength, fields); - } - - /** - * Deletes an index from a collection - * - * @param indexHandle - * the index handle - * @return IndexEntity - * @throws ArangoException - */ - public IndexEntity deleteIndex(final String indexHandle) throws ArangoException { - return indexDriver.deleteIndex(getDefaultDatabase(), indexHandle); - } - - /** - * Returns an index from a collection. - * - * @param indexHandle - * the index handle - * @return IndexEntity - * @throws ArangoException - */ - public IndexEntity getIndex(final String indexHandle) throws ArangoException { - return indexDriver.getIndex(getDefaultDatabase(), indexHandle); - } - - /** - * Returns all indices from a collection. - * - * @param collectionName - * The collection name. - * @return IndexesEntity - * @throws ArangoException - */ - public IndexesEntity getIndexes(final String collectionName) throws ArangoException { - return indexDriver.getIndexes(getDefaultDatabase(), collectionName); - } - - /** - * Returns the server log, for the parameters *logLevel* and *logLevelUpTo* - * please note the following: fatal or 0 error or 1 warning or 2 info or 3 - * debug or 4 The default value is info. - * - * @param logLevel - * if set only logs with this *logLevel* are returned - * @param logLevelUpTo - * if set all logs up to the *logLevelUpTo* are returned - * @param start - * Returns all log entries such that their log entry identifier - * (lid value) is greater or equal to start. - * @param size - * Restricts the result to at most size log entries. - * @param offset - * Starts to return log entries skipping the first offset log - * entries. - * @param sortAsc - * if set to true the default sort order (descending) is reverted - * to ascending - * @param text - * Only return the log entries containing the text specified in - * text. - * @return a AdminLogEntity object - * @throws ArangoException - */ - public AdminLogEntity getServerLog( - final Integer logLevel, - final Boolean logLevelUpTo, - final Integer start, - final Integer size, - final Integer offset, - final Boolean sortAsc, - final String text) throws ArangoException { - return adminDriver.getServerLog(logLevel, logLevelUpTo, start, size, offset, sortAsc, text); - } - - /** - * Returns the current statistics - * - * @return StatisticsEntity - * @throws ArangoException - */ - public StatisticsEntity getStatistics() throws ArangoException { - return adminDriver.getStatistics(); - } - - /** - * Returns the statistics description - * - * @return StatisticsDescriptionEntity - * @throws ArangoException - */ - public StatisticsDescriptionEntity getStatisticsDescription() throws ArangoException { - return adminDriver.getStatisticsDescription(); - } - - /** - * Returns the database version - * - * @return ArangoVersion - * @throws ArangoException - */ - public ArangoVersion getVersion() throws ArangoException { - return adminDriver.getVersion(); - } - - /** - * Returns the current server time - * - * @return ArangoUnixTime - * @throws ArangoException - */ - public ArangoUnixTime getTime() throws ArangoException { - return adminDriver.getTime(); - } - - /** - * Triggers the routes reloading in ArangoDB - * - * @return DefaultEntity - * @throws ArangoException - */ - public DefaultEntity reloadRouting() throws ArangoException { - return adminDriver.reloadRouting(); - } - - /** - * Executes a javascript code. - * - * @param jsCode - * a javascript function as string - * @return DefaultEntity - * @throws ArangoException - */ - public DefaultEntity executeScript(final String jsCode) throws ArangoException { - return adminDriver.executeScript(getDefaultDatabase(), jsCode); - } - - /** - * This will find all documents matching a given example. - * - * @param collectionName - * - The collection name. - * @param example - * The example as a map. - * @param skip - * The number of documents to skip in the query. - * @param limit - * The maximal amount of documents to return. The skip is applied - * before the limit restriction. - * @param clazz - * the expected class, the result from the server request is - * deserialized to an instance of this class. - * @return DocumentCursor - * @throws ArangoException - */ - public DocumentCursor executeSimpleByExampleDocuments( - final String collectionName, - final Map example, - final int skip, - final int limit, - final Class clazz) throws ArangoException { - return simpleDriver.executeSimpleByExampleDocuments(getDefaultDatabase(), collectionName, example, skip, limit, - clazz); - } - - /** - * Returns all documents of a collections. - * - * @param collectionName - * The collection name. - * @param skip - * The number of documents to skip in the query. - * @param limit - * The maximal amount of documents to return. The skip is applied - * before the limit restriction. - * @param clazz - * the expected class, the result from the server request is - * deserialized to an instance of this class. - * @return DocumentCursor - * @throws ArangoException - */ - public DocumentCursor executeSimpleAllDocuments( - final String collectionName, - final int skip, - final int limit, - final Class clazz) throws ArangoException { - return simpleDriver.executeSimpleAllDocuments(getDefaultDatabase(), collectionName, skip, limit, clazz); - } - - /** - * Returns the first document matching the example - * - * @param collectionName - * The collection name. - * @param example - * The example as a map. - * @param clazz - * the expected class, the result from the server request is - * deserialized to an instance of this class. - * @return a ScalarExampleEntity object - * @throws ArangoException - */ - public ScalarExampleEntity executeSimpleFirstExample( - final String collectionName, - final Map example, - final Class clazz) throws ArangoException { - return simpleDriver.executeSimpleFirstExample(getDefaultDatabase(), collectionName, example, clazz); - } - - /** - * Returns a random document from the collection - * - * @param collectionName - * The collection name. - * @param clazz - * the expected class, the result from the server request is - * deserialized to an instance of this class. - * @return a ScalarExampleEntity object - * @throws ArangoException - */ - public ScalarExampleEntity executeSimpleAny(final String collectionName, final Class clazz) - throws ArangoException { - return simpleDriver.executeSimpleAny(getDefaultDatabase(), collectionName, clazz); - } - - /** - * This will find all documents within a given range. - * - * @param collectionName - * The collection name. - * @param attribute - * The attribute path to check. - * @param left - * The lower bound - * @param right - * The upper bound - * @param closed - * If true, use interval including left and right, otherwise - * exclude right, but include left. - * @param skip - * The number of documents to skip in the query. - * @param limit - * The maximal amount of documents to return. The skip is applied - * before the limit restriction. - * @param clazz - * the expected class, the result from the server request is - * deserialized to an instance of this class. - * @return DocumentCursor - * @throws ArangoException - */ - public DocumentCursor executeSimpleRangeWithDocuments( - final String collectionName, - final String attribute, - final Object left, - final Object right, - final Boolean closed, - final int skip, - final int limit, - final Class clazz) throws ArangoException { - return simpleDriver.executeSimpleRangeWithDocuments(getDefaultDatabase(), collectionName, attribute, left, - right, closed, skip, limit, clazz); - } - - /** - * This will find all documents from the collection that match the fulltext - * query specified in query. In order to use the fulltext operator, a - * fulltext index must be defined for the collection and the specified - * attribute. - * - * @param collectionName - * The collection name. - * @param attribute - * The attribute path to check. - * @param query - * The fulltext query as string. - * @param skip - * The number of documents to skip in the query. - * @param limit - * The maximal amount of documents to return. The skip is applied - * before the limit restriction. - * @param clazz - * the expected class, the result from the server request is - * deserialized to an instance of this class. - * @return DocumentCursor - * @throws ArangoException - */ - public DocumentCursor executeSimpleFulltextWithDocuments( - final String collectionName, - final String attribute, - final String query, - final int skip, - final int limit, - final String index, - final Class clazz) throws ArangoException { - return simpleDriver.executeSimpleFulltextWithDocuments(getDefaultDatabase(), collectionName, attribute, query, - skip, limit, index, clazz); - } - - /** - * This will remove all documents in the collection that match the specified - * example object. - * - * @param collectionName - * The collection name. - * @param example - * The example as a map. - * @param waitForSync - * if set to true the response is returned when the server has - * finished. - * @param limit - * limits the amount of documents which will be deleted. - * @return SimpleByResultEntity - * @throws ArangoException - */ - public SimpleByResultEntity executeSimpleRemoveByExample( - final String collectionName, - final Map example, - final Boolean waitForSync, - final Integer limit) throws ArangoException { - return simpleDriver.executeSimpleRemoveByExample(getDefaultDatabase(), collectionName, example, waitForSync, - limit); - } - - /** - * This will replace all documents in the collection that match the - * specified example object. - * - * @param collectionName - * The collection name. - * @param example - * The example as a map. - * @param newValue - * The new values. - * @param waitForSync - * if set to true the response is returned when the server has - * finished. - * @param limit - * limits the amount of documents which will be replaced. - * @return SimpleByResultEntity - * @throws ArangoException - */ - public SimpleByResultEntity executeSimpleReplaceByExample( - final String collectionName, - final Map example, - final Map newValue, - final Boolean waitForSync, - final Integer limit) throws ArangoException { - return simpleDriver.executeSimpleReplaceByExample(getDefaultDatabase(), collectionName, example, newValue, - waitForSync, limit); - } - - /** - * This will update all documents in the collection that match the specified - * example object. - * - * @param collectionName - * The collection name. - * @param example - * The example as a map. - * @param newValue - * The new values. - * @param keepNull - * - If true null values are kept. - * @param waitForSync - * if set to true the response is returned when the server has - * finished. - * @param limit - * limits the amount of documents which will be updated. - * @return SimpleByResultEntity - * @throws ArangoException - */ - public SimpleByResultEntity executeSimpleUpdateByExample( - final String collectionName, - final Map example, - final Map newValue, - final Boolean keepNull, - final Boolean waitForSync, - final Integer limit) throws ArangoException { - return simpleDriver.executeSimpleUpdateByExample(getDefaultDatabase(), collectionName, example, newValue, - keepNull, waitForSync, limit); - } - - /** - * Creates a database user. - * - * @param username - * the username as string - * @param passwd - * the password as string - * @param active - * if true the user is active - * @param extra - * additional user data - * @return DefaultEntity - * @throws ArangoException - */ - public DefaultEntity createUser( - final String username, - final String passwd, - final Boolean active, - final Map extra) throws ArangoException { - return usersDriver.createUser(username, passwd, active, extra); - } - - /** - * Replaces the data of a database user. - * - * @param username - * the username as string - * @param passwd - * the password as string - * @param active - * if true the user is active - * @param extra - * additional user data - * @return DefaultEntity - * @throws ArangoException - */ - public DefaultEntity replaceUser( - final String username, - final String passwd, - final Boolean active, - final Map extra) throws ArangoException { - return usersDriver.replaceUser(username, passwd, active, extra); - } - - /** - * Updates the data of a database user. - * - * @param username - * the username as string - * @param passwd - * the password as string - * @param active - * if true the user is active - * @param extra - * additional user data - * @return DefaultEntity - * @throws ArangoException - */ - public DefaultEntity updateUser( - final String username, - final String passwd, - final Boolean active, - final Map extra) throws ArangoException { - return usersDriver.updateUser(username, passwd, active, extra); - } - - /** - * Deletes a database user. - * - * @param username - * the username as string - * @return DefaultEntity - * @throws ArangoException - */ - public DefaultEntity deleteUser(final String username) throws ArangoException { - return usersDriver.deleteUser(username); - } - - /** - * Returns a database user. - * - * @param username - * the username as string - * @return UserEntity - * @throws ArangoException - */ - public UserEntity getUser(final String username) throws ArangoException { - return usersDriver.getUser(username); - } - - /** - * Grants the User access to the given database. - * - * @param username - * the username as string - * @param database - * @return a DefaultEntity object - * @throws ArangoException - */ - public DefaultEntity grantDatabaseAccess(final String username, final String database) throws ArangoException { - return usersDriver.grantDatabaseAccess(username, database); - } - - /** - * Returns all database user as document. - * - * @return List> - * @throws ArangoException - */ - public List> getUsersDocument() throws ArangoException { - final DocumentCursor documentCursor = simpleDriver.executeSimpleAllDocuments(DATABASE_SYSTEM, - COLLECTION_USERS, 0, 0, UserEntity.class); - return documentCursor.asList(); - } - - /** - * Returns all database user. - * - * @return List - * @throws ArangoException - */ - public List getUsers() throws ArangoException { - final DocumentCursor documentCursor = simpleDriver.executeSimpleAllDocuments(DATABASE_SYSTEM, - COLLECTION_USERS, 0, 0, UserEntity.class); - return documentCursor.asEntityList(); - } - - /** - * Creates documents in a collection. - * - * @param collection - * the collection as a string - * @param values - * a list of Objects that will be stored as documents - * @return ImportResultEntity - * @throws ArangoException - */ - public ImportResultEntity importDocuments(final String collection, final Collection values) - throws ArangoException { - return importDriver.importDocuments(getDefaultDatabase(), collection, values, new ImportOptionsJson()); - } - - /** - * Creates documents in a collection. - * - * @param collection - * the collection as a string - * @param values - * a list of Objects that will be stored as documents - * @param importOptionsJson - * options for importing documents - * @return ImportResultEntity - * @throws ArangoException - */ - public ImportResultEntity importDocuments( - final String collection, - final Collection values, - final ImportOptionsJson importOptionsJson) throws ArangoException { - return importDriver.importDocuments(getDefaultDatabase(), collection, values, importOptionsJson); - } - - /** - * Creates documents in a collection. - * - * @param collection - * the collection as a string - * @param values - * a raw string containing JSON data - * @param importOptions - * options for importing documents - * @return ImportResultEntity - * @throws ArangoException - */ - public ImportResultEntity importDocumentsRaw( - final String collection, - final String values, - final ImportOptionsRaw importOptionsRaw) throws ArangoException { - return importDriver.importDocumentsRaw(getDefaultDatabase(), collection, values, importOptionsRaw); - } - - /** - * Creates documents in a collection. - * - * @param collection - * the collection as a string - * @param headerValues - * a list of lists that will be stored as documents - * @return ImportResultEntity - * @throws ArangoException - */ - public ImportResultEntity importDocumentsByHeaderValues( - final String collection, - final Collection> headerValues) throws ArangoException { - return importDriver.importDocumentsByHeaderValues(getDefaultDatabase(), collection, headerValues, - new ImportOptions()); - } - - /** - * Creates documents in a collection. - * - * @param collection - * the collection as a string - * @param headerValues - * a list of lists that will be stored as documents - * @param importOptions - * options for importing documents - * @return ImportResultEntity - * @throws ArangoException - */ - public ImportResultEntity importDocumentsByHeaderValues( - final String collection, - final Collection> headerValues, - final ImportOptions importOptions) throws ArangoException { - return importDriver.importDocumentsByHeaderValues(getDefaultDatabase(), collection, headerValues, - importOptions); - } - - /** - * Creates documents in a collection. - * - * @param collection - * the collection as a string - * @param headerValues - * raw JSON data that contains a list of lists that will be - * stored as documents - * @param importOptions - * options for importing documents - * @return ImportResultEntity - * @throws ArangoException - */ - public ImportResultEntity importDocumentsByHeaderValuesRaw( - final String collection, - final String headerValues, - final ImportOptions importOptions) throws ArangoException { - return importDriver.importDocumentsByHeaderValuesRaw(getDefaultDatabase(), collection, headerValues, - importOptions); - } - - /** - * Returns the current database - * - * @return DatabaseEntity - * @throws ArangoException - */ - public DatabaseEntity getCurrentDatabase() throws ArangoException { - return databaseDriver.getCurrentDatabase(); - } - - /** - * Returns all databases - * - * @return StringsResultEntity - * @throws ArangoException - */ - public StringsResultEntity getDatabases() throws ArangoException { - return getDatabases(false); - } - - /** - * Returns all databases - * - * @param currentUserAccessableOnly - * If true only the databases are returned that the current user - * can access - * @return StringsResultEntity - * @throws ArangoException - */ - public StringsResultEntity getDatabases(final boolean currentUserAccessableOnly) throws ArangoException { - return databaseDriver.getDatabases(currentUserAccessableOnly, null, null); - } - - /** - * Returns all databases the user identified by his credentials can access - * - * @param username - * the username as string - * @param password - * the password as string - * @return StringsResultEntity - * @throws ArangoException - */ - public StringsResultEntity getDatabases(final String username, final String password) throws ArangoException { - return databaseDriver.getDatabases(true, username, password); - } - - /** - * This method creates a database - * - * @param database - * the database name as a string - * @param users - * a list of users which are supposed to have access to the - * database - * @return BooleanResultEntity - * @throws ArangoException - */ - public BooleanResultEntity createDatabase(final String database, final UserEntity... users) throws ArangoException { - return databaseDriver.createDatabase(database, users); - } - - /** - * This method deletes a database - * - * @param database - * the database name as a string - * @return BooleanResultEntity - * @throws ArangoException - */ - public BooleanResultEntity deleteDatabase(final String database) throws ArangoException { - return databaseDriver.deleteDatabase(database); - } - - /** - * This method creates an endpoint. - * - * @param endpoint - * the endpoint as string - * @param databases - * a list of databases that are allowed on this endpoint - * @return BooleanResultEntity - */ - public BooleanResultEntity createEndpoint(final String endpoint, final String... databases) throws ArangoException { - return endpointDriver.createEndpoint(endpoint, databases); - } - - /** - * This method returns all endpoints. - * - * @return List - */ - public List getEndpoints() throws ArangoException { - return endpointDriver.getEndpoints(); - } - - /** - * This method deletes an endpoint - * - * @param endpoint - * the endpoint as string - * @return BooleanResultEntity - */ - public BooleanResultEntity deleteEndpoint(final String endpoint) throws ArangoException { - return endpointDriver.deleteEndpoint(endpoint); - } - - /** - * Returns the list of collections and indexes available on the server. This - * list can be used by replication clients to initiate an initial sync with - * the server. - * - * @return ReplicationInventoryEntity - * @throws ArangoException - */ - public ReplicationInventoryEntity getReplicationInventory() throws ArangoException { - return replicationDriver.getReplicationInventory(getDefaultDatabase(), null); - } - - /** - * Returns the list of collections and indexes available on the server. This - * list can be used by replication clients to initiate an initial sync with - * the server. - * - * @param includeSystem - * if true the system collections are included into the result - * @return ReplicationInventoryEntity - * @throws ArangoException - */ - public ReplicationInventoryEntity getReplicationInventory(final boolean includeSystem) throws ArangoException { - return replicationDriver.getReplicationInventory(getDefaultDatabase(), includeSystem); - } - - /** - * Returns the data from the collection for the requested range. - * - * @param collectionName - * the collection name - * @param from - * Lower bound tick value for results. - * @param to - * Upper bound tick value for results. - * @param chunkSize - * Approximate maximum size of the returned result. - * @param ticks - * Whether or not to include tick values in the dump. Default - * value is true. - * @param clazz - * the expected class, the result from the server request is - * deserialized to an instance of this class. - * @param handler - * a handler object that processes the dump - * @throws ArangoException - */ - public void getReplicationDump( - final String collectionName, - final Long from, - final Long to, - final Integer chunkSize, - final Boolean ticks, - final Class clazz, - final DumpHandler handler) throws ArangoException { - - replicationDriver.getReplicationDump(getDefaultDatabase(), collectionName, from, to, chunkSize, ticks, clazz, - handler); - - } - - /** - * Starts a full data synchronization from a remote endpoint into the local - * ArangoDB database. - * - * @param endpoint - * the endpoint as string - * @param database - * the database name as a string - * @param username - * the username as string - * @param password - * the password as string - * @param restrictType - * collection filtering. When specified, the allowed values are - * include or exclude. - * @param restrictCollections - * If restrictType is include, only the specified collections - * will be sychronised. If restrictType is exclude, all but the - * specified collections will be synchronized. - * @return ReplicationSyncEntity - * @throws ArangoException - */ - public ReplicationSyncEntity syncReplication( - final String endpoint, - final String database, - final String username, - final String password, - final RestrictType restrictType, - final String... restrictCollections) throws ArangoException { - return replicationDriver.syncReplication(getDefaultDatabase(), endpoint, database, username, password, - restrictType, restrictCollections); - } - - /** - * Returns the servers id. The id is also returned by other replication API - * methods, and this method is an easy means of determining a server's id. - * - * @return String - * @throws ArangoException - */ - public String getReplicationServerId() throws ArangoException { - return replicationDriver.getReplicationServerId(); - } - - /** - * Starts the replication logger - * - * @return boolean - * @throws ArangoException - */ - public boolean startReplicationLogger() throws ArangoException { - return replicationDriver.startReplicationLogger(getDefaultDatabase()); - } - - /** - * Stops the replication logger - * - * @return boolean - * @throws ArangoException - */ - public boolean stopReplicationLogger() throws ArangoException { - return replicationDriver.stopReplicationLogger(getDefaultDatabase()); - } - - /** - * Returns the current state of the server's replication logger. The state - * will include information about whether the logger is running and about - * the last logged tick value. - * - * @return ReplicationLoggerStateEntity - * @throws ArangoException - * @since 1.4.0 - */ - public ReplicationLoggerStateEntity getReplicationLoggerState() throws ArangoException { - return replicationDriver.getReplicationLoggerState(getDefaultDatabase()); - } - - /** - * Returns the configuration of the replication logger - * - * @return ReplicationLoggerConfigEntity - * @throws ArangoException - */ - public ReplicationLoggerConfigEntity getReplicationLoggerConfig() throws ArangoException { - return replicationDriver.getReplicationLoggerConfig(getDefaultDatabase()); - } - - /** - * Sets the replication logger configuration - * - * @param autoStart - * if true autoStart is activated - * @param logRemoteChanges - * if true remote changes are logged - * @param maxEvents - * the maximum amount of events to log - * @param maxEventsSize - * the maximum size of events - * @return ReplicationLoggerConfigEntity - * @throws ArangoException - */ - public ReplicationLoggerConfigEntity setReplicationLoggerConfig( - final Boolean autoStart, - final Boolean logRemoteChanges, - final Long maxEvents, - final Long maxEventsSize) throws ArangoException { - return replicationDriver.setReplicationLoggerConfig(getDefaultDatabase(), autoStart, logRemoteChanges, - maxEvents, maxEventsSize); - } - - /** - * Returns the configuration of the replication applier. - * - * @return ReplicationApplierConfigEntity - * @throws ArangoException - * @since 1.4.0 - */ - public ReplicationApplierConfigEntity getReplicationApplierConfig() throws ArangoException { - return replicationDriver.getReplicationApplierConfig(getDefaultDatabase()); - } - - /** - * Sets the configuration of the replication applier. - * - * @param endpoint - * the logger server to connect to (e.g. - * "tcp://192.168.173.13:8529"). - * @param database - * the name of the database on the endpoint. - * @param username - * an optional ArangoDB username to use when connecting to the - * endpoint - * @param password - * the password to use when connecting to the endpoint. - * @param maxConnectRetries - * the maximum number of connection attempts the applier will - * make in a row. If the applier cannot establish a connection to - * the endpoint in this number of attempts, it will stop itself. - * @param connectTimeout - * the timeout (in seconds) when attempting to connect to the - * endpoint. This value is used for each connection attempt. - * @param requestTimeout - * the timeout (in seconds) for individual requests to the - * endpoint. - * @param chunkSize - * the requested maximum size for log transfer packets that is - * used when the endpoint is contacted. - * @param autoStart - * whether or not to auto-start the replication applier on (next - * and following) server starts - * @param adaptivePolling - * if set to true, the replication applier will fall to sleep for - * an increasingly long period in case the logger server at the - * endpoint does not have any more replication events to apply. - * @return ReplicationApplierConfigEntity - * @throws ArangoException - */ - public ReplicationApplierConfigEntity setReplicationApplierConfig( - final String endpoint, - final String database, - final String username, - final String password, - final Integer maxConnectRetries, - final Integer connectTimeout, - final Integer requestTimeout, - final Integer chunkSize, - final Boolean autoStart, - final Boolean adaptivePolling) throws ArangoException { - return replicationDriver.setReplicationApplierConfig(getDefaultDatabase(), endpoint, database, username, - password, maxConnectRetries, connectTimeout, requestTimeout, chunkSize, autoStart, adaptivePolling); - } - - /** - * Sets the configuration of the replication applier. - * - * @param replicationApplierConfigEntity - * an instance of ReplicationApplierConfigEntity containing the - * complete config - * @return ReplicationApplierConfigEntity - * @throws ArangoException - */ - public ReplicationApplierConfigEntity setReplicationApplierConfig( - final ReplicationApplierConfigEntity replicationApplierConfigEntity) throws ArangoException { - return replicationDriver.setReplicationApplierConfig(getDefaultDatabase(), replicationApplierConfigEntity); - } - - /** - * Starts the replication applier. This will return immediately if the - * replication applier is already running. - * - * @param from - * The remote lastLogTick value from which to start applying. - * @return ReplicationApplierStateEntity - * @throws ArangoException - */ - public ReplicationApplierStateEntity startReplicationApplier(final Long from) throws ArangoException { - return replicationDriver.startReplicationApplier(getDefaultDatabase(), from); - } - - /** - * Stops the replication applier. This will return immediately if the - * replication applier is not running. - * - * @return ReplicationApplierStateEntity - * @throws ArangoException - */ - public ReplicationApplierStateEntity stopReplicationApplier() throws ArangoException { - return replicationDriver.stopReplicationApplier(getDefaultDatabase()); - } - - /** - * Returns the state of the replication applier, regardless of whether the - * applier is currently running or not. - * - * @return ReplicationApplierStateEntity - * @throws ArangoException - */ - public ReplicationApplierStateEntity getReplicationApplierState() throws ArangoException { - return replicationDriver.getReplicationApplierState(getDefaultDatabase()); - } - - /** - * Returns a GraphsEntity containing all graph as GraphEntity object of the - * default database. - * - * @return GraphsEntity Object containing all graphs of the database. - * @throws ArangoException - */ - public GraphsEntity getGraphs() throws ArangoException { - return graphDriver.getGraphs(getDefaultDatabase()); - } - - /** - * Creates a list of the names of all available graphs of the default - * database. - * - * @return List All graph names of the database. - * @throws ArangoException - */ - public List getGraphList() throws ArangoException { - return graphDriver.getGraphList(getDefaultDatabase()); - } - - /** - * Creates a graph. - * - * @param graphName - * The name of the graph to be created. - * @param edgeDefinitions - * List of the graphs edge definitions. - * @param orphanCollections - * List of the graphs orphan collections. - * @param waitForSync - * Wait for sync. - * @return GraphEntity The new graph. - * @throws ArangoException - */ - public GraphEntity createGraph( - final String graphName, - final List edgeDefinitions, - final List orphanCollections, - final Boolean waitForSync) throws ArangoException { - return graphDriver.createGraph(getDefaultDatabase(), graphName, edgeDefinitions, orphanCollections, - waitForSync); - } - - /** - * Creates a graph. - * - * @param graph - * The graph objet to be persistet. - * @param waitForSync - * Wait for sync. - * @return GraphEntity The new graph. - * @throws ArangoException - */ - public GraphEntity createGraph(final GraphEntity graph, final Boolean waitForSync) throws ArangoException { - final String graphName = graph.getName(); - final List edgeDefinitions = graph.getEdgeDefinitions(); - final List orphanCollections = graph.getOrphanCollections(); - return graphDriver.createGraph(getDefaultDatabase(), graphName, edgeDefinitions, orphanCollections, - waitForSync); - } - - /** - * Creates an empty graph. - * - * @param graphName - * The name of the graph to be created. - * @param waitForSync - * Wait for sync. - * @return GraphEntity The new graph. - * @throws ArangoException - */ - public GraphEntity createGraph(final String graphName, final Boolean waitForSync) throws ArangoException { - return graphDriver.createGraph(getDefaultDatabase(), graphName, waitForSync); - } - - /** - * Get graph object by name, including its edge definitions and vertex - * collections. - * - * @param graphName - * The name of the graph. - * @return GraphEntity The graph. - * @throws ArangoException - */ - public GraphEntity getGraph(final String graphName) throws ArangoException { - return graphDriver.getGraph(getDefaultDatabase(), graphName); - } - - /** - * Delete a graph by its name. The collections of the graph will not be - * dropped. - * - * @param graphName - * Name of the graph to be deleted. - * @return DeletedEntity - * @throws ArangoException - */ - public DeletedEntity deleteGraph(final String graphName) throws ArangoException { - return graphDriver.deleteGraph(getDefaultDatabase(), graphName, false); - } - - /** - * Delete a graph by its name. If dropCollections is true, all collections - * of the graph will be dropped, if they are not used in another graph. - * - * @param graphName - * Name of the graph to be deleted. - * @param dropCollections - * Indicates if the collections of the graph will be dropped - * @throws ArangoException - */ - public void deleteGraph(final String graphName, final Boolean dropCollections) throws ArangoException { - graphDriver.deleteGraph(getDefaultDatabase(), graphName, dropCollections); - } - - /** - * Returns a list of all vertex collection of a graph that are defined in - * the graphs edgeDefinitions (in "from", "to", and "orphanCollections") - * - * @param graphName - * The graph name. - * @return List List of the names of the vertex collections - * @throws ArangoException - */ - public List graphGetVertexCollections(final String graphName) throws ArangoException { - return graphGetVertexCollections(graphName, false); - } - - /** - * Returns a list of all vertex collection of a graph that are defined in - * the graphs edgeDefinitions (in "from", "to", and "orphanCollections") - * - * @param graphName - * The graph name. - * @param excludeOrphan - * @return List List of the names of the vertex collections - * @throws ArangoException - */ - public List graphGetVertexCollections(final String graphName, final boolean excludeOrphan) - throws ArangoException { - return graphDriver.getVertexCollections(getDefaultDatabase(), graphName, excludeOrphan); - } - - /** - * Removes a vertex collection from the graph and optionally deletes the - * collection, if it is not used in any other graph. - * - * @param graphName - * The graph name. - * @param collectionName - * The name of the vertex collection to be removed from the - * graph. - * @param dropCollection - * Indicates if the collection will be dropped - * @throws ArangoException - */ - public DeletedEntity graphDeleteVertexCollection( - final String graphName, - final String collectionName, - final Boolean dropCollection) throws ArangoException { - return graphDriver.deleteVertexCollection(getDefaultDatabase(), graphName, collectionName, dropCollection); - } - - /** - * Creates a vertex collection - * - * @param graphName - * The graph name. - * @param collectionName - * The name of the collection to be created. - * @return GraphEntity The graph, including the new collection. - * @throws ArangoException - */ - public GraphEntity graphCreateVertexCollection(final String graphName, final String collectionName) - throws ArangoException { - return graphDriver.createVertexCollection(getDefaultDatabase(), graphName, collectionName); - } - - /** - * Returns a list of all edge collection of a graph that are defined in the - * graphs edgeDefinitions - * - * @param graphName - * The graph name. - * @return List List of the names of all edge collections of the - * graph. - * @throws ArangoException - */ - public List graphGetEdgeCollections(final String graphName) throws ArangoException { - return graphDriver.getEdgeCollections(getDefaultDatabase(), graphName); - } - - /** - * Adds a new edge definition to an existing graph - * - * @param graphName - * The graph name. - * @param edgeDefinition - * The edge definition to be added. - * @return GraphEntity The graph, including the new edge definition. - * @throws ArangoException - */ - public GraphEntity graphCreateEdgeDefinition(final String graphName, final EdgeDefinitionEntity edgeDefinition) - throws ArangoException { - return graphDriver.createEdgeDefinition(getDefaultDatabase(), graphName, edgeDefinition); - } - - /** - * Replaces an existing edge definition to an existing graph. This will also - * change the edge definitions of all other graphs using this definition as - * well. - * - * @param graphName - * The name of the graph. - * @param edgeCollectionName - * The name of the edge collection of the edge definition that - * has to be replaced. - * @param edgeDefinition - * The new edge definition. - * @return GraphEntity The graph, including the changed edge definition. - * @throws ArangoException - */ - public GraphEntity graphReplaceEdgeDefinition( - final String graphName, - final String edgeCollectionName, - final EdgeDefinitionEntity edgeDefinition) throws ArangoException { - return graphDriver.replaceEdgeDefinition(getDefaultDatabase(), graphName, edgeCollectionName, edgeDefinition); - } - - /** - * Removes an existing edge definition from this graph. All data stored in - * the collections is dropped as well as long as it is not used in other - * graphs. - * - * @param graphName - * The name of the graph. - * @param edgeCollectionName - * The name of edge collection of the edge definition which has - * to be deleted. - * @return The graph, excluding the deleted edge definition. - */ - public GraphEntity graphDeleteEdgeDefinition( - final String graphName, - final String edgeCollectionName, - final Boolean dropCollection) throws ArangoException { - return graphDriver.deleteEdgeDefinition(getDefaultDatabase(), graphName, edgeCollectionName, dropCollection); - } - - /** - * Stores a new vertex with the information contained within the document - * into the given collection. - * - * @param graphName - * The name of the graph. - * @param collectionName - * The name of the collection, where the vertex will be created. - * @param vertex - * The vertex object to be stored - * @param waitForSync - * Wait for sync. - * @return DocumentEntity The resulting DocumentEntity containing the - * vertex document. - * @throws ArangoException - */ - public VertexEntity graphCreateVertex( - final String graphName, - final String collectionName, - final T vertex, - final Boolean waitForSync) throws ArangoException { - return graphDriver.createVertex(getDefaultDatabase(), graphName, collectionName, vertex, waitForSync); - } - - /** - * Stores a new vertex with the information contained within the document - * into the given collection. - * - * @param graphName - * The name of the graph. - * @param collectionName - * The name of the collection, where the vertex will be created. - * @param key - * The vertex key. - * @param vertex - * The vertex object to be stored - * @param waitForSync - * Wait for sync. - * @return DocumentEntity The resulting DocumentEntity containing the - * vertex document. - * @throws ArangoException - */ - public VertexEntity graphCreateVertex( - final String graphName, - final String collectionName, - final String key, - final T vertex, - final Boolean waitForSync) throws ArangoException { - return graphDriver.createVertex(getDefaultDatabase(), graphName, collectionName, key, vertex, waitForSync); - } - - /** - * Gets a vertex with the given key if it is contained within your graph. - * - * @param graphName - * The name of the graph. - * @param collectionName - * The collection, containing the vertex to get. - * @param key - * The key (document handle) of the vertex to get. - * @param clazz - * The class of the vertex to get. - * @return DocumentEntity The resulting DocumentEntity containing the - * vertex document. - * @throws ArangoException - */ - public VertexEntity graphGetVertex( - final String graphName, - final String collectionName, - final String key, - final Class clazz) throws ArangoException { - return graphDriver.getVertex(getDefaultDatabase(), graphName, collectionName, key, clazz, null, null); - } - - /** - * Gets a vertex with the given key if it is contained within your graph. - * - * @param graphName - * The name of the graph. - * @param collectionName - * The collection, containing the vertex to get. - * @param key - * The key (document handle) of the vertex to get. - * @param clazz - * The class of the vertex to get. - * @param ifMatchRevision - * If not null the revision of the vertex in the database has to - * be equal to return a document. - * @param ifNoneMatchRevision - * If not null the revision of the vertex in the database has to - * be different to return a document. - * @return DocumentEntity The resulting DocumentEntity containing the - * vertex document. - * @throws ArangoException - */ - public VertexEntity graphGetVertex( - final String graphName, - final String collectionName, - final String key, - final Class clazz, - final String ifNoneMatchRevision, - final String ifMatchRevision) throws ArangoException { - return graphDriver.getVertex(getDefaultDatabase(), graphName, collectionName, key, clazz, ifMatchRevision, - ifNoneMatchRevision); - } - - /** - * Deletes a vertex with the given key, if it is contained within the graph. - * Furthermore all edges connected to this vertex will be deleted. - * - * @param graphName - * The name of the graph. - * @param collectionName - * The collection, containing the vertex to delete. - * @param key - * The key (document handle) of the vertex to delete. - * @return DeletedEntity - * @throws ArangoException - */ - public DeletedEntity graphDeleteVertex(final String graphName, final String collectionName, final String key) - throws ArangoException { - return graphDriver.deleteVertex(getDefaultDatabase(), graphName, collectionName, key, null, null, null); - } - - /** - * Deletes a vertex with the given key, if it is contained within the graph. - * Furthermore all edges connected to this vertex will be deleted. - * - * @param graphName - * The name of the graph. - * @param collectionName - * The collection, containing the vertex to delete. - * @param key - * The key (document handle) of the vertex to delete. - * @param waitForSync - * Wait for sync. - * @return DeletedEntity - * @throws ArangoException - */ - public DeletedEntity graphDeleteVertex( - final String graphName, - final String collectionName, - final String key, - final Boolean waitForSync) throws ArangoException { - return graphDriver.deleteVertex(getDefaultDatabase(), graphName, collectionName, key, waitForSync, null, null); - } - - /** - * Deletes a vertex with the given key, if it is contained within the graph. - * Furthermore all edges connected to this vertex will be deleted. - * - * @param graphName - * The name of the graph. - * @param collectionName - * The collection, containing the vertex to delete. - * @param key - * The key (document handle) of the vertex to delete. - * @param waitForSync - * Wait for sync. - * @param ifMatchRevision - * If not null the revision of the vertex in the database has to - * be equal to return a document. - * @param ifNoneMatchRevision - * If not null the revision of the vertex in the database has to - * be different to return a document. - * @return DeletedEntity - * @throws ArangoException - */ - public DeletedEntity graphDeleteVertex( - final String graphName, - final String collectionName, - final String key, - final Boolean waitForSync, - final String ifMatchRevision, - final String ifNoneMatchRevision) throws ArangoException { - return graphDriver.deleteVertex(getDefaultDatabase(), graphName, collectionName, key, waitForSync, - ifMatchRevision, ifNoneMatchRevision); - } - - /** - * Replaces a vertex with the given key by the content in the body. This - * will only run successfully if the vertex is contained within the graph. - * - * @param graphName - * The name of the graph. - * @param collectionName - * The collection, containing the vertex to replace. - * @param key - * The key (document handle) of the vertex to replace. - * @param vertex - * The object to replace the existing vertex. - * @return DocumentEntity - * @throws ArangoException - */ - public VertexEntity graphReplaceVertex( - final String graphName, - final String collectionName, - final String key, - final T vertex) throws ArangoException { - return graphDriver.replaceVertex(getDefaultDatabase(), graphName, collectionName, key, vertex, null, null, - null); - } - - /** - * Replaces a vertex with the given key by the content in the body. This - * will only run successfully if the vertex is contained within the graph. - * - * @param graphName - * The name of the graph. - * @param collectionName - * The collection, containing the vertex to replace. - * @param key - * The key (document handle) of the vertex to replace. - * @param vertex - * The object to replace the existing vertex. - * @param waitForSync - * Wait for sync. - * @param ifMatchRevision - * If not null the revision of the vertex in the database has to - * be equal to replace the document. - * @param ifNoneMatchRevision - * If not null the revision of the vertex in the database has to - * be different to replace the document. - * @return a VertexEntity object - * @throws ArangoException - */ - public VertexEntity graphReplaceVertex( - final String graphName, - final String collectionName, - final String key, - final T vertex, - final Boolean waitForSync, - final String ifMatchRevision, - final String ifNoneMatchRevision) throws ArangoException { - return graphDriver.replaceVertex(getDefaultDatabase(), graphName, collectionName, key, vertex, waitForSync, - ifMatchRevision, ifNoneMatchRevision); - } - - /** - * Updates a vertex with the given key by adding the content in the body. - * This will only run successfully if the vertex is contained within the - * graph. - * - * @param graphName - * The name of the graph. - * @param collectionName - * The collection, containing the vertex to update. - * @param key - * The key (document handle) of the vertex to be updated. - * @param vertex - * The object to update the existing vertex. - * @param keepNull - * True if the update should keep null values - * @return a DocumentEntity object - * @throws ArangoException - */ - public VertexEntity graphUpdateVertex( - final String graphName, - final String collectionName, - final String key, - final T vertex, - final Boolean keepNull) throws ArangoException { - return graphDriver.updateVertex(getDefaultDatabase(), graphName, collectionName, key, vertex, keepNull, null, - null, null); - } - - /** - * Updates a vertex with the given key by adding the content in the body. - * This will only run successfully if the vertex is contained within the - * graph. - * - * @param graphName - * The name of the graph. - * @param collectionName - * The collection, containing the vertex to update. - * @param key - * The key (document handle) of the vertex to be updated. - * @param vertex - * The object to update the existing vertex. - * @param keepNull - * True if the update should keep null values - * @param waitForSync - * Wait for sync. - * @param ifMatchRevision - * If not null the revision of the vertex in the database has to - * be equal to update the document. - * @param ifNoneMatchRevision - * If not null the revision of the vertex in the database has to - * be different to update the document. - * @return DocumentEntity - * @throws ArangoException - */ - public VertexEntity graphUpdateVertex( - final String graphName, - final String collectionName, - final String key, - final T vertex, - final Boolean keepNull, - final Boolean waitForSync, - final String ifMatchRevision, - final String ifNoneMatchRevision) throws ArangoException { - return graphDriver.updateVertex(getDefaultDatabase(), graphName, collectionName, key, vertex, keepNull, - waitForSync, ifMatchRevision, ifNoneMatchRevision); - } - - /** - * Stores a new edge with the information contained within the body into the - * given collection. - * - * @param graphName - * The name of the graph. - * @param edgeCollectionName - * The name of the collection where the edge will be created. - * @param fromHandle - * Document handle of vertex, where the edge comes from. - * @param toHandle - * Document handle of vertex, where the edge goes to. - * @param value - * Object to be stored with edge. - * @param waitForSync - * Wait for sync. - * @return EdgeEntity - * @throws ArangoException - */ - public EdgeEntity graphCreateEdge( - final String graphName, - final String edgeCollectionName, - final String fromHandle, - final String toHandle, - final T value, - final Boolean waitForSync) throws ArangoException { - return graphDriver.createEdge(getDefaultDatabase(), graphName, edgeCollectionName, null, fromHandle, toHandle, - value, waitForSync); - } - - /** - * Stores a new edge with the information contained within the body into the - * given collection. - * - * @param graphName - * The name of the graph. - * @param edgeCollectionName - * The name of the collection where the edge will be created. - * @param key - * The key of the edge to create (has to be unique). - * @param fromHandle - * Document handle of vertex, where the edge comes from. - * @param toHandle - * Document handle of vertex, where the edge goes to. - * @param value - * Object to be stored with edge. - * @param waitForSync - * Wait for sync. - * @return a EdgeEntity object - * @throws ArangoException - */ - public EdgeEntity graphCreateEdge( - final String graphName, - final String edgeCollectionName, - final String key, - final String fromHandle, - final String toHandle, - final T value, - final Boolean waitForSync) throws ArangoException { - return graphDriver.createEdge(getDefaultDatabase(), graphName, edgeCollectionName, key, fromHandle, toHandle, - value, waitForSync); - } - - /** - * Stores a new edge with no further information into the given collection. - * - * @param graphName - * The name of the graph. - * @param edgeCollectionName - * The name of the collection where the edge will be created. - * @param key - * The key of the edge to create (has to be unique). - * @param fromHandle - * Document handle of vertex, where the edge comes from. - * @param toHandle - * Document handle of vertex, where the edge goes to. - * @return a EdgeEntity object - * @throws ArangoException - */ - public EdgeEntity graphCreateEdge( - final String graphName, - final String edgeCollectionName, - final String key, - final String fromHandle, - final String toHandle) throws ArangoException { - return graphDriver.createEdge(getDefaultDatabase(), graphName, edgeCollectionName, key, fromHandle, toHandle, - null, null); - } - - /** - * Loads an edge with the given key if it is contained within your graph. - * - * @param graphName - * The name of the graph. - * @param edgeCollectionName - * The name of the collection containing edge to get. - * @param key - * The key of the edge to get. - * @param clazz - * The class of the edge to get. - * @param ifMatchRevision - * If not null the revision of the vertex in the database has to - * be equal to load the edge. - * @param ifNoneMatchRevision - * If not null the revision of the vertex in the database has to - * be different to load the edge. - * @return a EdgeEntity object - * @throws ArangoException - */ - public EdgeEntity graphGetEdge( - final String graphName, - final String edgeCollectionName, - final String key, - final Class clazz, - final String ifMatchRevision, - final String ifNoneMatchRevision) throws ArangoException { - return graphDriver.getEdge(getDefaultDatabase(), graphName, edgeCollectionName, key, clazz, ifMatchRevision, - ifNoneMatchRevision); - } - - /** - * Loads an edge with the given key if it is contained within your graph. - * - * @param graphName - * The name of the graph. - * @param edgeCollectionName - * The name of the collection containing edge to get. - * @param key - * The key of the edge to get. - * @param clazz - * The class of the edge to get. - * @return a EdgeEntity object - * @throws ArangoException - */ - public EdgeEntity graphGetEdge( - final String graphName, - final String edgeCollectionName, - final String key, - final Class clazz) throws ArangoException { - return graphDriver.getEdge(getDefaultDatabase(), graphName, edgeCollectionName, key, clazz, null, null); - } - - /** - * Deletes an edge with the given id, if it is contained within the graph. - * - * @param graphName - * The name of the graph. - * @param edgeCollectionName - * The name of the collection containing edge to delete. - * @param key - * The key of the edge to delete. - * @return DeletedEntity - * @throws ArangoException - */ - public DeletedEntity graphDeleteEdge(final String graphName, final String edgeCollectionName, final String key) - throws ArangoException { - return graphDriver.deleteEdge(getDefaultDatabase(), graphName, edgeCollectionName, key, null, null, null); - } - - /** - * Deletes an edge with the given id, if it is contained within the graph. - * - * @param graphName - * The name of the graph. - * @param edgeCollectionName - * The name of the collection containing edge to delete. - * @param key - * The key of the edge to delete. - * @param waitForSync - * Wait for sync. - * @return a DeletedEntity object - * @throws ArangoException - */ - public DeletedEntity graphDeleteEdge( - final String graphName, - final String edgeCollectionName, - final String key, - final Boolean waitForSync) throws ArangoException { - return graphDriver.deleteEdge(getDefaultDatabase(), graphName, edgeCollectionName, key, waitForSync, null, - null); - } - - /** - * Deletes an edge with the given id, if it is contained within the graph. - * - * @param graphName - * The name of the graph. - * @param edgeCollectionName - * The name of the collection containing edge to delete. - * @param key - * The key of the edge to delete. - * @param waitForSync - * Wait for sync. - * @param ifMatchRevision - * If not null the revision of the vertex in the database has to - * be equal to delete the edge. - * @param ifNoneMatchRevision - * If not null the revision of the vertex in the database has to - * be different to delete the edge. - * @return DeletedEntity - * @throws ArangoException - */ - public DeletedEntity graphDeleteEdge( - final String graphName, - final String edgeCollectionName, - final String key, - final Boolean waitForSync, - final String ifMatchRevision, - final String ifNoneMatchRevision) throws ArangoException { - return graphDriver.deleteEdge(getDefaultDatabase(), graphName, edgeCollectionName, key, waitForSync, - ifMatchRevision, ifNoneMatchRevision); - } - - /** - * Replaces an edge with the given key by the content in the body. This will - * only run successfully if the edge is contained within the graph. - * - * @param graphName - * The name of the graph. - * @param edgeCollectionName - * The name of the collection containing edge to replace. - * @param key - * The key of the edge to replace. - * @param fromHandle - * Document handle of vertex, where the edge comes from. (can be - * null if value contains "_from" attribute) - * @param toHandle - * Document handle of vertex, where the edge goes to. (can be - * null if value contains "_to" attribute) - * @param value - * The object to replace the existing edge. - * @return a EdgeEntity object - * @throws ArangoException - */ - public EdgeEntity graphReplaceEdge( - final String graphName, - final String edgeCollectionName, - final String key, - final String fromHandle, - final String toHandle, - final T value) throws ArangoException { - return graphDriver.replaceEdge(getDefaultDatabase(), graphName, edgeCollectionName, key, fromHandle, toHandle, - value, null, null, null); - } - - /** - * Replaces an edge with the given key by the content in the body. This will - * only run successfully if the edge is contained within the graph. - * - * @param graphName - * The name of the graph. - * @param edgeCollectionName - * The name of the collection containing edge to replace. - * @param key - * The key of the edge to replace. - * @param fromHandle - * Document handle of vertex, where the edge comes from. (can be - * null if value contains "_from" attribute) - * @param toHandle - * Document handle of vertex, where the edge goes to. (can be - * null if value contains "_to" attribute) - * @param value - * The object to replace the existing edge. Since ArangoDB 3.X - * the replacement should contain "_from" and "_to". - * @param waitForSync - * Wait for sync. - * @param ifMatchRevision - * If not null the revision of the vertex in the database has to - * be equal to replace the edge. - * @param ifNoneMatchRevision - * If not null the revision of the vertex in the database has to - * be different to replace the edge. - * @return a EdgeEntity object - * @throws ArangoException - */ - public EdgeEntity graphReplaceEdge( - final String graphName, - final String edgeCollectionName, - final String key, - final String fromHandle, - final String toHandle, - final T value, - final Boolean waitForSync, - final String ifMatchRevision, - final String ifNoneMatchRevision) throws ArangoException { - return graphDriver.replaceEdge(getDefaultDatabase(), graphName, edgeCollectionName, key, fromHandle, toHandle, - value, waitForSync, ifMatchRevision, ifNoneMatchRevision); - } - - /** - * Updates an edge with the given key by adding the content in the body. - * This will only run successfully if the edge is contained within the - * graph. - * - * @param graphName - * The name of the graph. - * @param edgeCollectionName - * The name of the collection containing edge to update. - * @param key - * The key of the edge to update. - * @param fromHandle - * Document handle of vertex, where the edge comes from. (can be - * null if value contains "_from" attribute) - * @param toHandle - * Document handle of vertex, where the edge goes to. (can be - * null if value contains "_to" attribute) - * @param value - * The object to update the existing edge. - * @param keepNull - * @return a EdgeEntity object - * @throws ArangoException - */ - public EdgeEntity graphUpdateEdge( - final String graphName, - final String edgeCollectionName, - final String key, - final String fromHandle, - final String toHandle, - final T value, - final Boolean keepNull) throws ArangoException { - return graphDriver.updateEdge(getDefaultDatabase(), graphName, edgeCollectionName, key, fromHandle, toHandle, - value, null, keepNull, null, null); - } - - /** - * Updates an edge with the given key by adding the content in the body. - * This will only run successfully if the edge is contained within the - * graph. - * - * @param graphName - * The name of the graph. - * @param edgeCollectionName - * The name of the collection containing edge to update. - * @param key - * The key of the edge to update. - * @param value - * The object to update the existing edge. - * @param fromHandle - * Document handle of vertex, where the edge comes from. (can be - * null if value contains "_from" attribute) - * @param toHandle - * Document handle of vertex, where the edge goes to. (can be - * null if value contains "_to" attribute) - * @param waitForSync - * Wait for sync. - * @param keepNull - * @param ifMatchRevision - * If not null the revision of the vertex in the database has to - * be equal to update the edge. - * @param ifNoneMatchRevision - * If not null the revision of the vertex in the database has to - * be different to update the edge. - * @return a EdgeEntity object - * @throws ArangoException - */ - public EdgeEntity graphUpdateEdge( - final String graphName, - final String edgeCollectionName, - final String key, - final String fromHandle, - final String toHandle, - final T value, - final Boolean waitForSync, - final Boolean keepNull, - final String ifMatchRevision, - final String ifNoneMatchRevision) throws ArangoException { - return graphDriver.updateEdge(getDefaultDatabase(), graphName, edgeCollectionName, key, fromHandle, toHandle, - value, waitForSync, keepNull, ifMatchRevision, ifNoneMatchRevision); - } - - // Some methods not using the graph api - - /** - * Returns edges as an EdgeCursor by a given query - * - * @param query - * the query - * @param bindVars - * the variables - * @param aqlQueryOptions - * AQL query options (null for default values) - * @param clazz - * the result class - * @return EdgeCursor - * @throws ArangoException - */ - public EdgeCursor executeEdgeQuery( - final String query, - final Map bindVars, - final AqlQueryOptions aqlQueryOptions, - final Class clazz) throws ArangoException { - - @SuppressWarnings("unchecked") - final DocumentCursorResult> baseCursor = cursorDriver.executeBaseCursorQuery( - getDefaultDatabase(), query, bindVars, getAqlQueryOptions(aqlQueryOptions), EdgeEntity.class, clazz); - return new EdgeCursor(baseCursor); - } - - /** - * Returns vertices as a VertexCursor by a given query - * - * @param query - * the query - * @param bindVars - * the variables - * @param aqlQueryOptions - * AQL query options (null for default values) - * @param clazz - * the result class - * @return VertexCursor - * @throws ArangoException - */ - public VertexCursor executeVertexQuery( - final String query, - final Map bindVars, - final AqlQueryOptions aqlQueryOptions, - final Class clazz) throws ArangoException { - - @SuppressWarnings("unchecked") - final DocumentCursorResult> baseCursor = cursorDriver.executeBaseCursorQuery( - getDefaultDatabase(), query, bindVars, getAqlQueryOptions(aqlQueryOptions), VertexEntity.class, clazz); - return new VertexCursor(baseCursor); - } - - /** - * Returns an EdgeCursor by a given vertex example and some options - * - * @deprecated use AQL instead - * @param graphName - * The name of the graph. - * @param clazz - * @param vertexExample - * An example for the desired vertices - * @param graphEdgesOptions - * An object containing the options - * @param aqlQueryOptions - * AQL query options (null for default values (count = true)) - * @return EdgeCursor - * @throws ArangoException - */ - @Deprecated - @SuppressWarnings("unchecked") - public EdgeCursor graphGetEdgeCursor( - final String graphName, - final Class clazz, - final Object vertexExample, - final GraphEdgesOptions graphEdgesOptions, - final AqlQueryOptions aqlQueryOptions) throws ArangoException { - - GraphEdgesOptions tmpGraphEdgesOptions = graphEdgesOptions; - if (tmpGraphEdgesOptions == null) { - tmpGraphEdgesOptions = new GraphEdgesOptions(); - } - - validateCollectionName(graphName); - - final MapBuilder mapBuilder = new MapBuilder(); - final String query = GraphQueryUtil.createEdgeQuery(this, graphName, vertexExample, tmpGraphEdgesOptions, - mapBuilder); - final Map bindVars = mapBuilder.get(); - - AqlQueryOptions tmpAqlQueryOptions = aqlQueryOptions; - if (tmpAqlQueryOptions == null) { - tmpAqlQueryOptions = getDefaultAqlQueryOptions().setCount(true); - } - - final DocumentCursorResult> cursor = executeAqlQueryWithDocumentCursorResult(query, bindVars, - tmpAqlQueryOptions, EdgeEntity.class, clazz); - - return new EdgeCursor(cursor); - } - - /** - * Returns a VertexCursor by a given vertex example and some options - * - * @deprecated use AQL instead - * @param graphName - * The name of the graph. - * @param clazz - * @param vertexExample - * An example for the desired vertices - * @param graphVerticesOptions - * An object containing the options - * @param aqlQueryOptions - * AQL query options - * @return VertexCursor - * @throws ArangoException - */ - @Deprecated - public VertexCursor graphGetVertexCursor( - final String graphName, - final Class clazz, - final Object vertexExample, - final GraphVerticesOptions graphVerticesOptions, - final AqlQueryOptions aqlQueryOptions) throws ArangoException { - - validateCollectionName(graphName); - - GraphVerticesOptions tmpGraphVerticesOptions = graphVerticesOptions; - if (tmpGraphVerticesOptions == null) { - tmpGraphVerticesOptions = new GraphVerticesOptions(); - } - - final MapBuilder mapBuilder = new MapBuilder(); - final String query = GraphQueryUtil.createVerticesQuery(this, graphName, vertexExample, tmpGraphVerticesOptions, - mapBuilder); - final Map bindVars = mapBuilder.get(); - - return executeVertexQuery(query, bindVars, aqlQueryOptions, clazz); - } - - /** - * Returns all Edges of a graph, each edge as a PlainEdgeEntity. - * - * @param graphName - * The name of the graph. - * @return EdgeCursor - * @throws ArangoException - */ - public EdgeCursor graphGetEdgeCursor(final String graphName) throws ArangoException { - validateCollectionName(graphName); - - return graphGetEdgeCursor(graphName, PlainEdgeEntity.class, null, new GraphEdgesOptions(), null); - } - - /** - * Returns all Edges of a given vertex. - * - * @param graphName - * @param clazz - * @param vertexExample - * a vertex example or a document handle - * @return EdgeCursor - * @throws ArangoException - */ - public EdgeCursor graphGetEdgeCursorByExample( - final String graphName, - final Class clazz, - final Object vertexExample) throws ArangoException { - - return graphGetEdgeCursor(graphName, clazz, vertexExample, new GraphEdgesOptions(), null); - } - - /** - * @deprecated use AQL instead - */ - @Deprecated - public ShortestPathEntity graphGetShortestPath( - final String graphName, - final Object startVertexExample, - final Object endVertexExample, - final ShortestPathOptions shortestPathOptions, - final Class vertexClass, - final Class edgeClass) throws ArangoException { - - ShortestPathOptions tmpShortestPathOptions = shortestPathOptions; - if (tmpShortestPathOptions == null) { - tmpShortestPathOptions = new ShortestPathOptions(); - } - - return cursorDriver.getShortestPath(getDefaultDatabase(), graphName, startVertexExample, endVertexExample, - tmpShortestPathOptions, getDefaultAqlQueryOptions(), vertexClass, edgeClass, this); - } - - /** - * Creates an AQL Function - * - * @param name - * the name of the function as string - * @param code - * the function as javascript string - * @return DefaultEntity - * @throws ArangoException - */ - public DefaultEntity createAqlFunction(final String name, final String code) throws ArangoException { - return aqlFunctionsDriver.createAqlFunction(getDefaultDatabase(), name, code); - } - - /** - * Gets all AQL functions whithin a given namespace - * - * @param namespace - * the namespace - * @return AqlFunctionsEntity - * @throws ArangoException - */ - public AqlFunctionsEntity getAqlFunctions(final String namespace) throws ArangoException { - return aqlFunctionsDriver.getAqlFunctions(getDefaultDatabase(), namespace); - } - - /** - * Delete an AQL function. If *isNameSpace* is set to true all functions - * within the namespace *name* are deleted. - * - * @param name - * This is either the name of a function or a namespace - * @param isNameSpace - * If set to true the param *name* is treated as a namespace - * @return DefaultEntity - * @throws ArangoException - */ - public DefaultEntity deleteAqlFunction(final String name, final boolean isNameSpace) throws ArangoException { - return aqlFunctionsDriver.deleteAqlFunction(getDefaultDatabase(), name, isNameSpace); - } - - /** - * Creates a transaction entity. - * - * @param action - * the transaction as javascript code - * @return TransactionEntity - */ - public TransactionEntity createTransaction(final String action) { - return this.transactionDriver.createTransaction(action); - } - - /** - * Executes the transaction on the database server. - * - * @param transactionEntity - * The configuration object containing all data for the - * transaction - * @return TransactionResultEntity - * @throws ArangoException - */ - public TransactionResultEntity executeTransaction(final TransactionEntity transactionEntity) - throws ArangoException { - return this.transactionDriver.executeTransaction(getDefaultDatabase(), transactionEntity); - } - - /** - * Create an edge in an edge collection. - * - * @param collectionName - * name of the edge collection - * @param value - * the edge object - * @param fromHandle - * id of document 'from' - * @param toHandle - * id of document 'to' - * @param waitForSync - * wait for sync - * @return the new created EdgeEntity object - * @throws ArangoException - */ - public EdgeEntity createEdge( - final String collectionName, - final T value, - final String fromHandle, - final String toHandle, - final Boolean waitForSync) throws ArangoException { - - return createEdge(collectionName, null, value, fromHandle, toHandle, waitForSync); - } - - /** - * Create an edge in an edge collection. This method allows to define to - * documents key. Note that the collection's property - * CollectionKeyOption.allowUserKeys has to be set accordingly. - * - * @param collectionName - * name of the edge collection - * @param documentKey - * the desired document key - * @param value - * the edge object - * @param fromHandle - * id of document 'from' - * @param toHandle - * id of document 'to' - * @param waitForSync - * wait for sync - * @return the new created EdgeEntity object - * @throws ArangoException - */ - public EdgeEntity createEdge( - final String collectionName, - final String documentKey, - final T value, - final String fromHandle, - final String toHandle, - final Boolean waitForSync) throws ArangoException { - - return documentDriver.createEdge(getDefaultDatabase(), collectionName, documentKey, value, fromHandle, toHandle, - waitForSync); - } - - /** - * Do a graph traversal. - * - * See API documentation of Traversals - * - * @param traversalQueryOptions - * the traversal options - * @param vertexClazz - * Class of returned vertex documents. - * @param edgeClazz - * Class of returned edge documents. - * @return a TraversalEntity object - * @throws ArangoException - */ - public TraversalEntity getTraversal( - final TraversalQueryOptions traversalQueryOptions, - final Class vertexClazz, - final Class edgeClazz) throws ArangoException { - - return this.traversalDriver.getTraversal(getDefaultDatabase(), traversalQueryOptions, vertexClazz, edgeClazz); - } - - /** - * Clears the AQL query cache (since ArangoDB 2.7) - * - * @return DefaultEntity - * @throws ArangoException - */ - public DefaultEntity deleteQueryCache() throws ArangoException { - return queryCacheDriver.deleteQueryCache(); - } - - /** - * Returns the global configuration for the AQL query cache (since ArangoDB - * 2.7) - * - * @return QueryCachePropertiesEntity - * @throws ArangoException - */ - public QueryCachePropertiesEntity getQueryCacheProperties() throws ArangoException { - return queryCacheDriver.getQueryCacheProperties(); - } - - /** - * Changes the configuration for the AQL query cache (since ArangoDB 2.7) - * - * @return QueryCachePropertiesEntity - * @throws ArangoException - */ - public QueryCachePropertiesEntity setQueryCacheProperties(final QueryCachePropertiesEntity properties) - throws ArangoException { - return queryCacheDriver.setQueryCacheProperties(properties); - } - - /** - * Returns the configuration for the AQL query tracking - * - * @return the configuration - * @throws ArangoException - */ - public QueryTrackingPropertiesEntity getQueryTrackingProperties() throws ArangoException { - return this.cursorDriver.getQueryTrackingProperties(getDefaultDatabase()); - } - - /** - * Changes the configuration for the AQL query tracking - * - * @param properties - * the configuration - * @return the configuration - * @throws ArangoException - */ - public QueryTrackingPropertiesEntity setQueryTrackingProperties(final QueryTrackingPropertiesEntity properties) - throws ArangoException { - return this.cursorDriver.setQueryTrackingProperties(getDefaultDatabase(), properties); - } - - /** - * Returns a list of currently running AQL queries of the default database - * - * @return a list of currently running AQL queries - * @throws ArangoException - */ - public QueriesResultEntity getCurrentlyRunningQueries() throws ArangoException { - return this.cursorDriver.getCurrentlyRunningQueries(getDefaultDatabase()); - } - - /** - * Returns a list of currently running AQL queries of a database - * - * @param database - * the database name or null - * @return a list of currently running AQL queries - * @throws ArangoException - */ - public QueriesResultEntity getCurrentlyRunningQueries(final String database) throws ArangoException { - return this.cursorDriver.getCurrentlyRunningQueries(database); - } - - /** - * Returns a list of slow running AQL queries of the default database - * - * @return a list of slow running AQL queries - * @throws ArangoException - */ - public QueriesResultEntity getSlowQueries() throws ArangoException { - return this.cursorDriver.getSlowQueries(getDefaultDatabase()); - } - - /** - * Returns a list of slow running AQL queries of a database - * - * @param database - * the database name or null - * @return a list of slow running AQL queries - * @throws ArangoException - */ - public QueriesResultEntity getSlowQueries(final String database) throws ArangoException { - return this.cursorDriver.getSlowQueries(database); - } - - /** - * Clears the list of slow AQL queries of the default database - * - * @return a DefaultEntity object - * @throws ArangoException - */ - public DefaultEntity deleteSlowQueries() throws ArangoException { - return this.cursorDriver.deleteSlowQueries(getDefaultDatabase()); - } - - /** - * Clears the list of slow AQL queries of the default database - * - * @param database - * the database name or null - * @return a DefaultEntity object - * @throws ArangoException - */ - public DefaultEntity deleteSlowQueries(final String database) throws ArangoException { - return this.cursorDriver.deleteSlowQueries(database); - } - - /** - * Kills an AQL query - * - * @param id - * the identifier of a query - * @return a DefaultEntity object - * @throws ArangoException - */ - public DefaultEntity killQuery(final String id) throws ArangoException { - return this.cursorDriver.killQuery(getDefaultDatabase(), id); - } - - /** - * Kills an AQL query - * - * @param id - * the identifier of a query - * @param database - * the database name or null - * @return a DefaultEntity object - * @throws ArangoException - */ - public DefaultEntity killQuery(final String database, final String id) throws ArangoException { - return this.cursorDriver.killQuery(database, id); - } - - /** - * Returns the HTTP manager of the driver - * - * @return httpManager - */ - public HttpManager getHttpManager() { - return httpManager; - } - - /** - * Creates a document in the collection defined by the collection's name - * - * @param collectionName - * The name of the collection - * @param rawJsonString - * A string containing a JSON object - * @param waitForSync - * if set to true the response is returned when the server has - * finished. - * @return DocumentEntity - * @throws ArangoException - */ - public DocumentEntity createDocumentRaw( - final String collectionName, - final String rawJsonString, - final Boolean waitForSync) throws ArangoException { - return documentDriver.createDocumentRaw(getDefaultDatabase(), collectionName, rawJsonString, waitForSync); - } - - /** - * Returns the document as a JSON string. Note that the - * *ifNoneMatchRevision* and *ifMatchRevision* can not be used at the same - * time, one of these two has to be null. - * - * Throws ArangoException if the requested document is not available. - * - * @param documentHandle - * The document handle - * @param ifNoneMatchRevision - * if set the document is only returned id it has a different - * revision. - * @param ifMatchRevision - * if set the document is only returned id it has the same - * revision. - * @return a String - * @throws ArangoException - */ - public String getDocumentRaw( - final String documentHandle, - final String ifNoneMatchRevision, - final String ifMatchRevision) throws ArangoException { - return documentDriver.getDocumentRaw(getDefaultDatabase(), documentHandle, ifNoneMatchRevision, - ifMatchRevision); - } - - /** - * This method executes an AQL query and returns a CursorRawResult. - * - * Use CursorRawResult.iterator() to get the raw JSON strings. - * - * @param query - * an AQL query as string - * @param bindVars - * a map containing all bind variables, - * @param aqlQueryOptions - * AQL query options - * @return CursorRawResult - * @throws ArangoException - */ - public CursorRawResult executeAqlQueryRaw( - final String query, - final Map bindVars, - final AqlQueryOptions aqlQueryOptions) throws ArangoException { - - return cursorDriver.executeAqlQueryRaw(getDefaultDatabase(), query, bindVars, - getAqlQueryOptions(aqlQueryOptions)); - } - - /** - * This method replaces the content of the document defined by - * documentHandle. This method offers a parameter rev (revision). If the - * revision of the document on the server does not match the given revision - * an error is thrown. - * - * @param documentHandle - * The document's handle. - * @param rawJsonString - * A string containing a JSON object - * @param rev - * the desired revision. - * @param waitForSync - * if set to true the response is returned when the server has - * finished. - * @return DocumentEntity - * @throws ArangoException - */ - public DocumentEntity replaceDocumentRaw( - final String documentHandle, - final String rawJsonString, - final String rev, - final Boolean waitForSync) throws ArangoException { - return documentDriver.replaceDocumentRaw(getDefaultDatabase(), documentHandle, rawJsonString, rev, waitForSync); - } - - /** - * This method updates a document defined by documentHandle. This method - * offers a parameter rev (revision). If the revision of the document on the - * server does not match the given revision an error is thrown. - * - * @param documentHandle - * The document handle. - * @param rawJsonString - * A string containing a JSON object - * @param rev - * The desired revision - * @param waitForSync - * if set to true the response is returned when the server has - * finished. - * @param keepNull - * If true null values are kept. - * @return DocumentEntity - * @throws ArangoException - */ - public DocumentEntity updateDocumentRaw( - final String documentHandle, - final String rawJsonString, - final String rev, - final Boolean waitForSync, - final Boolean keepNull) throws ArangoException { - return documentDriver.updateDocumentRaw(getDefaultDatabase(), documentHandle, rawJsonString, rev, waitForSync, - keepNull); - } - - // - // private functions - // - - private void createModuleDrivers(final boolean createProxys) { - if (!createProxys) { - this.cursorDriver = ImplFactory.createCursorDriver(configure, this.httpManager); - this.batchDriver = ImplFactory.createBatchDriver(configure, this.httpManager); - this.collectionDriver = ImplFactory.createCollectionDriver(configure, this.httpManager); - this.documentDriver = ImplFactory.createDocumentDriver(configure, this.httpManager); - this.indexDriver = ImplFactory.createIndexDriver(configure, this.httpManager); - this.adminDriver = ImplFactory.createAdminDriver(configure, this.httpManager); - this.aqlFunctionsDriver = ImplFactory.createAqlFunctionsDriver(configure, this.httpManager); - this.simpleDriver = ImplFactory.createSimpleDriver(configure, cursorDriver, this.httpManager); - this.usersDriver = ImplFactory.createUsersDriver(configure, this.httpManager); - this.importDriver = ImplFactory.createImportDriver(configure, this.httpManager); - this.databaseDriver = ImplFactory.createDatabaseDriver(configure, this.httpManager); - this.endpointDriver = ImplFactory.createEndpointDriver(configure, this.httpManager); - this.replicationDriver = ImplFactory.createReplicationDriver(configure, this.httpManager); - this.graphDriver = ImplFactory.createGraphDriver(configure, cursorDriver, this.httpManager); - this.jobsDriver = ImplFactory.createJobsDriver(configure, this.httpManager); - this.transactionDriver = ImplFactory.createTransactionDriver(configure, this.httpManager); - this.traversalDriver = ImplFactory.createTraversalDriver(configure, httpManager); - this.queryCacheDriver = ImplFactory.createQueryCacheDriver(configure, httpManager); - } else { - this.transactionDriver = (InternalTransactionDriver) Proxy.newProxyInstance( - InternalTransactionDriver.class.getClassLoader(), new Class[] { InternalTransactionDriver.class }, - new InvocationHandlerImpl(this.transactionDriver)); - this.jobsDriver = (InternalJobsDriver) Proxy.newProxyInstance(InternalJobsDriver.class.getClassLoader(), - new Class[] { InternalJobsDriver.class }, new InvocationHandlerImpl(this.jobsDriver)); - this.cursorDriver = (InternalCursorDriver) Proxy.newProxyInstance( - InternalCursorDriver.class.getClassLoader(), new Class[] { InternalCursorDriver.class }, - new InvocationHandlerImpl(this.cursorDriver)); - this.collectionDriver = (InternalCollectionDriver) Proxy.newProxyInstance( - InternalCollectionDriver.class.getClassLoader(), new Class[] { InternalCollectionDriver.class }, - new InvocationHandlerImpl(this.collectionDriver)); - this.documentDriver = (InternalDocumentDriver) Proxy.newProxyInstance( - InternalDocumentDriver.class.getClassLoader(), new Class[] { InternalDocumentDriver.class }, - new InvocationHandlerImpl(this.documentDriver)); - this.indexDriver = (InternalIndexDriver) Proxy.newProxyInstance(InternalIndexDriver.class.getClassLoader(), - new Class[] { InternalIndexDriver.class }, new InvocationHandlerImpl(this.indexDriver)); - this.adminDriver = (InternalAdminDriver) Proxy.newProxyInstance(InternalAdminDriver.class.getClassLoader(), - new Class[] { InternalAdminDriver.class }, new InvocationHandlerImpl(this.adminDriver)); - this.aqlFunctionsDriver = (InternalAqlFunctionsDriver) Proxy.newProxyInstance( - InternalAqlFunctionsDriver.class.getClassLoader(), new Class[] { InternalAqlFunctionsDriver.class }, - new InvocationHandlerImpl(this.aqlFunctionsDriver)); - this.simpleDriver = (InternalSimpleDriver) Proxy.newProxyInstance( - InternalSimpleDriver.class.getClassLoader(), new Class[] { InternalSimpleDriver.class }, - new InvocationHandlerImpl(this.simpleDriver)); - this.usersDriver = (InternalUsersDriver) Proxy.newProxyInstance(InternalUsersDriver.class.getClassLoader(), - new Class[] { InternalUsersDriver.class }, new InvocationHandlerImpl(this.usersDriver)); - this.importDriver = (InternalImportDriver) Proxy.newProxyInstance( - InternalImportDriver.class.getClassLoader(), new Class[] { InternalImportDriver.class }, - new InvocationHandlerImpl(this.importDriver)); - this.databaseDriver = (InternalDatabaseDriver) Proxy.newProxyInstance( - InternalDatabaseDriver.class.getClassLoader(), new Class[] { InternalDatabaseDriver.class }, - new InvocationHandlerImpl(this.databaseDriver)); - this.endpointDriver = (InternalEndpointDriver) Proxy.newProxyInstance( - InternalEndpointDriver.class.getClassLoader(), new Class[] { InternalEndpointDriver.class }, - new InvocationHandlerImpl(this.endpointDriver)); - this.replicationDriver = (InternalReplicationDriver) Proxy.newProxyInstance( - InternalReplicationDriver.class.getClassLoader(), new Class[] { InternalReplicationDriver.class }, - new InvocationHandlerImpl(this.replicationDriver)); - this.graphDriver = (InternalGraphDriver) Proxy.newProxyInstance(InternalGraphDriver.class.getClassLoader(), - new Class[] { InternalGraphDriver.class }, new InvocationHandlerImpl(this.graphDriver)); - this.traversalDriver = (InternalTraversalDriver) Proxy.newProxyInstance( - InternalTraversalDriver.class.getClassLoader(), new Class[] { InternalTraversalDriver.class }, - new InvocationHandlerImpl(this.traversalDriver)); - this.queryCacheDriver = (InternalQueryCacheDriver) Proxy.newProxyInstance( - InternalQueryCacheDriver.class.getClassLoader(), new Class[] { InternalQueryCacheDriver.class }, - new InvocationHandlerImpl(this.queryCacheDriver)); - } - } - - private AqlQueryOptions getAqlQueryOptions(final AqlQueryOptions aqlQueryOptions) { - if (aqlQueryOptions == null) { - return getDefaultAqlQueryOptions(); - } - return aqlQueryOptions; - } -} diff --git a/src/main/java/com/arangodb/ArangoEdgeCollection.java b/src/main/java/com/arangodb/ArangoEdgeCollection.java new file mode 100644 index 000000000..42a3b14d2 --- /dev/null +++ b/src/main/java/com/arangodb/ArangoEdgeCollection.java @@ -0,0 +1,207 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb; + +import com.arangodb.entity.EdgeEntity; +import com.arangodb.entity.EdgeUpdateEntity; +import com.arangodb.internal.InternalArangoEdgeCollection; +import com.arangodb.internal.ArangoExecutorSync; +import com.arangodb.internal.velocystream.ConnectionSync; +import com.arangodb.model.DocumentReadOptions; +import com.arangodb.model.EdgeCreateOptions; +import com.arangodb.model.EdgeDeleteOptions; +import com.arangodb.model.EdgeReplaceOptions; +import com.arangodb.model.EdgeUpdateOptions; +import com.arangodb.velocystream.Response; + +/** + * @author Mark - mark at arangodb.com + * + */ +public class ArangoEdgeCollection extends InternalArangoEdgeCollection { + + protected ArangoEdgeCollection(final ArangoGraph graph, final String name) { + super(graph.executor(), graph.db(), graph.name(), 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 + */ + public EdgeEntity insertEdge(final T value) throws ArangoDBException { + return executor.execute(insertEdgeRequest(value, new EdgeCreateOptions()), + insertEdgeResponseDeserializer(value)); + } + + /** + * 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 + */ + public EdgeEntity insertEdge(final T value, final EdgeCreateOptions options) throws ArangoDBException { + return executor.execute(insertEdgeRequest(value, options), insertEdgeResponseDeserializer(value)); + } + + /** + * 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 + */ + public T getEdge(final String key, final Class type) throws ArangoDBException { + return executor.execute(getEdgeRequest(key, new DocumentReadOptions()), getEdgeResponseDeserializer(type)); + } + + /** + * 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 + */ + public T getEdge(final String key, final Class type, final DocumentReadOptions options) + throws ArangoDBException { + return executor.execute(getEdgeRequest(key, options), getEdgeResponseDeserializer(type)); + } + + /** + * 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 type + * The type of the edge-document (POJO class, VPackSlice or String for Json) + * @return information about the edge + * @throws ArangoDBException + */ + public EdgeUpdateEntity replaceEdge(final String key, final T value) throws ArangoDBException { + return executor.execute(replaceEdgeRequest(key, value, new EdgeReplaceOptions()), + replaceEdgeResponseDeserializer(value)); + } + + /** + * 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 type + * 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 + */ + public EdgeUpdateEntity replaceEdge(final String key, final T value, final EdgeReplaceOptions options) + throws ArangoDBException { + return executor.execute(replaceEdgeRequest(key, value, options), replaceEdgeResponseDeserializer(value)); + } + + /** + * Partially updates the edge identified by document-key. The value must contain a document with the attributes to + * patch (the patch document). All attributes from the patch document will be added to the existing document if they + * do not yet exist, and overwritten in the existing document if they do exist there. + * + * @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 information about the edge + * @throws ArangoDBException + */ + public EdgeUpdateEntity updateEdge(final String key, final T value) throws ArangoDBException { + return executor.execute(updateEdgeRequest(key, value, new EdgeUpdateOptions()), + updateEdgeResponseDeserializer(value)); + } + + /** + * Partially updates the edge identified by document-key. The value must contain a document with the attributes to + * patch (the patch document). All attributes from the patch document will be added to the existing document if they + * do not yet exist, and overwritten in the existing document if they do exist there. + * + * @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 information about the edge + * @throws ArangoDBException + */ + public EdgeUpdateEntity updateEdge(final String key, final T value, final EdgeUpdateOptions options) + throws ArangoDBException { + return executor.execute(updateEdgeRequest(key, value, options), updateEdgeResponseDeserializer(value)); + } + + /** + * Removes a edge + * + * @see API Documentation + * @param key + * The key of the edge + * @throws ArangoDBException + */ + public void deleteEdge(final String key) throws ArangoDBException { + executor.execute(deleteEdgeRequest(key, new EdgeDeleteOptions()), Void.class); + } + + /** + * Removes a edge + * + * @see API Documentation + * @param key + * The key of the edge + * @param options + * Additional options, can be null + * @throws ArangoDBException + */ + 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/ArangoException.java b/src/main/java/com/arangodb/ArangoException.java deleted file mode 100644 index 35c370800..000000000 --- a/src/main/java/com/arangodb/ArangoException.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Copyright (C) 2012 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb; - -import com.arangodb.entity.BaseEntity; - -/** - * @author tamtam180 - kirscheless at gmail.com - * - */ -public class ArangoException extends Exception { - - protected final BaseEntity entity; - - public ArangoException() { - super(); - this.entity = null; - } - - public ArangoException(BaseEntity entity) { - super((entity.getErrorNumber() == 0 ? "" : "[" + entity.getErrorNumber() + "] ") + entity.getErrorMessage()); - this.entity = entity; - } - - public ArangoException(String message, Throwable cause) { - super(message, cause); - this.entity = null; - } - - public ArangoException(String message) { - super(message); - this.entity = null; - } - - public ArangoException(Throwable cause) { - super(cause); - this.entity = null; - } - - public int getErrorNumber() { - return (entity == null) ? 0 : entity.getErrorNumber(); - } - - public int getCode() { - return (entity == null) ? 0 : entity.getCode(); - } - - public String getErrorMessage() { - return (entity == null) ? getMessage() : entity.getErrorMessage(); - } - - public BaseEntity getEntity() { - return entity; - } - - public boolean isUnauthorized() { - return entity != null && entity.isUnauthorized(); - } - - public void setCode(int code) { - if (entity != null) { - entity.setCode(code); - } - } - - public void setErrorNumber(int errorNumber) { - if (entity != null) { - entity.setErrorNumber(errorNumber); - } - } -} diff --git a/src/main/java/com/arangodb/ArangoGraph.java b/src/main/java/com/arangodb/ArangoGraph.java new file mode 100644 index 000000000..7590414eb --- /dev/null +++ b/src/main/java/com/arangodb/ArangoGraph.java @@ -0,0 +1,173 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb; + +import java.util.Collection; + +import com.arangodb.entity.EdgeDefinition; +import com.arangodb.entity.GraphEntity; +import com.arangodb.internal.ArangoExecutorSync; +import com.arangodb.internal.InternalArangoGraph; +import com.arangodb.internal.velocystream.ConnectionSync; +import com.arangodb.velocystream.Response; + +/** + * @author Mark - mark at arangodb.com + * + */ +public class ArangoGraph extends InternalArangoGraph { + + protected ArangoGraph(final ArangoDatabase db, final String name) { + super(db.executor(), db.name(), name); + } + + protected ArangoExecutorSync executor() { + return executor; + } + + /** + * Delete an existing graph + * + * @see API Documentation + * @throws ArangoDBException + */ + public void drop() throws ArangoDBException { + executor.execute(dropRequest(), Void.class); + } + + /** + * Get a graph from the graph module + * + * @see API Documentation + * @return the definition content of this graph + * @throws ArangoDBException + */ + public GraphEntity getInfo() throws ArangoDBException { + return executor.execute(getInfoRequest(), getInfoResponseDeserializer()); + } + + /** + * Lists all vertex collections used in this graph + * + * @see API + * Documentation + * @return all vertex collections within this graph + * @throws ArangoDBException + */ + public Collection getVertexCollections() throws ArangoDBException { + return executor.execute(getVertexCollectionsRequest(), getVertexCollectionsResponseDeserializer()); + } + + /** + * 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 + * The name of the collection + * @return information about the graph + * @throws ArangoDBException + */ + public GraphEntity addVertexCollection(final String name) throws ArangoDBException { + return executor.execute(addVertexCollectionRequest(name), addVertexCollectionResponseDeserializer()); + } + + /** + * Returns a handler of the vertex collection by the given name + * + * @param name + * Name of the vertex collection + * @return collection handler + */ + public ArangoVertexCollection vertexCollection(final String name) { + return new ArangoVertexCollection(this, name); + } + + /** + * Returns a handler of the edge collection by the given name + * + * @param name + * Name of the edge collection + * @return collection handler + */ + public ArangoEdgeCollection edgeCollection(final String name) { + return new ArangoEdgeCollection(this, name); + } + + /** + * Lists all edge collections used in this graph + * + * @see API + * Documentation + * @return all edge collections within this graph + * @throws ArangoDBException + */ + public Collection getEdgeDefinitions() throws ArangoDBException { + return executor.execute(getEdgeDefinitionsRequest(), getEdgeDefinitionsDeserializer()); + } + + /** + * Add a new edge definition to the graph + * + * @see API + * Documentation + * @param definition + * @return information about the graph + * @throws ArangoDBException + */ + public GraphEntity addEdgeDefinition(final EdgeDefinition definition) throws ArangoDBException { + return executor.execute(addEdgeDefinitionRequest(definition), addEdgeDefinitionResponseDeserializer()); + } + + /** + * 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 + */ + public GraphEntity replaceEdgeDefinition(final EdgeDefinition definition) throws ArangoDBException { + return executor.execute(replaceEdgeDefinitionRequest(definition), replaceEdgeDefinitionResponseDeserializer()); + } + + /** + * 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 + */ + public GraphEntity removeEdgeDefinition(final String definitionName) throws ArangoDBException { + return executor.execute(removeEdgeDefinitionRequest(definitionName), + removeEdgeDefinitionResponseDeserializer()); + } + +} diff --git a/src/main/java/com/arangodb/ArangoHost.java b/src/main/java/com/arangodb/ArangoHost.java deleted file mode 100644 index d2ea15166..000000000 --- a/src/main/java/com/arangodb/ArangoHost.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.arangodb; - -public class ArangoHost { - - /** - * server port - * */ - int port; - - /** - * server host - * */ - String host; - - public ArangoHost(String host, int port) { - this.host = host; - this.port = port; - } - - public int getPort() { - return port; - } - - public String getHost() { - return host; - } - - public void setPort(int port) { - this.port = port; - } - - public void setHost(String host) { - this.host = host; - } - - @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(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - ArangoHost other = (ArangoHost) obj; - if (host == null) { - if (other.host != null) - return false; - } else if (!host.equals(other.host)) - return false; - if (port != other.port) - return false; - return true; - } - -} diff --git a/src/main/java/com/arangodb/ArangoVertexCollection.java b/src/main/java/com/arangodb/ArangoVertexCollection.java new file mode 100644 index 000000000..98d84b891 --- /dev/null +++ b/src/main/java/com/arangodb/ArangoVertexCollection.java @@ -0,0 +1,222 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb; + +import com.arangodb.entity.VertexEntity; +import com.arangodb.entity.VertexUpdateEntity; +import com.arangodb.internal.ArangoExecutorSync; +import com.arangodb.internal.InternalArangoVertexCollection; +import com.arangodb.internal.velocystream.ConnectionSync; +import com.arangodb.model.DocumentReadOptions; +import com.arangodb.model.VertexCreateOptions; +import com.arangodb.model.VertexDeleteOptions; +import com.arangodb.model.VertexReplaceOptions; +import com.arangodb.model.VertexUpdateOptions; +import com.arangodb.velocystream.Response; + +/** + * @author Mark - mark at arangodb.com + * + */ +public class ArangoVertexCollection + extends InternalArangoVertexCollection { + + protected ArangoVertexCollection(final ArangoGraph graph, final String name) { + super(graph.executor(), graph.db(), graph.name(), 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 + */ + public void drop() throws ArangoDBException { + executor.execute(dropRequest(), Void.class); + } + + /** + * 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 + */ + public VertexEntity insertVertex(final T value) throws ArangoDBException { + return executor.execute(insertVertexRequest(value, new VertexCreateOptions()), + insertVertexResponseDeserializer(value)); + } + + /** + * 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 + */ + public VertexEntity insertVertex(final T value, final VertexCreateOptions options) throws ArangoDBException { + return executor.execute(insertVertexRequest(value, options), insertVertexResponseDeserializer(value)); + } + + /** + * Fetches an existing vertex + * + * @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 + */ + public T getVertex(final String key, final Class type) throws ArangoDBException { + return executor.execute(getVertexRequest(key, new DocumentReadOptions()), getVertexResponseDeserializer(type)); + } + + /** + * Fetches an existing vertex + * + * @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 + */ + public T getVertex(final String key, final Class type, final DocumentReadOptions options) + throws ArangoDBException { + return executor.execute(getVertexRequest(key, options), getVertexResponseDeserializer(type)); + } + + /** + * 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 type + * The type of the vertex-document (POJO class, VPackSlice or String for Json) + * @return information about the vertex + * @throws ArangoDBException + */ + public VertexUpdateEntity replaceVertex(final String key, final T value) throws ArangoDBException { + return executor.execute(replaceVertexRequest(key, value, new VertexReplaceOptions()), + replaceVertexResponseDeserializer(value)); + } + + /** + * 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 type + * 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 + */ + public VertexUpdateEntity replaceVertex(final String key, final T value, final VertexReplaceOptions options) + throws ArangoDBException { + return executor.execute(replaceVertexRequest(key, value, options), replaceVertexResponseDeserializer(value)); + } + + /** + * Partially updates the vertex identified by document-key. The value must contain a document with the attributes to + * patch (the patch document). All attributes from the patch document will be added to the existing document if they + * do not yet exist, and overwritten in the existing document if they do exist there. + * + * @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 information about the vertex + * @throws ArangoDBException + */ + public VertexUpdateEntity updateVertex(final String key, final T value) throws ArangoDBException { + return executor.execute(updateVertexRequest(key, value, new VertexUpdateOptions()), + updateVertexResponseDeserializer(value)); + } + + /** + * Partially updates the vertex identified by document-key. The value must contain a document with the attributes to + * patch (the patch document). All attributes from the patch document will be added to the existing document if they + * do not yet exist, and overwritten in the existing document if they do exist there. + * + * @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 information about the vertex + * @throws ArangoDBException + */ + public VertexUpdateEntity updateVertex(final String key, final T value, final VertexUpdateOptions options) + throws ArangoDBException { + return executor.execute(updateVertexRequest(key, value, options), updateVertexResponseDeserializer(value)); + } + + /** + * Removes a vertex + * + * @see API Documentation + * @param key + * The key of the vertex + * @throws ArangoDBException + */ + public void deleteVertex(final String key) throws ArangoDBException { + executor.execute(deleteVertexRequest(key, new VertexDeleteOptions()), Void.class); + } + + /** + * Removes a vertex + * + * @see API Documentation + * @param key + * The key of the vertex + * @param options + * Additional options, can be null + * @throws ArangoDBException + */ + 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/BaseArangoDriver.java b/src/main/java/com/arangodb/BaseArangoDriver.java deleted file mode 100644 index 1a49aa1bd..000000000 --- a/src/main/java/com/arangodb/BaseArangoDriver.java +++ /dev/null @@ -1,435 +0,0 @@ -/* - * Copyright (C) 2012 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb; - -import java.text.ParseException; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.regex.Pattern; - -import com.arangodb.entity.BaseEntity; -import com.arangodb.entity.DefaultEntity; -import com.arangodb.entity.DocumentEntity; -import com.arangodb.entity.EntityDeserializers; -import com.arangodb.entity.EntityFactory; -import com.arangodb.entity.KeyValueEntity; -import com.arangodb.entity.ReplicationDumpHeader; -import com.arangodb.entity.StreamEntity; -import com.arangodb.entity.marker.MissingInstanceCreater; -import com.arangodb.http.HttpResponseEntity; -import com.arangodb.util.DateUtils; -import com.arangodb.util.ReflectionUtils; -import com.arangodb.util.StringUtils; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.JsonParser; -import com.google.gson.JsonSyntaxException; - -/** - * @author tamtam180 - kirscheless at gmail.com - * - */ -public abstract class BaseArangoDriver { - - private static final Pattern databaseNamePattern = Pattern.compile("^[a-zA-Z][a-zA-Z0-9\\-_]{0,63}$"); - - protected String createDocumentHandle(final long collectionId, final String documentKey) { - return collectionId + "/" + documentKey; - } - - protected String createDocumentHandle(final String collectionName, final String documentKey) - throws ArangoException { - validateCollectionName(collectionName); - return collectionName + "/" + documentKey; - } - - protected void validateCollectionName(final String name) throws ArangoException { - if (name.indexOf('/') != -1) { - throw new ArangoException("does not allow '/' in name."); - } - } - - protected void validateDocumentHandle(final String documentHandle) throws ArangoException { - final int pos = documentHandle.indexOf('/'); - if (pos > 0) { - final String collectionName = documentHandle.substring(0, pos); - final String documentKey = documentHandle.substring(pos + 1); - - validateCollectionName(collectionName); - if (collectionName.length() != 0 && documentKey.length() != 0) { - return; - } - } - throw new ArangoException("invalid format documentHandle:" + documentHandle); - } - - /** - * @param database - * @param allowNull - * @throws ArangoException - * @see - * DatabaseNames documentation - */ - protected void validateDatabaseName(final String database, final boolean allowNull) throws ArangoException { - boolean valid = false; - if (database == null) { - if (allowNull) { - valid = true; - } - } else { - valid = databaseNamePattern.matcher(database).matches(); - if ("_system".equals(database)) { - valid = true; - } - } - if (!valid) { - throw new ArangoException("invalid format database:" + database); - } - } - - protected void setKeyValueHeader(final HttpResponseEntity res, final KeyValueEntity entity) throws ArangoException { - - final Map headers = res.getHeaders(); - - try { - final String strCreated = headers.get("x-voc-created"); - if (strCreated != null) { - entity.setCreated(DateUtils.parse(strCreated, "yyyy-MM-dd'T'HH:mm:ss'Z'")); - } - - final String strExpires = headers.get("x-voc-expires"); - if (strExpires != null) { - entity.setExpires(DateUtils.parse(strExpires, "yyyy-MM-dd'T'HH:mm:ss'Z'")); - } - - final String strExtened = headers.get("x-voc-extended"); - if (strExtened != null) { - final Map attributes = EntityFactory.createEntity(strExtened, Map.class); - entity.setAttributes(attributes); - } - - } catch (final ParseException e) { - throw new ArangoException(e); - } - - } - - protected ReplicationDumpHeader toReplicationDumpHeader(final HttpResponseEntity res) { - final ReplicationDumpHeader header = new ReplicationDumpHeader(); - - final Map headerMap = res.getHeaders(); - String value; - - value = headerMap.get("x-arango-replication-active"); - if (value != null) { - header.setActive(Boolean.parseBoolean(value)); - } - - value = headerMap.get("x-arango-replication-lastincluded"); - if (value != null) { - header.setLastincluded(Long.parseLong(value)); - } - - value = headerMap.get("x-arango-replication-lasttick"); - if (value != null) { - header.setLasttick(Long.parseLong(value)); - } - - value = headerMap.get("x-arango-replication-checkmore"); - if (value != null) { - header.setCheckmore(Boolean.parseBoolean(value)); - } - - return header; - } - - /** - * Checks the Http response for database or server errors - * - * @param res - * the response of the database - * @return The Http status code - * @throws ArangoException - * if any error happened - */ - private int checkServerErrors(final HttpResponseEntity res) throws ArangoException { - final int statusCode = res.getStatusCode(); - - if (statusCode >= 400) { // always throws ArangoException - final DefaultEntity defaultEntity = new DefaultEntity(); - if (res.getText() != null && !"".equals(res.getText()) && statusCode != 500) { - final JsonParser jsonParser = new JsonParser(); - final JsonElement jsonElement = jsonParser.parse(res.getText()); - final JsonObject jsonObject = jsonElement.getAsJsonObject(); - final JsonElement errorMessage = jsonObject.get("errorMessage"); - defaultEntity.setErrorMessage(errorMessage.getAsString()); - final JsonElement errorNumber = jsonObject.get("errorNum"); - defaultEntity.setErrorNumber(errorNumber.getAsInt()); - } else { - defaultEntity.setErrorMessage(res.createStatusPhrase()); - } - - defaultEntity.setCode(statusCode); - defaultEntity.setStatusCode(statusCode); - defaultEntity.setError(true); - final ArangoException arangoException = new ArangoException(defaultEntity); - arangoException.setCode(statusCode); - throw arangoException; - } - - return statusCode; - } - - /** - * Creates an entity object - * - * @param res - * the response of the database - * @param clazz - * the class of the entity object - * @param pclazz - * the class of the object wrapped in the entity object - * @param validate - * true for validation - * @return the result entity object of class T (T extends BaseEntity) - * @throws ArangoException - */ - protected T createEntity( - final HttpResponseEntity res, - final Class clazz, - final Class[] pclazz, - final boolean validate) throws ArangoException { - if (res == null) { - return null; - } - boolean isDocumentEntity = false; - - // the following was added to ensure, that attributes with a key like - // "error", "code", "errorNum" - // and "etag" will be serialized, when no error was thrown by the - // database - if (clazz == DocumentEntity.class) { - isDocumentEntity = true; - } - - final int statusCode = checkServerErrors(res); - - try { - EntityDeserializers.setParameterized(pclazz); - - final T entity = createEntityWithFallback(res, clazz); - - setStatusCode(res, entity); - if (validate) { - validate(res, entity); - } - - if (isDocumentEntity) { // && requestSuccessful NOTE: no need for - // this, an exception is always thrown - entity.setCode(statusCode); - entity.setErrorMessage(null); - entity.setError(false); - entity.setErrorNumber(0); - } - - return entity; - } finally { - EntityDeserializers.removeParameterized(); - } - } - - private T createEntityWithFallback(final HttpResponseEntity res, final Class clazz) - throws ArangoException { - T entity = createEntityImpl(res, clazz); - if (entity == null) { - final Class c = MissingInstanceCreater.getMissingClass(clazz); - entity = ReflectionUtils.newInstance(c); - } else if (res.isBatchRepsonse()) { - try { - entity = clazz.newInstance(); - } catch (final Exception e) { - throw new ArangoException(e); - } - } - return entity; - } - - /** - * Gets the raw JSON string with results, from the Http response - * - * @param res - * the response of the database - * @return A valid JSON string with the results - * @throws ArangoException - */ - protected String getJSONResponseText(final HttpResponseEntity res) throws ArangoException { - if (res == null) { - return null; - } - - checkServerErrors(res); - - // no errors, return results as a JSON string - final JsonParser jsonParser = new JsonParser(); - final JsonElement jsonElement = jsonParser.parse(res.getText()); - final JsonObject jsonObject = jsonElement.getAsJsonObject(); - final JsonElement result = jsonObject.get("result"); - return result.toString(); - } - - protected T createEntity(final String str, final Class clazz, final Class... pclazz) - throws ArangoException { - try { - EntityDeserializers.setParameterized(pclazz); - return EntityFactory.createEntity(str, clazz); - } finally { - EntityDeserializers.removeParameterized(); - } - } - - protected T createEntity(final HttpResponseEntity res, final Class clazz) - throws ArangoException { - return createEntity(res, clazz, null, true); - } - - protected T createEntity( - final HttpResponseEntity res, - final Class clazz, - final Class... pclazz) throws ArangoException { - return createEntity(res, clazz, pclazz, true); - } - - protected void setStatusCode(final HttpResponseEntity res, final BaseEntity entity) throws ArangoException { - if (entity != null) { - if (res.getEtag() != null) { - entity.setEtag(res.getEtag()); - } - entity.setStatusCode(res.getStatusCode()); - if (res.getRequestId() != null) { - entity.setRequestId(res.getRequestId()); - } - } - } - - protected void validate(final HttpResponseEntity res, final BaseEntity entity) throws ArangoException { - - if (entity != null && entity.isError()) { - throw new ArangoException(entity); - } - - // Custom Error - if (res.getStatusCode() >= 400) { - - BaseEntity tmpEntity = entity; - if (tmpEntity == null) { - tmpEntity = new DefaultEntity(); - } - - if (res.isTextResponse()) { - tmpEntity.setErrorNumber(res.getStatusCode()); - tmpEntity.setErrorMessage(res.getText()); - } else { - tmpEntity.setErrorNumber(res.getStatusCode()); - tmpEntity.setErrorMessage(res.getStatusPhrase()); - } - - switch (res.getStatusCode()) { - case 401: - tmpEntity.setErrorMessage("Unauthorized"); - break; - case 403: - tmpEntity.setErrorMessage("Forbidden"); - break; - default: - } - - throw new ArangoException(tmpEntity); - } - } - - @SuppressWarnings("unchecked") - protected T createEntityImpl(final HttpResponseEntity res, final Class type) throws ArangoException { - T result = null; - if (res.isJsonResponse()) { - try { - result = EntityFactory.createEntity(res.getText(), type); - } catch (final JsonSyntaxException e) { - throw new ArangoException("got JsonSyntaxException while creating entity", e); - } catch (final JsonParseException e) { - throw new ArangoException("got JsonParseException while creating entity", e); - } - } else if (res.isDumpResponse() && StreamEntity.class.isAssignableFrom(type)) { - result = (T) new StreamEntity(res.getStream()); - } else if (StringUtils.isNotEmpty(res.getText())) { - throw new ArangoException("expected JSON result from server but got: " + res.getText()); - } - - return result; - } - - protected String createEndpointUrl(final String database, final Object... paths) throws ArangoException { - final List list = new ArrayList(); - - if (database != null) { - validateDatabaseName(database, false); - list.add("_db"); - list.add(database); - } - for (final Object path : paths) { - if (path != null) { - list.add(path.toString()); - } - } - return StringUtils.join(false, list); - } - - protected String createEndpointUrl(final String database, final String str, final Object... paths) - throws ArangoException { - if (paths == null) { - return createEndpointUrl(database, paths); - } - final Object[] newPaths = new Object[paths.length + 1]; - newPaths[0] = str; - for (int i = 0; i < paths.length; i++) { - newPaths[i + 1] = paths[i]; - } - return createEndpointUrl(database, newPaths); - } - - protected String createUserEndpointUrl(final Object... paths) throws ArangoException { - return createEndpointUrl(null, "/_api/user", paths); - } - - protected String createJobEndpointUrl(final String database, final Object... paths) throws ArangoException { - return createEndpointUrl(database, "/_api/job", paths); - } - - protected String createIndexEndpointUrl(final String database, final Object... paths) throws ArangoException { - return createEndpointUrl(database, "/_api/index", paths); - } - - protected String createGharialEndpointUrl(final String database, final Object... paths) throws ArangoException { - return createEndpointUrl(database, "/_api/gharial", paths); - } - - protected String createDocumentEndpointUrl(final String database, final Object... paths) throws ArangoException { - return createEndpointUrl(database, "/_api/document", paths); - } -} diff --git a/src/main/java/com/arangodb/BaseCursorProxy.java b/src/main/java/com/arangodb/BaseCursorProxy.java deleted file mode 100644 index b8b4aece7..000000000 --- a/src/main/java/com/arangodb/BaseCursorProxy.java +++ /dev/null @@ -1,153 +0,0 @@ -package com.arangodb; - -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import com.arangodb.entity.DocumentEntity; - -/** - * @author a-brandt - */ -public class BaseCursorProxy> implements Iterable { - - private DocumentCursorResult baseCursor; - - public BaseCursorProxy(DocumentCursorResult baseCursor) { - this.baseCursor = baseCursor; - } - - @Override - public Iterator iterator() { - return baseCursor.iterator(); - } - - /** - * Returns an iterator over a entity set of elements of type T. - * - * @return an Iterator. - */ - public Iterator entityIterator() { - return baseCursor.entityIterator(); - } - - /** - * Returns the DocumentEntity objects as a list - * - * @return list of DocumentEntity objects - */ - public List asList() { - return baseCursor.asList(); - } - - /** - * Returns the entities of DocumentEntity objects as a list - * - * @return list of DocumentEntity objects - */ - public List asEntityList() { - return baseCursor.asEntityList(); - } - - /** - * Close cursor (removes cursor from database) - * - * @throws ArangoException - */ - public void close() throws ArangoException { - baseCursor.close(); - } - - /** - * Get total number of results (if requested) - * - * @return total number of results - */ - public int getCount() { - return baseCursor.getCount(); - } - - /** - * Get total number of results for queries with LIMIT clause - * - * @return total number of results - */ - public int getFullCount() { - return baseCursor.getFullCount(); - } - - /** - * Return a single instance that matches the query, or null if the query - * returns no results. - * - * Throws NonUniqueResultException (RuntimeException) if there is more than - * one matching result - * - * @return the single result or null - */ - public S getUniqueResult() { - return baseCursor.getUniqueResult(); - } - - /** - * If the resource has been modified it returns true - * - * @return boolean - */ - public boolean isNotModified() { - return baseCursor.getEntity().isNotModified(); - } - - public int getCode() { - return baseCursor.getEntity().getCode(); - } - - public int getStatusCode() { - return baseCursor.getEntity().getStatusCode(); - } - - public String getRequestId() { - return baseCursor.getEntity().getRequestId(); - } - - /** - * Returns true if the cursor can load more data from the database - * - * @return true, if the cursor can load more data from the database - */ - public boolean hasMore() { - return baseCursor.hasMore(); - } - - /** - * Returns the cursor identifier - * - * @return the cursor identifier - */ - public Long getCursorId() { - return baseCursor.getCursorId(); - } - - /** - * 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. (since ArangoDB 2.7) - * - * @return true, if the result is cached - * - */ - public boolean isCached() { - return baseCursor.isCached(); - } - - /** - * A list of extra stats returned by the query - * - * @return query stats - */ - public Map getExtra() { - return baseCursor.getExtra(); - } - -} diff --git a/src/main/java/com/arangodb/CursorRawResult.java b/src/main/java/com/arangodb/CursorRawResult.java deleted file mode 100644 index c31084ced..000000000 --- a/src/main/java/com/arangodb/CursorRawResult.java +++ /dev/null @@ -1,187 +0,0 @@ -/* - * Copyright (C) 2012 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.NoSuchElementException; - -import com.arangodb.entity.CursorEntity; -import com.arangodb.entity.WarningEntity; -import com.google.gson.JsonObject; - -/** - * @author tamtam180 - kirscheless at gmail.com - * - */ -public class CursorRawResult implements Iterable { - - private String database; - private InternalCursorDriver cursorDriver; - private CursorEntity entity; - private int pos; - private int count; - private CursorIterator iter; - - public CursorRawResult(String database, InternalCursorDriver cursorDriver, CursorEntity entity, - Class... clazz) { - this.database = database; - this.cursorDriver = cursorDriver; - this.entity = entity; - this.count = entity == null ? 0 : entity.getCount(); - this.pos = 0; - this.iter = null; - } - - @Override - public Iterator iterator() { - if (iter == null) { - iter = new CursorIterator(); - } - - return iter; - } - - /** - * Returns the objects as a list - * - * @return list of DocumentEntity objects - */ - public List asList() { - List result = new ArrayList(); - Iterator iterator = iterator(); - - while (iterator.hasNext()) { - result.add(iterator.next()); - } - - return result; - } - - /** - * Close cursor (removes cursor from database) - * - * @throws ArangoException - */ - public void close() throws ArangoException { - long cursorId = entity.getCursorId(); - cursorDriver.finishQuery(database, cursorId); - } - - /** - * Get total number of results (if requested) - * - * @return total number of results - */ - public int getCount() { - return count; - } - - /** - * Get total number of results for queries with LIMIT clause - * - * @return total number of results - */ - public int getFullCount() { - return entity.getFullCount(); - } - - /** - * Return a single instance that matches the query, or null if the query - * returns no results. - * - * Throws NonUniqueResultException (RuntimeException) if there is more than - * one matching result - * - * @return the single result or null - */ - public String getUniqueResult() { - return entity.getUniqueResult().toString(); - } - - /** - * read more values - * - * @throws ArangoException - */ - private void updateEntity() throws ArangoException { - long cursorId = entity.getCursorId(); - this.entity = cursorDriver.continueQuery(database, cursorId, JsonObject.class); - this.pos = 0; - } - - /** - * internal iterator - */ - public class CursorIterator implements Iterator { - - @Override - public boolean hasNext() { - if (entity == null) { - return false; - } - if (pos < entity.size()) { - return true; - } - if (entity.hasMore()) { - return true; - } - return false; - } - - @Override - public String next() { - if (hasNext()) { - if (pos >= entity.size()) { - try { - updateEntity(); - } catch (ArangoException e) { - throw new IllegalStateException(e); - } - } - return entity.get(pos++).toString(); - } - throw new NoSuchElementException(); - } - - @Override - public void remove() { - throw new UnsupportedOperationException("remove is not supported!"); - } - - } - - /** - * Returns true, if there are AQL warnings - * - * @return true, if there are AQL warnings - */ - public boolean hasWarning() { - return entity.hasWarnings(); - } - - /** - * Returns a list of AQL warnings (code and message) - * - * @return list of AQL warnings - */ - public List getWarnings() { - return entity.getWarnings(); - } - -} diff --git a/src/main/java/com/arangodb/CursorResult.java b/src/main/java/com/arangodb/CursorResult.java deleted file mode 100644 index e9e396235..000000000 --- a/src/main/java/com/arangodb/CursorResult.java +++ /dev/null @@ -1,237 +0,0 @@ -/* - * Copyright (C) 2012 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.NoSuchElementException; - -import com.arangodb.entity.CursorEntity; -import com.arangodb.entity.WarningEntity; - -/** - * @author tamtam180 - kirscheless at gmail.com - * - */ -public class CursorResult implements Iterable { - - private String database; - private InternalCursorDriver cursorDriver; - private Class[] clazz; - private CursorEntity entity; - private int pos; - private int count; - private CursorIterator iter; - - public CursorResult(String database, InternalCursorDriver cursorDriver, CursorEntity entity, Class... clazz) { - this.database = database; - this.cursorDriver = cursorDriver; - this.clazz = clazz; - this.entity = entity; - this.count = entity == null ? 0 : entity.getCount(); - this.pos = 0; - this.iter = null; - } - - @Override - public Iterator iterator() { - if (iter == null) { - iter = new CursorIterator(); - } - - return iter; - } - - /** - * Returns the objects as a list - * - * @return list of DocumentEntity objects - */ - public List asList() { - List result = new ArrayList(); - Iterator iterator = iterator(); - - while (iterator.hasNext()) { - result.add(iterator.next()); - } - - return result; - } - - /** - * Close cursor (removes cursor from database) - * - * @throws ArangoException - */ - public void close() throws ArangoException { - long cursorId = entity.getCursorId(); - cursorDriver.finishQuery(database, cursorId); - } - - /** - * Get total number of results (if requested) - * - * @return total number of results - */ - public int getCount() { - return count; - } - - /** - * Get total number of results for queries with LIMIT clause - * - * @return total number of results - */ - public int getFullCount() { - return entity.getFullCount(); - } - - /** - * Return a single instance that matches the query, or null if the query - * returns no results. - * - * Throws NonUniqueResultException (RuntimeException) if there is more than - * one matching result - * - * @return the single result or null - */ - public T getUniqueResult() { - return entity.getUniqueResult(); - } - - /** - * read more values - * - * @throws ArangoException - */ - private void updateEntity() throws ArangoException { - long cursorId = entity.getCursorId(); - this.entity = cursorDriver.continueQuery(database, cursorId, this.clazz); - this.pos = 0; - } - - /** - * Returns the CursorEntity object - * - * @return CursorEntity - */ - public CursorEntity getEntity() { - return entity; - } - - /** - * internal iterator - */ - public class CursorIterator implements Iterator { - - @Override - public boolean hasNext() { - if (entity == null) { - return false; - } - if (pos < entity.size()) { - return true; - } - if (entity.hasMore()) { - return true; - } - return false; - } - - @Override - public T next() { - if (hasNext()) { - if (pos >= entity.size()) { - try { - updateEntity(); - } catch (ArangoException e) { - throw new IllegalStateException(e); - } - } - return entity.get(pos++); - } - throw new NoSuchElementException(); - } - - @Override - public void remove() { - throw new UnsupportedOperationException("remove is not supported!"); - } - - } - - /** - * Returns true if the cursor can load more data from the database - * - * @return true, if the cursor can load more data from the database - */ - public boolean hasMore() { - return entity.hasMore(); - } - - /** - * Returns the cursor identifier - * - * @return the cursor identifier - */ - public Long getCursorId() { - return entity.getCursorId(); - } - - /** - * 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. (since ArangoDB 2.7) - * - * @return true, if the result is cached - * - */ - public boolean isCached() { - return entity.isCached(); - } - - /** - * Returns true, if there are AQL warnings - * - * @return true, if there are AQL warnings - */ - public boolean hasWarning() { - return entity.hasWarnings(); - } - - /** - * Returns a list of AQL warnings (code and message) - * - * @return list of AQL warnings - */ - public List getWarnings() { - return entity.getWarnings(); - } - - /** - * A list of extra stats returned by the query - * - * @return query stats - */ - public Map getExtra() { - return entity.getExtra(); - } - -} diff --git a/src/main/java/com/arangodb/CursorResultSet.java b/src/main/java/com/arangodb/CursorResultSet.java deleted file mode 100644 index 72970b71e..000000000 --- a/src/main/java/com/arangodb/CursorResultSet.java +++ /dev/null @@ -1,115 +0,0 @@ -/* - * Copyright (C) 2012 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb; - -import java.util.Iterator; -import java.util.NoSuchElementException; - -import com.arangodb.entity.CursorEntity; - -/** - * @author tamtam180 - kirscheless at gmail.com - * - */ -public class CursorResultSet implements Iterable { - - private String database; - private InternalCursorDriver cursorDriver; - private Class[] clazz; - private CursorEntity entity; - private int pos; - private int totalCount; - private Iterator itr; - - public CursorResultSet(String database, InternalCursorDriver cursorDriver, CursorEntity entity, - Class... clazz) { - this.database = database; - this.cursorDriver = cursorDriver; - this.clazz = clazz; - this.entity = entity; - this.totalCount = entity == null ? 0 : entity.getCount(); - this.pos = 0; - this.itr = new CursorIterator(); - } - - @Override - public Iterator iterator() { - return new CursorIterator(); - } - - public boolean hasNext() { - return itr.hasNext(); - } - - public T next() { - return itr.next(); - } - - public void close() throws ArangoException { - long cursorId = entity.getCursorId(); - cursorDriver.finishQuery(database, cursorId); - } - - public int getTotalCount() { - return totalCount; - } - - public void updateEntity() throws ArangoException { - long cursorId = entity.getCursorId(); - this.entity = cursorDriver.continueQuery(database, cursorId, this.clazz); - this.pos = 0; - } - - public class CursorIterator implements Iterator { - - @Override - public boolean hasNext() { - if (entity == null) { - return false; - } - if (pos < entity.size()) { - return true; - } - if (entity.hasMore()) { - return true; - } - return false; - } - - @Override - public T next() { - if (hasNext()) { - if (pos >= entity.size()) { - try { - updateEntity(); - } catch (ArangoException e) { - throw new IllegalStateException(e); - } - } - return entity.get(pos++); - } - throw new NoSuchElementException(); - } - - @Override - public void remove() { - throw new UnsupportedOperationException("remove does not support!!"); - } - - } - -} diff --git a/src/main/java/com/arangodb/Direction.java b/src/main/java/com/arangodb/Direction.java deleted file mode 100644 index f3de0900f..000000000 --- a/src/main/java/com/arangodb/Direction.java +++ /dev/null @@ -1,5 +0,0 @@ -package com.arangodb; - -public enum Direction { - OUTBOUND, INBOUND, ANY -} diff --git a/src/main/java/com/arangodb/DocumentCursor.java b/src/main/java/com/arangodb/DocumentCursor.java deleted file mode 100644 index aa98ef9fe..000000000 --- a/src/main/java/com/arangodb/DocumentCursor.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.arangodb; - -import com.arangodb.entity.DocumentEntity; - -/** - * @author a-brandt - */ -public class DocumentCursor extends BaseCursorProxy> { - - public DocumentCursor(DocumentCursorResult> baseCursor) { - super(baseCursor); - } -} diff --git a/src/main/java/com/arangodb/DocumentCursorResult.java b/src/main/java/com/arangodb/DocumentCursorResult.java deleted file mode 100644 index b4b5c1983..000000000 --- a/src/main/java/com/arangodb/DocumentCursorResult.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Copyright (C) 2012 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import com.arangodb.entity.CursorEntity; -import com.arangodb.entity.DocumentEntity; - -/** - * @author tamtam180 - kirscheless at gmail.com - * @author a-brandt - * - */ -public class DocumentCursorResult> extends CursorResult { - - public DocumentCursorResult(String database, InternalCursorDriver cursorDriver, CursorEntity entity, Class... clazz) { - super(database, cursorDriver, entity, clazz); - } - - /** - * Returns an iterator over a entity set of elements of type T. - * - * @return an Iterator. - */ - public Iterator entityIterator() { - return new EntityIterator(); - } - - /** - * Returns the entities of DocumentEntity objects as a list - * - * @return list of DocumentEntity objects - */ - public List asEntityList() { - List result = new ArrayList(); - Iterator iterator = iterator(); - - while (iterator.hasNext()) { - T e = iterator.next().getEntity(); - if (e != null) { - result.add(e); - } - } - - return result; - } - - /** - * internal entity iterator - */ - public class EntityIterator implements Iterator { - - private Iterator iterator; - - public EntityIterator() { - iterator = iterator(); - } - - @Override - public boolean hasNext() { - return iterator.hasNext(); - } - - @Override - public T next() { - return iterator.next().getEntity(); - } - - @Override - public void remove() { - iterator.remove(); - } - - } -} diff --git a/src/main/java/com/arangodb/EdgeCursor.java b/src/main/java/com/arangodb/EdgeCursor.java deleted file mode 100644 index eed915294..000000000 --- a/src/main/java/com/arangodb/EdgeCursor.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.arangodb; - -import com.arangodb.entity.EdgeEntity; - -/** - * @author a-brandt - */ -public class EdgeCursor extends BaseCursorProxy> { - - public EdgeCursor(DocumentCursorResult> baseCursor) { - super(baseCursor); - } -} diff --git a/src/main/java/com/arangodb/ErrorNums.java b/src/main/java/com/arangodb/ErrorNums.java deleted file mode 100644 index e95a3fd4b..000000000 --- a/src/main/java/com/arangodb/ErrorNums.java +++ /dev/null @@ -1,264 +0,0 @@ -package com.arangodb; - -public class ErrorNums { - - public static final int ERROR_NO_ERROR = 0; - public static final int ERROR_FAILED = 1; - public static final int ERROR_SYS_ERROR = 2; - public static final int ERROR_OUT_OF_MEMORY = 3; - public static final int ERROR_INTERNAL = 4; - public static final int ERROR_ILLEGAL_NUMBER = 5; - public static final int ERROR_NUMERIC_OVERFLOW = 6; - public static final int ERROR_ILLEGAL_OPTION = 7; - public static final int ERROR_DEAD_PID = 8; - public static final int ERROR_NOT_IMPLEMENTED = 9; - public static final int ERROR_BAD_PARAMETER = 10; - public static final int ERROR_FORBIDDEN = 11; - public static final int ERROR_OUT_OF_MEMORY_MMAP = 12; - public static final int ERROR_CORRUPTED_CSV = 13; - public static final int ERROR_FILE_NOT_FOUND = 14; - public static final int ERROR_CANNOT_WRITE_FILE = 15; - public static final int ERROR_CANNOT_OVERWRITE_FILE = 16; - public static final int ERROR_TYPE_ERROR = 17; - public static final int ERROR_LOCK_TIMEOUT = 18; - public static final int ERROR_CANNOT_CREATE_DIRECTORY = 19; - public static final int ERROR_CANNOT_CREATE_TEMP_FILE = 20; - public static final int ERROR_REQUEST_CANCELED = 21; - public static final int ERROR_DEBUG = 22; - public static final int ERROR_IP_ADDRESS_INVALID = 25; - public static final int ERROR_FILE_EXISTS = 27; - public static final int ERROR_LOCKED = 28; - public static final int ERROR_DEADLOCK = 29; - public static final int ERROR_HTTP_BAD_PARAMETER = 400; - public static final int ERROR_HTTP_UNAUTHORIZED = 401; - public static final int ERROR_HTTP_FORBIDDEN = 403; - public static final int ERROR_HTTP_NOT_FOUND = 404; - public static final int ERROR_HTTP_METHOD_NOT_ALLOWED = 405; - public static final int ERROR_HTTP_PRECONDITION_FAILED = 412; - public static final int ERROR_HTTP_SERVER_ERROR = 500; - public static final int ERROR_HTTP_CORRUPTED_JSON = 600; - public static final int ERROR_HTTP_SUPERFLUOUS_SUFFICES = 601; - public static final int ERROR_ARANGO_ILLEGAL_STATE = 1000; - public static final int ERROR_ARANGO_DATAFILE_SEALED = 1002; - public static final int ERROR_ARANGO_UNKNOWN_COLLECTION_TYPE = 1003; - public static final int ERROR_ARANGO_READ_ONLY = 1004; - public static final int ERROR_ARANGO_DUPLICATE_IDENTIFIER = 1005; - public static final int ERROR_ARANGO_DATAFILE_UNREADABLE = 1006; - public static final int ERROR_ARANGO_DATAFILE_EMPTY = 1007; - public static final int ERROR_ARANGO_RECOVERY = 1008; - public static final int ERROR_ARANGO_CORRUPTED_DATAFILE = 1100; - public static final int ERROR_ARANGO_ILLEGAL_PARAMETER_FILE = 1101; - public static final int ERROR_ARANGO_CORRUPTED_COLLECTION = 1102; - public static final int ERROR_ARANGO_MMAP_FAILED = 1103; - public static final int ERROR_ARANGO_FILESYSTEM_FULL = 1104; - public static final int ERROR_ARANGO_NO_JOURNAL = 1105; - public static final int ERROR_ARANGO_DATAFILE_ALREADY_EXISTS = 1106; - public static final int ERROR_ARANGO_DATADIR_LOCKED = 1107; - public static final int ERROR_ARANGO_COLLECTION_DIRECTORY_ALREADY_EXISTS = 1108; - public static final int ERROR_ARANGO_MSYNC_FAILED = 1109; - public static final int ERROR_ARANGO_DATADIR_UNLOCKABLE = 1110; - public static final int ERROR_ARANGO_SYNC_TIMEOUT = 1111; - public static final int ERROR_ARANGO_CONFLICT = 1200; - public static final int ERROR_ARANGO_DATADIR_INVALID = 1201; - public static final int ERROR_ARANGO_DOCUMENT_NOT_FOUND = 1202; - public static final int ERROR_ARANGO_COLLECTION_NOT_FOUND = 1203; - public static final int ERROR_ARANGO_COLLECTION_PARAMETER_MISSING = 1204; - public static final int ERROR_ARANGO_DOCUMENT_HANDLE_BAD = 1205; - public static final int ERROR_ARANGO_MAXIMAL_SIZE_TOO_SMALL = 1206; - public static final int ERROR_ARANGO_DUPLICATE_NAME = 1207; - public static final int ERROR_ARANGO_ILLEGAL_NAME = 1208; - public static final int ERROR_ARANGO_NO_INDEX = 1209; - public static final int ERROR_ARANGO_UNIQUE_CONSTRAINT_VIOLATED = 1210; - public static final int ERROR_ARANGO_INDEX_NOT_FOUND = 1212; - public static final int ERROR_ARANGO_CROSS_COLLECTION_REQUEST = 1213; - public static final int ERROR_ARANGO_INDEX_HANDLE_BAD = 1214; - public static final int ERROR_ARANGO_DOCUMENT_TOO_LARGE = 1216; - public static final int ERROR_ARANGO_COLLECTION_NOT_UNLOADED = 1217; - public static final int ERROR_ARANGO_COLLECTION_TYPE_INVALID = 1218; - public static final int ERROR_ARANGO_VALIDATION_FAILED = 1219; - public static final int ERROR_ARANGO_ATTRIBUTE_PARSER_FAILED = 1220; - public static final int ERROR_ARANGO_DOCUMENT_KEY_BAD = 1221; - public static final int ERROR_ARANGO_DOCUMENT_KEY_UNEXPECTED = 1222; - public static final int ERROR_ARANGO_DATADIR_NOT_WRITABLE = 1224; - public static final int ERROR_ARANGO_OUT_OF_KEYS = 1225; - public static final int ERROR_ARANGO_DOCUMENT_KEY_MISSING = 1226; - public static final int ERROR_ARANGO_DOCUMENT_TYPE_INVALID = 1227; - public static final int ERROR_ARANGO_DATABASE_NOT_FOUND = 1228; - public static final int ERROR_ARANGO_DATABASE_NAME_INVALID = 1229; - public static final int ERROR_ARANGO_USE_SYSTEM_DATABASE = 1230; - public static final int ERROR_ARANGO_ENDPOINT_NOT_FOUND = 1231; - public static final int ERROR_ARANGO_INVALID_KEY_GENERATOR = 1232; - public static final int ERROR_ARANGO_INVALID_EDGE_ATTRIBUTE = 1233; - public static final int ERROR_ARANGO_INDEX_DOCUMENT_ATTRIBUTE_MISSING = 1234; - public static final int ERROR_ARANGO_INDEX_CREATION_FAILED = 1235; - public static final int ERROR_ARANGO_WRITE_THROTTLE_TIMEOUT = 1236; - public static final int ERROR_ARANGO_COLLECTION_TYPE_MISMATCH = 1237; - public static final int ERROR_ARANGO_COLLECTION_NOT_LOADED = 1238; - public static final int ERROR_ARANGO_DOCUMENT_REV_BAD = 1239; - public static final int ERROR_ARANGO_DATAFILE_FULL = 1300; - public static final int ERROR_ARANGO_EMPTY_DATADIR = 1301; - public static final int ERROR_REPLICATION_NO_RESPONSE = 1400; - public static final int ERROR_REPLICATION_INVALID_RESPONSE = 1401; - public static final int ERROR_REPLICATION_MASTER_ERROR = 1402; - public static final int ERROR_REPLICATION_MASTER_INCOMPATIBLE = 1403; - public static final int ERROR_REPLICATION_MASTER_CHANGE = 1404; - public static final int ERROR_REPLICATION_LOOP = 1405; - public static final int ERROR_REPLICATION_UNEXPECTED_MARKER = 1406; - public static final int ERROR_REPLICATION_INVALID_APPLIER_STATE = 1407; - public static final int ERROR_REPLICATION_UNEXPECTED_TRANSACTION = 1408; - public static final int ERROR_REPLICATION_INVALID_APPLIER_CONFIGURATION = 1410; - public static final int ERROR_REPLICATION_RUNNING = 1411; - public static final int ERROR_REPLICATION_APPLIER_STOPPED = 1412; - public static final int ERROR_REPLICATION_NO_START_TICK = 1413; - public static final int ERROR_REPLICATION_START_TICK_NOT_PRESENT = 1414; - public static final int ERROR_CLUSTER_NO_AGENCY = 1450; - public static final int ERROR_CLUSTER_NO_COORDINATOR_HEADER = 1451; - public static final int ERROR_CLUSTER_COULD_NOT_LOCK_PLAN = 1452; - public static final int ERROR_CLUSTER_COLLECTION_ID_EXISTS = 1453; - public static final int ERROR_CLUSTER_COULD_NOT_CREATE_COLLECTION_IN_PLAN = 1454; - public static final int ERROR_CLUSTER_COULD_NOT_READ_CURRENT_VERSION = 1455; - public static final int ERROR_CLUSTER_COULD_NOT_CREATE_COLLECTION = 1456; - public static final int ERROR_CLUSTER_TIMEOUT = 1457; - public static final int ERROR_CLUSTER_COULD_NOT_REMOVE_COLLECTION_IN_PLAN = 1458; - public static final int ERROR_CLUSTER_COULD_NOT_REMOVE_COLLECTION_IN_CURRENT = 1459; - public static final int ERROR_CLUSTER_COULD_NOT_CREATE_DATABASE_IN_PLAN = 1460; - public static final int ERROR_CLUSTER_COULD_NOT_CREATE_DATABASE = 1461; - public static final int ERROR_CLUSTER_COULD_NOT_REMOVE_DATABASE_IN_PLAN = 1462; - public static final int ERROR_CLUSTER_COULD_NOT_REMOVE_DATABASE_IN_CURRENT = 1463; - public static final int ERROR_CLUSTER_SHARD_GONE = 1464; - public static final int ERROR_CLUSTER_CONNECTION_LOST = 1465; - public static final int ERROR_CLUSTER_MUST_NOT_SPECIFY_KEY = 1466; - public static final int ERROR_CLUSTER_GOT_CONTRADICTING_ANSWERS = 1467; - public static final int ERROR_CLUSTER_NOT_ALL_SHARDING_ATTRIBUTES_GIVEN = 1468; - public static final int ERROR_CLUSTER_MUST_NOT_CHANGE_SHARDING_ATTRIBUTES = 1469; - public static final int ERROR_CLUSTER_UNSUPPORTED = 1470; - public static final int ERROR_CLUSTER_ONLY_ON_COORDINATOR = 1471; - public static final int ERROR_CLUSTER_READING_PLAN_AGENCY = 1472; - public static final int ERROR_CLUSTER_COULD_NOT_TRUNCATE_COLLECTION = 1473; - public static final int ERROR_CLUSTER_AQL_COMMUNICATION = 1474; - public static final int ERROR_ARANGO_DOCUMENT_NOT_FOUND_OR_SHARDING_ATTRIBUTES_CHANGED = 1475; - public static final int ERROR_CLUSTER_COULD_NOT_DETERMINE_ID = 1476; - public static final int ERROR_CLUSTER_ONLY_ON_DBSERVER = 1477; - public static final int ERROR_CLUSTER_BACKEND_UNAVAILABLE = 1478; - public static final int ERROR_CLUSTER_UNKNOWN_CALLBACK_ENDPOINT = 1479; - public static final int ERROR_QUERY_KILLED = 1500; - public static final int ERROR_QUERY_PARSE = 1501; - public static final int ERROR_QUERY_EMPTY = 1502; - public static final int ERROR_QUERY_SCRIPT = 1503; - public static final int ERROR_QUERY_NUMBER_OUT_OF_RANGE = 1504; - public static final int ERROR_QUERY_VARIABLE_NAME_INVALID = 1510; - public static final int ERROR_QUERY_VARIABLE_REDECLARED = 1511; - public static final int ERROR_QUERY_VARIABLE_NAME_UNKNOWN = 1512; - public static final int ERROR_QUERY_COLLECTION_LOCK_FAILED = 1521; - public static final int ERROR_QUERY_TOO_MANY_COLLECTIONS = 1522; - public static final int ERROR_QUERY_DOCUMENT_ATTRIBUTE_REDECLARED = 1530; - public static final int ERROR_QUERY_FUNCTION_NAME_UNKNOWN = 1540; - public static final int ERROR_QUERY_FUNCTION_ARGUMENT_NUMBER_MISMATCH = 1541; - public static final int ERROR_QUERY_FUNCTION_ARGUMENT_TYPE_MISMATCH = 1542; - public static final int ERROR_QUERY_INVALID_REGEX = 1543; - public static final int ERROR_QUERY_BIND_PARAMETERS_INVALID = 1550; - public static final int ERROR_QUERY_BIND_PARAMETER_MISSING = 1551; - public static final int ERROR_QUERY_BIND_PARAMETER_UNDECLARED = 1552; - public static final int ERROR_QUERY_BIND_PARAMETER_TYPE = 1553; - public static final int ERROR_QUERY_INVALID_LOGICAL_VALUE = 1560; - public static final int ERROR_QUERY_INVALID_ARITHMETIC_VALUE = 1561; - public static final int ERROR_QUERY_DIVISION_BY_ZERO = 1562; - public static final int ERROR_QUERY_ARRAY_EXPECTED = 1563; - public static final int ERROR_QUERY_FAIL_CALLED = 1569; - public static final int ERROR_QUERY_GEO_INDEX_MISSING = 1570; - public static final int ERROR_QUERY_FULLTEXT_INDEX_MISSING = 1571; - public static final int ERROR_QUERY_INVALID_DATE_VALUE = 1572; - public static final int ERROR_QUERY_MULTI_MODIFY = 1573; - public static final int ERROR_QUERY_INVALID_AGGREGATE_EXPRESSION = 1574; - public static final int ERROR_QUERY_COMPILE_TIME_OPTIONS = 1575; - public static final int ERROR_QUERY_EXCEPTION_OPTIONS = 1576; - public static final int ERROR_QUERY_COLLECTION_USED_IN_EXPRESSION = 1577; - public static final int ERROR_QUERY_DISALLOWED_DYNAMIC_CALL = 1578; - public static final int ERROR_QUERY_ACCESS_AFTER_MODIFICATION = 1579; - public static final int ERROR_QUERY_FUNCTION_INVALID_NAME = 1580; - public static final int ERROR_QUERY_FUNCTION_INVALID_CODE = 1581; - public static final int ERROR_QUERY_FUNCTION_NOT_FOUND = 1582; - public static final int ERROR_QUERY_FUNCTION_RUNTIME_ERROR = 1583; - public static final int ERROR_QUERY_BAD_JSON_PLAN = 1590; - public static final int ERROR_QUERY_NOT_FOUND = 1591; - public static final int ERROR_QUERY_IN_USE = 1592; - public static final int ERROR_CURSOR_NOT_FOUND = 1600; - public static final int ERROR_CURSOR_BUSY = 1601; - public static final int ERROR_TRANSACTION_INTERNAL = 1650; - public static final int ERROR_TRANSACTION_NESTED = 1651; - public static final int ERROR_TRANSACTION_UNREGISTERED_COLLECTION = 1652; - public static final int ERROR_TRANSACTION_DISALLOWED_OPERATION = 1653; - public static final int ERROR_TRANSACTION_ABORTED = 1654; - public static final int ERROR_USER_INVALID_NAME = 1700; - public static final int ERROR_USER_INVALID_PASSWORD = 1701; - public static final int ERROR_USER_DUPLICATE = 1702; - public static final int ERROR_USER_NOT_FOUND = 1703; - public static final int ERROR_USER_CHANGE_PASSWORD = 1704; - public static final int ERROR_APPLICATION_INVALID_NAME = 1750; - public static final int ERROR_APPLICATION_INVALID_MOUNT = 1751; - public static final int ERROR_APPLICATION_DOWNLOAD_FAILED = 1752; - public static final int ERROR_APPLICATION_UPLOAD_FAILED = 1753; - public static final int ERROR_KEYVALUE_INVALID_KEY = 1800; - public static final int ERROR_KEYVALUE_KEY_EXISTS = 1801; - public static final int ERROR_KEYVALUE_KEY_NOT_FOUND = 1802; - public static final int ERROR_KEYVALUE_KEY_NOT_UNIQUE = 1803; - public static final int ERROR_KEYVALUE_KEY_NOT_CHANGED = 1804; - public static final int ERROR_KEYVALUE_KEY_NOT_REMOVED = 1805; - public static final int ERROR_KEYVALUE_NO_VALUE = 1806; - public static final int ERROR_TASK_INVALID_ID = 1850; - public static final int ERROR_TASK_DUPLICATE_ID = 1851; - public static final int ERROR_TASK_NOT_FOUND = 1852; - public static final int ERROR_GRAPH_INVALID_GRAPH = 1901; - public static final int ERROR_GRAPH_COULD_NOT_CREATE_GRAPH = 1902; - public static final int ERROR_GRAPH_INVALID_VERTEX = 1903; - public static final int ERROR_GRAPH_COULD_NOT_CREATE_VERTEX = 1904; - public static final int ERROR_GRAPH_COULD_NOT_CHANGE_VERTEX = 1905; - public static final int ERROR_GRAPH_INVALID_EDGE = 1906; - public static final int ERROR_GRAPH_COULD_NOT_CREATE_EDGE = 1907; - public static final int ERROR_GRAPH_COULD_NOT_CHANGE_EDGE = 1908; - public static final int ERROR_GRAPH_TOO_MANY_ITERATIONS = 1909; - public static final int ERROR_GRAPH_INVALID_FILTER_RESULT = 1910; - public static final int ERROR_GRAPH_COLLECTION_MULTI_USE = 1920; - public static final int ERROR_GRAPH_COLLECTION_USE_IN_MULTI_GRAPHS = 1921; - public static final int ERROR_GRAPH_CREATE_MISSING_NAME = 1922; - public static final int ERROR_GRAPH_CREATE_MALFORMED_EDGE_DEFINITION = 1923; - public static final int ERROR_GRAPH_NOT_FOUND = 1924; - public static final int ERROR_GRAPH_DUPLICATE = 1925; - public static final int ERROR_GRAPH_VERTEX_COL_DOES_NOT_EXIST = 1926; - public static final int ERROR_GRAPH_WRONG_COLLECTION_TYPE_VERTEX = 1927; - public static final int ERROR_GRAPH_NOT_IN_ORPHAN_COLLECTION = 1928; - public static final int ERROR_GRAPH_COLLECTION_USED_IN_EDGE_DEF = 1929; - public static final int ERROR_GRAPH_EDGE_COLLECTION_NOT_USED = 1930; - public static final int ERROR_GRAPH_NOT_AN_ARANGO_COLLECTION = 1931; - public static final int ERROR_GRAPH_NO_GRAPH_COLLECTION = 1932; - public static final int ERROR_GRAPH_INVALID_EXAMPLE_ARRAY_OBJECT_STRING = 1933; - public static final int ERROR_GRAPH_INVALID_EXAMPLE_ARRAY_OBJECT = 1934; - public static final int ERROR_GRAPH_INVALID_NUMBER_OF_ARGUMENTS = 1935; - public static final int ERROR_GRAPH_INVALID_PARAMETER = 1936; - public static final int ERROR_GRAPH_INVALID_ID = 1937; - public static final int ERROR_GRAPH_COLLECTION_USED_IN_ORPHANS = 1938; - public static final int ERROR_GRAPH_EDGE_COL_DOES_NOT_EXIST = 1939; - public static final int ERROR_GRAPH_EMPTY = 1940; - public static final int ERROR_SESSION_UNKNOWN = 1950; - public static final int ERROR_SESSION_EXPIRED = 1951; - public static final int SIMPLE_CLIENT_UNKNOWN_ERROR = 2000; - public static final int SIMPLE_CLIENT_COULD_NOT_CONNECT = 2001; - public static final int SIMPLE_CLIENT_COULD_NOT_WRITE = 2002; - public static final int SIMPLE_CLIENT_COULD_NOT_READ = 2003; - public static final int ERROR_MALFORMED_MANIFEST_FILE = 3000; - public static final int ERROR_INVALID_APPLICATION_MANIFEST = 3001; - public static final int ERROR_INVALID_FOXX_OPTIONS = 3004; - public static final int ERROR_INVALID_MOUNTPOINT = 3007; - public static final int ERROR_APP_NOT_FOUND = 3009; - public static final int ERROR_APP_NEEDS_CONFIGURATION = 3010; - public static final int ERROR_MODULE_NOT_FOUND = 3100; - public static final int ERROR_MODULE_FAILURE = 3103; - public static final int RESULT_ELEMENT_EXISTS = 10000; - public static final int RESULT_ELEMENT_NOT_FOUND = 10001; - public static final int ERROR_QUEUE_ALREADY_EXISTS = 21000; - public static final int ERROR_DISPATCHER_IS_STOPPING = 21001; - public static final int ERROR_QUEUE_UNKNOWN = 21002; - public static final int ERROR_QUEUE_FULL = 21003; - -} - diff --git a/src/main/java/com/arangodb/InternalAdminDriver.java b/src/main/java/com/arangodb/InternalAdminDriver.java deleted file mode 100644 index 8a5487419..000000000 --- a/src/main/java/com/arangodb/InternalAdminDriver.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.arangodb; - -import com.arangodb.entity.AdminLogEntity; -import com.arangodb.entity.ArangoUnixTime; -import com.arangodb.entity.ArangoVersion; -import com.arangodb.entity.DefaultEntity; -import com.arangodb.entity.StatisticsDescriptionEntity; -import com.arangodb.entity.StatisticsEntity; -import com.arangodb.impl.BaseDriverInterface; - -/** - * Created by fbartels on 10/27/14. - */ -public interface InternalAdminDriver extends BaseDriverInterface { - AdminLogEntity getServerLog( - Integer logLevel, - Boolean logLevelUpTo, - Integer start, - Integer size, - Integer offset, - Boolean sortAsc, - String text) throws ArangoException; - - /** - * Get the ArangoDB database statistics - * - * @return the database statistics - * @throws ArangoException - */ - StatisticsEntity getStatistics() throws ArangoException; - - StatisticsDescriptionEntity getStatisticsDescription() throws ArangoException; - - ArangoVersion getVersion() throws ArangoException; - - ArangoUnixTime getTime() throws ArangoException; - - DefaultEntity reloadRouting() throws ArangoException; - - DefaultEntity executeScript(String database, String jsCode) throws ArangoException; -} diff --git a/src/main/java/com/arangodb/InternalAqlFunctionsDriver.java b/src/main/java/com/arangodb/InternalAqlFunctionsDriver.java deleted file mode 100644 index d84fcf4db..000000000 --- a/src/main/java/com/arangodb/InternalAqlFunctionsDriver.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.arangodb; - -import com.arangodb.entity.AqlFunctionsEntity; -import com.arangodb.entity.DefaultEntity; -import com.arangodb.impl.BaseDriverInterface; - -/** - * Created by fbartels on 10/27/14. - */ -public interface InternalAqlFunctionsDriver extends BaseDriverInterface { - DefaultEntity createAqlFunction(String database, String name, String code) throws ArangoException; - - AqlFunctionsEntity getAqlFunctions(String database, String namespace) throws ArangoException; - - DefaultEntity deleteAqlFunction(String database, String name, boolean isNameSpace) throws ArangoException; -} diff --git a/src/main/java/com/arangodb/InternalCollectionDriver.java b/src/main/java/com/arangodb/InternalCollectionDriver.java deleted file mode 100644 index 4cb3c0fd7..000000000 --- a/src/main/java/com/arangodb/InternalCollectionDriver.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.arangodb; - -import com.arangodb.entity.CollectionEntity; -import com.arangodb.entity.CollectionOptions; -import com.arangodb.entity.CollectionsEntity; -import com.arangodb.impl.BaseDriverInterface; - -/** - * Created by fbartels on 10/27/14. - */ -public interface InternalCollectionDriver extends BaseDriverInterface { - CollectionEntity createCollection(String database, String name, CollectionOptions collectionOptions) - throws ArangoException; - - CollectionEntity getCollection(String database, String name) throws ArangoException; - - CollectionEntity getCollectionRevision(String database, String name) throws ArangoException; - - CollectionEntity getCollectionProperties(String database, String name) throws ArangoException; - - CollectionEntity getCollectionCount(String database, String name) throws ArangoException; - - CollectionEntity getCollectionFigures(String database, String name) throws ArangoException; - - CollectionEntity getCollectionChecksum(String database, String name, Boolean withRevisions, Boolean withData) - throws ArangoException; - - CollectionsEntity getCollections(String database, Boolean excludeSystem) throws ArangoException; - - CollectionEntity loadCollection(String database, String name, Boolean count) throws ArangoException; - - CollectionEntity unloadCollection(String database, String name) throws ArangoException; - - CollectionEntity truncateCollection(String database, String name) throws ArangoException; - - CollectionEntity setCollectionProperties(String database, String name, Boolean newWaitForSync, Long journalSize) - throws ArangoException; - - CollectionEntity renameCollection(String database, String name, String newName) throws ArangoException; - - CollectionEntity deleteCollection(String database, String name) throws ArangoException; -} diff --git a/src/main/java/com/arangodb/InternalCursorDriver.java b/src/main/java/com/arangodb/InternalCursorDriver.java deleted file mode 100644 index 4b64075f2..000000000 --- a/src/main/java/com/arangodb/InternalCursorDriver.java +++ /dev/null @@ -1,111 +0,0 @@ -package com.arangodb; - -import java.util.Map; - -import com.arangodb.entity.CursorEntity; -import com.arangodb.entity.DefaultEntity; -import com.arangodb.entity.DocumentEntity; -import com.arangodb.entity.QueriesResultEntity; -import com.arangodb.entity.QueryTrackingPropertiesEntity; -import com.arangodb.entity.ShortestPathEntity; -import com.arangodb.impl.BaseDriverInterface; -import com.arangodb.util.AqlQueryOptions; -import com.arangodb.util.ShortestPathOptions; - -/** - * Created by fbartels on 10/27/14. - * - */ -public interface InternalCursorDriver extends BaseDriverInterface { - - CursorEntity validateQuery(String database, String query) throws ArangoException; - - // request without DocumentEntity - CursorEntity executeCursorEntityQuery( - String database, - String query, - Map bindVars, - AqlQueryOptions aqlQueryOptions, - Class... clazz) throws ArangoException; - - CursorEntity continueQuery(String database, long cursorId, Class... clazz) throws ArangoException; - - DefaultEntity finishQuery(String database, long cursorId) throws ArangoException; - - // request a cursor without DocumentEntity - CursorResult executeAqlQuery( - String database, - String query, - Map bindVars, - AqlQueryOptions aqlQueryOptions, - Class clazz) throws ArangoException; - - // request a cursor without DocumentEntity - CursorRawResult executeAqlQueryRaw( - String database, - String query, - Map bindVars, - AqlQueryOptions aqlQueryOptions) throws ArangoException; - - // return the raw JSON response from server - String executeAqlQueryJSON( - String database, - String query, - Map bindVars, - AqlQueryOptions aqlQueryOptions) throws ArangoException; - - // request a cursor with DocumentEntity - > DocumentCursorResult executeBaseCursorQuery( - String database, - String query, - Map bindVars, - AqlQueryOptions aqlQueryOptions, - Class classDocumentEntity, - Class clazz) throws ArangoException; - - /** - * Get the shortest path from a vertex to another vertex - * - * @param database - * the database name - * @param graphName - * the graph name - * @param startVertexExample - * a start vertex example object (or null) - * @param endVertexExample - * a start vertex example object (or null) - * @param shortestPathOptions - * shortest path options - * @param aqlQueryOptions - * AQL query options - * @param vertexClass - * the vertex class - * @param edgeClass - * the edge class - * @return a ShortestPathEntity object - * @throws ArangoException - */ - public ShortestPathEntity getShortestPath( - String database, - String graphName, - Object startVertexExample, - Object endVertexExample, - ShortestPathOptions shortestPathOptions, - AqlQueryOptions aqlQueryOptions, - Class vertexClass, - Class edgeClass, - ArangoDriver driver) throws ArangoException; - - QueryTrackingPropertiesEntity getQueryTrackingProperties(String database) throws ArangoException; - - QueryTrackingPropertiesEntity setQueryTrackingProperties(String database, QueryTrackingPropertiesEntity properties) - throws ArangoException; - - QueriesResultEntity getCurrentlyRunningQueries(String database) throws ArangoException; - - QueriesResultEntity getSlowQueries(String database) throws ArangoException; - - DefaultEntity deleteSlowQueries(String database) throws ArangoException; - - DefaultEntity killQuery(String database, String id) throws ArangoException; -} diff --git a/src/main/java/com/arangodb/InternalDatabaseDriver.java b/src/main/java/com/arangodb/InternalDatabaseDriver.java deleted file mode 100644 index 1d6f7fccf..000000000 --- a/src/main/java/com/arangodb/InternalDatabaseDriver.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.arangodb; - -import com.arangodb.entity.BooleanResultEntity; -import com.arangodb.entity.DatabaseEntity; -import com.arangodb.entity.StringsResultEntity; -import com.arangodb.entity.UserEntity; -import com.arangodb.impl.BaseDriverInterface; - -/** - * Created by fbartels on 10/27/14. - */ -public interface InternalDatabaseDriver extends BaseDriverInterface { - DatabaseEntity getCurrentDatabase() throws ArangoException; - - StringsResultEntity getDatabases(boolean currentUserAccessableOnly, String username, String password) throws ArangoException; - - BooleanResultEntity createDatabase(String database, UserEntity... users) throws ArangoException; - - BooleanResultEntity deleteDatabase(String database) throws ArangoException; -} diff --git a/src/main/java/com/arangodb/InternalDocumentDriver.java b/src/main/java/com/arangodb/InternalDocumentDriver.java deleted file mode 100644 index bc065fec2..000000000 --- a/src/main/java/com/arangodb/InternalDocumentDriver.java +++ /dev/null @@ -1,81 +0,0 @@ -package com.arangodb; - -import java.util.List; - -import com.arangodb.entity.DocumentEntity; -import com.arangodb.entity.EdgeEntity; -import com.arangodb.impl.BaseDriverInterface; - -/** - * Created by fbartels on 10/27/14. - */ -public interface InternalDocumentDriver extends BaseDriverInterface { - DocumentEntity createDocument( - String database, - String collectionName, - String documentKey, - T value, - Boolean waitForSync) throws ArangoException; - - DocumentEntity createDocumentRaw( - String database, - String collectionName, - String rawJsonString, - Boolean waitForSync) throws ArangoException; - - DocumentEntity replaceDocument( - String database, - String documentHandle, - T value, - String rev, - Boolean waitForSync) throws ArangoException; - - DocumentEntity replaceDocumentRaw( - String database, - String documentHandle, - String rawJsonString, - String rev, - Boolean waitForSync) throws ArangoException; - - DocumentEntity updateDocument( - String database, - String documentHandle, - T value, - String rev, - Boolean waitForSync, - Boolean keepNull) throws ArangoException; - - DocumentEntity updateDocumentRaw( - String database, - String documentHandle, - String rawJsonString, - String rev, - Boolean waitForSync, - Boolean keepNull) throws ArangoException; - - List getDocuments(String database, String collectionName) throws ArangoException; - - String checkDocument(String database, String documentHandle) throws ArangoException; - - DocumentEntity getDocument( - String database, - String documentHandle, - Class clazz, - String ifNoneMatchRevision, - String ifMatchRevision) throws ArangoException; - - String getDocumentRaw(String database, String documentHandle, String ifNoneMatchRevision, String ifMatchRevision) - throws ArangoException; - - DocumentEntity deleteDocument(String database, String documentHandle, String rev) throws ArangoException; - - EdgeEntity createEdge( - String database, - String collectionName, - String documentKey, - T value, - String fromHandle, - String toHandle, - Boolean waitForSync) throws ArangoException; - -} diff --git a/src/main/java/com/arangodb/InternalEndpointDriver.java b/src/main/java/com/arangodb/InternalEndpointDriver.java deleted file mode 100644 index f77bc8cb9..000000000 --- a/src/main/java/com/arangodb/InternalEndpointDriver.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.arangodb; - -import java.util.List; - -import com.arangodb.entity.BooleanResultEntity; -import com.arangodb.entity.Endpoint; -import com.arangodb.impl.BaseDriverInterface; - -/** - * Created by fbartels on 10/27/14. - */ -public interface InternalEndpointDriver extends BaseDriverInterface { - BooleanResultEntity createEndpoint(String endpoint, String... databases) throws ArangoException; - - List getEndpoints() throws ArangoException; - - BooleanResultEntity deleteEndpoint(String endpoint) throws ArangoException; -} diff --git a/src/main/java/com/arangodb/InternalGraphDriver.java b/src/main/java/com/arangodb/InternalGraphDriver.java deleted file mode 100644 index de9d5421e..000000000 --- a/src/main/java/com/arangodb/InternalGraphDriver.java +++ /dev/null @@ -1,467 +0,0 @@ -/** - * Copyright 2004-2014 triAGENS GmbH, Cologne, Germany - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Copyright holder is triAGENS GmbH, Cologne, Germany - * - * @author fbartels - * @author gschwab - * @author Copyright 2014, triAGENS GmbH, Cologne, Germany - */ - -package com.arangodb; - -import java.util.List; - -import com.arangodb.entity.DeletedEntity; -import com.arangodb.entity.EdgeDefinitionEntity; -import com.arangodb.entity.EdgeEntity; -import com.arangodb.entity.GraphEntity; -import com.arangodb.entity.GraphsEntity; -import com.arangodb.entity.marker.VertexEntity; -import com.arangodb.impl.BaseDriverInterface; - -public interface InternalGraphDriver extends BaseDriverInterface { - - /** - * Creates an empty graph. - * - * @param databaseName - * @param graphName - * @param waitForSync - * @return GraphEntity - * @throws ArangoException - */ - GraphEntity createGraph(String databaseName, String graphName, Boolean waitForSync) throws ArangoException; - - /** - * Creates a graph. - * - * @param databaseName - * @param graphName - * @param edgeDefinitions - * @param orphanCollections - * @param waitForSync - * @return GraphEntity - * @throws ArangoException - */ - GraphEntity createGraph( - String databaseName, - String graphName, - List edgeDefinitions, - List orphanCollections, - Boolean waitForSync) throws ArangoException; - - /** - * Returns a GraphsEntity containing all graph as GraphEntity object. - * - * @param databaseName - * @return GraphsEntity - * @throws ArangoException - */ - GraphsEntity getGraphs(String databaseName) throws ArangoException; - - /** - * Creates a list of the names of all available graphs. - * - * @param databaseName - * @return List - * @throws ArangoException - */ - List getGraphList(String databaseName) throws ArangoException; - - /** - * Get graph object by name, including its edge definitions and vertex - * collections. - * - * @param databaseName - * @param graphName - * @return GraphEntity - * @throws ArangoException - */ - GraphEntity getGraph(String databaseName, String graphName) throws ArangoException; - - /** - * Delete a graph by its name. If dropCollections is true, all collections - * of the graph will be dropped, if they are not used in another graph. - * - * @param databaseName - * @param graphName - * @param dropCollections - * @return DeletedEntity - * @throws ArangoException - */ - DeletedEntity deleteGraph(String databaseName, String graphName, Boolean dropCollections) throws ArangoException; - - /** - * Returns a list of names of all vertex collections of a graph, defined in - * the graphs edgeDefinitions (in "from", "to", and "orphanCollections") - * - * @param databaseName - * @param graphName - * @return List - * @throws ArangoException - */ - List getVertexCollections(String databaseName, String graphName, boolean excludeOrphan) - throws ArangoException; - - /** - * - * @param databaseName - * @param graphName - * @param collectionName - * @return GraphEntity - * @throws ArangoException - */ - GraphEntity createVertexCollection(String databaseName, String graphName, String collectionName) - throws ArangoException; - - /** - * - * @param databaseName - * @param graphName - * @param collectionName - * @param dropCollection - * @return DeletedEntity - * @throws ArangoException - */ - DeletedEntity deleteVertexCollection( - String databaseName, - String graphName, - String collectionName, - Boolean dropCollection) throws ArangoException; - - /** - * Returns a list of names of all edge collections of a graph that are - * defined in the graphs edgeDefinitions - * - * @param databaseName - * @param graphName - * @return List - * @throws ArangoException - */ - List getEdgeCollections(String databaseName, String graphName) throws ArangoException; - - /** - * Adds a new edge definition to an existing graph. - * - * @param databaseName - * @param graphName - * @param edgeDefinition - * @return GraphEntity - * @throws ArangoException - */ - GraphEntity createEdgeDefinition(String databaseName, String graphName, EdgeDefinitionEntity edgeDefinition) - throws ArangoException; - - /** - * Replaces an existing edge definition to an existing graph. This will also - * change the edge definitions of all other graphs using this definition as - * well. - * - * @param databaseName - * @param graphName - * @param edgeName - * @param edgeDefinition - * @return GraphEntity - * @throws ArangoException - */ - GraphEntity replaceEdgeDefinition( - String databaseName, - String graphName, - String edgeName, - EdgeDefinitionEntity edgeDefinition) throws ArangoException; - - /** - * Removes an existing edge definition from this graph. All data stored in - * the collections is dropped as well as long as it is not used in other - * graphs. - * - * @param databaseName - * @param graphName - * @param edgeName - * @param dropCollection - * @return GraphEntity - * @throws ArangoException - */ - GraphEntity deleteEdgeDefinition(String databaseName, String graphName, String edgeName, Boolean dropCollection) - throws ArangoException; - - /** - * Stores a new vertex with the information contained within the document - * into the given collection. - * - * @param database - * @param graphName - * @param collectionName - * @param vertex - * @param waitForSync - * @return DocumentEntity - * @throws ArangoException - */ - VertexEntity createVertex( - String database, - String graphName, - String collectionName, - T vertex, - Boolean waitForSync) throws ArangoException; - - /** - * Stores a new vertex with the information contained within the document - * into the given collection. - * - * @param database - * @param graphName - * @param collectionName - * @param key - * @param vertex - * @param waitForSync - * @return DocumentEntity - * @throws ArangoException - */ - VertexEntity createVertex( - String database, - String graphName, - String collectionName, - String key, - T vertex, - Boolean waitForSync) throws ArangoException; - - /** - * Gets a vertex with the given key if it is contained within your graph. - * - * @param database - * @param graphName - * @param collectionName - * @param key - * @param clazz - * @param ifMatchRevision - * @param ifNoneMatchRevision - * @return a VertexEntity object - * @throws ArangoException - */ - VertexEntity getVertex( - String database, - String graphName, - String collectionName, - String key, - Class clazz, - String ifMatchRevision, - String ifNoneMatchRevision) throws ArangoException; - - /** - * Replaces a vertex with the given key by the content in the body. This - * will only run successfully if the vertex is contained within the graph. - * - * @param database - * @param graphName - * @param collectionName - * @param key - * @param vertex - * @param waitForSync - * @param ifMatchRevision - * @param ifNoneMatchRevision - * @return DocumentEntity - * @throws ArangoException - */ - VertexEntity replaceVertex( - String database, - String graphName, - String collectionName, - String key, - T vertex, - Boolean waitForSync, - String ifMatchRevision, - String ifNoneMatchRevision) throws ArangoException; - - /** - * Updates a vertex with the given key by adding the content in the body. - * This will only run successfully if the vertex is contained within the - * graph. - * - * @param databaseName - * @param graphName - * @param collectionName - * @param key - * @param vertex - * @param keepNull - * @param waitForSync - * @param ifMatchRevision - * @param ifNoneMatchRevision - * @return a VertexEntity object - * @throws ArangoException - */ - VertexEntity updateVertex( - String databaseName, - String graphName, - String collectionName, - String key, - T vertex, - Boolean keepNull, - Boolean waitForSync, - String ifMatchRevision, - String ifNoneMatchRevision) throws ArangoException; - - /** - * Deletes a vertex with the given key, if it is contained within the graph. - * Furthermore all edges connected to this vertex will be deleted. - * - * @param database - * @param graphName - * @param collectionName - * @param key - * @param waitForSync - * @param ifMatchRevision - * @param ifNoneMatchRevision - * @return a DeletedEntity object - * @throws ArangoException - */ - DeletedEntity deleteVertex( - String database, - String graphName, - String collectionName, - String key, - Boolean waitForSync, - String ifMatchRevision, - String ifNoneMatchRevision) throws ArangoException; - - /** - * - * - * @param database - * @param graphName - * @param edgeCollectionName - * @param key - * @param fromHandle - * @param toHandle - * @param value - * @param waitForSync - * @return a EdgeEntity object - * @throws ArangoException - */ - EdgeEntity createEdge( - String database, - String graphName, - String edgeCollectionName, - String key, - String fromHandle, - String toHandle, - T value, - Boolean waitForSync) throws ArangoException; - - /** - * Loads an edge with the given key if it is contained within your graph. - * - * @param database - * @param graphName - * @param edgeCollectionName - * @param key - * @param clazz - * @param ifNoneMatchRevision - * @param ifMatchRevision - * @return a EdgeEntity object - * @throws ArangoException - */ - EdgeEntity getEdge( - String database, - String graphName, - String edgeCollectionName, - String key, - Class clazz, - String ifMatchRevision, - String ifNoneMatchRevision) throws ArangoException; - - /** - * Deletes an edge with the given id, if it is contained within the graph. - * - * @param database - * @param graphName - * @param edgeCollectionName - * @param key - * @param waitForSync - * @param rev - * @param ifMatchRevision - * @return DeletedEntity - * @throws ArangoException - */ - DeletedEntity deleteEdge( - String database, - String graphName, - String edgeCollectionName, - String key, - Boolean waitForSync, - String rev, - String ifMatchRevision) throws ArangoException; - - /** - * Replaces an edge with the given key by the content in the body. This will - * only run successfully if the edge is contained within the graph. - * - * @param database - * @param graphName - * @param edgeCollectionName - * @param key - * @param fromHandle - * @param toHandle - * @param value - * @param waitForSync - * @param ifMatchRevision - * @param ifNoneMatchRevision - * @return EdgeEntity - * @throws ArangoException - */ - EdgeEntity replaceEdge( - String database, - String graphName, - String edgeCollectionName, - String key, - String fromHandle, - String toHandle, - T value, - Boolean waitForSync, - String ifMatchRevision, - String ifNoneMatchRevision) throws ArangoException; - - /** - * Updates an edge with the given key by adding the content in the body. - * This will only run successfully if the edge is contained within the - * graph. - * - * @param database - * @param graphName - * @param edgeCollectionName - * @param key - * @param fromHandle - * @param toHandle - * @param value - * @param waitForSync - * @param keepNull - * @param ifMatchRevision - * @param ifNoneMatchRevision - * @return EdgeEntity - * @throws ArangoException - */ - EdgeEntity updateEdge( - String database, - String graphName, - String edgeCollectionName, - String key, - String fromHandle, - String toHandle, - T value, - Boolean waitForSync, - Boolean keepNull, - String ifMatchRevision, - String ifNoneMatchRevision) throws ArangoException; - -} diff --git a/src/main/java/com/arangodb/InternalImportDriver.java b/src/main/java/com/arangodb/InternalImportDriver.java deleted file mode 100644 index 8ebeaa23d..000000000 --- a/src/main/java/com/arangodb/InternalImportDriver.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.arangodb; - -import java.util.Collection; - -import com.arangodb.entity.ImportResultEntity; -import com.arangodb.impl.BaseDriverInterface; -import com.arangodb.util.ImportOptions; -import com.arangodb.util.ImportOptionsJson; -import com.arangodb.util.ImportOptionsRaw; - -/** - * Created by fbartels on 10/27/14. - */ -public interface InternalImportDriver extends BaseDriverInterface { - - ImportResultEntity importDocuments( - String database, - String collection, - Collection values, - ImportOptionsJson importOptionsJson) throws ArangoException; - - ImportResultEntity importDocumentsRaw( - String database, - String collection, - String values, - ImportOptionsRaw importOptionsRaw) throws ArangoException; - - ImportResultEntity importDocumentsByHeaderValues( - String database, - String collection, - Collection> headerValues, - ImportOptions importOptions) throws ArangoException; - - ImportResultEntity importDocumentsByHeaderValuesRaw( - String database, - String collection, - String headerValues, - ImportOptions importOptions) throws ArangoException; -} diff --git a/src/main/java/com/arangodb/InternalIndexDriver.java b/src/main/java/com/arangodb/InternalIndexDriver.java deleted file mode 100644 index 83f03dd52..000000000 --- a/src/main/java/com/arangodb/InternalIndexDriver.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.arangodb; - -import com.arangodb.entity.IndexEntity; -import com.arangodb.entity.IndexType; -import com.arangodb.entity.IndexesEntity; -import com.arangodb.impl.BaseDriverInterface; - -/** - * Created by fbartels on 10/27/14. - */ -public interface InternalIndexDriver extends BaseDriverInterface { - IndexEntity createIndex( - String database, - String collectionName, - IndexType type, - boolean unique, - boolean sparse, - String... fields) throws ArangoException; - - IndexEntity createIndex(String database, String collectionName, IndexType type, boolean unique, String... fields) - throws ArangoException; - - IndexEntity createFulltextIndex(String database, String collectionName, Integer minLength, String... fields) - throws ArangoException; - - IndexEntity deleteIndex(String database, String indexHandle) throws ArangoException; - - IndexEntity getIndex(String database, String indexHandle) throws ArangoException; - - IndexesEntity getIndexes(String database, String collectionName) throws ArangoException; -} diff --git a/src/main/java/com/arangodb/InternalJobsDriver.java b/src/main/java/com/arangodb/InternalJobsDriver.java deleted file mode 100644 index d6920495f..000000000 --- a/src/main/java/com/arangodb/InternalJobsDriver.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.arangodb; - -import java.util.List; - -import com.arangodb.entity.JobsEntity; -import com.arangodb.impl.BaseDriverInterface; - -/** - * Created by fbartels on 10/28/14. - */ -public interface InternalJobsDriver extends BaseDriverInterface { - - List getJobs(String database, JobsEntity.JobState jobState, int count) throws ArangoException; - - List getJobs(String database, JobsEntity.JobState jobState) throws ArangoException; - - void deleteAllJobs(String database) throws ArangoException; - - void deleteJobById(String database, String jobId) throws ArangoException; - - void deleteExpiredJobs(String database, int timeStamp) throws ArangoException; - - T getJobResult(String database, String jobId) throws ArangoException; - -} diff --git a/src/main/java/com/arangodb/InternalQueryCacheDriver.java b/src/main/java/com/arangodb/InternalQueryCacheDriver.java deleted file mode 100644 index da59691b4..000000000 --- a/src/main/java/com/arangodb/InternalQueryCacheDriver.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.arangodb; - -import com.arangodb.entity.DefaultEntity; -import com.arangodb.entity.QueryCachePropertiesEntity; -import com.arangodb.impl.BaseDriverInterface; - -/** - * Created by a-brandt on 2015-09-11. - */ -public interface InternalQueryCacheDriver extends BaseDriverInterface { - - DefaultEntity deleteQueryCache() throws ArangoException; - - QueryCachePropertiesEntity getQueryCacheProperties() throws ArangoException; - - QueryCachePropertiesEntity setQueryCacheProperties(QueryCachePropertiesEntity properties) throws ArangoException; - -} diff --git a/src/main/java/com/arangodb/InternalReplicationDriver.java b/src/main/java/com/arangodb/InternalReplicationDriver.java deleted file mode 100644 index 6fbefaa47..000000000 --- a/src/main/java/com/arangodb/InternalReplicationDriver.java +++ /dev/null @@ -1,78 +0,0 @@ -package com.arangodb; - -import com.arangodb.entity.ReplicationApplierConfigEntity; -import com.arangodb.entity.ReplicationApplierStateEntity; -import com.arangodb.entity.ReplicationInventoryEntity; -import com.arangodb.entity.ReplicationLoggerConfigEntity; -import com.arangodb.entity.ReplicationLoggerStateEntity; -import com.arangodb.entity.ReplicationSyncEntity; -import com.arangodb.entity.RestrictType; -import com.arangodb.impl.BaseDriverInterface; -import com.arangodb.util.DumpHandler; - -/** - * Created by fbartels on 10/27/14. - */ -public interface InternalReplicationDriver extends BaseDriverInterface { - ReplicationInventoryEntity getReplicationInventory(String database, Boolean includeSystem) throws ArangoException; - - void getReplicationDump( - String database, - String collectionName, - Long from, - Long to, - Integer chunkSize, - Boolean ticks, - Class clazz, - DumpHandler handler) throws ArangoException; - - ReplicationSyncEntity syncReplication( - String localDatabase, - String endpoint, - String database, - String username, - String password, - RestrictType restrictType, - String... restrictCollections) throws ArangoException; - - String getReplicationServerId() throws ArangoException; - - boolean startReplicationLogger(String database) throws ArangoException; - - boolean stopReplicationLogger(String database) throws ArangoException; - - ReplicationLoggerConfigEntity getReplicationLoggerConfig(String database) throws ArangoException; - - ReplicationLoggerConfigEntity setReplicationLoggerConfig( - String database, - Boolean autoStart, - Boolean logRemoteChanges, - Long maxEvents, - Long maxEventsSize) throws ArangoException; - - ReplicationLoggerStateEntity getReplicationLoggerState(String database) throws ArangoException; - - ReplicationApplierConfigEntity getReplicationApplierConfig(String database) throws ArangoException; - - ReplicationApplierConfigEntity setReplicationApplierConfig( - String localDatabase, - String endpoint, - String database, - String username, - String password, - Integer maxConnectRetries, - Integer connectTimeout, - Integer requestTimeout, - Integer chunkSize, - Boolean autoStart, - Boolean adaptivePolling) throws ArangoException; - - ReplicationApplierConfigEntity setReplicationApplierConfig(String database, ReplicationApplierConfigEntity param) - throws ArangoException; - - ReplicationApplierStateEntity startReplicationApplier(String database, Long from) throws ArangoException; - - ReplicationApplierStateEntity stopReplicationApplier(String database) throws ArangoException; - - ReplicationApplierStateEntity getReplicationApplierState(String database) throws ArangoException; -} diff --git a/src/main/java/com/arangodb/InternalSimpleDriver.java b/src/main/java/com/arangodb/InternalSimpleDriver.java deleted file mode 100644 index 6adf27cae..000000000 --- a/src/main/java/com/arangodb/InternalSimpleDriver.java +++ /dev/null @@ -1,83 +0,0 @@ -package com.arangodb; - -import java.util.Map; - -import com.arangodb.entity.ScalarExampleEntity; -import com.arangodb.entity.SimpleByResultEntity; -import com.arangodb.impl.BaseDriverInterface; - -/** - * Created by fbartels on 10/27/14. - */ -public interface InternalSimpleDriver extends BaseDriverInterface { - - DocumentCursor executeSimpleAllDocuments( - String database, - String collectionName, - int skip, - int limit, - Class clazz) throws ArangoException; - - DocumentCursor executeSimpleByExampleDocuments( - String database, - String collectionName, - Map example, - int skip, - int limit, - Class clazz) throws ArangoException; - - ScalarExampleEntity executeSimpleFirstExample( - String database, - String collectionName, - Map example, - Class clazz) throws ArangoException; - - ScalarExampleEntity executeSimpleAny(String database, String collectionName, Class clazz) - throws ArangoException; - - DocumentCursor executeSimpleRangeWithDocuments( - String database, - String collectionName, - String attribute, - Object left, - Object right, - Boolean closed, - int skip, - int limit, - Class clazz) throws ArangoException; - - SimpleByResultEntity executeSimpleRemoveByExample( - String database, - String collectionName, - Map example, - Boolean waitForSync, - Integer limit) throws ArangoException; - - SimpleByResultEntity executeSimpleReplaceByExample( - String database, - String collectionName, - Map example, - Map newValue, - Boolean waitForSync, - Integer limit) throws ArangoException; - - SimpleByResultEntity executeSimpleUpdateByExample( - String database, - String collectionName, - Map example, - Map newValue, - Boolean keepNull, - Boolean waitForSync, - Integer limit) throws ArangoException; - - DocumentCursor executeSimpleFulltextWithDocuments( - String database, - String collectionName, - String attribute, - String query, - int skip, - int limit, - String index, - Class clazz) throws ArangoException; - -} diff --git a/src/main/java/com/arangodb/InternalTransactionDriver.java b/src/main/java/com/arangodb/InternalTransactionDriver.java deleted file mode 100644 index 96d7a5e27..000000000 --- a/src/main/java/com/arangodb/InternalTransactionDriver.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.arangodb; - -import com.arangodb.entity.TransactionEntity; -import com.arangodb.entity.TransactionResultEntity; -import com.arangodb.impl.BaseDriverInterface; - -/** - * Created by fbartels on 10/28/14. - */ -public interface InternalTransactionDriver extends BaseDriverInterface { - - TransactionEntity createTransaction(String action); - - TransactionResultEntity executeTransaction(String database, TransactionEntity transactionEntity) - throws ArangoException; - -} diff --git a/src/main/java/com/arangodb/InternalTraversalDriver.java b/src/main/java/com/arangodb/InternalTraversalDriver.java deleted file mode 100644 index fca74eb80..000000000 --- a/src/main/java/com/arangodb/InternalTraversalDriver.java +++ /dev/null @@ -1,55 +0,0 @@ -/** - * Copyright 2004-2015 triAGENS GmbH, Cologne, Germany - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Copyright holder is triAGENS GmbH, Cologne, Germany - * - * @author a-brandt - * @author Copyright 2015, triAGENS GmbH, Cologne, Germany - */ - -package com.arangodb; - -import com.arangodb.entity.TraversalEntity; -import com.arangodb.impl.BaseDriverInterface; -import com.arangodb.util.TraversalQueryOptions; - -public interface InternalTraversalDriver extends BaseDriverInterface { - - public enum Strategy { - DEPTHFIRST, - BREADTHFIRST - } - - public enum Order { - PREORDER, - POSTORDER - } - - public enum ItemOrder { - FORWARD, - BACKWARD - } - - public enum Uniqueness { - NONE, - GLOBAL, - PATH - } - - TraversalEntity getTraversal( - String databaseName, - TraversalQueryOptions traversalQueryOptions, - Class vertexClazz, - Class edgeClazz) throws ArangoException; -} diff --git a/src/main/java/com/arangodb/InternalUsersDriver.java b/src/main/java/com/arangodb/InternalUsersDriver.java deleted file mode 100644 index 6b17d68c7..000000000 --- a/src/main/java/com/arangodb/InternalUsersDriver.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.arangodb; - -import java.util.Map; - -import com.arangodb.entity.DefaultEntity; -import com.arangodb.entity.UserEntity; -import com.arangodb.entity.UsersEntity; -import com.arangodb.impl.BaseDriverInterface; - -/** - * Created by fbartels on 10/27/14. - */ -public interface InternalUsersDriver extends BaseDriverInterface { - DefaultEntity createUser(String username, String passwd, Boolean active, Map extra) - throws ArangoException; - - DefaultEntity deleteUser(String username) throws ArangoException; - - UserEntity getUser(String username) throws ArangoException; - - UsersEntity getUsers() throws ArangoException; - - DefaultEntity replaceUser(String username, String passwd, Boolean active, Map extra) - throws ArangoException; - - DefaultEntity updateUser(String username, String passwd, Boolean active, Map extra) - throws ArangoException; - - DefaultEntity grantDatabaseAccess(final String username, final String database) throws ArangoException; -} diff --git a/src/main/java/com/arangodb/NonUniqueResultException.java b/src/main/java/com/arangodb/NonUniqueResultException.java deleted file mode 100644 index b7d7c9041..000000000 --- a/src/main/java/com/arangodb/NonUniqueResultException.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.arangodb; - -/** - * @author mrbatista - */ -public class NonUniqueResultException extends RuntimeException { - - /** - * Constructs a NonUniqueResultException. - * - * @param resultCount - * The number of actual results. - */ - public NonUniqueResultException(int resultCount) { - super("Query did not return a unique result: " + resultCount); - } - -} diff --git a/src/main/java/com/arangodb/VertexCursor.java b/src/main/java/com/arangodb/VertexCursor.java deleted file mode 100644 index 4ff77d376..000000000 --- a/src/main/java/com/arangodb/VertexCursor.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.arangodb; - -import com.arangodb.entity.marker.VertexEntity; - -/** - * @author a-brandt - */ -public class VertexCursor extends BaseCursorProxy> { - - public VertexCursor(DocumentCursorResult> baseCursor) { - super(baseCursor); - } -} diff --git a/src/main/java/com/arangodb/entity/AdminLogEntity.java b/src/main/java/com/arangodb/entity/AdminLogEntity.java deleted file mode 100644 index aea21c42b..000000000 --- a/src/main/java/com/arangodb/entity/AdminLogEntity.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Copyright (C) 2012 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.entity; - -import java.io.Serializable; -import java.util.Date; -import java.util.List; - -/** - * - * A entity defining admin logs - * - * @author tamtam180 - kirscheless at gmail.com - * - */ -public class AdminLogEntity extends BaseEntity { - - /** - * The total amount of log entries - */ - int totalAmount; - - /** - * A list of log entries - * @see com.arangodb.entity.AdminLogEntity.LogEntry - */ - List logs; - - public int getTotalAmount() { - return totalAmount; - } - public List getLogs() { - return logs; - } - public void setTotalAmount(int totalAmount) { - this.totalAmount = totalAmount; - } - public void setLogs(List logs) { - this.logs = logs; - } - - public static class LogEntry implements Serializable { - - /** - * The log id - */ - int lid; - - /** - * The integer representation of a log level - */ - int level; - - /** - * The timestamp of the log entry - */ - Date timestamp; - - /** - * The log message - */ - String text; - - public int getLid() { - return lid; - } - public int getLevel() { - return level; - } - public Date getTimestamp() { - return timestamp; - } - public String getText() { - return text; - } - public void setLid(int lid) { - this.lid = lid; - } - public void setLevel(int level) { - this.level = level; - } - public void setTimestamp(Date timestamp) { - this.timestamp = timestamp; - } - public void setText(String text) { - this.text = text; - } - } - -} diff --git a/src/main/java/com/arangodb/entity/AqlExecutionExplainEntity.java b/src/main/java/com/arangodb/entity/AqlExecutionExplainEntity.java new file mode 100644 index 000000000..3ee66e445 --- /dev/null +++ b/src/main/java/com/arangodb/entity/AqlExecutionExplainEntity.java @@ -0,0 +1,297 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.entity; + +import java.util.Collection; + +/** + * @author Mark - mark at arangodb.com + * + * @see API Documentation + */ +public class AqlExecutionExplainEntity { + + 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 IndexEntity indexes; + private ExecutionExpression expression; + private ExecutionCollection condition; + private Boolean reverse; + + public String getType() { + return type; + } + + public Collection getDependencies() { + return dependencies; + } + + public Long getId() { + return id; + } + + public Integer getEstimatedCost() { + return estimatedCost; + } + + public Integer getEstimatedNrItems() { + return estimatedNrItems; + } + + public Long getDepth() { + return depth; + } + + public String getDatabase() { + return database; + } + + public String getCollection() { + return collection; + } + + public ExecutionVariable getInVariable() { + return inVariable; + } + + public ExecutionVariable getOutVariable() { + return outVariable; + } + + public ExecutionVariable getConditionVariable() { + return conditionVariable; + } + + public Boolean getRandom() { + return random; + } + + public Long getOffset() { + return offset; + } + + public Long getLimit() { + return limit; + } + + public Boolean getFullCount() { + return fullCount; + } + + public ExecutionNode getSubquery() { + return subquery; + } + + public Boolean getIsConst() { + return isConst; + } + + public Boolean getCanThrow() { + return canThrow; + } + + public String getExpressionType() { + return expressionType; + } + + public IndexEntity 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; + } + +} diff --git a/src/main/java/com/arangodb/entity/AqlFunctionEntity.java b/src/main/java/com/arangodb/entity/AqlFunctionEntity.java new file mode 100644 index 000000000..ca81f938c --- /dev/null +++ b/src/main/java/com/arangodb/entity/AqlFunctionEntity.java @@ -0,0 +1,53 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.entity; + +/** + * @author Mark - mark at arangodb.com + * + * @see API + * Documentation + */ +public class AqlFunctionEntity { + + private String name; + private String code; + + 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; + } + +} diff --git a/src/main/java/com/arangodb/entity/AqlFunctionsEntity.java b/src/main/java/com/arangodb/entity/AqlFunctionsEntity.java deleted file mode 100644 index 406156b34..000000000 --- a/src/main/java/com/arangodb/entity/AqlFunctionsEntity.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright (C) 2012 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.entity; - -import java.util.Map; - -/** - * An entity wrapping a list of AQL functions - * - * @author Florian Bartels - * - */ -public class AqlFunctionsEntity extends BaseEntity { - - /** - * A map containing the function name as key and the function as value - */ - Map aqlFunctions; - - public AqlFunctionsEntity() { - // needed for ReflectionUtils - } - - public AqlFunctionsEntity(Map aqlfunctions) { - this.aqlFunctions = aqlfunctions; - } - - public Map getAqlFunctions() { - return aqlFunctions; - } - - public int size() { - return this.aqlFunctions.size(); - } - -} diff --git a/src/main/java/com/arangodb/entity/AqlParseEntity.java b/src/main/java/com/arangodb/entity/AqlParseEntity.java new file mode 100644 index 000000000..dbdd24c5a --- /dev/null +++ b/src/main/java/com/arangodb/entity/AqlParseEntity.java @@ -0,0 +1,77 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.entity; + +import java.util.Collection; + +/** + * @author Mark - mark at arangodb.com + * + * @see API Documentation + */ +public class AqlParseEntity { + + 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 Collection getSubNodes() { + return subNodes; + } + + public String getName() { + return name; + } + + public Long getId() { + return id; + } + + public Object getValue() { + return value; + } + + } + + private Collection collections; + private Collection bindVars; + private Collection ast; + + public Collection getCollections() { + return collections; + } + + public Collection getBindVars() { + return bindVars; + } + + public Collection getAst() { + return ast; + } + +} diff --git a/src/main/java/com/arangodb/entity/ArangoDBVersion.java b/src/main/java/com/arangodb/entity/ArangoDBVersion.java new file mode 100644 index 000000000..aecf45bb5 --- /dev/null +++ b/src/main/java/com/arangodb/entity/ArangoDBVersion.java @@ -0,0 +1,53 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.entity; + +/** + * @author Mark - mark at arangodb.com + * + * @see API + * Documentation + */ +public class ArangoDBVersion { + + private String server; + private String version; + + 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; + } + +} diff --git a/src/main/java/com/arangodb/entity/ArangoUnixTime.java b/src/main/java/com/arangodb/entity/ArangoUnixTime.java deleted file mode 100644 index 9446f631c..000000000 --- a/src/main/java/com/arangodb/entity/ArangoUnixTime.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright (C) 2012 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.entity; - -/** - * An entity representing the arango server time - * - * @author tamtam180 - kirscheless at gmail.com - * - */ -public class ArangoUnixTime extends BaseEntity { - - /** - * the unix timestamp as double - */ - double time; - - /** - * the unix timestamp as integer - */ - int second; - - /** - * the microseconds part of the unix timestamp - */ - int microsecond; - - public long getTimeMillis() { - return 1000L * second + (microsecond/1000); - } - - public double getTime() { - return time; - } - public int getSecond() { - return second; - } - public int getMicrosecond() { - return microsecond; - } - public void setTime(double time) { - this.time = time; - } - public void setSecond(int second) { - this.second = second; - } - public void setMicrosecond(int microsecond) { - this.microsecond = microsecond; - } - -} diff --git a/src/main/java/com/arangodb/entity/ArangoVersion.java b/src/main/java/com/arangodb/entity/ArangoVersion.java deleted file mode 100644 index e1a7c9f9c..000000000 --- a/src/main/java/com/arangodb/entity/ArangoVersion.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright (C) 2012 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.entity; - - - -/** - * - * An entity representing the ArangoDB version - * - * @author tamtam180 - kirscheless at gmail.com - * - */ -public class ArangoVersion extends BaseEntity { - - /** - * Name of the server - */ - String server; - - /** - * The current version - */ - String version; - - public String getServer() { - return server; - } - public String getVersion() { - return version; - } - public void setServer(String server) { - this.server = server; - } - public void setVersion(String version) { - this.version = version; - } - -} diff --git a/src/main/java/com/arangodb/entity/BaseDocument.java b/src/main/java/com/arangodb/entity/BaseDocument.java index 300e6bc3a..64c78c7ab 100644 --- a/src/main/java/com/arangodb/entity/BaseDocument.java +++ b/src/main/java/com/arangodb/entity/BaseDocument.java @@ -1,186 +1,183 @@ -package com.arangodb.entity; - -import java.util.HashMap; -import java.util.Map; - -import com.google.gson.annotations.SerializedName; - -/** - * Created by gschwab on 1/14/15. - */ -public class BaseDocument extends BaseEntity implements DocumentHolder { - - public static final String REV = "_rev"; - - public static final String KEY = "_key"; - - public static final String ID = "_id"; - - public static final String FROM = "_from"; - - public static final String TO = "_to"; - - /** - * the documents revision number - */ - @SerializedName(REV) - String documentRevision; - - /** - * the document handle - */ - @SerializedName(ID) - String documentHandle; - - /** - * the document key - */ - @SerializedName(KEY) - String documentKey; - - /** - * the map containing the key value pairs - */ - Map properties = new HashMap(); - - /** - * create an empty BaseDocument - */ - public BaseDocument() { - this.init(); - } - - /** - * create an empty BaseDocument with a given key - * - * @param documentKey - * the unique key of the document - */ - public BaseDocument(final String documentKey) { - this.init(); - this.documentKey = documentKey; - } - - /** - * create an BaseDocument with given attributes - * - * @param properties - * the attributes (key/value) of the document to be created - */ - public BaseDocument(final Map properties) { - this(null, properties); - } - - /** - * create an BaseDocument with given key and attributes - * - * @param documentKey - * the unique key of the document - * @param properties - * the attributes (key/value) of the document to be created - */ - public BaseDocument(final String documentKey, final Map properties) { - this.init(); - if (documentKey != null) { - this.documentKey = documentKey; - } - if (properties.containsKey(REV)) { - this.documentRevision = (String) properties.get(REV); - properties.remove(REV); - } - if (properties.containsKey(KEY)) { - if (documentKey == null) { - this.documentKey = (String) properties.get(KEY); - } - properties.remove(KEY); - } - this.properties = properties; - } - - private void init() { - // this.properties = new HashMap(); - } - - @Override - public String getDocumentRevision() { - return this.documentRevision; - } - - @Override - public String getDocumentHandle() { - return this.documentHandle; - } - - @Override - public String getDocumentKey() { - return this.documentKey; - } - - @Override - public void setDocumentRevision(final String documentRevision) { - this.documentRevision = documentRevision; - } - - @Override - public void setDocumentHandle(final String documentHandle) { - this.documentHandle = documentHandle; - } - - @Override - public void setDocumentKey(final String documentKey) { - this.documentKey = documentKey; - } - - public Map getProperties() { - return properties; - } - - public void setProperties(final Map properties) { - this.properties = properties; - } - - /** - * add an attribute to the document. If the key already exists, the value of - * the attribute will be replaced, - * - * @param key - * the key of the attribute - * @param value - * the value of the attribute - */ - public void addAttribute(final String key, final Object value) { - this.properties.put(key, value); - } - - /** - * update the value of the attribute with the given key - * - * @param key - * the key of the attribute - * @param value - * the value of the attribute ti replace the old value - */ - public void updateAttribute(final String key, final Object value) { - if (this.properties.containsKey(key)) { - this.properties.put(key, value); - } - } - - /** - * get a single attribute of the document - * - * @param key - * the key of the attribute - * @return value of the attribute key - */ - public Object getAttribute(final String key) { - return this.properties.get(key); - } - - @Override - public String toString() { - return "BaseDocument [documentRevision=" + documentRevision + ", documentHandle=" + documentHandle - + ", documentKey=" + documentKey + ", properties=" + properties + "]"; - } - -} +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.entity; + +import java.io.Serializable; +import java.util.HashMap; +import java.util.Map; + +import com.arangodb.entity.DocumentField.Type; + +/** + * @author Mark - mark at arangodb.com + * + */ +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 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() { + final StringBuilder sb = new StringBuilder(); + sb.append("BaseDocument [documentRevision="); + sb.append(revision); + sb.append(", documentHandle="); + sb.append(id); + sb.append(", documentKey="); + sb.append(key); + sb.append(", properties="); + sb.append(properties); + sb.append("]"); + return sb.toString(); + } + + @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) { + if (other.revision != null) { + return false; + } + } else if (!revision.equals(other.revision)) { + return false; + } + return true; + } + +} diff --git a/src/main/java/com/arangodb/entity/BaseEdgeDocument.java b/src/main/java/com/arangodb/entity/BaseEdgeDocument.java new file mode 100644 index 000000000..0bf4b4f01 --- /dev/null +++ b/src/main/java/com/arangodb/entity/BaseEdgeDocument.java @@ -0,0 +1,135 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.entity; + +import java.util.Map; + +import com.arangodb.entity.DocumentField.Type; + +/** + * @author Mark - mark at arangodb.com + * + */ +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 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() { + final StringBuilder sb = new StringBuilder(); + sb.append("BaseDocument [documentRevision="); + sb.append(revision); + sb.append(", documentHandle="); + sb.append(id); + sb.append(", documentKey="); + sb.append(key); + sb.append(", from="); + sb.append(from); + sb.append(", to="); + sb.append(to); + sb.append(", properties="); + sb.append(properties); + sb.append("]"); + return sb.toString(); + } + + @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) { + if (other.to != null) { + return false; + } + } else if (!to.equals(other.to)) { + return false; + } + return true; + } + +} diff --git a/src/main/java/com/arangodb/entity/BaseEntity.java b/src/main/java/com/arangodb/entity/BaseEntity.java deleted file mode 100644 index 7aecd17eb..000000000 --- a/src/main/java/com/arangodb/entity/BaseEntity.java +++ /dev/null @@ -1,160 +0,0 @@ -/* - * Copyright (C) 2012 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.entity; - -import java.io.Serializable; - -import com.arangodb.annotations.Exclude; - -/** - * @author tamtam180 - kirscheless at gmail.com - * - */ -public abstract class BaseEntity implements Serializable { - - /** - * If true an error occurred while creating this entity - */ - @Exclude(deserialize = false) - boolean error; - - /** - * The http response code of the response - */ - @Exclude(deserialize = false) - int code; - - /** - * The Arango error number of the error - */ - @Exclude(deserialize = false) - int errorNumber; - - /** - * If an error occurred this is the error message - */ - @Exclude(deserialize = false) - String errorMessage; - - /** - * The http status code of the response - */ - @Exclude(deserialize = false) - int statusCode; - - /** - * The check sum of the requested resource - */ - @Exclude(deserialize = false) - String etag; - - /** - * The requestId, this attribute is only used for batch requests. - */ - @Exclude(deserialize = false) - String requestId; - - /** - * If the resource has been modified it returns true - * - * @return boolean - */ - public boolean isNotModified() { - return statusCode == 304; - } - - /** - * If the request is unauthorized this returns true - * - * @return boolean - */ - public boolean isUnauthorized() { - return statusCode == 401; - } - - /** - * If this is the response of a batch request it returns true - * - * @return boolean - */ - public boolean isBatchResponseEntity() { - return statusCode == 206; - } - - public boolean isError() { - return error; - } - - public void setError(final boolean error) { - this.error = error; - } - - public int getCode() { - return code; - } - - public int getErrorNumber() { - return errorNumber; - } - - public String getErrorMessage() { - return errorMessage; - } - - public void setCode(final int code) { - this.code = code; - } - - public void setErrorNumber(final int errorNumber) { - this.errorNumber = errorNumber; - } - - public void setErrorMessage(final String errorMessage) { - this.errorMessage = errorMessage; - } - - public String getEtag() { - return etag; - } - - public void setEtag(final String etag) { - this.etag = etag; - } - - public int getStatusCode() { - return statusCode; - } - - public void setStatusCode(final int statusCode) { - this.statusCode = statusCode; - } - - public String getRequestId() { - return requestId; - } - - public void setRequestId(final String requestId) { - this.requestId = requestId; - } - - @Override - public String toString() { - return "BaseEntity [error=" + error + ", code=" + code + ", errorNumber=" + errorNumber + ", errorMessage=" - + errorMessage + ", statusCode=" + statusCode + ", etag=" + etag + ", requestId=" + requestId + "]"; - } - -} diff --git a/src/main/java/com/arangodb/entity/BaseMapEntity.java b/src/main/java/com/arangodb/entity/BaseMapEntity.java deleted file mode 100644 index b978ae0eb..000000000 --- a/src/main/java/com/arangodb/entity/BaseMapEntity.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Copyright (C) 2012 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.entity; - -import java.util.Collection; -import java.util.Map; -import java.util.Set; -import java.util.TreeMap; - -/** - * - * Abstract base class for map results - * - * @author tamtam180 - kirscheless at gmail.com - * - */ -public abstract class BaseMapEntity extends BaseEntity implements Map { - - private final TreeMap innerMap = new TreeMap(); - - @Override - public int size() { - return innerMap.size(); - } - - @Override - public boolean isEmpty() { - return innerMap.isEmpty(); - } - - @Override - public boolean containsKey(Object key) { - return innerMap.containsKey(key); - } - - @Override - public boolean containsValue(Object value) { - return innerMap.containsValue(value); - } - - @Override - public V get(Object key) { - return innerMap.get(key); - } - - @Override - public V put(K key, V value) { - return innerMap.put(key, value); - } - - @Override - public V remove(Object key) { - return innerMap.remove(key); - } - - @Override - public void putAll(Map t) { - innerMap.putAll(t); - } - - @Override - public void clear() { - innerMap.clear(); - } - - @Override - public Set keySet() { - return innerMap.keySet(); - } - - @Override - public Collection values() { - return innerMap.values(); - } - - @Override - public Set> entrySet() { - return innerMap.entrySet(); - } - -} diff --git a/src/main/java/com/arangodb/entity/BatchResponseEntity.java b/src/main/java/com/arangodb/entity/BatchResponseEntity.java deleted file mode 100644 index a2110f6eb..000000000 --- a/src/main/java/com/arangodb/entity/BatchResponseEntity.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright (C) 2012 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.entity; - -import com.arangodb.http.HttpResponseEntity; -import com.arangodb.http.InvocationObject; - -/** - * This entity is a representation of the result of a batch part - * - * @author tamtam180 - kirscheless at gmail.com - * - */ -public class BatchResponseEntity extends BaseEntity { - - /** - * The context of the function call, this is used to to process the server - * response to an api entity. - */ - InvocationObject invocationObject; - - /** - * The http response of the batch part. - */ - public HttpResponseEntity httpResponseEntity; - - public BatchResponseEntity(InvocationObject invocationObject) { - this.invocationObject = invocationObject; - this.httpResponseEntity = new HttpResponseEntity(); - } - - public InvocationObject getInvocationObject() { - - return invocationObject; - } - - public void setInvocationObject(InvocationObject invocationObject) { - this.invocationObject = invocationObject; - } - - public HttpResponseEntity getHttpResponseEntity() { - return httpResponseEntity; - } - - public void setHttpResponseEntity(HttpResponseEntity httpResponseEntity) { - this.httpResponseEntity = httpResponseEntity; - } - -} diff --git a/src/main/java/com/arangodb/entity/BatchResponseListEntity.java b/src/main/java/com/arangodb/entity/BatchResponseListEntity.java deleted file mode 100644 index fcbbaf181..000000000 --- a/src/main/java/com/arangodb/entity/BatchResponseListEntity.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright (C) 2012 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.entity; - -import java.util.List; - -import com.arangodb.ArangoException; - -/** - * A representation of the complete result of a batch request. - * - * @author tamtam180 - kirscheless at gmail.com - * - */ -public class BatchResponseListEntity extends BaseEntity { - - /** - * A list of BatchResponseEntities, each one representing a single batch - * part of a batch request. - */ - List batchResponseEntities; - - public List getBatchResponseEntities() { - return batchResponseEntities; - } - - public void setBatchResponseEntities(List batchResponseEntities) { - this.batchResponseEntities = batchResponseEntities; - } - - public BatchResponseEntity getResponseFromRequestId(String requestId) throws ArangoException { - for (BatchResponseEntity bpe : this.batchResponseEntities) { - if (bpe.getRequestId().equals(requestId)) { - return bpe; - } - } - throw new ArangoException("RequestId not found in batch."); - - } - -} diff --git a/src/main/java/com/arangodb/entity/CollectionEntity.java b/src/main/java/com/arangodb/entity/CollectionEntity.java index 7dc255b24..2cb13c5de 100644 --- a/src/main/java/com/arangodb/entity/CollectionEntity.java +++ b/src/main/java/com/arangodb/entity/CollectionEntity.java @@ -1,450 +1,70 @@ -/* - * Copyright (C) 2012 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.entity; - -import java.io.Serializable; - -/** - * A representation of an ArangoDB collection - * - * @author tamtam180 - kirscheless at gmail.com - * - */ -public class CollectionEntity extends BaseEntity { - - /** - * The collections name - */ - String name; - - /** - * The unique id of the collection - */ - long id; - - /** - * The collections type, either EDGE or DOCUMENT - */ - CollectionType type; - - /** - * The state of the collection - */ - CollectionStatus status; - - /** - * If true each write operation is synchronised to disk before the server - * sends a response - */ - Boolean waitForSync; - - /** - * If true the collection is a system collection - */ - Boolean isSystem; - - /** - * If true then the collection data will be kept in memory only and ArangoDB - * will not write or sync the data to disk. - */ - Boolean isVolatile; - - /** - * The maximal size setting for journals / datafiles. - */ - long journalSize; - - /** - * The amount of documents in the collection - */ - long count; - - /** - * The collection figures - * - * @see com.arangodb.entity.CollectionEntity.Figures - * @see com.arangodb.ArangoDriver#getCollectionFigures(long) - * @see com.arangodb.ArangoDriver#getCollectionFigures(String) - */ - Figures figures; - - /** - * The collection key options - * - * @see com.arangodb.entity.CollectionKeyOption - */ - CollectionKeyOption keyOptions; - - /** - * The checksum of the collection - * - * @see com.arangodb.ArangoDriver#getCollectionChecksum(String, Boolean, - * Boolean) - */ - long checksum; - - /** - * Whether or not the collection will be compacted. - */ - Boolean doCompact; - - public String getName() { - return name; - } - - public long getId() { - return id; - } - - public CollectionType getType() { - return type; - } - - public CollectionStatus getStatus() { - return status; - } - - public long getChecksum() { - return checksum; - } - - public void setIsSystem(final Boolean isSystem) { - this.isSystem = isSystem; - } - - public void setIsVolatile(final Boolean isVolatile) { - this.isVolatile = isVolatile; - } - - public void setChecksum(final long checksum) { - this.checksum = checksum; - } - - public Boolean getWaitForSync() { - return waitForSync; - } - - public Boolean getIsSystem() { - return isSystem; - } - - public Boolean getIsVolatile() { - return isVolatile; - } - - public long getJournalSize() { - return journalSize; - } - - public long getCount() { - return count; - } - - public Figures getFigures() { - return figures; - } - - public CollectionKeyOption getKeyOptions() { - return keyOptions; - } - - public void setName(final String name) { - this.name = name; - } - - public void setId(final long id) { - this.id = id; - } - - public void setType(final CollectionType type) { - this.type = type; - } - - public void setStatus(final CollectionStatus status) { - this.status = status; - } - - public void setWaitForSync(final Boolean waitForSync) { - this.waitForSync = waitForSync; - } - - public void setSystem(final Boolean isSystem) { - this.isSystem = isSystem; - } - - public void setVolatile(final Boolean isVolatile) { - this.isVolatile = isVolatile; - } - - public void setJournalSize(final long journalSize) { - this.journalSize = journalSize; - } - - public void setCount(final long count) { - this.count = count; - } - - public void setFigures(final Figures figures) { - this.figures = figures; - } - - public void setKeyOptions(final CollectionKeyOption keyOptions) { - this.keyOptions = keyOptions; - } - - public Boolean getDoCompact() { - return doCompact; - } - - public void setDoCompact(final Boolean doCompact) { - this.doCompact = doCompact; - } - - /** - * additional statistical information about the collection. - */ - public static class Figures implements Serializable { - - /** - * The number of curretly active documents in all datafiles and journals - * of the collection. Documents that are contained in the write-ahead - * log only are not reported in this figure. - */ - long aliveCount; - - /** - * The total size in bytes used by all active documents of the - * collection. Documents that are contained in the write-ahead log only - * are not reported in this figure. - */ - long aliveSize; - - /** - * The number of dead documents. This includes document versions that - * have been deleted or replaced by a newer version. Documents deleted - * or replaced that are contained the write-ahead log only are not - * reported in this figure. - */ - long deadCount; - - /** - * The total size in bytes used by all dead documents. - */ - long deadSize; - - /** - * The total number of deletion markers. Deletion markers only contained - * in the write-ahead log are not reporting in this figure. - */ - long deadDeletion; - - /** - * The number of datafiles. - */ - long datafileCount; - - /** - * The total filesize of datafiles (in bytes). - */ - long datafileFileSize; - - /** - * The number of journal files. - */ - long journalsCount; - - /** - * The total filesize of all journal files (in bytes). - */ - long journalsFileSize; - - /** - * The number of compactor files. - */ - long compactorsCount; - - /** - * The total filesize of all compactor files (in bytes). - */ - long compactorsFileSize; - - /** - * The total number of indexes defined for the collection, including the - * pre-defined indexes (e.g. primary index). - */ - long indexesCount; - - /** - * The total memory allocated for indexes in bytes. - */ - long indexesSize; - - /** - * The tick of the last marker that was stored in a journal of the - * collection. This might be 0 if the collection does not yet have a - * journal. - */ - long lastTick; - - /** - * The number of markers in the write-ahead log for this collection that - * have not been transferred to journals or datafiles. - */ - long uncollectedLogfileEntries; - - public long getAliveCount() { - return aliveCount; - } - - public long getAliveSize() { - return aliveSize; - } - - public long getDeadCount() { - return deadCount; - } - - public long getDeadSize() { - return deadSize; - } - - public long getDeadDeletion() { - return deadDeletion; - } - - public long getDatafileCount() { - return datafileCount; - } - - public long getDatafileFileSize() { - return datafileFileSize; - } - - public long getJournalsCount() { - return journalsCount; - } - - public long getJournalsFileSize() { - return journalsFileSize; - } - - public long getCompactorsCount() { - return compactorsCount; - } - - public long getCompactorsFileSize() { - return compactorsFileSize; - } - - public void setAliveCount(final long aliveCount) { - this.aliveCount = aliveCount; - } - - public void setAliveSize(final long aliveSize) { - this.aliveSize = aliveSize; - } - - public void setDeadCount(final long deadCount) { - this.deadCount = deadCount; - } - - public void setDeadSize(final long deadSize) { - this.deadSize = deadSize; - } - - public void setDeadDeletion(final long deadDeletion) { - this.deadDeletion = deadDeletion; - } - - public void setDatafileCount(final long datafileCount) { - this.datafileCount = datafileCount; - } - - public void setDatafileFileSize(final long datafileFileSize) { - this.datafileFileSize = datafileFileSize; - } - - public void setJournalsCount(final long journalsCount) { - this.journalsCount = journalsCount; - } - - public void setJournalsFileSize(final long journalsFileSize) { - this.journalsFileSize = journalsFileSize; - } - - public void setCompactorsCount(final long compactorsCount) { - this.compactorsCount = compactorsCount; - } - - public void setCompactorsFileSize(final long compactorsFileSize) { - this.compactorsFileSize = compactorsFileSize; - } - - public long getIndexesCount() { - return indexesCount; - } - - public void setIndexesCount(final long indexesCount) { - this.indexesCount = indexesCount; - } - - public long getIndexesSize() { - return indexesSize; - } - - public void setIndexesSize(final long indexesSize) { - this.indexesSize = indexesSize; - } - - public long getLastTick() { - return lastTick; - } - - public void setLastTick(final long lastTick) { - this.lastTick = lastTick; - } - - public long getUncollectedLogfileEntries() { - return uncollectedLogfileEntries; - } - - public void setUncollectedLogfileEntries(final long uncollectedLogfileEntries) { - this.uncollectedLogfileEntries = uncollectedLogfileEntries; - } - - @Override - public String toString() { - return "Figures [aliveCount=" + aliveCount + ", aliveSize=" + aliveSize + ", deadCount=" + deadCount - + ", deadSize=" + deadSize + ", deadDeletion=" + deadDeletion + ", datafileCount=" + datafileCount - + ", datafileFileSize=" + datafileFileSize + ", journalsCount=" + journalsCount - + ", journalsFileSize=" + journalsFileSize + ", compactorsCount=" + compactorsCount - + ", compactorsFileSize=" + compactorsFileSize + ", indexesCount=" + indexesCount + ", indexesSize=" - + indexesSize + ", lastTick=" + lastTick + ", uncollectedLogfileEntries=" - + uncollectedLogfileEntries + "]"; - } - - } - - @Override - public String toString() { - return "CollectionEntity [name=" + name + ", id=" + id + ", type=" + type + ", status=" + status - + ", waitForSync=" + waitForSync + ", isSystem=" + isSystem + ", isVolatile=" + isVolatile - + ", journalSize=" + journalSize + ", count=" + count + ", figures=" + figures + ", keyOptions=" - + keyOptions + ", checksum=" + checksum + ", doCompact=" + doCompact + "]"; - } - -} +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.entity; + +/** + * @author Mark - mark at arangodb.com + * + * @see API Documentation + */ +public class CollectionEntity { + + 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 String getId() { + return id; + } + + public String getName() { + return name; + } + + public Boolean getWaitForSync() { + return waitForSync; + } + + public Boolean getIsVolatile() { + return isVolatile; + } + + public Boolean getIsSystem() { + return isSystem; + } + + public CollectionStatus getStatus() { + return status; + } + + public CollectionType getType() { + return type; + } + +} diff --git a/src/main/java/com/arangodb/entity/CollectionKeyOption.java b/src/main/java/com/arangodb/entity/CollectionKeyOption.java deleted file mode 100644 index 9cb7727cf..000000000 --- a/src/main/java/com/arangodb/entity/CollectionKeyOption.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright (C) 2012,2013 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.entity; - -import java.io.Serializable; - -/** - * - * additional options for key generation. - * - * @author tamtam180 - kirscheless at gmail.com - * - */ -public class CollectionKeyOption implements Serializable { - - /** - * specifies the type of the key generator. The currently available generators are traditional and autoincrement. - */ - String type; - - /** - * 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. - */ - boolean allowUserKeys; - - /** - * increment value for autoincrement key generator. Not used for other key generator types. - */ - long increment; - - /** - * initial offset value for autoincrement key generator. Not used for other key generator types. - */ - long offset; - - public static CollectionKeyOption createIncrementOption(boolean allowUserKeys, long increment, long offset) { - CollectionKeyOption option = new CollectionKeyOption(); - option.setType("autoincrement"); - option.setAllowUserKeys(allowUserKeys); - option.setIncrement(increment); - option.setOffset(offset); - return option; - } - - public String getType() { - return type; - } - public boolean isAllowUserKeys() { - return allowUserKeys; - } - public long getIncrement() { - return increment; - } - public long getOffset() { - return offset; - } - public void setType(String type) { - this.type = type; - } - public void setAllowUserKeys(boolean allowUserKeys) { - this.allowUserKeys = allowUserKeys; - } - public void setIncrement(long increment) { - this.increment = increment; - } - public void setOffset(long offset) { - this.offset = offset; - } - -} diff --git a/src/main/java/com/arangodb/entity/CollectionOptions.java b/src/main/java/com/arangodb/entity/CollectionOptions.java deleted file mode 100644 index bdfc13151..000000000 --- a/src/main/java/com/arangodb/entity/CollectionOptions.java +++ /dev/null @@ -1,155 +0,0 @@ -package com.arangodb.entity; - -import java.util.List; - -/** - * - * Convenience object for collection creation. - * - * @see com.arangodb.entity.CollectionEntity - * - * @author Florian Bartels - * - */ -public class CollectionOptions { - - /** - * If true each write operation is synchronised to disk before the server - * sends a response - */ - private Boolean waitForSync; - - /** - * Whether or not the collection will be compacted. - */ - private Boolean doCompact; - - /** - * The maximal size setting for journals / datafiles. - */ - private Integer journalSize; - - /** - * If true the collection is a system collection - */ - private Boolean isSystem; - - /** - * If true then the collection data will be kept in memory only and ArangoDB - * will not write or sync the data to disk. - */ - private Boolean isVolatile; - - /** - * The collections type, either EDGE or DOCUMENT - */ - private CollectionType type; - - /** - * The collection key options - * - * @see com.arangodb.entity.CollectionKeyOption - */ - private CollectionKeyOption keyOptions; - - /** - * in a cluster, this value determines the number of shards to create for - * the collection. In a single server setup, this option is meaningless. - */ - private int numberOfShards; - - /** - * 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. - */ - private List shardKeys; - - public CollectionOptions() { - // do nothing here - } - - public Boolean getWaitForSync() { - return waitForSync; - } - - public CollectionOptions setWaitForSync(Boolean waitForSync) { - this.waitForSync = waitForSync; - return this; - } - - public Boolean getDoCompact() { - return doCompact; - } - - public CollectionOptions setDoCompact(Boolean doCompact) { - this.doCompact = doCompact; - return this; - } - - public Integer getJournalSize() { - return journalSize; - } - - public CollectionOptions setJournalSize(Integer journalSize) { - this.journalSize = journalSize; - return this; - } - - public Boolean getIsSystem() { - return isSystem; - } - - public CollectionOptions setIsSystem(Boolean isSystem) { - this.isSystem = isSystem; - return this; - } - - public Boolean getIsVolatile() { - return isVolatile; - } - - public CollectionOptions setIsVolatile(Boolean isVolatile) { - this.isVolatile = isVolatile; - return this; - } - - public CollectionType getType() { - return type; - } - - public CollectionOptions setType(CollectionType type) { - this.type = type; - return this; - } - - public CollectionKeyOption getKeyOptions() { - return keyOptions; - } - - public CollectionOptions setKeyOptions(CollectionKeyOption keyOptions) { - this.keyOptions = keyOptions; - return this; - } - - public int getNumberOfShards() { - return numberOfShards; - } - - public CollectionOptions setNumberOfShards(int numberOfShards) { - this.numberOfShards = numberOfShards; - return this; - } - - public List getShardKeys() { - return shardKeys; - } - - public CollectionOptions setShardKeys(List shardKeys) { - this.shardKeys = shardKeys; - return this; - } - -} diff --git a/src/main/java/com/arangodb/entity/CollectionPropertiesEntity.java b/src/main/java/com/arangodb/entity/CollectionPropertiesEntity.java new file mode 100644 index 000000000..a57f5bc1b --- /dev/null +++ b/src/main/java/com/arangodb/entity/CollectionPropertiesEntity.java @@ -0,0 +1,108 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.entity; + +import java.util.Collection; + +/** + * @author Mark - mark at arangodb.com + * + * @see API + * 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; + + public CollectionPropertiesEntity() { + super(); + } + + 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 contains the names of document attributes that are used to determine the target shard for documents. Only + * in a cluster setup + */ + public Integer getNumberOfShards() { + return numberOfShards; + } + + public void setNumberOfShards(final Integer numberOfShards) { + this.numberOfShards = numberOfShards; + } + + /** + * @return the number of shards of the collection. Only in a cluster setup. + */ + public Collection getShardKeys() { + return shardKeys; + } + + public void setShardKeys(final Collection shardKeys) { + this.shardKeys = shardKeys; + } + +} diff --git a/src/main/java/com/arangodb/entity/CollectionRevisionEntity.java b/src/main/java/com/arangodb/entity/CollectionRevisionEntity.java new file mode 100644 index 000000000..0a090bea5 --- /dev/null +++ b/src/main/java/com/arangodb/entity/CollectionRevisionEntity.java @@ -0,0 +1,37 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.entity; + +/** + * @author Mark - mark at arangodb.com + * + * @see API + * Documentation + */ +public class CollectionRevisionEntity extends CollectionEntity { + + private String 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 36d25a68d..cdaf3f985 100644 --- a/src/main/java/com/arangodb/entity/CollectionStatus.java +++ b/src/main/java/com/arangodb/entity/CollectionStatus.java @@ -1,78 +1,50 @@ -/* - * Copyright (C) 2012 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.entity; - -import java.io.Serializable; -import java.util.TreeMap; - -/** - * Enumeration describing the collection state - * - * @author tamtam180 - kirscheless at gmail.com - * - */ -public enum CollectionStatus { - - /** - * initial state of a new collection - */ - NEW_BORN_COLLECTION(1), - - /** - * collection is not in memory - */ - UNLOADED(2), - - /** - * collection is in memory - */ - LOADED(3), - - /** - * temporary state of a collection in the process of being unloaded - */ - IN_THE_PROCESS_OF_BEING_UNLOADED(4), - - /** - * deleted state - */ - DELETED(5); - - private static class Holder implements Serializable { - private static final long serialVersionUID = -7016368432042468015L; - private static TreeMap lookupMap = new TreeMap(); - - private Holder() { - // do nothing here - } - } - - private final int status; - - private CollectionStatus(int status) { - this.status = status; - Holder.lookupMap.put(status, this); - } - - public int status() { - return status; - } - - public static CollectionStatus valueOf(int status) { - return Holder.lookupMap.get(status); - } -} +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.entity; + +/** + * @author Mark - mark at arangodb.com + * + */ +public enum CollectionStatus { + + NEW_BORN_COLLECTION(1), UNLOADED(2), LOADED(3), IN_THE_PROCESS_OF_BEING_UNLOADED(4), DELETED(5); + + private final int status; + + private CollectionStatus(final int status) { + this.status = 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; + } + +} diff --git a/src/main/java/com/arangodb/entity/CollectionStatusTypeAdapter.java b/src/main/java/com/arangodb/entity/CollectionStatusTypeAdapter.java deleted file mode 100644 index 8d9635587..000000000 --- a/src/main/java/com/arangodb/entity/CollectionStatusTypeAdapter.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright (C) 2012 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.entity; - -import java.io.IOException; - -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonToken; -import com.google.gson.stream.JsonWriter; - -/** - * - * Used only internally for entity deserialisation - * - * @author tamtam180 - kirscheless at gmail.com - * - */ -public class CollectionStatusTypeAdapter extends TypeAdapter { - - @Override - public void write(JsonWriter out, CollectionStatus value) throws IOException { - out.value(value.status()); - } - - @Override - public CollectionStatus read(JsonReader in) throws IOException { - if (in.peek() == JsonToken.NULL) { - in.nextNull(); - return null; - } - - return CollectionStatus.valueOf(in.nextInt()); - } - -} diff --git a/src/main/java/com/arangodb/entity/CollectionType.java b/src/main/java/com/arangodb/entity/CollectionType.java index 368c65be6..a5aba4c56 100644 --- a/src/main/java/com/arangodb/entity/CollectionType.java +++ b/src/main/java/com/arangodb/entity/CollectionType.java @@ -1,58 +1,49 @@ -/* - * Copyright (C) 2012 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.entity; - -/** - * Enumeration class for collection types. - * - * @author tamtam180 - kirscheless at gmail.com - * - */ -public enum CollectionType { - /** - * Document collection type - */ - DOCUMENT(2), - - /** - * Edge collection type, used for graphs - */ - EDGE(3); - - private final int type; - - private CollectionType(int type) { - this.type = type; - } - - public int getType() { - return type; - } - - public static CollectionType valueOf(int type) { - CollectionType result = null; - - if (type == 2) { - result = DOCUMENT; - } - else if (type == 3) { - result = EDGE; - } - - return result; - } -} +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.entity; + +/** + * @author Mark - mark at arangodb.com + * + */ +public enum CollectionType { + + DOCUMENT(2), EDGES(3); + + private final int type; + + private CollectionType(final int type) { + this.type = 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; + } +} diff --git a/src/main/java/com/arangodb/entity/CollectionsEntity.java b/src/main/java/com/arangodb/entity/CollectionsEntity.java deleted file mode 100644 index 4cc99f8ff..000000000 --- a/src/main/java/com/arangodb/entity/CollectionsEntity.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright (C) 2012 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.entity; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import com.arangodb.util.CollectionUtils; - -/** - * A entity representing a list of ArangoDB collections - * - * @author tamtam180 - kirscheless at gmail.com - * - */ -public class CollectionsEntity extends BaseEntity { - - /** - * The list of collections - */ - private List collections; - - public List getCollections() { - return collections; - } - - public Map getNames() { - Map names = new HashMap(); - - if (CollectionUtils.isNotEmpty(collections)) { - for (CollectionEntity collectionEntity : collections) { - names.put(collectionEntity.getName(), collectionEntity); - } - } - - return names; - } - - public void setCollections(List collections) { - this.collections = collections; - } - - @Override - public String toString() { - return "CollectionsEntity [collections=" + collections + "]"; - } - -} diff --git a/src/main/java/com/arangodb/entity/CursorEntity.java b/src/main/java/com/arangodb/entity/CursorEntity.java index ddc672579..f4d419235 100644 --- a/src/main/java/com/arangodb/entity/CursorEntity.java +++ b/src/main/java/com/arangodb/entity/CursorEntity.java @@ -1,222 +1,154 @@ -/* - * Copyright (C) 2012 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.entity; - -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import com.arangodb.NonUniqueResultException; -import com.arangodb.util.CollectionUtils; - -/** - * Cursor entity that represents the result of a AQL query. - * - * @author tamtam180 - kirscheless at gmail.com - * @author mrbatista - * - */ -public class CursorEntity extends BaseEntity implements Iterable { - - /** - * True if the cursor has more results. - */ - boolean hasMore; - - /** - * The amount of results in the cursor - */ - int count = -1; - - /** - * The number of results before the final LIMIT - */ - int fullCount = -1; - - /** - * The cursor id - */ - long cursorId = -1; - - /** - * 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. (since ArangoDB 2.7) - */ - boolean cached = false; - - /** - * A list of bind variables returned by the query - */ - List bindVars; - - /** - * A list of extra data returned by the query - */ - Map extra; - - /** - * A list of objects containing the results - */ - List results; - - /** - * A list of warnings - */ - List warnings; - - @Override - public Iterator iterator() { - return CollectionUtils.safetyIterator(results); - } - - /** - * The size of the cursor results. - * - * @return int - */ - public int size() { - if (results == null) { - return 0; - } - return results.size(); - } - - /** - * Returns the cursor element at position *index* - * - * @param index - * @return Object - */ - public T get(int index) { - rangeCheck(index); - return results.get(index); - } - - private void rangeCheck(int index) { - int size = size(); - if (index < 0 || index >= size) { - throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size); - } - } - - /** - * Returns the DocumentEntity objects of this CursorDocumentEntity - * - * @return list of DocumentEntity objects - */ - public List getResults() { - return results; - } - - /** - * Return a single instance that matches the query, or null if the query - * returns no results. - * - * Throws NonUniqueResultException (RuntimeException) if there is more than - * one matching result - * - * @return the single result or null - */ - public T getUniqueResult() { - int size = size(); - if (size == 0) { - return null; - } - if (size > 1) { - throw new NonUniqueResultException(size); - } - return get(0); - } - - public boolean isHasMore() { - return hasMore; - } - - public boolean hasMore() { - return hasMore; - } - - public int getFullCount() { - return fullCount; - } - - public int getCount() { - return count; - } - - public long getCursorId() { - return cursorId; - } - - public List getBindVars() { - return bindVars; - } - - public Map getExtra() { - return extra; - } - - public void setResults(List results) { - this.results = results; - } - - public void setHasMore(boolean hasMore) { - this.hasMore = hasMore; - } - - public void setFullCount(int count) { - this.fullCount = count; - } - - public void setCount(int count) { - this.count = count; - } - - public void setCursorId(long cursorId) { - this.cursorId = cursorId; - } - - public void setBindVars(List bindVars) { - this.bindVars = bindVars; - } - - public void setExtra(Map extra) { - this.extra = extra; - } - - public boolean isCached() { - return cached; - } - - public void setCached(boolean cached) { - this.cached = cached; - } - - public List getWarnings() { - return warnings; - } - - public void setWarnings(List warnings) { - this.warnings = warnings; - } - - public boolean hasWarnings() { - return CollectionUtils.isNotEmpty(this.warnings); - } -} +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.entity; + +import java.util.Collection; + +import com.arangodb.velocypack.VPackSlice; + +/** + * @author Mark - mark at arangodb.com + * + * @see API + * Documentation + */ +public class CursorEntity { + + private String id; + private Integer count; + private Extras extra; + private Boolean cached; + private Boolean hasMore; + private VPackSlice result; + + 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 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/DatabaseEntity.java b/src/main/java/com/arangodb/entity/DatabaseEntity.java index c460e9c41..a8f579f94 100644 --- a/src/main/java/com/arangodb/entity/DatabaseEntity.java +++ b/src/main/java/com/arangodb/entity/DatabaseEntity.java @@ -1,72 +1,65 @@ -/* - * Copyright (C) 2012,2013 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.entity; - -/** - * An entity representing an ArangoDB database - * - * @author tamtam180 - kirscheless at gmail.com - * - */ -public class DatabaseEntity extends BaseEntity { - - /** - * The name of the database - */ - String name; - - /** - * The id of the database - */ - String id; - - /** - * The path of the database - */ - String path; - - /** - * If true the database is the system database - */ - boolean isSystem; - - public String getName() { - return name; - } - public String getId() { - return id; - } - public String getPath() { - return path; - } - public boolean isSystem() { - return isSystem; - } - public void setName(String name) { - this.name = name; - } - public void setId(String id) { - this.id = id; - } - public void setPath(String path) { - this.path = path; - } - public void setSystem(boolean isSystem) { - this.isSystem = isSystem; - } - -} +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.entity; + +/** + * @author Mark - mark at arangodb.com + * + * @see API + * Documentation + */ +public class DatabaseEntity { + + private String id; + private String name; + private String path; + private Boolean isSystem; + + /** + * @return the id of the database + */ + public String getId() { + return id; + } + + /** + * @return the name of the database + */ + public String getName() { + return name; + } + + /** + * @return the filesystem path of the database + */ + public String getPath() { + return path; + } + + /** + * @return whether or not the database is the _system database + */ + public Boolean getIsSystem() { + return isSystem; + } + +} diff --git a/src/main/java/com/arangodb/entity/DocumentCreateEntity.java b/src/main/java/com/arangodb/entity/DocumentCreateEntity.java new file mode 100644 index 000000000..70ff2f7a4 --- /dev/null +++ b/src/main/java/com/arangodb/entity/DocumentCreateEntity.java @@ -0,0 +1,51 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.entity; + +import com.arangodb.velocypack.annotations.Expose; + +/** + * @author Mark - mark at arangodb.com + * + * @see API + * Documentation + */ +public class DocumentCreateEntity extends DocumentEntity { + + @Expose(deserialize = false) + private T newDocument; + + public DocumentCreateEntity() { + super(); + } + + /** + * @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; + } + +} diff --git a/src/main/java/com/arangodb/entity/DocumentDeleteEntity.java b/src/main/java/com/arangodb/entity/DocumentDeleteEntity.java new file mode 100644 index 000000000..07285d450 --- /dev/null +++ b/src/main/java/com/arangodb/entity/DocumentDeleteEntity.java @@ -0,0 +1,51 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.entity; + +import com.arangodb.velocypack.annotations.Expose; + +/** + * @author Mark - mark at arangodb.com + * + * @see API + * Documentation + */ +public class DocumentDeleteEntity extends DocumentEntity { + + @Expose(deserialize = false) + private T oldDocument; + + 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; + } + + 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 1ef3f1dd8..b912eb241 100644 --- a/src/main/java/com/arangodb/entity/DocumentEntity.java +++ b/src/main/java/com/arangodb/entity/DocumentEntity.java @@ -1,95 +1,54 @@ -/* - * Copyright (C) 2012 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.entity; - -/** - * The generic document entity - * - * @author tamtam180 - kirscheless at gmail.com - * - */ -public class DocumentEntity extends BaseEntity implements DocumentHolder { - - /** - * the documents revision - */ - String documentRevision; - - /** - * the document handle - */ - String documentHandle; - - /** - * the document key - */ - String documentKey; - - /** - * The entity representation of the requested document. - */ - T entity; - - public DocumentEntity() { - // do nothing here - } - - @Override - public String getDocumentRevision() { - return documentRevision; - } - - @Override - public String getDocumentHandle() { - return documentHandle; - } - - public T getEntity() { - return entity; - } - - @Override - public void setDocumentRevision(final String documentRevision) { - this.documentRevision = documentRevision; - } - - @Override - public void setDocumentHandle(final String documentHandle) { - this.documentHandle = documentHandle; - } - - public void setEntity(final T entity) { - this.entity = entity; - } - - @Override - public String getDocumentKey() { - return documentKey; - } - - @Override - public void setDocumentKey(final String documentKey) { - this.documentKey = documentKey; - } - - @Override - public String toString() { - return "DocumentEntity [documentRevision=" + documentRevision + ", documentHandle=" + documentHandle - + ", documentKey=" + documentKey + ", entity=" + entity + "]"; - } - -} +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.entity; + +import com.arangodb.entity.DocumentField.Type; + +/** + * @author Mark - mark at arangodb.com + * + */ +public class DocumentEntity { + + @DocumentField(Type.KEY) + private String key; + @DocumentField(Type.ID) + private String id; + @DocumentField(Type.REV) + private String rev; + + public DocumentEntity() { + super(); + } + + public String getKey() { + return key; + } + + public String getId() { + return id; + } + + 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 new file mode 100644 index 000000000..4abb03a75 --- /dev/null +++ b/src/main/java/com/arangodb/entity/DocumentField.java @@ -0,0 +1,52 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.entity; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * @author Mark - mark at arangodb.com + * + */ +@Retention(RetentionPolicy.RUNTIME) +@Target({ ElementType.FIELD }) +public @interface DocumentField { + + public static enum Type { + ID("_id"), KEY("_key"), REV("_rev"), FROM("_from"), TO("_to"); + + private final String serializeName; + + private Type(final String serializeName) { + this.serializeName = serializeName; + } + + public String getSerializeName() { + return serializeName; + } + } + + Type value(); + +} diff --git a/src/main/java/com/arangodb/entity/DocumentResultEntity.java b/src/main/java/com/arangodb/entity/DocumentResultEntity.java deleted file mode 100644 index 21ac004bd..000000000 --- a/src/main/java/com/arangodb/entity/DocumentResultEntity.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright (C) 2012,2013 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.entity; - -import java.util.List; - -/** - * An entity representing a list of documents - * - * @author tamtam180 - kirscheless at gmail.com - * - */ -public class DocumentResultEntity extends BaseEntity { - - /** - * The list of generic document entities - */ - List> result; - - /** - * Returns the first document from the list - * - * @return DocumentEntity - */ - public DocumentEntity getOne() { - if (result == null || result.isEmpty()) { - return null; - } - return result.get(0); - } - - /** - * The size of the documents list - * - * @return int - */ - public int size() { - if (result == null) { - return 0; - } - return result.size(); - } - - public List> getResult() { - return result; - } - - public void setResult(List> result) { - this.result = result; - } - -} diff --git a/src/main/java/com/arangodb/entity/DocumentUpdateEntity.java b/src/main/java/com/arangodb/entity/DocumentUpdateEntity.java new file mode 100644 index 000000000..fe60e7e12 --- /dev/null +++ b/src/main/java/com/arangodb/entity/DocumentUpdateEntity.java @@ -0,0 +1,74 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.entity; + +import com.arangodb.velocypack.annotations.Expose; +import com.arangodb.velocypack.annotations.SerializedName; + +/** + * @author Mark - mark at arangodb.com + * @param + * + * @see API + * Documentation + * + */ +public class DocumentUpdateEntity extends DocumentEntity { + + @SerializedName("_oldRev") + private String oldRev; + @Expose(deserialize = false) + private T newDocument; + @Expose(deserialize = false) + private T oldDocument; + + public DocumentUpdateEntity() { + super(); + } + + 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; + } + + 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; + } + + public void setOld(final T oldDocument) { + this.oldDocument = oldDocument; + } + +} diff --git a/src/main/java/com/arangodb/entity/DocumentsEntity.java b/src/main/java/com/arangodb/entity/DocumentsEntity.java deleted file mode 100644 index 7aabae9b2..000000000 --- a/src/main/java/com/arangodb/entity/DocumentsEntity.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright (C) 2012 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.entity; - -import java.util.Iterator; -import java.util.List; - -import com.arangodb.util.CollectionUtils; - -/** - * An entity representing a list of document ids - * - * @author tamtam180 - kirscheless at gmail.com - * - */ -public class DocumentsEntity extends BaseEntity implements Iterable { - - /** - * the list of document ids - */ - List documents; - - @Override - public Iterator iterator() { - return CollectionUtils.safetyIterator(documents); - } - - public List getDocuments() { - return documents; - } - - public void setDocuments(List documents) { - this.documents = documents; - } - -} diff --git a/src/main/java/com/arangodb/entity/EdgeDefinition.java b/src/main/java/com/arangodb/entity/EdgeDefinition.java new file mode 100644 index 000000000..c7ed7674d --- /dev/null +++ b/src/main/java/com/arangodb/entity/EdgeDefinition.java @@ -0,0 +1,64 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.entity; + +import java.util.Arrays; +import java.util.Collection; + +/** + * @author Mark - mark at arangodb.com + * + * @see API Documentation + */ +public class EdgeDefinition { + + private String collection; + private Collection from; + private Collection to; + + public String getCollection() { + return collection; + } + + public EdgeDefinition collection(final String collection) { + this.collection = collection; + return this; + } + + public Collection getFrom() { + return from; + } + + public EdgeDefinition from(final String... from) { + this.from = Arrays.asList(from); + return this; + } + + public Collection getTo() { + return to; + } + + public EdgeDefinition to(final String... to) { + this.to = Arrays.asList(to); + return this; + } + +} diff --git a/src/main/java/com/arangodb/entity/EdgeDefinitionEntity.java b/src/main/java/com/arangodb/entity/EdgeDefinitionEntity.java deleted file mode 100644 index 040febd95..000000000 --- a/src/main/java/com/arangodb/entity/EdgeDefinitionEntity.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.arangodb.entity; - -import java.util.ArrayList; -import java.util.List; - -public class EdgeDefinitionEntity { - - String collection; - List from; - List to; - - public EdgeDefinitionEntity() { - this.from = new ArrayList(); - this.to = new ArrayList(); - } - - public String getCollection() { - return collection; - } - - public EdgeDefinitionEntity setCollection(String collection) { - this.collection = collection; - return this; - } - - public List getFrom() { - return from; - } - - public EdgeDefinitionEntity setFrom(List from) { - this.from = from; - return this; - } - - public List getTo() { - return to; - } - - public EdgeDefinitionEntity setTo(List to) { - this.to = to; - return this; - } -} diff --git a/src/main/java/com/arangodb/entity/EdgeDefinitionsEntity.java b/src/main/java/com/arangodb/entity/EdgeDefinitionsEntity.java deleted file mode 100644 index 639fca34b..000000000 --- a/src/main/java/com/arangodb/entity/EdgeDefinitionsEntity.java +++ /dev/null @@ -1,97 +0,0 @@ -package com.arangodb.entity; - -import java.util.ArrayList; -import java.util.List; - -public class EdgeDefinitionsEntity { - - /** - * The list of edgeDefinitions - */ - private List edgeDefinitions; - - /** - * A list of edge collections used in the edge definitions - */ - private List edgeCollections; - - public EdgeDefinitionsEntity(List edgeDefinitions) { - this.edgeDefinitions = edgeDefinitions; - this.edgeCollections = new ArrayList(); - this.evalEdgeCollections(); - } - - public EdgeDefinitionsEntity() { - this.edgeDefinitions = new ArrayList(); - this.edgeCollections = new ArrayList(); - } - - /** - * returns the number of edge definitions - * - * @return number of edge definitions - */ - public int getSize() { - return this.edgeDefinitions.size(); - } - - /** - * get all edge definitions - * - * @return a list of EdgeDefinitionEntity objects - */ - public List getEdgeDefinitions() { - return edgeDefinitions; - } - - /** - * set the edge definitions (overwrites existing edge definitions) - * - * @param edgeDefinitions - * the edge definitions to be set - */ - public void setEdgeDefinitions(List edgeDefinitions) { - this.edgeDefinitions = edgeDefinitions; - this.evalEdgeCollections(); - } - - /** - * add a single edge definition - * - * @param edgeDefinition - * the edge definition to be added - */ - public void addEdgeDefinition(EdgeDefinitionEntity edgeDefinition) { - if (!this.edgeCollections.contains(edgeDefinition.getCollection())) { - this.edgeDefinitions.add(edgeDefinition); - this.edgeCollections.add(edgeDefinition.getCollection()); - } - } - - /** - * get a single edge definition identified by its edge collection name - * - * @param collectionName - * the name of the edge collection - * @return the adjacent edgeDefinition or null, if no match - */ - public EdgeDefinitionEntity getEdgeDefinition(String collectionName) { - for (EdgeDefinitionEntity edgeDefintion : this.edgeDefinitions) { - if (edgeDefintion.getCollection().equals(collectionName)) { - return edgeDefintion; - } - } - return null; - } - - /** - * fills the list of edgeCollections - */ - private void evalEdgeCollections() { - this.edgeCollections.clear(); - for (EdgeDefinitionEntity edgeDefintion : this.edgeDefinitions) { - this.edgeCollections.add(edgeDefintion.getCollection()); - } - } - -} diff --git a/src/main/java/com/arangodb/entity/EdgeEntity.java b/src/main/java/com/arangodb/entity/EdgeEntity.java index 650ccf843..390e79234 100644 --- a/src/main/java/com/arangodb/entity/EdgeEntity.java +++ b/src/main/java/com/arangodb/entity/EdgeEntity.java @@ -1,49 +1,33 @@ -/* - * Copyright (C) 2012,2013 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.entity; - -import com.google.gson.annotations.SerializedName; - -/** - * @author tamtam180 - kirscheless at gmail.com - * @author gschwab - * - */ -public class EdgeEntity extends DocumentEntity { - - @SerializedName(BaseDocument.FROM) - String fromVertexHandle; - @SerializedName(BaseDocument.TO) - String toVertexHandle; - - public String getFromVertexHandle() { - return fromVertexHandle; - } - - public String getToVertexHandle() { - return toVertexHandle; - } - - public void setFromVertexHandle(String fromVertexHandle) { - this.fromVertexHandle = fromVertexHandle; - } - - public void setToVertexHandle(String toVertexHandle) { - this.toVertexHandle = toVertexHandle; - } - -} +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.entity; + +/** + * @author Mark - mark at arangodb.com + * + */ +public class EdgeEntity extends DocumentEntity { + + public EdgeEntity() { + super(); + } + +} diff --git a/src/main/java/com/arangodb/entity/EdgeUpdateEntity.java b/src/main/java/com/arangodb/entity/EdgeUpdateEntity.java new file mode 100644 index 000000000..b8e774b59 --- /dev/null +++ b/src/main/java/com/arangodb/entity/EdgeUpdateEntity.java @@ -0,0 +1,43 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.entity; + +import com.arangodb.velocypack.annotations.SerializedName; + +/** + * @author Mark - mark at arangodb.com + * + * @see API Documentation + */ +public class EdgeUpdateEntity extends DocumentEntity { + + @SerializedName("_oldRev") + private String oldRev; + + public EdgeUpdateEntity() { + super(); + } + + public String getOldRev() { + return oldRev; + } + +} diff --git a/src/main/java/com/arangodb/entity/Endpoint.java b/src/main/java/com/arangodb/entity/Endpoint.java deleted file mode 100644 index dccb4919a..000000000 --- a/src/main/java/com/arangodb/entity/Endpoint.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright (C) 2012,2013 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.entity; - -import java.io.Serializable; -import java.util.List; - -/** - * This entity represents an endpoint - * - * @author tamtam180 - kirscheless at gmail.com - * - */ -public class Endpoint implements Serializable { - - /** - * The endpoint address as string - */ - private String endpoint; - - /** - * The list of databases available at this endpoint as string - */ - private List databases; - - public String getEndpoint() { - return endpoint; - } - - public List getDatabases() { - return databases; - } - - public void setEndpoint(String endpoint) { - this.endpoint = endpoint; - } - - public void setDatabases(List databases) { - this.databases = databases; - } - -} diff --git a/src/main/java/com/arangodb/entity/EntityDeserializers.java b/src/main/java/com/arangodb/entity/EntityDeserializers.java deleted file mode 100644 index 042f8b717..000000000 --- a/src/main/java/com/arangodb/entity/EntityDeserializers.java +++ /dev/null @@ -1,2518 +0,0 @@ -/* - * Copyright (C) 2012 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.entity; - -import java.lang.reflect.Type; -import java.math.BigDecimal; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Date; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; -import java.util.TreeMap; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.arangodb.entity.CollectionEntity.Figures; -import com.arangodb.entity.QueryCachePropertiesEntity.CacheMode; -import com.arangodb.entity.ReplicationApplierState.LastError; -import com.arangodb.entity.ReplicationApplierState.Progress; -import com.arangodb.entity.ReplicationInventoryEntity.Collection; -import com.arangodb.entity.ReplicationInventoryEntity.CollectionParameter; -import com.arangodb.entity.ReplicationLoggerStateEntity.Client; -import com.arangodb.entity.StatisticsDescriptionEntity.Figure; -import com.arangodb.entity.StatisticsDescriptionEntity.Group; -import com.arangodb.entity.StatisticsEntity.FigureValue; -import com.arangodb.entity.marker.VertexEntity; -import com.arangodb.util.DateUtils; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonPrimitive; -import com.google.gson.reflect.TypeToken; - -/** - * Entity deserializer , internally used. - * - * @author tamtam180 - kirscheless at gmail.com - * - */ -public class EntityDeserializers { - - private static final String ADAPTIVE_POLLING = "adaptivePolling"; - - private static final String AUTO_START = "autoStart"; - - private static final String CHUNK_SIZE = "chunkSize"; - - private static final String REQUEST_TIMEOUT = "requestTimeout"; - - private static final String CONNECT_TIMEOUT = "connectTimeout"; - - private static final String MAX_CONNECT_RETRIES = "maxConnectRetries"; - - private static final String PASSWORD = "password"; - - private static final String USERNAME = "username"; - - private static final String DATABASE = "database"; - - private static final String ENDPOINT = "endpoint"; - - private static final String SERVER = "server"; - - private static final String ETAG = "etag"; - - private static final String ERROR_MESSAGE = "errorMessage"; - - private static final String ERROR_NUM = "errorNum"; - - private static final String CODE = "code"; - - private static final String ERROR = "error"; - - private static final String RESULT = "result"; - - private static final String VERSION = "version"; - - private static final String PATHS = "paths"; - - private static final String VERTICES = "vertices"; - - private static final String SIZE = "size"; - - private static final String COUNT = "count"; - - private static final String ALIVE = "alive"; - - private static final String WARNINGS = "warnings"; - - private static final String ALT_DATE_TIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"; - - private static final String DO_COMPACT = "doCompact"; - - private static final String CHECKSUM = "checksum"; - - private static final String KEY_OPTIONS = "keyOptions"; - - private static final String TYPE = "type"; - - private static final String FIGURES = "figures"; - - private static final String REVISION = "revision"; - - private static final String JOURNAL_SIZE = "journalSize"; - - private static final String IS_VOLATILE = "isVolatile"; - - private static final String IS_SYSTEM = "isSystem"; - - private static final String WAIT_FOR_SYNC = "waitForSync"; - - private static final String STATUS = "status"; - - private static final String ID = "id"; - - private static final String NAME = "name"; - - private static final String EXTRA = "extra"; - - private static final String ACTIVE = "active"; - - private static final String COLLECTIONS = "collections"; - - private static final String LAST_ERROR = "lastError"; - - private static final String LAST_AVAILABLE_CONTINUOUS_TICK = "lastAvailableContinuousTick"; - - private static final String LAST_PROCESSED_CONTINUOUS_TICK = "lastProcessedContinuousTick"; - - private static final String LAST_APPLIED_CONTINUOUS_TICK = "lastAppliedContinuousTick"; - - private static final String INDEXES = "indexes"; - - private static final String EDGES = "edges"; - - private static final String STATE = "state"; - - private static final String FILE_SIZE = "fileSize"; - - private static final String UPDATED = "updated"; - - private static final String REPLACED = "replaced"; - - private static final String DELETED = "deleted"; - - private static final String MESSAGE = "message"; - - private static final String CREATED = "created"; - private static final String ERRORS = "errors"; - private static final String EMPTY = "empty"; - private static final String IGNORED = "ignored"; - private static final String DETAILS = "details"; - - private static Logger logger = LoggerFactory.getLogger(EntityDeserializers.class); - - private static class ClassHolder { - private final Class[] clazz; - private int idx; - - ClassHolder(final Class... clazz) { - this.clazz = clazz; - this.idx = 0; - } - - public boolean isEmpty() { - return clazz == null || clazz.length == 0; - } - - public Class get() { - if (isEmpty()) { - return null; - } - return clazz[idx]; - } - - public Class next() { - if (isEmpty()) { - return null; - } - if (idx + 1 >= clazz.length) { - throw new IllegalStateException("idx max-over!! idx=" + (idx + 1)); - } - return clazz[++idx]; - } - - public boolean hasNext() { - if (isEmpty()) { - return false; - } - if (idx + 1 >= clazz.length) { - return false; - } - return true; - } - - public Class back() { - if (isEmpty()) { - return null; - } - if (idx - 1 < 0) { - throw new IllegalStateException("idx min-over!! idx=" + (idx - 1)); - } - return clazz[--idx]; - } - } - - private static ThreadLocal parameterizedBridger = new ThreadLocal(); - - private EntityDeserializers() { - // this is a helper class - } - - public static void setParameterized(final Class... clazz) { - parameterizedBridger.set(new ClassHolder(clazz)); - } - - public static void removeParameterized() { - parameterizedBridger.remove(); - } - - private static Class getParameterized() { - final ClassHolder holder = parameterizedBridger.get(); - if (holder == null) { - return null; - } - return holder.get(); - } - - private static boolean hasNextParameterized() { - final ClassHolder holder = parameterizedBridger.get(); - if (holder == null) { - return false; - } - return holder.hasNext(); - } - - private static Class nextParameterized() { - final ClassHolder holder = parameterizedBridger.get(); - if (holder == null) { - return null; - } - return holder.next(); - } - - private static T deserializeBaseParameter(final JsonObject obj, final T entity) { - if (obj.has(ERROR) && obj.getAsJsonPrimitive(ERROR).isBoolean()) { - entity.error = obj.getAsJsonPrimitive(ERROR).getAsBoolean(); - } - if (obj.has(CODE) && obj.getAsJsonPrimitive(CODE).isNumber()) { - entity.code = obj.getAsJsonPrimitive(CODE).getAsInt(); - } - if (obj.has(ERROR_NUM) && obj.getAsJsonPrimitive(ERROR_NUM).isNumber()) { - entity.errorNumber = obj.getAsJsonPrimitive(ERROR_NUM).getAsInt(); - } - if (obj.has(ERROR_MESSAGE)) { - entity.errorMessage = obj.getAsJsonPrimitive(ERROR_MESSAGE).getAsString(); - } - if (obj.has(ETAG) && obj.getAsJsonPrimitive(ERROR_NUM).isString()) { - entity.etag = obj.getAsJsonPrimitive(ETAG).getAsString(); - } - - return entity; - } - - private static T deserializeDocumentParameter(final JsonObject obj, final T entity) { - - if (obj.has("_rev")) { - entity.setDocumentRevision(obj.getAsJsonPrimitive("_rev").getAsString()); - } - if (obj.has("_id")) { - entity.setDocumentHandle(obj.getAsJsonPrimitive("_id").getAsString()); - } - if (obj.has("_key")) { - entity.setDocumentKey(obj.getAsJsonPrimitive("_key").getAsString()); - } - - return entity; - } - - public static class DefaultEntityDeserializer implements JsonDeserializer { - @Override - public DefaultEntity deserialize( - final JsonElement json, - final Type typeOfT, - final JsonDeserializationContext context) { - if (json.isJsonNull()) { - return null; - } - return deserializeBaseParameter(json.getAsJsonObject(), new DefaultEntity()); - } - } - - public static class VersionDeserializer implements JsonDeserializer { - - @Override - public ArangoVersion deserialize( - final JsonElement json, - final Type typeOfT, - final JsonDeserializationContext context) { - - if (json.isJsonNull()) { - return null; - } - - final JsonObject obj = json.getAsJsonObject(); - final ArangoVersion entity = deserializeBaseParameter(obj, new ArangoVersion()); - - if (obj.has(SERVER)) { - entity.server = obj.getAsJsonPrimitive(SERVER).getAsString(); - } - - if (obj.has(VERSION)) { - entity.version = obj.getAsJsonPrimitive(VERSION).getAsString(); - } - - return entity; - } - } - - public static class ArangoUnixTimeDeserializer implements JsonDeserializer { - @Override - public ArangoUnixTime deserialize( - final JsonElement json, - final Type typeOfT, - final JsonDeserializationContext context) { - - if (json.isJsonNull()) { - return null; - } - - final JsonObject obj = json.getAsJsonObject(); - final ArangoUnixTime entity = deserializeBaseParameter(obj, new ArangoUnixTime()); - - if (obj.has("time")) { - entity.time = obj.getAsJsonPrimitive("time").getAsDouble(); - final String time = obj.getAsJsonPrimitive("time").getAsString(); // 実際はdoubleだけど精度の問題が心配なので文字列で処理する。 - entity.second = (int) entity.time; - - final int pos = time.indexOf('.'); - entity.microsecond = (pos >= 0 && pos + 1 != time.length()) ? Integer.parseInt(time.substring(pos + 1)) - : 0; - } - - return entity; - } - } - - public static class FiguresDeserializer implements JsonDeserializer { - - @Override - public Figures deserialize( - final JsonElement json, - final Type typeOfT, - final JsonDeserializationContext context) { - - if (json.isJsonNull()) { - return null; - } - - final JsonObject obj = json.getAsJsonObject(); - final Figures entity = new Figures(); - - if (obj.has(ALIVE)) { - final JsonObject alive = obj.getAsJsonObject(ALIVE); - entity.aliveCount = alive.getAsJsonPrimitive(COUNT).getAsLong(); - entity.aliveSize = alive.getAsJsonPrimitive(SIZE).getAsLong(); - } - - if (obj.has("dead")) { - final JsonObject dead = obj.getAsJsonObject("dead"); - entity.deadCount = dead.getAsJsonPrimitive(COUNT).getAsLong(); - entity.deadSize = dead.getAsJsonPrimitive(SIZE).getAsLong(); - entity.deadDeletion = dead.getAsJsonPrimitive("deletion").getAsLong(); - } - - if (obj.has("datafiles")) { - final JsonObject datafiles = obj.getAsJsonObject("datafiles"); - entity.datafileCount = datafiles.getAsJsonPrimitive(COUNT).getAsLong(); - entity.datafileFileSize = datafiles.getAsJsonPrimitive(FILE_SIZE).getAsLong(); - } - - if (obj.has("journals")) { - final JsonObject journals = obj.getAsJsonObject("journals"); - entity.journalsCount = journals.getAsJsonPrimitive(COUNT).getAsLong(); - entity.journalsFileSize = journals.getAsJsonPrimitive(FILE_SIZE).getAsLong(); - } - - if (obj.has("compactors")) { - final JsonObject compactors = obj.getAsJsonObject("compactors"); - entity.compactorsCount = compactors.getAsJsonPrimitive(COUNT).getAsLong(); - entity.compactorsFileSize = compactors.getAsJsonPrimitive(FILE_SIZE).getAsLong(); - } - - if (obj.has(INDEXES)) { - final JsonObject indexes = obj.getAsJsonObject(INDEXES); - entity.indexesCount = indexes.getAsJsonPrimitive(COUNT).getAsLong(); - entity.indexesSize = indexes.getAsJsonPrimitive(SIZE).getAsLong(); - } - - if (obj.has("lastTick")) { - entity.lastTick = obj.getAsJsonPrimitive("lastTick").getAsLong(); - } - - if (obj.has("uncollectedLogfileEntries")) { - entity.uncollectedLogfileEntries = obj.getAsJsonPrimitive("uncollectedLogfileEntries").getAsLong(); - } - - return entity; - } - } - - public static class CollectionKeyOptionDeserializer implements JsonDeserializer { - @Override - public CollectionKeyOption deserialize( - final JsonElement json, - final Type typeOfT, - final JsonDeserializationContext context) { - - if (json.isJsonNull()) { - return null; - } - - final JsonObject obj = json.getAsJsonObject(); - final CollectionKeyOption entity = new CollectionKeyOption(); - - if (obj.has("type")) { - entity.type = obj.getAsJsonPrimitive("type").getAsString(); - } - - if (obj.has("allowUserKeys")) { - entity.allowUserKeys = obj.getAsJsonPrimitive("allowUserKeys").getAsBoolean(); - } - - if (obj.has("increment")) { - entity.increment = obj.getAsJsonPrimitive("increment").getAsLong(); - } - - if (obj.has("offset")) { - entity.offset = obj.getAsJsonPrimitive("offset").getAsLong(); - } - - return entity; - } - } - - public static class CollectionEntityDeserializer implements JsonDeserializer { - - @Override - public CollectionEntity deserialize( - final JsonElement json, - final Type typeOfT, - final JsonDeserializationContext context) { - - if (json.isJsonNull()) { - return null; - } - - final JsonObject obj = json.getAsJsonObject(); - final CollectionEntity entity = deserializeBaseParameter(obj, new CollectionEntity()); - - if (obj.has(NAME)) { - entity.name = obj.getAsJsonPrimitive(NAME).getAsString(); - } - - if (obj.has(ID)) { - entity.id = obj.getAsJsonPrimitive(ID).getAsLong(); - } - - if (obj.has(STATUS)) { - entity.status = context.deserialize(obj.get(STATUS), CollectionStatus.class); - } - - if (obj.has(WAIT_FOR_SYNC)) { - entity.waitForSync = obj.getAsJsonPrimitive(WAIT_FOR_SYNC).getAsBoolean(); - } - - if (obj.has(IS_SYSTEM)) { - entity.isSystem = obj.getAsJsonPrimitive(IS_SYSTEM).getAsBoolean(); - } - - if (obj.has(IS_VOLATILE)) { - entity.isVolatile = obj.getAsJsonPrimitive(IS_VOLATILE).getAsBoolean(); - } - - if (obj.has(JOURNAL_SIZE)) { - entity.journalSize = obj.getAsJsonPrimitive(JOURNAL_SIZE).getAsLong(); - } - - if (obj.has(COUNT)) { - entity.count = obj.getAsJsonPrimitive(COUNT).getAsLong(); - } - - if (obj.has(FIGURES)) { - entity.figures = context.deserialize(obj.get(FIGURES), Figures.class); - } - - if (obj.has(TYPE)) { - entity.type = CollectionType.valueOf(obj.getAsJsonPrimitive(TYPE).getAsInt()); - } - - if (obj.has(KEY_OPTIONS)) { - entity.keyOptions = context.deserialize(obj.get(KEY_OPTIONS), CollectionKeyOption.class); - } - - if (obj.has(CHECKSUM)) { - entity.checksum = obj.getAsJsonPrimitive(CHECKSUM).getAsLong(); - } - - if (obj.has(DO_COMPACT)) { - entity.doCompact = obj.getAsJsonPrimitive(DO_COMPACT).getAsBoolean(); - } - - return entity; - } - } - - public static class CollectionsEntityDeserializer implements JsonDeserializer { - private final Type collectionsType = new TypeToken>() { - }.getType(); - - @SuppressWarnings("unchecked") - @Override - public CollectionsEntity deserialize( - final JsonElement json, - final Type typeOfT, - final JsonDeserializationContext context) { - - if (json.isJsonNull()) { - return null; - } - - final JsonObject obj = json.getAsJsonObject(); - final CollectionsEntity entity = deserializeBaseParameter(obj, new CollectionsEntity()); - - if (obj.has(RESULT)) { - entity.setCollections((List) context.deserialize(obj.get(RESULT), collectionsType)); - } else { - entity.setCollections(new ArrayList()); - } - - return entity; - } - } - - public static class AqlfunctionsEntityDeserializer implements JsonDeserializer { - - @Override - public AqlFunctionsEntity deserialize( - final JsonElement json, - final Type typeOfT, - final JsonDeserializationContext context) { - - if (json.isJsonNull()) { - return null; - } - - final JsonArray obj = json.getAsJsonArray(); - final Iterator iterator = obj.iterator(); - final Map functions = new HashMap(); - while (iterator.hasNext()) { - final JsonElement e = iterator.next(); - final JsonObject o = e.getAsJsonObject(); - functions.put(o.get("name").getAsString(), o.get(CODE).getAsString()); - } - return new AqlFunctionsEntity(functions); - } - } - - public static class JobsEntityDeserializer implements JsonDeserializer { - - @Override - public JobsEntity deserialize( - final JsonElement json, - final Type typeOfT, - final JsonDeserializationContext context) { - - if (json.isJsonNull()) { - return null; - } - - final JsonArray obj = json.getAsJsonArray(); - final Iterator iterator = obj.iterator(); - final List jobs = new ArrayList(); - while (iterator.hasNext()) { - final JsonElement e = iterator.next(); - jobs.add(e.getAsString()); - } - return new JobsEntity(jobs); - } - } - - public static class CursorEntityDeserializer implements JsonDeserializer> { - - private final Type bindVarsType = new TypeToken>() { - }.getType(); - - private final Type extraType = new TypeToken>() { - }.getType(); - - @Override - public CursorEntity deserialize( - final JsonElement json, - final Type typeOfT, - final JsonDeserializationContext context) { - - if (json.isJsonNull()) { - return null; - } - - final JsonObject obj = json.getAsJsonObject(); - final CursorEntity entity = deserializeBaseParameter(obj, new CursorEntity()); - - if (obj.has(RESULT)) { - final JsonArray array = obj.getAsJsonArray(RESULT); - if (array == null || array.isJsonNull() || array.size() == 0) { - entity.results = Collections.emptyList(); - } else { - getResultObjects(context, entity, array); - } - } - - if (obj.has("hasMore")) { - entity.hasMore = obj.getAsJsonPrimitive("hasMore").getAsBoolean(); - } - - if (obj.has(COUNT)) { - entity.count = obj.getAsJsonPrimitive(COUNT).getAsInt(); - } - - if (obj.has(ID)) { - entity.cursorId = obj.getAsJsonPrimitive(ID).getAsLong(); - } - - if (obj.has("cached")) { - entity.cached = obj.getAsJsonPrimitive("cached").getAsBoolean(); - } - - if (obj.has("bindVars")) { - entity.bindVars = context.deserialize(obj.get("bindVars"), bindVarsType); - } - - entity.warnings = new ArrayList(); - if (obj.has(EXTRA)) { - entity.extra = context.deserialize(obj.get(EXTRA), extraType); - getFullCount(entity); - getWarnings(entity); - } - - return entity; - } - - private void getResultObjects( - final JsonDeserializationContext context, - final CursorEntity entity, - final JsonArray array) { - final Class clazz = getParameterized(); - final boolean withDocument = DocumentEntity.class.isAssignableFrom(clazz); - if (withDocument) { - nextParameterized(); - } - try { - final List list = new ArrayList(array.size()); - for (int i = 0, imax = array.size(); i < imax; i++) { - list.add(context.deserialize(array.get(i), clazz)); - } - entity.results = list; - } finally { - if (withDocument) { - backParameterized(); - } - } - } - - private void getWarnings(final CursorEntity entity) { - if (entity.extra.containsKey(WARNINGS)) { - final Object object = entity.extra.get(WARNINGS); - if (object instanceof List) { - final List l = (List) entity.extra.get(WARNINGS); - getWarningsFromList(entity, l); - } - } - } - - private void getWarningsFromList(final CursorEntity entity, final List l) { - for (final Object o : l) { - if (o instanceof Map) { - final Map m = (Map) o; - if (m.containsKey(CODE) && m.get(CODE) instanceof Double && m.containsKey(MESSAGE) - && m.get(MESSAGE) instanceof String) { - final Long code = ((Double) m.get(CODE)).longValue(); - final String message = (String) m.get(MESSAGE); - entity.warnings.add(new WarningEntity(code, message)); - } - } - } - } - - private void getFullCount(final CursorEntity entity) { - if (entity.extra.containsKey("stats") && entity.extra.get("stats") instanceof Map) { - final Map m = (Map) entity.extra.get("stats"); - if (m.containsKey("fullCount") && m.get("fullCount") instanceof Double) { - final Double v = (Double) m.get("fullCount"); - entity.fullCount = v.intValue(); - } - } - } - - private Class backParameterized() { - final ClassHolder holder = parameterizedBridger.get(); - if (holder == null) { - return null; - } - return holder.back(); - } - - } - - public static class DocumentEntityDeserializer implements JsonDeserializer> { - - @Override - public DocumentEntity deserialize( - final JsonElement json, - final Type typeOfT, - final JsonDeserializationContext context) { - - if (json.isJsonNull()) { - return new DocumentEntity(); - } - - if (json.isJsonPrimitive()) { - return new DocumentEntity(); - } - - if (json.isJsonArray()) { - return new DocumentEntity(); - } - - final JsonObject obj = json.getAsJsonObject(); - - final DocumentEntity entity = new DocumentEntity(); - deserializeDocumentParameter(obj, entity); - - // 他のフィールドはリフレクションで。 (TODO: Annotationのサポートと上記パラメータを弾く) - final Class clazz = getParameterized(); - if (clazz != null) { - entity.entity = context.deserialize(obj, clazz); - - if (clazz.getName().equalsIgnoreCase(BaseDocument.class.getName())) { - // iterate all key/value pairs of the jsonObject and - // determine its class(String, Number, Boolean, HashMap, - // List) - ((BaseDocument) entity.entity).setProperties(DeserializeSingleEntry.deserializeJsonObject(obj)); - } - } - - return entity; - } - } - - public static class DeserializeSingleEntry { - - private static final List nonProperties = Arrays.asList("_id", "_rev", "_key"); - - private DeserializeSingleEntry() { - // this is a helper class - } - - /** - * deserialize any jsonElement - * - * @param jsonElement - * @return a object - */ - public static Object deserializeJsonElement(final JsonElement jsonElement) { - if (jsonElement.getClass() == JsonPrimitive.class) { - return deserializeJsonPrimitive((JsonPrimitive) jsonElement); - } else if (jsonElement.getClass() == JsonArray.class) { - return deserializeJsonArray((JsonArray) jsonElement); - } else if (jsonElement.getClass() == JsonObject.class) { - return deserializeJsonObject((JsonObject) jsonElement); - } - return null; - } - - /** - * deserializes a JsonObject into a Map - * - * @param jsonObject - * a jsonObject - * @return the deserialized jsonObject - */ - private static Map deserializeJsonObject(final JsonObject jsonObject) { - final Map result = new HashMap(); - final Set> entrySet = jsonObject.entrySet(); - for (final Map.Entry entry : entrySet) { - if (!nonProperties.contains(entry.getKey())) { - result.put(entry.getKey(), deserializeJsonElement(jsonObject.get(entry.getKey()))); - } - } - return result; - } - - private static List deserializeJsonArray(final JsonArray jsonArray) { - final List tmpObjectList = new ArrayList(); - final Iterator iterator = jsonArray.iterator(); - while (iterator.hasNext()) { - tmpObjectList.add(deserializeJsonElement(iterator.next())); - } - return tmpObjectList; - } - - /** - * deserializes a jsonPrimitiv into the equivalent java primitive - * - * @param jsonPrimitive - * @return null|String|Double|Boolean - */ - private static Object deserializeJsonPrimitive(final JsonPrimitive jsonPrimitive) { - if (jsonPrimitive.isBoolean()) { - return jsonPrimitive.getAsBoolean(); - } else if (jsonPrimitive.isNumber()) { - return jsonPrimitive.getAsDouble(); - } else if (jsonPrimitive.isString()) { - return jsonPrimitive.getAsString(); - } - return null; - } - - } - - public static class DocumentsEntityDeserializer implements JsonDeserializer { - private final Type documentsType = new TypeToken>() { - }.getType(); - - @Override - public DocumentsEntity deserialize( - final JsonElement json, - final Type typeOfT, - final JsonDeserializationContext context) { - - if (json.isJsonNull()) { - return null; - } - - final JsonObject obj = json.getAsJsonObject(); - final DocumentsEntity entity = deserializeBaseParameter(obj, new DocumentsEntity()); - - if (obj.has("documents")) { - entity.documents = context.deserialize(obj.get("documents"), documentsType); - } - - return entity; - } - - } - - public static class IndexEntityDeserializer implements JsonDeserializer { - private final Type fieldsType = new TypeToken>() { - }.getType(); - - @Override - public IndexEntity deserialize( - final JsonElement json, - final Type typeOfT, - final JsonDeserializationContext context) { - - if (json.isJsonNull()) { - return null; - } - - final JsonObject obj = json.getAsJsonObject(); - final IndexEntity entity = deserializeBaseParameter(obj, new IndexEntity()); - - if (obj.has(ID)) { - entity.id = obj.getAsJsonPrimitive(ID).getAsString(); - } - - if (obj.has("type")) { - final String type = obj.getAsJsonPrimitive("type").getAsString().toUpperCase(Locale.US); - if (type.startsWith(IndexType.GEO.name())) { - entity.type = IndexType.GEO; - } else { - entity.type = IndexType.valueOf(type); - } - } - - if (obj.has("fields")) { - entity.fields = context.deserialize(obj.getAsJsonArray("fields"), fieldsType); - } - - if (obj.has("geoJson")) { - entity.geoJson = obj.getAsJsonPrimitive("geoJson").getAsBoolean(); - } - - if (obj.has("isNewlyCreated")) { - entity.isNewlyCreated = obj.getAsJsonPrimitive("isNewlyCreated").getAsBoolean(); - } - - if (obj.has("unique")) { - entity.unique = obj.getAsJsonPrimitive("unique").getAsBoolean(); - } - - if (obj.has("sparse")) { - entity.sparse = obj.getAsJsonPrimitive("sparse").getAsBoolean(); - } - - if (obj.has("size")) { - entity.size = obj.getAsJsonPrimitive("size").getAsInt(); - } - - if (obj.has("minLength")) { - entity.minLength = obj.getAsJsonPrimitive("minLength").getAsInt(); - } - - if (obj.has("selectivityEstimate")) { - entity.selectivityEstimate = obj.getAsJsonPrimitive("selectivityEstimate").getAsDouble(); - } - - return entity; - } - } - - public static class IndexesEntityDeserializer implements JsonDeserializer { - private final Type indexesType = new TypeToken>() { - }.getType(); - private final Type identifiersType = new TypeToken>() { - }.getType(); - - @Override - public IndexesEntity deserialize( - final JsonElement json, - final Type typeOfT, - final JsonDeserializationContext context) { - - if (json.isJsonNull()) { - return null; - } - - final JsonObject obj = json.getAsJsonObject(); - final IndexesEntity entity = deserializeBaseParameter(obj, new IndexesEntity()); - - if (obj.has(INDEXES)) { - entity.indexes = context.deserialize(obj.get(INDEXES), indexesType); - } - - if (obj.has("identifiers")) { - entity.identifiers = context.deserialize(obj.get("identifiers"), identifiersType); - } - - return entity; - } - - } - - public static class AdminLogEntryEntityDeserializer implements JsonDeserializer { - @Override - public AdminLogEntity deserialize( - final JsonElement json, - final Type typeOfT, - final JsonDeserializationContext context) { - - if (json.isJsonNull()) { - return null; - } - - final JsonObject obj = json.getAsJsonObject(); - final AdminLogEntity entity = deserializeBaseParameter(obj, new AdminLogEntity()); - // 全ての要素は必ずあることが前提なのでhasチェックはしない - final int[] lids = context.deserialize(obj.getAsJsonArray("lid"), int[].class); - final int[] levels = context.deserialize(obj.getAsJsonArray("level"), int[].class); - final long[] timestamps = context.deserialize(obj.getAsJsonArray("timestamp"), long[].class); - final String[] texts = context.deserialize(obj.getAsJsonArray("text"), String[].class); - - // 配列のサイズが全て同じであること - if (lids.length != levels.length || lids.length != timestamps.length || lids.length != texts.length) { - throw new IllegalStateException("each parameters returns wrong length."); - } - - entity.logs = new ArrayList(lids.length); - for (int i = 0; i < lids.length; i++) { - final AdminLogEntity.LogEntry entry = new AdminLogEntity.LogEntry(); - entry.lid = lids[i]; - entry.level = levels[i]; - entry.timestamp = new Date(timestamps[i] * 1000L); - entry.text = texts[i]; - entity.logs.add(entry); - } - - if (obj.has("totalAmount")) { - entity.totalAmount = obj.getAsJsonPrimitive("totalAmount").getAsInt(); - } - - return entity; - } - } - - public static class StatisticsEntityDeserializer implements JsonDeserializer { - Type countsType = new TypeToken() { - }.getType(); - - @Override - public StatisticsEntity deserialize( - final JsonElement json, - final Type typeOfT, - final JsonDeserializationContext context) { - - if (json.isJsonNull()) { - return null; - } - - final JsonObject obj = json.getAsJsonObject(); - final StatisticsEntity entity = deserializeBaseParameter(obj, new StatisticsEntity()); - - deserializeSystem(obj, entity); - - deserializeClient(context, obj, entity); - - deserializeServer(obj, entity); - - return entity; - - } - - private void deserializeServer(final JsonObject obj, final StatisticsEntity entity) { - if (obj.has(SERVER)) { - final JsonObject svr = obj.getAsJsonObject(SERVER); - entity.server = new StatisticsEntity.Server(); - - if (svr.has("uptime")) { - entity.server.uptime = svr.getAsJsonPrimitive("uptime").getAsDouble(); - } - } - } - - private void deserializeClient( - final JsonDeserializationContext context, - final JsonObject obj, - final StatisticsEntity entity) { - if (obj.has("client")) { - final StatisticsEntity.Client cli = new StatisticsEntity.Client(); - cli.figures = new TreeMap(); - entity.client = cli; - - final JsonObject client = obj.getAsJsonObject("client"); - if (client.has("httpConnections")) { - cli.httpConnections = client.getAsJsonPrimitive("httpConnections").getAsInt(); - } - for (final Entry ent : client.entrySet()) { - if (!"httpConnections".equals(ent.getKey())) { - final JsonObject f = ent.getValue().getAsJsonObject(); - final FigureValue fv = new FigureValue(); - fv.sum = f.getAsJsonPrimitive("sum").getAsDouble(); - fv.count = f.getAsJsonPrimitive(COUNT).getAsLong(); - fv.counts = context.deserialize(f.getAsJsonArray("counts"), countsType); - cli.figures.put(ent.getKey(), fv); - } - } - } - } - - private void deserializeSystem(final JsonObject obj, final StatisticsEntity entity) { - if (obj.has("system")) { - final StatisticsEntity.System sys = new StatisticsEntity.System(); - entity.system = sys; - - final JsonObject system = obj.getAsJsonObject("system"); - if (system.has("minorPageFaults")) { - sys.minorPageFaults = system.getAsJsonPrimitive("minorPageFaults").getAsLong(); - } - if (system.has("majorPageFaults")) { - sys.majorPageFaults = system.getAsJsonPrimitive("majorPageFaults").getAsLong(); - } - if (system.has("userTime")) { - sys.userTime = system.getAsJsonPrimitive("userTime").getAsDouble(); - } - if (system.has("systemTime")) { - sys.systemTime = system.getAsJsonPrimitive("systemTime").getAsDouble(); - } - if (system.has("numberOfThreads")) { - sys.numberOfThreads = system.getAsJsonPrimitive("numberOfThreads").getAsInt(); - } - if (system.has("residentSize")) { - sys.residentSize = system.getAsJsonPrimitive("residentSize").getAsLong(); - } - if (system.has("virtualSize")) { - sys.virtualSize = system.getAsJsonPrimitive("virtualSize").getAsLong(); - } - } - } - } - - public static class StatisticsDescriptionEntityDeserializer - implements JsonDeserializer { - Type cutsTypes = new TypeToken() { - }.getType(); - - @Override - public StatisticsDescriptionEntity deserialize( - final JsonElement json, - final Type typeOfT, - final JsonDeserializationContext context) { - - if (json.isJsonNull()) { - return null; - } - - final JsonObject obj = json.getAsJsonObject(); - final StatisticsDescriptionEntity entity = deserializeBaseParameter(obj, new StatisticsDescriptionEntity()); - - if (obj.has("groups")) { - final JsonArray groups = obj.getAsJsonArray("groups"); - entity.groups = new ArrayList(groups.size()); - for (int i = 0, imax = groups.size(); i < imax; i++) { - final JsonObject g = groups.get(i).getAsJsonObject(); - - final Group group = new Group(); - group.group = g.getAsJsonPrimitive("group").getAsString(); - group.name = g.getAsJsonPrimitive("name").getAsString(); - group.description = g.getAsJsonPrimitive("description").getAsString(); - - entity.groups.add(group); - } - } - - if (obj.has(FIGURES)) { - final JsonArray figures = obj.getAsJsonArray(FIGURES); - entity.figures = new ArrayList(figures.size()); - for (int i = 0, imax = figures.size(); i < imax; i++) { - final JsonObject f = figures.get(i).getAsJsonObject(); - - final Figure figure = new Figure(); - figure.group = f.getAsJsonPrimitive("group").getAsString(); - figure.identifier = f.getAsJsonPrimitive("identifier").getAsString(); - figure.name = f.getAsJsonPrimitive("name").getAsString(); - figure.description = f.getAsJsonPrimitive("description").getAsString(); - figure.type = f.getAsJsonPrimitive("type").getAsString(); - figure.units = f.getAsJsonPrimitive("units").getAsString(); - if (f.has("cuts")) { - figure.cuts = context.deserialize(f.getAsJsonArray("cuts"), cutsTypes); - } - - entity.figures.add(figure); - - } - } - - return entity; - } - } - - public static class ScalarExampleEntityDeserializer implements JsonDeserializer> { - - @Override - public ScalarExampleEntity deserialize( - final JsonElement json, - final Type typeOfT, - final JsonDeserializationContext context) { - - if (json.isJsonNull()) { - return null; - } - - final JsonObject obj = json.getAsJsonObject(); - final ScalarExampleEntity entity = deserializeBaseParameter(obj, new ScalarExampleEntity()); - - if (obj.has("document")) { - entity.document = context.deserialize(obj.get("document"), DocumentEntity.class); - } - - return entity; - } - - } - - public static class SimpleByResultEntityDeserializer implements JsonDeserializer { - - @Override - public SimpleByResultEntity deserialize( - final JsonElement json, - final Type typeOfT, - final JsonDeserializationContext context) { - - if (json.isJsonNull()) { - return null; - } - - final JsonObject obj = json.getAsJsonObject(); - final SimpleByResultEntity entity = deserializeBaseParameter(obj, new SimpleByResultEntity()); - - if (obj.has(DELETED)) { - entity.count = entity.deleted = obj.getAsJsonPrimitive(DELETED).getAsInt(); - } - - if (obj.has(REPLACED)) { - entity.count = entity.replaced = obj.getAsJsonPrimitive(REPLACED).getAsInt(); - } - - if (obj.has(UPDATED)) { - entity.count = entity.updated = obj.getAsJsonPrimitive(UPDATED).getAsInt(); - } - - return entity; - } - - } - - public static class TransactionResultEntityDeserializer implements JsonDeserializer { - - @Override - public TransactionResultEntity deserialize( - final JsonElement json, - final Type typeOfT, - final JsonDeserializationContext context) { - - if (json.isJsonNull()) { - return null; - } - - final JsonObject obj = json.getAsJsonObject(); - final TransactionResultEntity entity = deserializeBaseParameter(obj, new TransactionResultEntity()); - - if (obj.has(RESULT)) { // MEMO: - if (obj.get(RESULT) instanceof JsonObject) { - entity.setResult(obj.get(RESULT)); - } else if (obj.getAsJsonPrimitive(RESULT).isBoolean()) { - entity.setResult(obj.getAsJsonPrimitive(RESULT).getAsBoolean()); - } else if (obj.getAsJsonPrimitive(RESULT).isNumber()) { - entity.setResult(obj.getAsJsonPrimitive(RESULT).getAsNumber()); - } else if (obj.getAsJsonPrimitive(RESULT).isString()) { - entity.setResult(obj.getAsJsonPrimitive(RESULT).getAsString()); - } - } - - return entity; - } - - } - - public static class UserEntityDeserializer implements JsonDeserializer { - - @Override - public UserEntity deserialize( - final JsonElement json, - final Type typeOfT, - final JsonDeserializationContext context) { - - if (json.isJsonNull()) { - return null; - } - - final JsonObject obj = json.getAsJsonObject(); - final UserEntity entity = deserializeBaseParameter(obj, new UserEntity()); - - if (obj.has("user")) { // MEMO: - // RequestはusernameなのにResponseは何故userなのか。。 - entity.username = obj.getAsJsonPrimitive("user").getAsString(); - } - - if (obj.has(PASSWORD)) { - entity.password = obj.getAsJsonPrimitive(PASSWORD).getAsString(); - } - - if (obj.has(ACTIVE)) { - entity.active = obj.getAsJsonPrimitive(ACTIVE).getAsBoolean(); - } else if (obj.has("authData")) { - // for simple/all requsts - final JsonObject authData = obj.getAsJsonObject("authData"); - if (authData.has(ACTIVE)) { - entity.active = authData.getAsJsonPrimitive(ACTIVE).getAsBoolean(); - } - } - - if (obj.has(EXTRA)) { - entity.extra = context.deserialize(obj.getAsJsonObject(EXTRA), Map.class); - } else if (obj.has("userData")) { - // for simple/all requsts - entity.extra = context.deserialize(obj.getAsJsonObject("userData"), Map.class); - } else { - entity.extra = new HashMap(); - } - - return entity; - } - - } - - public static class ImportResultEntityDeserializer implements JsonDeserializer { - - @Override - public ImportResultEntity deserialize( - final JsonElement json, - final Type typeOfT, - final JsonDeserializationContext context) { - - if (json.isJsonNull()) { - return null; - } - - final JsonObject obj = json.getAsJsonObject(); - final ImportResultEntity entity = deserializeBaseParameter(obj, new ImportResultEntity()); - - if (obj.has(CREATED)) { - entity.setCreated(obj.getAsJsonPrimitive(CREATED).getAsInt()); - } - - if (obj.has(ERRORS)) { - entity.setErrors(obj.getAsJsonPrimitive(ERRORS).getAsInt()); - } - - if (obj.has(EMPTY)) { - entity.setEmpty(obj.getAsJsonPrimitive(EMPTY).getAsInt()); - } - - if (obj.has(UPDATED)) { - entity.setUpdated(obj.getAsJsonPrimitive(UPDATED).getAsInt()); - } - - if (obj.has(IGNORED)) { - entity.setIgnored(obj.getAsJsonPrimitive(IGNORED).getAsInt()); - } - - if (obj.has(DETAILS)) { - final JsonArray asJsonArray = obj.getAsJsonArray(DETAILS); - for (final JsonElement jsonElement : asJsonArray) { - entity.getDetails().add(jsonElement.getAsString()); - } - } - - return entity; - } - } - - public static class DatabaseEntityDeserializer implements JsonDeserializer { - @Override - public DatabaseEntity deserialize( - final JsonElement json, - final Type typeOfT, - final JsonDeserializationContext context) { - - if (json.isJsonNull()) { - return null; - } - - final JsonObject obj = json.getAsJsonObject(); - final DatabaseEntity entity = deserializeBaseParameter(obj, new DatabaseEntity()); - - if (obj.has(RESULT)) { - final JsonObject result = obj.getAsJsonObject(RESULT); - if (result.has("name")) { - entity.name = result.getAsJsonPrimitive("name").getAsString(); - } - if (result.has(ID)) { - entity.id = result.getAsJsonPrimitive(ID).getAsString(); - } - if (result.has("path")) { - entity.path = result.getAsJsonPrimitive("path").getAsString(); - } - if (result.has(IS_SYSTEM)) { - entity.isSystem = result.getAsJsonPrimitive(IS_SYSTEM).getAsBoolean(); - } - } - - return entity; - } - } - - public static class StringsResultEntityDeserializer implements JsonDeserializer { - Type resultType = new TypeToken>() { - }.getType(); - - @Override - public StringsResultEntity deserialize( - final JsonElement json, - final Type typeOfT, - final JsonDeserializationContext context) { - - if (json.isJsonNull()) { - return null; - } - - final JsonObject obj = json.getAsJsonObject(); - final StringsResultEntity entity = deserializeBaseParameter(obj, new StringsResultEntity()); - - if (obj.has(RESULT)) { - entity.result = context.deserialize(obj.get(RESULT), resultType); - } - - return entity; - } - } - - public static class BooleanResultEntityDeserializer implements JsonDeserializer { - @Override - public BooleanResultEntity deserialize( - final JsonElement json, - final Type typeOfT, - final JsonDeserializationContext context) { - - if (json.isJsonNull()) { - return null; - } - - final JsonObject obj = json.getAsJsonObject(); - final BooleanResultEntity entity = deserializeBaseParameter(obj, new BooleanResultEntity()); - - if (obj.has(RESULT)) { - entity.result = obj.getAsJsonPrimitive(RESULT).getAsBoolean(); - } - - return entity; - } - } - - public static class EndpointDeserializer implements JsonDeserializer { - Type databasesType = new TypeToken>() { - }.getType(); - - @SuppressWarnings("unchecked") - @Override - public Endpoint deserialize( - final JsonElement json, - final Type typeOfT, - final JsonDeserializationContext context) { - - if (json.isJsonNull()) { - return null; - } - - final JsonObject obj = json.getAsJsonObject(); - - final Endpoint entity = new Endpoint(); - entity.setDatabases((List) context.deserialize(obj.getAsJsonArray("databases"), databasesType)); - entity.setEndpoint(obj.getAsJsonPrimitive("endpoint").getAsString()); - - return entity; - } - } - - public static class DocumentResultEntityDeserializer implements JsonDeserializer> { - Type documentsType = new TypeToken>>() { - }.getType(); - - @Override - public DocumentResultEntity deserialize( - final JsonElement json, - final Type typeOfT, - final JsonDeserializationContext context) { - - if (json.isJsonNull()) { - return null; - } - - final JsonObject obj = json.getAsJsonObject(); - final DocumentResultEntity entity = deserializeBaseParameter(obj, - new DocumentResultEntity()); - - if (obj.has(RESULT)) { - final JsonElement resultElem = obj.get(RESULT); - if (resultElem.isJsonArray()) { - entity.result = context.deserialize(resultElem, documentsType); - } else if (resultElem.isJsonObject()) { - final DocumentEntity doc = context.deserialize(resultElem, DocumentEntity.class); - final List> list = new ArrayList>(1); - list.add(doc); - entity.result = list; - } else { - throw new IllegalStateException("result type is not array or object:" + resultElem); - } - } - - return entity; - } - } - - public static class ReplicationStateDeserializer implements JsonDeserializer { - @Override - public ReplicationState deserialize( - final JsonElement json, - final Type typeOfT, - final JsonDeserializationContext context) { - - if (json.isJsonNull()) { - return null; - } - - final JsonObject obj = json.getAsJsonObject(); - final ReplicationState entity = new ReplicationState(); - - entity.running = obj.getAsJsonPrimitive("running").getAsBoolean(); - entity.lastLogTick = obj.getAsJsonPrimitive("lastLogTick").getAsLong(); - entity.totalEvents = obj.getAsJsonPrimitive("totalEvents").getAsLong(); - entity.time = DateUtils.parse(obj.getAsJsonPrimitive("time").getAsString()); - - return entity; - } - } - - public static class ReplicationInventoryEntityDeserializer implements JsonDeserializer { - - private final Type indexesType = new TypeToken>() { - }.getType(); - - @Override - public ReplicationInventoryEntity deserialize( - final JsonElement json, - final Type typeOfT, - final JsonDeserializationContext context) { - - if (json.isJsonNull()) { - return null; - } - - final JsonObject obj = json.getAsJsonObject(); - final ReplicationInventoryEntity entity = deserializeBaseParameter(obj, new ReplicationInventoryEntity()); - - if (obj.has(COLLECTIONS)) { - final JsonArray collections = obj.getAsJsonArray(COLLECTIONS); - entity.collections = new ArrayList(collections.size()); - for (int i = 0, imax = collections.size(); i < imax; i++) { - final JsonObject elem = collections.get(i).getAsJsonObject(); - final Collection col = new Collection(); - - if (elem.has("parameters")) { - final JsonObject parameters = elem.getAsJsonObject("parameters"); - addCollectionParameters(col, parameters); - } - - if (elem.has(INDEXES)) { - col.indexes = context.deserialize(elem.getAsJsonArray(INDEXES), indexesType); - } - - entity.collections.add(col); - } - } - - if (obj.has(STATE)) { - entity.state = context.deserialize(obj.getAsJsonObject(STATE), ReplicationState.class); - } - - if (obj.has("tick")) { - entity.tick = obj.getAsJsonPrimitive("tick").getAsLong(); - } - - return entity; - } - - private void addCollectionParameters(final Collection col, final JsonObject parameters) { - col.parameter = new CollectionParameter(); - if (parameters.has(VERSION)) { - col.parameter.version = parameters.getAsJsonPrimitive(VERSION).getAsInt(); - } - if (parameters.has("type")) { - col.parameter.type = CollectionType.valueOf(parameters.getAsJsonPrimitive("type").getAsInt()); - } - if (parameters.has("cid")) { - col.parameter.cid = parameters.getAsJsonPrimitive("cid").getAsLong(); - } - if (parameters.has(DELETED)) { - col.parameter.deleted = parameters.getAsJsonPrimitive(DELETED).getAsBoolean(); - } - if (parameters.has(DO_COMPACT)) { - col.parameter.doCompact = parameters.getAsJsonPrimitive(DO_COMPACT).getAsBoolean(); - } - if (parameters.has("maximalSize")) { - col.parameter.maximalSize = parameters.getAsJsonPrimitive("maximalSize").getAsLong(); - } - if (parameters.has("name")) { - col.parameter.name = parameters.getAsJsonPrimitive("name").getAsString(); - } - if (parameters.has(IS_VOLATILE)) { - col.parameter.isVolatile = parameters.getAsJsonPrimitive(IS_VOLATILE).getAsBoolean(); - } - if (parameters.has(WAIT_FOR_SYNC)) { - col.parameter.waitForSync = parameters.getAsJsonPrimitive(WAIT_FOR_SYNC).getAsBoolean(); - } - } - } - - public static class ReplicationDumpRecordDeserializer implements JsonDeserializer> { - Type documentsType = new TypeToken>>() { - }.getType(); - - @Override - public ReplicationDumpRecord deserialize( - final JsonElement json, - final Type typeOfT, - final JsonDeserializationContext context) { - - if (json.isJsonNull()) { - return null; - } - - final JsonObject obj = json.getAsJsonObject(); - final ReplicationDumpRecord> entity = new ReplicationDumpRecord>(); - - if (obj.has("tick")) { - entity.tick = obj.getAsJsonPrimitive("tick").getAsLong(); - } - if (obj.has("type")) { - final int type = obj.getAsJsonPrimitive("type").getAsInt(); - entity.type = ReplicationEventType.valueOf(type); - } - if (obj.has("key")) { - entity.key = obj.getAsJsonPrimitive("key").getAsString(); - } - if (obj.has("rev")) { - entity.rev = obj.getAsJsonPrimitive("rev").getAsString(); - } - if (obj.has("data")) { - entity.data = context.deserialize(obj.getAsJsonObject("data"), DocumentEntity.class); - } - - return entity; - } - } - - public static class ReplicationSyncEntityDeserializer implements JsonDeserializer { - Type collectionsType = new TypeToken>() { - }.getType(); - - @Override - public ReplicationSyncEntity deserialize( - final JsonElement json, - final Type typeOfT, - final JsonDeserializationContext context) { - - if (json.isJsonNull()) { - return null; - } - - final JsonObject obj = json.getAsJsonObject(); - final ReplicationSyncEntity entity = deserializeBaseParameter(obj, new ReplicationSyncEntity()); - - if (obj.has(COLLECTIONS)) { - entity.collections = context.deserialize(obj.getAsJsonArray(COLLECTIONS), collectionsType); - } - if (obj.has("lastLogTick")) { - entity.lastLogTick = obj.getAsJsonPrimitive("lastLogTick").getAsLong(); - } - - return entity; - } - } - - public static class MapAsEntityDeserializer implements JsonDeserializer { - Type mapType = new TypeToken>() { - }.getType(); - - @Override - public MapAsEntity deserialize( - final JsonElement json, - final Type typeOfT, - final JsonDeserializationContext context) { - - if (json.isJsonNull()) { - return null; - } - - final JsonObject obj = json.getAsJsonObject(); - final MapAsEntity entity = deserializeBaseParameter(obj, new MapAsEntity()); - - entity.map = context.deserialize(obj, mapType); - - return entity; - } - } - - public static class ReplicationLoggerConfigEntityDeserializer - implements JsonDeserializer { - @Override - public ReplicationLoggerConfigEntity deserialize( - final JsonElement json, - final Type typeOfT, - final JsonDeserializationContext context) { - - if (json.isJsonNull()) { - return null; - } - - final JsonObject obj = json.getAsJsonObject(); - final ReplicationLoggerConfigEntity entity = deserializeBaseParameter(obj, - new ReplicationLoggerConfigEntity()); - - if (obj.has(AUTO_START)) { - entity.autoStart = obj.getAsJsonPrimitive(AUTO_START).getAsBoolean(); - } - if (obj.has("logRemoteChanges")) { - entity.logRemoteChanges = obj.getAsJsonPrimitive("logRemoteChanges").getAsBoolean(); - } - if (obj.has("maxEvents")) { - entity.maxEvents = obj.getAsJsonPrimitive("maxEvents").getAsLong(); - } - if (obj.has("maxEventsSize")) { - entity.maxEventsSize = obj.getAsJsonPrimitive("maxEventsSize").getAsLong(); - } - - return entity; - } - } - - public static class ReplicationApplierConfigEntityDeserializer - implements JsonDeserializer { - - @Override - public ReplicationApplierConfigEntity deserialize( - final JsonElement json, - final Type typeOfT, - final JsonDeserializationContext context) { - - if (json.isJsonNull()) { - return null; - } - - final JsonObject obj = json.getAsJsonObject(); - final ReplicationApplierConfigEntity entity = deserializeBaseParameter(obj, - new ReplicationApplierConfigEntity()); - - if (obj.has(ENDPOINT)) { - entity.endpoint = obj.getAsJsonPrimitive(ENDPOINT).getAsString(); - } - - if (obj.has(DATABASE)) { - entity.database = obj.getAsJsonPrimitive(DATABASE).getAsString(); - } - - if (obj.has(USERNAME)) { - entity.username = obj.getAsJsonPrimitive(USERNAME).getAsString(); - } - - if (obj.has(PASSWORD)) { - entity.password = obj.getAsJsonPrimitive(PASSWORD).getAsString(); - } - - if (obj.has(MAX_CONNECT_RETRIES)) { - entity.maxConnectRetries = obj.getAsJsonPrimitive(MAX_CONNECT_RETRIES).getAsInt(); - } - - if (obj.has(CONNECT_TIMEOUT)) { - entity.connectTimeout = obj.getAsJsonPrimitive(CONNECT_TIMEOUT).getAsInt(); - } - - if (obj.has(REQUEST_TIMEOUT)) { - entity.requestTimeout = obj.getAsJsonPrimitive(REQUEST_TIMEOUT).getAsInt(); - } - - if (obj.has(CHUNK_SIZE)) { - entity.chunkSize = obj.getAsJsonPrimitive(CHUNK_SIZE).getAsInt(); - } - - if (obj.has(AUTO_START)) { - entity.autoStart = obj.getAsJsonPrimitive(AUTO_START).getAsBoolean(); - } - - if (obj.has(ADAPTIVE_POLLING)) { - entity.adaptivePolling = obj.getAsJsonPrimitive(ADAPTIVE_POLLING).getAsBoolean(); - } - - return entity; - } - } - - public static class ReplicationApplierStateDeserializer implements JsonDeserializer { - - @Override - public ReplicationApplierState deserialize( - final JsonElement json, - final Type typeOfT, - final JsonDeserializationContext context) { - - if (json.isJsonNull()) { - return null; - } - - final JsonObject obj = json.getAsJsonObject(); - final ReplicationApplierState state = new ReplicationApplierState(); - - if (obj.has("running")) { - state.running = obj.getAsJsonPrimitive("running").getAsBoolean(); - } - - deserializeTicks(obj, state); - - if (obj.has("time")) { - state.time = DateUtils.parse(obj.getAsJsonPrimitive("time").getAsString()); - } - if (obj.has("totalRequests")) { - state.totalRequests = obj.getAsJsonPrimitive("totalRequests").getAsLong(); - } - if (obj.has("totalFailedConnects")) { - state.totalFailedConnects = obj.getAsJsonPrimitive("totalFailedConnects").getAsLong(); - } - if (obj.has("totalEvents")) { - state.totalEvents = obj.getAsJsonPrimitive("totalEvents").getAsLong(); - } - - deserializeLastError(obj, state); - - deserializeProgress(obj, state); - - return state; - } - - private void deserializeTicks(final JsonObject obj, final ReplicationApplierState state) { - if (obj.has(LAST_APPLIED_CONTINUOUS_TICK) && !obj.get(LAST_APPLIED_CONTINUOUS_TICK).isJsonNull()) { - state.lastAppliedContinuousTick = obj.getAsJsonPrimitive(LAST_APPLIED_CONTINUOUS_TICK).getAsLong(); - } - if (obj.has(LAST_PROCESSED_CONTINUOUS_TICK) && !obj.get(LAST_PROCESSED_CONTINUOUS_TICK).isJsonNull()) { - state.lastProcessedContinuousTick = obj.getAsJsonPrimitive(LAST_PROCESSED_CONTINUOUS_TICK).getAsLong(); - } - if (obj.has(LAST_AVAILABLE_CONTINUOUS_TICK) && !obj.get(LAST_AVAILABLE_CONTINUOUS_TICK).isJsonNull()) { - state.lastAvailableContinuousTick = obj.getAsJsonPrimitive(LAST_AVAILABLE_CONTINUOUS_TICK).getAsLong(); - } - } - - private void deserializeProgress(final JsonObject obj, final ReplicationApplierState state) { - if (obj.has("progress")) { - final JsonObject progress = obj.getAsJsonObject("progress"); - state.progress = new Progress(); - if (progress.has("failedConnects")) { - state.progress.failedConnects = progress.getAsJsonPrimitive("failedConnects").getAsLong(); - } - if (progress.has(MESSAGE)) { - state.progress.message = progress.getAsJsonPrimitive(MESSAGE).getAsString(); - } - if (progress.has("time")) { - state.progress.time = DateUtils.parse(progress.getAsJsonPrimitive("time").getAsString()); - } - } - } - - private void deserializeLastError(final JsonObject obj, final ReplicationApplierState state) { - if (obj.has(LAST_ERROR) && !obj.get(LAST_ERROR).isJsonNull()) { - final JsonObject lastError = obj.getAsJsonObject(LAST_ERROR); - state.lastError = new LastError(); - if (lastError.has("time")) { - state.lastError.setTime(DateUtils.parse(lastError.getAsJsonPrimitive("time").getAsString())); - } - if (lastError.has(ERROR_NUM)) { - state.lastError.setErrorNum(lastError.getAsJsonPrimitive(ERROR_NUM).getAsInt()); - } - if (lastError.has(ERROR_MESSAGE)) { - state.lastError.setErrorMessage(lastError.getAsJsonPrimitive(ERROR_MESSAGE).getAsString()); - } - } - } - } - - public static class ReplicationApplierStateEntityDeserializer - implements JsonDeserializer { - @Override - public ReplicationApplierStateEntity deserialize( - final JsonElement json, - final Type typeOfT, - final JsonDeserializationContext context) { - - if (json.isJsonNull()) { - return null; - } - - final JsonObject obj = json.getAsJsonObject(); - final ReplicationApplierStateEntity entity = deserializeBaseParameter(obj, - new ReplicationApplierStateEntity()); - - if (obj.has(ENDPOINT)) { - entity.endpoint = obj.getAsJsonPrimitive(ENDPOINT).getAsString(); - } - - if (obj.has(DATABASE)) { - entity.database = obj.getAsJsonPrimitive(DATABASE).getAsString(); - } - - if (obj.has(SERVER)) { - final JsonObject server = obj.getAsJsonObject(SERVER); - entity.serverVersion = server.getAsJsonPrimitive(VERSION).getAsString(); - entity.serverId = server.getAsJsonPrimitive("serverId").getAsString(); - } - - if (obj.has(STATE)) { - entity.state = context.deserialize(obj.get(STATE), ReplicationApplierState.class); - } - - return entity; - } - } - - public static class ReplicationLoggerStateEntityDeserializer - implements JsonDeserializer { - private final Type clientsType = new TypeToken>() { - }.getType(); - - @Override - public ReplicationLoggerStateEntity deserialize( - final JsonElement json, - final Type typeOfT, - final JsonDeserializationContext context) { - - if (json.isJsonNull()) { - return null; - } - - final JsonObject obj = json.getAsJsonObject(); - final ReplicationLoggerStateEntity entity = deserializeBaseParameter(obj, - new ReplicationLoggerStateEntity()); - - if (obj.has(STATE)) { - entity.state = context.deserialize(obj.get(STATE), ReplicationState.class); - } - - if (obj.has(SERVER)) { - final JsonObject server = obj.getAsJsonObject(SERVER); - entity.serverVersion = server.getAsJsonPrimitive(VERSION).getAsString(); - entity.serverId = server.getAsJsonPrimitive("serverId").getAsString(); - } - - if (obj.has("clients")) { - entity.clients = context.deserialize(obj.getAsJsonArray("clients"), clientsType); - } - - return entity; - } - } - - public static class ReplicationLoggerStateEntityClientDeserializer - implements JsonDeserializer { - @Override - public ReplicationLoggerStateEntity.Client deserialize( - final JsonElement json, - final Type typeOfT, - final JsonDeserializationContext context) { - - if (json.isJsonNull()) { - return null; - } - - final JsonObject obj = json.getAsJsonObject(); - final Client client = new Client(); - - if (obj.has("serverId")) { - client.serverId = obj.getAsJsonPrimitive("serverId").getAsString(); - } - - if (obj.has("lastServedTick")) { - client.lastServedTick = obj.getAsJsonPrimitive("lastServedTick").getAsLong(); - } - - if (obj.has("time")) { - client.time = DateUtils.parse(obj.getAsJsonPrimitive("time").getAsString()); - } - - return client; - } - } - - public static class GraphEntityDeserializer implements JsonDeserializer { - - private static final String COLLECTION = "collection"; - - @Override - public GraphEntity deserialize( - final JsonElement json, - final Type typeOfT, - final JsonDeserializationContext context) { - - if (json.isJsonNull()) { - return null; - } - - final JsonObject obj = json.getAsJsonObject(); - final GraphEntity entity = deserializeBaseParameter(obj, new GraphEntity()); - - final JsonObject graph = obj.has("graph") ? obj.getAsJsonObject("graph") : obj; - deserializeDocumentParameter(graph, entity); - - if (graph.has("name")) { - entity.name = graph.get("name").getAsString(); - } - - if (graph.has("orphanCollections")) { - final JsonArray orphanCollections = graph.getAsJsonArray("orphanCollections"); - entity.orphanCollections = new ArrayList(); - if (orphanCollections != null) { - entity.orphanCollections = new ArrayList(orphanCollections.size()); - for (int i = 0, imax = orphanCollections.size(); i < imax; i++) { - final String orphanCollection = orphanCollections.get(i).getAsString(); - - entity.orphanCollections.add(orphanCollection); - } - } - } - - if (graph.has("edgeDefinitions")) { - final JsonArray edgeDefinitions = graph.getAsJsonArray("edgeDefinitions"); - entity.edgeDefinitionsEntity = new EdgeDefinitionsEntity(); - if (edgeDefinitions != null) { - addEdgeDefinitions(entity, edgeDefinitions); - } - } - - return entity; - - } - - private void addEdgeDefinitions(final GraphEntity entity, final JsonArray edgeDefinitions) { - for (int i = 0, imax = edgeDefinitions.size(); i < imax; i++) { - final EdgeDefinitionEntity edgeDefinitionEntity = new EdgeDefinitionEntity(); - final JsonObject edgeDefinition = edgeDefinitions.get(i).getAsJsonObject(); - if (edgeDefinition.has(COLLECTION)) { - edgeDefinitionEntity.setCollection(edgeDefinition.get(COLLECTION).getAsString()); - } - if (edgeDefinition.has("from")) { - final List from = new ArrayList(); - final JsonElement fromElem = edgeDefinition.get("from"); - final JsonArray fromArray = fromElem.getAsJsonArray(); - final Iterator iterator = fromArray.iterator(); - while (iterator.hasNext()) { - final JsonElement e = iterator.next(); - from.add(e.getAsString()); - } - - edgeDefinitionEntity.setFrom(from); - } - if (edgeDefinition.has("to")) { - final List to = new ArrayList(); - final JsonElement toElem = edgeDefinition.get("to"); - final JsonArray toArray = toElem.getAsJsonArray(); - final Iterator iterator = toArray.iterator(); - while (iterator.hasNext()) { - final JsonElement e = iterator.next(); - to.add(e.getAsString()); - } - edgeDefinitionEntity.setTo(to); - } - entity.edgeDefinitionsEntity.addEdgeDefinition(edgeDefinitionEntity); - } - } - } - - public static class GraphsEntityDeserializer implements JsonDeserializer { - private final Type graphsType = new TypeToken>() { - }.getType(); - - @Override - public GraphsEntity deserialize( - final JsonElement json, - final Type typeOfT, - final JsonDeserializationContext context) { - - if (json.isJsonNull()) { - return null; - } - - final JsonObject obj = json.getAsJsonObject(); - final GraphsEntity entity = deserializeBaseParameter(obj, new GraphsEntity()); - - if (obj.has("graphs")) { - entity.graphs = context.deserialize(obj.get("graphs"), graphsType); - } - - return entity; - - } - } - - public static class BaseDocumentDeserializer implements JsonDeserializer { - @Override - public BaseDocument deserialize( - final JsonElement json, - final Type typeOfT, - final JsonDeserializationContext context) { - - if (json.isJsonNull()) { - return null; - } - - final JsonObject obj = json.getAsJsonObject(); - final BaseDocument entity = deserializeDocumentParameter(obj, new BaseDocument()); - - if (entity instanceof BaseDocument) { - entity.setProperties(DeserializeSingleEntry.deserializeJsonObject(obj)); - } - - return entity; - } - } - - public static class DeleteEntityDeserializer implements JsonDeserializer { - @Override - public DeletedEntity deserialize( - final JsonElement json, - final Type typeOfT, - final JsonDeserializationContext context) { - - if (json.isJsonNull()) { - return null; - } - - final JsonObject obj = json.getAsJsonObject(); - final DeletedEntity entity = deserializeBaseParameter(obj, new DeletedEntity()); - - if (obj.has(DELETED)) { - entity.deleted = obj.getAsJsonPrimitive(DELETED).getAsBoolean(); - } - if (obj.has("removed")) { - entity.deleted = obj.getAsJsonPrimitive("removed").getAsBoolean(); - } - - return entity; - - } - } - - public static class VertexEntityDeserializer implements JsonDeserializer> { - @Override - public VertexEntity deserialize( - final JsonElement json, - final Type typeOfT, - final JsonDeserializationContext context) { - - if (json.isJsonNull()) { - return null; - } - - final JsonObject obj = json.getAsJsonObject(); - final VertexEntity entity = deserializeBaseParameter(obj, new VertexEntity()); - - final JsonObject vertex = obj.has("vertex") ? obj.getAsJsonObject("vertex") : obj; - deserializeDocumentParameter(vertex, entity); - - final Class clazz = getParameterized(); - if (clazz != null) { - entity.setEntity(context.deserialize(vertex, clazz)); - } - - return entity; - } - } - - public static class EdgeEntityDeserializer implements JsonDeserializer> { - @Override - public EdgeEntity deserialize( - final JsonElement json, - final Type typeOfT, - final JsonDeserializationContext context) { - - if (json.isJsonNull()) { - return null; - } - - final JsonObject obj = json.getAsJsonObject(); - final EdgeEntity entity = deserializeBaseParameter(obj, new EdgeEntity()); - - final JsonObject edge = obj.has("edge") ? obj.getAsJsonObject("edge") : obj; - deserializeDocumentParameter(edge, entity); - - if (edge.has("_from")) { - entity.fromVertexHandle = edge.getAsJsonPrimitive("_from").getAsString(); - } - if (edge.has("_to")) { - entity.toVertexHandle = edge.getAsJsonPrimitive("_to").getAsString(); - } - - // 他のフィールドはリフレクションで。 (TODO: Annotationのサポートと上記パラメータを弾く) - final Class clazz = getParameterized(); - if (clazz != null) { - entity.entity = context.deserialize(edge, clazz); - } - - return entity; - } - - } - - public static class TraversalEntityDeserializer implements JsonDeserializer> { - - @Override - public TraversalEntity deserialize( - final JsonElement json, - final Type typeOfT, - final JsonDeserializationContext context) { - - if (json.isJsonNull()) { - return null; - } - - final JsonObject obj = json.getAsJsonObject(); - final TraversalEntity entity = deserializeBaseParameter(obj, - new TraversalEntity()); - deserializeBaseParameter(obj, entity); - - final JsonObject result = getFirstResultAsJsonObject(obj); - if (result != null && result.getAsJsonObject().has("visited")) { - final JsonObject visited = result.getAsJsonObject().getAsJsonObject("visited"); - - final Class vertexClazz = getParameterized(); - Class edgeClazz = null; - - if (hasNextParameterized()) { - edgeClazz = nextParameterized(); - } - - if (visited.has(VERTICES)) { - entity.setVertices(getVertices(vertexClazz, context, visited.getAsJsonArray(VERTICES))); - } - if (visited.has(PATHS)) { - entity.setPaths(getPaths(context, visited, vertexClazz, edgeClazz)); - } - } - - return entity; - } - - private List> getPaths( - final JsonDeserializationContext context, - final JsonObject visited, - final Class vertexClazz, - final Class edgeClazz) { - final List> pathEntities = new ArrayList>(); - final JsonArray paths = visited.getAsJsonArray(PATHS); - if (paths != null) { - for (int i = 0, imax = paths.size(); i < imax; i++) { - final JsonObject path = paths.get(i).getAsJsonObject(); - final PathEntity pathEntity = new PathEntity(); - - if (path.has(EDGES)) { - pathEntity.setEdges(getEdges(edgeClazz, context, path.getAsJsonArray(EDGES))); - } - if (path.has(VERTICES)) { - pathEntity.setVertices(getVertices(vertexClazz, context, path.getAsJsonArray(VERTICES))); - } - - pathEntities.add(pathEntity); - } - } - return pathEntities; - } - - } - - public static class ShortestPathEntityDeserializer implements JsonDeserializer> { - @Override - public ShortestPathEntity deserialize( - final JsonElement json, - final Type typeOfT, - final JsonDeserializationContext context) { - - if (json.isJsonNull()) { - return null; - } - - final JsonObject obj = json.getAsJsonObject(); - final ShortestPathEntity entity = deserializeBaseParameter(obj, - new ShortestPathEntity()); - deserializeBaseParameter(obj, entity); - - final JsonObject result = getFirstResultAsJsonObject(obj); - if (result != null) { - final Class vertexClazz = getParameterized(); - Class edgeClazz = null; - - if (hasNextParameterized()) { - edgeClazz = nextParameterized(); - } - - if (result.has("distance")) { - entity.setDistance(result.get("distance").getAsLong()); - } else { - entity.setDistance(-1L); - } - if (result.has(EDGES)) { - // new version >= 2.6 - entity.setEdges(getEdges(edgeClazz, context, result.getAsJsonArray(EDGES))); - } - if (result.has(VERTICES)) { - // new version >= 2.6 - entity.setVertices(getVertices(vertexClazz, context, result.getAsJsonArray(VERTICES))); - } - if (result.has(PATHS)) { - // old version < 2.6 - addOldPath(context, entity, result, vertexClazz, edgeClazz); - } - } else { - entity.setDistance(-1L); - } - - return entity; - } - - private void addOldPath( - final JsonDeserializationContext context, - final ShortestPathEntity entity, - final JsonObject result, - final Class vertexClazz, - final Class edgeClazz) { - final JsonArray paths = result.getAsJsonArray(PATHS); - if (paths != null && paths.size() > 0) { - final JsonObject path = paths.get(0).getAsJsonObject(); - - if (path.has(EDGES)) { - entity.setEdges(getEdges(edgeClazz, context, path.getAsJsonArray(EDGES))); - } - if (path.has(VERTICES)) { - entity.setVertices(getVertices(vertexClazz, context, path.getAsJsonArray(VERTICES))); - } - } - } - } - - public static class QueryCachePropertiesEntityDeserializer implements JsonDeserializer { - - @Override - public QueryCachePropertiesEntity deserialize( - final JsonElement json, - final Type typeOfT, - final JsonDeserializationContext context) { - - if (json.isJsonNull()) { - return null; - } - - final JsonObject obj = json.getAsJsonObject(); - final QueryCachePropertiesEntity entity = deserializeBaseParameter(obj, new QueryCachePropertiesEntity()); - - if (obj.has("mode")) { - final String modeAsString = obj.getAsJsonPrimitive("mode").getAsString(); - entity.setMode(CacheMode.valueOf(modeAsString)); - } - - if (obj.has("maxResults")) { - entity.setMaxResults(obj.getAsJsonPrimitive("maxResults").getAsLong()); - } - - return entity; - } - - } - - public static class QueriesResultEntityDeserializer implements JsonDeserializer { - - @Override - public QueriesResultEntity deserialize( - final JsonElement json, - final Type typeOfT, - final JsonDeserializationContext context) { - - if (json.isJsonNull()) { - return null; - } - - final JsonArray array = json.getAsJsonArray(); - final Iterator iterator = array.iterator(); - final List queries = new ArrayList(); - while (iterator.hasNext()) { - final JsonElement element = iterator.next(); - final JsonObject obj = element.getAsJsonObject(); - final QueryEntity entity = new QueryEntity(); - - if (obj.has(ID)) { - entity.setId(obj.getAsJsonPrimitive(ID).getAsString()); - queries.add(entity); - } - - if (obj.has("query")) { - entity.setQuery(obj.getAsJsonPrimitive("query").getAsString()); - } - - if (obj.has("started")) { - final String str = obj.getAsJsonPrimitive("started").getAsString(); - - final SimpleDateFormat sdf = new SimpleDateFormat(ALT_DATE_TIME_FORMAT); - try { - entity.setStarted(sdf.parse(str)); - } catch (final ParseException e) { - logger.debug("got ParseException for date string: " + str); - } - } - - if (obj.has("runTime")) { - entity.setRunTime(obj.getAsJsonPrimitive("runTime").getAsDouble()); - } - - } - - return new QueriesResultEntity(queries); - } - } - - public static class QueryTrackingPropertiesEntityDeserializer - implements JsonDeserializer { - - @Override - public QueryTrackingPropertiesEntity deserialize( - final JsonElement json, - final Type typeOfT, - final JsonDeserializationContext context) { - - if (json.isJsonNull()) { - return null; - } - - final JsonObject obj = json.getAsJsonObject(); - final QueryTrackingPropertiesEntity entity = deserializeBaseParameter(obj, - new QueryTrackingPropertiesEntity()); - - if (obj.has("enabled")) { - entity.setEnabled(obj.getAsJsonPrimitive("enabled").getAsBoolean()); - } - - if (obj.has("trackSlowQueries")) { - entity.setTrackSlowQueries(obj.getAsJsonPrimitive("trackSlowQueries").getAsBoolean()); - } - - if (obj.has("maxSlowQueries")) { - entity.setMaxSlowQueries(obj.getAsJsonPrimitive("maxSlowQueries").getAsLong()); - } - - if (obj.has("slowQueryThreshold")) { - entity.setSlowQueryThreshold(obj.getAsJsonPrimitive("slowQueryThreshold").getAsLong()); - } - - if (obj.has("maxQueryStringLength")) { - entity.setMaxQueryStringLength(obj.getAsJsonPrimitive("maxQueryStringLength").getAsLong()); - } - - return entity; - } - - } - - private static JsonObject getFirstResultAsJsonObject(final JsonObject obj) { - if (obj.has(RESULT)) { - if (obj.get(RESULT).isJsonArray()) { - return getElementAsJsonObject(obj.getAsJsonArray(RESULT)); - } else if (obj.get(RESULT).isJsonObject()) { - return obj.getAsJsonObject(RESULT); - } - } - return null; - } - - private static JsonObject getElementAsJsonObject(final JsonArray arr) { - if (arr != null && arr.size() > 0) { - final JsonElement jsonElement = arr.get(0); - if (jsonElement.isJsonObject()) { - return jsonElement.getAsJsonObject(); - } - } - return null; - } - - private static List> getVertices( - final Class vertexClazz, - final JsonDeserializationContext context, - final JsonArray vertices) { - final List> list = new ArrayList>(); - if (vertices != null) { - for (int i = 0, imax = vertices.size(); i < imax; i++) { - final JsonObject vertex = vertices.get(i).getAsJsonObject(); - final VertexEntity ve = getVertex(context, vertex, vertexClazz); - list.add(ve); - } - } - return list; - } - - private static VertexEntity getVertex( - final JsonDeserializationContext context, - final JsonObject vertex, - final Class vertexClazz) { - final VertexEntity ve = deserializeBaseParameter(vertex, new VertexEntity()); - deserializeDocumentParameter(vertex, ve); - if (vertexClazz != null) { - ve.setEntity(context.deserialize(vertex, vertexClazz)); - } else { - ve.setEntity(context.deserialize(vertex, Object.class)); - } - return ve; - } - - private static List> getEdges( - final Class edgeClazz, - final JsonDeserializationContext context, - final JsonArray edges) { - final List> list = new ArrayList>(); - if (edges != null) { - for (int i = 0, imax = edges.size(); i < imax; i++) { - final JsonObject edge = edges.get(i).getAsJsonObject(); - final EdgeEntity ve = context.deserialize(edge, EdgeEntity.class); - list.add(ve); - } - } - return list; - } -} diff --git a/src/main/java/com/arangodb/entity/EntityFactory.java b/src/main/java/com/arangodb/entity/EntityFactory.java deleted file mode 100644 index 9b45a0255..000000000 --- a/src/main/java/com/arangodb/entity/EntityFactory.java +++ /dev/null @@ -1,252 +0,0 @@ -/* - * Copyright (C) 2012 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.entity; - -import java.io.StringWriter; -import java.lang.reflect.Field; -import java.lang.reflect.Type; -import java.util.Collection; -import java.util.Iterator; - -import com.arangodb.annotations.DocumentKey; -import com.arangodb.annotations.Exclude; -import com.arangodb.entity.CollectionEntity.Figures; -import com.arangodb.entity.EntityDeserializers.CollectionKeyOptionDeserializer; -import com.arangodb.entity.marker.VertexEntity; -import com.arangodb.http.JsonSequenceEntity; -import com.google.gson.ExclusionStrategy; -import com.google.gson.FieldAttributes; -import com.google.gson.FieldNamingPolicy; -import com.google.gson.FieldNamingStrategy; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonElement; -import com.google.gson.JsonNull; -import com.google.gson.JsonObject; -import com.google.gson.JsonParser; - -/** - * Entity factory , internally used. - * - * @author tamtam180 - kirscheless at gmail.com - */ -public class EntityFactory { - - private static Gson gson; - private static Gson gsonNull; - - private EntityFactory() { - // this is a helper class - } - - public static GsonBuilder getGsonBuilder() { - return new GsonBuilder().addSerializationExclusionStrategy(new ExcludeExclusionStrategy(true)) - .addDeserializationExclusionStrategy(new ExcludeExclusionStrategy(false)) - .setFieldNamingStrategy(new ArangoFieldNamingStrategy()) - .registerTypeAdapter(CollectionStatus.class, new CollectionStatusTypeAdapter()) - .registerTypeAdapter(CollectionEntity.class, new EntityDeserializers.CollectionEntityDeserializer()) - .registerTypeAdapter(CollectionsEntity.class, new EntityDeserializers.CollectionsEntityDeserializer()) - .registerTypeAdapter(DocumentEntity.class, new EntityDeserializers.DocumentEntityDeserializer()) - .registerTypeAdapter(DocumentsEntity.class, new EntityDeserializers.DocumentsEntityDeserializer()) - .registerTypeAdapter(AqlFunctionsEntity.class, new EntityDeserializers.AqlfunctionsEntityDeserializer()) - .registerTypeAdapter(JobsEntity.class, new EntityDeserializers.JobsEntityDeserializer()) - .registerTypeAdapter(ArangoVersion.class, new EntityDeserializers.VersionDeserializer()) - .registerTypeAdapter(ArangoUnixTime.class, new EntityDeserializers.ArangoUnixTimeDeserializer()) - .registerTypeAdapter(DefaultEntity.class, new EntityDeserializers.DefaultEntityDeserializer()) - .registerTypeAdapter(Figures.class, new EntityDeserializers.FiguresDeserializer()) - .registerTypeAdapter(CursorEntity.class, new EntityDeserializers.CursorEntityDeserializer()) - .registerTypeAdapter(IndexEntity.class, new EntityDeserializers.IndexEntityDeserializer()) - .registerTypeAdapter(IndexesEntity.class, new EntityDeserializers.IndexesEntityDeserializer()) - .registerTypeAdapter(ScalarExampleEntity.class, - new EntityDeserializers.ScalarExampleEntityDeserializer()) - .registerTypeAdapter(SimpleByResultEntity.class, - new EntityDeserializers.SimpleByResultEntityDeserializer()) - .registerTypeAdapter(TransactionResultEntity.class, - new EntityDeserializers.TransactionResultEntityDeserializer()) - .registerTypeAdapter(AdminLogEntity.class, new EntityDeserializers.AdminLogEntryEntityDeserializer()) - .registerTypeAdapter(StatisticsEntity.class, new EntityDeserializers.StatisticsEntityDeserializer()) - .registerTypeAdapter(StatisticsDescriptionEntity.class, - new EntityDeserializers.StatisticsDescriptionEntityDeserializer()) - .registerTypeAdapter(UserEntity.class, new EntityDeserializers.UserEntityDeserializer()) - .registerTypeAdapter(ImportResultEntity.class, new EntityDeserializers.ImportResultEntityDeserializer()) - .registerTypeAdapter(DatabaseEntity.class, new EntityDeserializers.DatabaseEntityDeserializer()) - .registerTypeAdapter(StringsResultEntity.class, - new EntityDeserializers.StringsResultEntityDeserializer()) - .registerTypeAdapter(BooleanResultEntity.class, - new EntityDeserializers.BooleanResultEntityDeserializer()) - .registerTypeAdapter(Endpoint.class, new EntityDeserializers.EndpointDeserializer()) - .registerTypeAdapter(DocumentResultEntity.class, - new EntityDeserializers.DocumentResultEntityDeserializer()) - .registerTypeAdapter(CollectionKeyOptionDeserializer.class, - new EntityDeserializers.CollectionKeyOptionDeserializer()) - .registerTypeAdapter(ReplicationInventoryEntity.class, - new EntityDeserializers.ReplicationInventoryEntityDeserializer()) - .registerTypeAdapter(ReplicationDumpRecord.class, - new EntityDeserializers.ReplicationDumpRecordDeserializer()) - .registerTypeAdapter(ReplicationSyncEntity.class, - new EntityDeserializers.ReplicationSyncEntityDeserializer()) - .registerTypeAdapter(MapAsEntity.class, new EntityDeserializers.MapAsEntityDeserializer()) - .registerTypeAdapter(ReplicationLoggerConfigEntity.class, - new EntityDeserializers.ReplicationLoggerConfigEntityDeserializer()) - .registerTypeAdapter(ReplicationApplierConfigEntity.class, - new EntityDeserializers.ReplicationApplierConfigEntityDeserializer()) - .registerTypeAdapter(ReplicationApplierState.class, - new EntityDeserializers.ReplicationApplierStateDeserializer()) - .registerTypeAdapter(ReplicationApplierStateEntity.class, - new EntityDeserializers.ReplicationApplierStateEntityDeserializer()) - .registerTypeAdapter(ReplicationLoggerStateEntity.class, - new EntityDeserializers.ReplicationLoggerStateEntityDeserializer()) - .registerTypeAdapter(ReplicationLoggerStateEntity.Client.class, - new EntityDeserializers.ReplicationLoggerStateEntityClientDeserializer()) - .registerTypeAdapter(BaseDocument.class, new EntityDeserializers.BaseDocumentDeserializer()) - .registerTypeAdapter(GraphEntity.class, new EntityDeserializers.GraphEntityDeserializer()) - .registerTypeAdapter(GraphsEntity.class, new EntityDeserializers.GraphsEntityDeserializer()) - .registerTypeAdapter(DeletedEntity.class, new EntityDeserializers.DeleteEntityDeserializer()) - .registerTypeAdapter(VertexEntity.class, new EntityDeserializers.VertexEntityDeserializer()) - .registerTypeAdapter(EdgeEntity.class, new EntityDeserializers.EdgeEntityDeserializer()) - .registerTypeAdapter(TraversalEntity.class, new EntityDeserializers.TraversalEntityDeserializer()) - .registerTypeAdapter(ShortestPathEntity.class, new EntityDeserializers.ShortestPathEntityDeserializer()) - .registerTypeAdapter(QueryCachePropertiesEntity.class, - new EntityDeserializers.QueryCachePropertiesEntityDeserializer()) - .registerTypeAdapter(QueriesResultEntity.class, - new EntityDeserializers.QueriesResultEntityDeserializer()) - .registerTypeAdapter(QueryTrackingPropertiesEntity.class, - new EntityDeserializers.QueryTrackingPropertiesEntityDeserializer()) - .setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); - } - - static { - configure(getGsonBuilder()); - } - - /** - * Configures instances of Gson used by this factory. - * - * @param builders - * one or two GsonBuilder instances. If only one is provided it will be used for initializing both - * gson and gsonNull fields (latter with serializeNulls() called - * prior to creating). If two are given - first initializes gson field, second initializes - * gsonNull (used when serialization of nulls is requested). - */ - public static void configure(GsonBuilder... builders) { - if (builders.length < 1) { - throw new IllegalArgumentException("builders"); - } - - gson = builders[0].create(); - - if (builders.length > 1) { - gsonNull = builders[1].create(); - } else { - // use the first one again, but with nulls serialization turned on - gsonNull = builders[0].serializeNulls().create(); - } - } - - public static T createEntity(String jsonText, Type type) { - return gson.fromJson(jsonText, type); - } - - public static String toJsonString(T obj) { - return toJsonString(obj, false); - } - - public static JsonSequenceEntity toJsonSequenceEntity(Iterator itr) { - return new JsonSequenceEntity(itr, gson); - } - - public static String toImportHeaderValues(Collection> headerValues) { - StringWriter writer = new StringWriter(); - for (Collection array : headerValues) { - gson.toJson(array, writer); - writer.write('\n'); - } - writer.flush(); - return writer.toString(); - } - - public static String toJsonString(T obj, boolean includeNullValue) { - if (obj != null && obj.getClass().equals(BaseDocument.class)) { - String tmp = includeNullValue ? gsonNull.toJson(obj) : gson.toJson(obj); - JsonParser jsonParser = new JsonParser(); - JsonElement jsonElement = jsonParser.parse(tmp); - JsonObject jsonObject = jsonElement.getAsJsonObject(); - JsonObject result = jsonObject.getAsJsonObject("properties"); - JsonElement keyObject = jsonObject.get("_key"); - if (keyObject != null && keyObject.getClass() != JsonNull.class) { - result.add("_key", jsonObject.get("_key")); - } - JsonElement handleObject = jsonObject.get("_id"); - if (handleObject != null && handleObject.getClass() != JsonNull.class) { - result.add("_id", jsonObject.get("_id")); - } - // JsonElement revisionValue = jsonObject.get("documentRevision"); - // result.add("_rev", revisionValue); - return result.toString(); - } - return includeNullValue ? gsonNull.toJson(obj) : gson.toJson(obj); - } - - /** - * @param obj - * @param includeNullValue - * @return a JsonElement object - * @since 1.4.0 - */ - public static JsonElement toJsonElement(T obj, boolean includeNullValue) { - return includeNullValue ? gsonNull.toJsonTree(obj) : gson.toJsonTree(obj); - } - - /** - * @author tamtam180 - kirscheless at gmail.com - * @since 1.4.0 - */ - private static class ExcludeExclusionStrategy implements ExclusionStrategy { - private boolean serialize; - - public ExcludeExclusionStrategy(boolean serialize) { - this.serialize = serialize; - } - - @Override - public boolean shouldSkipField(FieldAttributes f) { - Exclude annotation = f.getAnnotation(Exclude.class); - if (annotation != null && (serialize ? annotation.serialize() : annotation.deserialize())) { - return true; - } - return false; - } - - @Override - public boolean shouldSkipClass(Class clazz) { - return false; - } - } - - private static class ArangoFieldNamingStrategy implements FieldNamingStrategy { - private static final String KEY = "_key"; - - @Override - public String translateName(Field f) { - DocumentKey key = f.getAnnotation(DocumentKey.class); - if (key == null) { - return FieldNamingPolicy.IDENTITY.translateName(f); - } - return KEY; - } - } -} diff --git a/src/main/java/com/arangodb/entity/ErrorEntity.java b/src/main/java/com/arangodb/entity/ErrorEntity.java new file mode 100644 index 000000000..cf0cd8c25 --- /dev/null +++ b/src/main/java/com/arangodb/entity/ErrorEntity.java @@ -0,0 +1,58 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.entity; + +/** + * @author Mark - mark at arangodb.com + * + */ +public class ErrorEntity { + + private String errorMessage; + private int code; + private int errorNum; + + public ErrorEntity() { + super(); + } + + /** + * @return a descriptive error message + */ + public String getErrorMessage() { + return errorMessage; + } + + /** + * @return the status code + */ + public int getCode() { + return code; + } + + /** + * @return the server error number + */ + public int getErrorNum() { + return errorNum; + } + +} diff --git a/src/main/java/com/arangodb/entity/FilterCondition.java b/src/main/java/com/arangodb/entity/FilterCondition.java deleted file mode 100644 index 24bbf42c2..000000000 --- a/src/main/java/com/arangodb/entity/FilterCondition.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright (C) 2012,2013 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.entity; - -import java.io.Serializable; - -/** - * @author tamtam180 - kirscheless at gmail.com - * - */ -public class FilterCondition implements Serializable { - - String key; - Object value; - String compare; - - public FilterCondition() { - - } - - public FilterCondition(String key, Object value, String compare) { - this.key = key; - this.value = value; - this.compare = compare; - } - - public String getKey() { - return key; - } - - public Object getValue() { - return value; - } - - public String getCompare() { - return compare; - } - - public void setKey(String key) { - this.key = key; - } - - public void setValue(Object value) { - this.value = value; - } - - public void setCompare(String compare) { - this.compare = compare; - } - -} diff --git a/src/main/java/com/arangodb/entity/GraphEntity.java b/src/main/java/com/arangodb/entity/GraphEntity.java index e1c7d053f..3d8fae3e1 100644 --- a/src/main/java/com/arangodb/entity/GraphEntity.java +++ b/src/main/java/com/arangodb/entity/GraphEntity.java @@ -1,125 +1,63 @@ -/* - * Copyright (C) 2012,2013 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.entity; - -import java.util.List; - -import com.google.gson.annotations.SerializedName; - -/** - * @author tamtam180 - kirscheless at gmail.com - * @since 1.4.0 - */ -public class GraphEntity extends BaseEntity implements DocumentHolder { - - /** - * Revision of graph. - */ - @SerializedName("_rev") - String documentRevision; - - /** - * Id of graph. - */ - @SerializedName("_id") - String documentHandle; - - /** - * Key of graph. - */ - @SerializedName("_key") - String documentKey; - - /** - * List of collections of the graph which are not used in an edge - * definition. - */ - List orphanCollections; - - /** - * The edge definitions of the graph. - */ - EdgeDefinitionsEntity edgeDefinitionsEntity; - - /** - * Name of the graph. - */ - String name; - - @Override - public String getDocumentRevision() { - return documentRevision; - } - - @Override - public String getDocumentHandle() { - return documentHandle; - } - - @Override - public String getDocumentKey() { - return documentKey; - } - - @Override - public void setDocumentRevision(final String documentRevision) { - this.documentRevision = documentRevision; - } - - @Override - public void setDocumentHandle(final String documentHandle) { - this.documentHandle = documentHandle; - } - - @Override - public void setDocumentKey(final String documentKey) { - this.documentKey = documentKey; - } - - public EdgeDefinitionsEntity getEdgeDefinitionsEntity() { - return edgeDefinitionsEntity; - } - - public List getEdgeDefinitions() { - return edgeDefinitionsEntity.getEdgeDefinitions(); - } - - public void setEdgeDefinitionsEntity(final EdgeDefinitionsEntity edgeDefinitionsEntity) { - this.edgeDefinitionsEntity = edgeDefinitionsEntity; - } - - public void setEdgeDefinitions(final List edgeDefinitions) { - this.edgeDefinitionsEntity.setEdgeDefinitions(edgeDefinitions); - } - - public List getOrphanCollections() { - return orphanCollections; - } - - public void setOrphanCollections(final List orphanCollections) { - this.orphanCollections = orphanCollections; - } - - public void setName(final String name) { - this.name = name; - } - - public String getName() { - return name; - } - -} +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.entity; + +import java.util.Collection; + +/** + * @author Mark - mark at arangodb.com + * + * @see API Documentation + */ +public class GraphEntity { + + private String name; + private Collection edgeDefinitions; + private Collection orphanCollections; + private Boolean isSmart; + private Integer numberOfShards; + private String smartGraphAttribute; + + public String getName() { + return name; + } + + public Collection getEdgeDefinitions() { + return edgeDefinitions; + } + + public Collection getOrphanCollections() { + return orphanCollections; + } + + public Boolean getIsSmart() { + return isSmart; + } + + public Integer getNumberOfShards() { + return numberOfShards; + } + + public String getSmartGraphAttribute() { + return smartGraphAttribute; + } + +} diff --git a/src/main/java/com/arangodb/entity/GraphGetCollectionsResultEntity.java b/src/main/java/com/arangodb/entity/GraphGetCollectionsResultEntity.java deleted file mode 100644 index 35121f07e..000000000 --- a/src/main/java/com/arangodb/entity/GraphGetCollectionsResultEntity.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.arangodb.entity; - -import java.util.ArrayList; -import java.util.List; - -/** - * @author gschwab - * - */ -public class GraphGetCollectionsResultEntity extends BaseEntity { - - List collections; - - public List getCollections() { - if (collections == null) { - collections = new ArrayList(); - } - return collections; - } - - public void setCollections(List collections) { - this.collections = collections; - } - -} \ No newline at end of file diff --git a/src/main/java/com/arangodb/entity/GraphsEntity.java b/src/main/java/com/arangodb/entity/GraphsEntity.java deleted file mode 100644 index e574d8cb6..000000000 --- a/src/main/java/com/arangodb/entity/GraphsEntity.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright (C) 2012,2013 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.entity; - -import java.util.List; - -/** - * @author tamtam180 - kirscheless at gmail.com - * @since 1.4.0 - */ -public class GraphsEntity extends BaseEntity { - - List graphs; - - public List getGraphs() { - return graphs; - } - - public void setGraphs(List graphs) { - this.graphs = graphs; - } - -} diff --git a/src/main/java/com/arangodb/entity/ImportResultEntity.java b/src/main/java/com/arangodb/entity/ImportResultEntity.java deleted file mode 100644 index dad369886..000000000 --- a/src/main/java/com/arangodb/entity/ImportResultEntity.java +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Copyright (C) 2012,2013 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.entity; - -import java.util.ArrayList; -import java.util.List; - -/** - * @author tamtam180 - kirscheless at gmail.com - * - */ -public class ImportResultEntity extends BaseEntity { - - private int created; - private int errors; - private int empty; - private int updated; - private int ignored; - private List details; - - public ImportResultEntity() { - super(); - details = new ArrayList(); - } - - public int getCreated() { - return created; - } - - public void setCreated(int created) { - this.created = created; - } - - public int getErrors() { - return errors; - } - - public void setErrors(int errors) { - this.errors = errors; - } - - public int getEmpty() { - return empty; - } - - public void setEmpty(int empty) { - this.empty = empty; - } - - public int getUpdated() { - return updated; - } - - public void setUpdated(int updated) { - this.updated = updated; - } - - public int getIgnored() { - return ignored; - } - - public void setIgnored(int ignored) { - this.ignored = ignored; - } - - public List getDetails() { - return details; - } - - public void setDetails(List details) { - this.details = details; - } - -} diff --git a/src/main/java/com/arangodb/entity/IndexEntity.java b/src/main/java/com/arangodb/entity/IndexEntity.java index 3abc27ab7..cb199d115 100644 --- a/src/main/java/com/arangodb/entity/IndexEntity.java +++ b/src/main/java/com/arangodb/entity/IndexEntity.java @@ -1,142 +1,86 @@ -/* - * Copyright (C) 2012 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.entity; - -import java.util.List; - -/** - * An entity representing an index on a collection - * - * @author tamtam180 - kirscheless at gmail.com - * - */ -public class IndexEntity extends BaseEntity { - - /** - * the index id - */ - String id; - - /** - * the type of the index - * @see com.arangodb.entity.IndexType - */ - IndexType type; - - /** - * the fields the index is defined on - */ - List fields; - - /** - * if the index is a geoIndex and *geoJson* is true, then the order within the list is longitude followed by latitude. - * This corresponds to the format described in http://geojson.org/geojson-spec.html#positions - */ - boolean geoJson; - - /** - * is a newly created index - */ - boolean isNewlyCreated; - - /** - * if true the index is a unique index. - */ - boolean unique; - - /** - * if true the index is sparse - */ - boolean sparse; - - /** - * the maximum amount of documents in case the index type is capped - */ - int size; - - /** - * minimum character length of words to index in case the index type is a fulltext - */ - int minLength; - - /** - * index selectivity estimate (if provided by the index) - */ - double selectivityEstimate; - - public String getId() { - return id; - } - public IndexType getType() { - return type; - } - public List getFields() { - return fields; - } - public boolean isGeoJson() { - return geoJson; - } - public boolean isNewlyCreated() { - return isNewlyCreated; - } - public boolean isUnique() { - return unique; - } - public boolean isSparse() { - return sparse; - } - public int getSize() { - return size; - } - public double getSelectivityEstimate() { - return selectivityEstimate; - } - public void setId(String id) { - this.id = id; - } - public void setType(IndexType type) { - this.type = type; - } - public void setFields(List fields) { - this.fields = fields; - } - public void setGeoJson(boolean getJson) { - this.geoJson = getJson; - } - public void setNewlyCreated(boolean isNewlyCreated) { - this.isNewlyCreated = isNewlyCreated; - } - public void setUnique(boolean unique) { - this.unique = unique; - } - public void setSparse(boolean sparse) { - this.sparse = sparse; - } - public void setSize(int size) { - this.size = size; - } - public int getMinLength() { - return minLength; - } - public void setMinLength(int minLength) { - this.minLength = minLength; - } - public void setSelectivityEstimate(double selectivityEstimate) { - this.selectivityEstimate = selectivityEstimate; - } - -} +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.entity; + +import java.util.Collection; + +/** + * @author Mark - mark at arangodb.com + * + */ +public class IndexEntity { + + private String id; + private IndexType type; + private Collection fields; + private Integer selectivityEstimate; + private Boolean unique; + private Boolean sparse; + private Integer minLength; + private Boolean isNewlyCreated; + private Boolean geoJson; + private Boolean constraint; + + public IndexEntity() { + super(); + } + + public String getId() { + return id; + } + + public IndexType getType() { + return type; + } + + public Collection getFields() { + return fields; + } + + public Integer 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 Boolean getConstraint() { + return constraint; + } + +} diff --git a/src/main/java/com/arangodb/entity/IndexType.java b/src/main/java/com/arangodb/entity/IndexType.java index d18f475f8..45f3ce625 100644 --- a/src/main/java/com/arangodb/entity/IndexType.java +++ b/src/main/java/com/arangodb/entity/IndexType.java @@ -1,41 +1,29 @@ -/* - * Copyright (C) 2012 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.entity; - -/** - * Index Type. - * - * @author tamtam180 - kirscheless at gmail.com - * @see - * Indexes - */ -public enum IndexType { - /** Primary Index */ - PRIMARY, - /** Edge Index */ - EDGE, - /** Geo Index */ - GEO, - /** Hash Index */ - HASH, - /** Skiplist Index */ - SKIPLIST, - /** Fulltext Inex */ - FULLTEXT, - /** Persistent Index */ - PERSISTENT -} +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.entity; + +/** + * @author Mark - mark at arangodb.com + * + */ +public enum IndexType { + primary, hash, skiplist, persistent, geo, geo1, geo2, fulltext +} diff --git a/src/main/java/com/arangodb/entity/IndexesEntity.java b/src/main/java/com/arangodb/entity/IndexesEntity.java deleted file mode 100644 index 635931456..000000000 --- a/src/main/java/com/arangodb/entity/IndexesEntity.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (C) 2012 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.entity; - -import java.util.List; -import java.util.Map; - -/** - * An entity defining an index list - * - * @author tamtam180 - kirscheless at gmail.com - * - */ -public class IndexesEntity extends BaseEntity { - - /** - * the list of index entites - */ - List indexes; - - /** - * a map containing the indices , there ids as keys. - */ - Map identifiers; - - public List getIndexes() { - return indexes; - } - public Map getIdentifiers() { - return identifiers; - } - public void setIndexes(List indexes) { - this.indexes = indexes; - } - public void setIdentifiers(Map identifiers) { - this.identifiers = identifiers; - } - - -} diff --git a/src/main/java/com/arangodb/entity/JobsEntity.java b/src/main/java/com/arangodb/entity/JobsEntity.java deleted file mode 100644 index e3bc8795b..000000000 --- a/src/main/java/com/arangodb/entity/JobsEntity.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright (C) 2012 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.entity; - -import java.util.List; - -/** - * This entity represents a list of job ids. - * - * - * @author tamtam180 - kirscheless at gmail.com - * - */ -public class JobsEntity extends BaseEntity { - - /** - * The enumeration containing the job state - */ - public enum JobState { - DONE, PENDING; - public java.lang.String getName() { - if (this == DONE) { - return "done"; - } - if (this == PENDING) { - return "pending"; - } - return null; - } - } - - private List jobs; - - public JobsEntity(List jobs) { - this.jobs = jobs; - } - - public List getJobs() { - return jobs; - } - - public void setJobs(List jobs) { - this.jobs = jobs; - } -} diff --git a/src/main/java/com/arangodb/entity/KeyOptions.java b/src/main/java/com/arangodb/entity/KeyOptions.java new file mode 100644 index 000000000..005c48fc1 --- /dev/null +++ b/src/main/java/com/arangodb/entity/KeyOptions.java @@ -0,0 +1,78 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.entity; + +/** + * @author Mark - mark at arangodb.com + * + */ +public class KeyOptions { + + private Boolean allowUserKeys; + private KeyType type; + private Integer increment; + private Integer offset; + + 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 Boolean getAllowUserKeys() { + return allowUserKeys; + } + + public void setAllowUserKeys(final Boolean allowUserKeys) { + this.allowUserKeys = allowUserKeys; + } + + public KeyType getType() { + return type; + } + + public void setType(final KeyType type) { + this.type = type; + } + + public Integer getIncrement() { + return increment; + } + + public void setIncrement(final Integer increment) { + this.increment = increment; + } + + public Integer getOffset() { + return offset; + } + + public void setOffset(final Integer offset) { + this.offset = offset; + } + +} diff --git a/src/main/java/com/arangodb/entity/RestrictType.java b/src/main/java/com/arangodb/entity/KeyType.java similarity index 65% rename from src/main/java/com/arangodb/entity/RestrictType.java rename to src/main/java/com/arangodb/entity/KeyType.java index d4a9d2c42..d2a3cb25d 100644 --- a/src/main/java/com/arangodb/entity/RestrictType.java +++ b/src/main/java/com/arangodb/entity/KeyType.java @@ -1,26 +1,29 @@ -/* - * Copyright (C) 2012,2013 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.entity; - -/** - * @author tamtam180 - kirscheless at gmail.com - * - */ -public enum RestrictType { - INCLUDE, - EXCLUDE -} +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.entity; + +/** + * @author Mark - mark at arangodb.com + * + */ +public enum KeyType { + traditional, autoincrement +} diff --git a/src/main/java/com/arangodb/entity/KeyValueEntity.java b/src/main/java/com/arangodb/entity/KeyValueEntity.java deleted file mode 100644 index e9f8ae3c7..000000000 --- a/src/main/java/com/arangodb/entity/KeyValueEntity.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright (C) 2012 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.entity; - -import java.util.Date; -import java.util.Map; - -/** - * @author tamtam180 - kirscheless at gmail.com - * - */ -public class KeyValueEntity extends BaseEntity { - - long id; - boolean saved; - - Date created; - Date expires; - Map attributes; - public long getId() { - return id; - } - public boolean isSaved() { - return saved; - } - public Date getCreated() { - return created; - } - public Date getExpires() { - return expires; - } - public Map getAttributes() { - return attributes; - } - public void setId(long id) { - this.id = id; - } - public void setSaved(boolean saved) { - this.saved = saved; - } - public void setCreated(Date created) { - this.created = created; - } - public void setExpires(Date expires) { - this.expires = expires; - } - public void setAttributes(Map attributes) { - this.attributes = attributes; - } - -} diff --git a/src/main/java/com/arangodb/entity/LogEntity.java b/src/main/java/com/arangodb/entity/LogEntity.java new file mode 100644 index 000000000..c52aa96be --- /dev/null +++ b/src/main/java/com/arangodb/entity/LogEntity.java @@ -0,0 +1,76 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.entity; + +import java.util.List; + +/** + * @author Mark - mark at arangodb.com + * + * @see API + * Documentation + */ +public class LogEntity { + + 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 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 texts of all log entries + */ + public List getText() { + return text; + } + + /** + * @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 new file mode 100644 index 000000000..c39361a81 --- /dev/null +++ b/src/main/java/com/arangodb/entity/LogLevel.java @@ -0,0 +1,50 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.entity; + +/** + * @author Mark - mark at arangodb.com + * + */ +public enum LogLevel { + + FATAL(0), ERROR(1), WARNING(2), INFO(3), DEBUG(4); + + private final int level; + + private LogLevel(final int level) { + this.level = 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; + } + +} diff --git a/src/main/java/com/arangodb/entity/MultiDocumentEntity.java b/src/main/java/com/arangodb/entity/MultiDocumentEntity.java new file mode 100644 index 000000000..256fd4c54 --- /dev/null +++ b/src/main/java/com/arangodb/entity/MultiDocumentEntity.java @@ -0,0 +1,54 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.entity; + +import java.util.Collection; + +/** + * @author Mark - mark at arangodb.com + * + */ +public class MultiDocumentEntity { + + private Collection documents; + private Collection errors; + + public MultiDocumentEntity() { + super(); + } + + public Collection getDocuments() { + return documents; + } + + public void setDocuments(final Collection documents) { + this.documents = documents; + } + + public Collection getErrors() { + return errors; + } + + public void setErrors(final Collection errors) { + this.errors = errors; + } + +} diff --git a/src/main/java/com/arangodb/entity/PathEntity.java b/src/main/java/com/arangodb/entity/PathEntity.java index 5ce6607f9..763a1654f 100644 --- a/src/main/java/com/arangodb/entity/PathEntity.java +++ b/src/main/java/com/arangodb/entity/PathEntity.java @@ -1,77 +1,56 @@ -/** - * Copyright 2004-2015 triAGENS GmbH, Cologne, Germany - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Copyright holder is triAGENS GmbH, Cologne, Germany - * - * @author a-brandt - * @author Copyright 2015, triAGENS GmbH, Cologne, Germany - */ - -package com.arangodb.entity; - -/** - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Copyright holder is triAGENS GmbH, Cologne, Germany - * - * @author a-brandt - * @author Copyright 2015, triAGENS GmbH, Cologne, Germany - */ - -import java.util.List; - -import com.arangodb.entity.marker.VertexEntity; - -/** - * @author a-brandt - */ -public class PathEntity { - - /** - * List of edges. - */ - private List> edges; - - /** - * List of vertices. - */ - private List> vertices; - - public List> getEdges() { - return edges; - } - - public void setEdges(List> edges) { - this.edges = edges; - } - - public List> getVertices() { - return vertices; - } - - public void setVertices(List> vertices) { - this.vertices = vertices; - } - -} +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.entity; + +import java.util.Collection; + +/** + * @author Mark - mark at arangodb.com + * + * @see API + * Documentation + */ +public class PathEntity { + + private Collection edges; + private Collection vertices; + + public PathEntity() { + super(); + } + + public Collection getEdges() { + return edges; + } + + public void setEdges(final Collection edges) { + this.edges = edges; + } + + public Collection getVertices() { + return vertices; + } + + public void setVertices(final Collection vertices) { + this.vertices = vertices; + } + +} diff --git a/src/main/java/com/arangodb/entity/PlainEdgeEntity.java b/src/main/java/com/arangodb/entity/PlainEdgeEntity.java deleted file mode 100644 index 42b3692fa..000000000 --- a/src/main/java/com/arangodb/entity/PlainEdgeEntity.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.arangodb.entity; - -import com.google.gson.annotations.SerializedName; - -public class PlainEdgeEntity extends BaseEntity { - - @SerializedName("_rev") - String documentRevision; - @SerializedName("_id") - String documentHandle; - @SerializedName("_key") - String documentKey; - @SerializedName("_from") - String fromCollection; - @SerializedName("_to") - String toCollection; - - public String getDocumentRevision() { - return documentRevision; - } - - public void setDocumentRevision(final String documentRevision) { - this.documentRevision = documentRevision; - } - - public String getDocumentHandle() { - return documentHandle; - } - - public void setDocumentHandle(final String documentHandle) { - this.documentHandle = documentHandle; - } - - public String getDocumentKey() { - return documentKey; - } - - public void setDocumentKey(final String documentKey) { - this.documentKey = documentKey; - } - - public String getFromCollection() { - return fromCollection; - } - - public void setFromCollection(final String fromCollection) { - this.fromCollection = fromCollection; - } - - public String getToCollection() { - return toCollection; - } - - public void setToCollection(final String toCollection) { - this.toCollection = toCollection; - } - -} diff --git a/src/main/java/com/arangodb/entity/QueriesResultEntity.java b/src/main/java/com/arangodb/entity/QueriesResultEntity.java deleted file mode 100644 index 1c9834959..000000000 --- a/src/main/java/com/arangodb/entity/QueriesResultEntity.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.arangodb.entity; - -import java.util.List; - -public class QueriesResultEntity extends BaseEntity { - - /** - * The list of queries - */ - private List queries; - - public QueriesResultEntity() { - - } - - public QueriesResultEntity(List queries) { - this.queries = queries; - } - - /** - * Returns the list of queries - * - * @return the list of queries - */ - public List getQueries() { - return queries; - } - - /** - * Sets the list of queries - * - * @param queries - * the list of queries - */ - public void setQueries(List queries) { - this.queries = queries; - } - -} diff --git a/src/main/java/com/arangodb/entity/QueryCachePropertiesEntity.java b/src/main/java/com/arangodb/entity/QueryCachePropertiesEntity.java index 614b52da4..97726cbe2 100644 --- a/src/main/java/com/arangodb/entity/QueryCachePropertiesEntity.java +++ b/src/main/java/com/arangodb/entity/QueryCachePropertiesEntity.java @@ -1,84 +1,73 @@ -/* - * Copyright (C) 2012,2013 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.entity; - -/** - * @author a-brandt - */ -public class QueryCachePropertiesEntity extends BaseEntity { - - public enum CacheMode { - off, on, demand; - } - - /** - * The mode the AQL query cache operates in. The mode is one of the - * following values: "off", "on" or "demand". - */ - private CacheMode mode; - - /** - * The maximum number of query results that will be stored per - * database-specific cache. - */ - private Long maxResults; - - public QueryCachePropertiesEntity() { - } - - /** - * Returns the mode the AQL query cache operates in. - * - * @return The mode is one of the following values: "off", "on" or "demand". - */ - public CacheMode getMode() { - return mode; - } - - /** - * Sets the mode the AQL query cache operates in. - * - * @param mode - * The mode is one of the following values: "off", "on" or - * "demand". - */ - public void setMode(CacheMode mode) { - this.mode = mode; - } - - /** - * Returns the maximum number of query results that will be stored per - * database-specific cache. - * - * @return the maximum number - */ - public Long getMaxResults() { - return maxResults; - } - - /** - * Sets the maximum number of query results that will be stored per - * database-specific cache. - * - * @param maxResults - * the maximum number - */ - public void setMaxResults(Long maxResults) { - this.maxResults = maxResults; - } - -} +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.entity; + +/** + * @author Mark - mark at arangodb.com + * + * @see API + * Documentation + */ +public class QueryCachePropertiesEntity { + + public enum CacheMode { + off, on, demand; + } + + private CacheMode mode; + private Long maxResults; + + 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; + } + + /** + * @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; + } + + /** + * @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 689f815d8..9e948d5b8 100644 --- a/src/main/java/com/arangodb/entity/QueryEntity.java +++ b/src/main/java/com/arangodb/entity/QueryEntity.java @@ -1,105 +1,71 @@ -package com.arangodb.entity; - -import java.util.Date; - -public class QueryEntity { - - /** - * the query's id - */ - private String id; - - /** - * the query string (potentially truncated) - */ - private String query; - - /** - * the date and time when the query was started - */ - private Date started; - - /** - * the query's run time up to the point the list of queries was queried - */ - private Double runTime; - - /** - * Returns the query's id - * - * @return the query's id - */ - public String getId() { - return id; - } - - /** - * Sets the query's id - * - * @param id - * the query's id - */ - public void setId(String id) { - this.id = id; - } - - /** - * Returns the query string (potentially truncated) - * - * @return the query string - */ - public String getQuery() { - return query; - } - - /** - * Set the query string - * - * @param query - * the query string - */ - public void setQuery(String query) { - this.query = query; - } - - /** - * Returns the date and time when the query was started - * - * @return the date and time - */ - public Date getStarted() { - return started; - } - - /** - * Sets the date and time when the query was started - * - * @param started - * the date and time - */ - public void setStarted(Date started) { - this.started = started; - } - - /** - * Returns the query's run time up to the point the list of queries was - * queried - * - * @return the query's run time - */ - public Double getRunTime() { - return runTime; - } - - /** - * Sets the query's run time up to the point the list of queries was queried - * - * @param runTime - * the query's run time - */ - - public void setRunTime(Double runTime) { - this.runTime = runTime; - } - -} +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.entity; + +import java.util.Date; + +/** + * @author Mark - mark at arangodb.com + * + */ +public class QueryEntity { + + public static final String PROPERTY_STARTED = "started"; + + private String id; + private String query; + private Date started; + private Double runTime; + + public QueryEntity() { + super(); + } + + /** + * @return the query's id + */ + public String getId() { + return id; + } + + /** + * @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 query's run time up to the point the list of queries was queried + */ + public Double getRunTime() { + return runTime; + } + +} diff --git a/src/main/java/com/arangodb/entity/QueryTrackingPropertiesEntity.java b/src/main/java/com/arangodb/entity/QueryTrackingPropertiesEntity.java index 39d058249..b1a0a9aff 100644 --- a/src/main/java/com/arangodb/entity/QueryTrackingPropertiesEntity.java +++ b/src/main/java/com/arangodb/entity/QueryTrackingPropertiesEntity.java @@ -1,101 +1,130 @@ -/* - * Copyright (C) 2012,2013 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.entity; - -/** - * @author a-brandt - */ -public class QueryTrackingPropertiesEntity extends BaseEntity { - - /** - * if set to true, then queries will be tracked. If set to false, neither - * queries nor slow queries will be tracked. - */ - private Boolean enabled; - - /** - * 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. - */ - private Boolean trackSlowQueries; - - /** - * 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. - */ - private Long maxSlowQueries; - - /** - * 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. - */ - private Long slowQueryThreshold; - - /** - * 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. - */ - private Long maxQueryStringLength; - - public Boolean getEnabled() { - return enabled; - } - - public void setEnabled(Boolean enabled) { - this.enabled = enabled; - } - - public Boolean getTrackSlowQueries() { - return trackSlowQueries; - } - - public void setTrackSlowQueries(Boolean trackSlowQueries) { - this.trackSlowQueries = trackSlowQueries; - } - - public Long getMaxSlowQueries() { - return maxSlowQueries; - } - - public void setMaxSlowQueries(Long maxSlowQueries) { - this.maxSlowQueries = maxSlowQueries; - } - - public Long getSlowQueryThreshold() { - return slowQueryThreshold; - } - - public void setSlowQueryThreshold(Long slowQueryThreshold) { - this.slowQueryThreshold = slowQueryThreshold; - } - - public Long getMaxQueryStringLength() { - return maxQueryStringLength; - } - - public void setMaxQueryStringLength(Long maxQueryStringLength) { - this.maxQueryStringLength = maxQueryStringLength; - } - -} +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.entity; + +/** + * @author Mark - mark at arangodb.com + * + */ +public class QueryTrackingPropertiesEntity { + + private Boolean enabled; + private Boolean trackSlowQueries; + private Long maxSlowQueries; + private Long slowQueryThreshold; + private Long maxQueryStringLength; + + 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; + } + + /** + * @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; + } + + /** + * @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; + } + + /** + * @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; + } + + /** + * @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; + } + + /** + * @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/ReplicationApplierConfigEntity.java b/src/main/java/com/arangodb/entity/ReplicationApplierConfigEntity.java deleted file mode 100644 index 80bb9f35b..000000000 --- a/src/main/java/com/arangodb/entity/ReplicationApplierConfigEntity.java +++ /dev/null @@ -1,143 +0,0 @@ -/* - * Copyright (C) 2012,2013 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.entity; - -/** - * The configuration of the replication applier. The configuration can only be changed while the applier is not running. - * The updated configuration will be saved immediately but only become active with the next start of the applier. - * - * @author tamtam180 - kirscheless at gmail.com - * - */ -public class ReplicationApplierConfigEntity extends BaseEntity { - - /** - * the logger server to connect to (e.g. "tcp://192.168.173.13:8529"). The endpoint must be specified. - */ - String endpoint; - - /** - * the name of the database on the endpoint. If not specified, defaults to the current local database name. - */ - String database; - - /** - * an optional ArangoDB username to use when connecting to the endpoint. - */ - String username; - - /** - * the password to use when connecting to the endpoint. - */ - String password; - - /** - * the maximum number of connection attempts the applier will make in a row. If the applier cannot establish a - * connection to the endpoint in this number of attempts, it will stop itself. - */ - Integer maxConnectRetries; - - /** - * the timeout (in seconds) when attempting to connect to the endpoint. This value is used for each connection attempt. - */ - Integer connectTimeout; - - /** - * the timeout (in seconds) for individual requests to the endpoint. - */ - Integer requestTimeout; - - /** - * the requested maximum size for log transfer packets that is used when the endpoint is contacted. - */ - Integer chunkSize; - - /** - * whether or not to auto-start the replication applier on (next and following) server starts - */ - Boolean autoStart; - - /** - * if set to true, the replication applier will fall to sleep for an increasingly long period in case the logger - * server at the endpoint does not have any more replication events to apply. - */ - Boolean adaptivePolling; - - - - public String getEndpoint() { - return endpoint; - } - public String getDatabase() { - return database; - } - public String getUsername() { - return username; - } - public String getPassword() { - return password; - } - public Integer getMaxConnectRetries() { - return maxConnectRetries; - } - public Integer getConnectTimeout() { - return connectTimeout; - } - public Integer getRequestTimeout() { - return requestTimeout; - } - public Integer getChunkSize() { - return chunkSize; - } - public Boolean getAutoStart() { - return autoStart; - } - public Boolean getAdaptivePolling() { - return adaptivePolling; - } - public void setEndpoint(String endpoint) { - this.endpoint = endpoint; - } - public void setDatabase(String database) { - this.database = database; - } - public void setUsername(String username) { - this.username = username; - } - public void setPassword(String password) { - this.password = password; - } - public void setMaxConnectRetries(Integer maxConnectRetries) { - this.maxConnectRetries = maxConnectRetries; - } - public void setConnectTimeout(Integer connectTimeout) { - this.connectTimeout = connectTimeout; - } - public void setRequestTimeout(Integer requestTimeout) { - this.requestTimeout = requestTimeout; - } - public void setChunkSize(Integer chunkSize) { - this.chunkSize = chunkSize; - } - public void setAutoStart(Boolean autoStart) { - this.autoStart = autoStart; - } - public void setAdaptivePolling(Boolean adaptivePolling) { - this.adaptivePolling = adaptivePolling; - } - -} diff --git a/src/main/java/com/arangodb/entity/ReplicationApplierState.java b/src/main/java/com/arangodb/entity/ReplicationApplierState.java deleted file mode 100644 index c903e1475..000000000 --- a/src/main/java/com/arangodb/entity/ReplicationApplierState.java +++ /dev/null @@ -1,248 +0,0 @@ -/* - * Copyright (C) 2012,2013 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.entity; - -import java.io.Serializable; -import java.util.Date; - -/** - * the state of the replication applier, regardless of whether the applier is - * currently running or not. - * - * @author tamtam180 - kirscheless at gmail.com - * - */ -public class ReplicationApplierState implements Serializable { - - /** - * whether or not the applier is active and running - */ - Boolean running; - - /** - * the last tick value from the continuous replication log the applier has - * applied - */ - Long lastAppliedContinuousTick; - - /** - * the last tick value from the continuous replication log the applier has - * processed. - */ - Long lastProcessedContinuousTick; - - /** - * the last tick value the logger server can provide. - */ - Long lastAvailableContinuousTick; - - /** - * the time on the applier server. - */ - Date time; - - /** - * the total number of requests the applier has made to the endpoint. - */ - Long totalRequests; - - /** - * the total number of failed connection attempts the applier has made. - */ - Long totalFailedConnects; - - /** - * the total number of log events the applier has processed. - */ - Long totalEvents; - - /** - * details about the last error that happened on the applier. - */ - LastError lastError; - - /** - * details about the replication applier progress. - * - * @see com.arangodb.entity.ReplicationApplierState.Progress - */ - Progress progress; - - public static class Progress implements Serializable { - /** - * the date and time the progress was logged - */ - Date time; - - /** - * a textual description of the progress - */ - String message; - - /** - * the current number of failed connection attempts - */ - Long failedConnects; - - public Date getTime() { - return time; - } - - public String getMessage() { - return message; - } - - public Long getFailedConnects() { - return failedConnects; - } - - public void setTime(Date time) { - this.time = time; - } - - public void setMessage(String message) { - this.message = message; - } - - public void setFailedConnects(Long failedConnects) { - this.failedConnects = failedConnects; - } - } - - public static class LastError implements Serializable { - /** - * the date and time the error occurred In case no error has occurred, - * lastError will be empty. - */ - private Date time; - - /** - * a textual error description - */ - private String errorMessage; - - /** - * a numerical error code - */ - private Integer errorNum; - - public Date getTime() { - return time; - } - - public String getErrorMessage() { - return errorMessage; - } - - public Integer getErrorNum() { - return errorNum; - } - - public void setTime(Date time) { - this.time = time; - } - - public void setErrorMessage(String errorMessage) { - this.errorMessage = errorMessage; - } - - public void setErrorNum(Integer errorNum) { - this.errorNum = errorNum; - } - } - - public Boolean getRunning() { - return running; - } - - public Long getLastAppliedContinuousTick() { - return lastAppliedContinuousTick; - } - - public Long getLastProcessedContinuousTick() { - return lastProcessedContinuousTick; - } - - public Long getLastAvailableContinuousTick() { - return lastAvailableContinuousTick; - } - - public Date getTime() { - return time; - } - - public Long getTotalRequests() { - return totalRequests; - } - - public Long getTotalFailedConnects() { - return totalFailedConnects; - } - - public Long getTotalEvents() { - return totalEvents; - } - - public LastError getLastError() { - return lastError; - } - - public Progress getProgress() { - return progress; - } - - public void setRunning(Boolean running) { - this.running = running; - } - - public void setLastAppliedContinuousTick(Long lastAppliedContinuousTick) { - this.lastAppliedContinuousTick = lastAppliedContinuousTick; - } - - public void setLastProcessedContinuousTick(Long lastProcessedContinuousTick) { - this.lastProcessedContinuousTick = lastProcessedContinuousTick; - } - - public void setLastAvailableContinuousTick(Long lastAvailableContinuousTick) { - this.lastAvailableContinuousTick = lastAvailableContinuousTick; - } - - public void setTime(Date time) { - this.time = time; - } - - public void setTotalRequests(Long totalRequests) { - this.totalRequests = totalRequests; - } - - public void setTotalFailedConnects(Long totalFailedConnects) { - this.totalFailedConnects = totalFailedConnects; - } - - public void setTotalEvents(Long totalEvents) { - this.totalEvents = totalEvents; - } - - public void setLastError(LastError lastError) { - this.lastError = lastError; - } - - public void setProgress(Progress progress) { - this.progress = progress; - } - -} diff --git a/src/main/java/com/arangodb/entity/ReplicationApplierStateEntity.java b/src/main/java/com/arangodb/entity/ReplicationApplierStateEntity.java deleted file mode 100644 index 77fe4d01f..000000000 --- a/src/main/java/com/arangodb/entity/ReplicationApplierStateEntity.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Copyright (C) 2012,2013 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.entity; - -/** - * An entity representing a ReplicationApplierState - * - * @author tamtam180 - kirscheless at gmail.com - * - */ -public class ReplicationApplierStateEntity extends BaseEntity { - - /** - * The applier state - * @see com.arangodb.entity.ReplicationApplierState - */ - ReplicationApplierState state; - - /** - * The version of the server - */ - String serverVersion; - - /** - * The server id - */ - String serverId; - - /** - * The endpoint - */ - String endpoint; - - /** - * The database - */ - String database; - - public ReplicationApplierState getState() { - return state; - } - public String getServerVersion() { - return serverVersion; - } - public String getServerId() { - return serverId; - } - public String getEndpoint() { - return endpoint; - } - public String getDatabase() { - return database; - } - public void setState(ReplicationApplierState state) { - this.state = state; - } - public void setServerVersion(String serverVersion) { - this.serverVersion = serverVersion; - } - public void setServerId(String serverId) { - this.serverId = serverId; - } - public void setEndpoint(String endpoint) { - this.endpoint = endpoint; - } - public void setDatabase(String database) { - this.database = database; - } - -} diff --git a/src/main/java/com/arangodb/entity/ReplicationDumpHeader.java b/src/main/java/com/arangodb/entity/ReplicationDumpHeader.java deleted file mode 100644 index cdd9f49d2..000000000 --- a/src/main/java/com/arangodb/entity/ReplicationDumpHeader.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright (C) 2012,2013 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.entity; - -import java.io.Serializable; - -/** - * - * - * @author tamtam180 - kirscheless at gmail.com - * - */ -public class ReplicationDumpHeader implements Serializable { - - Long lasttick; - Boolean checkmore; - Long lastincluded; - Boolean active; - - public Long getLasttick() { - return lasttick; - } - public Boolean getCheckmore() { - return checkmore; - } - public Long getLastincluded() { - return lastincluded; - } - public Boolean getActive() { - return active; - } - public void setLasttick(Long lasttick) { - this.lasttick = lasttick; - } - public void setCheckmore(Boolean checkmore) { - this.checkmore = checkmore; - } - public void setLastincluded(Long lastincluded) { - this.lastincluded = lastincluded; - } - public void setActive(Boolean active) { - this.active = active; - } - -} diff --git a/src/main/java/com/arangodb/entity/ReplicationDumpRecord.java b/src/main/java/com/arangodb/entity/ReplicationDumpRecord.java deleted file mode 100644 index 7dfac9e8a..000000000 --- a/src/main/java/com/arangodb/entity/ReplicationDumpRecord.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright (C) 2012,2013 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.entity; - -import java.io.Serializable; - -/** - * @author tamtam180 - kirscheless at gmail.com - * - */ -public class ReplicationDumpRecord implements Serializable { - - long tick; - ReplicationEventType type; - String key; - String rev; - DocumentEntity data; - - public long getTick() { - return tick; - } - - public ReplicationEventType getType() { - return type; - } - - public String getKey() { - return key; - } - - public String getRev() { - return rev; - } - - public DocumentEntity getData() { - return data; - } - - public void setTick(final long tick) { - this.tick = tick; - } - - public void setType(final ReplicationEventType type) { - this.type = type; - } - - public void setKey(final String key) { - this.key = key; - } - - public void setRev(final String rev) { - this.rev = rev; - } - - public void setData(final DocumentEntity data) { - this.data = data; - } - -} diff --git a/src/main/java/com/arangodb/entity/ReplicationEventType.java b/src/main/java/com/arangodb/entity/ReplicationEventType.java deleted file mode 100644 index d76b79a59..000000000 --- a/src/main/java/com/arangodb/entity/ReplicationEventType.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright (C) 2012,2013 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.entity; - -import java.util.TreeMap; - -/** - * @author tamtam180 - kirscheless at gmail.com - * @since 1.4.0 - * @see ArangoDB - * documentation - * - */ -public enum ReplicationEventType { - - LOGGER_STOPPED(1000), - LOGGER_STARTED(1001), - - COLLECTION_CREATED(2000), - COLLECTION_DROPPED(2001), - COLLECTION_RENAMED(2002), - COLLECTION_PROP_CHANGED(2003), - - INDEX_CREATED(2100), - INDEX_DROPPED(2101), - - TRANSACTION_STARTED(2200), - TRANSACTION_COMMITED(2201), - - DOCUMENT_UPSERT(2300), - EDGE_UPSERT(2301), - DELETION(2302); - - private static TreeMap lookup = new TreeMap(); - static { - for (ReplicationEventType type : ReplicationEventType.values()) { - lookup.put(type.getType(), type); - } - } - - private final int type; - - private ReplicationEventType(int type) { - this.type = type; - // ここでMapに入れた方がスマートだが、初期化エラーが出る - } - - public int getType() { - return type; - } - - public static ReplicationEventType valueOf(int type) { - return lookup.get(type); - } - -} diff --git a/src/main/java/com/arangodb/entity/ReplicationInventoryEntity.java b/src/main/java/com/arangodb/entity/ReplicationInventoryEntity.java deleted file mode 100644 index b95be0cc6..000000000 --- a/src/main/java/com/arangodb/entity/ReplicationInventoryEntity.java +++ /dev/null @@ -1,135 +0,0 @@ -/* - * Copyright (C) 2012,2013 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.entity; - -import java.io.Serializable; -import java.util.List; - -/** - * @author tamtam180 - kirscheless at gmail.com - * - */ -public class ReplicationInventoryEntity extends BaseEntity { - - List collections; - ReplicationState state; - long tick; - - public List getCollections() { - return collections; - } - public ReplicationState getState() { - return state; - } - public long getTick() { - return tick; - } - public void setCollections(List collections) { - this.collections = collections; - } - public void setState(ReplicationState state) { - this.state = state; - } - public void setTick(long tick) { - this.tick = tick; - } - - public static class CollectionParameter implements Serializable { - int version; - CollectionType type; - long cid; - boolean deleted; - boolean doCompact; - long maximalSize; - String name; - boolean isVolatile; - boolean waitForSync; - public int getVersion() { - return version; - } - public CollectionType getType() { - return type; - } - public long getCid() { - return cid; - } - public boolean isDeleted() { - return deleted; - } - public boolean isDoCompact() { - return doCompact; - } - public long getMaximalSize() { - return maximalSize; - } - public String getName() { - return name; - } - public boolean isVolatile() { - return isVolatile; - } - public boolean isWaitForSync() { - return waitForSync; - } - public void setVersion(int version) { - this.version = version; - } - public void setType(CollectionType type) { - this.type = type; - } - public void setCid(long cid) { - this.cid = cid; - } - public void setDeleted(boolean deleted) { - this.deleted = deleted; - } - public void setDoCompact(boolean doCompact) { - this.doCompact = doCompact; - } - public void setMaximalSize(long maximalSize) { - this.maximalSize = maximalSize; - } - public void setName(String name) { - this.name = name; - } - public void setVolatile(boolean isVolatile) { - this.isVolatile = isVolatile; - } - public void setWaitForSync(boolean waitForSync) { - this.waitForSync = waitForSync; - } - } - - public static class Collection implements Serializable { - CollectionParameter parameter; - List indexes; - public CollectionParameter getParameter() { - return parameter; - } - public List getIndexes() { - return indexes; - } - public void setParameter(CollectionParameter parameter) { - this.parameter = parameter; - } - public void setIndexes(List indexes) { - this.indexes = indexes; - } - - } - -} diff --git a/src/main/java/com/arangodb/entity/ReplicationLoggerConfigEntity.java b/src/main/java/com/arangodb/entity/ReplicationLoggerConfigEntity.java deleted file mode 100644 index 612d58461..000000000 --- a/src/main/java/com/arangodb/entity/ReplicationLoggerConfigEntity.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright (C) 2012,2013 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.entity; - - -/** - * @author tamtam180 - kirscheless at gmail.com - * - */ -public class ReplicationLoggerConfigEntity extends BaseEntity { - - boolean autoStart; - boolean logRemoteChanges; - long maxEvents; - long maxEventsSize; - - public boolean isAutoStart() { - return autoStart; - } - public boolean isLogRemoteChanges() { - return logRemoteChanges; - } - public long getMaxEvents() { - return maxEvents; - } - public long getMaxEventsSize() { - return maxEventsSize; - } - public void setAutoStart(boolean autoStart) { - this.autoStart = autoStart; - } - public void setLogRemoteChanges(boolean logRemoteChanges) { - this.logRemoteChanges = logRemoteChanges; - } - public void setMaxEvents(long maxEvents) { - this.maxEvents = maxEvents; - } - public void setMaxEventsSize(long maxEventsSize) { - this.maxEventsSize = maxEventsSize; - } - -} diff --git a/src/main/java/com/arangodb/entity/ReplicationLoggerStateEntity.java b/src/main/java/com/arangodb/entity/ReplicationLoggerStateEntity.java deleted file mode 100644 index f9963ace1..000000000 --- a/src/main/java/com/arangodb/entity/ReplicationLoggerStateEntity.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Copyright (C) 2012,2013 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.entity; - -import java.io.Serializable; -import java.util.Date; -import java.util.List; - -/** - * @author tamtam180 - kirscheless at gmail.com - * @since 1.4.0 - */ -public class ReplicationLoggerStateEntity extends BaseEntity { - - ReplicationState state; - String serverVersion; - String serverId; - List clients; - - public ReplicationState getState() { - return state; - } - - public String getServerVersion() { - return serverVersion; - } - - public String getServerId() { - return serverId; - } - - public List getClients() { - return clients; - } - - public void setState(ReplicationState state) { - this.state = state; - } - - public void setServerVersion(String serverVersion) { - this.serverVersion = serverVersion; - } - - public void setServerId(String serverId) { - this.serverId = serverId; - } - - public void setClients(List clients) { - this.clients = clients; - } - - public static class Client implements Serializable { - String serverId; - Long lastServedTick; - Date time; - public String getServerId() { - return serverId; - } - public Long getLastServedTick() { - return lastServedTick; - } - public Date getTime() { - return time; - } - public void setServerId(String serverId) { - this.serverId = serverId; - } - public void setLastServedTick(Long lastServedTick) { - this.lastServedTick = lastServedTick; - } - public void setTime(Date time) { - this.time = time; - } - } - -} diff --git a/src/main/java/com/arangodb/entity/ReplicationState.java b/src/main/java/com/arangodb/entity/ReplicationState.java deleted file mode 100644 index 6888e8d9f..000000000 --- a/src/main/java/com/arangodb/entity/ReplicationState.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright (C) 2012,2013 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.entity; - -import java.io.Serializable; -import java.util.Date; - -/** - * @author tamtam180 - kirscheless at gmail.com - * - */ -public class ReplicationState implements Serializable { - - boolean running; - long lastLogTick; - long totalEvents; - Date time; - - public boolean isRunning() { - return running; - } - public long getLastLogTick() { - return lastLogTick; - } - public long getTotalEvents() { - return totalEvents; - } - public Date getTime() { - return time; - } - public void setRunning(boolean running) { - this.running = running; - } - public void setLastLogTick(long lastLogTick) { - this.lastLogTick = lastLogTick; - } - public void setTotalEvents(long totalEvents) { - this.totalEvents = totalEvents; - } - public void setTime(Date time) { - this.time = time; - } - -} diff --git a/src/main/java/com/arangodb/entity/ReplicationSyncEntity.java b/src/main/java/com/arangodb/entity/ReplicationSyncEntity.java deleted file mode 100644 index 7272eb6aa..000000000 --- a/src/main/java/com/arangodb/entity/ReplicationSyncEntity.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright (C) 2012,2013 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.entity; - -import java.util.List; - -/** - * Result of a full data synchronization from a remote endpoint into the local ArangoDB database. - * - * @author tamtam180 - kirscheless at gmail.com - * - */ -public class ReplicationSyncEntity extends BaseEntity { - - /** - * a list of collections that were transferred from the endpoint - */ - List collections; - - /** - * the last log tick on the endpoint at the time the transfer was started. Use this value as the from value when - * starting the continuous synchronization later. - */ - long lastLogTick; - - public List getCollections() { - return collections; - } - public long getLastLogTick() { - return lastLogTick; - } - public void setCollections(List collections) { - this.collections = collections; - } - public void setLastLogTick(long lastLogTick) { - this.lastLogTick = lastLogTick; - } - -} diff --git a/src/main/java/com/arangodb/entity/ScalarExampleEntity.java b/src/main/java/com/arangodb/entity/ScalarExampleEntity.java deleted file mode 100644 index 55cce435c..000000000 --- a/src/main/java/com/arangodb/entity/ScalarExampleEntity.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright (C) 2012 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.entity; - - -/** - * @author tamtam180 - kirscheless at gmail.com - * - */ -public class ScalarExampleEntity extends BaseEntity { - - //transient JsonElement _documentJson; - DocumentEntity document; - - public DocumentEntity getDocument() { - return document; - } - - public void setDocument(DocumentEntity document) { - this.document = document; - } - -} diff --git a/src/main/java/com/arangodb/entity/ShortestPathEntity.java b/src/main/java/com/arangodb/entity/ShortestPathEntity.java deleted file mode 100644 index a36b1e65e..000000000 --- a/src/main/java/com/arangodb/entity/ShortestPathEntity.java +++ /dev/null @@ -1,87 +0,0 @@ -/** - * Copyright 2004-2015 triAGENS GmbH, Cologne, Germany - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Copyright holder is triAGENS GmbH, Cologne, Germany - * - * @author a-brandt - * @author Copyright 2015, triAGENS GmbH, Cologne, Germany - */ - -package com.arangodb.entity; - -import java.util.List; - -import com.arangodb.entity.marker.VertexEntity; - -/** - * @author a-brandt - */ -public class ShortestPathEntity extends BaseEntity { - - /** - * path distance - */ - private Long distance; - - /** - * List of edges of the shortest path. - */ - private List> edges; - - /** - * List of vertices of the shortest path. (first vertex is the start vertex - * and the last vertex is the end vertex) - */ - private List> vertices; - - /** - * Retuns the distance - * - * @return the distance - */ - public Long getDistance() { - return distance; - } - - public void setDistance(Long distance) { - this.distance = distance; - } - - /** - * Returns the list of edges of the shortest path. - * - * @return the list of edges of the shortest path. - */ - public List> getEdges() { - return edges; - } - - public void setEdges(List> edges) { - this.edges = edges; - } - - /** - * Returns the list of vertices of the shortest path. - * - * @return the list of vertices of the shortest path. - */ - public List> getVertices() { - return vertices; - } - - public void setVertices(List> vertices) { - this.vertices = vertices; - } - -} diff --git a/src/main/java/com/arangodb/entity/SimpleByResultEntity.java b/src/main/java/com/arangodb/entity/SimpleByResultEntity.java deleted file mode 100644 index f9cca998a..000000000 --- a/src/main/java/com/arangodb/entity/SimpleByResultEntity.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright (C) 2012,2013 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.entity; - -/** - * @author tamtam180 - kirscheless at gmail.com - * - */ -public class SimpleByResultEntity extends BaseEntity { - - int count; - - int updated; - int replaced; - int deleted; - - public int getCount() { - return count; - } - public int getUpdated() { - return updated; - } - public int getReplaced() { - return replaced; - } - public int getDeleted() { - return deleted; - } - public void setCount(int count) { - this.count = count; - } - public void setUpdated(int updated) { - this.updated = updated; - } - public void setReplaced(int replaced) { - this.replaced = replaced; - } - public void setDeleted(int deleted) { - this.deleted = deleted; - } - -} diff --git a/src/main/java/com/arangodb/entity/StatisticsDescriptionEntity.java b/src/main/java/com/arangodb/entity/StatisticsDescriptionEntity.java deleted file mode 100644 index 9f9b5484f..000000000 --- a/src/main/java/com/arangodb/entity/StatisticsDescriptionEntity.java +++ /dev/null @@ -1,126 +0,0 @@ -/* - * Copyright (C) 2012,2013 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.entity; - -import java.io.Serializable; -import java.math.BigDecimal; -import java.util.List; - -/** - * @author tamtam180 - kirscheless at gmail.com - * - */ -public class StatisticsDescriptionEntity extends BaseEntity { - - List groups; - List
figures; - - public List getGroups() { - return groups; - } - - public List
getFigures() { - return figures; - } - - public void setGroups(List groups) { - this.groups = groups; - } - - public void setFigures(List
figures) { - this.figures = figures; - } - - - public static class Group implements Serializable { - String group; - String name; - String description; - public String getGroup() { - return group; - } - public String getName() { - return name; - } - public String getDescription() { - return description; - } - public void setGroup(String group) { - this.group = group; - } - public void setName(String name) { - this.name = name; - } - public void setDescription(String description) { - this.description = description; - } - - } - - public static class Figure implements Serializable { - String group; - String identifier; - String name; - String description; - String type; - String units; - BigDecimal[] cuts; - public String getGroup() { - return group; - } - public String getIdentifier() { - return identifier; - } - public String getName() { - return name; - } - public String getDescription() { - return description; - } - public String getType() { - return type; - } - public String getUnits() { - return units; - } - public BigDecimal[] getCuts() { - return cuts; - } - public void setGroup(String group) { - this.group = group; - } - public void setIdentifier(String identifier) { - this.identifier = identifier; - } - public void setName(String name) { - this.name = name; - } - public void setDescription(String description) { - this.description = description; - } - public void setType(String type) { - this.type = type; - } - public void setUnits(String units) { - this.units = units; - } - public void setCuts(BigDecimal[] cuts) { - this.cuts = cuts; - } - } - -} diff --git a/src/main/java/com/arangodb/entity/StatisticsEntity.java b/src/main/java/com/arangodb/entity/StatisticsEntity.java deleted file mode 100644 index 90e7c06e5..000000000 --- a/src/main/java/com/arangodb/entity/StatisticsEntity.java +++ /dev/null @@ -1,190 +0,0 @@ -/* - * Copyright (C) 2012,2013 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.entity; - -import java.io.Serializable; -import java.util.Map; - -/** - * @author tamtam180 - kirscheless at gmail.com - * @author gschwab - * - */ -public class StatisticsEntity extends BaseEntity { - - System system; - Client client; - Server server; - - public System getSystem() { - return system; - } - - public Client getClient() { - return client; - } - - public Server getServer() { - return server; - } - - public void setSystem(System system) { - this.system = system; - } - - public void setClient(Client client) { - this.client = client; - } - - public void setServer(Server server) { - this.server = server; - } - - public static class FigureValue implements Serializable { - double sum; - long count; - long[] counts; - - public double getSum() { - return sum; - } - - public long getCount() { - return count; - } - - public long[] getCounts() { - return counts; - } - - public void setSum(double sum) { - this.sum = sum; - } - - public void setCount(long count) { - this.count = count; - } - - public void setCounts(long[] counts) { - this.counts = counts; - } - - } - - public static class Client implements Serializable { - int httpConnections; - Map figures; - - public int getHttpConnections() { - return httpConnections; - } - - public Map getFigures() { - return figures; - } - - public void setHttpConnections(int httpConnections) { - this.httpConnections = httpConnections; - } - - public void setFigures(Map figures) { - this.figures = figures; - } - } - - public static class Server implements Serializable { - double uptime; - - public double getUptime() { - return uptime; - } - - public void setUptime(double uptime) { - this.uptime = uptime; - } - - } - - public static class System implements Serializable { - - long minorPageFaults; - long majorPageFaults; - double userTime; - double systemTime; - int numberOfThreads; - long residentSize; - long virtualSize; - - public long getMinorPageFaults() { - return minorPageFaults; - } - - public long getMajorPageFaults() { - return majorPageFaults; - } - - public double getUserTime() { - return userTime; - } - - public double getSystemTime() { - return systemTime; - } - - public int getNumberOfThreads() { - return numberOfThreads; - } - - public long getResidentSize() { - return residentSize; - } - - public long getVirtualSize() { - return virtualSize; - } - - public void setMinorPageFaults(long minorPageFaults) { - this.minorPageFaults = minorPageFaults; - } - - public void setMajorPageFaults(long majorPageFaults) { - this.majorPageFaults = majorPageFaults; - } - - public void setUserTime(double userTime) { - this.userTime = userTime; - } - - public void setSystemTime(double systemTime) { - this.systemTime = systemTime; - } - - public void setNumberOfThreads(int numberOfThreads) { - this.numberOfThreads = numberOfThreads; - } - - public void setResidentSize(long residentSize) { - this.residentSize = residentSize; - } - - public void setVirtualSize(long virtualSize) { - this.virtualSize = virtualSize; - } - - } - -} diff --git a/src/main/java/com/arangodb/entity/StringsResultEntity.java b/src/main/java/com/arangodb/entity/StringsResultEntity.java deleted file mode 100644 index 3874a5e49..000000000 --- a/src/main/java/com/arangodb/entity/StringsResultEntity.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright (C) 2012,2013 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.entity; - -import java.util.List; - -/** - * @author tamtam180 - kirscheless at gmail.com - * @author gschwab - * - */ -public class StringsResultEntity extends BaseEntity { - - /** - * List of strings - */ - List result; - - public List getResult() { - return result; - } - - public void setResult(List result) { - this.result = result; - } - -} diff --git a/src/main/java/com/arangodb/entity/TransactionEntity.java b/src/main/java/com/arangodb/entity/TransactionEntity.java deleted file mode 100644 index a5d62b5dd..000000000 --- a/src/main/java/com/arangodb/entity/TransactionEntity.java +++ /dev/null @@ -1,115 +0,0 @@ -/* - * Copyright (C) 2012 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.entity; - -import java.util.ArrayList; -import java.util.List; - -/** - * @author tamtam180 - kirscheless at gmail.com - * - */ -public class TransactionEntity extends BaseEntity { - - public static class ReadWriteCollections { - - private List read = new ArrayList(); - - private List write = new ArrayList(); - - private boolean allowImplicit = true; - - public boolean isAllowImplicit() { - return allowImplicit; - } - - public void setAllowImplicit(boolean allowImplicit) { - this.allowImplicit = allowImplicit; - } - } - - ReadWriteCollections collections = new ReadWriteCollections(); - - String action; - - Boolean waitForSync; - - int lockTimeout; - - Object params; - - public TransactionEntity(String action) { - this.action = action; - } - - public ReadWriteCollections getCollections() { - return collections; - } - - public void setCollections(ReadWriteCollections collections) { - this.collections = collections; - } - - public void addReadCollection(String collection) { - this.collections.read.add(collection); - } - - public void addWriteCollection(String collection) { - this.collections.write.add(collection); - } - - /** - * @param allowImplicit - * allows(true)/ disallows(false) read access to other - * collections than specified. Default is true. - */ - public void setAllowImplicit(final boolean allowImplicit) { - collections.setAllowImplicit(allowImplicit); - } - - public String getAction() { - return action; - } - - public void setAction(String action) { - this.action = action; - } - - public Boolean getWaitForSync() { - return waitForSync; - } - - public void setWaitForSync(Boolean waitForSync) { - this.waitForSync = waitForSync; - } - - public int getLockTimeout() { - return lockTimeout; - } - - public void setLockTimeout(int lockTimeout) { - this.lockTimeout = lockTimeout; - } - - public Object getParams() { - return params; - } - - public void setParams(Object params) { - this.params = params; - } -} diff --git a/src/main/java/com/arangodb/entity/TransactionResultEntity.java b/src/main/java/com/arangodb/entity/TransactionResultEntity.java deleted file mode 100644 index 550f3dd15..000000000 --- a/src/main/java/com/arangodb/entity/TransactionResultEntity.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright (C) 2012 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.entity; - -import com.google.gson.JsonObject; - -/** - * @author tamtam180 - kirscheless at gmail.com - * @author gschwab - * - */ -public class TransactionResultEntity extends BaseEntity { - - /** - * Result object of transaction. - */ - private Object result; - - public JsonObject getResultAsJsonObject() { - return (JsonObject) result; - } - - public long getResultAsLong() { - java.lang.Number number = (java.lang.Number) this.result; - return number.longValue(); - } - - public double getResultAsDouble() { - java.lang.Number number = (java.lang.Number) this.result; - return number.doubleValue(); - } - - public byte getResultAsByte() { - java.lang.Number number = (java.lang.Number) this.result; - return number.byteValue(); - } - - public float getResultAsFloat() { - java.lang.Number number = (java.lang.Number) this.result; - return number.floatValue(); - } - - public int getResultAsInt() { - java.lang.Number number = (java.lang.Number) this.result; - return number.intValue(); - } - - public boolean getResultAsBoolean() { - return (Boolean) result; - } - - public String getResultAsString() { - return (String) result; - } - - public void setResult(Object result) { - this.result = result; - } -} diff --git a/src/main/java/com/arangodb/entity/TraversalEntity.java b/src/main/java/com/arangodb/entity/TraversalEntity.java index 642fcf524..9e3119572 100644 --- a/src/main/java/com/arangodb/entity/TraversalEntity.java +++ b/src/main/java/com/arangodb/entity/TraversalEntity.java @@ -1,68 +1,56 @@ -/** - * Copyright 2004-2015 triAGENS GmbH, Cologne, Germany - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Copyright holder is triAGENS GmbH, Cologne, Germany - * - * @author a-brandt - * @author Copyright 2015, triAGENS GmbH, Cologne, Germany - */ - -package com.arangodb.entity; - -import java.util.List; - -import com.arangodb.entity.marker.VertexEntity; - -/** - * @author a-brandt - */ -public class TraversalEntity extends BaseEntity { - - /** - * List of vertices. - */ - private List> vertices; - - /** - * List of paths. - */ - private List> paths; - - /** - * get the traversal vertices - * - * @return list of VertexEntity objects - */ - public List> getVertices() { - return vertices; - } - - public void setVertices(List> vertices) { - this.vertices = vertices; - } - - /** - * get the traversal path - * - * @return list of PathEntity objects - */ - public List> getPaths() { - return paths; - } - - public void setPaths(List> paths) { - this.paths = paths; - } - -} +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.entity; + +import java.util.Collection; + +/** + * @author Mark - mark at arangodb.com + * + * @see API + * Documentation + */ +public class TraversalEntity { + + private Collection vertices; + private Collection> paths; + + public TraversalEntity() { + super(); + } + + public Collection getVertices() { + return vertices; + } + + public void setVertices(final Collection vertices) { + this.vertices = vertices; + } + + public Collection> getPaths() { + return 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 f384f55e7..f3fe331a4 100644 --- a/src/main/java/com/arangodb/entity/UserEntity.java +++ b/src/main/java/com/arangodb/entity/UserEntity.java @@ -1,93 +1,62 @@ -/* - * Copyright (C) 2012,2013 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.entity; - -import java.util.Map; - -import com.google.gson.annotations.SerializedName; - -/** - * @author tamtam180 - kirscheless at gmail.com - * @author gschwab - */ -public class UserEntity extends BaseEntity { - - /** - * Name of the user. - */ - @SerializedName("username") - String username; - - /** - * Password of the user. - */ - @SerializedName("passwd") - String password; - - /** - * Indicates, if user is active. - */ - Boolean active; - - /** - * Additional information on user. - */ - Map extra; - - public UserEntity() { - } - - public UserEntity(String username, String password, Boolean active, Map extra) { - this.username = username; - this.password = password; - this.active = active; - this.extra = extra; - } - - public String getUsername() { - return username; - } - - public String getPassword() { - return password; - } - - public Boolean isActive() { - return active; - } - - public Map getExtra() { - return extra; - } - - public void setUsername(String username) { - this.username = username; - } - - public void setPassword(String password) { - this.password = password; - } - - public void setActive(Boolean active) { - this.active = active; - } - - public void setExtra(Map extra) { - this.extra = extra; - } - -} +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.entity; + +import java.util.Map; + +/** + * @author Mark - mark at arangodb.com + * + * @see API Documentation + */ +public class UserEntity { + + 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/UsersEntity.java b/src/main/java/com/arangodb/entity/UsersEntity.java deleted file mode 100644 index df5ee7cdc..000000000 --- a/src/main/java/com/arangodb/entity/UsersEntity.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.arangodb.entity; - -import java.util.List; -import java.util.Map; - -/** - * @author a-brandt - * @author gschwab - * - */ -public class UsersEntity extends BaseEntity { - - /** - * List of users. - */ - private List users; - - /** - * Map of users. - */ - private Map names; - - public List getUsers() { - return users; - } - - public void setUsers(List users) { - this.users = users; - } - - public Map getNames() { - return names; - } - - public void setNames(Map names) { - this.names = names; - } - -} diff --git a/src/main/java/com/arangodb/entity/DefaultEntity.java b/src/main/java/com/arangodb/entity/VertexEntity.java similarity index 62% rename from src/main/java/com/arangodb/entity/DefaultEntity.java rename to src/main/java/com/arangodb/entity/VertexEntity.java index 831225d1d..1f5395856 100644 --- a/src/main/java/com/arangodb/entity/DefaultEntity.java +++ b/src/main/java/com/arangodb/entity/VertexEntity.java @@ -1,32 +1,33 @@ -/* - * Copyright (C) 2012 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.entity; - -/** - * A default entity extending the base entity . This is used mostly as a result - * object for empty server responses - * - * @author tamtam180 - kirscheless at gmail.com - * - */ -public class DefaultEntity extends BaseEntity { - - public DefaultEntity() { - // do nothing here - } - -} +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.entity; + +/** + * @author Mark - mark at arangodb.com + * + */ +public class VertexEntity extends DocumentEntity { + + public VertexEntity() { + super(); + } + +} diff --git a/src/main/java/com/arangodb/entity/StreamEntity.java b/src/main/java/com/arangodb/entity/VertexUpdateEntity.java similarity index 52% rename from src/main/java/com/arangodb/entity/StreamEntity.java rename to src/main/java/com/arangodb/entity/VertexUpdateEntity.java index 39e814909..10485a445 100644 --- a/src/main/java/com/arangodb/entity/StreamEntity.java +++ b/src/main/java/com/arangodb/entity/VertexUpdateEntity.java @@ -1,49 +1,42 @@ -/* - * Copyright (C) 2012,2013 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.entity; - -import java.io.InputStream; - -/** - * @author tamtam180 - kirscheless at gmail.com - * @author gschwab - * - */ -public class StreamEntity extends BaseEntity { - - /** - * Input stream. - */ - InputStream stream; - - public StreamEntity() { - // do nothing here - } - - public StreamEntity(InputStream stream) { - this.stream = stream; - } - - public InputStream getStream() { - return stream; - } - - public void setStream(InputStream stream) { - this.stream = stream; - } - -} +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.entity; + +import com.arangodb.velocypack.annotations.SerializedName; + +/** + * @author Mark - mark at arangodb.com + * + */ +public class VertexUpdateEntity extends DocumentEntity { + + @SerializedName("_oldRev") + private String oldRev; + + public VertexUpdateEntity() { + super(); + } + + public String getOldRev() { + return oldRev; + } + +} diff --git a/src/main/java/com/arangodb/entity/WarningEntity.java b/src/main/java/com/arangodb/entity/WarningEntity.java deleted file mode 100644 index 5d9977617..000000000 --- a/src/main/java/com/arangodb/entity/WarningEntity.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright (C) 2012,2013 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.entity; - -/** - * @author a-brandt - */ -public class WarningEntity { - - /** - * a warning code - */ - Long code; - - /** - * a warning message - */ - String message; - - public WarningEntity() { - // do nothing here - } - - public WarningEntity(Long code, String message) { - this.code = code; - this.message = message; - } - - /** - * returns the warning code - * - * @return a warning code - */ - public Long getCode() { - return code; - } - - public void setCode(Long code) { - this.code = code; - } - - /** - * returns a warning message - * - * @return a warning message - */ - public String getMessage() { - return message; - } - - public void setMessage(String message) { - this.message = message; - } - - @Override - public String toString() { - return "WarningEntity [code=" + code + ", message=" + message + "]"; - } - -} diff --git a/src/main/java/com/arangodb/entity/marker/MissingInstanceCreater.java b/src/main/java/com/arangodb/entity/marker/MissingInstanceCreater.java deleted file mode 100644 index 92479f2d9..000000000 --- a/src/main/java/com/arangodb/entity/marker/MissingInstanceCreater.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (C) 2012,2013 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.entity.marker; - -import java.util.HashMap; - -import com.arangodb.entity.BaseEntity; -import com.arangodb.entity.DocumentEntity; - -/** - * @author tamtam180 - kirscheless at gmail.com - * @since 1.4.0 - */ -public class MissingInstanceCreater { - - private static HashMap, Class> mapping = new HashMap, Class>(); - static { - mapping.put(VertexEntity.class, DocumentEntity.class); - } - - private MissingInstanceCreater() { - // this is a helper class - } - - @SuppressWarnings("unchecked") - public static Class getMissingClass(Class clazz) { - Class c = (Class) mapping.get(clazz); - if (c == null) { - c = clazz; - } - return c; - } - -} diff --git a/src/main/java/com/arangodb/http/BatchHttpManager.java b/src/main/java/com/arangodb/http/BatchHttpManager.java deleted file mode 100644 index 56bc791e8..000000000 --- a/src/main/java/com/arangodb/http/BatchHttpManager.java +++ /dev/null @@ -1,68 +0,0 @@ -package com.arangodb.http; - -import java.util.ArrayList; -import java.util.List; - -import com.arangodb.ArangoConfigure; -import com.arangodb.ArangoException; - -/** - * Created by fbartels on 10/22/14. - */ -public class BatchHttpManager extends HttpManager { - - private List callStack = new ArrayList(); - - private InvocationObject currentObject; - - private boolean batchModeActive = false; - - public BatchHttpManager(ArangoConfigure configure) { - super(configure); - } - - @Override - public HttpResponseEntity execute(HttpRequestEntity requestEntity) throws ArangoException { - if (!this.isBatchModeActive()) { - return super.execute(requestEntity); - } - - int id = callStack.size() + 1; - callStack.add(new BatchPart(requestEntity.type.toString(), buildUrl("", requestEntity), requestEntity.bodyText, - requestEntity.headers, this.getCurrentObject(), id)); - this.setCurrentObject(null); - HttpResponseEntity responseEntity = new HttpResponseEntity(); - - // http status - responseEntity.statusCode = 206; - responseEntity.statusPhrase = "Batch mode active, request has been stacked"; - responseEntity.setRequestId("request" + id); - return responseEntity; - } - - public List getCallStack() { - return callStack; - } - - @Override - public InvocationObject getCurrentObject() { - return currentObject; - } - - @Override - public void setCurrentObject(InvocationObject currentObject) { - this.currentObject = currentObject; - } - - public boolean isBatchModeActive() { - return batchModeActive; - } - - public void setBatchModeActive(boolean batchModeActive) { - this.batchModeActive = batchModeActive; - } - - public void emptyCallStack() { - this.callStack = new ArrayList(); - } -} \ No newline at end of file diff --git a/src/main/java/com/arangodb/http/BatchPart.java b/src/main/java/com/arangodb/http/BatchPart.java deleted file mode 100644 index 39dbfcb7d..000000000 --- a/src/main/java/com/arangodb/http/BatchPart.java +++ /dev/null @@ -1,79 +0,0 @@ -package com.arangodb.http; - -import java.util.Map; - -/** - * Created by fbartels on 10/22/14. - */ -public class BatchPart { - - private String method; - private String url; - private String body; - private Map headers; - private InvocationObject invocationObject; - private String id; - - public BatchPart(String method, String url, String body, Map headers, - InvocationObject invocationObject, int id) { - this.method = method; - this.url = url; - this.body = body; - this.headers = headers; - this.invocationObject = invocationObject; - this.id = "request" + id; - } - - public String getBody() { - return body; - } - - @Override - public String toString() { - return "BatchPart{" + "method='" + method + '\'' + ", url='" + url + '\'' + ", body='" + body + '\'' + '}'; - } - - public InvocationObject getInvocationObject() { - return this.invocationObject; - } - - public void setInvocationObject(InvocationObject invocationObject) { - this.invocationObject = invocationObject; - } - - public void setBody(String body) { - this.body = body; - } - - public String getMethod() { - return method; - } - - public void setMethod(String method) { - this.method = method; - } - - public String getUrl() { - return url; - } - - public void setUrl(String url) { - this.url = url; - } - - public Map getHeaders() { - return headers; - } - - public void setHeaders(Map headers) { - this.headers = headers; - } - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } -} diff --git a/src/main/java/com/arangodb/http/CURLLogger.java b/src/main/java/com/arangodb/http/CURLLogger.java deleted file mode 100644 index 631e57bec..000000000 --- a/src/main/java/com/arangodb/http/CURLLogger.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Copyright (C) 2012,2013 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.http; - -import java.util.Map.Entry; - -import org.apache.http.auth.Credentials; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.arangodb.http.HttpRequestEntity.RequestType; -import com.arangodb.util.StringUtils; - -/** - * @author tamtam180 - kirscheless at gmail.com - * @since 1.4.1 - */ -public class CURLLogger { - - private static Logger logger = LoggerFactory.getLogger(CURLLogger.class); - - private CURLLogger() { - // this is a helper class - } - - public static void log(String url, HttpRequestEntity requestEntity, Credentials credencials) { - - boolean includeBody = (requestEntity.type == RequestType.POST || requestEntity.type == RequestType.PUT - || requestEntity.type == RequestType.PATCH) && StringUtils.isNotEmpty(requestEntity.bodyText); - - StringBuilder buffer = new StringBuilder(); - - if (includeBody) { - buffer.append("\n"); - buffer.append("cat <<-___EOB___ | "); - } - - buffer.append("curl -X ").append(requestEntity.type); - buffer.append(" --dump -"); - - // header - if (requestEntity.hasHeaders()) { - for (Entry header : requestEntity.headers.entrySet()) { - buffer.append(" -H '").append(header.getKey()).append(":").append(header.getValue()).append("'"); - } - } - - // basic auth - 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(requestEntity.bodyText); - buffer.append("\n"); - buffer.append("___EOB___"); - } - - logger.debug("[CURL]{}", buffer); - - } - -} diff --git a/src/main/java/com/arangodb/http/HttpManager.java b/src/main/java/com/arangodb/http/HttpManager.java deleted file mode 100644 index 030961f02..000000000 --- a/src/main/java/com/arangodb/http/HttpManager.java +++ /dev/null @@ -1,712 +0,0 @@ -/* - * Copyright (C) 2012 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.http; - -import java.io.IOException; -import java.net.SocketException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.TreeMap; - -import org.apache.http.Header; -import org.apache.http.HeaderElement; -import org.apache.http.HeaderElementIterator; -import org.apache.http.HttpEntity; -import org.apache.http.HttpHost; -import org.apache.http.HttpResponse; -import org.apache.http.HttpStatus; -import org.apache.http.NameValuePair; -import org.apache.http.StatusLine; -import org.apache.http.auth.AuthenticationException; -import org.apache.http.auth.Credentials; -import org.apache.http.auth.UsernamePasswordCredentials; -import org.apache.http.client.ClientProtocolException; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.client.config.RequestConfig.Builder; -import org.apache.http.client.methods.HttpDelete; -import org.apache.http.client.methods.HttpEntityEnclosingRequestBase; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.methods.HttpHead; -import org.apache.http.client.methods.HttpPatch; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.client.methods.HttpPut; -import org.apache.http.client.methods.HttpRequestBase; -import org.apache.http.client.utils.URLEncodedUtils; -import org.apache.http.config.Registry; -import org.apache.http.config.RegistryBuilder; -import org.apache.http.conn.ConnectionKeepAliveStrategy; -import org.apache.http.conn.socket.ConnectionSocketFactory; -import org.apache.http.conn.socket.PlainConnectionSocketFactory; -import org.apache.http.conn.ssl.SSLConnectionSocketFactory; -import org.apache.http.entity.ContentType; -import org.apache.http.entity.StringEntity; -import org.apache.http.impl.auth.BasicScheme; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.DefaultHttpRequestRetryHandler; -import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.http.impl.conn.DefaultProxyRoutePlanner; -import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; -import org.apache.http.message.BasicHeaderElementIterator; -import org.apache.http.message.BasicNameValuePair; -import org.apache.http.protocol.HTTP; -import org.apache.http.protocol.HttpContext; -import org.apache.http.ssl.SSLContexts; -import org.apache.http.util.EntityUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.arangodb.ArangoConfigure; -import com.arangodb.ArangoException; -import com.arangodb.http.HttpRequestEntity.RequestType; -import com.arangodb.util.IOUtils; - -/** - * @author tamtam180 - kirscheless at gmail.com - * @author a-brandt - * - */ -public class HttpManager { - - private static final ContentType APPLICATION_JSON_UTF8 = ContentType.create("application/json", "utf-8"); - - private static Logger logger = LoggerFactory.getLogger(HttpManager.class); - - private PoolingHttpClientConnectionManager cm; - private CloseableHttpClient client; - - private ArangoConfigure configure; - - private HttpResponseEntity preDefinedResponse; - - private HttpMode httpMode = HttpMode.SYNC; - - private List jobIds = new ArrayList(); - - private final Map jobs = new HashMap(); - - public enum HttpMode { - SYNC, ASYNC, FIREANDFORGET - } - - public HttpManager(final ArangoConfigure configure) { - this.configure = configure; - } - - public ArangoConfigure getConfiguration() { - return this.configure; - } - - public void init() { - // socket factory for HTTP - final ConnectionSocketFactory plainsf = new PlainConnectionSocketFactory(); - - // socket factory for HTTPS - final SSLConnectionSocketFactory sslsf = initSSLConnectionSocketFactory(); - - // register socket factories - final Registry r = RegistryBuilder. create() - .register("http", plainsf).register("https", sslsf).build(); - - // ConnectionManager - cm = new PoolingHttpClientConnectionManager(r); - cm.setDefaultMaxPerRoute(configure.getMaxPerConnection()); - cm.setMaxTotal(configure.getMaxTotalConnection()); - - final Builder custom = RequestConfig.custom(); - - // RequestConfig - if (configure.getConnectionTimeout() >= 0) { - custom.setConnectTimeout(configure.getConnectionTimeout()); - } - if (configure.getTimeout() >= 0) { - custom.setConnectionRequestTimeout(configure.getTimeout()); - custom.setSocketTimeout(configure.getTimeout()); - } - - cm.setValidateAfterInactivity(configure.getValidateAfterInactivity()); - - final RequestConfig requestConfig = custom.build(); - - final HttpClientBuilder builder = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig); - builder.setConnectionManager(cm); - - // KeepAlive Strategy - final ConnectionKeepAliveStrategy keepAliveStrategy = new ConnectionKeepAliveStrategy() { - - @Override - public long getKeepAliveDuration(final HttpResponse response, final HttpContext context) { - return HttpManager.this.getKeepAliveDuration(response); - } - - }; - builder.setKeepAliveStrategy(keepAliveStrategy); - - // Retry Handler - builder.setRetryHandler(new DefaultHttpRequestRetryHandler(configure.getRetryCount(), false)); - - // Proxy - addProxyToBuilder(builder); - - // Client - client = builder.build(); - } - - private long getKeepAliveDuration(final HttpResponse response) { - // Honor 'keep-alive' header - 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) { - // ignore this exception - } - } - } - // otherwise keep alive for 30 seconds - return 30L * 1000L; - } - - private void addProxyToBuilder(final HttpClientBuilder builder) { - if (configure.getProxyHost() != null && configure.getProxyPort() != 0) { - final HttpHost proxy = new HttpHost(configure.getProxyHost(), configure.getProxyPort(), "http"); - - final DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy); - builder.setRoutePlanner(routePlanner); - } - } - - public void destroy() { - if (cm != null) { - cm.shutdown(); - } - configure = null; - try { - if (client != null) { - client.close(); - } - } catch (final IOException e) { - } - } - - public HttpMode getHttpMode() { - return httpMode; - } - - public void setHttpMode(final HttpMode httpMode) { - this.httpMode = httpMode; - } - - public HttpResponseEntity doGet(final String url) throws ArangoException { - return doGet(url, null); - } - - public HttpResponseEntity doGet(final String url, final Map params) throws ArangoException { - return doHeadGetDelete(RequestType.GET, url, null, params); - } - - public HttpResponseEntity doGet( - final String url, - final Map headers, - final Map params) throws ArangoException { - return doHeadGetDelete(RequestType.GET, url, headers, params); - } - - public HttpResponseEntity doGet( - final String url, - final Map headers, - final Map params, - final String username, - final String password) throws ArangoException { - return doHeadGetDelete(RequestType.GET, url, headers, params, username, password); - } - - public HttpResponseEntity doHead(final String url, final Map params) throws ArangoException { - return doHeadGetDelete(RequestType.HEAD, url, null, params); - } - - public HttpResponseEntity doDelete(final String url, final Map params) throws ArangoException { - return doHeadGetDelete(RequestType.DELETE, url, null, params); - } - - public HttpResponseEntity doDelete( - final String url, - final Map headers, - final Map params) throws ArangoException { - return doHeadGetDelete(RequestType.DELETE, url, headers, params); - } - - public HttpResponseEntity doHeadGetDelete( - final RequestType type, - final String url, - final Map headers, - final Map params) throws ArangoException { - return doHeadGetDelete(type, url, headers, params, null, null); - } - - public HttpResponseEntity doHeadGetDelete( - final RequestType type, - final String url, - final Map headers, - final Map params, - final String username, - final String password) throws ArangoException { - final HttpRequestEntity requestEntity = new HttpRequestEntity(); - requestEntity.type = type; - requestEntity.url = url; - requestEntity.headers = headers; - requestEntity.parameters = params; - requestEntity.username = username; - requestEntity.password = password; - return execute(requestEntity); - } - - public HttpResponseEntity doPost( - final String url, - final Map headers, - final Map params, - final String bodyText) throws ArangoException { - return doPostPutPatch(RequestType.POST, url, headers, params, bodyText, null); - } - - public HttpResponseEntity doPost(final String url, final Map params, final String bodyText) - throws ArangoException { - return doPostPutPatch(RequestType.POST, url, null, params, bodyText, null); - } - - public HttpResponseEntity doPost(final String url, final Map params, final HttpEntity entity) - throws ArangoException { - return doPostPutPatch(RequestType.POST, url, null, params, null, entity); - } - - public HttpResponseEntity doPostWithHeaders( - final String url, - final Map params, - final HttpEntity entity, - final Map headers, - final String body) throws ArangoException { - return doPostPutPatch(RequestType.POST, url, headers, params, body, entity); - } - - public HttpResponseEntity doPut( - final String url, - final Map headers, - final Map params, - final String bodyText) throws ArangoException { - return doPostPutPatch(RequestType.PUT, url, headers, params, bodyText, null); - } - - public HttpResponseEntity doPut(final String url, final Map params, final String bodyText) - throws ArangoException { - return doPostPutPatch(RequestType.PUT, url, null, params, bodyText, null); - } - - public HttpResponseEntity doPatch( - final String url, - final Map headers, - final Map params, - final String bodyText) throws ArangoException { - return doPostPutPatch(RequestType.PATCH, url, headers, params, bodyText, null); - } - - public HttpResponseEntity doPatch(final String url, final Map params, final String bodyText) - throws ArangoException { - return doPostPutPatch(RequestType.PATCH, url, null, params, bodyText, null); - } - - private HttpResponseEntity doPostPutPatch( - final RequestType type, - final String url, - final Map headers, - final Map params, - final String bodyText, - final HttpEntity entity) throws ArangoException { - final HttpRequestEntity requestEntity = new HttpRequestEntity(); - requestEntity.type = type; - requestEntity.url = url; - requestEntity.headers = headers; - requestEntity.parameters = params; - requestEntity.bodyText = bodyText; - requestEntity.entity = entity; - return execute(requestEntity); - } - - /** - * Executes the request and handles connect exceptions - * - * @param requestEntity - * the request - * @return the response of the request - * - * @throws ArangoException - */ - public HttpResponseEntity execute(final HttpRequestEntity requestEntity) throws ArangoException { - int retries = 0; - final int connectRetryCount = configure.getConnectRetryCount(); - - while (true) { - try { - return executeInternal(configure.getBaseUrl(), requestEntity); - } catch (final SocketException ex) { - retries++; - if (connectRetryCount > 0 && retries > connectRetryCount) { - logger.error(ex.getMessage(), ex); - throw new ArangoException(ex); - } - - if (configure.hasFallbackHost()) { - configure.changeCurrentHost(); - } - - logger.warn(ex.getMessage(), ex); - try { - // 1000 milliseconds is one second. - Thread.sleep(configure.getConnectRetryWait()); - } catch (final InterruptedException iex) { - Thread.currentThread().interrupt(); - } - } - } - } - - /** - * Executes the request - * - * @param requestEntity - * the request - * @return the response of the request - * @throws ArangoException - */ - private HttpResponseEntity executeInternal(final String baseUrl, final HttpRequestEntity requestEntity) - throws ArangoException, SocketException { - - final String url = buildUrl(baseUrl, requestEntity); - - logRequest(requestEntity, url); - - final HttpRequestBase request = buildHttpRequestBase(requestEntity, url); - - // common-header - final String userAgent = "Mozilla/5.0 (compatible; ArangoDB-JavaDriver/1.1; +http://mt.orz.at/)"; - request.setHeader("User-Agent", userAgent); - - addOptionalHeaders(requestEntity, request); - - addHttpModeHeader(request); - - // Basic Auth - final Credentials credentials = addCredentials(requestEntity, request); - - // CURL/HTTP Logger - if (configure.isEnableCURLLogger()) { - CURLLogger.log(url, requestEntity, credentials); - } - - HttpResponseEntity responseEntity = null; - if (preDefinedResponse != null) { - responseEntity = preDefinedResponse; - } else { - final HttpResponse response = executeRequest(request); - if (response != null) { - try { - responseEntity = buildHttpResponseEntity(requestEntity, response); - consumeResponse(response); - } catch (final IOException e) { - throw new ArangoException(e); - } - - if (this.getHttpMode().equals(HttpMode.ASYNC)) { - final Map map = responseEntity.getHeaders(); - this.addJob(map.get("X-Arango-Async-Id"), this.getCurrentObject()); - } else if (this.getHttpMode().equals(HttpMode.FIREANDFORGET)) { - responseEntity = null; - } - } - } - - return responseEntity; - } - - private void consumeResponse(final HttpResponse response) throws IOException { - final HttpEntity entity = response.getEntity(); - if (entity != null) { - EntityUtils.consume(entity); - } - } - - private HttpResponse executeRequest(final HttpRequestBase request) throws SocketException, ArangoException { - try { - return client.execute(request); - } catch (final SocketException ex) { - // catch SocketException before IOException - throw ex; - } catch (final ClientProtocolException e) { - throw new ArangoException(e); - } catch (final IOException e) { - throw new ArangoException(e); - } - } - - private HttpResponseEntity buildHttpResponseEntity( - final HttpRequestEntity requestEntity, - final HttpResponse response) throws IOException { - final HttpResponseEntity responseEntity = new HttpResponseEntity(); - - // http status - final StatusLine status = response.getStatusLine(); - responseEntity.statusCode = status.getStatusCode(); - responseEntity.statusPhrase = status.getReasonPhrase(); - - if (logger.isDebugEnabled()) { - logger.debug("[RES]http-{}: statusCode={}", requestEntity.type, responseEntity.statusCode); - } - - // ヘッダの処理 - // // TODO etag特殊処理は削除する。 - final Header etagHeader = response.getLastHeader("etag"); - if (etagHeader != null) { - responseEntity.etag = etagHeader.getValue().replace("\"", ""); - } - // ヘッダをMapに変換する - responseEntity.headers = new TreeMap(); - for (final Header header : response.getAllHeaders()) { - responseEntity.headers.put(header.getName(), header.getValue()); - } - - // レスポンスの取得 - final HttpEntity entity = response.getEntity(); - if (entity != null) { - final Header contentType = entity.getContentType(); - if (contentType != null) { - responseEntity.contentType = contentType.getValue(); - if (responseEntity.isDumpResponse()) { - responseEntity.stream = entity.getContent(); - if (logger.isDebugEnabled()) { - logger.debug("[RES]http-{}: stream, {}", requestEntity.type, contentType.getValue()); - } - } - } - // Close stream in this method. - if (responseEntity.stream == null) { - responseEntity.text = IOUtils.toString(entity.getContent()); - if (logger.isDebugEnabled()) { - logger.debug("[RES]http-{}: text={}", requestEntity.type, responseEntity.text); - } - } - } - return responseEntity; - } - - private void addHttpModeHeader(final HttpRequestBase request) { - if (this.getHttpMode().equals(HttpMode.ASYNC)) { - request.addHeader("x-arango-async", "store"); - } else if (this.getHttpMode().equals(HttpMode.FIREANDFORGET)) { - request.addHeader("x-arango-async", "true"); - } - } - - private Credentials addCredentials(final HttpRequestEntity requestEntity, final HttpRequestBase request) - throws ArangoException { - Credentials credentials = null; - if (requestEntity.username != null && requestEntity.password != null) { - credentials = new UsernamePasswordCredentials(requestEntity.username, requestEntity.password); - } else if (configure.getUser() != null && configure.getPassword() != null) { - credentials = new UsernamePasswordCredentials(configure.getUser(), configure.getPassword()); - } - if (credentials != null) { - final BasicScheme basicScheme = new BasicScheme(); - try { - request.addHeader(basicScheme.authenticate(credentials, request, null)); - } catch (final AuthenticationException e) { - throw new ArangoException(e); - } - } - return credentials; - } - - private void addOptionalHeaders(final HttpRequestEntity requestEntity, final HttpRequestBase request) { - if (requestEntity.headers != null) { - for (final Entry keyValue : requestEntity.headers.entrySet()) { - request.setHeader(keyValue.getKey(), keyValue.getValue().toString()); - } - } - } - - private HttpRequestBase buildHttpRequestBase(final HttpRequestEntity requestEntity, final String url) { - HttpRequestBase request; - switch (requestEntity.type) { - case POST: - final HttpPost post = new HttpPost(url); - configureBodyParams(requestEntity, post); - request = post; - break; - case PUT: - final HttpPut put = new HttpPut(url); - configureBodyParams(requestEntity, put); - request = put; - break; - case PATCH: - final HttpPatch patch = new HttpPatch(url); - configureBodyParams(requestEntity, patch); - request = patch; - break; - case HEAD: - request = new HttpHead(url); - break; - case DELETE: - request = new HttpDelete(url); - break; - case GET: - default: - request = new HttpGet(url); - break; - } - return request; - } - - private void logRequest(final HttpRequestEntity requestEntity, final String url) { - if (logger.isDebugEnabled()) { - if (requestEntity.type == RequestType.POST || requestEntity.type == RequestType.PUT - || requestEntity.type == RequestType.PATCH) { - logger.debug("[REQ]http-{}: url={}, headers={}, body={}", - new Object[] { requestEntity.type, url, requestEntity.headers, requestEntity.bodyText }); - } else { - logger.debug("[REQ]http-{}: url={}, headers={}", - new Object[] { requestEntity.type, url, requestEntity.headers }); - } - } - } - - public static String buildUrl(final String baseUrl, final HttpRequestEntity requestEntity) { - if (requestEntity.parameters != null && !requestEntity.parameters.isEmpty()) { - final String paramString = URLEncodedUtils.format(toList(requestEntity.parameters), "utf-8"); - if (requestEntity.url.contains("?")) { - return baseUrl + requestEntity.url + "&" + paramString; - } else { - return baseUrl + requestEntity.url + "?" + paramString; - } - } - return baseUrl + requestEntity.url; - } - - 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().toString())); - } - } - return paramList; - } - - public static void configureBodyParams( - final HttpRequestEntity requestEntity, - final HttpEntityEnclosingRequestBase request) { - - if (requestEntity.entity != null) { - request.setEntity(requestEntity.entity); - } else if (requestEntity.bodyText != null) { - request.setEntity(new StringEntity(requestEntity.bodyText, APPLICATION_JSON_UTF8)); - } - - } - - public static boolean is400Error(final ArangoException e) { - return e.getCode() == HttpStatus.SC_BAD_REQUEST; - } - - public static boolean is404Error(final ArangoException e) { - return e.getCode() == HttpStatus.SC_NOT_FOUND; - } - - public static boolean is412Error(final ArangoException e) { - return e.getCode() == HttpStatus.SC_PRECONDITION_FAILED; - } - - public static boolean is200(final HttpResponseEntity res) { - return res.getStatusCode() == HttpStatus.SC_OK; - } - - public static boolean is400Error(final HttpResponseEntity res) { - return res.getStatusCode() == HttpStatus.SC_BAD_REQUEST; - } - - public static boolean is404Error(final HttpResponseEntity res) { - return res.getStatusCode() == HttpStatus.SC_NOT_FOUND; - } - - public static boolean is412Error(final HttpResponseEntity res) { - return res.getStatusCode() == HttpStatus.SC_PRECONDITION_FAILED; - } - - public CloseableHttpClient getClient() { - return client; - } - - public InvocationObject getCurrentObject() { - // do nothing here (used in BatchHttpManager) - return null; - } - - public void setCurrentObject(final InvocationObject currentObject) { - // do nothing here (used in BatchHttpManager) - } - - public void setPreDefinedResponse(final HttpResponseEntity preDefinedResponse) { - this.preDefinedResponse = preDefinedResponse; - } - - public List getJobIds() { - return jobIds; - } - - public Map getJobs() { - return jobs; - } - - public void addJob(final String jobId, final InvocationObject invocationObject) { - jobIds.add(jobId); - jobs.put(jobId, invocationObject); - } - - public String getLastJobId() { - return jobIds.isEmpty() ? null : jobIds.get(jobIds.size() - 1); - } - - public void resetJobs() { - this.jobIds = new ArrayList(); - this.jobs.clear(); - - } - - private SSLConnectionSocketFactory initSSLConnectionSocketFactory() { - SSLConnectionSocketFactory sslsf; - if (configure.getSslContext() != null) { - sslsf = new SSLConnectionSocketFactory(configure.getSslContext()); - } else { - sslsf = new SSLConnectionSocketFactory(SSLContexts.createSystemDefault()); - } - return sslsf; - } - -} diff --git a/src/main/java/com/arangodb/http/HttpRequestEntity.java b/src/main/java/com/arangodb/http/HttpRequestEntity.java deleted file mode 100644 index c4ddb6915..000000000 --- a/src/main/java/com/arangodb/http/HttpRequestEntity.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Copyright (C) 2012 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.http; - -import java.util.Map; - -import org.apache.http.HttpEntity; - -/** - * @author tamtam180 - kirscheless at gmail.com - * - */ -public class HttpRequestEntity { - - public enum RequestType { - GET, POST, PUT, DELETE, HEAD, PATCH - } - - public Map headers; - public RequestType type; - public String url; - public Map parameters; - public String username; - public String password; - public String bodyText; - public HttpEntity entity; - - public Map getHeaders() { - return headers; - } - - public void setHeaders(Map headers) { - this.headers = headers; - } - - public boolean hasHeaders() { - return headers != null && !headers.isEmpty(); - } - - public RequestType getType() { - return type; - } - - public void setType(RequestType type) { - this.type = type; - } - - public String getUrl() { - return url; - } - - public void setUrl(String url) { - this.url = url; - } - - public Map getParameters() { - return parameters; - } - - public void setParameters(Map parameters) { - this.parameters = parameters; - } - - public String getUsername() { - return username; - } - - public void setUsername(String username) { - this.username = username; - } - - public String getPassword() { - return password; - } - - public void setPassword(String password) { - this.password = password; - } - - public String getBodyText() { - return bodyText; - } - - public void setBodyText(String bodyText) { - this.bodyText = bodyText; - } - - public HttpEntity getEntity() { - return entity; - } - - public void setEntity(HttpEntity entity) { - this.entity = entity; - } - -} diff --git a/src/main/java/com/arangodb/http/HttpResponseEntity.java b/src/main/java/com/arangodb/http/HttpResponseEntity.java deleted file mode 100644 index cf594eac2..000000000 --- a/src/main/java/com/arangodb/http/HttpResponseEntity.java +++ /dev/null @@ -1,180 +0,0 @@ -/* - * Copyright (C) 2012 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.http; - -import java.io.InputStream; -import java.util.Map; - -/** - * @author tamtam180 - kirscheless at gmail.com - * - */ -public class HttpResponseEntity { - - int statusCode; - String statusPhrase; - String text; - InputStream stream; - String etag; - String requestId; - Map headers; - - String contentType; - - /** - * Checks if the content type is "application/json" - * - * @return true if the content type is "application/json" - * @since 1.4.0 - */ - public boolean isJsonResponse() { - return contentType != null && contentType.startsWith("application/json"); - } - - /** - * Checks if the content type is "application/x-arango-dump" - * - * @return true if the content type is "application/x-arango-dump" - * @since 1.4.0 - */ - public boolean isDumpResponse() { - return contentType != null && contentType.startsWith("application/x-arango-dump"); - } - - /** - * Checks if the content type is "text/plain" - * - * @return true if the content type is "text/plain" - * @since 1.4.0 - */ - public boolean isTextResponse() { - return contentType != null && contentType.startsWith("text/plain"); - } - - public boolean isBatchRepsonse() { - return requestId != null; - } - - public int getStatusCode() { - return statusCode; - } - - public InputStream getStream() { - return stream; - } - - public void setStream(final InputStream stream) { - this.stream = stream; - } - - public String getStatusPhrase() { - return statusPhrase; - } - - public String getText() { - return text; - } - - public void setStatusCode(final int statusCode) { - this.statusCode = statusCode; - } - - public void setStatusPhrase(final String statusPhrase) { - this.statusPhrase = statusPhrase; - } - - public void setText(final String text) { - this.text = text; - } - - public String getEtag() { - return etag; - } - - public void setEtag(final String etag) { - this.etag = etag; - } - - public Map getHeaders() { - return headers; - } - - public void setHeaders(final Map headers) { - this.headers = headers; - } - - public String getContentType() { - return contentType; - } - - public void setContentType(final String contentType) { - this.contentType = contentType; - } - - public String getRequestId() { - return requestId; - } - - public void setRequestId(final String requestId) { - this.requestId = requestId; - } - - public String createStatusPhrase() { - String result; - switch (statusCode) { - case 400: - result = "Bad Request"; - break; - case 401: - result = "Unauthorized"; - break; - case 403: - result = "Forbidden"; - break; - case 404: - result = "Not Found"; - break; - case 405: - result = "Method Not Allowed"; - break; - case 406: - result = "Not Acceptable"; - break; - case 407: - result = "Proxy Authentication Required"; - break; - case 408: - result = "Request Time-out"; - break; - case 409: - result = "Conflict"; - break; - case 500: - result = "Internal Server Error"; - break; - default: - result = "unknown error"; - break; - } - - if (statusCode == 500) { - return result + ": " + getText(); - } - - return result; - } -} diff --git a/src/main/java/com/arangodb/http/InvocationHandlerImpl.java b/src/main/java/com/arangodb/http/InvocationHandlerImpl.java deleted file mode 100644 index 5f0dc8d78..000000000 --- a/src/main/java/com/arangodb/http/InvocationHandlerImpl.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.arangodb.http; - -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.Method; - -import com.arangodb.impl.BaseDriverInterface; - -/** - * Created by fbartels on 10/27/14. - */ -public class InvocationHandlerImpl implements InvocationHandler { - private BaseDriverInterface testImpl; - - public InvocationHandlerImpl(BaseDriverInterface impl) { - this.testImpl = impl; - } - - @Override - public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { - if (Object.class == method.getDeclaringClass()) { - String name = method.getName(); - if ("equals".equals(name)) { - return proxy == args[0]; - } else if ("hashCode".equals(name)) { - return System.identityHashCode(proxy); - } else if ("toString".equals(name)) { - return proxy.getClass().getName() + "@" + Integer.toHexString(System.identityHashCode(proxy)) - + ", with InvocationHandler " + this; - } else { - throw new IllegalStateException(String.valueOf(method)); - } - } - testImpl.getHttpManager().setCurrentObject(new InvocationObject(method, testImpl, args)); - return method.invoke(testImpl, args); - } -} diff --git a/src/main/java/com/arangodb/http/InvocationObject.java b/src/main/java/com/arangodb/http/InvocationObject.java deleted file mode 100644 index 8b3f8982e..000000000 --- a/src/main/java/com/arangodb/http/InvocationObject.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.arangodb.http; - -import java.lang.reflect.Method; - -import com.arangodb.impl.BaseDriverInterface; - -/** - * Created by fbartels on 10/27/14. - */ -public class InvocationObject { - - private Method method; - - private Object[] args; - - private BaseDriverInterface arangoDriver; - - public InvocationObject(Method method, BaseDriverInterface arangoDriver, Object[] args) { - this.method = method; - this.args = args; - this.arangoDriver = arangoDriver; - } - - public Method getMethod() { - return method; - } - - public void setMethod(Method method) { - this.method = method; - } - - public Object[] getArgs() { - return args; - } - - public void setArgs(Object[] args) { - this.args = args; - } - - public BaseDriverInterface getArangoDriver() { - return arangoDriver; - } - - public void setArangoDriver(BaseDriverInterface arangoDriver) { - this.arangoDriver = arangoDriver; - } - -} diff --git a/src/main/java/com/arangodb/http/JsonSequenceEntity.java b/src/main/java/com/arangodb/http/JsonSequenceEntity.java deleted file mode 100644 index 2a9d131b7..000000000 --- a/src/main/java/com/arangodb/http/JsonSequenceEntity.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright (C) 2012,2013 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.http; - -import java.io.BufferedWriter; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.util.Iterator; - -import org.apache.http.entity.AbstractHttpEntity; - -import com.google.gson.Gson; - -/** - * @author tamtam180 - kirscheless at gmail.com - * - */ -public class JsonSequenceEntity extends AbstractHttpEntity { - - private Iterator it; - private Gson gson; - - public JsonSequenceEntity(Iterator it, Gson gson) { - this.it = it; - this.gson = gson; - setChunked(true); - setContentType("binary/octet-stream"); - } - - @Override - public boolean isRepeatable() { - return false; - } - - @Override - public long getContentLength() { - return -1; - } - - @Override - public InputStream getContent() throws IOException { - throw new IllegalStateException("cannot support this method."); - } - - @Override - public boolean isStreaming() { - return true; - } - - @Override - public void writeTo(OutputStream outstream) throws IOException { - - if (outstream == null) { - throw new IllegalArgumentException("Output stream may not be null"); - } - - BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outstream, "UTF-8")); - while (it.hasNext()) { - Object value = it.next(); - gson.toJson(value, writer); - writer.newLine(); - } - writer.flush(); - } - -} diff --git a/src/main/java/com/arangodb/impl/AnnotationHandler.java b/src/main/java/com/arangodb/impl/AnnotationHandler.java deleted file mode 100644 index 79227edae..000000000 --- a/src/main/java/com/arangodb/impl/AnnotationHandler.java +++ /dev/null @@ -1,167 +0,0 @@ -package com.arangodb.impl; - -import java.lang.annotation.Annotation; -import java.lang.reflect.Field; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.arangodb.entity.BaseDocument; -import com.google.gson.annotations.SerializedName; - -public class AnnotationHandler { - - private static Logger logger = LoggerFactory.getLogger(AnnotationHandler.class); - - static class DocumentAttributes { - public Field rev; // NOSONAR - public Field id; // NOSONAR - public Field key; // NOSONAR - public Field from; // NOSONAR - public Field to; // NOSONAR - } - - static Map, DocumentAttributes> class2DocumentAttributes; - - static { - class2DocumentAttributes = new HashMap, DocumentAttributes>(); - } - - public AnnotationHandler() { - // do nothing here - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - public synchronized void updateDocumentAttributes( - final Object o, - final String rev, - final String id, - final String key) { - if (o != null) { - if (o instanceof java.util.Map) { - final java.util.Map m = (java.util.Map) o; - m.put(BaseDocument.ID, id); - m.put(BaseDocument.KEY, key); - m.put(BaseDocument.REV, rev); - } else { - final DocumentAttributes documentAttributes = getDocumentAttributes(o); - setAttribute(documentAttributes.id, o, id); - setAttribute(documentAttributes.key, o, key); - setAttribute(documentAttributes.rev, o, rev); - } - } - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - public synchronized void updateDocumentRev(final Object o, final String rev) { - if (o != null) { - if (o instanceof java.util.Map) { - final java.util.Map m = (java.util.Map) o; - m.put(BaseDocument.REV, rev); - } else { - final DocumentAttributes documentAttributes = getDocumentAttributes(o); - setAttribute(documentAttributes.rev, o, rev); - } - } - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - public synchronized void updateEdgeAttributes( - final Object o, - final String rev, - final String id, - final String key, - final String from, - final String to) { - if (o != null) { - if (o instanceof java.util.Map) { - final java.util.Map m = (java.util.Map) o; - m.put(BaseDocument.ID, id); - m.put(BaseDocument.KEY, key); - m.put(BaseDocument.REV, rev); - if (from != null) { - m.put(BaseDocument.FROM, from); - } - if (to != null) { - m.put(BaseDocument.TO, to); - } - } else { - final DocumentAttributes documentAttributes = getDocumentAttributes(o); - setAttribute(documentAttributes.id, o, id); - setAttribute(documentAttributes.key, o, key); - setAttribute(documentAttributes.rev, o, rev); - if (from != null) { - setAttribute(documentAttributes.from, o, from); - } - if (to != null) { - setAttribute(documentAttributes.to, o, to); - } - } - } - } - - private void setAttribute(final Field field, final Object o, final Object value) { - if (field != null) { - try { - field.setAccessible(true); - field.set(o, value); - } catch (final Exception e) { - logger.error("could not update document attribute of class " + value.getClass().getCanonicalName(), e); - } - } - } - - private DocumentAttributes getDocumentAttributes(final Object o) { - final Class clazz = o.getClass(); - DocumentAttributes documentAttributes = class2DocumentAttributes.get(clazz); - - if (documentAttributes == null) { - documentAttributes = new DocumentAttributes(); - documentAttributes.id = getFieldByAnnotationValue(clazz, BaseDocument.ID); - documentAttributes.key = getFieldByAnnotationValue(clazz, BaseDocument.KEY); - documentAttributes.rev = getFieldByAnnotationValue(clazz, BaseDocument.REV); - documentAttributes.from = getFieldByAnnotationValue(clazz, BaseDocument.FROM); - documentAttributes.to = getFieldByAnnotationValue(clazz, BaseDocument.TO); - class2DocumentAttributes.put(clazz, documentAttributes); - } - - return documentAttributes; - } - - private Field getFieldByAnnotationValue(final Class clazz, final String value) { - - final List fields = getAllDeclaredFields(clazz); - for (final Field field : fields) { - - final Annotation[] annotations = field.getAnnotations(); - for (final Annotation annotation : annotations) { - - if (annotation instanceof SerializedName && value.equals(((SerializedName) annotation).value())) { - return field; - } - } - } - - return null; - } - - private List getAllDeclaredFields(final Class clazz) { - final List result = new ArrayList(); - - Class current = clazz; - - while (current != null) { - final Field[] fields = current.getDeclaredFields(); - for (final Field field : fields) { - result.add(field); - } - current = current.getSuperclass(); - } - return result; - } - -} diff --git a/src/main/java/com/arangodb/impl/BaseArangoDriverImpl.java b/src/main/java/com/arangodb/impl/BaseArangoDriverImpl.java deleted file mode 100644 index beaca5cc2..000000000 --- a/src/main/java/com/arangodb/impl/BaseArangoDriverImpl.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright (C) 2012 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.impl; - -import com.arangodb.ArangoConfigure; -import com.arangodb.BaseArangoDriver; -import com.arangodb.http.HttpManager; - -/** - * @author tamtam180 - kirscheless at gmail.com - * - */ -class BaseArangoDriverImpl extends BaseArangoDriver implements BaseDriverInterface { - - protected static final String COLLECTION = "collection"; - protected ArangoConfigure configure; - protected HttpManager httpManager; - protected AnnotationHandler annotationHandler; - - BaseArangoDriverImpl(ArangoConfigure configure, HttpManager httpManager) { - this.configure = configure; - this.httpManager = httpManager; - this.annotationHandler = new AnnotationHandler(); - } - - @Override - public HttpManager getHttpManager() { - return this.httpManager; - } - - @Override - public void setHttpManager(HttpManager httpManager) { - this.httpManager = httpManager; - } - -} diff --git a/src/main/java/com/arangodb/impl/BaseArangoDriverWithCursorImpl.java b/src/main/java/com/arangodb/impl/BaseArangoDriverWithCursorImpl.java deleted file mode 100644 index fb1098a5a..000000000 --- a/src/main/java/com/arangodb/impl/BaseArangoDriverWithCursorImpl.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright (C) 2012 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.impl; - -import com.arangodb.ArangoConfigure; -import com.arangodb.InternalCursorDriver; -import com.arangodb.http.HttpManager; - -/** - * @author tamtam180 - kirscheless at gmail.com - * - */ -class BaseArangoDriverWithCursorImpl extends BaseArangoDriverImpl { - - protected InternalCursorDriver cursorDriver; - - BaseArangoDriverWithCursorImpl(ArangoConfigure configure, InternalCursorDriver cursorDriver, HttpManager httpManager) { - super(configure, httpManager); - this.cursorDriver = cursorDriver; - } - -} diff --git a/src/main/java/com/arangodb/impl/BaseDriverInterface.java b/src/main/java/com/arangodb/impl/BaseDriverInterface.java deleted file mode 100644 index 760850531..000000000 --- a/src/main/java/com/arangodb/impl/BaseDriverInterface.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.arangodb.impl; - -import com.arangodb.http.HttpManager; - -/** - * Created by fbartels on 10/27/14. - */ -public interface BaseDriverInterface { - - public HttpManager getHttpManager(); - - public void setHttpManager(HttpManager httpManager); - -} diff --git a/src/main/java/com/arangodb/impl/ImplFactory.java b/src/main/java/com/arangodb/impl/ImplFactory.java deleted file mode 100644 index c59b56082..000000000 --- a/src/main/java/com/arangodb/impl/ImplFactory.java +++ /dev/null @@ -1,125 +0,0 @@ -/* - * Copyright (C) 2012 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.impl; - -import com.arangodb.ArangoConfigure; -import com.arangodb.InternalCursorDriver; -import com.arangodb.InternalTransactionDriver; -import com.arangodb.http.HttpManager; - -/** - * @author tamtam180 - kirscheless at gmail.com - * @author a-brandt - * - */ -public class ImplFactory { - - private ImplFactory() { - // this is a helper class - } - - public static InternalCursorDriverImpl createCursorDriver(ArangoConfigure configure, HttpManager httpManager) { - return new InternalCursorDriverImpl(configure, httpManager); - } - - public static InternalCollectionDriverImpl createCollectionDriver( - ArangoConfigure configure, - HttpManager httpManager) { - return new InternalCollectionDriverImpl(configure, httpManager); - } - - public static InternalDocumentDriverImpl createDocumentDriver(ArangoConfigure configure, HttpManager httpManager) { - return new InternalDocumentDriverImpl(configure, httpManager); - } - - public static InternalJobsDriverImpl createJobsDriver(ArangoConfigure configure, HttpManager httpManager) { - return new InternalJobsDriverImpl(configure, httpManager); - } - - public static InternalTransactionDriver createTransactionDriver( - ArangoConfigure configure, - HttpManager httpManager) { - return new InternalTransactionDriverImpl(configure, httpManager); - } - - public static InternalSimpleDriverImpl createSimpleDriver( - ArangoConfigure configure, - InternalCursorDriver cursorDriver, - HttpManager httpManager) { - return new InternalSimpleDriverImpl(configure, cursorDriver, httpManager); - } - - public static InternalIndexDriverImpl createIndexDriver(ArangoConfigure configure, HttpManager httpManager) { - return new InternalIndexDriverImpl(configure, httpManager); - } - - public static InternalAdminDriverImpl createAdminDriver(ArangoConfigure configure, HttpManager httpManager) { - return new InternalAdminDriverImpl(configure, httpManager); - } - - public static InternalAqlFunctionsDriverImpl createAqlFunctionsDriver( - ArangoConfigure configure, - HttpManager httpManager) { - return new InternalAqlFunctionsDriverImpl(configure, httpManager); - } - - public static InternalBatchDriverImpl createBatchDriver(ArangoConfigure configure, HttpManager httpManager) { - return new InternalBatchDriverImpl(configure, httpManager); - } - - public static InternalUsersDriverImpl createUsersDriver(ArangoConfigure configure, HttpManager httpManager) { - return new InternalUsersDriverImpl(configure, httpManager); - } - - public static InternalImportDriverImpl createImportDriver(ArangoConfigure configure, HttpManager httpManager) { - return new InternalImportDriverImpl(configure, httpManager); - } - - public static InternalDatabaseDriverImpl createDatabaseDriver(ArangoConfigure configure, HttpManager httpManager) { - return new InternalDatabaseDriverImpl(configure, httpManager); - } - - public static InternalEndpointDriverImpl createEndpointDriver(ArangoConfigure configure, HttpManager httpManager) { - return new InternalEndpointDriverImpl(configure, httpManager); - } - - public static InternalReplicationDriverImpl createReplicationDriver( - ArangoConfigure configure, - HttpManager httpManager) { - return new InternalReplicationDriverImpl(configure, httpManager); - } - - public static InternalGraphDriverImpl createGraphDriver( - ArangoConfigure configure, - InternalCursorDriver cursorDriver, - HttpManager httpManager) { - return new InternalGraphDriverImpl(configure, cursorDriver, httpManager); - } - - public static InternalTraversalDriverImpl createTraversalDriver( - ArangoConfigure configure, - HttpManager httpManager) { - return new InternalTraversalDriverImpl(configure, httpManager); - } - - public static InternalQueryCacheDriverImpl createQueryCacheDriver( - ArangoConfigure configure, - HttpManager httpManager) { - return new InternalQueryCacheDriverImpl(configure, httpManager); - } - -} diff --git a/src/main/java/com/arangodb/impl/InternalAdminDriverImpl.java b/src/main/java/com/arangodb/impl/InternalAdminDriverImpl.java deleted file mode 100644 index 4ad88a2c1..000000000 --- a/src/main/java/com/arangodb/impl/InternalAdminDriverImpl.java +++ /dev/null @@ -1,133 +0,0 @@ -/* - * Copyright (C) 2012 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.impl; - -import com.arangodb.ArangoConfigure; -import com.arangodb.ArangoException; -import com.arangodb.entity.AdminLogEntity; -import com.arangodb.entity.ArangoUnixTime; -import com.arangodb.entity.ArangoVersion; -import com.arangodb.entity.DefaultEntity; -import com.arangodb.entity.StatisticsDescriptionEntity; -import com.arangodb.entity.StatisticsEntity; -import com.arangodb.http.HttpManager; -import com.arangodb.http.HttpResponseEntity; -import com.arangodb.util.MapBuilder; - -/** - * @author tamtam180 - kirscheless at gmail.com - * - */ -public class InternalAdminDriverImpl extends BaseArangoDriverImpl implements com.arangodb.InternalAdminDriver { - - // MEMO: ADMINはdatabase関係ない - - InternalAdminDriverImpl(ArangoConfigure configure, HttpManager httpManager) { - super(configure, httpManager); - } - - @Override - public AdminLogEntity getServerLog( - Integer logLevel, - Boolean logLevelUpTo, - Integer start, - Integer size, - Integer offset, - Boolean sortAsc, - String text) throws ArangoException { - - // パラメータを作る - MapBuilder param = new MapBuilder(); - if (logLevel != null) { - if (logLevelUpTo != null && logLevelUpTo.booleanValue()) { - param.put("upto", logLevel); - } else { - param.put("level", logLevel); - } - } - param.put("start", start); - param.put("size", size); - param.put("offset", offset); - if (sortAsc != null) { - param.put("sort", sortAsc.booleanValue() ? "asc" : "desc"); - } - param.put("search", text); - - HttpResponseEntity res = httpManager.doGet(createEndpointUrl(null, "/_admin/log"), param.get()); - - return createEntity(res, AdminLogEntity.class); - } - - @Override - public StatisticsEntity getStatistics() throws ArangoException { - - HttpResponseEntity res = httpManager.doGet(createEndpointUrl(null, "/_admin/statistics")); - - return createEntity(res, StatisticsEntity.class); - } - - @Override - public StatisticsDescriptionEntity getStatisticsDescription() throws ArangoException { - - HttpResponseEntity res = httpManager.doGet(createEndpointUrl(null, "/_admin/statistics-description")); - - return createEntity(res, StatisticsDescriptionEntity.class); - } - - /** - * Returns the ArangoDB version - * - * @return a ArangoVersion object - * @throws ArangoException - * @see - * HttpMiscVersion documentation - */ - @Override - public ArangoVersion getVersion() throws ArangoException { - - HttpResponseEntity res = httpManager.doGet(createEndpointUrl(null, "/_api/version")); - - return createEntity(res, ArangoVersion.class); - } - - @Override - public ArangoUnixTime getTime() throws ArangoException { - - HttpResponseEntity res = httpManager.doGet(createEndpointUrl(null, "/_admin/time")); - - return createEntity(res, ArangoUnixTime.class); - } - - @Override - public DefaultEntity reloadRouting() throws ArangoException { - - HttpResponseEntity res = httpManager.doPost(createEndpointUrl(null, "/_admin/routing/reload"), null, - (String) null); - - return createEntity(res, DefaultEntity.class, null, false); - } - - @Override - public DefaultEntity executeScript(String database, String jsCode) throws ArangoException { - - HttpResponseEntity res = httpManager.doPost(createEndpointUrl(database, "/_admin/execute"), null, jsCode); - - return createEntity(res, DefaultEntity.class); - } - -} diff --git a/src/main/java/com/arangodb/impl/InternalAqlFunctionsDriverImpl.java b/src/main/java/com/arangodb/impl/InternalAqlFunctionsDriverImpl.java deleted file mode 100644 index a302186e1..000000000 --- a/src/main/java/com/arangodb/impl/InternalAqlFunctionsDriverImpl.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright (C) 2012 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.impl; - -import com.arangodb.ArangoConfigure; -import com.arangodb.ArangoException; -import com.arangodb.entity.AqlFunctionsEntity; -import com.arangodb.entity.DefaultEntity; -import com.arangodb.entity.EntityFactory; -import com.arangodb.http.HttpManager; -import com.arangodb.http.HttpResponseEntity; -import com.arangodb.util.MapBuilder; - -/** - * @author Florian Bartels - * - */ -public class InternalAqlFunctionsDriverImpl extends BaseArangoDriverImpl - implements com.arangodb.InternalAqlFunctionsDriver { - - private static final String API_AQLFUNCTION = "/_api/aqlfunction"; - - InternalAqlFunctionsDriverImpl(ArangoConfigure configure, HttpManager httpManager) { - super(configure, httpManager); - } - - @Override - public DefaultEntity createAqlFunction(String database, String name, String code) throws ArangoException { - HttpResponseEntity res = httpManager.doPost(createEndpointUrl(database, API_AQLFUNCTION), null, - EntityFactory.toJsonString(new MapBuilder().put("name", name).put("code", code).get())); - return createEntity(res, DefaultEntity.class, null, false); - } - - @Override - public AqlFunctionsEntity getAqlFunctions(String database, String namespace) throws ArangoException { - - String appendix = ""; - if (namespace != null) { - appendix = "?namespace=" + namespace; - } - HttpResponseEntity res = httpManager.doGet(createEndpointUrl(database, API_AQLFUNCTION + appendix)); - return createEntity(res, AqlFunctionsEntity.class); - - } - - @Override - public DefaultEntity deleteAqlFunction(String database, String name, boolean isNameSpace) throws ArangoException { - - HttpResponseEntity res = httpManager.doDelete(createEndpointUrl(database, API_AQLFUNCTION, name), - new MapBuilder().put("group", isNameSpace).get()); - - return createEntity(res, DefaultEntity.class); - - } - -} diff --git a/src/main/java/com/arangodb/impl/InternalBatchDriverImpl.java b/src/main/java/com/arangodb/impl/InternalBatchDriverImpl.java deleted file mode 100644 index 3f46db8bb..000000000 --- a/src/main/java/com/arangodb/impl/InternalBatchDriverImpl.java +++ /dev/null @@ -1,167 +0,0 @@ -/* - * Copyright (C) 2012 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.impl; - -import java.io.ByteArrayInputStream; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import com.arangodb.ArangoConfigure; -import com.arangodb.ArangoException; -import com.arangodb.entity.BatchResponseEntity; -import com.arangodb.entity.BatchResponseListEntity; -import com.arangodb.entity.DefaultEntity; -import com.arangodb.http.BatchPart; -import com.arangodb.http.HttpManager; -import com.arangodb.http.HttpResponseEntity; -import com.arangodb.http.InvocationObject; - -/** - * @author Florian Bartels - * - */ -public class InternalBatchDriverImpl extends BaseArangoDriverImpl { - - private static String newline = System.getProperty("line.separator"); - - private static final String BOUNDARY = "dlmtrMLTPRT"; - - private static final String DELIMITER = "--" + BOUNDARY; - - private BatchResponseListEntity batchResponseListEntity; - - InternalBatchDriverImpl(final ArangoConfigure configure, final HttpManager httpManager) { - super(configure, httpManager); - } - - public DefaultEntity executeBatch(final List callStack, final String defaultDataBase) - throws ArangoException { - - final StringBuilder sb = new StringBuilder(); - - final Map resolver = new HashMap(); - - for (final BatchPart bp : callStack) { - addBatchPart(sb, bp); - resolver.put(bp.getId(), bp.getInvocationObject()); - } - - sb.append(DELIMITER + "--"); - - final Map headers = new HashMap(); - headers.put("Content-Type", "multipart/form-data; boundary=" + BOUNDARY); - - final HttpResponseEntity res = httpManager.doPostWithHeaders(createEndpointUrl(defaultDataBase, "/_api/batch"), - null, null, headers, sb.toString()); - - final String data = res.getText(); - res.setContentType("application/json"); - res.setText(""); - final List batchResponseEntityList = handleResponse(resolver, data); - batchResponseListEntity = new BatchResponseListEntity(); - batchResponseListEntity.setBatchResponseEntities(batchResponseEntityList); - return createEntity(res, DefaultEntity.class, null, false); - } - - public BatchResponseListEntity getBatchResponseListEntity() { - return batchResponseListEntity; - } - - private List handleResponse(final Map resolver, final String data) { - String currentId = null; - Boolean fetchText = false; - final List batchResponseEntityList = new ArrayList(); - BatchResponseEntity batchResponseEntity = new BatchResponseEntity(null); - final StringBuilder sb = new StringBuilder(); - for (final String line : data.split(newline)) { - line.trim(); - line.replaceAll("\r", ""); - if (line.indexOf("Content-Id") != -1) { - addBatchResponseEntity(currentId, batchResponseEntityList, batchResponseEntity); - currentId = line.split(" ")[1].trim(); - batchResponseEntity = new BatchResponseEntity(resolver.get(currentId)); - batchResponseEntity.setRequestId(currentId); - } else if (isContentTypeLine(line)) { - final String ct = line.replaceAll("Content-Type: ", ""); - batchResponseEntity.httpResponseEntity.setContentType(ct); - } else if (line.indexOf("Etag") != -1) { - final String etag = line.split(" ")[1].replaceAll("\"", "").trim(); - batchResponseEntity.httpResponseEntity.setEtag(etag); - } else if (line.indexOf("HTTP/1.1") != -1) { - batchResponseEntity.httpResponseEntity.setStatusCode(Integer.valueOf(line.split(" ")[1])); - } else if (line.indexOf("Content-Length") != -1) { - fetchText = true; - sb.setLength(0); - } else if (isDelimiterLine(resolver, currentId, line)) { - fetchText = false; - copyResponseToEntity(batchResponseEntity, sb); - } else if (canFetchLine(fetchText, line)) { - sb.append(line); - } - } - if (batchResponseEntity.getHttpResponseEntity() != null) { - batchResponseEntityList.add(batchResponseEntity); - } - return batchResponseEntityList; - } - - private void copyResponseToEntity(final BatchResponseEntity batchResponseEntity, final StringBuilder sb) { - if (!batchResponseEntity.httpResponseEntity.isDumpResponse()) { - batchResponseEntity.httpResponseEntity.setText(sb.toString()); - } else { - final InputStream is = new ByteArrayInputStream(sb.toString().getBytes()); - batchResponseEntity.httpResponseEntity.setStream(is); - } - } - - private boolean isDelimiterLine( - final Map resolver, - final String currentId, - final String line) { - return line.indexOf(DELIMITER) != -1 && resolver.get(currentId) != null; - } - - private boolean canFetchLine(final Boolean fetchText, final String line) { - return fetchText && !line.equals(newline); - } - - private boolean isContentTypeLine(final String line) { - return line.indexOf("Content-Type:") != -1 - && line.indexOf("Content-Type: application/x-arango-batchpart") == -1; - } - - private void addBatchResponseEntity( - final String currentId, - final List batchResponseEntityList, - final BatchResponseEntity batchResponseEntity) { - if (currentId != null) { - batchResponseEntityList.add(batchResponseEntity); - } - } - - private void addBatchPart(final StringBuilder sb, final BatchPart bp) { - sb.append(DELIMITER + newline); - sb.append("Content-Type: application/x-arango-batchpart" + newline); - sb.append("Content-Id: " + bp.getId() + newline + newline); - sb.append(bp.getMethod() + " " + bp.getUrl() + " " + "HTTP/1.1" + newline); - sb.append("Host: " + this.configure.getArangoHost().getHost() + newline + newline); - sb.append(bp.getBody() == null ? "" : bp.getBody() + newline + newline); - } -} diff --git a/src/main/java/com/arangodb/impl/InternalCollectionDriverImpl.java b/src/main/java/com/arangodb/impl/InternalCollectionDriverImpl.java deleted file mode 100644 index a6c5f56f3..000000000 --- a/src/main/java/com/arangodb/impl/InternalCollectionDriverImpl.java +++ /dev/null @@ -1,209 +0,0 @@ -/* - * Copyright (C) 2012 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.impl; - -import com.arangodb.ArangoConfigure; -import com.arangodb.ArangoException; -import com.arangodb.entity.CollectionEntity; -import com.arangodb.entity.CollectionOptions; -import com.arangodb.entity.CollectionsEntity; -import com.arangodb.entity.EntityFactory; -import com.arangodb.http.HttpManager; -import com.arangodb.http.HttpResponseEntity; -import com.arangodb.util.MapBuilder; - -/** - * @author tamtam180 - kirscheless at gmail.com - * - */ -public class InternalCollectionDriverImpl extends BaseArangoDriverImpl - implements com.arangodb.InternalCollectionDriver { - - private static final String API_COLLECTION = "/_api/collection"; - - InternalCollectionDriverImpl(ArangoConfigure configure, HttpManager httpManager) { - super(configure, httpManager); - } - - @Override - public CollectionEntity createCollection(String database, String name, CollectionOptions collectionOptions) - throws ArangoException { - CollectionOptions tmpCollectionOptions = collectionOptions; - if (tmpCollectionOptions == null) { - tmpCollectionOptions = new CollectionOptions(); - } - HttpResponseEntity res = httpManager.doPost(createEndpointUrl(database, API_COLLECTION), null, - EntityFactory.toJsonString( - new MapBuilder().put("name", name).put("waitForSync", tmpCollectionOptions.getWaitForSync()) - .put("doCompact", tmpCollectionOptions.getDoCompact()) - .put("journalSize", tmpCollectionOptions.getJournalSize()) - .put("isSystem", tmpCollectionOptions.getIsSystem()) - .put("isVolatile", tmpCollectionOptions.getIsVolatile()) - .put("keyOptions", tmpCollectionOptions.getKeyOptions()) - .put("numberOfShards", tmpCollectionOptions.getNumberOfShards()) - .put("shardKeys", tmpCollectionOptions.getShardKeys()) - .put("type", tmpCollectionOptions.getType() == null ? null - : tmpCollectionOptions.getType().getType()) - .get())); - - return createEntity(res, CollectionEntity.class); - - } - - @Override - public CollectionEntity getCollection(String database, String name) throws ArangoException { - validateCollectionName(name); - - HttpResponseEntity res = httpManager.doGet(createEndpointUrl(database, API_COLLECTION, name), null); - - return createEntity(res, CollectionEntity.class); - } - - @Override - public CollectionEntity getCollectionRevision(String database, String name) throws ArangoException { - - validateCollectionName(name); - - HttpResponseEntity res = httpManager.doGet(createEndpointUrl(database, API_COLLECTION, name, "/revision"), - null); - - return createEntity(res, CollectionEntity.class); - } - - @Override - public CollectionEntity getCollectionProperties(String database, String name) throws ArangoException { - - validateCollectionName(name); - - HttpResponseEntity res = httpManager.doGet(createEndpointUrl(database, API_COLLECTION, name, "/properties"), - null); - - return createEntity(res, CollectionEntity.class); - } - - @Override - public CollectionEntity getCollectionCount(String database, String name) throws ArangoException { - - validateCollectionName(name); - - HttpResponseEntity res = httpManager.doGet(createEndpointUrl(database, API_COLLECTION, name, "/count"), null); - - return createEntity(res, CollectionEntity.class); - } - - @Override - public CollectionEntity getCollectionFigures(String database, String name) throws ArangoException { - - validateCollectionName(name); - - HttpResponseEntity res = httpManager.doGet(createEndpointUrl(database, API_COLLECTION, name, "/figures"), null); - - return createEntity(res, CollectionEntity.class); - } - - @Override - public CollectionEntity getCollectionChecksum(String database, String name, Boolean withRevisions, Boolean withData) - throws ArangoException { - - validateCollectionName(name); - HttpResponseEntity res = httpManager.doGet(createEndpointUrl(database, API_COLLECTION, name, "/checksum"), - new MapBuilder().put("withRevisions", withRevisions).put("withData", withData).get()); - - return createEntity(res, CollectionEntity.class); - - } - - @Override - public CollectionsEntity getCollections(String database, Boolean excludeSystem) throws ArangoException { - - HttpResponseEntity res = httpManager.doGet(createEndpointUrl(database, API_COLLECTION), null, - new MapBuilder().put("excludeSystem", excludeSystem).get()); - - return createEntity(res, CollectionsEntity.class); - - } - - @Override - public CollectionEntity loadCollection(String database, String name, Boolean count) throws ArangoException { - - validateCollectionName(name); - HttpResponseEntity res = httpManager.doPut(createEndpointUrl(database, API_COLLECTION, name, "/load"), null, - EntityFactory.toJsonString(new MapBuilder("count", count).get())); - - return createEntity(res, CollectionEntity.class); - - } - - @Override - public CollectionEntity unloadCollection(String database, String name) throws ArangoException { - - validateCollectionName(name); - - HttpResponseEntity res = httpManager.doPut(createEndpointUrl(database, "/_api/collection/", name, "/unload"), - null, null); - - return createEntity(res, CollectionEntity.class); - } - - @Override - public CollectionEntity truncateCollection(String database, String name) throws ArangoException { - - validateCollectionName(name); - - HttpResponseEntity res = httpManager.doPut(createEndpointUrl(database, API_COLLECTION, name, "/truncate"), null, - null); - - return createEntity(res, CollectionEntity.class); - } - - @Override - public CollectionEntity setCollectionProperties( - String database, - String name, - Boolean newWaitForSync, - Long journalSize) throws ArangoException { - - validateCollectionName(name); - HttpResponseEntity res = httpManager.doPut(createEndpointUrl(database, API_COLLECTION, name, "/properties"), - null, EntityFactory.toJsonString( - new MapBuilder().put("waitForSync", newWaitForSync).put("journalSize", journalSize).get())); - - return createEntity(res, CollectionEntity.class); - } - - @Override - public CollectionEntity renameCollection(String database, String name, String newName) throws ArangoException { - - validateCollectionName(newName); - - HttpResponseEntity res = httpManager.doPut(createEndpointUrl(database, API_COLLECTION, name, "/rename"), null, - EntityFactory.toJsonString(new MapBuilder("name", newName).get())); - - return createEntity(res, CollectionEntity.class); - } - - @Override - public CollectionEntity deleteCollection(String database, String name) throws ArangoException { - - validateCollectionName(name); - - HttpResponseEntity res = httpManager.doDelete(createEndpointUrl(database, API_COLLECTION, name), null); - - return createEntity(res, CollectionEntity.class); - } - -} diff --git a/src/main/java/com/arangodb/impl/InternalCursorDriverImpl.java b/src/main/java/com/arangodb/impl/InternalCursorDriverImpl.java deleted file mode 100644 index 7ee5e12e8..000000000 --- a/src/main/java/com/arangodb/impl/InternalCursorDriverImpl.java +++ /dev/null @@ -1,249 +0,0 @@ -/* - * Copyright (C) 2012 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.impl; - -import java.util.Collections; -import java.util.Map; - -import com.arangodb.ArangoConfigure; -import com.arangodb.ArangoDriver; -import com.arangodb.ArangoException; -import com.arangodb.CursorRawResult; -import com.arangodb.CursorResult; -import com.arangodb.DocumentCursorResult; -import com.arangodb.entity.CursorEntity; -import com.arangodb.entity.DefaultEntity; -import com.arangodb.entity.DocumentEntity; -import com.arangodb.entity.EntityFactory; -import com.arangodb.entity.QueriesResultEntity; -import com.arangodb.entity.QueryTrackingPropertiesEntity; -import com.arangodb.entity.ShortestPathEntity; -import com.arangodb.http.HttpManager; -import com.arangodb.http.HttpResponseEntity; -import com.arangodb.util.AqlQueryOptions; -import com.arangodb.util.GraphQueryUtil; -import com.arangodb.util.MapBuilder; -import com.arangodb.util.ShortestPathOptions; -import com.google.gson.JsonObject; - -/** - * @author tamtam180 - kirscheless at gmail.com - */ -public class InternalCursorDriverImpl extends BaseArangoDriverImpl implements com.arangodb.InternalCursorDriver { - - InternalCursorDriverImpl(final ArangoConfigure configure, final HttpManager httpManager) { - super(configure, httpManager); - } - - @Override - public CursorEntity validateQuery(final String database, final String query) throws ArangoException { - final HttpResponseEntity res = httpManager.doPost(createEndpointUrl(database, "/_api/query"), null, - EntityFactory.toJsonString(new MapBuilder("query", query).get())); - - return createEntity(res, CursorEntity.class); - } - - @Override - public String executeAqlQueryJSON( - final String database, - final String query, - final Map bindVars, - final AqlQueryOptions aqlQueryOptions) throws ArangoException { - - return getJSONResponseText(getCursor(database, query, bindVars, aqlQueryOptions)); - } - - @SuppressWarnings("unchecked") - @Override - public CursorEntity executeCursorEntityQuery( - final String database, - final String query, - final Map bindVars, - final AqlQueryOptions aqlQueryOptions, - final Class... clazz) throws ArangoException { - - final HttpResponseEntity res = getCursor(database, query, bindVars, aqlQueryOptions); - - return createEntity(res, CursorEntity.class, clazz); - } - - private HttpResponseEntity getCursor( - final String database, - final String query, - final Map bindVars, - final AqlQueryOptions aqlQueryOptions) throws ArangoException { - - final Map map = aqlQueryOptions.toMap(); - map.put("query", query); - map.put("bindVars", bindVars == null ? Collections.emptyMap() : bindVars); - - return httpManager.doPost(createEndpointUrl(database, "/_api/cursor"), null, EntityFactory.toJsonString(map)); - } - - @SuppressWarnings("unchecked") - @Override - public CursorEntity continueQuery(final String database, final long cursorId, final Class... clazz) - throws ArangoException { - - final HttpResponseEntity res = httpManager.doPut(createEndpointUrl(database, "/_api/cursor", cursorId), null, - null); - - return createEntity(res, CursorEntity.class, clazz); - } - - @Override - public DefaultEntity finishQuery(final String database, final long cursorId) throws ArangoException { - final HttpResponseEntity res = httpManager.doDelete(createEndpointUrl(database, "/_api/cursor/", cursorId), - null); - - try { - return createEntity(res, DefaultEntity.class); - } catch (final ArangoException e) { - // TODO Mode - if (e.getErrorNumber() == 1600) { - // 既に削除されている - return (DefaultEntity) e.getEntity(); - } - throw e; - } - } - - @Override - public > DocumentCursorResult executeBaseCursorQuery( - final String database, - final String query, - final Map bindVars, - final AqlQueryOptions aqlQueryOptions, - final Class classDocumentEntity, - final Class clazz) throws ArangoException { - - final CursorEntity entity = executeCursorEntityQuery(database, query, bindVars, aqlQueryOptions, - classDocumentEntity, clazz); - - return new DocumentCursorResult(database, this, entity, classDocumentEntity, clazz); - } - - @Override - public CursorResult executeAqlQuery( - final String database, - final String query, - final Map bindVars, - final AqlQueryOptions aqlQueryOptions, - final Class clazz) throws ArangoException { - - final CursorEntity entity = executeCursorEntityQuery(database, query, bindVars, aqlQueryOptions, clazz); - - return new CursorResult(database, this, entity, clazz); - } - - @Override - public CursorRawResult executeAqlQueryRaw( - final String database, - final String query, - final Map bindVars, - final AqlQueryOptions aqlQueryOptions) throws ArangoException { - - final CursorEntity entity = executeCursorEntityQuery(database, query, bindVars, aqlQueryOptions, - JsonObject.class); - - return new CursorRawResult(database, this, entity); - } - - /** - * @deprecated use AQL instead - */ - @Deprecated - @SuppressWarnings("unchecked") - @Override - public ShortestPathEntity getShortestPath( - final String database, - final String graphName, - final Object startVertexExample, - final Object endVertexExample, - final ShortestPathOptions shortestPathOptions, - final AqlQueryOptions aqlQueryOptions, - final Class vertexClass, - final Class edgeClass, - final ArangoDriver driver) throws ArangoException { - - validateCollectionName(graphName); - - ShortestPathOptions tmpShortestPathOptions = shortestPathOptions; - if (tmpShortestPathOptions == null) { - tmpShortestPathOptions = new ShortestPathOptions(); - } - - MapBuilder mapBuilder = new MapBuilder(); - final String query = GraphQueryUtil.createShortestPathQuery(driver, database, graphName, startVertexExample, - endVertexExample, tmpShortestPathOptions, vertexClass, edgeClass, mapBuilder); - - final Map bindVars = mapBuilder.get(); - final HttpResponseEntity res = getCursor(database, query, bindVars, aqlQueryOptions); - - return createEntity(res, ShortestPathEntity.class, vertexClass, edgeClass); - } - - @Override - public QueryTrackingPropertiesEntity getQueryTrackingProperties(final String database) throws ArangoException { - - final HttpResponseEntity res = httpManager.doGet(createEndpointUrl(database, "/_api/query/properties"), null, - null); - - return createEntity(res, QueryTrackingPropertiesEntity.class); - } - - @Override - public QueryTrackingPropertiesEntity setQueryTrackingProperties( - final String database, - final QueryTrackingPropertiesEntity properties) throws ArangoException { - final HttpResponseEntity res = httpManager.doPut(createEndpointUrl(database, "/_api/query/properties"), null, - EntityFactory.toJsonString(properties)); - - return createEntity(res, QueryTrackingPropertiesEntity.class); - } - - @Override - public QueriesResultEntity getCurrentlyRunningQueries(final String database) throws ArangoException { - final HttpResponseEntity res = httpManager.doGet(createEndpointUrl(database, "/_api/query/current"), null, - null); - - return createEntity(res, QueriesResultEntity.class); - } - - @Override - public QueriesResultEntity getSlowQueries(final String database) throws ArangoException { - final HttpResponseEntity res = httpManager.doGet(createEndpointUrl(database, "/_api/query/slow"), null, null); - - return createEntity(res, QueriesResultEntity.class); - } - - @Override - public DefaultEntity deleteSlowQueries(final String database) throws ArangoException { - final HttpResponseEntity res = httpManager.doDelete(createEndpointUrl(database, "/_api/query/slow"), null, - null); - - return createEntity(res, DefaultEntity.class); - } - - @Override - public DefaultEntity killQuery(final String database, final String id) throws ArangoException { - final HttpResponseEntity res = httpManager.doDelete(createEndpointUrl(database, "/_api/query", id), null, null); - - return createEntity(res, DefaultEntity.class); - } - -} diff --git a/src/main/java/com/arangodb/impl/InternalDatabaseDriverImpl.java b/src/main/java/com/arangodb/impl/InternalDatabaseDriverImpl.java deleted file mode 100644 index a9de848ca..000000000 --- a/src/main/java/com/arangodb/impl/InternalDatabaseDriverImpl.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Copyright (C) 2012,2013 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.impl; - -import java.util.TreeMap; - -import com.arangodb.ArangoConfigure; -import com.arangodb.ArangoException; -import com.arangodb.entity.BooleanResultEntity; -import com.arangodb.entity.DatabaseEntity; -import com.arangodb.entity.EntityFactory; -import com.arangodb.entity.StringsResultEntity; -import com.arangodb.entity.UserEntity; -import com.arangodb.http.HttpManager; -import com.arangodb.http.HttpResponseEntity; - -/** - * @author tamtam180 - kirscheless at gmail.com - * - */ -public class InternalDatabaseDriverImpl extends BaseArangoDriverImpl implements com.arangodb.InternalDatabaseDriver { - - private static final String API_DATABASE = "/_api/database"; - - InternalDatabaseDriverImpl(ArangoConfigure configure, HttpManager httpManager) { - super(configure, httpManager); - } - - @Override - public DatabaseEntity getCurrentDatabase() throws ArangoException { - - HttpResponseEntity res = httpManager.doGet(createEndpointUrl(null, "/_api/database/current")); - return createEntity(res, DatabaseEntity.class); - - } - - @Override - public StringsResultEntity getDatabases(boolean currentUserAccessableOnly, String username, String password) - throws ArangoException { - HttpResponseEntity res = httpManager.doGet( - createEndpointUrl(null, API_DATABASE, currentUserAccessableOnly ? "user" : null), null, null, username, - password); - return createEntity(res, StringsResultEntity.class); - - } - - @Override - public BooleanResultEntity createDatabase(String database, UserEntity... users) throws ArangoException { - - validateDatabaseName(database, false); - - TreeMap body = new TreeMap(); - body.put("name", database); - if (users != null && users.length > 0) { - body.put("users", users); - } - - HttpResponseEntity res = httpManager.doPost(createEndpointUrl(null, API_DATABASE), null, - EntityFactory.toJsonString(body)); - - return createEntity(res, BooleanResultEntity.class); - - } - - @Override - public BooleanResultEntity deleteDatabase(String database) throws ArangoException { - - validateDatabaseName(database, false); - - TreeMap body = new TreeMap(); - body.put("name", database); - - HttpResponseEntity res = httpManager.doDelete(createEndpointUrl(null, API_DATABASE, database), null); - - return createEntity(res, BooleanResultEntity.class); - - } - -} diff --git a/src/main/java/com/arangodb/impl/InternalDocumentDriverImpl.java b/src/main/java/com/arangodb/impl/InternalDocumentDriverImpl.java deleted file mode 100644 index a909fb262..000000000 --- a/src/main/java/com/arangodb/impl/InternalDocumentDriverImpl.java +++ /dev/null @@ -1,302 +0,0 @@ -/* - * Copyright (C) 2012 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.impl; - -import java.util.List; -import java.util.Map; - -import com.arangodb.ArangoConfigure; -import com.arangodb.ArangoException; -import com.arangodb.entity.BaseDocument; -import com.arangodb.entity.CursorEntity; -import com.arangodb.entity.DefaultEntity; -import com.arangodb.entity.DocumentEntity; -import com.arangodb.entity.EdgeEntity; -import com.arangodb.entity.EntityFactory; -import com.arangodb.http.HttpManager; -import com.arangodb.http.HttpResponseEntity; -import com.arangodb.util.EdgeUtils; -import com.arangodb.util.MapBuilder; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; - -/** - * @author tamtam180 - kirscheless at gmail.com - * - */ -public class InternalDocumentDriverImpl extends BaseArangoDriverImpl implements com.arangodb.InternalDocumentDriver { - - private static final String WAIT_FOR_SYNC = "waitForSync"; - - InternalDocumentDriverImpl(final ArangoConfigure configure, final HttpManager httpManager) { - super(configure, httpManager); - } - - private DocumentEntity internalCreateDocument( - final String database, - final String collectionName, - final String documentKey, - final T value, - final Boolean waitForSync, - final boolean raw) throws ArangoException { - - validateCollectionName(collectionName); - - String body; - if (raw) { - body = value.toString(); - } else if (documentKey != null) { - final JsonElement elem = EntityFactory.toJsonElement(value, false); - if (elem.isJsonObject()) { - elem.getAsJsonObject().addProperty(BaseDocument.KEY, documentKey); - } - body = EntityFactory.toJsonString(elem); - } else { - body = EntityFactory.toJsonString(value); - } - - final HttpResponseEntity res = httpManager.doPost(createDocumentEndpointUrl(database), - new MapBuilder().put(COLLECTION, collectionName).put(WAIT_FOR_SYNC, waitForSync).get(), body); - - @SuppressWarnings("unchecked") - final DocumentEntity result = createEntity(res, DocumentEntity.class); - - annotationHandler.updateDocumentAttributes(value, result.getDocumentRevision(), result.getDocumentHandle(), - result.getDocumentKey()); - - result.setEntity(value); - return result; - } - - @Override - public DocumentEntity createDocument( - final String database, - final String collectionName, - final String documentKey, - final T value, - final Boolean waitForSync) throws ArangoException { - return internalCreateDocument(database, collectionName, documentKey, value, waitForSync, false); - } - - @Override - public DocumentEntity createDocumentRaw( - final String database, - final String collectionName, - final String rawJsonObjectString, - final Boolean waitForSync) throws ArangoException { - return internalCreateDocument(database, collectionName, null, rawJsonObjectString, waitForSync, true); - } - - @SuppressWarnings("unchecked") - @Override - public DocumentEntity replaceDocument( - final String database, - final String documentHandle, - final T value, - final String rev, - final Boolean waitForSync) throws ArangoException { - - validateDocumentHandle(documentHandle); - - final HttpResponseEntity res = httpManager.doPut(createDocumentEndpointUrl(database, documentHandle), - createRevisionCheckHeader(rev), new MapBuilder().put(WAIT_FOR_SYNC, waitForSync).get(), - EntityFactory.toJsonString(value)); - - final DocumentEntity result = createEntity(res, DocumentEntity.class); - annotationHandler.updateDocumentRev(value, result.getDocumentRevision()); - result.setEntity(value); - return result; - } - - @Override - public DocumentEntity replaceDocumentRaw( - final String database, - final String documentHandle, - final String rawJsonString, - final String rev, - final Boolean waitForSync) throws ArangoException { - - validateDocumentHandle(documentHandle); - final HttpResponseEntity res = httpManager.doPut(createDocumentEndpointUrl(database, documentHandle), - createRevisionCheckHeader(rev), new MapBuilder().put(WAIT_FOR_SYNC, waitForSync).get(), rawJsonString); - - @SuppressWarnings("unchecked") - final DocumentEntity result = createEntity(res, DocumentEntity.class); - result.setEntity(rawJsonString); - return result; - } - - @Override - public DocumentEntity updateDocument( - final String database, - final String documentHandle, - final T value, - final String rev, - final Boolean waitForSync, - final Boolean keepNull) throws ArangoException { - - validateDocumentHandle(documentHandle); - final HttpResponseEntity res = httpManager.doPatch(createDocumentEndpointUrl(database, documentHandle), - createRevisionCheckHeader(rev), - new MapBuilder().put(WAIT_FOR_SYNC, waitForSync).put("keepNull", keepNull).get(), - EntityFactory.toJsonString(value, keepNull != null && !keepNull)); - - @SuppressWarnings("unchecked") - final DocumentEntity result = createEntity(res, DocumentEntity.class); - annotationHandler.updateDocumentAttributes(value, result.getDocumentRevision(), result.getDocumentHandle(), - result.getDocumentKey()); - result.setEntity(value); - return result; - } - - @Override - public DocumentEntity updateDocumentRaw( - final String database, - final String documentHandle, - final String rawJsonString, - final String rev, - final Boolean waitForSync, - final Boolean keepNull) throws ArangoException { - - validateDocumentHandle(documentHandle); - final HttpResponseEntity res = httpManager.doPatch(createDocumentEndpointUrl(database, documentHandle), - createRevisionCheckHeader(rev), - new MapBuilder().put(WAIT_FOR_SYNC, waitForSync).put("keepNull", keepNull).get(), rawJsonString); - - @SuppressWarnings("unchecked") - final DocumentEntity result = createEntity(res, DocumentEntity.class); - result.setEntity(rawJsonString); - return result; - } - - @Override - public List getDocuments(final String database, final String collectionName) throws ArangoException { - final HttpResponseEntity res = httpManager.doPut(createEndpointUrl(database, "/_api/simple/all-keys"), null, - EntityFactory.toJsonString(new MapBuilder().put(COLLECTION, collectionName).put("type", "id").get())); - - @SuppressWarnings("unchecked") - final CursorEntity tmp = createEntity(res, CursorEntity.class, String.class); - - return tmp.getResults(); - } - - @Override - public String checkDocument(final String database, final String documentHandle) throws ArangoException { - validateDocumentHandle(documentHandle); - final HttpResponseEntity res = httpManager.doHead(createDocumentEndpointUrl(database, documentHandle), null); - - final DefaultEntity entity = createEntity(res, DefaultEntity.class); - return entity.getEtag(); - - } - - @Override - public DocumentEntity getDocument( - final String database, - final String documentHandle, - final Class clazz, - final String ifNoneMatchRevision, - final String ifMatchRevision) throws ArangoException { - - validateDocumentHandle(documentHandle); - final HttpResponseEntity res = httpManager.doGet(createDocumentEndpointUrl(database, documentHandle), - new MapBuilder().put("If-None-Match", ifNoneMatchRevision, true).put("If-Match", ifMatchRevision).get(), - null); - @SuppressWarnings("unchecked") - DocumentEntity entity = createEntity(res, DocumentEntity.class, clazz); - if (entity == null) { - entity = new DocumentEntity(); - } - return entity; - } - - @Override - public String getDocumentRaw( - final String database, - final String documentHandle, - final String ifNoneMatchRevision, - final String ifMatchRevision) throws ArangoException { - - validateDocumentHandle(documentHandle); - final HttpResponseEntity res = httpManager.doGet(createDocumentEndpointUrl(database, documentHandle), - new MapBuilder().put("If-None-Match", ifNoneMatchRevision, true).put("If-Match", ifMatchRevision).get(), - null); - - if (res.getStatusCode() >= 400) { - final BaseDocument entity = new BaseDocument(); - entity.setError(true); - entity.setCode(res.getStatusCode()); - entity.setStatusCode(res.getStatusCode()); - entity.setErrorNumber(res.getStatusCode()); - entity.setErrorMessage(res.getText()); - throw new ArangoException(entity); - } - - return res.getText(); - } - - @Override - public DocumentEntity deleteDocument(final String database, final String documentHandle, final String rev) - throws ArangoException { - - validateDocumentHandle(documentHandle); - final HttpResponseEntity res = httpManager.doDelete(createDocumentEndpointUrl(database, documentHandle), - createRevisionCheckHeader(rev), null); - return createEntity(res, DocumentEntity.class); - } - - private Map createRevisionCheckHeader(final String rev) { - Map header = null; - if (rev != null) { - final MapBuilder mapBuilder = new MapBuilder().put("If-Match", rev); - header = mapBuilder.get(); - } - return header; - } - - @Override - public EdgeEntity createEdge( - final String database, - final String collectionName, - final String documentKey, - final T value, - final String fromHandle, - final String toHandle, - final Boolean waitForSync) throws ArangoException { - - validateCollectionName(collectionName); - - final JsonObject obj = EdgeUtils.valueToEdgeJsonObject(documentKey, fromHandle, toHandle, value); - - final HttpResponseEntity res = httpManager.doPost(createDocumentEndpointUrl(database), - new MapBuilder().put(COLLECTION, collectionName).put(WAIT_FOR_SYNC, waitForSync).get(), - EntityFactory.toJsonString(obj)); - - @SuppressWarnings("unchecked") - final EdgeEntity entity = createEntity(res, EdgeEntity.class); - - if (value != null) { - entity.setEntity(value); - annotationHandler.updateDocumentAttributes(value, entity.getDocumentRevision(), entity.getDocumentHandle(), - entity.getDocumentKey()); - } - - entity.setFromVertexHandle(fromHandle); - entity.setToVertexHandle(toHandle); - return entity; - } -} diff --git a/src/main/java/com/arangodb/impl/InternalEndpointDriverImpl.java b/src/main/java/com/arangodb/impl/InternalEndpointDriverImpl.java deleted file mode 100644 index e55a19792..000000000 --- a/src/main/java/com/arangodb/impl/InternalEndpointDriverImpl.java +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Copyright (C) 2012,2013 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.impl; - -import java.lang.reflect.Type; -import java.util.List; - -import com.arangodb.ArangoConfigure; -import com.arangodb.ArangoException; -import com.arangodb.entity.BooleanResultEntity; -import com.arangodb.entity.Endpoint; -import com.arangodb.entity.EntityFactory; -import com.arangodb.http.HttpManager; -import com.arangodb.http.HttpResponseEntity; -import com.arangodb.util.MapBuilder; -import com.arangodb.util.StringUtils; -import com.google.gson.reflect.TypeToken; - -/** - * @author tamtam180 - kirscheless at gmail.com - * @since 1.4 - */ -public class InternalEndpointDriverImpl extends BaseArangoDriverImpl implements com.arangodb.InternalEndpointDriver { - - private static final String API_ENDPOINT = "/_api/endpoint"; - - InternalEndpointDriverImpl(ArangoConfigure configure, HttpManager httpManager) { - super(configure, httpManager); - } - - @Override - public BooleanResultEntity createEndpoint(String endpoint, String... databases) throws ArangoException { - - // TODO: validate endpoint - - // validate databases - if (databases != null) { - for (String db : databases) { - validateDatabaseName(db, false); - } - } - - HttpResponseEntity res = httpManager.doPost(createEndpointUrl(null, API_ENDPOINT), null, - EntityFactory.toJsonString(new MapBuilder().put("endpoint", endpoint).put("databases", databases).get())); - - return createEntity(res, BooleanResultEntity.class); - - } - - @Override - public List getEndpoints() throws ArangoException { - - Type type = new TypeToken>() { - }.getType(); - HttpResponseEntity res = httpManager.doGet(createEndpointUrl(null, API_ENDPOINT)); - - // because it is not include common-attribute. - return EntityFactory.createEntity(res.getText(), type); - - } - - @Override - public BooleanResultEntity deleteEndpoint(String endpoint) throws ArangoException { - - // TODO: validate endpoint - - HttpResponseEntity res = httpManager.doDelete( - createEndpointUrl(null, API_ENDPOINT, StringUtils.encodeUrl(endpoint)), null); - - return createEntity(res, BooleanResultEntity.class); - - } - -} diff --git a/src/main/java/com/arangodb/impl/InternalGraphDriverImpl.java b/src/main/java/com/arangodb/impl/InternalGraphDriverImpl.java deleted file mode 100644 index 66321bf38..000000000 --- a/src/main/java/com/arangodb/impl/InternalGraphDriverImpl.java +++ /dev/null @@ -1,689 +0,0 @@ -/* - * Copyright (C) 2012,2013 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.impl; - -import java.util.ArrayList; -import java.util.List; - -import com.arangodb.ArangoConfigure; -import com.arangodb.ArangoException; -import com.arangodb.InternalCursorDriver; -import com.arangodb.entity.DeletedEntity; -import com.arangodb.entity.EdgeDefinitionEntity; -import com.arangodb.entity.EdgeEntity; -import com.arangodb.entity.EntityFactory; -import com.arangodb.entity.GraphEntity; -import com.arangodb.entity.GraphGetCollectionsResultEntity; -import com.arangodb.entity.GraphsEntity; -import com.arangodb.entity.marker.VertexEntity; -import com.arangodb.http.BatchHttpManager; -import com.arangodb.http.HttpManager; -import com.arangodb.http.HttpResponseEntity; -import com.arangodb.util.CollectionUtils; -import com.arangodb.util.EdgeUtils; -import com.arangodb.util.MapBuilder; -import com.arangodb.util.StringUtils; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; - -/** - * @author tamtam180 - kirscheless at gmail.com - * @author gschwab - * @author a-brandt - */ -public class InternalGraphDriverImpl extends BaseArangoDriverWithCursorImpl - implements com.arangodb.InternalGraphDriver { - - private static final String WAIT_FOR_SYNC = "waitForSync"; - private static final String IF_NONE_MATCH = "If-None-Match"; - private static final String IF_MATCH = "If-Match"; - private static final String UNKNOWN_ERROR = "unknown error"; - private static final String VERTEX = "/vertex"; - private static final String EDGE = "/edge"; - private static final String EXCLUDE_ORPHAN = "excludeOrphan"; - - InternalGraphDriverImpl(final ArangoConfigure configure, final InternalCursorDriver cursorDriver, - final HttpManager httpManager) { - super(configure, cursorDriver, httpManager); - } - - @Override - public GraphEntity createGraph(final String databaseName, final String graphName, final Boolean waitForSync) - throws ArangoException { - final HttpResponseEntity response = httpManager.doPost(createGharialEndpointUrl(databaseName), - new MapBuilder().put(WAIT_FOR_SYNC, waitForSync).get(), - EntityFactory.toJsonString(new MapBuilder().put("name", graphName).get())); - return createEntity(response, GraphEntity.class); - } - - @Override - public GraphEntity createGraph( - final String databaseName, - final String graphName, - final List edgeDefinitions, - final List orphanCollections, - final Boolean waitForSync) throws ArangoException { - - final HttpResponseEntity response = httpManager - .doPost(createGharialEndpointUrl(databaseName), new MapBuilder().put(WAIT_FOR_SYNC, waitForSync).get(), - EntityFactory.toJsonString( - new MapBuilder().put("name", graphName).put("edgeDefinitions", edgeDefinitions) - .put("orphanCollections", orphanCollections).get())); - return createEntity(response, GraphEntity.class); - } - - @Override - public GraphsEntity getGraphs(final String databaseName) throws ArangoException { - - final GraphsEntity graphsEntity = new GraphsEntity(); - final List graphEntities = new ArrayList(); - final List graphList = this.getGraphList(databaseName); - if (CollectionUtils.isNotEmpty(graphList)) { - for (final String graphName : graphList) { - graphEntities.add(this.getGraph(databaseName, graphName)); - } - } - graphsEntity.setGraphs(graphEntities); - return graphsEntity; - - } - - @Override - public List getGraphList(final String databaseName) throws ArangoException { - final HttpResponseEntity res = httpManager.doGet(createGharialEndpointUrl(databaseName)); - final GraphsEntity graphsEntity = createEntity(res, GraphsEntity.class); - final List graphList = new ArrayList(); - final List graphs = graphsEntity.getGraphs(); - if (CollectionUtils.isNotEmpty(graphs)) { - for (final GraphEntity graph : graphs) { - graphList.add(graph.getDocumentKey()); - } - } - return graphList; - } - - @Override - public GraphEntity getGraph(final String databaseName, final String graphName) throws ArangoException { - validateCollectionName(graphName); // ?? - final HttpResponseEntity res = httpManager.doGet( - createGharialEndpointUrl(databaseName, StringUtils.encodeUrl(graphName)), new MapBuilder().get(), null); - return createEntity(res, GraphEntity.class); - - } - - @Override - public DeletedEntity deleteGraph(final String databaseName, final String graphName, final Boolean dropCollections) - throws ArangoException { - validateCollectionName(graphName); // ?? - final HttpResponseEntity res = httpManager.doDelete( - createGharialEndpointUrl(databaseName, StringUtils.encodeUrl(graphName)), new MapBuilder().get(), - new MapBuilder().put("dropCollections", dropCollections).get()); - - if (wrongResult(res)) { - throw new ArangoException(UNKNOWN_ERROR); - } - - DeletedEntity result; - if (isInBatchMode()) { - result = new DeletedEntity(); - } else { - result = createEntity(res, DeletedEntity.class, null, true); - } - - return result; - } - - @Override - public List getVertexCollections( - final String databaseName, - final String graphName, - final boolean excludeOrphan) throws ArangoException { - validateCollectionName(graphName); - final HttpResponseEntity res = httpManager.doGet( - createGharialEndpointUrl(databaseName, StringUtils.encodeUrl(graphName), VERTEX), - new MapBuilder().put(EXCLUDE_ORPHAN, excludeOrphan).get()); - - if (wrongResult(res)) { - throw new ArangoException(UNKNOWN_ERROR); - } - - GraphGetCollectionsResultEntity result; - if (isInBatchMode()) { - result = new GraphGetCollectionsResultEntity(); - } else { - result = createEntity(res, GraphGetCollectionsResultEntity.class, null, true); - } - return result.getCollections(); - } - - /** - * Removes a vertex collection from the graph and optionally deletes the - * collection, if it is not used in any other graph. - * - * @param databaseName - * @param graphName - * @param collectionName - * @param dropCollection - * @throws ArangoException - */ - @Override - public DeletedEntity deleteVertexCollection( - final String databaseName, - final String graphName, - final String collectionName, - final Boolean dropCollection) throws ArangoException { - validateDatabaseName(databaseName, false); - validateCollectionName(collectionName); - validateCollectionName(graphName); - - final HttpResponseEntity res = httpManager.doDelete( - createGharialEndpointUrl(databaseName, StringUtils.encodeUrl(graphName), VERTEX, - StringUtils.encodeUrl(collectionName)), - new MapBuilder().get(), new MapBuilder().put("dropCollection", dropCollection).get()); - - if (wrongResult(res)) { - throw new ArangoException(UNKNOWN_ERROR); - } - - DeletedEntity result; - if (isInBatchMode()) { - result = new DeletedEntity(); - } else { - result = createEntity(res, DeletedEntity.class, null, true); - } - - return result; - } - - @Override - public GraphEntity createVertexCollection( - final String databaseName, - final String graphName, - final String collectionName) throws ArangoException { - validateCollectionName(graphName); - validateCollectionName(collectionName); - - final HttpResponseEntity res = httpManager.doPost( - createGharialEndpointUrl(databaseName, StringUtils.encodeUrl(graphName), VERTEX), null, - EntityFactory.toJsonString(new MapBuilder().put(COLLECTION, collectionName).get())); - - if (wrongResult(res)) { - throw new ArangoException(UNKNOWN_ERROR); - } - - GraphEntity result; - if (isInBatchMode()) { - result = new GraphEntity(); - } else { - result = createEntity(res, GraphEntity.class, null, true); - } - - return result; - } - - @Override - public List getEdgeCollections(final String databaseName, final String graphName) throws ArangoException { - validateCollectionName(graphName); - final HttpResponseEntity res = httpManager - .doGet(createGharialEndpointUrl(databaseName, StringUtils.encodeUrl(graphName), EDGE)); - - if (wrongResult(res)) { - throw new ArangoException(UNKNOWN_ERROR); - } - - GraphGetCollectionsResultEntity result; - if (isInBatchMode()) { - result = new GraphGetCollectionsResultEntity(); - } else { - result = createEntity(res, GraphGetCollectionsResultEntity.class, null, true); - } - - return result.getCollections(); - } - - @Override - public GraphEntity createEdgeDefinition( - final String databaseName, - final String graphName, - final EdgeDefinitionEntity edgeDefinition) throws ArangoException { - - validateCollectionName(graphName); - validateCollectionName(edgeDefinition.getCollection()); - - final String edgeDefinitionJson = this.convertToString(edgeDefinition); - - final HttpResponseEntity res = httpManager.doPost( - createGharialEndpointUrl(databaseName, StringUtils.encodeUrl(graphName), EDGE), null, edgeDefinitionJson); - - if (wrongResult(res)) { - throw new ArangoException(UNKNOWN_ERROR); - } - - GraphEntity result; - if (isInBatchMode()) { - result = new GraphEntity(); - } else { - result = createEntity(res, GraphEntity.class, null, true); - } - - return result; - } - - @Override - public GraphEntity replaceEdgeDefinition( - final String databaseName, - final String graphName, - final String edgeName, - final EdgeDefinitionEntity edgeDefinition) throws ArangoException { - - validateCollectionName(graphName); - validateCollectionName(edgeDefinition.getCollection()); - - final String edgeDefinitionJson = this.convertToString(edgeDefinition); - - final HttpResponseEntity res = httpManager.doPut(createGharialEndpointUrl(databaseName, - StringUtils.encodeUrl(graphName), EDGE, StringUtils.encodeUrl(edgeName)), null, edgeDefinitionJson); - - if (wrongResult(res)) { - throw new ArangoException(UNKNOWN_ERROR); - } - - GraphEntity result; - if (isInBatchMode()) { - result = new GraphEntity(); - } else { - result = createEntity(res, GraphEntity.class, null, true); - } - - return result; - - } - - @Override - public GraphEntity deleteEdgeDefinition( - final String databaseName, - final String graphName, - final String edgeName, - final Boolean dropCollection) throws ArangoException { - validateCollectionName(graphName); - validateCollectionName(edgeName); - - final HttpResponseEntity res = httpManager.doDelete(createGharialEndpointUrl(databaseName, - StringUtils.encodeUrl(graphName), EDGE, StringUtils.encodeUrl(edgeName)), - new MapBuilder().put("dropCollection", dropCollection).get()); - - if (wrongResult(res)) { - throw new ArangoException(UNKNOWN_ERROR); - } - - GraphEntity result; - if (isInBatchMode()) { - result = new GraphEntity(); - } else { - result = createEntity(res, GraphEntity.class, null, true); - } - - return result; - } - - @Override - public VertexEntity createVertex( - final String database, - final String graphName, - final String collectionName, - final T vertex, - final Boolean waitForSync) throws ArangoException { - return createVertex(database, graphName, collectionName, null, vertex, waitForSync); - } - - @SuppressWarnings("unchecked") - @Override - public VertexEntity createVertex( - final String database, - final String graphName, - final String collectionName, - final String key, - final T vertex, - final Boolean waitForSync) throws ArangoException { - - JsonObject obj; - if (vertex == null) { - obj = new JsonObject(); - } else { - final JsonElement elem = EntityFactory.toJsonElement(vertex, false); - if (elem.isJsonObject()) { - obj = elem.getAsJsonObject(); - } else { - throw new IllegalArgumentException("vertex need object type(not support array, primitive, etc..)."); - } - } - if (key != null) { - obj.addProperty("_key", key); - } - - validateCollectionName(graphName); - final HttpResponseEntity res = httpManager.doPost( - createGharialEndpointUrl(database, StringUtils.encodeUrl(graphName), VERTEX, - StringUtils.encodeUrl(collectionName)), - new MapBuilder().put(WAIT_FOR_SYNC, waitForSync).get(), EntityFactory.toJsonString(obj)); - - if (wrongResult(res)) { - throw new ArangoException(UNKNOWN_ERROR); - } - - VertexEntity result; - if (isInBatchMode()) { - result = new VertexEntity(); - result.setEntity(vertex); - result.setRequestId(res.getRequestId()); - } else { - if (vertex != null) { - result = createEntity(res, VertexEntity.class, vertex.getClass()); - } else { - result = createEntity(res, VertexEntity.class); - } - result.setEntity(vertex); - annotationHandler.updateDocumentAttributes(result.getEntity(), result.getDocumentRevision(), - result.getDocumentHandle(), result.getDocumentKey()); - } - return result; - } - - private boolean wrongResult(final HttpResponseEntity res) { - if (res.isJsonResponse()) { - return false; - } - if (httpManager instanceof BatchHttpManager && ((BatchHttpManager) httpManager).isBatchModeActive()) { - // we are in batch mode - return false; - } - - return true; - } - - private boolean isInBatchMode() { - return httpManager instanceof BatchHttpManager && ((BatchHttpManager) httpManager).isBatchModeActive(); - } - - @SuppressWarnings("unchecked") - @Override - public VertexEntity getVertex( - final String databaseName, - final String graphName, - final String collectionName, - final String key, - final Class clazz, - final String ifMatchRevision, - final String ifNoneMatchRevision) throws ArangoException { - - validateCollectionName(graphName); - final HttpResponseEntity res = httpManager.doGet( - createGharialEndpointUrl(databaseName, StringUtils.encodeUrl(graphName), VERTEX, - StringUtils.encodeUrl(collectionName), StringUtils.encodeUrl(key)), - new MapBuilder().put(IF_MATCH, ifMatchRevision, true).put(IF_NONE_MATCH, ifNoneMatchRevision, true).get(), - new MapBuilder().get()); - - return createEntity(res, VertexEntity.class, clazz); - } - - @SuppressWarnings("unchecked") - @Override - public VertexEntity replaceVertex( - final String databaseName, - final String graphName, - final String collectionName, - final String key, - final T vertex, - final Boolean waitForSync, - final String ifMatchRevision, - final String ifNoneMatchRevision) throws ArangoException { - - validateCollectionName(graphName); - final HttpResponseEntity res = httpManager.doPut( - createGharialEndpointUrl(databaseName, StringUtils.encodeUrl(graphName), VERTEX, - StringUtils.encodeUrl(collectionName), StringUtils.encodeUrl(key)), - new MapBuilder().put(IF_MATCH, ifMatchRevision, true).put(IF_NONE_MATCH, ifNoneMatchRevision, true).get(), - new MapBuilder().put(WAIT_FOR_SYNC, waitForSync).get(), EntityFactory.toJsonString(vertex)); - - VertexEntity result; - if (vertex != null) { - result = createEntity(res, VertexEntity.class, vertex.getClass()); - result.setEntity(vertex); - annotationHandler.updateDocumentAttributes(result.getEntity(), result.getDocumentRevision(), - result.getDocumentHandle(), result.getDocumentKey()); - } else { - result = createEntity(res, VertexEntity.class); - } - return result; - } - - @SuppressWarnings("unchecked") - @Override - public VertexEntity updateVertex( - final String databaseName, - final String graphName, - final String collectionName, - final String key, - final T vertex, - final Boolean keepNull, - final Boolean waitForSync, - final String ifMatchRevision, - final String ifNoneMatchRevision) throws ArangoException { - - validateCollectionName(graphName); - final HttpResponseEntity res = httpManager.doPatch( - createGharialEndpointUrl(databaseName, StringUtils.encodeUrl(graphName), VERTEX, - StringUtils.encodeUrl(collectionName), StringUtils.encodeUrl(key)), - new MapBuilder().put(IF_MATCH, ifMatchRevision, true).put(IF_NONE_MATCH, ifNoneMatchRevision, true).get(), - new MapBuilder().put("keepNull", keepNull).put(WAIT_FOR_SYNC, waitForSync).get(), - EntityFactory.toJsonString(vertex, keepNull != null && !keepNull)); - - VertexEntity result; - if (vertex != null) { - result = createEntity(res, VertexEntity.class, vertex.getClass()); - result.setEntity(vertex); - annotationHandler.updateDocumentAttributes(result.getEntity(), result.getDocumentRevision(), - result.getDocumentHandle(), result.getDocumentKey()); - } else { - result = createEntity(res, VertexEntity.class); - } - return result; - } - - @Override - public DeletedEntity deleteVertex( - final String databaseName, - final String graphName, - final String collectionName, - final String key, - final Boolean waitForSync, - final String ifMatchRevision, - final String ifNoneMatchRevision) throws ArangoException { - - validateCollectionName(graphName); - final HttpResponseEntity res = httpManager.doDelete( - createGharialEndpointUrl(databaseName, StringUtils.encodeUrl(graphName), VERTEX, - StringUtils.encodeUrl(collectionName), StringUtils.encodeUrl(key)), - new MapBuilder().put(IF_MATCH, ifMatchRevision, true).put(IF_NONE_MATCH, ifNoneMatchRevision, true).get(), - new MapBuilder().put(WAIT_FOR_SYNC, waitForSync).get()); - - return createEntity(res, DeletedEntity.class); - } - - @SuppressWarnings("unchecked") - @Override - public EdgeEntity createEdge( - final String database, - final String graphName, - final String edgeCollectionName, - final String key, - final String fromHandle, - final String toHandle, - final T value, - final Boolean waitForSync) throws ArangoException { - - final JsonObject obj = EdgeUtils.valueToEdgeJsonObject(key, fromHandle, toHandle, value); - - validateCollectionName(graphName); - final HttpResponseEntity res = httpManager.doPost( - createGharialEndpointUrl(database, StringUtils.encodeUrl(graphName), EDGE, - StringUtils.encodeUrl(edgeCollectionName)), - new MapBuilder().put(WAIT_FOR_SYNC, waitForSync).get(), EntityFactory.toJsonString(obj)); - - final EdgeEntity entity = createEntity(res, EdgeEntity.class, value == null ? null : value.getClass()); - if (value != null) { - entity.setEntity(value); - annotationHandler.updateEdgeAttributes(value, entity.getDocumentRevision(), entity.getDocumentHandle(), - entity.getDocumentKey(), fromHandle, toHandle); - } - - entity.setFromVertexHandle(fromHandle); - entity.setToVertexHandle(toHandle); - return entity; - } - - @SuppressWarnings("unchecked") - @Override - public EdgeEntity getEdge( - final String database, - final String graphName, - final String edgeCollectionName, - final String key, - final Class clazz, - final String ifMatchRevision, - final String ifNoneMatchRevision) throws ArangoException { - - validateCollectionName(graphName); - final HttpResponseEntity res = httpManager.doGet( - createGharialEndpointUrl(database, StringUtils.encodeUrl(graphName), EDGE, - StringUtils.encodeUrl(edgeCollectionName), StringUtils.encodeUrl(key)), - new MapBuilder().put(IF_NONE_MATCH, ifNoneMatchRevision, true).put(IF_MATCH, ifMatchRevision, true).get(), - new MapBuilder().get()); - - return createEntity(res, EdgeEntity.class, clazz); - } - - @Override - public DeletedEntity deleteEdge( - final String database, - final String graphName, - final String edgeCollectionName, - final String key, - final Boolean waitForSync, - final String ifMatchRevision, - final String ifNoneMatchRevision) throws ArangoException { - - validateCollectionName(graphName); - final HttpResponseEntity res = httpManager.doDelete( - createEndpointUrl(database, "/_api/gharial", StringUtils.encodeUrl(graphName), EDGE, - StringUtils.encodeUrl(edgeCollectionName), StringUtils.encodeUrl(key)), - new MapBuilder().put(IF_NONE_MATCH, ifNoneMatchRevision, true).put(IF_MATCH, ifMatchRevision, true).get(), - new MapBuilder().put(WAIT_FOR_SYNC, waitForSync).get()); - - return createEntity(res, DeletedEntity.class); - - } - - @SuppressWarnings("unchecked") - @Override - public EdgeEntity replaceEdge( - final String database, - final String graphName, - final String edgeCollectionName, - final String key, - final String fromHandle, - final String toHandle, - final T value, - final Boolean waitForSync, - final String ifMatchRevision, - final String ifNoneMatchRevision) throws ArangoException { - - final JsonObject obj = EdgeUtils.valueToEdgeJsonObject(key, fromHandle, toHandle, value); - - validateCollectionName(graphName); - final HttpResponseEntity res = httpManager.doPut( - createGharialEndpointUrl(database, StringUtils.encodeUrl(graphName), EDGE, - StringUtils.encodeUrl(edgeCollectionName), StringUtils.encodeUrl(key)), - new MapBuilder().put(IF_NONE_MATCH, ifNoneMatchRevision, true).put(IF_MATCH, ifMatchRevision, true).get(), - new MapBuilder().put(WAIT_FOR_SYNC, waitForSync).get(), EntityFactory.toJsonString(obj)); - - final EdgeEntity entity = createEntity(res, EdgeEntity.class, value == null ? null : value.getClass()); - if (value != null) { - entity.setEntity(value); - annotationHandler.updateEdgeAttributes(entity.getEntity(), entity.getDocumentRevision(), - entity.getDocumentHandle(), entity.getDocumentKey(), fromHandle, toHandle); - } - if (fromHandle != null) { - entity.setFromVertexHandle(fromHandle); - } - if (toHandle != null) { - entity.setToVertexHandle(toHandle); - } - - return entity; - } - - @SuppressWarnings("unchecked") - @Override - public EdgeEntity updateEdge( - final String database, - final String graphName, - final String edgeCollectionName, - final String key, - final String fromHandle, - final String toHandle, - final T value, - final Boolean waitForSync, - final Boolean keepNull, - final String ifMatchRevision, - final String ifNoneMatchRevision) throws ArangoException { - - final JsonObject obj = EdgeUtils.valueToEdgeJsonObject(key, fromHandle, toHandle, value); - - validateCollectionName(graphName); - final HttpResponseEntity res = httpManager.doPatch( - createGharialEndpointUrl(database, StringUtils.encodeUrl(graphName), EDGE, - StringUtils.encodeUrl(edgeCollectionName), StringUtils.encodeUrl(key)), - new MapBuilder().put(IF_NONE_MATCH, ifNoneMatchRevision, true).put(IF_MATCH, ifMatchRevision, true).get(), - new MapBuilder().put(WAIT_FOR_SYNC, waitForSync).put("keepNull", keepNull).get(), - EntityFactory.toJsonString(obj)); - - final EdgeEntity entity = createEntity(res, EdgeEntity.class, value == null ? null : value.getClass()); - if (value != null) { - entity.setEntity(value); - annotationHandler.updateEdgeAttributes(entity.getEntity(), entity.getDocumentRevision(), - entity.getDocumentHandle(), entity.getDocumentKey(), fromHandle, toHandle); - } - - if (fromHandle != null) { - entity.setFromVertexHandle(fromHandle); - } - if (toHandle != null) { - entity.setToVertexHandle(toHandle); - } - - return entity; - } - - private String convertToString(final EdgeDefinitionEntity edgeDefinition) { - final JsonObject rawEdgeDefinition = (JsonObject) EntityFactory - .toJsonElement(new MapBuilder().put("edgeDefinition", edgeDefinition).get(), false); - final JsonElement edgeDefinitionJson = rawEdgeDefinition.get("edgeDefinition"); - return edgeDefinitionJson.toString(); - } - -} diff --git a/src/main/java/com/arangodb/impl/InternalImportDriverImpl.java b/src/main/java/com/arangodb/impl/InternalImportDriverImpl.java deleted file mode 100644 index 194beeb8c..000000000 --- a/src/main/java/com/arangodb/impl/InternalImportDriverImpl.java +++ /dev/null @@ -1,116 +0,0 @@ -/* - * Copyright (C) 2012,2013 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.impl; - -import java.util.Collection; -import java.util.Map; - -import com.arangodb.ArangoConfigure; -import com.arangodb.ArangoException; -import com.arangodb.entity.EntityFactory; -import com.arangodb.entity.ImportResultEntity; -import com.arangodb.http.HttpManager; -import com.arangodb.http.HttpResponseEntity; -import com.arangodb.util.ImportOptions; -import com.arangodb.util.ImportOptionsJson; -import com.arangodb.util.ImportOptionsRaw; - -/** - * @author tamtam180 - kirscheless at gmail.com - * @see - * HttpBulkImports documentation - */ -public class InternalImportDriverImpl extends BaseArangoDriverImpl implements com.arangodb.InternalImportDriver { - - InternalImportDriverImpl(ArangoConfigure configure, HttpManager httpManager) { - super(configure, httpManager); - } - - @Override - public ImportResultEntity importDocuments( - String database, - String collection, - Collection values, - ImportOptionsJson importOptionsJson) throws ArangoException { - - Map map = importOptionsJson.toMap(); - map.put("type", "list"); - - return importDocumentsInternal(database, collection, EntityFactory.toJsonString(values), map); - } - - @Override - public ImportResultEntity importDocumentsRaw( - String database, - String collection, - String values, - ImportOptionsRaw importOptionsRaw) throws ArangoException { - - return importDocumentsInternal(database, collection, values, importOptionsRaw.toMap()); - } - - @Override - public ImportResultEntity importDocumentsByHeaderValues( - String database, - String collection, - Collection> headerValues, - ImportOptions importOptions) throws ArangoException { - - return importDocumentsByHeaderValuesInternal(database, collection, - EntityFactory.toImportHeaderValues(headerValues), importOptions); - } - - @Override - public ImportResultEntity importDocumentsByHeaderValuesRaw( - String database, - String collection, - String headerValues, - ImportOptions importOptions) throws ArangoException { - - return importDocumentsByHeaderValuesInternal(database, collection, headerValues, importOptions); - } - - private ImportResultEntity importDocumentsInternal( - String database, - String collection, - String values, - Map importOptions) throws ArangoException { - - importOptions.put(COLLECTION, collection); - - HttpResponseEntity res = httpManager.doPost(createEndpointUrl(database, "/_api/import"), importOptions, values); - - return createEntity(res, ImportResultEntity.class); - } - - private ImportResultEntity importDocumentsByHeaderValuesInternal( - String database, - String collection, - String headerValues, - ImportOptions importOptions) throws ArangoException { - - Map map = importOptions.toMap(); - map.put(COLLECTION, collection); - - HttpResponseEntity res = httpManager.doPost(createEndpointUrl(database, "/_api/import"), map, headerValues); - - return createEntity(res, ImportResultEntity.class); - - } - -} diff --git a/src/main/java/com/arangodb/impl/InternalIndexDriverImpl.java b/src/main/java/com/arangodb/impl/InternalIndexDriverImpl.java deleted file mode 100644 index 1e4601dce..000000000 --- a/src/main/java/com/arangodb/impl/InternalIndexDriverImpl.java +++ /dev/null @@ -1,127 +0,0 @@ -/* - * Copyright (C) 2012 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.impl; - -import java.util.Locale; - -import com.arangodb.ArangoConfigure; -import com.arangodb.ArangoException; -import com.arangodb.entity.EntityFactory; -import com.arangodb.entity.IndexEntity; -import com.arangodb.entity.IndexType; -import com.arangodb.entity.IndexesEntity; -import com.arangodb.http.HttpManager; -import com.arangodb.http.HttpResponseEntity; -import com.arangodb.util.MapBuilder; - -/** - * @author tamtam180 - kirscheless at gmail.com - * - */ -public class InternalIndexDriverImpl extends BaseArangoDriverWithCursorImpl - implements com.arangodb.InternalIndexDriver { - - private static final String FIELDS = "fields"; - private static final String SPARSE = "sparse"; - private static final String UNIQUE = "unique"; - private static final String TYPE = "type"; - - InternalIndexDriverImpl(ArangoConfigure configure, HttpManager httpManager) { - super(configure, null, httpManager); - } - - @Override - public IndexEntity createIndex( - String database, - String collectionName, - IndexType type, - boolean unique, - boolean sparse, - String... fields) throws ArangoException { - - if (type == IndexType.PRIMARY) { - throw new IllegalArgumentException("cannot create primary index."); - } - if (type == IndexType.EDGE) { - throw new IllegalArgumentException("cannot create edge index."); - } - - validateCollectionName(collectionName); - HttpResponseEntity res = httpManager.doPost(createIndexEndpointUrl(database), - new MapBuilder(COLLECTION, collectionName).get(), - EntityFactory.toJsonString(new MapBuilder().put(TYPE, type.name().toLowerCase(Locale.US)) - .put(UNIQUE, unique).put(SPARSE, sparse).put(FIELDS, fields).get())); - - return createEntity(res, IndexEntity.class); - } - - @Override - public IndexEntity createIndex( - String database, - String collectionName, - IndexType type, - boolean unique, - String... fields) throws ArangoException { - return createIndex(database, collectionName, type, unique, false, fields); - } - - @Override - public IndexEntity createFulltextIndex(String database, String collectionName, Integer minLength, String... fields) - throws ArangoException { - - validateCollectionName(collectionName); - - HttpResponseEntity res = httpManager.doPost(createIndexEndpointUrl(database), - new MapBuilder(COLLECTION, collectionName).get(), - EntityFactory.toJsonString(new MapBuilder().put(TYPE, IndexType.FULLTEXT.name().toLowerCase(Locale.US)) - .put("minLength", minLength).put(FIELDS, fields).get())); - - return createEntity(res, IndexEntity.class); - } - - @Override - public IndexEntity deleteIndex(String database, String indexHandle) throws ArangoException { - - validateDocumentHandle(indexHandle); - - HttpResponseEntity res = httpManager.doDelete(createIndexEndpointUrl(database, indexHandle), null); - - return createEntity(res, IndexEntity.class); - } - - @Override - public IndexEntity getIndex(String database, String indexHandle) throws ArangoException { - - validateDocumentHandle(indexHandle); - - HttpResponseEntity res = httpManager.doGet(createIndexEndpointUrl(database, indexHandle)); - - return createEntity(res, IndexEntity.class); - } - - @Override - public IndexesEntity getIndexes(String database, String collectionName) throws ArangoException { - - validateCollectionName(collectionName); - - HttpResponseEntity res = httpManager.doGet(createIndexEndpointUrl(database), - new MapBuilder(COLLECTION, collectionName).get()); - - return createEntity(res, IndexesEntity.class); - } - -} diff --git a/src/main/java/com/arangodb/impl/InternalJobsDriverImpl.java b/src/main/java/com/arangodb/impl/InternalJobsDriverImpl.java deleted file mode 100644 index 81bf8de63..000000000 --- a/src/main/java/com/arangodb/impl/InternalJobsDriverImpl.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright (C) 2012,2013 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.impl; - -import java.util.List; - -import com.arangodb.ArangoConfigure; -import com.arangodb.ArangoException; -import com.arangodb.entity.JobsEntity; -import com.arangodb.http.HttpManager; -import com.arangodb.http.HttpResponseEntity; -import com.arangodb.http.InvocationObject; -import com.arangodb.util.MapBuilder; - -/** - * @author tamtam180 - kirscheless at gmail.com - */ -public class InternalJobsDriverImpl extends BaseArangoDriverImpl implements com.arangodb.InternalJobsDriver { - - InternalJobsDriverImpl(ArangoConfigure configure, HttpManager httpManager) { - super(configure, httpManager); - } - - @Override - public List getJobs(String database, JobsEntity.JobState jobState, int count) throws ArangoException { - HttpResponseEntity res = httpManager.doGet(createJobEndpointUrl(database, jobState.getName()), - new MapBuilder().put("count", count).get()); - return createEntity(res, JobsEntity.class).getJobs(); - } - - @Override - public List getJobs(String database, JobsEntity.JobState jobState) throws ArangoException { - HttpResponseEntity res = httpManager.doGet(createJobEndpointUrl(database, jobState.getName())); - return createEntity(res, JobsEntity.class).getJobs(); - } - - @Override - public void deleteAllJobs(String database) throws ArangoException { - httpManager.doDelete(createJobEndpointUrl(database, "all"), null); - } - - @Override - public void deleteJobById(String database, String jobId) throws ArangoException { - httpManager.doDelete(createJobEndpointUrl(database, jobId), null); - } - - @Override - public void deleteExpiredJobs(String database, int timeStamp) throws ArangoException { - httpManager.doDelete(createJobEndpointUrl(database, "expired"), new MapBuilder().put("stamp", timeStamp).get()); - } - - @SuppressWarnings("unchecked") - @Override - public T getJobResult(String database, String jobId) throws ArangoException { - InvocationObject io = this.getHttpManager().getJobs().get(jobId); - if (io == null) { - throw new ArangoException("No result for JobId."); - } - this.getHttpManager().getJobs().remove(jobId); - this.getHttpManager() - .setPreDefinedResponse(httpManager.doPut(createJobEndpointUrl(database, jobId), null, null)); - T result; - try { - result = (T) io.getMethod().invoke(io.getArangoDriver(), io.getArgs()); - } catch (Exception e) { - this.getHttpManager().setPreDefinedResponse(null); - throw new ArangoException(e); - } - this.getHttpManager().setPreDefinedResponse(null); - return result; - } -} diff --git a/src/main/java/com/arangodb/impl/InternalQueryCacheDriverImpl.java b/src/main/java/com/arangodb/impl/InternalQueryCacheDriverImpl.java deleted file mode 100644 index 3e3a1b68e..000000000 --- a/src/main/java/com/arangodb/impl/InternalQueryCacheDriverImpl.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright (C) 2012,2013 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.impl; - -import com.arangodb.ArangoConfigure; -import com.arangodb.ArangoException; -import com.arangodb.entity.DefaultEntity; -import com.arangodb.entity.EntityFactory; -import com.arangodb.entity.QueryCachePropertiesEntity; -import com.arangodb.http.HttpManager; -import com.arangodb.http.HttpResponseEntity; - -/** - * @author a-brandt - * - */ -public class InternalQueryCacheDriverImpl extends BaseArangoDriverImpl - implements com.arangodb.InternalQueryCacheDriver { - - InternalQueryCacheDriverImpl(ArangoConfigure configure, HttpManager httpManager) { - super(configure, httpManager); - } - - @Override - public DefaultEntity deleteQueryCache() throws ArangoException { - - HttpResponseEntity res = httpManager.doDelete(createEndpointUrl(null, "/_api/query-cache"), null); - - return createEntity(res, DefaultEntity.class); - } - - @Override - public QueryCachePropertiesEntity getQueryCacheProperties() throws ArangoException { - - HttpResponseEntity res = httpManager.doGet(createEndpointUrl(null, "/_api/query-cache"), null); - - return createEntity(res, QueryCachePropertiesEntity.class); - - } - - @Override - public QueryCachePropertiesEntity setQueryCacheProperties(QueryCachePropertiesEntity properties) - throws ArangoException { - - HttpResponseEntity res = httpManager.doPut(createEndpointUrl(null, "/_api/query-cache/properties"), null, - EntityFactory.toJsonString(properties)); - - return createEntity(res, QueryCachePropertiesEntity.class); - } - -} diff --git a/src/main/java/com/arangodb/impl/InternalReplicationDriverImpl.java b/src/main/java/com/arangodb/impl/InternalReplicationDriverImpl.java deleted file mode 100644 index 344620046..000000000 --- a/src/main/java/com/arangodb/impl/InternalReplicationDriverImpl.java +++ /dev/null @@ -1,284 +0,0 @@ -/* - * Copyright (C) 2012,2013 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.impl; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.UnsupportedEncodingException; -import java.util.Locale; - -import com.arangodb.ArangoConfigure; -import com.arangodb.ArangoException; -import com.arangodb.entity.EntityFactory; -import com.arangodb.entity.MapAsEntity; -import com.arangodb.entity.ReplicationApplierConfigEntity; -import com.arangodb.entity.ReplicationApplierStateEntity; -import com.arangodb.entity.ReplicationDumpHeader; -import com.arangodb.entity.ReplicationDumpRecord; -import com.arangodb.entity.ReplicationInventoryEntity; -import com.arangodb.entity.ReplicationLoggerConfigEntity; -import com.arangodb.entity.ReplicationLoggerStateEntity; -import com.arangodb.entity.ReplicationSyncEntity; -import com.arangodb.entity.RestrictType; -import com.arangodb.entity.StreamEntity; -import com.arangodb.http.HttpManager; -import com.arangodb.http.HttpResponseEntity; -import com.arangodb.util.DumpHandler; -import com.arangodb.util.IOUtils; -import com.arangodb.util.MapBuilder; - -/** - * @author tamtam180 - kirscheless at gmail.com - * - */ -public class InternalReplicationDriverImpl extends BaseArangoDriverImpl - implements com.arangodb.InternalReplicationDriver { - - InternalReplicationDriverImpl(ArangoConfigure configure, HttpManager httpManager) { - super(configure, httpManager); - } - - @Override - public ReplicationInventoryEntity getReplicationInventory(String database, Boolean includeSystem) - throws ArangoException { - - HttpResponseEntity res = httpManager.doGet(createEndpointUrl(database, "/_api/replication/inventory"), - new MapBuilder().put("includeSystem", includeSystem).get()); - - return createEntity(res, ReplicationInventoryEntity.class); - - } - - @SuppressWarnings("unchecked") - @Override - public void getReplicationDump( - String database, - String collectionName, - Long from, - Long to, - Integer chunkSize, - Boolean ticks, - Class clazz, - DumpHandler handler) throws ArangoException { - - HttpResponseEntity res = httpManager.doGet(createEndpointUrl(database, "/_api/replication/dump"), - new MapBuilder().put(COLLECTION, collectionName).put("from", from).put("to", to).put("chunkSize", chunkSize) - .put("ticks", ticks).get()); - - ReplicationDumpHeader header = toReplicationDumpHeader(res); - boolean cont = handler.head(header); - - StreamEntity entity = createEntity(res, StreamEntity.class); - BufferedReader reader = null; - try { - reader = new BufferedReader(new InputStreamReader(entity.getStream(), "utf-8")); - String line = null; - while (cont && (line = reader.readLine()) != null) { - if (line.length() == 0) { - continue; - } - cont = handler.handle(createEntity(line, ReplicationDumpRecord.class, clazz)); - } - } catch (UnsupportedEncodingException e) { - throw new ArangoException("got UnsupportedEncodingException for utf-8", e); - } catch (IOException e) { - throw new ArangoException(e); - } finally { - IOUtils.close(reader); - } - - } - - @Override - public ReplicationSyncEntity syncReplication( - String localDatabase, - String endpoint, - String database, - String username, - String password, - RestrictType restrictType, - String... restrictCollections) throws ArangoException { - - HttpResponseEntity res = httpManager.doPut(createEndpointUrl(localDatabase, "/_api/replication/sync"), null, - EntityFactory.toJsonString(new MapBuilder().put("endpoint", endpoint).put("database", database) - .put("username", username).put("password", password) - .put("restrictType", restrictType == null ? null : restrictType.name().toLowerCase(Locale.US)) - .put("restrictCollections", - restrictCollections == null || restrictCollections.length == 0 ? null : restrictCollections) - .get())); - - return createEntity(res, ReplicationSyncEntity.class); - - } - - @Override - public String getReplicationServerId() throws ArangoException { - - HttpResponseEntity res = httpManager.doGet(createEndpointUrl(null, "/_api/replication/server-id")); // MEMO: - // not - // use - // database, - // because - // same - // value - // each - // database. - - MapAsEntity entity = createEntity(res, MapAsEntity.class); - return (String) entity.getMap().get("serverId"); - - } - - @Override - public boolean startReplicationLogger(String database) throws ArangoException { - - HttpResponseEntity res = httpManager.doPut(createEndpointUrl(database, "/_api/replication/logger-start"), null, - null); - - MapAsEntity entity = createEntity(res, MapAsEntity.class); - return (Boolean) entity.getMap().get("running"); - - } - - @Override - public boolean stopReplicationLogger(String database) throws ArangoException { - - HttpResponseEntity res = httpManager.doPut(createEndpointUrl(database, "/_api/replication/logger-stop"), null, - null); - - MapAsEntity entity = createEntity(res, MapAsEntity.class); - return (Boolean) entity.getMap().get("running"); - - } - - @Override - public ReplicationLoggerConfigEntity getReplicationLoggerConfig(String database) throws ArangoException { - - HttpResponseEntity res = httpManager.doGet(createEndpointUrl(database, "/_api/replication/logger-config")); - - return createEntity(res, ReplicationLoggerConfigEntity.class); - - } - - @Override - public ReplicationLoggerConfigEntity setReplicationLoggerConfig( - String database, - Boolean autoStart, - Boolean logRemoteChanges, - Long maxEvents, - Long maxEventsSize) throws ArangoException { - - HttpResponseEntity res = httpManager.doPut(createEndpointUrl(database, "/_api/replication/logger-config"), null, - EntityFactory - .toJsonString(new MapBuilder().put("autoStart", autoStart).put("logRemoteChanges", logRemoteChanges) - .put("maxEvents", maxEvents).put("maxEventsSize", maxEventsSize).get())); - - return createEntity(res, ReplicationLoggerConfigEntity.class); - - } - - @Override - public ReplicationLoggerStateEntity getReplicationLoggerState(String database) throws ArangoException { - - HttpResponseEntity res = httpManager.doGet(createEndpointUrl(database, "/_api/replication/logger-state")); - - return createEntity(res, ReplicationLoggerStateEntity.class); - - } - - @Override - public ReplicationApplierConfigEntity getReplicationApplierConfig(String database) throws ArangoException { - - HttpResponseEntity res = httpManager.doGet(createEndpointUrl(database, "/_api/replication/applier-config")); - - return createEntity(res, ReplicationApplierConfigEntity.class); - - } - - @Override - public ReplicationApplierConfigEntity setReplicationApplierConfig( - String localDatabase, - String endpoint, - String database, - String username, - String password, - Integer maxConnectRetries, - Integer connectTimeout, - Integer requestTimeout, - Integer chunkSize, - Boolean autoStart, - Boolean adaptivePolling) throws ArangoException { - - ReplicationApplierConfigEntity bodyParam = new ReplicationApplierConfigEntity(); - bodyParam.setEndpoint(endpoint); - bodyParam.setDatabase(database); - bodyParam.setUsername(username); - bodyParam.setPassword(password); - bodyParam.setMaxConnectRetries(maxConnectRetries); - bodyParam.setConnectTimeout(connectTimeout); - bodyParam.setRequestTimeout(requestTimeout); - bodyParam.setChunkSize(chunkSize); - bodyParam.setAutoStart(autoStart); - bodyParam.setAdaptivePolling(adaptivePolling); - - return setReplicationApplierConfig(localDatabase, bodyParam); - - } - - @Override - public ReplicationApplierConfigEntity setReplicationApplierConfig( - String database, - ReplicationApplierConfigEntity param) throws ArangoException { - - HttpResponseEntity res = httpManager.doPut(createEndpointUrl(database, "/_api/replication/applier-config"), - null, EntityFactory.toJsonString(param)); - - return createEntity(res, ReplicationApplierConfigEntity.class); - - } - - @Override - public ReplicationApplierStateEntity startReplicationApplier(String database, Long from) throws ArangoException { - - HttpResponseEntity res = httpManager.doPut(createEndpointUrl(database, "/_api/replication/applier-start"), - new MapBuilder().put("from", from).get(), null); - - return createEntity(res, ReplicationApplierStateEntity.class); - - } - - @Override - public ReplicationApplierStateEntity stopReplicationApplier(String database) throws ArangoException { - - HttpResponseEntity res = httpManager.doPut(createEndpointUrl(database, "/_api/replication/applier-stop"), null, - null); - - return createEntity(res, ReplicationApplierStateEntity.class); - - } - - @Override - public ReplicationApplierStateEntity getReplicationApplierState(String database) throws ArangoException { - - HttpResponseEntity res = httpManager.doGet(createEndpointUrl(database, "/_api/replication/applier-state")); - - return createEntity(res, ReplicationApplierStateEntity.class); - - } - -} diff --git a/src/main/java/com/arangodb/impl/InternalSimpleDriverImpl.java b/src/main/java/com/arangodb/impl/InternalSimpleDriverImpl.java deleted file mode 100644 index a55c23ad0..000000000 --- a/src/main/java/com/arangodb/impl/InternalSimpleDriverImpl.java +++ /dev/null @@ -1,287 +0,0 @@ -/* - * Copyright (C) 2012 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.impl; - -import java.util.Map; - -import com.arangodb.ArangoConfigure; -import com.arangodb.ArangoException; -import com.arangodb.DocumentCursor; -import com.arangodb.DocumentCursorResult; -import com.arangodb.InternalCursorDriver; -import com.arangodb.entity.CursorEntity; -import com.arangodb.entity.DocumentEntity; -import com.arangodb.entity.EntityFactory; -import com.arangodb.entity.ScalarExampleEntity; -import com.arangodb.entity.SimpleByResultEntity; -import com.arangodb.http.HttpManager; -import com.arangodb.http.HttpResponseEntity; -import com.arangodb.util.MapBuilder; - -/** - * @author tamtam180 - kirscheless at gmail.com - * - */ -public class InternalSimpleDriverImpl extends BaseArangoDriverWithCursorImpl - implements com.arangodb.InternalSimpleDriver { - - private static final String WAIT_FOR_SYNC = "waitForSync"; - private static final String LIMIT = "limit"; - private static final String EXAMPLE = "example"; - - InternalSimpleDriverImpl(final ArangoConfigure configure, final InternalCursorDriver cursorDriver, - final HttpManager httpManager) { - super(configure, cursorDriver, httpManager); - } - - // ----- all -------------------- - - @Override - public DocumentCursor executeSimpleAllDocuments( - final String database, - final String collectionName, - final int skip, - final int limit, - final Class clazz) throws ArangoException { - - final HttpResponseEntity res = getSimpleAll(database, collectionName, skip, limit); - return responseToDocumentCursor(database, clazz, res); - } - - // ----- example -------------------- - - @Override - public DocumentCursor executeSimpleByExampleDocuments( - final String database, - final String collectionName, - final Map example, - final int skip, - final int limit, - final Class clazz) throws ArangoException { - - final HttpResponseEntity res = getSimpleByExample(database, collectionName, example, skip, limit); - return responseToDocumentCursor(database, clazz, res); - } - - // ----- first -------------------- - - @SuppressWarnings("unchecked") - @Override - public ScalarExampleEntity executeSimpleFirstExample( - final String database, - final String collectionName, - final Map example, - final Class clazz) throws ArangoException { - - validateCollectionName(collectionName); - final HttpResponseEntity res = httpManager.doPut(createEndpointUrl(database, "/_api/simple/first-example"), - null, - EntityFactory.toJsonString(new MapBuilder().put(COLLECTION, collectionName).put(EXAMPLE, example).get())); - - return createEntity(res, ScalarExampleEntity.class, clazz); - } - - // ----- any -------------------- - - @SuppressWarnings("unchecked") - @Override - public ScalarExampleEntity executeSimpleAny( - final String database, - final String collectionName, - final Class clazz) throws ArangoException { - - validateCollectionName(collectionName); - final HttpResponseEntity res = httpManager.doPut(createEndpointUrl(database, "/_api/simple/any"), null, - EntityFactory.toJsonString(new MapBuilder().put(COLLECTION, collectionName).get())); - - return createEntity(res, ScalarExampleEntity.class, clazz); - } - - // ----- range -------------------- - - @Override - public DocumentCursor executeSimpleRangeWithDocuments( - final String database, - final String collectionName, - final String attribute, - final Object left, - final Object right, - final Boolean closed, - final int skip, - final int limit, - final Class clazz) throws ArangoException { - - final HttpResponseEntity res = getSimpleRange(database, collectionName, attribute, left, right, closed, skip, - limit); - return responseToDocumentCursor(database, clazz, res); - } - - // ----- remove-by-example -------------------- - - @Override - public SimpleByResultEntity executeSimpleRemoveByExample( - final String database, - final String collectionName, - final Map example, - final Boolean waitForSync, - final Integer limit) throws ArangoException { - - validateCollectionName(collectionName); - final HttpResponseEntity res = httpManager - .doPut(createEndpointUrl(database, "/_api/simple/remove-by-example"), null, - EntityFactory.toJsonString(new MapBuilder().put(COLLECTION, collectionName).put(EXAMPLE, example) - .put(WAIT_FOR_SYNC, waitForSync) - .put(LIMIT, limit != null && limit.intValue() > 0 ? limit : null).get())); - - return createEntity(res, SimpleByResultEntity.class); - } - - // ----- replace-by-example -------------------- - - @Override - public SimpleByResultEntity executeSimpleReplaceByExample( - final String database, - final String collectionName, - final Map example, - final Map newValue, - final Boolean waitForSync, - final Integer limit) throws ArangoException { - - validateCollectionName(collectionName); - final HttpResponseEntity res = httpManager.doPut(createEndpointUrl(database, "/_api/simple/replace-by-example"), - null, - EntityFactory.toJsonString(new MapBuilder().put(COLLECTION, collectionName).put(EXAMPLE, example) - .put("newValue", newValue).put(WAIT_FOR_SYNC, waitForSync) - .put(LIMIT, limit != null && limit.intValue() > 0 ? limit : null).get())); - - return createEntity(res, SimpleByResultEntity.class); - } - - // ----- update-by-example -------------------- - - @Override - public SimpleByResultEntity executeSimpleUpdateByExample( - final String database, - final String collectionName, - final Map example, - final Map newValue, - final Boolean keepNull, - final Boolean waitForSync, - final Integer limit) throws ArangoException { - - validateCollectionName(collectionName); - final HttpResponseEntity res = httpManager.doPut(createEndpointUrl(database, "/_api/simple/update-by-example"), - null, - EntityFactory.toJsonString( - new MapBuilder().put(COLLECTION, collectionName).put(EXAMPLE, example).put("newValue", newValue) - .put("keepNull", keepNull).put(WAIT_FOR_SYNC, waitForSync) - .put(LIMIT, limit != null && limit.intValue() > 0 ? limit : null).get(), - keepNull != null && !keepNull)); - - return createEntity(res, SimpleByResultEntity.class); - } - - // ----- Fulltext -------------------- - - @Override - public DocumentCursor executeSimpleFulltextWithDocuments( - final String database, - final String collectionName, - final String attribute, - final String query, - final int skip, - final int limit, - final String index, - final Class clazz) throws ArangoException { - - final HttpResponseEntity res = getSimpleFulltext(database, collectionName, attribute, query, skip, limit, - index); - return responseToDocumentCursor(database, clazz, res); - } - - // ----- private functions - - private HttpResponseEntity getSimpleAll( - final String database, - final String collectionName, - final int skip, - final int limit) throws ArangoException { - validateCollectionName(collectionName); - return httpManager.doPut(createEndpointUrl(database, "/_api/simple/all"), null, - EntityFactory.toJsonString(new MapBuilder().put(COLLECTION, collectionName) - .put("skip", skip > 0 ? skip : null).put(LIMIT, limit > 0 ? limit : null).get())); - } - - private HttpResponseEntity getSimpleByExample( - final String database, - final String collectionName, - final Map example, - final int skip, - final int limit) throws ArangoException { - validateCollectionName(collectionName); - return httpManager.doPut(createEndpointUrl(database, "/_api/simple/by-example"), null, - EntityFactory.toJsonString(new MapBuilder().put(COLLECTION, collectionName).put(EXAMPLE, example) - .put("skip", skip > 0 ? skip : null).put(LIMIT, limit > 0 ? limit : null).get())); - } - - private HttpResponseEntity getSimpleRange( - final String database, - final String collectionName, - final String attribute, - final Object left, - final Object right, - final Boolean closed, - final int skip, - final int limit) throws ArangoException { - validateCollectionName(collectionName); - return httpManager.doPut(createEndpointUrl(database, "/_api/simple/range"), null, - EntityFactory.toJsonString(new MapBuilder().put(COLLECTION, collectionName).put("attribute", attribute) - .put("left", left).put("right", right).put("closed", closed).put("skip", skip > 0 ? skip : null) - .put(LIMIT, limit > 0 ? limit : null).get())); - } - - private HttpResponseEntity getSimpleFulltext( - final String database, - final String collectionName, - final String attribute, - final String query, - final int skip, - final int limit, - final String index) throws ArangoException { - validateCollectionName(collectionName); - return httpManager.doPut(createEndpointUrl(database, "/_api/simple/fulltext"), null, - EntityFactory.toJsonString(new MapBuilder().put(COLLECTION, collectionName).put("attribute", attribute) - .put("query", query).put("skip", skip > 0 ? skip : null).put(LIMIT, limit > 0 ? limit : null) - .put("index", index).get())); - } - - @SuppressWarnings("unchecked") - private DocumentCursor responseToDocumentCursor( - final String database, - final Class clazz, - final HttpResponseEntity res) throws ArangoException { - - final CursorEntity> baseCursorEntity = createEntity(res, CursorEntity.class, - DocumentEntity.class, clazz); - - final DocumentCursorResult> baseCursor = new DocumentCursorResult>( - database, cursorDriver, baseCursorEntity, DocumentEntity.class, clazz); - - return new DocumentCursor(baseCursor); - } - -} diff --git a/src/main/java/com/arangodb/impl/InternalTransactionDriverImpl.java b/src/main/java/com/arangodb/impl/InternalTransactionDriverImpl.java deleted file mode 100644 index 99438c80b..000000000 --- a/src/main/java/com/arangodb/impl/InternalTransactionDriverImpl.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.arangodb.impl; - -import com.arangodb.ArangoConfigure; -import com.arangodb.ArangoException; -import com.arangodb.InternalTransactionDriver; -import com.arangodb.entity.EntityFactory; -import com.arangodb.entity.TransactionEntity; -import com.arangodb.entity.TransactionResultEntity; -import com.arangodb.http.HttpManager; -import com.arangodb.http.HttpResponseEntity; -import com.arangodb.util.MapBuilder; - -/** - * Created by fbartels on 10/30/14. - */ -public class InternalTransactionDriverImpl extends BaseArangoDriverImpl implements InternalTransactionDriver { - - InternalTransactionDriverImpl(ArangoConfigure configure, HttpManager httpManager) { - super(configure, httpManager); - } - - @Override - public TransactionEntity createTransaction(String action) { - return new TransactionEntity(action); - } - - @Override - public TransactionResultEntity executeTransaction(String database, TransactionEntity transactionEntity) - throws ArangoException { - HttpResponseEntity res = httpManager.doPost( - createEndpointUrl(database, "/_api/transaction"), - null, - EntityFactory.toJsonString(new MapBuilder().put("collections", transactionEntity.getCollections()) - .put("action", transactionEntity.getAction()) - .put("lockTimeout", transactionEntity.getLockTimeout()) - .put("params", transactionEntity.getParams()).get())); - return createEntity(res, TransactionResultEntity.class); - } -} diff --git a/src/main/java/com/arangodb/impl/InternalTraversalDriverImpl.java b/src/main/java/com/arangodb/impl/InternalTraversalDriverImpl.java deleted file mode 100644 index ae32400dc..000000000 --- a/src/main/java/com/arangodb/impl/InternalTraversalDriverImpl.java +++ /dev/null @@ -1,59 +0,0 @@ -/** - * Copyright 2004-2015 triAGENS GmbH, Cologne, Germany - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Copyright holder is triAGENS GmbH, Cologne, Germany - * - * @author a-brandt - * @author Copyright 2015, triAGENS GmbH, Cologne, Germany - */ - -package com.arangodb.impl; - -import com.arangodb.ArangoConfigure; -import com.arangodb.ArangoException; -import com.arangodb.entity.EntityFactory; -import com.arangodb.entity.TraversalEntity; -import com.arangodb.http.HttpManager; -import com.arangodb.http.HttpResponseEntity; -import com.arangodb.util.TraversalQueryOptions; - -/** - * @author a-brandt - */ -public class InternalTraversalDriverImpl extends BaseArangoDriverImpl implements com.arangodb.InternalTraversalDriver { - - InternalTraversalDriverImpl(ArangoConfigure configure, HttpManager httpManager) { - super(configure, httpManager); - } - - @SuppressWarnings("unchecked") - @Override - public TraversalEntity getTraversal( - String databaseName, - TraversalQueryOptions traversalQueryOptions, - Class vertexClazz, - Class edgeClazz) throws ArangoException { - - TraversalQueryOptions options = (traversalQueryOptions != null) ? traversalQueryOptions - : new TraversalQueryOptions(); - - String body = EntityFactory.toJsonString(options.toMap()); - - HttpResponseEntity response = httpManager.doPost(createEndpointUrl(databaseName, "/_api/traversal"), null, - body); - - return createEntity(response, TraversalEntity.class, vertexClazz, edgeClazz); - } - -} diff --git a/src/main/java/com/arangodb/impl/InternalUsersDriverImpl.java b/src/main/java/com/arangodb/impl/InternalUsersDriverImpl.java deleted file mode 100644 index c39827cb1..000000000 --- a/src/main/java/com/arangodb/impl/InternalUsersDriverImpl.java +++ /dev/null @@ -1,114 +0,0 @@ -/* - * Copyright (C) 2012,2013 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.impl; - -import java.util.Map; - -import com.arangodb.ArangoConfigure; -import com.arangodb.ArangoException; -import com.arangodb.entity.DefaultEntity; -import com.arangodb.entity.EntityFactory; -import com.arangodb.entity.UserEntity; -import com.arangodb.entity.UsersEntity; -import com.arangodb.http.HttpManager; -import com.arangodb.http.HttpResponseEntity; -import com.arangodb.util.MapBuilder; -import com.arangodb.util.StringUtils; - -/** - * @author tamtam180 - kirscheless at gmail.com - * - */ -public class InternalUsersDriverImpl extends BaseArangoDriverImpl implements com.arangodb.InternalUsersDriver { - - private static final String EXTRA = "extra"; - private static final String ACTIVE = "active"; - private static final String PW = "passwd"; - private static final String USERNAME = "user"; - private static final String GRANT = "grant"; - private static final String DATABASE = "database"; - private static final String READ_WRITE = "rw"; - - InternalUsersDriverImpl(ArangoConfigure configure, HttpManager httpManager) { - super(configure, httpManager); - } - - @Override - public DefaultEntity createUser(String username, String passwd, Boolean active, Map extra) - throws ArangoException { - - HttpResponseEntity res = httpManager.doPost(createUserEndpointUrl(), null, EntityFactory.toJsonString( - new MapBuilder().put(USERNAME, username).put(PW, passwd).put(ACTIVE, active).put(EXTRA, extra).get())); - - return createEntity(res, DefaultEntity.class); - } - - @Override - public DefaultEntity deleteUser(String username) throws ArangoException { - - HttpResponseEntity res = httpManager.doDelete(createUserEndpointUrl(StringUtils.encodeUrl(username)), null); - - return createEntity(res, DefaultEntity.class); - } - - @Override - public UserEntity getUser(String username) throws ArangoException { - - HttpResponseEntity res = httpManager.doGet(createUserEndpointUrl(StringUtils.encodeUrl(username)), null); - - return createEntity(res, UserEntity.class); - } - - @Override - public UsersEntity getUsers() throws ArangoException { - - HttpResponseEntity res = httpManager.doGet(createUserEndpointUrl(), null); - - return createEntity(res, UsersEntity.class); - } - - @Override - public DefaultEntity replaceUser(String username, String passwd, Boolean active, Map extra) - throws ArangoException { - - HttpResponseEntity res = httpManager.doPut(createUserEndpointUrl(StringUtils.encodeUrl(username)), null, - EntityFactory.toJsonString(new MapBuilder().put(PW, passwd).put(ACTIVE, active).put(EXTRA, extra).get())); - - return createEntity(res, DefaultEntity.class); - } - - @Override - public DefaultEntity updateUser(String username, String passwd, Boolean active, Map extra) - throws ArangoException { - - HttpResponseEntity res = httpManager.doPatch(createUserEndpointUrl(StringUtils.encodeUrl(username)), null, - EntityFactory.toJsonString(new MapBuilder().put(PW, passwd).put(ACTIVE, active).put(EXTRA, extra).get())); - - return createEntity(res, DefaultEntity.class); - } - - @Override - public DefaultEntity grantDatabaseAccess(String username, String database) throws ArangoException { - - final HttpResponseEntity res = httpManager.doPut( - createUserEndpointUrl(StringUtils.encodeUrl(username), DATABASE, StringUtils.encodeUrl(database)), null, - EntityFactory.toJsonString(new MapBuilder().put(GRANT, READ_WRITE).get())); - - return createEntity(res, DefaultEntity.class); - } - -} diff --git a/src/main/java/com/arangodb/internal/ArangoCursorExecute.java b/src/main/java/com/arangodb/internal/ArangoCursorExecute.java new file mode 100644 index 000000000..1f9d94a49 --- /dev/null +++ b/src/main/java/com/arangodb/internal/ArangoCursorExecute.java @@ -0,0 +1,36 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.internal; + +import com.arangodb.ArangoDBException; +import com.arangodb.entity.CursorEntity; + +/** + * @author Mark - mark at arangodb.com + * + */ +public interface ArangoCursorExecute { + + CursorEntity next(String id) throws ArangoDBException; + + void close(String id) throws ArangoDBException; + +} diff --git a/src/main/java/com/arangodb/internal/ArangoCursorIterator.java b/src/main/java/com/arangodb/internal/ArangoCursorIterator.java new file mode 100644 index 000000000..56de439f3 --- /dev/null +++ b/src/main/java/com/arangodb/internal/ArangoCursorIterator.java @@ -0,0 +1,75 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.internal; + +import java.util.Iterator; +import java.util.NoSuchElementException; + +import com.arangodb.ArangoCursor; +import com.arangodb.entity.CursorEntity; + +/** + * @author Mark - mark at arangodb.com + * @param + * + */ +public class ArangoCursorIterator implements Iterator { + + private CursorEntity result; + private int pos; + + private final ArangoCursor cursor; + private final InternalArangoDatabase db; + private final ArangoCursorExecute execute; + + public 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; + } + + @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()); + pos = 0; + } + if (!hasNext()) { + throw new NoSuchElementException(); + } + return db.executor.deserialize(result.getResult().get(pos++), cursor.getType()); + } + + @Override + public void remove() { + throw new UnsupportedOperationException(); + } + +} diff --git a/src/main/java/com/arangodb/internal/ArangoDBConstants.java b/src/main/java/com/arangodb/internal/ArangoDBConstants.java new file mode 100644 index 000000000..f357d1c1c --- /dev/null +++ b/src/main/java/com/arangodb/internal/ArangoDBConstants.java @@ -0,0 +1,103 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.internal; + +/** + * @author Mark - mark at arangodb.com + * + */ +public class ArangoDBConstants { + + 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 Boolean DEFAULT_USE_SSL = false; + + public static final int INTEGER_BYTES = Integer.SIZE / Byte.SIZE; + public static final int LONG_BYTES = Long.SIZE / Byte.SIZE; + 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 String PATH_API_DOCUMENT = "/_api/document"; + public static final String PATH_API_COLLECTION = "/_api/collection"; + public static final String PATH_API_DATABASE = "/_api/database"; + public static final String PATH_API_VERSION = "/_api/version"; + public static final String PATH_API_INDEX = "/_api/index"; + public static final String PATH_API_USER = "/_api/user"; + public static final String PATH_API_CURSOR = "/_api/cursor"; + public static final String PATH_API_GHARIAL = "/_api/gharial"; + public static final String PATH_API_TRANSACTION = "/_api/transaction"; + public static final String PATH_API_AQLFUNCTION = "/_api/aqlfunction"; + public static final String PATH_API_EXPLAIN = "/_api/explain"; + public static final String PATH_API_QUERY = "/_api/query"; + public static final String PATH_API_QUERY_CACHE = "/_api/query-cache"; + public static final String PATH_API_QUERY_CACHE_PROPERTIES = "/_api/query-cache/properties"; + public static final String PATH_API_QUERY_PROPERTIES = "/_api/query/properties"; + public static final String PATH_API_QUERY_CURRENT = "/_api/query/current"; + public static final String PATH_API_QUERY_SLOW = "/_api/query/slow"; + public static final String PATH_API_TRAVERSAL = "/_api/traversal"; + public static final String PATH_API_ADMIN_LOG = "/_admin/log"; + public static final String PATH_API_ADMIN_ROUTING_RELOAD = "/_admin/routing/reload"; + + public static final String ENCRYPTION_PLAIN = "plain"; + + public static final String SYSTEM = "_system"; + public static final String ID = "id"; + public static final String RESULT = "result"; + public static final String VISITED = "visited"; + public static final String VERTICES = "vertices"; + public static final String EDGES = "edges"; + 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 MERGE_OBJECTS = "mergeObjects"; + public static final String IGNORE_REVS = "ignoreRevs"; + public static final String RETURN_NEW = "returnNew"; + public static final String NEW = "new"; + public static final String RETURN_OLD = "returnOld"; + public static final String OLD = "old"; + public static final String COLLECTION = "collection"; + public static final String COLLECTIONS = "collections"; + public static final String EXCLUDE_SYSTEM = "excludeSystem"; + public static final String USER = "user"; + public static final String RW = "rw"; + public static final String NONE = "none"; + public static final String DATABASE = "database"; + public static final String CURRENT = "current"; + public static final String INDEXES = "indexes"; + public static final String TRUNCATE = "truncate"; + public static final String COUNT = "count"; + public static final String LOAD = "load"; + public static final String UNLOAD = "unload"; + public static final String PROPERTIES = "properties"; + public static final String RENAME = "rename"; + public static final String REVISION = "revision"; + public static final String FULLCOUNT = "fullCount"; + public static final String GROUP = "group"; + public static final String NAMESPACE = "namespace"; + public static final String GRAPH = "graph"; + public static final String GRAPHS = "graphs"; + public static final String VERTEX = "vertex"; + public static final String EDGE = "edge"; + public static final String ERROR = "error"; +} diff --git a/src/main/java/com/arangodb/internal/ArangoExecuteable.java b/src/main/java/com/arangodb/internal/ArangoExecuteable.java new file mode 100644 index 000000000..5fb27ee17 --- /dev/null +++ b/src/main/java/com/arangodb/internal/ArangoExecuteable.java @@ -0,0 +1,38 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.internal; + +import com.arangodb.internal.velocystream.Connection; + +/** + * @author Mark - mark at arangodb.com + * + */ +public abstract class ArangoExecuteable, R, C extends Connection> { + + protected final E executor; + + public ArangoExecuteable(final E executor) { + super(); + this.executor = executor; + } + +} diff --git a/src/main/java/com/arangodb/internal/ArangoExecutor.java b/src/main/java/com/arangodb/internal/ArangoExecutor.java new file mode 100644 index 000000000..1360bf677 --- /dev/null +++ b/src/main/java/com/arangodb/internal/ArangoExecutor.java @@ -0,0 +1,210 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.internal; + +import java.lang.reflect.Type; +import java.util.Map; +import java.util.concurrent.Future; +import java.util.regex.Pattern; + +import com.arangodb.ArangoDBException; +import com.arangodb.internal.velocystream.Communication; +import com.arangodb.internal.velocystream.Connection; +import com.arangodb.velocypack.VPack; +import com.arangodb.velocypack.VPackParser; +import com.arangodb.velocypack.VPackSlice; +import com.arangodb.velocypack.exception.VPackException; +import com.arangodb.velocypack.exception.VPackParserException; +import com.arangodb.velocystream.Response; + +/** + * @author Mark - mark at arangodb.com + * + */ +public abstract class ArangoExecutor { + + public static interface ResponseDeserializer { + T deserialize(Response response) throws VPackException; + } + + private static final String REGEX_DOCUMENT_KEY = "[^/]+"; + private static final String REGEX_DOCUMENT_ID = "[^/]+/[^/]+"; + + protected final Communication communication; + protected final VPack vpacker; + protected final VPack vpackerNull; + protected final VPackParser vpackParser; + protected final DocumentCache documentCache; + protected final CollectionCache collectionCache; + + protected ArangoExecutor(final Communication communication, final VPack vpacker, final VPack vpackerNull, + final VPackParser vpackParser, final DocumentCache documentCache, final CollectionCache collectionCache) { + super(); + this.communication = communication; + this.vpacker = vpacker; + this.vpackerNull = vpackerNull; + this.vpackParser = vpackParser; + this.documentCache = documentCache; + this.collectionCache = collectionCache; + } + + public Communication communication() { + return communication; + } + + protected VPack vpack() { + return vpacker; + } + + protected VPack vpackNull() { + return vpackerNull; + } + + protected VPackParser vpackParser() { + return vpackParser; + } + + public DocumentCache documentCache() { + return documentCache; + } + + protected CollectionCache collectionCache() { + return collectionCache; + } + + protected String createPath(final String... params) { + final StringBuilder sb = new StringBuilder(); + for (int i = 0; i < params.length; i++) { + if (i > 0) { + sb.append("/"); + } + sb.append(params[i]); + } + return sb.toString(); + } + + public void validateDocumentKey(final String key) throws ArangoDBException { + validateName("document key", REGEX_DOCUMENT_KEY, key); + } + + public void validateDocumentId(final String id) throws ArangoDBException { + validateName("document id", REGEX_DOCUMENT_ID, id); + } + + protected 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)); + } + } + + @SuppressWarnings("unchecked") + protected T createResult( + final VPack vpack, + final VPackParser vpackParser, + final Type type, + final Response response) { + return (T) ((type != Void.class && response.getBody() != null) ? deserialize(response.getBody(), type) : null); + } + + @SuppressWarnings("unchecked") + protected 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); + } else { + doc = vpacker.deserialize(vpack, type); + } + return doc; + } catch (final VPackException e) { + throw new ArangoDBException(e); + } + } + + protected VPackSlice serialize(final Object entity) throws ArangoDBException { + try { + final VPackSlice vpack; + if (String.class.isAssignableFrom(entity.getClass())) { + vpack = vpackParser.fromJson((String) entity); + } else { + vpack = vpacker.serialize(entity); + } + return vpack; + } catch (final VPackException e) { + throw new ArangoDBException(e); + } + } + + protected VPackSlice serialize(final Object entity, final boolean serializeNullValues) throws ArangoDBException { + try { + final VPackSlice vpack; + if (String.class.isAssignableFrom(entity.getClass())) { + vpack = vpackParser.fromJson((String) entity, serializeNullValues); + } else { + final VPack vp = serializeNullValues ? vpackerNull : vpacker; + vpack = vp.serialize(entity); + } + return vpack; + } catch (final VPackException e) { + throw new ArangoDBException(e); + } + } + + protected VPackSlice serialize(final Object entity, final Type type) throws ArangoDBException { + try { + return vpacker.serialize(entity, type); + } catch (final VPackException e) { + throw new ArangoDBException(e); + } + } + + protected VPackSlice serialize(final Object entity, final Type type, final boolean serializeNullValues) + throws ArangoDBException { + try { + final VPack vp = serializeNullValues ? vpackerNull : vpacker; + return vp.serialize(entity, type); + } catch (final VPackException e) { + throw new ArangoDBException(e); + } + } + + protected VPackSlice serialize(final Object entity, final Type type, final Map additionalFields) + throws ArangoDBException { + try { + return vpacker.serialize(entity, type, additionalFields); + } catch (final VPackParserException e) { + throw new ArangoDBException(e); + } + } + + protected T unwrap(final Future future) throws ArangoDBException { + try { + return future.get(); + } catch (final Exception e) { + final Throwable cause = e.getCause(); + if (cause != null && ArangoDBException.class.isAssignableFrom(cause.getClass())) { + throw ArangoDBException.class.cast(cause); + } + throw new ArangoDBException(e); + } + } +} diff --git a/src/main/java/com/arangodb/internal/ArangoExecutorSync.java b/src/main/java/com/arangodb/internal/ArangoExecutorSync.java new file mode 100644 index 000000000..cf3d1c43d --- /dev/null +++ b/src/main/java/com/arangodb/internal/ArangoExecutorSync.java @@ -0,0 +1,64 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.internal; + +import java.lang.reflect.Type; + +import com.arangodb.ArangoDBException; +import com.arangodb.internal.velocystream.Communication; +import com.arangodb.internal.velocystream.ConnectionSync; +import com.arangodb.velocypack.VPack; +import com.arangodb.velocypack.VPackParser; +import com.arangodb.velocypack.exception.VPackException; +import com.arangodb.velocystream.Request; +import com.arangodb.velocystream.Response; + +/** + * @author Mark - mark at arangodb.com + * + */ +public class ArangoExecutorSync extends ArangoExecutor { + + public ArangoExecutorSync(final Communication communication, final VPack vpacker, + final VPack vpackerNull, final VPackParser vpackParser, final DocumentCache documentCache, + final CollectionCache collectionCache) { + super(communication, vpacker, vpackerNull, vpackParser, documentCache, collectionCache); + } + + public T execute(final Request request, final Type type) throws ArangoDBException { + return execute(request, new ResponseDeserializer() { + @Override + public T deserialize(final Response response) throws VPackException { + return createResult(vpacker, vpackParser, type, response); + } + }); + } + + public T execute(final Request request, final ResponseDeserializer responseDeserializer) + throws ArangoDBException { + try { + final Response response = communication.execute(request); + return responseDeserializer.deserialize(response); + } catch (final VPackException e) { + throw new ArangoDBException(e); + } + } +} diff --git a/src/main/java/com/arangodb/internal/CollectionCache.java b/src/main/java/com/arangodb/internal/CollectionCache.java new file mode 100644 index 000000000..2684267aa --- /dev/null +++ b/src/main/java/com/arangodb/internal/CollectionCache.java @@ -0,0 +1,108 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.internal; + +import java.util.Date; +import java.util.HashMap; +import java.util.Map; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.arangodb.ArangoDBException; +import com.arangodb.ArangoDatabase; +import com.arangodb.entity.CollectionEntity; + +/** + * @author Mark - mark at arangodb.com + * + */ +public class CollectionCache { + + private static final Logger LOGGER = LoggerFactory.getLogger(CollectionCache.class); + private static final long MAX_CACHE_TIME = 600000; + + private static class CollectionInfo { + private final String name; + private final long time; + + public CollectionInfo(final String name, final long time) { + super(); + this.name = name; + this.time = time; + } + } + + public static interface DBAccess { + ArangoDatabase db(final String name); + } + + private final Map> cache; + private DBAccess access; + private String db; + + public CollectionCache() { + super(); + cache = new HashMap>(); + } + + public void init(final DBAccess access) { + this.access = access; + } + + public void setDb(final String db) { + this.db = db; + } + + public String getCollectionName(final long id) { + final CollectionInfo info = getInfo(id); + return info != null ? info.name : null; + } + + private CollectionInfo getInfo(final long id) { + Map dbCache = cache.get(db); + if (dbCache == null) { + dbCache = new HashMap(); + cache.put(db, dbCache); + } + CollectionInfo info = dbCache.get(id); + if (info == null || isExpired(info.time)) { + try { + final String name = execute(id); + info = new CollectionInfo(name, new Date().getTime()); + dbCache.put(id, info); + } catch (final ArangoDBException e) { + LOGGER.error(e.getMessage(), e); + } + } + return info; + } + + private String execute(final long id) throws ArangoDBException { + final CollectionEntity result = access.db(db).collection(String.valueOf(id)).getInfo(); + return result.getName(); + } + + private boolean isExpired(final long time) { + return new Date().getTime() > time + MAX_CACHE_TIME; + } + +} diff --git a/src/main/java/com/arangodb/internal/DocumentCache.java b/src/main/java/com/arangodb/internal/DocumentCache.java new file mode 100644 index 000000000..331785188 --- /dev/null +++ b/src/main/java/com/arangodb/internal/DocumentCache.java @@ -0,0 +1,111 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.internal; + +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; +import java.util.Map.Entry; + +import com.arangodb.ArangoDBException; +import com.arangodb.entity.DocumentField; +import com.arangodb.entity.DocumentField.Type; + +/** + * @author Mark - mark at arangodb.com + * + */ +public class DocumentCache { + + private final Map, Map> cache; + + public DocumentCache() { + super(); + cache = new HashMap, Map>(); + } + + 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 e) { + throw new ArangoDBException(e); + } catch (final 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 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 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 new file mode 100644 index 000000000..7ca8c87e5 --- /dev/null +++ b/src/main/java/com/arangodb/internal/InternalArangoCollection.java @@ -0,0 +1,550 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.internal; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; + +import com.arangodb.entity.DocumentCreateEntity; +import com.arangodb.entity.DocumentDeleteEntity; +import com.arangodb.entity.DocumentField; +import com.arangodb.entity.DocumentUpdateEntity; +import com.arangodb.entity.ErrorEntity; +import com.arangodb.entity.IndexEntity; +import com.arangodb.entity.MultiDocumentEntity; +import com.arangodb.internal.ArangoExecutor.ResponseDeserializer; +import com.arangodb.internal.velocystream.Connection; +import com.arangodb.model.CollectionPropertiesOptions; +import com.arangodb.model.CollectionRenameOptions; +import com.arangodb.model.DocumentCreateOptions; +import com.arangodb.model.DocumentDeleteOptions; +import com.arangodb.model.DocumentExistsOptions; +import com.arangodb.model.DocumentReadOptions; +import com.arangodb.model.DocumentReplaceOptions; +import com.arangodb.model.DocumentUpdateOptions; +import com.arangodb.model.FulltextIndexOptions; +import com.arangodb.model.GeoIndexOptions; +import com.arangodb.model.HashIndexOptions; +import com.arangodb.model.OptionsBuilder; +import com.arangodb.model.PersistentIndexOptions; +import com.arangodb.model.SkiplistIndexOptions; +import com.arangodb.velocypack.Type; +import com.arangodb.velocypack.VPackSlice; +import com.arangodb.velocypack.exception.VPackException; +import com.arangodb.velocystream.Request; +import com.arangodb.velocystream.RequestType; +import com.arangodb.velocystream.Response; + +/** + * @author Mark - mark at arangodb.com + * + */ +public class InternalArangoCollection, R, C extends Connection> + extends ArangoExecuteable { + + private final String name; + private final String db; + + public InternalArangoCollection(final E executor, final String db, final String name) { + super(executor); + this.db = db; + this.name = name; + } + + public String name() { + return name; + } + + public String createDocumentHandle(final String key) { + executor.validateDocumentKey(key); + return executor.createPath(name, key); + } + + public Request insertDocumentRequest(final T value, final DocumentCreateOptions options) { + final Request request = new Request(db, RequestType.POST, + executor.createPath(ArangoDBConstants.PATH_API_DOCUMENT, name)); + final DocumentCreateOptions params = (options != null ? options : new DocumentCreateOptions()); + request.putQueryParam(ArangoDBConstants.WAIT_FOR_SYNC, params.getWaitForSync()); + request.putQueryParam(ArangoDBConstants.RETURN_NEW, params.getReturnNew()); + request.setBody(executor.serialize(value)); + return request; + } + + public ResponseDeserializer> insertDocumentResponseDeserializer(final T value) { + return new ResponseDeserializer>() { + @SuppressWarnings("unchecked") + @Override + public DocumentCreateEntity deserialize(final Response response) throws VPackException { + final VPackSlice body = response.getBody(); + final DocumentCreateEntity doc = executor.deserialize(body, DocumentCreateEntity.class); + final VPackSlice newDoc = body.get(ArangoDBConstants.NEW); + if (newDoc.isObject()) { + doc.setNew((T) executor.deserialize(newDoc, value.getClass())); + } + 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; + } + }; + } + + public Request insertDocumentsRequest(final Collection values, final DocumentCreateOptions params) { + final Request request = new Request(db, RequestType.POST, + executor.createPath(ArangoDBConstants.PATH_API_DOCUMENT, name)); + request.putQueryParam(ArangoDBConstants.WAIT_FOR_SYNC, params.getWaitForSync()); + request.putQueryParam(ArangoDBConstants.RETURN_NEW, params.getReturnNew()); + request.setBody(executor.serialize(values)); + return request; + } + + @SuppressWarnings("unchecked") + public ResponseDeserializer>> insertDocumentsResponseDeserializer( + final Collection values, + final DocumentCreateOptions params) { + return new ResponseDeserializer>>() { + @Override + public MultiDocumentEntity> deserialize(final Response response) + throws VPackException { + Class type = null; + if (params.getReturnNew() != null && params.getReturnNew()) { + if (!values.isEmpty()) { + type = (Class) values.iterator().next().getClass(); + } + } + final MultiDocumentEntity> multiDocument = new MultiDocumentEntity>(); + final Collection> docs = new ArrayList>(); + final Collection errors = new ArrayList(); + final VPackSlice body = response.getBody(); + for (final Iterator iterator = body.arrayIterator(); iterator.hasNext();) { + final VPackSlice next = iterator.next(); + if (next.get(ArangoDBConstants.ERROR).isTrue()) { + errors.add((ErrorEntity) executor.deserialize(next, ErrorEntity.class)); + } else { + final DocumentCreateEntity doc = executor.deserialize(next, DocumentCreateEntity.class); + final VPackSlice newDoc = next.get(ArangoDBConstants.NEW); + if (newDoc.isObject()) { + doc.setNew((T) executor.deserialize(newDoc, type)); + } + docs.add(doc); + } + } + multiDocument.setDocuments(docs); + multiDocument.setErrors(errors); + return multiDocument; + } + }; + } + + public Request getDocumentRequest(final String key, final DocumentReadOptions options) { + final Request request = new Request(db, RequestType.GET, + executor.createPath(ArangoDBConstants.PATH_API_DOCUMENT, createDocumentHandle(key))); + final DocumentReadOptions params = (options != null ? options : new DocumentReadOptions()); + request.putHeaderParam(ArangoDBConstants.IF_NONE_MATCH, params.getIfNoneMatch()); + request.putHeaderParam(ArangoDBConstants.IF_MATCH, params.getIfMatch()); + return request; + } + + public Request replaceDocumentRequest(final String key, final T value, final DocumentReplaceOptions options) { + final Request request = new Request(db, RequestType.PUT, + executor.createPath(ArangoDBConstants.PATH_API_DOCUMENT, createDocumentHandle(key))); + final DocumentReplaceOptions params = (options != null ? options : new DocumentReplaceOptions()); + request.putQueryParam(ArangoDBConstants.WAIT_FOR_SYNC, params.getWaitForSync()); + request.putQueryParam(ArangoDBConstants.IGNORE_REVS, params.getIgnoreRevs()); + request.putQueryParam(ArangoDBConstants.RETURN_NEW, params.getReturnNew()); + request.putQueryParam(ArangoDBConstants.RETURN_OLD, params.getReturnOld()); + request.putHeaderParam(ArangoDBConstants.IF_MATCH, params.getIfMatch()); + request.setBody(executor.serialize(value)); + return request; + } + + public ResponseDeserializer> replaceDocumentResponseDeserializer(final T value) { + return new ResponseDeserializer>() { + @SuppressWarnings("unchecked") + @Override + public DocumentUpdateEntity deserialize(final Response response) throws VPackException { + final VPackSlice body = response.getBody(); + final DocumentUpdateEntity doc = executor.deserialize(body, DocumentUpdateEntity.class); + final VPackSlice newDoc = body.get(ArangoDBConstants.NEW); + if (newDoc.isObject()) { + doc.setNew((T) executor.deserialize(newDoc, value.getClass())); + } + final VPackSlice oldDoc = body.get(ArangoDBConstants.OLD); + if (oldDoc.isObject()) { + doc.setOld((T) executor.deserialize(oldDoc, value.getClass())); + } + final Map values = new HashMap(); + values.put(DocumentField.Type.REV, doc.getRev()); + executor.documentCache.setValues(value, values); + return doc; + } + }; + } + + public Request replaceDocumentsRequest(final Collection values, final DocumentReplaceOptions params) { + final Request request; + request = new Request(db, RequestType.PUT, executor.createPath(ArangoDBConstants.PATH_API_DOCUMENT, name)); + request.putQueryParam(ArangoDBConstants.WAIT_FOR_SYNC, params.getWaitForSync()); + request.putQueryParam(ArangoDBConstants.IGNORE_REVS, params.getIgnoreRevs()); + request.putQueryParam(ArangoDBConstants.RETURN_NEW, params.getReturnNew()); + request.putQueryParam(ArangoDBConstants.RETURN_OLD, params.getReturnOld()); + request.putHeaderParam(ArangoDBConstants.IF_MATCH, params.getIfMatch()); + request.setBody(executor.serialize(values)); + return request; + } + + @SuppressWarnings("unchecked") + public ResponseDeserializer>> replaceDocumentsResponseDeserializer( + final Collection values, + final DocumentReplaceOptions params) { + return new ResponseDeserializer>>() { + @Override + public MultiDocumentEntity> deserialize(final Response response) + throws VPackException { + Class type = null; + if ((params.getReturnNew() != null && params.getReturnNew()) + || (params.getReturnOld() != null && params.getReturnOld())) { + if (!values.isEmpty()) { + type = (Class) values.iterator().next().getClass(); + } + } + final MultiDocumentEntity> multiDocument = new MultiDocumentEntity>(); + final Collection> docs = new ArrayList>(); + final Collection errors = new ArrayList(); + final VPackSlice body = response.getBody(); + for (final Iterator iterator = body.arrayIterator(); iterator.hasNext();) { + final VPackSlice next = iterator.next(); + if (next.get(ArangoDBConstants.ERROR).isTrue()) { + errors.add((ErrorEntity) executor.deserialize(next, ErrorEntity.class)); + } else { + final DocumentUpdateEntity doc = executor.deserialize(next, DocumentUpdateEntity.class); + final VPackSlice newDoc = next.get(ArangoDBConstants.NEW); + if (newDoc.isObject()) { + doc.setNew((T) executor.deserialize(newDoc, type)); + } + final VPackSlice oldDoc = next.get(ArangoDBConstants.OLD); + if (oldDoc.isObject()) { + doc.setOld((T) executor.deserialize(oldDoc, type)); + } + docs.add(doc); + } + } + multiDocument.setDocuments(docs); + multiDocument.setErrors(errors); + return multiDocument; + } + }; + } + + public Request updateDocumentRequest(final String key, final T value, final DocumentUpdateOptions options) { + final Request request; + request = new Request(db, RequestType.PATCH, + executor.createPath(ArangoDBConstants.PATH_API_DOCUMENT, createDocumentHandle(key))); + final DocumentUpdateOptions params = (options != null ? options : new DocumentUpdateOptions()); + request.putQueryParam(ArangoDBConstants.KEEP_NULL, params.getKeepNull()); + request.putQueryParam(ArangoDBConstants.MERGE_OBJECTS, params.getMergeObjects()); + request.putQueryParam(ArangoDBConstants.WAIT_FOR_SYNC, params.getWaitForSync()); + request.putQueryParam(ArangoDBConstants.IGNORE_REVS, params.getIgnoreRevs()); + request.putQueryParam(ArangoDBConstants.RETURN_NEW, params.getReturnNew()); + request.putQueryParam(ArangoDBConstants.RETURN_OLD, params.getReturnOld()); + request.putHeaderParam(ArangoDBConstants.IF_MATCH, params.getIfMatch()); + request.setBody(executor.serialize(value, true)); + return request; + } + + public ResponseDeserializer> updateDocumentResponseDeserializer(final T value) { + return new ResponseDeserializer>() { + @SuppressWarnings("unchecked") + @Override + public DocumentUpdateEntity deserialize(final Response response) throws VPackException { + final VPackSlice body = response.getBody(); + final DocumentUpdateEntity doc = executor.deserialize(body, DocumentUpdateEntity.class); + final VPackSlice newDoc = body.get(ArangoDBConstants.NEW); + if (newDoc.isObject()) { + doc.setNew((T) executor.deserialize(newDoc, value.getClass())); + } + final VPackSlice oldDoc = body.get(ArangoDBConstants.OLD); + if (oldDoc.isObject()) { + doc.setOld((T) executor.deserialize(oldDoc, value.getClass())); + } + return doc; + } + }; + } + + public Request updateDocumentsRequest(final Collection values, final DocumentUpdateOptions params) { + final Request request; + request = new Request(db, RequestType.PATCH, executor.createPath(ArangoDBConstants.PATH_API_DOCUMENT, name)); + final Boolean keepNull = params.getKeepNull(); + request.putQueryParam(ArangoDBConstants.KEEP_NULL, keepNull); + request.putQueryParam(ArangoDBConstants.MERGE_OBJECTS, params.getMergeObjects()); + request.putQueryParam(ArangoDBConstants.WAIT_FOR_SYNC, params.getWaitForSync()); + request.putQueryParam(ArangoDBConstants.IGNORE_REVS, params.getIgnoreRevs()); + request.putQueryParam(ArangoDBConstants.RETURN_NEW, params.getReturnNew()); + request.putQueryParam(ArangoDBConstants.RETURN_OLD, params.getReturnOld()); + request.putHeaderParam(ArangoDBConstants.IF_MATCH, params.getIfMatch()); + request.setBody(executor.serialize(values, true)); + return request; + } + + @SuppressWarnings("unchecked") + public ResponseDeserializer>> updateDocumentsResponseDeserializer( + final Collection values, + final DocumentUpdateOptions params) { + return new ResponseDeserializer>>() { + @Override + public MultiDocumentEntity> deserialize(final Response response) + throws VPackException { + Class type = null; + if ((params.getReturnNew() != null && params.getReturnNew()) + || (params.getReturnOld() != null && params.getReturnOld())) { + if (!values.isEmpty()) { + type = (Class) values.iterator().next().getClass(); + } + } + final MultiDocumentEntity> multiDocument = new MultiDocumentEntity>(); + final Collection> docs = new ArrayList>(); + final Collection errors = new ArrayList(); + final VPackSlice body = response.getBody(); + for (final Iterator iterator = body.arrayIterator(); iterator.hasNext();) { + final VPackSlice next = iterator.next(); + if (next.get(ArangoDBConstants.ERROR).isTrue()) { + errors.add((ErrorEntity) executor.deserialize(next, ErrorEntity.class)); + } else { + final DocumentUpdateEntity doc = executor.deserialize(next, DocumentUpdateEntity.class); + final VPackSlice newDoc = next.get(ArangoDBConstants.NEW); + if (newDoc.isObject()) { + doc.setNew((T) executor.deserialize(newDoc, type)); + } + final VPackSlice oldDoc = next.get(ArangoDBConstants.OLD); + if (oldDoc.isObject()) { + doc.setOld((T) executor.deserialize(oldDoc, type)); + } + docs.add(doc); + } + } + multiDocument.setDocuments(docs); + multiDocument.setErrors(errors); + return multiDocument; + } + }; + } + + public Request deleteDocumentRequest(final String key, final DocumentDeleteOptions options) { + final Request request; + request = new Request(db, RequestType.DELETE, + executor.createPath(ArangoDBConstants.PATH_API_DOCUMENT, createDocumentHandle(key))); + final DocumentDeleteOptions params = (options != null ? options : new DocumentDeleteOptions()); + request.putQueryParam(ArangoDBConstants.WAIT_FOR_SYNC, params.getWaitForSync()); + request.putQueryParam(ArangoDBConstants.RETURN_OLD, params.getReturnOld()); + request.putHeaderParam(ArangoDBConstants.IF_MATCH, params.getIfMatch()); + return request; + } + + public ResponseDeserializer> deleteDocumentResponseDeserializer(final Class type) { + return new ResponseDeserializer>() { + @SuppressWarnings("unchecked") + @Override + public DocumentDeleteEntity deserialize(final Response response) throws VPackException { + final VPackSlice body = response.getBody(); + final DocumentDeleteEntity doc = executor.deserialize(body, DocumentDeleteEntity.class); + final VPackSlice oldDoc = body.get(ArangoDBConstants.OLD); + if (oldDoc.isObject()) { + doc.setOld((T) executor.deserialize(oldDoc, type)); + } + return doc; + } + }; + } + + public Request deleteDocumentsRequest(final Collection keys, final DocumentDeleteOptions options) { + final Request request; + request = new Request(db, RequestType.DELETE, executor.createPath(ArangoDBConstants.PATH_API_DOCUMENT, name)); + final DocumentDeleteOptions params = (options != null ? options : new DocumentDeleteOptions()); + request.putQueryParam(ArangoDBConstants.WAIT_FOR_SYNC, params.getWaitForSync()); + request.putQueryParam(ArangoDBConstants.RETURN_OLD, params.getReturnOld()); + request.setBody(executor.serialize(keys)); + return request; + } + + public ResponseDeserializer>> deleteDocumentsResponseDeserializer( + final Class type) { + return new ResponseDeserializer>>() { + @SuppressWarnings("unchecked") + @Override + public MultiDocumentEntity> deserialize(final Response response) + throws VPackException { + final MultiDocumentEntity> multiDocument = new MultiDocumentEntity>(); + final Collection> docs = new ArrayList>(); + final Collection errors = new ArrayList(); + final VPackSlice body = response.getBody(); + for (final Iterator iterator = body.arrayIterator(); iterator.hasNext();) { + final VPackSlice next = iterator.next(); + if (next.get(ArangoDBConstants.ERROR).isTrue()) { + errors.add((ErrorEntity) executor.deserialize(next, ErrorEntity.class)); + } else { + final DocumentDeleteEntity doc = executor.deserialize(next, DocumentDeleteEntity.class); + final VPackSlice oldDoc = next.get(ArangoDBConstants.OLD); + if (oldDoc.isObject()) { + doc.setOld((T) executor.deserialize(oldDoc, type)); + } + docs.add(doc); + } + } + multiDocument.setDocuments(docs); + multiDocument.setErrors(errors); + return multiDocument; + } + }; + } + + public Request documentExistsRequest(final String key, final DocumentExistsOptions options) { + final Request request; + request = new Request(db, RequestType.HEAD, + executor.createPath(ArangoDBConstants.PATH_API_DOCUMENT, createDocumentHandle(key))); + final DocumentExistsOptions params = (options != null ? options : new DocumentExistsOptions()); + request.putHeaderParam(ArangoDBConstants.IF_MATCH, params.getIfMatch()); + request.putHeaderParam(ArangoDBConstants.IF_NONE_MATCH, params.getIfNoneMatch()); + return request; + } + + public Request createHashIndexRequest(final Collection fields, final HashIndexOptions options) { + final Request request; + request = new Request(db, RequestType.POST, ArangoDBConstants.PATH_API_INDEX); + request.putQueryParam(ArangoDBConstants.COLLECTION, name); + request.setBody( + executor.serialize(OptionsBuilder.build(options != null ? options : new HashIndexOptions(), fields))); + return request; + } + + public Request createSkiplistIndexRequest(final Collection fields, final SkiplistIndexOptions options) { + final Request request; + request = new Request(db, RequestType.POST, ArangoDBConstants.PATH_API_INDEX); + request.putQueryParam(ArangoDBConstants.COLLECTION, name); + request.setBody( + executor.serialize(OptionsBuilder.build(options != null ? options : new SkiplistIndexOptions(), fields))); + return request; + } + + public Request createPersistentIndexRequest(final Collection fields, final PersistentIndexOptions options) { + final Request request; + request = new Request(db, RequestType.POST, ArangoDBConstants.PATH_API_INDEX); + request.putQueryParam(ArangoDBConstants.COLLECTION, name); + request.setBody( + executor.serialize(OptionsBuilder.build(options != null ? options : new PersistentIndexOptions(), fields))); + return request; + } + + public Request createGeoIndexRequest(final Collection fields, final GeoIndexOptions options) { + final Request request; + request = new Request(db, RequestType.POST, ArangoDBConstants.PATH_API_INDEX); + request.putQueryParam(ArangoDBConstants.COLLECTION, name); + request.setBody( + executor.serialize(OptionsBuilder.build(options != null ? options : new GeoIndexOptions(), fields))); + return request; + } + + public Request getIndexesRequest() { + final Request request; + request = new Request(db, RequestType.GET, ArangoDBConstants.PATH_API_INDEX); + request.putQueryParam(ArangoDBConstants.COLLECTION, name); + return request; + } + + public ResponseDeserializer> getIndexesResponseDeserializer() { + return new ResponseDeserializer>() { + @Override + public Collection deserialize(final Response response) throws VPackException { + return executor.deserialize(response.getBody().get(ArangoDBConstants.INDEXES), + new Type>() { + }.getType()); + } + }; + } + + public Request truncateRequest() { + return new Request(db, RequestType.PUT, + executor.createPath(ArangoDBConstants.PATH_API_COLLECTION, name, ArangoDBConstants.TRUNCATE)); + } + + public Request countRequest() { + return new Request(db, RequestType.GET, + executor.createPath(ArangoDBConstants.PATH_API_COLLECTION, name, ArangoDBConstants.COUNT)); + } + + public Request createFulltextIndexRequest(final Collection fields, final FulltextIndexOptions options) { + final Request request; + request = new Request(db, RequestType.POST, ArangoDBConstants.PATH_API_INDEX); + request.putQueryParam(ArangoDBConstants.COLLECTION, name); + request.setBody( + executor.serialize(OptionsBuilder.build(options != null ? options : new FulltextIndexOptions(), fields))); + return request; + } + + public Request dropRequest() { + return new Request(db, RequestType.DELETE, executor.createPath(ArangoDBConstants.PATH_API_COLLECTION, name)); + } + + public Request loadRequest() { + return new Request(db, RequestType.PUT, + executor.createPath(ArangoDBConstants.PATH_API_COLLECTION, name, ArangoDBConstants.LOAD)); + } + + public Request unloadRequest() { + return new Request(db, RequestType.PUT, + executor.createPath(ArangoDBConstants.PATH_API_COLLECTION, name, ArangoDBConstants.UNLOAD)); + } + + public Request getInfoRequest() { + return new Request(db, RequestType.GET, executor.createPath(ArangoDBConstants.PATH_API_COLLECTION, name)); + } + + public Request getPropertiesRequest() { + return new Request(db, RequestType.GET, + executor.createPath(ArangoDBConstants.PATH_API_COLLECTION, name, ArangoDBConstants.PROPERTIES)); + } + + public Request changePropertiesRequest(final CollectionPropertiesOptions options) { + final Request request; + request = new Request(db, RequestType.PUT, + executor.createPath(ArangoDBConstants.PATH_API_COLLECTION, name, ArangoDBConstants.PROPERTIES)); + request.setBody(executor.serialize(options != null ? options : new CollectionPropertiesOptions())); + return request; + } + + public Request renameRequest(final String newName) { + final Request request; + request = new Request(db, RequestType.PUT, + executor.createPath(ArangoDBConstants.PATH_API_COLLECTION, name, ArangoDBConstants.RENAME)); + request.setBody(executor.serialize(OptionsBuilder.build(new CollectionRenameOptions(), newName))); + return request; + } + + public Request getRevisionRequest() { + return new Request(db, RequestType.GET, + executor.createPath(ArangoDBConstants.PATH_API_COLLECTION, name, ArangoDBConstants.REVISION)); + } +} diff --git a/src/main/java/com/arangodb/internal/InternalArangoDB.java b/src/main/java/com/arangodb/internal/InternalArangoDB.java new file mode 100644 index 000000000..954a4f8f0 --- /dev/null +++ b/src/main/java/com/arangodb/internal/InternalArangoDB.java @@ -0,0 +1,153 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.internal; + +import java.util.Collection; + +import com.arangodb.entity.UserEntity; +import com.arangodb.internal.ArangoExecutor.ResponseDeserializer; +import com.arangodb.internal.velocystream.Connection; +import com.arangodb.model.DBCreateOptions; +import com.arangodb.model.LogOptions; +import com.arangodb.model.OptionsBuilder; +import com.arangodb.model.UserCreateOptions; +import com.arangodb.model.UserUpdateOptions; +import com.arangodb.velocypack.Type; +import com.arangodb.velocypack.VPackSlice; +import com.arangodb.velocypack.exception.VPackException; +import com.arangodb.velocystream.Request; +import com.arangodb.velocystream.RequestType; +import com.arangodb.velocystream.Response; + +/** + * @author Mark - mark at arangodb.com + * @param + * @param + * + */ +public class InternalArangoDB, R, C extends Connection> + extends ArangoExecuteable { + + public InternalArangoDB(final E executor) { + super(executor); + } + + protected Request createDatabaseRequest(final String name) { + final Request request = new Request(ArangoDBConstants.SYSTEM, RequestType.POST, + ArangoDBConstants.PATH_API_DATABASE); + request.setBody(executor.serialize(OptionsBuilder.build(new DBCreateOptions(), name))); + return request; + } + + protected ResponseDeserializer createDatabaseResponseDeserializer() { + return new ResponseDeserializer() { + @Override + public Boolean deserialize(final Response response) throws VPackException { + return response.getBody().get(ArangoDBConstants.RESULT).getAsBoolean(); + } + }; + } + + protected Request getDatabasesRequest(final String database) { + return new Request(database, RequestType.GET, ArangoDBConstants.PATH_API_DATABASE); + } + + protected ResponseDeserializer> getDatabaseResponseDeserializer() { + return new ResponseDeserializer>() { + @Override + public Collection deserialize(final Response response) throws VPackException { + final VPackSlice result = response.getBody().get(ArangoDBConstants.RESULT); + return executor.deserialize(result, new Type>() { + }.getType()); + } + }; + } + + protected Request getAccessibleDatabasesRequest(final String database) { + return new Request(database, RequestType.GET, + executor.createPath(ArangoDBConstants.PATH_API_DATABASE, ArangoDBConstants.USER)); + } + + protected Request getVersionRequest() { + return new Request(ArangoDBConstants.SYSTEM, RequestType.GET, ArangoDBConstants.PATH_API_VERSION); + } + + protected Request createUserRequest( + final String database, + final String user, + final String passwd, + final UserCreateOptions options) { + final Request request; + request = new Request(database, RequestType.POST, ArangoDBConstants.PATH_API_USER); + request.setBody(executor + .serialize(OptionsBuilder.build(options != null ? options : new UserCreateOptions(), user, passwd))); + return request; + } + + protected Request deleteUserRequest(final String database, final String user) { + return new Request(database, RequestType.DELETE, executor.createPath(ArangoDBConstants.PATH_API_USER, user)); + } + + protected Request getUsersRequest(final String database) { + return new Request(database, RequestType.GET, ArangoDBConstants.PATH_API_USER); + } + + protected Request getUserRequest(final String database, final String user) { + return new Request(database, RequestType.GET, executor.createPath(ArangoDBConstants.PATH_API_USER, user)); + } + + protected ResponseDeserializer> getUsersResponseDeserializer() { + return new ResponseDeserializer>() { + @Override + public Collection deserialize(final Response response) throws VPackException { + final VPackSlice result = response.getBody().get(ArangoDBConstants.RESULT); + return executor.deserialize(result, new Type>() { + }.getType()); + } + }; + } + + protected Request updateUserRequest(final String database, final String user, final UserUpdateOptions options) { + final Request request; + request = new Request(database, RequestType.PATCH, executor.createPath(ArangoDBConstants.PATH_API_USER, user)); + request.setBody(executor.serialize(options != null ? options : new UserUpdateOptions())); + return request; + } + + protected Request replaceUserRequest(final String database, final String user, final UserUpdateOptions options) { + final Request request; + request = new Request(database, RequestType.PUT, executor.createPath(ArangoDBConstants.PATH_API_USER, user)); + request.setBody(executor.serialize(options != null ? options : new UserUpdateOptions())); + return request; + } + + protected Request getLogsRequest(final LogOptions options) { + final LogOptions params = options != null ? options : new LogOptions(); + return new Request(ArangoDBConstants.SYSTEM, RequestType.GET, ArangoDBConstants.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()); + } +} diff --git a/src/main/java/com/arangodb/internal/InternalArangoDatabase.java b/src/main/java/com/arangodb/internal/InternalArangoDatabase.java new file mode 100644 index 000000000..7732ace75 --- /dev/null +++ b/src/main/java/com/arangodb/internal/InternalArangoDatabase.java @@ -0,0 +1,356 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.internal; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Iterator; +import java.util.Map; + +import com.arangodb.entity.CollectionEntity; +import com.arangodb.entity.DatabaseEntity; +import com.arangodb.entity.EdgeDefinition; +import com.arangodb.entity.GraphEntity; +import com.arangodb.entity.PathEntity; +import com.arangodb.entity.QueryCachePropertiesEntity; +import com.arangodb.entity.QueryTrackingPropertiesEntity; +import com.arangodb.entity.TraversalEntity; +import com.arangodb.internal.ArangoExecutor.ResponseDeserializer; +import com.arangodb.internal.velocystream.Connection; +import com.arangodb.model.AqlFunctionCreateOptions; +import com.arangodb.model.AqlFunctionDeleteOptions; +import com.arangodb.model.AqlFunctionGetOptions; +import com.arangodb.model.AqlQueryExplainOptions; +import com.arangodb.model.AqlQueryOptions; +import com.arangodb.model.AqlQueryParseOptions; +import com.arangodb.model.CollectionCreateOptions; +import com.arangodb.model.CollectionsReadOptions; +import com.arangodb.model.GraphCreateOptions; +import com.arangodb.model.OptionsBuilder; +import com.arangodb.model.TransactionOptions; +import com.arangodb.model.TraversalOptions; +import com.arangodb.model.UserAccessOptions; +import com.arangodb.velocypack.Type; +import com.arangodb.velocypack.VPackSlice; +import com.arangodb.velocypack.exception.VPackException; +import com.arangodb.velocystream.Request; +import com.arangodb.velocystream.RequestType; +import com.arangodb.velocystream.Response; + +/** + * @author Mark - mark at arangodb.com + * + */ +public class InternalArangoDatabase, R, C extends Connection> + extends ArangoExecuteable { + + private final String name; + + public InternalArangoDatabase(final E executor, final String name) { + super(executor); + this.name = name; + } + + public String name() { + return name; + } + + protected Request createCollectionRequest(final String name, final CollectionCreateOptions options) { + return new Request(name(), RequestType.POST, ArangoDBConstants.PATH_API_COLLECTION).setBody( + executor.serialize(OptionsBuilder.build(options != null ? options : new CollectionCreateOptions(), name))); + } + + protected Request getCollectionsRequest(final CollectionsReadOptions options) { + final Request request; + request = new Request(name(), RequestType.GET, ArangoDBConstants.PATH_API_COLLECTION); + final CollectionsReadOptions params = (options != null ? options : new CollectionsReadOptions()); + request.putQueryParam(ArangoDBConstants.EXCLUDE_SYSTEM, params.getExcludeSystem()); + return request; + } + + protected ResponseDeserializer> getCollectionsResponseDeserializer() { + return new ResponseDeserializer>() { + @Override + public Collection deserialize(final Response response) throws VPackException { + final VPackSlice result = response.getBody().get(ArangoDBConstants.RESULT); + return executor.deserialize(result, new Type>() { + }.getType()); + } + }; + } + + protected Request getIndexRequest(final String id) { + return new Request(name, RequestType.GET, executor.createPath(ArangoDBConstants.PATH_API_INDEX, id)); + } + + protected Request deleteIndexRequest(final String id) { + return new Request(name, RequestType.DELETE, executor.createPath(ArangoDBConstants.PATH_API_INDEX, id)); + } + + protected ResponseDeserializer deleteIndexResponseDeserializer() { + return new ResponseDeserializer() { + @Override + public String deserialize(final Response response) throws VPackException { + return response.getBody().get(ArangoDBConstants.ID).getAsString(); + } + }; + } + + protected Request dropRequest() { + return new Request(ArangoDBConstants.SYSTEM, RequestType.DELETE, + executor.createPath(ArangoDBConstants.PATH_API_DATABASE, name)); + } + + protected ResponseDeserializer createDropResponseDeserializer() { + return new ResponseDeserializer() { + @Override + public Boolean deserialize(final Response response) throws VPackException { + return response.getBody().get(ArangoDBConstants.RESULT).getAsBoolean(); + } + }; + } + + protected Request grantAccessRequest(final String user) { + return new Request(ArangoDBConstants.SYSTEM, RequestType.PUT, + executor.createPath(ArangoDBConstants.PATH_API_USER, user, ArangoDBConstants.DATABASE, name)).setBody( + executor.serialize(OptionsBuilder.build(new UserAccessOptions(), ArangoDBConstants.RW))); + } + + protected Request revokeAccessRequest(final String user) { + return new Request(ArangoDBConstants.SYSTEM, RequestType.PUT, + executor.createPath(ArangoDBConstants.PATH_API_USER, user, ArangoDBConstants.DATABASE, name)).setBody( + executor.serialize(OptionsBuilder.build(new UserAccessOptions(), ArangoDBConstants.NONE))); + } + + protected Request queryRequest( + final String query, + final Map bindVars, + final AqlQueryOptions options) { + return new Request(name, RequestType.POST, ArangoDBConstants.PATH_API_CURSOR).setBody(executor + .serialize(OptionsBuilder.build(options != null ? options : new AqlQueryOptions(), query, bindVars))); + } + + protected Request queryNextRequest(final String id) { + return new Request(name, RequestType.PUT, executor.createPath(ArangoDBConstants.PATH_API_CURSOR, id)); + } + + protected Request queryCloseRequest(final String id) { + return new Request(name, RequestType.DELETE, executor.createPath(ArangoDBConstants.PATH_API_CURSOR, id)); + } + + protected Request explainQueryRequest( + final String query, + final Map bindVars, + final AqlQueryExplainOptions options) { + return new Request(name, RequestType.POST, ArangoDBConstants.PATH_API_EXPLAIN).setBody(executor.serialize( + OptionsBuilder.build(options != null ? options : new AqlQueryExplainOptions(), query, bindVars))); + } + + protected Request parseQueryRequest(final String query) { + return new Request(name, RequestType.POST, ArangoDBConstants.PATH_API_QUERY) + .setBody(executor.serialize(OptionsBuilder.build(new AqlQueryParseOptions(), query))); + } + + protected Request clearQueryCacheRequest() { + return new Request(name, RequestType.DELETE, ArangoDBConstants.PATH_API_QUERY_CACHE); + } + + protected Request getQueryCachePropertiesRequest() { + return new Request(name, RequestType.GET, ArangoDBConstants.PATH_API_QUERY_CACHE_PROPERTIES); + } + + protected Request setQueryCachePropertiesRequest(final QueryCachePropertiesEntity properties) { + return new Request(name, RequestType.PUT, ArangoDBConstants.PATH_API_QUERY_CACHE_PROPERTIES) + .setBody(executor.serialize(properties)); + } + + protected Request getQueryTrackingPropertiesRequest() { + return new Request(name, RequestType.GET, ArangoDBConstants.PATH_API_QUERY_PROPERTIES); + } + + protected Request setQueryTrackingPropertiesRequest(final QueryTrackingPropertiesEntity properties) { + return new Request(name, RequestType.PUT, ArangoDBConstants.PATH_API_QUERY_PROPERTIES) + .setBody(executor.serialize(properties)); + } + + protected Request getCurrentlyRunningQueriesRequest() { + return new Request(name, RequestType.GET, ArangoDBConstants.PATH_API_QUERY_CURRENT); + } + + protected Request getSlowQueriesRequest() { + return new Request(name, RequestType.GET, ArangoDBConstants.PATH_API_QUERY_SLOW); + } + + protected Request clearSlowQueriesRequest() { + return new Request(name, RequestType.DELETE, ArangoDBConstants.PATH_API_QUERY_SLOW); + } + + protected Request killQueryRequest(final String id) { + return new Request(name, RequestType.DELETE, executor.createPath(ArangoDBConstants.PATH_API_QUERY, id)); + } + + protected Request createAqlFunctionRequest( + final String name, + final String code, + final AqlFunctionCreateOptions options) { + return new Request(name(), RequestType.POST, ArangoDBConstants.PATH_API_AQLFUNCTION).setBody(executor.serialize( + OptionsBuilder.build(options != null ? options : new AqlFunctionCreateOptions(), name, code))); + } + + protected Request deleteAqlFunctionRequest(final String name, final AqlFunctionDeleteOptions options) { + final Request request = new Request(name(), RequestType.DELETE, + executor.createPath(ArangoDBConstants.PATH_API_AQLFUNCTION, name)); + final AqlFunctionDeleteOptions params = options != null ? options : new AqlFunctionDeleteOptions(); + request.putQueryParam(ArangoDBConstants.GROUP, params.getGroup()); + return request; + } + + protected Request getAqlFunctionsRequest(final AqlFunctionGetOptions options) { + final Request request = new Request(name(), RequestType.GET, ArangoDBConstants.PATH_API_AQLFUNCTION); + final AqlFunctionGetOptions params = options != null ? options : new AqlFunctionGetOptions(); + request.putQueryParam(ArangoDBConstants.NAMESPACE, params.getNamespace()); + return request; + } + + protected Request createGraphRequest( + final String name, + final Collection edgeDefinitions, + final GraphCreateOptions options) { + return new Request(name(), RequestType.POST, ArangoDBConstants.PATH_API_GHARIAL).setBody(executor.serialize( + OptionsBuilder.build(options != null ? options : new GraphCreateOptions(), name, edgeDefinitions))); + } + + protected ResponseDeserializer createGraphResponseDeserializer() { + return new ResponseDeserializer() { + @Override + public GraphEntity deserialize(final Response response) throws VPackException { + return executor.deserialize(response.getBody().get(ArangoDBConstants.GRAPH), GraphEntity.class); + } + }; + } + + protected Request getGraphsRequest() { + return new Request(name, RequestType.GET, ArangoDBConstants.PATH_API_GHARIAL); + } + + protected ResponseDeserializer> getGraphsResponseDeserializer() { + return new ResponseDeserializer>() { + @Override + public Collection deserialize(final Response response) throws VPackException { + return executor.deserialize(response.getBody().get(ArangoDBConstants.GRAPHS), + new Type>() { + }.getType()); + } + }; + } + + protected Request transactionRequest(final String action, final TransactionOptions options) { + return new Request(name, RequestType.POST, ArangoDBConstants.PATH_API_TRANSACTION).setBody( + executor.serialize(OptionsBuilder.build(options != null ? options : new TransactionOptions(), action))); + } + + protected ResponseDeserializer transactionResponseDeserializer(final Class type) { + return new ResponseDeserializer() { + @Override + public T deserialize(final Response response) throws VPackException { + final VPackSlice body = response.getBody(); + if (body != null) { + final VPackSlice result = body.get(ArangoDBConstants.RESULT); + if (!result.isNone()) { + return executor.deserialize(result, type); + } + } + return null; + } + }; + } + + protected Request getInfoRequest() { + return new Request(name, RequestType.GET, + executor.createPath(ArangoDBConstants.PATH_API_DATABASE, ArangoDBConstants.CURRENT)); + } + + protected ResponseDeserializer getInfoResponseDeserializer() { + return new ResponseDeserializer() { + @Override + public DatabaseEntity deserialize(final Response response) throws VPackException { + return executor.deserialize(response.getBody().get(ArangoDBConstants.RESULT), DatabaseEntity.class); + } + }; + } + + protected Request executeTraversalRequest(final TraversalOptions options) { + return new Request(name, RequestType.POST, ArangoDBConstants.PATH_API_TRAVERSAL) + .setBody(executor.serialize(options != null ? options : new TransactionOptions())); + } + + @SuppressWarnings("hiding") + protected ResponseDeserializer> executeTraversalResponseDeserializer( + final Class vertexClass, + final Class edgeClass) { + return new ResponseDeserializer>() { + @Override + public TraversalEntity deserialize(final Response response) throws VPackException { + final TraversalEntity result = new TraversalEntity(); + final VPackSlice visited = response.getBody().get(ArangoDBConstants.RESULT) + .get(ArangoDBConstants.VISITED); + result.setVertices(deserializeVertices(vertexClass, visited)); + + final Collection> paths = new ArrayList>(); + for (final Iterator iterator = visited.get("paths").arrayIterator(); iterator.hasNext();) { + final PathEntity path = new PathEntity(); + final VPackSlice next = iterator.next(); + path.setEdges(deserializeEdges(edgeClass, next)); + path.setVertices(deserializeVertices(vertexClass, next)); + paths.add(path); + } + result.setPaths(paths); + return result; + } + }; + } + + @SuppressWarnings("unchecked") + protected Collection deserializeVertices(final Class vertexClass, final VPackSlice vpack) + throws VPackException { + final Collection vertices = new ArrayList(); + for (final Iterator iterator = vpack.get(ArangoDBConstants.VERTICES).arrayIterator(); iterator + .hasNext();) { + vertices.add((V) executor.deserialize(iterator.next(), vertexClass)); + } + return vertices; + } + + @SuppressWarnings({ "hiding", "unchecked" }) + protected Collection deserializeEdges(final Class edgeClass, final VPackSlice next) + throws VPackException { + final Collection edges = new ArrayList(); + for (final Iterator iteratorEdge = next.get(ArangoDBConstants.EDGES).arrayIterator(); iteratorEdge + .hasNext();) { + edges.add((E) executor.deserialize(iteratorEdge.next(), edgeClass)); + } + return edges; + } + + protected Request reloadRoutingRequest() { + return new Request(name, RequestType.POST, ArangoDBConstants.PATH_API_ADMIN_ROUTING_RELOAD); + } +} diff --git a/src/main/java/com/arangodb/internal/InternalArangoEdgeCollection.java b/src/main/java/com/arangodb/internal/InternalArangoEdgeCollection.java new file mode 100644 index 000000000..c42521b8e --- /dev/null +++ b/src/main/java/com/arangodb/internal/InternalArangoEdgeCollection.java @@ -0,0 +1,167 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.internal; + +import java.util.HashMap; +import java.util.Map; + +import com.arangodb.entity.DocumentField; +import com.arangodb.entity.EdgeEntity; +import com.arangodb.entity.EdgeUpdateEntity; +import com.arangodb.internal.ArangoExecutor.ResponseDeserializer; +import com.arangodb.internal.velocystream.Connection; +import com.arangodb.model.DocumentReadOptions; +import com.arangodb.model.EdgeCreateOptions; +import com.arangodb.model.EdgeDeleteOptions; +import com.arangodb.model.EdgeReplaceOptions; +import com.arangodb.model.EdgeUpdateOptions; +import com.arangodb.velocypack.VPackSlice; +import com.arangodb.velocypack.exception.VPackException; +import com.arangodb.velocystream.Request; +import com.arangodb.velocystream.RequestType; +import com.arangodb.velocystream.Response; + +/** + * @author Mark - mark at arangodb.com + * + */ +public class InternalArangoEdgeCollection, R, C extends Connection> + extends ArangoExecuteable { + + private final String db; + private final String graph; + private final String name; + + public InternalArangoEdgeCollection(final E executor, final String db, final String graph, final String name) { + super(executor); + this.db = db; + this.graph = graph; + this.name = name; + } + + public String name() { + return name; + } + + protected String createDocumentHandle(final String key) { + executor.validateDocumentKey(key); + return executor.createPath(name, key); + } + + protected Request insertEdgeRequest(final T value, final EdgeCreateOptions options) { + final Request request = new Request(db, RequestType.POST, + executor.createPath(ArangoDBConstants.PATH_API_GHARIAL, graph, ArangoDBConstants.EDGE, name)); + final EdgeCreateOptions params = (options != null ? options : new EdgeCreateOptions()); + request.putQueryParam(ArangoDBConstants.WAIT_FOR_SYNC, params.getWaitForSync()); + request.setBody(executor.serialize(value)); + return request; + } + + protected ResponseDeserializer insertEdgeResponseDeserializer(final T value) { + return new ResponseDeserializer() { + @Override + public EdgeEntity deserialize(final Response response) throws VPackException { + final VPackSlice body = response.getBody().get(ArangoDBConstants.EDGE); + final EdgeEntity doc = executor.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 DocumentReadOptions options) { + final Request request = new Request(db, RequestType.GET, executor.createPath(ArangoDBConstants.PATH_API_GHARIAL, + graph, ArangoDBConstants.EDGE, createDocumentHandle(key))); + final DocumentReadOptions params = (options != null ? options : new DocumentReadOptions()); + request.putHeaderParam(ArangoDBConstants.IF_NONE_MATCH, params.getIfNoneMatch()); + request.putHeaderParam(ArangoDBConstants.IF_MATCH, params.getIfMatch()); + return request; + } + + protected ResponseDeserializer getEdgeResponseDeserializer(final Class type) { + return new ResponseDeserializer() { + @Override + public T deserialize(final Response response) throws VPackException { + return executor.deserialize(response.getBody().get(ArangoDBConstants.EDGE), type); + } + }; + } + + protected Request replaceEdgeRequest(final String key, final T value, final EdgeReplaceOptions options) { + final Request request = new Request(db, RequestType.PUT, executor.createPath(ArangoDBConstants.PATH_API_GHARIAL, + graph, ArangoDBConstants.EDGE, createDocumentHandle(key))); + final EdgeReplaceOptions params = (options != null ? options : new EdgeReplaceOptions()); + request.putQueryParam(ArangoDBConstants.WAIT_FOR_SYNC, params.getWaitForSync()); + request.putHeaderParam(ArangoDBConstants.IF_MATCH, params.getIfMatch()); + request.setBody(executor.serialize(value)); + return request; + } + + protected ResponseDeserializer replaceEdgeResponseDeserializer(final T value) { + return new ResponseDeserializer() { + @Override + public EdgeUpdateEntity deserialize(final Response response) throws VPackException { + final VPackSlice body = response.getBody().get(ArangoDBConstants.EDGE); + final EdgeUpdateEntity doc = executor.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 = new Request(db, RequestType.PATCH, executor.createPath(ArangoDBConstants.PATH_API_GHARIAL, graph, + ArangoDBConstants.EDGE, createDocumentHandle(key))); + final EdgeUpdateOptions params = (options != null ? options : new EdgeUpdateOptions()); + request.putQueryParam(ArangoDBConstants.KEEP_NULL, params.getKeepNull()); + request.putQueryParam(ArangoDBConstants.WAIT_FOR_SYNC, params.getWaitForSync()); + request.putHeaderParam(ArangoDBConstants.IF_MATCH, params.getIfMatch()); + request.setBody(executor.serialize(value, true)); + return request; + } + + protected ResponseDeserializer updateEdgeResponseDeserializer(final T value) { + return new ResponseDeserializer() { + @Override + public EdgeUpdateEntity deserialize(final Response response) throws VPackException { + final VPackSlice body = response.getBody().get(ArangoDBConstants.EDGE); + return executor.deserialize(body, EdgeUpdateEntity.class); + } + }; + } + + protected Request deleteEdgeRequest(final String key, final EdgeDeleteOptions options) { + final Request request = new Request(db, RequestType.DELETE, executor.createPath( + ArangoDBConstants.PATH_API_GHARIAL, graph, ArangoDBConstants.EDGE, createDocumentHandle(key))); + final EdgeDeleteOptions params = (options != null ? options : new EdgeDeleteOptions()); + request.putQueryParam(ArangoDBConstants.WAIT_FOR_SYNC, params.getWaitForSync()); + request.putHeaderParam(ArangoDBConstants.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 new file mode 100644 index 000000000..a97258e9e --- /dev/null +++ b/src/main/java/com/arangodb/internal/InternalArangoGraph.java @@ -0,0 +1,162 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.internal; + +import java.util.Collection; + +import com.arangodb.entity.EdgeDefinition; +import com.arangodb.entity.GraphEntity; +import com.arangodb.internal.ArangoExecutor.ResponseDeserializer; +import com.arangodb.internal.velocystream.Connection; +import com.arangodb.model.OptionsBuilder; +import com.arangodb.model.VertexCollectionCreateOptions; +import com.arangodb.velocypack.Type; +import com.arangodb.velocypack.exception.VPackException; +import com.arangodb.velocystream.Request; +import com.arangodb.velocystream.RequestType; +import com.arangodb.velocystream.Response; + +/** + * @author Mark - mark at arangodb.com + * + */ +public class InternalArangoGraph, R, C extends Connection> + extends ArangoExecuteable { + + private final String db; + private final String name; + + public InternalArangoGraph(final E executor, final String db, final String name) { + super(executor); + this.db = db; + this.name = name; + } + + public String db() { + return db; + } + + public String name() { + return name; + } + + protected Request dropRequest() { + return new Request(db, RequestType.DELETE, executor.createPath(ArangoDBConstants.PATH_API_GHARIAL, name)); + } + + protected Request getInfoRequest() { + return new Request(db, RequestType.GET, executor.createPath(ArangoDBConstants.PATH_API_GHARIAL, name)); + } + + protected ResponseDeserializer getInfoResponseDeserializer() { + return addVertexCollectionResponseDeserializer(); + } + + protected Request getVertexCollectionsRequest() { + return new Request(db, RequestType.GET, + executor.createPath(ArangoDBConstants.PATH_API_GHARIAL, name, ArangoDBConstants.VERTEX)); + } + + protected ResponseDeserializer> getVertexCollectionsResponseDeserializer() { + return new ResponseDeserializer>() { + @Override + public Collection deserialize(final Response response) throws VPackException { + return executor.deserialize(response.getBody().get(ArangoDBConstants.COLLECTIONS), + new Type>() { + }.getType()); + } + }; + } + + protected Request addVertexCollectionRequest(final String name) { + final Request request = new Request(db, RequestType.POST, + executor.createPath(ArangoDBConstants.PATH_API_GHARIAL, name(), ArangoDBConstants.VERTEX)); + request.setBody(executor.serialize(OptionsBuilder.build(new VertexCollectionCreateOptions(), name))); + return request; + } + + protected ResponseDeserializer addVertexCollectionResponseDeserializer() { + return addEdgeDefinitionResponseDeserializer(); + } + + protected Request getEdgeDefinitionsRequest() { + return new Request(db, RequestType.GET, + executor.createPath(ArangoDBConstants.PATH_API_GHARIAL, name, ArangoDBConstants.EDGE)); + } + + protected ResponseDeserializer> getEdgeDefinitionsDeserializer() { + return new ResponseDeserializer>() { + @Override + public Collection deserialize(final Response response) throws VPackException { + return executor.deserialize(response.getBody().get(ArangoDBConstants.COLLECTIONS), + new Type>() { + }.getType()); + } + }; + } + + protected Request addEdgeDefinitionRequest(final EdgeDefinition definition) { + final Request request = new Request(db, RequestType.POST, + executor.createPath(ArangoDBConstants.PATH_API_GHARIAL, name, ArangoDBConstants.EDGE)); + request.setBody(executor.serialize(definition)); + return request; + } + + protected ResponseDeserializer addEdgeDefinitionResponseDeserializer() { + return new ResponseDeserializer() { + @Override + public GraphEntity deserialize(final Response response) throws VPackException { + return executor.deserialize(response.getBody().get(ArangoDBConstants.GRAPH), GraphEntity.class); + } + }; + } + + protected Request replaceEdgeDefinitionRequest(final EdgeDefinition definition) { + final Request request = new Request(db, RequestType.PUT, executor.createPath(ArangoDBConstants.PATH_API_GHARIAL, + name, ArangoDBConstants.EDGE, definition.getCollection())); + request.setBody(executor.serialize(definition)); + return request; + } + + protected ResponseDeserializer replaceEdgeDefinitionResponseDeserializer() { + return new ResponseDeserializer() { + @Override + public GraphEntity deserialize(final Response response) throws VPackException { + return executor.deserialize(response.getBody().get(ArangoDBConstants.GRAPH), GraphEntity.class); + } + }; + } + + protected Request removeEdgeDefinitionRequest(final String definitionName) { + return new Request(db, RequestType.DELETE, + executor.createPath(ArangoDBConstants.PATH_API_GHARIAL, name, ArangoDBConstants.EDGE, definitionName)); + } + + protected ResponseDeserializer removeEdgeDefinitionResponseDeserializer() { + return new ResponseDeserializer() { + @Override + public GraphEntity deserialize(final Response response) throws VPackException { + return executor.deserialize(response.getBody().get(ArangoDBConstants.GRAPH), GraphEntity.class); + } + }; + } + +} diff --git a/src/main/java/com/arangodb/internal/InternalArangoVertexCollection.java b/src/main/java/com/arangodb/internal/InternalArangoVertexCollection.java new file mode 100644 index 000000000..455ac3919 --- /dev/null +++ b/src/main/java/com/arangodb/internal/InternalArangoVertexCollection.java @@ -0,0 +1,172 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.internal; + +import java.util.HashMap; +import java.util.Map; + +import com.arangodb.entity.DocumentField; +import com.arangodb.entity.VertexEntity; +import com.arangodb.entity.VertexUpdateEntity; +import com.arangodb.internal.ArangoExecutor.ResponseDeserializer; +import com.arangodb.internal.velocystream.Connection; +import com.arangodb.model.DocumentReadOptions; +import com.arangodb.model.VertexCreateOptions; +import com.arangodb.model.VertexDeleteOptions; +import com.arangodb.model.VertexReplaceOptions; +import com.arangodb.model.VertexUpdateOptions; +import com.arangodb.velocypack.VPackSlice; +import com.arangodb.velocypack.exception.VPackException; +import com.arangodb.velocystream.Request; +import com.arangodb.velocystream.RequestType; +import com.arangodb.velocystream.Response; + +/** + * @author Mark - mark at arangodb.com + * + */ +public class InternalArangoVertexCollection, R, C extends Connection> + extends ArangoExecuteable { + + private final String db; + private final String graph; + private final String name; + + public InternalArangoVertexCollection(final E executor, final String db, final String graph, final String name) { + super(executor); + this.db = db; + this.graph = graph; + this.name = name; + } + + public String name() { + return name; + } + + protected String createDocumentHandle(final String key) { + executor.validateDocumentKey(key); + return executor.createPath(name, key); + } + + protected Request dropRequest() { + return new Request(db, RequestType.DELETE, + executor.createPath(ArangoDBConstants.PATH_API_GHARIAL, graph, ArangoDBConstants.VERTEX, name)); + } + + protected Request insertVertexRequest(final T value, final VertexCreateOptions options) { + final Request request = new Request(db, RequestType.POST, + executor.createPath(ArangoDBConstants.PATH_API_GHARIAL, graph, ArangoDBConstants.VERTEX, name)); + final VertexCreateOptions params = (options != null ? options : new VertexCreateOptions()); + request.putQueryParam(ArangoDBConstants.WAIT_FOR_SYNC, params.getWaitForSync()); + request.setBody(executor.serialize(value)); + return request; + } + + protected ResponseDeserializer insertVertexResponseDeserializer(final T value) { + return new ResponseDeserializer() { + @Override + public VertexEntity deserialize(final Response response) throws VPackException { + final VPackSlice body = response.getBody().get(ArangoDBConstants.VERTEX); + final VertexEntity doc = executor.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 DocumentReadOptions options) { + final Request request = new Request(db, RequestType.GET, executor.createPath(ArangoDBConstants.PATH_API_GHARIAL, + graph, ArangoDBConstants.VERTEX, createDocumentHandle(key))); + final DocumentReadOptions params = (options != null ? options : new DocumentReadOptions()); + request.putHeaderParam(ArangoDBConstants.IF_NONE_MATCH, params.getIfNoneMatch()); + request.putHeaderParam(ArangoDBConstants.IF_MATCH, params.getIfMatch()); + return request; + } + + protected ResponseDeserializer getVertexResponseDeserializer(final Class type) { + return new ResponseDeserializer() { + @Override + public T deserialize(final Response response) throws VPackException { + return executor.deserialize(response.getBody().get(ArangoDBConstants.VERTEX), type); + } + }; + } + + protected Request replaceVertexRequest(final String key, final T value, final VertexReplaceOptions options) { + final Request request = new Request(db, RequestType.PUT, executor.createPath(ArangoDBConstants.PATH_API_GHARIAL, + graph, ArangoDBConstants.VERTEX, createDocumentHandle(key))); + final VertexReplaceOptions params = (options != null ? options : new VertexReplaceOptions()); + request.putQueryParam(ArangoDBConstants.WAIT_FOR_SYNC, params.getWaitForSync()); + request.putHeaderParam(ArangoDBConstants.IF_MATCH, params.getIfMatch()); + request.setBody(executor.serialize(value)); + return request; + } + + protected ResponseDeserializer replaceVertexResponseDeserializer(final T value) { + return new ResponseDeserializer() { + @Override + public VertexUpdateEntity deserialize(final Response response) throws VPackException { + final VPackSlice body = response.getBody().get(ArangoDBConstants.VERTEX); + final VertexUpdateEntity doc = executor.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 = new Request(db, RequestType.PATCH, executor.createPath(ArangoDBConstants.PATH_API_GHARIAL, graph, + ArangoDBConstants.VERTEX, createDocumentHandle(key))); + final VertexUpdateOptions params = (options != null ? options : new VertexUpdateOptions()); + request.putQueryParam(ArangoDBConstants.KEEP_NULL, params.getKeepNull()); + request.putQueryParam(ArangoDBConstants.WAIT_FOR_SYNC, params.getWaitForSync()); + request.putHeaderParam(ArangoDBConstants.IF_MATCH, params.getIfMatch()); + request.setBody(executor.serialize(value, true)); + return request; + } + + protected ResponseDeserializer updateVertexResponseDeserializer(final T value) { + return new ResponseDeserializer() { + @Override + public VertexUpdateEntity deserialize(final Response response) throws VPackException { + final VPackSlice body = response.getBody().get(ArangoDBConstants.VERTEX); + return executor.deserialize(body, VertexUpdateEntity.class); + } + }; + } + + protected Request deleteVertexRequest(final String key, final VertexDeleteOptions options) { + final Request request = new Request(db, RequestType.DELETE, executor.createPath( + ArangoDBConstants.PATH_API_GHARIAL, graph, ArangoDBConstants.VERTEX, createDocumentHandle(key))); + final VertexDeleteOptions params = (options != null ? options : new VertexDeleteOptions()); + request.putQueryParam(ArangoDBConstants.WAIT_FOR_SYNC, params.getWaitForSync()); + request.putHeaderParam(ArangoDBConstants.IF_MATCH, params.getIfMatch()); + return request; + } + +} diff --git a/src/main/java/com/arangodb/internal/velocypack/VPackConfigure.java b/src/main/java/com/arangodb/internal/velocypack/VPackConfigure.java new file mode 100644 index 000000000..be885c5dd --- /dev/null +++ b/src/main/java/com/arangodb/internal/velocypack/VPackConfigure.java @@ -0,0 +1,134 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.internal.velocypack; + +import java.lang.reflect.Field; +import java.util.Date; + +import org.json.simple.JSONValue; + +import com.arangodb.entity.BaseDocument; +import com.arangodb.entity.BaseEdgeDocument; +import com.arangodb.entity.CollectionStatus; +import com.arangodb.entity.CollectionType; +import com.arangodb.entity.DocumentField; +import com.arangodb.entity.LogLevel; +import com.arangodb.entity.QueryEntity; +import com.arangodb.internal.CollectionCache; +import com.arangodb.internal.velocystream.AuthenticationRequest; +import com.arangodb.model.TraversalOptions; +import com.arangodb.velocypack.VPack; +import com.arangodb.velocypack.VPackDeserializationContext; +import com.arangodb.velocypack.VPackDeserializer; +import com.arangodb.velocypack.VPackFieldNamingStrategy; +import com.arangodb.velocypack.VPackJsonDeserializer; +import com.arangodb.velocypack.VPackParser; +import com.arangodb.velocypack.VPackSlice; +import com.arangodb.velocypack.ValueType; +import com.arangodb.velocypack.exception.VPackException; +import com.arangodb.velocypack.internal.util.NumberUtil; +import com.arangodb.velocystream.Request; +import com.arangodb.velocystream.Response; + +/** + * @author Mark - mark at arangodb.com + * + */ +public class VPackConfigure { + + private static final String ID = "_id"; + + public static void configure( + final VPack.Builder builder, + final VPackParser vpackParser, + final CollectionCache cache) { + + builder.fieldNamingStrategy(new VPackFieldNamingStrategy() { + @Override + public String translateName(final Field field) { + final DocumentField annotation = field.getAnnotation(DocumentField.class); + if (annotation != null) { + return annotation.value().getSerializeName(); + } + return field.getName(); + } + }); + builder.registerDeserializer(ID, String.class, new VPackDeserializer() { + @Override + public String deserialize( + final VPackSlice parent, + final VPackSlice vpack, + final VPackDeserializationContext context) throws VPackException { + final String id; + if (vpack.isCustom()) { + final long idLong = NumberUtil.toLong(vpack.getBuffer(), vpack.getStart() + 1, + vpack.getByteSize() - 1); + final String collectionName = cache.getCollectionName(idLong); + if (collectionName != null) { + final VPackSlice key = parent.get("_key"); + id = String.format("%s/%s", collectionName, key.getAsString()); + } else { + id = null; + } + } else { + id = vpack.getAsString(); + } + return id; + } + }); + vpackParser.registerDeserializer(ID, ValueType.CUSTOM, new VPackJsonDeserializer() { + @Override + public void deserialize( + final VPackSlice parent, + final String attribute, + final VPackSlice vpack, + final StringBuilder json) throws VPackException { + final String id; + final long idLong = NumberUtil.toLong(vpack.getBuffer(), vpack.getStart() + 1, vpack.getByteSize() - 1); + final String collectionName = cache.getCollectionName(idLong); + if (collectionName != null) { + final VPackSlice key = parent.get("_key"); + id = String.format("%s/%s", collectionName, key.getAsString()); + } else { + id = null; + } + json.append(JSONValue.toJSONString(id)); + } + }); + + builder.registerSerializer(Request.class, VPackSerializers.REQUEST); + builder.registerSerializer(AuthenticationRequest.class, VPackSerializers.AUTH_REQUEST); + builder.registerSerializer(CollectionType.class, VPackSerializers.COLLECTION_TYPE); + builder.registerSerializer(BaseDocument.class, VPackSerializers.BASE_DOCUMENT); + builder.registerSerializer(BaseEdgeDocument.class, VPackSerializers.BASE_EDGE_DOCUMENT); + builder.registerSerializer(TraversalOptions.Order.class, VPackSerializers.TRAVERSAL_ORDER); + builder.registerSerializer(LogLevel.class, VPackSerializers.LOG_LEVEL); + + builder.registerDeserializer(Response.class, VPackDeserializers.RESPONSE); + builder.registerDeserializer(CollectionType.class, VPackDeserializers.COLLECTION_TYPE); + builder.registerDeserializer(CollectionStatus.class, VPackDeserializers.COLLECTION_STATUS); + builder.registerDeserializer(BaseDocument.class, VPackDeserializers.BASE_DOCUMENT); + builder.registerDeserializer(BaseEdgeDocument.class, VPackDeserializers.BASE_EDGE_DOCUMENT); + builder.registerDeserializer(QueryEntity.PROPERTY_STARTED, Date.class, VPackDeserializers.DATE_STRING); + builder.registerDeserializer(LogLevel.class, VPackDeserializers.LOG_LEVEL); + } + +} diff --git a/src/main/java/com/arangodb/internal/velocypack/VPackDeserializers.java b/src/main/java/com/arangodb/internal/velocypack/VPackDeserializers.java new file mode 100644 index 000000000..4d2c6ab0a --- /dev/null +++ b/src/main/java/com/arangodb/internal/velocypack/VPackDeserializers.java @@ -0,0 +1,133 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.internal.velocypack; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.Map; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.arangodb.entity.BaseDocument; +import com.arangodb.entity.BaseEdgeDocument; +import com.arangodb.entity.CollectionStatus; +import com.arangodb.entity.CollectionType; +import com.arangodb.entity.LogLevel; +import com.arangodb.velocypack.VPackDeserializationContext; +import com.arangodb.velocypack.VPackDeserializer; +import com.arangodb.velocypack.VPackSlice; +import com.arangodb.velocypack.exception.VPackException; +import com.arangodb.velocystream.Response; + +/** + * @author Mark - mark at arangodb.com + * + */ +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 = new VPackDeserializer() { + @Override + public Response deserialize( + final VPackSlice parent, + final VPackSlice vpack, + final VPackDeserializationContext context) throws VPackException { + final Response response = new Response(); + response.setVersion(vpack.get(0).getAsInt()); + response.setType(vpack.get(1).getAsInt()); + response.setResponseCode(vpack.get(2).getAsInt()); + return response; + } + }; + + public static final VPackDeserializer COLLECTION_TYPE = new VPackDeserializer() { + @Override + public CollectionType deserialize( + final VPackSlice parent, + final VPackSlice vpack, + final VPackDeserializationContext context) throws VPackException { + return CollectionType.fromType(vpack.getAsInt()); + } + }; + + public static final VPackDeserializer COLLECTION_STATUS = new VPackDeserializer() { + @Override + public CollectionStatus deserialize( + final VPackSlice parent, + final VPackSlice vpack, + final VPackDeserializationContext context) throws VPackException { + return CollectionStatus.fromStatus(vpack.getAsInt()); + } + }; + + @SuppressWarnings("unchecked") + public static final VPackDeserializer BASE_DOCUMENT = new VPackDeserializer() { + @Override + public BaseDocument deserialize( + final VPackSlice parent, + final VPackSlice vpack, + final VPackDeserializationContext context) throws VPackException { + return new BaseDocument(context.deserialize(vpack, Map.class)); + } + }; + + @SuppressWarnings("unchecked") + public static final VPackDeserializer BASE_EDGE_DOCUMENT = new VPackDeserializer() { + @Override + public BaseEdgeDocument deserialize( + final VPackSlice parent, + final VPackSlice vpack, + final VPackDeserializationContext context) throws VPackException { + return new BaseEdgeDocument(context.deserialize(vpack, Map.class)); + } + }; + + public static final VPackDeserializer DATE_STRING = new VPackDeserializer() { + @Override + public Date deserialize( + final VPackSlice parent, + final VPackSlice vpack, + final VPackDeserializationContext context) throws VPackException { + 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 = new VPackDeserializer() { + @Override + public LogLevel deserialize( + final VPackSlice parent, + final VPackSlice vpack, + final VPackDeserializationContext context) throws VPackException { + return LogLevel.fromLevel(vpack.getAsInt()); + } + }; +} diff --git a/src/main/java/com/arangodb/internal/velocypack/VPackSerializers.java b/src/main/java/com/arangodb/internal/velocypack/VPackSerializers.java new file mode 100644 index 000000000..d5040e5d9 --- /dev/null +++ b/src/main/java/com/arangodb/internal/velocypack/VPackSerializers.java @@ -0,0 +1,162 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.internal.velocypack; + +import java.util.HashMap; +import java.util.Map; +import java.util.Map.Entry; + +import com.arangodb.entity.BaseDocument; +import com.arangodb.entity.BaseEdgeDocument; +import com.arangodb.entity.CollectionType; +import com.arangodb.entity.DocumentField; +import com.arangodb.entity.LogLevel; +import com.arangodb.internal.velocystream.AuthenticationRequest; +import com.arangodb.model.TraversalOptions; +import com.arangodb.model.TraversalOptions.Order; +import com.arangodb.velocypack.VPackBuilder; +import com.arangodb.velocypack.VPackSerializationContext; +import com.arangodb.velocypack.VPackSerializer; +import com.arangodb.velocypack.ValueType; +import com.arangodb.velocypack.exception.VPackException; +import com.arangodb.velocystream.Request; + +/** + * @author Mark - mark at arangodb.com + * + */ +public class VPackSerializers { + + public static final VPackSerializer REQUEST = new VPackSerializer() { + @Override + public void serialize( + final VPackBuilder builder, + final String attribute, + final Request value, + final VPackSerializationContext context) throws VPackException { + builder.add(attribute, ValueType.ARRAY); + builder.add(value.getVersion()); + builder.add(value.getType()); + builder.add(value.getDatabase()); + builder.add(value.getRequestType().getType()); + builder.add(value.getRequest()); + builder.add(ValueType.OBJECT); + for (final Entry entry : value.getQueryParam().entrySet()) { + builder.add(entry.getKey(), entry.getValue()); + } + builder.close(); + builder.add(ValueType.OBJECT); + for (final Entry entry : value.getHeaderParam().entrySet()) { + builder.add(entry.getKey(), entry.getValue()); + } + builder.close(); + builder.close(); + } + }; + + public static final VPackSerializer AUTH_REQUEST = new VPackSerializer() { + @Override + public void serialize( + final VPackBuilder builder, + final String attribute, + final AuthenticationRequest value, + final VPackSerializationContext context) throws VPackException { + builder.add(attribute, ValueType.ARRAY); + builder.add(value.getVersion()); + builder.add(value.getType()); + builder.add(value.getEncryption()); + builder.add(value.getUser()); + builder.add(value.getPassword()); + builder.close(); + } + }; + + public static final VPackSerializer COLLECTION_TYPE = new VPackSerializer() { + @Override + public void serialize( + final VPackBuilder builder, + final String attribute, + final CollectionType value, + final VPackSerializationContext context) throws VPackException { + builder.add(attribute, value.getType()); + } + }; + + public static final VPackSerializer BASE_DOCUMENT = new VPackSerializer() { + @Override + public void serialize( + final VPackBuilder builder, + final String attribute, + final BaseDocument value, + final VPackSerializationContext context) throws VPackException { + final Map doc = new HashMap(); + doc.putAll(value.getProperties()); + doc.put(DocumentField.Type.ID.getSerializeName(), value.getId()); + doc.put(DocumentField.Type.KEY.getSerializeName(), value.getKey()); + doc.put(DocumentField.Type.REV.getSerializeName(), value.getRevision()); + context.serialize(builder, attribute, doc); + } + }; + + public static final VPackSerializer BASE_EDGE_DOCUMENT = new VPackSerializer() { + @Override + public void serialize( + final VPackBuilder builder, + final String attribute, + final BaseEdgeDocument value, + final VPackSerializationContext context) throws VPackException { + final Map doc = new HashMap(); + doc.putAll(value.getProperties()); + doc.put(DocumentField.Type.ID.getSerializeName(), value.getId()); + doc.put(DocumentField.Type.KEY.getSerializeName(), value.getKey()); + doc.put(DocumentField.Type.REV.getSerializeName(), value.getRevision()); + doc.put(DocumentField.Type.FROM.getSerializeName(), value.getFrom()); + doc.put(DocumentField.Type.TO.getSerializeName(), value.getTo()); + context.serialize(builder, attribute, doc); + } + }; + + public static final VPackSerializer TRAVERSAL_ORDER = new VPackSerializer() { + @Override + public void serialize( + final VPackBuilder builder, + final String attribute, + final Order value, + final VPackSerializationContext context) throws VPackException { + if (TraversalOptions.Order.preorder_expander == value) { + builder.add(attribute, "preorder-expander"); + } else { + builder.add(attribute, value.name()); + } + } + }; + + public static final VPackSerializer LOG_LEVEL = new VPackSerializer() { + @Override + public void serialize( + final VPackBuilder builder, + final String attribute, + final LogLevel value, + final VPackSerializationContext context) throws VPackException { + builder.add(attribute, value.getLevel()); + } + }; +} diff --git a/src/main/java/com/arangodb/internal/velocystream/AuthenticationRequest.java b/src/main/java/com/arangodb/internal/velocystream/AuthenticationRequest.java new file mode 100644 index 000000000..7b4436579 --- /dev/null +++ b/src/main/java/com/arangodb/internal/velocystream/AuthenticationRequest.java @@ -0,0 +1,55 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.internal.velocystream; + +import com.arangodb.velocystream.Request; + +/** + * @author Mark - mark at arangodb.com + * + */ +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; + } + +} diff --git a/src/main/java/com/arangodb/internal/velocystream/Chunk.java b/src/main/java/com/arangodb/internal/velocystream/Chunk.java new file mode 100644 index 000000000..bf0726c9e --- /dev/null +++ b/src/main/java/com/arangodb/internal/velocystream/Chunk.java @@ -0,0 +1,89 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.internal.velocystream; + +/** + * @author Mark - mark at arangodb.com + * + */ +public class Chunk { + + 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 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; + } + + public long getMessageId() { + return messageId; + } + + public long getMessageLength() { + return messageLength; + } + + public boolean isFirstChunk() { + return 1 == (chunkX & 0x1); + } + + public int getChunk() { + return chunkX >> 1; + } + + public int getChunkX() { + return chunkX; + } + + public int getContentOffset() { + return contentOffset; + } + + public int getContentLength() { + return contentLength; + } + +} diff --git a/src/main/java/com/arangodb/internal/velocystream/Communication.java b/src/main/java/com/arangodb/internal/velocystream/Communication.java new file mode 100644 index 000000000..f47530807 --- /dev/null +++ b/src/main/java/com/arangodb/internal/velocystream/Communication.java @@ -0,0 +1,157 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.internal.velocystream; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.concurrent.atomic.AtomicLong; + +import javax.net.ssl.SSLContext; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.arangodb.ArangoDBException; +import com.arangodb.entity.ErrorEntity; +import com.arangodb.internal.ArangoDBConstants; +import com.arangodb.internal.CollectionCache; +import com.arangodb.velocypack.VPack; +import com.arangodb.velocypack.VPackSlice; +import com.arangodb.velocypack.exception.VPackParserException; +import com.arangodb.velocystream.Request; +import com.arangodb.velocystream.Response; + +/** + * @author Mark - mark at arangodb.com + * + */ +public abstract class Communication { + + private static final int ERROR_STATUS = 300; + + private static final Logger LOGGER = LoggerFactory.getLogger(Communication.class); + + protected static final AtomicLong mId = new AtomicLong(0L); + protected final VPack vpack; + protected final C connection; + protected final CollectionCache collectionCache; + + protected final String user; + protected final String password; + + protected final Integer chunksize; + + protected Communication(final String host, final Integer port, final Integer timeout, final String user, + final String password, final Boolean useSsl, final SSLContext sslContext, final VPack vpack, + final CollectionCache collectionCache, final Integer chunksize, final C connection) { + this.user = user; + this.password = password; + this.vpack = vpack; + this.collectionCache = collectionCache; + this.connection = connection; + this.chunksize = chunksize != null ? chunksize : ArangoDBConstants.CHUNK_DEFAULT_CONTENT_SIZE; + } + + protected void connect(final Connection connection) { + if (!connection.isOpen()) { + try { + connection.open(); + if (user != null) { + authenticate(); + } + } catch (final IOException e) { + LOGGER.error(e.getMessage(), e); + throw new ArangoDBException(e); + } + } + } + + protected abstract void authenticate(); + + public void disconnect() { + disconnect(connection); + } + + public void disconnect(final Connection connection) { + connection.close(); + } + + public abstract R execute(final Request request) throws ArangoDBException; + + protected void checkError(final Response response) throws ArangoDBException { + try { + if (response.getResponseCode() >= ERROR_STATUS) { + if (response.getBody() != null) { + throw new ArangoDBException(createErrorMessage(response)); + } else { + throw new ArangoDBException(String.format("Response Code: %s", response.getResponseCode())); + } + } + } catch (final VPackParserException e) { + throw new ArangoDBException(e); + } + } + + private String createErrorMessage(final Response response) throws VPackParserException { + String errorMessage; + final ErrorEntity errorEntity = vpack.deserialize(response.getBody(), ErrorEntity.class); + errorMessage = String.format("Response: %s, Error: %s - %s", errorEntity.getCode(), errorEntity.getErrorNum(), + errorEntity.getErrorMessage()); + return errorMessage; + } + + protected Response createResponse(final Message messsage) throws VPackParserException { + final Response response = vpack.deserialize(messsage.getHead(), Response.class); + if (messsage.getBody() != null) { + response.setBody(messsage.getBody()); + } + return response; + } + + protected Message createMessage(final Request request) throws VPackParserException { + final long id = mId.incrementAndGet(); + return new Message(id, vpack.serialize(request), request.getBody()); + } + + protected Collection buildChunks(final Message message) throws IOException { + 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; + } + +} diff --git a/src/main/java/com/arangodb/internal/velocystream/CommunicationSync.java b/src/main/java/com/arangodb/internal/velocystream/CommunicationSync.java new file mode 100644 index 000000000..33be5da99 --- /dev/null +++ b/src/main/java/com/arangodb/internal/velocystream/CommunicationSync.java @@ -0,0 +1,147 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.internal.velocystream; + +import java.io.IOException; + +import javax.net.ssl.SSLContext; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.arangodb.ArangoDBException; +import com.arangodb.internal.ArangoDBConstants; +import com.arangodb.internal.CollectionCache; +import com.arangodb.velocypack.VPack; +import com.arangodb.velocypack.exception.VPackParserException; +import com.arangodb.velocystream.Request; +import com.arangodb.velocystream.Response; + +/** + * @author Mark - mark at arangodb.com + * + */ +public class CommunicationSync extends Communication { + + private static final Logger LOGGER = LoggerFactory.getLogger(CommunicationSync.class); + + public static class Builder { + private String host; + private Integer port; + private Integer timeout; + private String user; + private String password; + private Boolean useSsl; + private SSLContext sslContext; + private Integer chunksize; + + public Builder() { + super(); + } + + public Builder host(final String host) { + this.host = host; + return this; + } + + public Builder port(final Integer port) { + this.port = port; + return this; + } + + 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 Communication build(final VPack vpack, final CollectionCache collectionCache) { + return new CommunicationSync(host, port, timeout, user, password, useSsl, sslContext, vpack, + collectionCache, chunksize); + } + } + + protected CommunicationSync(final String host, final Integer port, final Integer timeout, final String user, + final String password, final Boolean useSsl, final SSLContext sslContext, final VPack vpack, + final CollectionCache collectionCache, final Integer chunksize) { + super(host, port, timeout, user, password, useSsl, sslContext, vpack, collectionCache, chunksize, + new ConnectionSync.Builder().host(host).port(port).timeout(timeout).useSsl(useSsl) + .sslContext(sslContext).build()); + } + + @Override + public Response execute(final Request request) throws ArangoDBException { + connect(connection); + try { + final Message requestMessage = createMessage(request); + final Message responseMessage = send(requestMessage); + collectionCache.setDb(request.getDatabase()); + final Response response = createResponse(responseMessage); + checkError(response); + return response; + } catch (final VPackParserException e) { + throw new ArangoDBException(e); + } catch (final IOException e) { + throw new ArangoDBException(e); + } + + } + + private Message send(final Message message) throws IOException { + 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 Response response = execute( + new AuthenticationRequest(user, password != null ? password : "", ArangoDBConstants.ENCRYPTION_PLAIN)); + checkError(response); + } + +} diff --git a/src/main/java/com/arangodb/internal/velocystream/Connection.java b/src/main/java/com/arangodb/internal/velocystream/Connection.java new file mode 100644 index 000000000..7629de4f6 --- /dev/null +++ b/src/main/java/com/arangodb/internal/velocystream/Connection.java @@ -0,0 +1,209 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.internal.velocystream; + +import java.io.BufferedOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.InetSocketAddress; +import java.net.Socket; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.util.Collection; + +import javax.net.SocketFactory; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLSocket; +import javax.net.ssl.SSLSocketFactory; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.arangodb.ArangoDBException; +import com.arangodb.internal.ArangoDBConstants; +import com.arangodb.velocypack.VPackSlice; + +/** + * @author Mark - mark at arangodb.com + * + */ +public abstract class Connection { + + private static final Logger LOGGER = LoggerFactory.getLogger(Connection.class); + + private final String host; + private final Integer port; + private final Integer timeout; + private final Boolean useSsl; + private final SSLContext sslContext; + + private Socket socket; + private OutputStream outputStream; + private InputStream inputStream; + + protected Connection(final String host, final Integer port, final Integer timeout, final Boolean useSsl, + final SSLContext sslContext) { + super(); + this.host = host; + this.port = port; + this.timeout = timeout; + this.useSsl = useSsl; + this.sslContext = sslContext; + } + + public synchronized boolean isOpen() { + return socket != null && socket.isConnected() && !socket.isClosed(); + } + + public synchronized void open() throws IOException { + if (isOpen()) { + return; + } + if (useSsl != null && useSsl) { + if (sslContext != null) { + socket = sslContext.getSocketFactory().createSocket(); + } else { + socket = SSLSocketFactory.getDefault().createSocket(); + } + } else { + socket = SocketFactory.getDefault().createSocket(); + } + final String host = this.host != null ? this.host : ArangoDBConstants.DEFAULT_HOST; + final Integer port = this.port != null ? this.port : ArangoDBConstants.DEFAULT_PORT; + if (LOGGER.isDebugEnabled()) { + LOGGER.debug(String.format("Open connection to addr=%s,port=%s", host, port)); + } + socket.connect(new InetSocketAddress(host, port), + timeout != null ? timeout : ArangoDBConstants.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 (useSsl != null && useSsl) { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug(String.format("Start Handshake on %s", socket)); + } + ((SSLSocket) socket).startHandshake(); + } + } + + public synchronized void close() { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug(String.format("Close connection %s", socket)); + } + if (socket != null) { + try { + socket.close(); + } catch (final IOException e) { + throw new ArangoDBException(e); + } + } + } + + protected synchronized void writeIntern(final Message message, final Collection chunks) { + 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())); + } + 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) { + throw new RuntimeException(e); + } + } + } + + private void writeChunkHead(final Chunk chunk) throws IOException { + final long messageLength = chunk.getMessageLength(); + final int headLength = messageLength > -1L ? ArangoDBConstants.CHUNK_MAX_HEADER_SIZE + : ArangoDBConstants.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(ArangoDBConstants.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(ArangoDBConstants.LONG_BYTES).getLong(); + contentLength = length - ArangoDBConstants.CHUNK_MAX_HEADER_SIZE; + } else { + messageLength = -1L; + contentLength = length - ArangoDBConstants.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())); + } + 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; + } + } + } + +} diff --git a/src/main/java/com/arangodb/internal/velocystream/ConnectionSync.java b/src/main/java/com/arangodb/internal/velocystream/ConnectionSync.java new file mode 100644 index 000000000..90c4d9621 --- /dev/null +++ b/src/main/java/com/arangodb/internal/velocystream/ConnectionSync.java @@ -0,0 +1,122 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.internal.velocystream; + +import java.io.IOException; +import java.util.Collection; + +import javax.net.ssl.SSLContext; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.arangodb.ArangoDBException; + +/** + * @author Mark - mark at arangodb.com + * + */ +public class ConnectionSync extends Connection { + + private static final Logger LOGGER = LoggerFactory.getLogger(ConnectionSync.class); + + public static class Builder { + + private String host; + private Integer port; + private Integer timeout; + private Boolean useSsl; + private SSLContext sslContext; + + public Builder() { + super(); + } + + public Builder host(final String host) { + this.host = host; + return this; + } + + public Builder port(final Integer port) { + this.port = port; + 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 ConnectionSync build() { + return new ConnectionSync(host, port, timeout, useSsl, sslContext); + } + } + + private ConnectionSync(final String host, final Integer port, final Integer timeout, final Boolean useSsl, + final SSLContext sslContext) { + super(host, port, timeout, useSsl, sslContext); + } + + public synchronized Message write(final Message message, final Collection chunks) throws ArangoDBException { + super.writeIntern(message, chunks); + byte[] chunkBuffer = null; + int off = 0; + while (chunkBuffer == null || off < chunkBuffer.length) { + if (!isOpen()) { + close(); + throw new ArangoDBException(new IOException("The socket is closed.")); + } + try { + final Chunk chunk = readChunk(); + final int contentLength = chunk.getContentLength(); + if (chunkBuffer == null) { + if (!chunk.isFirstChunk()) { + throw new ArangoDBException("Wrong Chunk recieved! Expected first Chunk."); + } + final int length = (int) (chunk.getMessageLength() > 0 ? chunk.getMessageLength() : contentLength); + chunkBuffer = new byte[length]; + } + readBytesIntoBuffer(chunkBuffer, off, contentLength); + off += contentLength; + } catch (final Exception e) { + close(); + throw new ArangoDBException(e); + } + } + final Message responseMessage = new Message(message.getId(), chunkBuffer); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug(String.format("Received Message (id=%s, head=%s, body=%s)", responseMessage.getId(), + responseMessage.getHead(), responseMessage.getBody() != null ? responseMessage.getBody() : "{}")); + } + return responseMessage; + } + +} diff --git a/src/main/java/com/arangodb/internal/velocystream/Message.java b/src/main/java/com/arangodb/internal/velocystream/Message.java new file mode 100644 index 000000000..4e83f57e1 --- /dev/null +++ b/src/main/java/com/arangodb/internal/velocystream/Message.java @@ -0,0 +1,68 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.internal.velocystream; + +import java.nio.BufferUnderflowException; + +import com.arangodb.velocypack.VPackSlice; + +/** + * @author Mark - mark at arangodb.com + * + */ +public class Message { + + 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 VPackSlice head, final VPackSlice body) { + super(); + this.id = id; + this.head = head; + this.body = body; + } + + public long getId() { + return id; + } + + public VPackSlice getHead() { + return head; + } + + public VPackSlice getBody() { + return body; + } + +} diff --git a/src/main/java/com/arangodb/model/AqlFunctionCreateOptions.java b/src/main/java/com/arangodb/model/AqlFunctionCreateOptions.java new file mode 100644 index 000000000..dcec05237 --- /dev/null +++ b/src/main/java/com/arangodb/model/AqlFunctionCreateOptions.java @@ -0,0 +1,83 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.model; + +/** + * @author Mark - mark at arangodb.com + * + * @see API + * Documentation + */ +public class AqlFunctionCreateOptions { + + private String name; + private String code; + private Boolean isDeterministic; + + 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; + } + + 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; + } + + 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; + } + + 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 new file mode 100644 index 000000000..958fcc13d --- /dev/null +++ b/src/main/java/com/arangodb/model/AqlFunctionDeleteOptions.java @@ -0,0 +1,54 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.model; + +/** + * @author Mark - mark at arangodb.com + * + * @see API + * Documentation + */ +public class AqlFunctionDeleteOptions { + + private Boolean group; + + public AqlFunctionDeleteOptions() { + super(); + } + + 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; + } + +} diff --git a/src/main/java/com/arangodb/model/AqlFunctionGetOptions.java b/src/main/java/com/arangodb/model/AqlFunctionGetOptions.java new file mode 100644 index 000000000..ae8d94c85 --- /dev/null +++ b/src/main/java/com/arangodb/model/AqlFunctionGetOptions.java @@ -0,0 +1,52 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.model; + +/** + * @author Mark - mark at arangodb.com + * + * @see API + * Documentation + */ +public class AqlFunctionGetOptions { + + private String namespace; + + public AqlFunctionGetOptions() { + super(); + } + + 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; + } + +} diff --git a/src/main/java/com/arangodb/model/AqlQueryExplainOptions.java b/src/main/java/com/arangodb/model/AqlQueryExplainOptions.java new file mode 100644 index 000000000..518fd2d20 --- /dev/null +++ b/src/main/java/com/arangodb/model/AqlQueryExplainOptions.java @@ -0,0 +1,137 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.model; + +import java.util.Collection; +import java.util.Map; + +/** + * @author Mark - mark at arangodb.com + * + * @see API Documentation + */ +public class AqlQueryExplainOptions { + + private Map bindVars; + private String query; + private Options options; + + public AqlQueryExplainOptions() { + super(); + } + + protected Map getBindVars() { + return bindVars; + } + + /** + * @param bindVars + * key/value pairs representing the bind parameters + * @return options + */ + protected AqlQueryExplainOptions bindVars(final Map 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 new file mode 100644 index 000000000..7d87d09ea --- /dev/null +++ b/src/main/java/com/arangodb/model/AqlQueryOptions.java @@ -0,0 +1,238 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.model; + +import java.util.Collection; +import java.util.Map; + +/** + * @author Mark - mark at arangodb.com + * + * @see API + * Documentation + */ +public class AqlQueryOptions { + + private Boolean count; + private Integer ttl; + private Integer batchSize; + private Boolean cache; + private Map bindVars; + private String query; + private Options options; + + 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 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 Map getBindVars() { + return bindVars; + } + + /** + * @param bindVars + * key/value pairs representing the bind parameters + * @return options + */ + protected AqlQueryOptions bindVars(final Map 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; + } + + /** + * @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 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; + } + + private Options getOptions() { + if (options == null) { + options = new Options(); + } + return options; + } + + private static class Options { + private Boolean profile; + private Optimizer optimizer; + private Boolean fullCount; + private Integer maxPlans; + + 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/AqlQueryParseOptions.java b/src/main/java/com/arangodb/model/AqlQueryParseOptions.java new file mode 100644 index 000000000..9af3dbaa6 --- /dev/null +++ b/src/main/java/com/arangodb/model/AqlQueryParseOptions.java @@ -0,0 +1,50 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.model; + +/** + * @author Mark - mark at arangodb.com + * + * @see API Documentation + */ +public class AqlQueryParseOptions { + + private String query; + + public AqlQueryParseOptions() { + super(); + } + + 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; + } + +} diff --git a/src/main/java/com/arangodb/model/CollectionCreateOptions.java b/src/main/java/com/arangodb/model/CollectionCreateOptions.java new file mode 100644 index 000000000..aa138b679 --- /dev/null +++ b/src/main/java/com/arangodb/model/CollectionCreateOptions.java @@ -0,0 +1,239 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.model; + +import com.arangodb.entity.CollectionType; +import com.arangodb.entity.KeyOptions; +import com.arangodb.entity.KeyType; + +/** + * @author Mark - mark at arangodb.com + * + * @see API + * Documentation + */ +public class CollectionCreateOptions { + + private String name; + private Long journalSize; + 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; + + public CollectionCreateOptions() { + super(); + } + + 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 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; + } + + public Integer getNumberOfShards() { + return numberOfShards; + } + + /** + * @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 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; + } + +} diff --git a/src/main/java/com/arangodb/model/CollectionPropertiesOptions.java b/src/main/java/com/arangodb/model/CollectionPropertiesOptions.java new file mode 100644 index 000000000..54ef731e9 --- /dev/null +++ b/src/main/java/com/arangodb/model/CollectionPropertiesOptions.java @@ -0,0 +1,68 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.model; + +/** + * @author Mark - mark at arangodb.com + * + * @see API + * Documentation + */ +public class CollectionPropertiesOptions { + + private Boolean waitForSync; + private Long journalSize; + + public CollectionPropertiesOptions() { + super(); + } + + 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; + } + + 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; + } + +} diff --git a/src/main/java/com/arangodb/model/CollectionRenameOptions.java b/src/main/java/com/arangodb/model/CollectionRenameOptions.java new file mode 100644 index 000000000..a1496f338 --- /dev/null +++ b/src/main/java/com/arangodb/model/CollectionRenameOptions.java @@ -0,0 +1,49 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.model; + +/** + * @author Mark - mark at arangodb.com + * + */ +public class CollectionRenameOptions { + + private String name; + + public CollectionRenameOptions() { + super(); + } + + public String getName() { + return name; + } + + /** + * @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/CollectionsReadOptions.java b/src/main/java/com/arangodb/model/CollectionsReadOptions.java new file mode 100644 index 000000000..c4cc3cf74 --- /dev/null +++ b/src/main/java/com/arangodb/model/CollectionsReadOptions.java @@ -0,0 +1,51 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.model; + +/** + * @author Mark - mark at arangodb.com + * + * @see API + * Documentation + */ +public class CollectionsReadOptions { + + private Boolean excludeSystem; + + public CollectionsReadOptions() { + super(); + } + + 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; + } + +} diff --git a/src/main/java/com/arangodb/model/DBCreateOptions.java b/src/main/java/com/arangodb/model/DBCreateOptions.java new file mode 100644 index 000000000..2f18ec0ae --- /dev/null +++ b/src/main/java/com/arangodb/model/DBCreateOptions.java @@ -0,0 +1,49 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.model; + +/** + * @author Mark - mark at arangodb.com + * + */ +public class DBCreateOptions { + + private String name; + + public DBCreateOptions() { + super(); + } + + public String getName() { + return name; + } + + /** + * @param name + * Has to contain a valid database name + * @return options + */ + protected DBCreateOptions name(final String name) { + this.name = name; + return this; + } + +} diff --git a/src/main/java/com/arangodb/model/DocumentCreateOptions.java b/src/main/java/com/arangodb/model/DocumentCreateOptions.java new file mode 100644 index 000000000..4467539ca --- /dev/null +++ b/src/main/java/com/arangodb/model/DocumentCreateOptions.java @@ -0,0 +1,66 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.model; + +/** + * @author Mark - mark at arangodb.com + * + * @see API + * Documentation + */ +public class DocumentCreateOptions { + + private Boolean waitForSync; + private Boolean returnNew; + + 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; + } + +} diff --git a/src/main/java/com/arangodb/model/DocumentDeleteOptions.java b/src/main/java/com/arangodb/model/DocumentDeleteOptions.java new file mode 100644 index 000000000..a5b745408 --- /dev/null +++ b/src/main/java/com/arangodb/model/DocumentDeleteOptions.java @@ -0,0 +1,82 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.model; + +/** + * @author Mark - mark at arangodb.com + * + * @see API + * Documentation + */ +public class DocumentDeleteOptions { + + private Boolean waitForSync; + private String ifMatch; + private Boolean returnOld; + + public DocumentDeleteOptions() { + super(); + } + + 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; + } + + 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; + } + + 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; + } + +} diff --git a/src/main/java/com/arangodb/model/DocumentExistsOptions.java b/src/main/java/com/arangodb/model/DocumentExistsOptions.java new file mode 100644 index 000000000..d44e9cc16 --- /dev/null +++ b/src/main/java/com/arangodb/model/DocumentExistsOptions.java @@ -0,0 +1,66 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.model; + +/** + * @author Mark - mark at arangodb.com + * + * @see API + * Documentation + */ +public class DocumentExistsOptions { + + private String ifNoneMatch; + private String ifMatch; + + public DocumentExistsOptions() { + super(); + } + + 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; + } + + 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; + } + +} diff --git a/src/main/java/com/arangodb/model/DocumentReadOptions.java b/src/main/java/com/arangodb/model/DocumentReadOptions.java new file mode 100644 index 000000000..4cd6ae259 --- /dev/null +++ b/src/main/java/com/arangodb/model/DocumentReadOptions.java @@ -0,0 +1,66 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.model; + +/** + * @author Mark - mark at arangodb.com + * + * @see API + * Documentation + */ +public class DocumentReadOptions { + + private String ifNoneMatch; + private String ifMatch; + + public DocumentReadOptions() { + super(); + } + + 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; + } + +} diff --git a/src/main/java/com/arangodb/model/DocumentReplaceOptions.java b/src/main/java/com/arangodb/model/DocumentReplaceOptions.java new file mode 100644 index 000000000..8c22bd1e4 --- /dev/null +++ b/src/main/java/com/arangodb/model/DocumentReplaceOptions.java @@ -0,0 +1,114 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.model; + +/** + * @author Mark - mark at arangodb.com + * + * @see API + * Documentation + */ +public class DocumentReplaceOptions { + + private Boolean waitForSync; + private Boolean ignoreRevs; + private String ifMatch; + private Boolean returnNew; + private Boolean returnOld; + + 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; + } + +} diff --git a/src/main/java/com/arangodb/model/DocumentUpdateOptions.java b/src/main/java/com/arangodb/model/DocumentUpdateOptions.java new file mode 100644 index 000000000..f82f57204 --- /dev/null +++ b/src/main/java/com/arangodb/model/DocumentUpdateOptions.java @@ -0,0 +1,149 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.model; + +/** + * @author Mark - mark at arangodb.com + * + * @see API + * Documentation + */ +public class DocumentUpdateOptions { + + private Boolean keepNull; + private Boolean mergeObjects; + private Boolean waitForSync; + private Boolean ignoreRevs; + private String ifMatch; + private Boolean returnNew; + private Boolean returnOld; + + 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; + } + +} diff --git a/src/main/java/com/arangodb/model/EdgeCreateOptions.java b/src/main/java/com/arangodb/model/EdgeCreateOptions.java new file mode 100644 index 000000000..625a60209 --- /dev/null +++ b/src/main/java/com/arangodb/model/EdgeCreateOptions.java @@ -0,0 +1,50 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.model; + +/** + * @author Mark - mark at arangodb.com + * + * @see API Documentation + */ +public class EdgeCreateOptions { + + private Boolean waitForSync; + + public EdgeCreateOptions() { + super(); + } + + public Boolean getWaitForSync() { + return waitForSync; + } + + /** + * @param waitForSync + * Wait until document has been synced to disk. + * @return options + */ + public EdgeCreateOptions waitForSync(final Boolean waitForSync) { + this.waitForSync = waitForSync; + return this; + } + +} diff --git a/src/main/java/com/arangodb/model/EdgeDeleteOptions.java b/src/main/java/com/arangodb/model/EdgeDeleteOptions.java new file mode 100644 index 000000000..9b40d5c56 --- /dev/null +++ b/src/main/java/com/arangodb/model/EdgeDeleteOptions.java @@ -0,0 +1,64 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.model; + +/** + * @author Mark - mark at arangodb.com + * + * @see API Documentation + */ +public class EdgeDeleteOptions { + + private Boolean waitForSync; + private String ifMatch; + + public EdgeDeleteOptions() { + super(); + } + + 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; + } + + 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; + } +} diff --git a/src/main/java/com/arangodb/model/EdgeReplaceOptions.java b/src/main/java/com/arangodb/model/EdgeReplaceOptions.java new file mode 100644 index 000000000..1d165e655 --- /dev/null +++ b/src/main/java/com/arangodb/model/EdgeReplaceOptions.java @@ -0,0 +1,64 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.model; + +/** + * @author Mark - mark at arangodb.com + * + * @see API Documentation + */ +public class EdgeReplaceOptions { + + private Boolean waitForSync; + private String ifMatch; + + public EdgeReplaceOptions() { + super(); + } + + 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; + } + + 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; + } +} diff --git a/src/main/java/com/arangodb/model/EdgeUpdateOptions.java b/src/main/java/com/arangodb/model/EdgeUpdateOptions.java new file mode 100644 index 000000000..c34128b94 --- /dev/null +++ b/src/main/java/com/arangodb/model/EdgeUpdateOptions.java @@ -0,0 +1,82 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.model; + +/** + * @author Mark - mark at arangodb.com + * + * @see API Documentation + */ +public class EdgeUpdateOptions { + + private Boolean keepNull; + private Boolean waitForSync; + private String ifMatch; + + public EdgeUpdateOptions() { + 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 EdgeUpdateOptions keepNull(final Boolean keepNull) { + this.keepNull = keepNull; + return this; + } + + 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; + } + + 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; + } +} diff --git a/src/main/java/com/arangodb/model/FulltextIndexOptions.java b/src/main/java/com/arangodb/model/FulltextIndexOptions.java new file mode 100644 index 000000000..1b79a7104 --- /dev/null +++ b/src/main/java/com/arangodb/model/FulltextIndexOptions.java @@ -0,0 +1,76 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.model; + +import java.util.Collection; + +import com.arangodb.entity.IndexType; + +/** + * @author Mark - mark at arangodb.com + * + * @see API + * Documentation + */ +public class FulltextIndexOptions { + + private Collection fields; + private final IndexType type = IndexType.fulltext; + private Integer minLength; + + public FulltextIndexOptions() { + super(); + } + + protected Collection getFields() { + return fields; + } + + /** + * @param fields + * A list of attribute paths + * @return options + */ + protected FulltextIndexOptions fields(final Collection fields) { + this.fields = fields; + return this; + } + + protected IndexType getType() { + return type; + } + + 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; + } + +} diff --git a/src/main/java/com/arangodb/model/GeoIndexOptions.java b/src/main/java/com/arangodb/model/GeoIndexOptions.java new file mode 100644 index 000000000..9fc96c324 --- /dev/null +++ b/src/main/java/com/arangodb/model/GeoIndexOptions.java @@ -0,0 +1,75 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.model; + +import java.util.Collection; + +import com.arangodb.entity.IndexType; + +/** + * @author Mark - mark at arangodb.com + * + * @see API Documentation + */ +public class GeoIndexOptions { + + private Collection fields; + private final IndexType type = IndexType.geo; + private Boolean geoJson; + + public GeoIndexOptions() { + super(); + } + + protected Collection getFields() { + return fields; + } + + /** + * @param fields + * A list of attribute paths + * @return options + */ + protected GeoIndexOptions fields(final Collection fields) { + this.fields = fields; + return this; + } + + protected IndexType getType() { + return type; + } + + 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; + } + +} diff --git a/src/main/java/com/arangodb/model/GraphCreateOptions.java b/src/main/java/com/arangodb/model/GraphCreateOptions.java new file mode 100644 index 000000000..d05e0f88a --- /dev/null +++ b/src/main/java/com/arangodb/model/GraphCreateOptions.java @@ -0,0 +1,145 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.model; + +import java.util.Arrays; +import java.util.Collection; + +import com.arangodb.entity.EdgeDefinition; + +/** + * @author Mark - mark at arangodb.com + * + * @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; + } + + public GraphCreateOptions isSmart(final Boolean isSmart) { + this.isSmart = isSmart; + return this; + } + + public Integer getNumberOfShards() { + return getOptions().getNumberOfShards(); + } + + public void numberOfShards(final Integer numberOfShards) { + getOptions().setNumberOfShards(numberOfShards); + } + + public String getSmartGraphAttribute() { + return getOptions().getSmartGraphAttribute(); + } + + public void smartGraphAttribute(final String smartGraphAttribute) { + getOptions().setSmartGraphAttribute(smartGraphAttribute); + } + + private SmartOptions getOptions() { + if (options == null) { + options = new SmartOptions(); + } + return options; + } + + public static class SmartOptions { + private Integer numberOfShards; + private String smartGraphAttribute; + + public SmartOptions() { + super(); + } + + 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/HashIndexOptions.java b/src/main/java/com/arangodb/model/HashIndexOptions.java new file mode 100644 index 000000000..82172a0cc --- /dev/null +++ b/src/main/java/com/arangodb/model/HashIndexOptions.java @@ -0,0 +1,89 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.model; + +import java.util.Collection; + +import com.arangodb.entity.IndexType; + +/** + * @author Mark - mark at arangodb.com + * + * @see API Documentation + */ +public class HashIndexOptions { + + private Collection fields; + private final IndexType type = IndexType.hash; + private Boolean unique; + private Boolean sparse; + + public HashIndexOptions() { + super(); + } + + protected Collection getFields() { + return fields; + } + + /** + * @param fields + * A list of attribute paths + * @return options + */ + protected HashIndexOptions fields(final Collection fields) { + this.fields = fields; + return this; + } + + protected IndexType getType() { + return type; + } + + 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; + } + + 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; + } + +} diff --git a/src/main/java/com/arangodb/model/LogOptions.java b/src/main/java/com/arangodb/model/LogOptions.java new file mode 100644 index 000000000..2ee3886fe --- /dev/null +++ b/src/main/java/com/arangodb/model/LogOptions.java @@ -0,0 +1,159 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.model; + +import com.arangodb.entity.LogLevel; + +/** + * @author Mark - mark at arangodb.com + * + * @see 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; + } + +} diff --git a/src/main/java/com/arangodb/model/OptionsBuilder.java b/src/main/java/com/arangodb/model/OptionsBuilder.java new file mode 100644 index 000000000..445790e81 --- /dev/null +++ b/src/main/java/com/arangodb/model/OptionsBuilder.java @@ -0,0 +1,120 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.model; + +import java.util.Collection; +import java.util.Map; + +import com.arangodb.entity.EdgeDefinition; + +/** + * @author Mark - mark at arangodb.com + * + */ +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 Collection fields) { + return options.fields(fields); + } + + public static SkiplistIndexOptions build(final SkiplistIndexOptions options, final Collection fields) { + return options.fields(fields); + } + + public static PersistentIndexOptions build(final PersistentIndexOptions options, final Collection fields) { + return options.fields(fields); + } + + public static GeoIndexOptions build(final GeoIndexOptions options, final Collection fields) { + return options.fields(fields); + } + + public static FulltextIndexOptions build(final FulltextIndexOptions options, final Collection 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 Map bindVars) { + return options.query(query).bindVars(bindVars); + } + + public static AqlQueryExplainOptions build( + final AqlQueryExplainOptions options, + final String query, + final Map 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 DBCreateOptions build(final DBCreateOptions options, final String name) { + return options.name(name); + } + + public static UserAccessOptions build(final UserAccessOptions options, final String 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); + } + +} diff --git a/src/main/java/com/arangodb/model/PersistentIndexOptions.java b/src/main/java/com/arangodb/model/PersistentIndexOptions.java new file mode 100644 index 000000000..c01689f16 --- /dev/null +++ b/src/main/java/com/arangodb/model/PersistentIndexOptions.java @@ -0,0 +1,90 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.model; + +import java.util.Collection; + +import com.arangodb.entity.IndexType; + +/** + * @author Mark - mark at arangodb.com + * + * @see API + * Documentation + */ +public class PersistentIndexOptions { + + private Collection fields; + protected IndexType type = IndexType.persistent; + private Boolean unique; + private Boolean sparse; + + public PersistentIndexOptions() { + super(); + } + + protected Collection getFields() { + return fields; + } + + /** + * @param fields + * A list of attribute paths + * @return options + */ + protected PersistentIndexOptions fields(final Collection fields) { + this.fields = fields; + return this; + } + + protected IndexType getType() { + return type; + } + + 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; + } + + 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; + } + +} diff --git a/src/main/java/com/arangodb/model/SkiplistIndexOptions.java b/src/main/java/com/arangodb/model/SkiplistIndexOptions.java new file mode 100644 index 000000000..92086aecb --- /dev/null +++ b/src/main/java/com/arangodb/model/SkiplistIndexOptions.java @@ -0,0 +1,89 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.model; + +import java.util.Collection; + +import com.arangodb.entity.IndexType; + +/** + * @author Mark - mark at arangodb.com + * + * @see API Documentation + */ +public class SkiplistIndexOptions { + + private Collection fields; + private final IndexType type = IndexType.skiplist; + private Boolean unique; + private Boolean sparse; + + public SkiplistIndexOptions() { + super(); + } + + protected Collection getFields() { + return fields; + } + + /** + * @param fields + * A list of attribute paths + * @return options + */ + protected SkiplistIndexOptions fields(final Collection fields) { + this.fields = fields; + return this; + } + + protected IndexType getType() { + return type; + } + + 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; + } + + 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; + } + +} diff --git a/src/main/java/com/arangodb/model/TransactionOptions.java b/src/main/java/com/arangodb/model/TransactionOptions.java new file mode 100644 index 000000000..18624a4b6 --- /dev/null +++ b/src/main/java/com/arangodb/model/TransactionOptions.java @@ -0,0 +1,164 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.model; + +import java.util.Arrays; +import java.util.Collection; + +/** + * @author Mark - mark at arangodb.com + * + * @see API + * Documentation + */ +public class TransactionOptions { + + private String action; + private Object params; + private final TransactionCollectionOptions collections; + private Integer lockTimeout; + private Boolean waitForSync; + + 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; + } + + public TransactionOptions allowImplicit(final Boolean allowImplicit) { + collections.allowImplicit(allowImplicit); + return this; + } + + public static class TransactionCollectionOptions { + + private Collection read; + private Collection write; + private Boolean allowImplicit; + + public Collection getRead() { + return read; + } + + public TransactionCollectionOptions read(final String... read) { + this.read = Arrays.asList(read); + return this; + } + + public Collection getWrite() { + return write; + } + + public TransactionCollectionOptions write(final String... write) { + this.write = Arrays.asList(write); + return this; + } + + public Boolean getAllowImplicit() { + return allowImplicit; + } + + public TransactionCollectionOptions allowImplicit(final Boolean allowImplicit) { + this.allowImplicit = allowImplicit; + return this; + } + + } + +} diff --git a/src/main/java/com/arangodb/model/TraversalOptions.java b/src/main/java/com/arangodb/model/TraversalOptions.java new file mode 100644 index 000000000..2d8bebb5b --- /dev/null +++ b/src/main/java/com/arangodb/model/TraversalOptions.java @@ -0,0 +1,387 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.model; + +/** + * @author Mark - mark at arangodb.com + * + * @see API Documentation + */ +public class TraversalOptions { + + public static enum Direction { + outbound, inbound, any + } + + public static enum ItemOrder { + forward, backward + } + + public static enum Strategy { + depthfirst, breadthfirst + } + + public static enum UniquenessType { + none, global, path + } + + public static 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 new file mode 100644 index 000000000..f2fcf392f --- /dev/null +++ b/src/main/java/com/arangodb/model/UserAccessOptions.java @@ -0,0 +1,44 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.model; + +/** + * @author Mark - mark at arangodb.com + * + */ +public class UserAccessOptions { + + private String grant; + + public UserAccessOptions() { + super(); + } + + protected String getGrant() { + return grant; + } + + protected UserAccessOptions grant(final String 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 new file mode 100644 index 000000000..9545eaadb --- /dev/null +++ b/src/main/java/com/arangodb/model/UserCreateOptions.java @@ -0,0 +1,98 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.model; + +import java.util.Map; + +/** + * @author Mark - mark at arangodb.com + * + * @see API Documentation + */ +public class UserCreateOptions { + + private String user; + private String passwd; + private Boolean active; + private Map extra; + + public UserCreateOptions() { + super(); + } + + 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; + } + + protected String getPasswd() { + return passwd; + } + + /** + * @param passwd + * The user password + * @return options + */ + protected UserCreateOptions passwd(final String passwd) { + this.passwd = passwd; + return this; + } + + 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; + } + + 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; + } + +} diff --git a/src/main/java/com/arangodb/model/UserUpdateOptions.java b/src/main/java/com/arangodb/model/UserUpdateOptions.java new file mode 100644 index 000000000..58f9bb1c9 --- /dev/null +++ b/src/main/java/com/arangodb/model/UserUpdateOptions.java @@ -0,0 +1,83 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.model; + +import java.util.Map; + +/** + * @author Mark - mark at arangodb.com + * + * @see API Documentation + */ +public class UserUpdateOptions { + + private String passwd; + private Boolean active; + private Map extra; + + public UserUpdateOptions() { + super(); + } + + public String getPasswd() { + return passwd; + } + + /** + * @param passwd + * The user password + * @return options + */ + public UserUpdateOptions passwd(final String passwd) { + this.passwd = passwd; + return this; + } + + 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; + } + + 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; + } + +} diff --git a/src/main/java/com/arangodb/model/VertexCollectionCreateOptions.java b/src/main/java/com/arangodb/model/VertexCollectionCreateOptions.java new file mode 100644 index 000000000..796380df9 --- /dev/null +++ b/src/main/java/com/arangodb/model/VertexCollectionCreateOptions.java @@ -0,0 +1,49 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.model; + +/** + * @author Mark - mark at arangodb.com + * + */ +public class VertexCollectionCreateOptions { + + private String collection; + + public VertexCollectionCreateOptions() { + super(); + } + + 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; + } + +} diff --git a/src/main/java/com/arangodb/model/VertexCreateOptions.java b/src/main/java/com/arangodb/model/VertexCreateOptions.java new file mode 100644 index 000000000..74d9d8d7e --- /dev/null +++ b/src/main/java/com/arangodb/model/VertexCreateOptions.java @@ -0,0 +1,50 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.model; + +/** + * @author Mark - mark at arangodb.com + * + * @see API Documentation + */ +public class VertexCreateOptions { + + private Boolean waitForSync; + + public VertexCreateOptions() { + super(); + } + + 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; + } + +} diff --git a/src/main/java/com/arangodb/model/VertexDeleteOptions.java b/src/main/java/com/arangodb/model/VertexDeleteOptions.java new file mode 100644 index 000000000..a61038462 --- /dev/null +++ b/src/main/java/com/arangodb/model/VertexDeleteOptions.java @@ -0,0 +1,64 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.model; + +/** + * @author Mark - mark at arangodb.com + * + * @see API Documentation + */ +public class VertexDeleteOptions { + + private Boolean waitForSync; + private String ifMatch; + + public VertexDeleteOptions() { + super(); + } + + 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; + } + + 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; + } +} diff --git a/src/main/java/com/arangodb/model/VertexReplaceOptions.java b/src/main/java/com/arangodb/model/VertexReplaceOptions.java new file mode 100644 index 000000000..1f86a7dc4 --- /dev/null +++ b/src/main/java/com/arangodb/model/VertexReplaceOptions.java @@ -0,0 +1,64 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.model; + +/** + * @author Mark - mark at arangodb.com + * + * @see API Documentation + */ +public class VertexReplaceOptions { + + private Boolean waitForSync; + private String ifMatch; + + public VertexReplaceOptions() { + super(); + } + + 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; + } + + 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; + } +} diff --git a/src/main/java/com/arangodb/model/VertexUpdateOptions.java b/src/main/java/com/arangodb/model/VertexUpdateOptions.java new file mode 100644 index 000000000..ccae01746 --- /dev/null +++ b/src/main/java/com/arangodb/model/VertexUpdateOptions.java @@ -0,0 +1,82 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.model; + +/** + * @author Mark - mark at arangodb.com + * + * @see API Documentation + */ +public class VertexUpdateOptions { + + private Boolean keepNull; + private Boolean waitForSync; + private String ifMatch; + + public VertexUpdateOptions() { + 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 VertexUpdateOptions keepNull(final Boolean keepNull) { + this.keepNull = keepNull; + return this; + } + + 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; + } + + 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; + } +} diff --git a/src/main/java/com/arangodb/util/AbstractOptions.java b/src/main/java/com/arangodb/util/AbstractOptions.java deleted file mode 100644 index c51838900..000000000 --- a/src/main/java/com/arangodb/util/AbstractOptions.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.arangodb.util; - -import java.util.List; -import java.util.Map; - -public abstract class AbstractOptions { - - protected void putAttribute(Map object, String key, Object value) { - if (value != null) { - object.put(key, value); - } - } - - protected void putAttributeToLower(Map object, String key, Object value) { - if (value != null) { - object.put(key, value.toString().toLowerCase()); - } - } - - protected void putAttribute(MapBuilder object, String key, Object value) { - if (value != null) { - object.put(key, value); - } - } - - protected void putAttributeToLower(MapBuilder object, String key, Object value) { - if (value != null) { - object.put(key, value.toString().toLowerCase()); - } - } - - protected void putAttributeCollection(MapBuilder object, String key, List value) { - if (CollectionUtils.isNotEmpty(value)) { - object.put(key, value); - } - } -} diff --git a/src/main/java/com/arangodb/util/AqlQueryOptions.java b/src/main/java/com/arangodb/util/AqlQueryOptions.java deleted file mode 100644 index f3e1741fd..000000000 --- a/src/main/java/com/arangodb/util/AqlQueryOptions.java +++ /dev/null @@ -1,216 +0,0 @@ -package com.arangodb.util; - -import java.util.Map; - -public class AqlQueryOptions implements OptionsInterface { - - private Boolean count; - private Integer batchSize; - private Boolean fullCount; - private Boolean cache; - private Integer ttl; - private Boolean profile; - - /** - * boolean flag that indicates whether the number of documents in the result - * set should be returned in the "count" attribute of the result (optional). - * Calculating the "count" attribute might in the future have a performance - * impact for some queries so this option is turned off by default, and - * "count" is only returned when requested. - * - * @return flag that indicates whether the number of documents in the result - * set should be returned - */ - public Boolean getCount() { - return count; - } - - /** - * boolean flag that indicates whether the number of documents in the result - * set should be returned in the "count" attribute of the result (optional). - * Calculating the "count" attribute might in the future have a performance - * impact for some queries so this option is turned off by default, and - * "count" is only returned when requested. - * - * @param count - * boolean flag - * @return this - */ - public AqlQueryOptions setCount(Boolean count) { - this.count = count; - return this; - } - - /** - * maximum number of result documents to be transferred from the server to - * the client in one roundtrip (optional). If this attribute is not set, a - * server-controlled default value will be used. The batch size has to be - * greater than 0. - * - * @return maximum number of result documents - */ - public Integer getBatchSize() { - return batchSize; - } - - /** - * maximum number of result documents to be transferred from the server to - * the client in one roundtrip (optional). If this attribute is not set, a - * server-controlled default value will be used. The batch size has to be - * greater than 0. - * - * @param batchSize - * maximum number of result documents - * @return this - */ - public AqlQueryOptions setBatchSize(Integer batchSize) { - this.batchSize = batchSize; - return this; - } - - /** - * if set to true, then the additional query profiling information will be - * returned in the extra.stats return attribute if the query result is not - * served from the query cache. - * - * @return boolean flag - */ - public Boolean getProfile() { - return profile; - } - - /** - * if set to true, then the additional query profiling information will be - * returned in the extra.stats return attribute if the query result is not - * served from the query cache. - * - * @param profile - * boolean flag - * @return this - */ - public AqlQueryOptions setProfile(Boolean profile) { - this.profile = profile; - return this; - } - - /** - * if set to true and the query contains a LIMIT clause, then the result - * will contain an extra attribute extra with a sub-attribute fullCount. - * This sub-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. - * - * @return boolean flag - */ - public Boolean getFullCount() { - return fullCount; - } - - /** - * if set to true and the query contains a LIMIT clause, then the result - * will contain an extra attribute extra with a sub-attribute fullCount. - * This sub-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. - * - * @param fullCount - * boolean flag - * @return this - */ - public AqlQueryOptions setFullCount(Boolean fullCount) { - this.fullCount = fullCount; - return this; - } - - /** - * an optional 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 optional time-to-live - */ - public Integer getTtl() { - return ttl; - } - - /** - * an optional 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. - * - * @param ttl - * optional time-to-live - * @return this - */ - public AqlQueryOptions setTtl(Integer ttl) { - this.ttl = ttl; - return this; - } - - /** - * 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. (since ArangoDB 2.7) - * - * @return boolean flag - */ - public Boolean getCache() { - return 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. (since ArangoDB 2.7) - * - * @param cache - * boolean flag - * @return this - */ - public AqlQueryOptions setCache(Boolean cache) { - this.cache = cache; - return this; - } - - @Override - public Map toMap() { - MapBuilder mp = new MapBuilder(); - if (count != null) { - mp.put("count", count); - } - if (batchSize != null) { - mp.put("batchSize", batchSize); - } - if (ttl != null) { - mp.put("ttl", ttl); - } - if (cache != null) { - mp.put("cache", cache); - } - - MapBuilder optionsMp = new MapBuilder(); - - if (fullCount != null) { - optionsMp.put("fullCount", fullCount); - } - - if (profile != null) { - optionsMp.put("profile", profile); - } - - // TODO add maxPlans - - // TODO add optimizer.rules - - mp.put("options", optionsMp.get()); - - return mp.get(); - } - -} diff --git a/src/main/java/com/arangodb/util/CollectionUtils.java b/src/main/java/com/arangodb/util/CollectionUtils.java deleted file mode 100644 index f2fc75ccd..000000000 --- a/src/main/java/com/arangodb/util/CollectionUtils.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Copyright (C) 2012 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.util; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Iterator; -import java.util.List; -import java.util.NoSuchElementException; - -/** - * @author tamtam180 - kirscheless at gmail.com - * - */ -public class CollectionUtils { - - private static final EmptyIterator EMPTY_ITERATOR = new EmptyIterator(); - - private CollectionUtils() { - // this is a helper class - } - - public static class EmptyIterator implements Iterator { - @Override - public boolean hasNext() { - return false; - } - - @Override - public E next() { - throw new NoSuchElementException(); - } - - @Override - public void remove() { - throw new IllegalStateException(); - } - } - - @SuppressWarnings("unchecked") - public static Iterator emptyIterator() { - return (Iterator) EMPTY_ITERATOR; - } - - public static Iterator safetyIterator(Collection collection) { - if (collection == null) { - return emptyIterator(); - } - return collection.iterator(); - } - - public static List safety(List list) { - if (list == null) { - return new ArrayList(0); // mutable list - } - return list; - } - - public static String join(T[] array, String separator) { - if (array == null || array.length == 0) { - return ""; - } - - StringBuilder buffer = new StringBuilder(); - buffer.append(array[0]); - - for (int i = 1; i < array.length; i++) { - buffer.append(separator); - buffer.append(array[i]); - } - - return buffer.toString(); - } - - public static boolean isNotEmpty(final Collection coll) { - return coll != null && !coll.isEmpty(); - } - -} diff --git a/src/main/java/com/arangodb/util/DateUtils.java b/src/main/java/com/arangodb/util/DateUtils.java deleted file mode 100644 index ba152242f..000000000 --- a/src/main/java/com/arangodb/util/DateUtils.java +++ /dev/null @@ -1,173 +0,0 @@ -/* - * Copyright (C) 2012 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.util; - -import java.io.Serializable; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.HashMap; -import java.util.Locale; -import java.util.TimeZone; - -import com.google.gson.JsonParseException; - -/** - * @author tamtam180 - kirscheless at gmail.com - * - */ -public class DateUtils { - - private static TimeZone utcTimeZone = TimeZone.getTimeZone("UTC"); - - private static ThreadLocal dateFormats = new ThreadLocal() { - @Override - protected LocalFormat initialValue() { - return new LocalFormat(); - } - }; - - private DateUtils() { - // this is a helper class - } - - static class TripleKey - implements Serializable { - private static final long serialVersionUID = 2612228100559578823L; - private T first; - private U second; - private V third; - - public TripleKey() { - // do nothing here - } - - public TripleKey(T first, U second, V third) { - this.first = first; - this.second = second; - this.third = third; - } - - public T getFirst() { - return first; - } - - public void setFirst(T first) { - this.first = first; - } - - public U getSecond() { - return second; - } - - public void setSecond(U second) { - this.second = second; - } - - public V getThird() { - return third; - } - - public void setThird(V third) { - this.third = third; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((first == null) ? 0 : first.hashCode()); - result = prime * result + ((second == null) ? 0 : second.hashCode()); - result = prime * result + ((third == null) ? 0 : third.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; - TripleKey other = (TripleKey) obj; - if (first == null) { - if (other.first != null) - return false; - } else if (!first.equals(other.first)) - return false; - if (second == null) { - if (other.second != null) - return false; - } else if (!second.equals(other.second)) - return false; - if (third == null) { - if (other.third != null) - return false; - } else if (!third.equals(other.third)) - return false; - return true; - } - } - - private static class LocalFormat { - private HashMap, SimpleDateFormat> sdfMap = new HashMap, SimpleDateFormat>(); - - public SimpleDateFormat getDateFormat(String format, Locale locale, TimeZone timeZone) { - TripleKey key = new TripleKey(format, locale, timeZone); - SimpleDateFormat sdf = sdfMap.get(key); - if (sdf == null) { - sdf = new SimpleDateFormat(format); - sdf.setTimeZone(timeZone); - sdfMap.put(key, sdf); - } - return sdf; - } - - } - - public static Date parse(String text, String format) throws ParseException { - - SimpleDateFormat dateFormat = dateFormats.get().getDateFormat(format, Locale.US, utcTimeZone); - - return dateFormat.parse(text); - } - - /** - * Parse date-string in "yyyy-MM-dd'T'HH:mm:ss'Z'" format. - * - * @param dateString - * @return a Date object - */ - public static Date parse(String dateString) { - - try { - return DateUtils.parse(dateString, "yyyy-MM-dd'T'HH:mm:ss'Z'"); - } catch (ParseException e) { - throw new JsonParseException("time format invalid:" + dateString); - } - - } - - public static String format(Date date, String format) { - - SimpleDateFormat dateFormat = dateFormats.get().getDateFormat(format, Locale.US, TimeZone.getDefault()); - - return dateFormat.format(date); - } - -} diff --git a/src/main/java/com/arangodb/util/DumpHandler.java b/src/main/java/com/arangodb/util/DumpHandler.java deleted file mode 100644 index 2b4403aab..000000000 --- a/src/main/java/com/arangodb/util/DumpHandler.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (C) 2012,2013 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.util; - -import com.arangodb.entity.ReplicationDumpHeader; -import com.arangodb.entity.ReplicationDumpRecord; - -/** - * @author tamtam180 - kirscheless at gmail.com - * - */ -public interface DumpHandler { - - public boolean head(ReplicationDumpHeader header); - public boolean handle(ReplicationDumpRecord entity); - -} diff --git a/src/main/java/com/arangodb/util/EdgeUtils.java b/src/main/java/com/arangodb/util/EdgeUtils.java deleted file mode 100644 index 13e820d94..000000000 --- a/src/main/java/com/arangodb/util/EdgeUtils.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.arangodb.util; - -import com.arangodb.entity.BaseDocument; -import com.arangodb.entity.EntityFactory; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; - -/** - * @author Mark - mark@arangodb.com - * - */ -public class EdgeUtils { - - private EdgeUtils() { - super(); - } - - public static JsonObject valueToEdgeJsonObject( - final String key, - final String fromHandle, - final String toHandle, - final T value) { - JsonObject obj; - if (value == null) { - obj = new JsonObject(); - } else { - final JsonElement elem = EntityFactory.toJsonElement(value, false); - if (elem.isJsonObject()) { - obj = elem.getAsJsonObject(); - } else { - throw new IllegalArgumentException("value need object type(not support array, primitive, etc..)."); - } - } - if (key != null) { - obj.addProperty(BaseDocument.KEY, key); - } - if (fromHandle != null) { - obj.addProperty(BaseDocument.FROM, fromHandle); - } - if (toHandle != null) { - obj.addProperty(BaseDocument.TO, toHandle); - } - return obj; - } -} diff --git a/src/main/java/com/arangodb/util/GraphEdgesOptions.java b/src/main/java/com/arangodb/util/GraphEdgesOptions.java deleted file mode 100644 index a03b54c23..000000000 --- a/src/main/java/com/arangodb/util/GraphEdgesOptions.java +++ /dev/null @@ -1,227 +0,0 @@ -package com.arangodb.util; - -import java.util.List; - -import com.arangodb.Direction; - -public class GraphEdgesOptions { - - private Direction direction; - private List edgeCollectionRestriction; - private List startVertexCollectionRestriction; - private List endVertexCollectionRestriction; - private Object edgeExamples; - private Object neighborExamples; - private Integer minDepth; - private Integer maxDepth; - private Integer limit; - private Boolean includeData = Boolean.TRUE; - - /** - * The direction of the edges as a string. Possible values are outbound, - * inbound and any (default). - * - * @return the direction - */ - public Direction getDirection() { - return direction; - } - - /** - * The direction of the edges as a string. Possible values are outbound, - * inbound and any (default). - * - * @param direction - * @return this - */ - public GraphEdgesOptions setDirection(Direction direction) { - this.direction = direction; - return this; - } - - /** - * One or multiple edge collection names. Only edges from these collections - * will be considered for the path. - * - * @return One or multiple edge collection names. - */ - public List getEdgeCollectionRestriction() { - return edgeCollectionRestriction; - } - - /** - * One or multiple edge collection names. Only edges from these collections - * will be considered for the path. - * - * @param edgeCollectionRestriction - * @return this - */ - public GraphEdgesOptions setEdgeCollectionRestriction(List edgeCollectionRestriction) { - this.edgeCollectionRestriction = edgeCollectionRestriction; - return this; - } - - /** - * One or multiple vertex collection names. Only vertices from these - * collections will be considered as start vertex of a path. - * - * @return One or multiple vertex collection names. - */ - public List getStartVertexCollectionRestriction() { - return startVertexCollectionRestriction; - } - - /** - * One or multiple vertex collection names. Only vertices from these - * collections will be considered as start vertex of a path. - * - * @param startVertexCollectionRestriction - * @return this - */ - public GraphEdgesOptions setStartVertexCollectionRestriction(List startVertexCollectionRestriction) { - this.startVertexCollectionRestriction = startVertexCollectionRestriction; - return this; - } - - /** - * One or multiple vertex collection names. Only vertices from these - * collections will be considered as end vertex of a path. - * - * @return One or multiple vertex collection names. - */ - public List getEndVertexCollectionRestriction() { - return endVertexCollectionRestriction; - } - - /** - * One or multiple vertex collection names. Only vertices from these - * collections will be considered as end vertex of a path. - * - * @param endVertexCollectionRestriction - * @return this - */ - public GraphEdgesOptions setEndVertexCollectionRestriction(List endVertexCollectionRestriction) { - this.endVertexCollectionRestriction = endVertexCollectionRestriction; - return this; - } - - /** - * A filter example for the edges - * - * @return A filter example for the edges - */ - public Object getEdgeExamples() { - return edgeExamples; - } - - /** - * A filter example for the edges - * - * @param edgeExamples - * @return this - */ - public GraphEdgesOptions setEdgeExamples(Object edgeExamples) { - this.edgeExamples = edgeExamples; - return this; - } - - /** - * An example for the desired neighbors - * - * @return An example for the desired neighbors - */ - public Object getNeighborExamples() { - return neighborExamples; - } - - /** - * An example for the desired neighbors - * - * @param neighborExamples - * @return this - */ - public GraphEdgesOptions setNeighborExamples(Object neighborExamples) { - this.neighborExamples = neighborExamples; - return this; - } - - /** - * Defines the minimal length of a path from an edge to a vertex (default is - * 1, which means only the edges directly connected to a vertex would be - * returned). - * - * @return efines the minimal length of a path - */ - public Integer getMinDepth() { - return minDepth; - } - - /** - * Defines the minimal length of a path from an edge to a vertex (default is - * 1, which means only the edges directly connected to a vertex would be - * returned). - * - * @param minDepth - * @return this - */ - public GraphEdgesOptions setMinDepth(Integer minDepth) { - this.minDepth = minDepth; - return this; - } - - /** - * Defines the maximal length of a path from an edge to a vertex (default is - * 1, which means only the edges directly connected to a vertex would be - * returned). - * - * @return Defines the maximal length of a path - */ - public Integer getMaxDepth() { - return maxDepth; - } - - /** - * Defines the maximal length of a path from an edge to a vertex (default is - * 1, which means only the edges directly connected to a vertex would be - * returned). - * - * @param maxDepth - * @return this - */ - public GraphEdgesOptions setMaxDepth(Integer maxDepth) { - this.maxDepth = maxDepth; - return this; - } - - public Integer getLimit() { - return limit; - } - - public GraphEdgesOptions setLimit(Integer limit) { - this.limit = limit; - return this; - } - - /** - * Get include data - * - * @return returns true, if the return values are compatible with older - * versions of AnrangoDB - */ - public Boolean getIncludeData() { - return includeData; - } - - /** - * set include data to be compatible with older versions of AnrangoDB - * - * @param includeData - * - * @since ArangoDB 2.6 - */ - public GraphEdgesOptions setIncludeData(Boolean includeData) { - this.includeData = includeData; - return this; - } - -} diff --git a/src/main/java/com/arangodb/util/GraphQueryUtil.java b/src/main/java/com/arangodb/util/GraphQueryUtil.java deleted file mode 100644 index dde6a35b2..000000000 --- a/src/main/java/com/arangodb/util/GraphQueryUtil.java +++ /dev/null @@ -1,335 +0,0 @@ -package com.arangodb.util; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map.Entry; -import java.util.Set; - -import com.arangodb.ArangoDriver; -import com.arangodb.ArangoException; -import com.arangodb.Direction; -import com.google.gson.Gson; -import com.google.gson.JsonArray; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; - -/** - * @author Mark - mark@arangodb.com - * - */ -public class GraphQueryUtil { - - private static final String AND = " && "; - private static final String OR = " || "; - private static final String GRAPH_NAME = "graphName"; - private static final String VERTEX_EXAMPLE = "vertexExample"; - private static final String START_VERTEX_EXAMPLE = "startVertexExample"; - private static final String END_VERTEX_EXAMPLE = "endVertexExample"; - private static final String SOURCE = "source"; - private static final String TARGET = "target"; - - public static String createEdgeQuery( - final ArangoDriver driver, - final String graphName, - final Object vertexExample, - final GraphEdgesOptions graphEdgesOptions, - final MapBuilder bindVars) throws ArangoException { - - final StringBuilder sb = new StringBuilder(); - if (vertexExample != null && String.class.isAssignableFrom(vertexExample.getClass())) { - sb.append("FOR v,e IN "); - appendDepth(graphEdgesOptions, sb); - appendDirection(graphEdgesOptions.getDirection(), sb); - appendBindVar(VERTEX_EXAMPLE, vertexExample, bindVars, sb); - } else { - final List startVertexCollectionRestriction = graphEdgesOptions - .getStartVertexCollectionRestriction(); - final List vertexCollections = startVertexCollectionRestriction != null - && startVertexCollectionRestriction.size() > 0 ? startVertexCollectionRestriction - : driver.graphGetVertexCollections(graphName, true); - appendFor("start", vertexExample, sb, vertexCollections); - sb.append(" FOR v,e IN "); - appendDepth(graphEdgesOptions, sb); - appendDirection(graphEdgesOptions.getDirection(), sb); - sb.append(" start"); - } - final List edgeCollectionRestriction = graphEdgesOptions.getEdgeCollectionRestriction(); - appendEdgeCollectionsOrGraph(graphName, bindVars, sb, edgeCollectionRestriction); - appendFilter("e", graphEdgesOptions.getEdgeExamples(), sb); - appendFilter("v", graphEdgesOptions.getNeighborExamples(), sb); - { - final List endVertexCollectionRestriction = graphEdgesOptions.getEndVertexCollectionRestriction(); - if (endVertexCollectionRestriction != null && endVertexCollectionRestriction.size() > 0) { - sb.append(" FILTER "); - for (String endVertexCollection : endVertexCollectionRestriction) { - sb.append("IS_SAME_COLLECTION(`"); - sb.append(endVertexCollection); - sb.append("`,v)"); - sb.append(OR); - } - sb.delete(sb.length() - OR.length(), sb.length() - 1); - } - } - final Integer limit = graphEdgesOptions.getLimit(); - if (limit != null) { - sb.append(" LIMIT "); - sb.append(limit.intValue()); - } - sb.append(" RETURN distinct e"); - if (graphEdgesOptions.getIncludeData() != null && !graphEdgesOptions.getIncludeData().booleanValue()) { - sb.append(".id"); - } - - final String query = sb.toString(); - return query; - } - - private static void appendEdgeCollectionsOrGraph( - final String graphName, - final MapBuilder bindVars, - final StringBuilder sb, - final List edgeCollectionRestriction) { - sb.append(" "); - if (edgeCollectionRestriction != null && edgeCollectionRestriction.size() > 0) { - for (String edgeCollection : edgeCollectionRestriction) { - sb.append("`"); - sb.append(edgeCollection); - sb.append("`,"); - } - // remove last , - sb.deleteCharAt(sb.length() - 1); - } else { - appendGraphName(graphName, bindVars, sb); - } - } - - private static void appendBindVar( - final String param, - final Object var, - final MapBuilder bindVars, - final StringBuilder sb) { - sb.append(" @"); - sb.append(param); - bindVars.put(param, var); - } - - private static void appendFor( - final String var, - final Object vertexExample, - final StringBuilder sb, - final List vertexCollections) throws ArangoException { - if (vertexCollections.size() == 1) { - sb.append("FOR "); - sb.append(var); - sb.append(" IN `"); - sb.append(vertexCollections.get(0)); - sb.append("`"); - appendFilter(var, vertexExample, sb); - } else { - sb.append("FOR "); - sb.append(var); - sb.append(" IN UNION ("); - for (String vertexCollection : vertexCollections) { - sb.append("(FOR "); - sb.append(var); - sb.append(" IN `"); - sb.append(vertexCollection); - sb.append("`"); - appendFilter(var, vertexExample, sb); - sb.append(" RETURN "); - sb.append(var); - sb.append("),"); - } - // remove last , - sb.deleteCharAt(sb.length() - 1); - sb.append(")"); - } - sb.append(" "); - } - - private static void appendGraphName(final String graphName, final MapBuilder bindVars, final StringBuilder sb) { - sb.append("GRAPH"); - appendBindVar(GRAPH_NAME, graphName, bindVars, sb); - } - - private static void appendDepth(final GraphEdgesOptions graphEdgesOptions, final StringBuilder sb) { - final Integer minDepth = graphEdgesOptions.getMinDepth(); - final Integer maxDepth = graphEdgesOptions.getMaxDepth(); - if (minDepth != null || maxDepth != null) { - sb.append(minDepth != null ? minDepth : 1); - sb.append(".."); - sb.append(maxDepth != null ? maxDepth : 1); - sb.append(" "); - } - } - - private static void appendDirection(final Direction direction, final StringBuilder sb) { - final String directionName = direction != null ? direction.name() : Direction.ANY.name(); - sb.append(directionName); - } - - private static void appendFilter(final String var, final Object example, final StringBuilder sb) - throws ArangoException { - if (example != null) { - final Gson gson = new Gson(); - final JsonElement json = gson.toJsonTree(example); - if (json.isJsonObject()) { - sb.append(" FILTER "); - appendObjectinFilter(var, json.getAsJsonObject(), sb); - } else if (json.isJsonArray()) { - sb.append(" FILTER "); - final JsonArray jsonArray = json.getAsJsonArray(); - if (jsonArray.size() > 0) { - for (JsonElement jsonElement : jsonArray) { - if (jsonElement.isJsonObject()) { - sb.append("("); - appendObjectinFilter(var, jsonElement.getAsJsonObject(), sb); - sb.append(")"); - sb.append(OR); - } else if (!jsonElement.isJsonNull()) { - throw new ArangoException("invalide format of entry in array example: " - + example.getClass().getSimpleName() + ". only objects in array allowed."); - } - } - sb.delete(sb.length() - OR.length(), sb.length() - 1); - } - } else { - throw new ArangoException("invalide format of example: " + example.getClass().getSimpleName() - + ". only object or array allowed."); - } - } - } - - private static void appendObjectinFilter(final String var, final JsonObject jsonObject, final StringBuilder sb) { - final Set> entrySet = jsonObject.entrySet(); - for (Entry entry : entrySet) { - sb.append(var); - sb.append(".`"); - sb.append(entry.getKey()); - sb.append("` == "); - sb.append(entry.getValue().toString()); - sb.append(AND); - } - sb.delete(sb.length() - AND.length(), sb.length() - 1); - } - - public static String createVerticesQuery( - final ArangoDriver driver, - final String graphName, - final Object vertexExample, - final GraphVerticesOptions graphVerticesOptions, - final MapBuilder bindVars) throws ArangoException { - - StringBuilder sb = new StringBuilder(); - final boolean stringVertexExample = vertexExample != null - && String.class.isAssignableFrom(vertexExample.getClass()); - if (stringVertexExample) { - sb.append("RETURN "); - sb.append("DOCUMENT("); - appendBindVar(VERTEX_EXAMPLE, vertexExample, bindVars, sb); - sb.append(")"); - } else { - final List startVertexCollectionRestriction = graphVerticesOptions.getVertexCollectionRestriction(); - final List vertexCollections = startVertexCollectionRestriction != null - && startVertexCollectionRestriction.size() > 0 ? startVertexCollectionRestriction - : driver.graphGetVertexCollections(graphName, true); - appendFor("start", vertexExample, sb, vertexCollections); - sb.append(" RETURN start"); - } - - final String query = sb.toString(); - return query; - } - - public static String createShortestPathQuery( - final ArangoDriver driver, - final String database, - final String graphName, - final Object startVertexExample, - final Object endVertexExample, - final ShortestPathOptions shortestPathOptions, - final Class vertexClass, - final Class edgeClass, - final MapBuilder bindVars) throws ArangoException { - /* - * - * final String query = - * "for i in graph_shortest_path(@graphName, @startVertexExample, @endVertexExample, @options) return i" - * ; final Map bindVars = mapBuilder.put("graphName", - * graphName) .put("startVertexExample", - * startVertexExample).put("endVertexExample", endVertexExample) - * .put("options", options).get(); - */ - final StringBuilder sb = new StringBuilder(); - final boolean notStringStartVertexExample = startVertexExample != null - && !String.class.isAssignableFrom(startVertexExample.getClass()); - boolean notStringEndVertexExample = endVertexExample != null - && !String.class.isAssignableFrom(endVertexExample.getClass()); - if (notStringStartVertexExample || notStringEndVertexExample) { - final List startVertexCollectionRestriction = shortestPathOptions - .getStartVertexCollectionRestriction(); - final List endVertexCollectionRestriction = shortestPathOptions.getEndVertexCollectionRestriction(); - final boolean startVertexCollectionRestrictionNotEmpty = startVertexCollectionRestriction != null - && startVertexCollectionRestriction.size() > 0; - final boolean endVertexCollectionRestrictionNotEmpty = endVertexCollectionRestriction != null - && endVertexCollectionRestriction.size() > 0; - final List vertexCollections = (!startVertexCollectionRestrictionNotEmpty - || !endVertexCollectionRestrictionNotEmpty) ? driver.graphGetVertexCollections(graphName, true) - : new ArrayList(); - - if (notStringStartVertexExample) { - final List tmpStartVertexCollectionRestriction = startVertexCollectionRestrictionNotEmpty - ? startVertexCollectionRestriction : vertexCollections; - appendFor(SOURCE, startVertexExample, sb, tmpStartVertexCollectionRestriction); - } - if (notStringEndVertexExample) { - final List tmpEndVertexCollectionRestriction = endVertexCollectionRestrictionNotEmpty - ? endVertexCollectionRestriction : vertexCollections; - appendFor(TARGET, endVertexExample, sb, tmpEndVertexCollectionRestriction); - } - if (notStringStartVertexExample && notStringEndVertexExample) { - sb.append("FILTER target != source "); - } - } - {// p - sb.append("LET p = ( FOR v, e IN "); - appendDirection(shortestPathOptions.getDirection(), sb); - sb.append(" SHORTEST_PATH "); - if (notStringStartVertexExample) { - sb.append(SOURCE); - } else { - appendBindVar(START_VERTEX_EXAMPLE, startVertexExample, bindVars, sb); - } - sb.append(" TO "); - if (notStringEndVertexExample) { - sb.append(TARGET); - } else { - appendBindVar(END_VERTEX_EXAMPLE, endVertexExample, bindVars, sb); - } - List edgeCollectionRestriction = shortestPathOptions.getEdgeCollectionRestriction(); - appendEdgeCollectionsOrGraph(graphName, bindVars, sb, edgeCollectionRestriction); - - final String weight = shortestPathOptions.getWeight(); - if (weight != null) { - sb.append(" OPTIONS {weightAttribute: @attribute, defaultWeight: @default} "); - sb.append( - " RETURN { v: v, e: e, d: IS_NULL(e) ? 0 : (IS_NUMBER(e[@attribute]) ? e[@attribute] : @default)}) "); - bindVars.put("attribute", weight); - final Long defaultWeight = shortestPathOptions.getDefaultWeight(); - bindVars.put("default", defaultWeight != null ? defaultWeight : 1); - } else { - sb.append(" RETURN {v: v, e: e, d: IS_NULL(e) ? 0 : 1}) "); - } - } - sb.append("FILTER LENGTH(p) > 0 "); - if (shortestPathOptions.getIncludeData() != null && !shortestPathOptions.getIncludeData().booleanValue()) { - sb.append( - "RETURN { vertices: p[*].v._id, edges: p[* FILTER CURRENT.e != null].e._id, distance: SUM(p[*].d)}"); - } else { - sb.append("RETURN { vertices: p[*].v, edges: p[* FILTER CURRENT.e != null].e, distance: SUM(p[*].d)}"); - } - - final String query = sb.toString(); - return query; - } -} diff --git a/src/main/java/com/arangodb/util/GraphVerticesOptions.java b/src/main/java/com/arangodb/util/GraphVerticesOptions.java deleted file mode 100644 index 69106081d..000000000 --- a/src/main/java/com/arangodb/util/GraphVerticesOptions.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.arangodb.util; - -import java.util.List; - -public class GraphVerticesOptions { - - private List vertexCollectionRestriction; - - /** - * One or multiple vertex collections that should be considered. - * - * @return One or multiple vertex collections that should be considered. - */ - public List getVertexCollectionRestriction() { - return vertexCollectionRestriction; - } - - /** - * One or multiple vertex collections that should be considered. - * - * @param vertexCollectionRestriction - */ - public void setVertexCollectionRestriction(List vertexCollectionRestriction) { - this.vertexCollectionRestriction = vertexCollectionRestriction; - } - -} diff --git a/src/main/java/com/arangodb/util/IOUtils.java b/src/main/java/com/arangodb/util/IOUtils.java deleted file mode 100644 index 1942eaf36..000000000 --- a/src/main/java/com/arangodb/util/IOUtils.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright (C) 2012 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.util; - -import java.io.BufferedInputStream; -import java.io.Closeable; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.UnsupportedEncodingException; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * @author tamtam180 - kirscheless at gmail.com - * - */ -public class IOUtils { - - private static Logger logger = LoggerFactory.getLogger(IOUtils.class); - - private IOUtils() { - // this is a helper class - } - - public static String toString(InputStream input) throws IOException { - return toString(input, "utf-8"); - } - - public static String toString(InputStream input, String encode) throws IOException { - - InputStreamReader in; - try { - - StringBuilder buffer = new StringBuilder(8012); - - in = new InputStreamReader(new BufferedInputStream(input), encode); - char[] cbuf = new char[8012]; - int len; - while ((len = in.read(cbuf)) != -1) { - buffer.append(cbuf, 0, len); - } - - return buffer.toString(); - - } catch (UnsupportedEncodingException e) { - throw new RuntimeException(e); - } finally { - close(input); - } - } - - public static void close(Closeable input) { - if (input != null) { - try { - input.close(); - } catch (IOException e) { - logger.error("could not close a file", e); - } - } - } - -} diff --git a/src/main/java/com/arangodb/util/ImportOptions.java b/src/main/java/com/arangodb/util/ImportOptions.java deleted file mode 100644 index 9ca1601fa..000000000 --- a/src/main/java/com/arangodb/util/ImportOptions.java +++ /dev/null @@ -1,181 +0,0 @@ -package com.arangodb.util; - -import java.util.Map; - -public class ImportOptions implements OptionsInterface { - - public enum OnDuplicate { - ERROR, UPDATE, REPLACE, IGNORE - } - - private Boolean overwrite; - private Boolean waitForSync; - private OnDuplicate onDuplicate; - private Boolean complete; - private Boolean details; - - /** - * overwrite (optional): 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 preseved. - * - * @return - */ - public Boolean getOverwrite() { - return overwrite; - } - - /** - * overwrite (optional): 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 preseved. - * - * - * @param overwrite - * @return this ImportOptions object - */ - public ImportOptions setOverwrite(Boolean overwrite) { - this.overwrite = overwrite; - return this; - } - - /** - * (optional) Wait until documents have been synced to disk before - * returning. - * - * @return - */ - public Boolean getWaitForSync() { - return waitForSync; - } - - /** - * (optional) Wait until documents have been synced to disk before - * returning. - * - * @param waitForSync - * @return this ImportOptions object - */ - public ImportOptions setWaitForSync(Boolean waitForSync) { - this.waitForSync = waitForSync; - return this; - } - - /** - * (optional) Controls what action is carried out in case of a unique key - * constraint violation. Possible values are: - * - * OnDuplicate.ERROR: this will not import the current document because of - * the unique key constraint violation. This is the default setting. - * - * OnDuplicate.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 preseved. - * - * OnDuplicate.REPLACE: this will replace an existing document in the - * database with the data specified in the request. - * - * OnDuplicate.IGNORE: this will not update an existing document and simply - * ignore the error caused by the unique key constraint violation. - * - * @return - */ - public OnDuplicate getOnDuplicate() { - return onDuplicate; - } - - /** - * (optional) Controls what action is carried out in case of a unique key - * constraint violation. Possible values are: - * - * OnDuplicate.ERROR: this will not import the current document because of - * the unique key constraint violation. This is the default setting. - * - * OnDuplicate.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 preseved. - * - * OnDuplicate.REPLACE: this will replace an existing document in the - * database with the data specified in the request. - * - * OnDuplicate.IGNORE: this will not update an existing document and simply - * ignore the error caused by the unique key constraint violation. - * - * @param onDuplicate - * @return this ImportOptions object - */ - public ImportOptions setOnDuplicate(OnDuplicate onDuplicate) { - this.onDuplicate = onDuplicate; - return this; - } - - /** - * (optional) 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 - */ - public Boolean getComplete() { - return complete; - } - - /** - * (optional) 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. - * - * @param complete - * @return this ImportOptions object - */ - public ImportOptions setComplete(Boolean complete) { - this.complete = complete; - return this; - } - - /** - * (optional) If set to true, the result will include an attribute details - * with details about documents that could not be imported. - * - * @return - */ - public Boolean getDetails() { - return details; - } - - /** - * (optional) If set to true, the result will include an attribute details - * with details about documents that could not be imported. - * - * @param details - * @return this ImportOptions object - */ - public ImportOptions setDetails(Boolean details) { - this.details = details; - return this; - } - - @Override - public Map toMap() { - MapBuilder mp = new MapBuilder(); - - if (overwrite != null) { - mp.put("overwrite", overwrite); - } - if (waitForSync != null) { - mp.put("waitForSync", waitForSync); - } - if (onDuplicate != null) { - mp.put("onDuplicate", onDuplicate.toString().toLowerCase()); - } - if (complete != null) { - mp.put("complete", complete); - } - if (details != null) { - mp.put("details", details); - } - - return mp.get(); - } - -} diff --git a/src/main/java/com/arangodb/util/ImportOptionsJson.java b/src/main/java/com/arangodb/util/ImportOptionsJson.java deleted file mode 100644 index 1d6d46149..000000000 --- a/src/main/java/com/arangodb/util/ImportOptionsJson.java +++ /dev/null @@ -1,73 +0,0 @@ -package com.arangodb.util; - -import java.util.Map; - -public class ImportOptionsJson extends ImportOptions { - - private String fromPrefix; - private String toPrefix; - - /** - * 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 prefix for the values in _from attributes - */ - public String getFromPrefix() { - return 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. - * - * @param fromPrefix - * @return this ImportOptionsJson object - */ - public ImportOptionsJson setFromPrefix(String fromPrefix) { - this.fromPrefix = fromPrefix; - return this; - } - - /** - * 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 prefix for the values in _to attributes - */ - public String getToPrefix() { - return 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. - * - * @param toPrefix - * @return this ImportOptionsJson object - */ - public ImportOptionsJson setToPrefix(String toPrefix) { - this.toPrefix = toPrefix; - return this; - } - - @Override - public Map toMap() { - Map map = super.toMap(); - - if (fromPrefix != null) { - map.put("fromPrefix", fromPrefix); - } - - if (toPrefix != null) { - map.put("toPrefix", toPrefix); - } - - return map; - } - -} diff --git a/src/main/java/com/arangodb/util/ImportOptionsRaw.java b/src/main/java/com/arangodb/util/ImportOptionsRaw.java deleted file mode 100644 index 4c57a5314..000000000 --- a/src/main/java/com/arangodb/util/ImportOptionsRaw.java +++ /dev/null @@ -1,70 +0,0 @@ -package com.arangodb.util; - -import java.util.Map; - -public class ImportOptionsRaw extends ImportOptionsJson { - - public enum ImportType { - DOCUMENTS, LIST, AUTO - } - - private ImportType importType; - - public ImportOptionsRaw(ImportType importType) { - this.importType = importType; - } - - /** - * Determines how the body of the request will be interpreted. type can have - * the following values: - * - * ImportType.DOCUMENTS: when this type is used, each line in the request - * body is expected to be an individual JSON-encoded document. Multiple JSON - * objects in the request body need to be separated by newlines. - * - * ImportType.LIST: when this type is used, the request body must contain a - * single JSON-encoded array of individual objects to import. - * - * ImportType.AUTO: if set, this will automatically determine the body type - * (either documents or list). - * - * @return - */ - public ImportType getImportType() { - return importType; - } - - /** - * Determines how the body of the request will be interpreted. type can have - * the following values: - * - * ImportType.DOCUMENTS: when this type is used, each line in the request - * body is expected to be an individual JSON-encoded document. Multiple JSON - * objects in the request body need to be separated by newlines. - * - * ImportType.LIST: when this type is used, the request body must contain a - * single JSON-encoded array of individual objects to import. - * - * ImportType.AUTO: if set, this will automatically determine the body type - * (either documents or list). - * - * @param importType - * @return - */ - public ImportOptionsRaw setImportType(ImportType importType) { - this.importType = importType; - return this; - } - - @Override - public Map toMap() { - Map map = super.toMap(); - - if (importType != null) { - map.put("type", importType.toString().toLowerCase()); - } - - return map; - } - -} diff --git a/src/main/java/com/arangodb/util/JsonUtils.java b/src/main/java/com/arangodb/util/JsonUtils.java deleted file mode 100644 index ae2d1ebb8..000000000 --- a/src/main/java/com/arangodb/util/JsonUtils.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Copyright (C) 2012 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.util; - -import com.google.gson.JsonArray; -import com.google.gson.JsonElement; -import com.google.gson.JsonPrimitive; - -/** - * @author tamtam180 - kirscheless at gmail.com - * - */ -public class JsonUtils { - - private JsonUtils() { - // this is a helper class - } - - public static int[] toArray(JsonArray array) { - int len = array.size(); - int[] iarray = new int[len]; - for (int i = 0; i < len; i++) { - iarray[i] = array.get(i).getAsInt(); - } - return iarray; - } - - public static double[] toDoubleArray(JsonArray array) { - int len = array.size(); - double[] darray = new double[len]; - for (int i = 0; i < len; i++) { - darray[i] = toDouble(array.get(i)); - } - return darray; - } - - public static double toDouble(JsonElement elem) { - if (elem != null && !elem.isJsonNull()) { - JsonPrimitive primitive = elem.getAsJsonPrimitive(); - if (primitive.isNumber()) { - return primitive.getAsDouble(); - } else if (primitive.isString()) { - if ("INF".equals(primitive.getAsString())) { - return Double.POSITIVE_INFINITY; - } else if ("NaN".equals(primitive.getAsString())) { - return Double.NaN; - } - } - } - return Double.NaN; - } - - public static Object convertNullToMap(OptionsInterface o) { - if (o == null) { - return new MapBuilder().get(); - } - return o.toMap(); - } - - public static Object convertNullToMap(Object o) { - if (o == null) { - return new MapBuilder().get(); - } - return o; - } -} diff --git a/src/main/java/com/arangodb/util/MapBuilder.java b/src/main/java/com/arangodb/util/MapBuilder.java index a5685e994..10ffd219a 100644 --- a/src/main/java/com/arangodb/util/MapBuilder.java +++ b/src/main/java/com/arangodb/util/MapBuilder.java @@ -1,61 +1,47 @@ -/* - * Copyright (C) 2012 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.util; - -import java.util.LinkedHashMap; -import java.util.Map; - -/** - * @author tamtam180 - kirscheless at gmail.com - * - */ -public class MapBuilder { - - private boolean ignoreValue = true; - private LinkedHashMap map; - - public MapBuilder() { - map = new LinkedHashMap(); - } - public MapBuilder(boolean ignoreValue) { - this(); - this.ignoreValue = ignoreValue; - } - public MapBuilder(String key, Object value) { - this(); - put(key, value); - } - public MapBuilder(String key, Object value, boolean ignoreValue) { - this(); - this.ignoreValue = ignoreValue; - put(key, value); - } - - public MapBuilder put(String key, Object value) { - return put(key, value, false); - } - public MapBuilder put(String key, Object value, boolean toString) { - if (!this.ignoreValue || (key != null && value != null)) { - map.put(key, toString ? value.toString() : value); - } - return this; - } - public Map get() { - return map; - } - -} +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.util; + +import java.util.LinkedHashMap; +import java.util.Map; + +/** + * @author Mark - mark at arangodb.com + * + */ +public class MapBuilder { + + private final Map map; + + public MapBuilder() { + super(); + map = new LinkedHashMap(); + } + + public MapBuilder put(final String key, final Object value) { + map.put(key, value); + return this; + } + + public Map get() { + return map; + } +} diff --git a/src/main/java/com/arangodb/util/OptionsInterface.java b/src/main/java/com/arangodb/util/OptionsInterface.java deleted file mode 100644 index f4fcc3409..000000000 --- a/src/main/java/com/arangodb/util/OptionsInterface.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.arangodb.util; - -import java.util.Map; - -public interface OptionsInterface { - - public Map toMap(); - -} diff --git a/src/main/java/com/arangodb/util/ReflectionUtils.java b/src/main/java/com/arangodb/util/ReflectionUtils.java deleted file mode 100644 index 539f325b8..000000000 --- a/src/main/java/com/arangodb/util/ReflectionUtils.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright (C) 2012 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.util; - -import com.arangodb.ArangoException; - -/** - * @author tamtam180 - kirscheless at gmail.com - * - */ -public class ReflectionUtils { - - private ReflectionUtils() { - // this is a helper class - } - - @SuppressWarnings("unchecked") - public static T newInstance(Class clazz) throws ArangoException { - try { - return (T) clazz.newInstance(); - } catch (InstantiationException e) { - throw new ArangoException(e); - } catch (IllegalAccessException e) { - throw new ArangoException(e); - } - } - -} diff --git a/src/main/java/com/arangodb/util/ShortestPathOptions.java b/src/main/java/com/arangodb/util/ShortestPathOptions.java deleted file mode 100644 index c5936e2e2..000000000 --- a/src/main/java/com/arangodb/util/ShortestPathOptions.java +++ /dev/null @@ -1,172 +0,0 @@ -package com.arangodb.util; - -import java.util.List; - -import com.arangodb.Direction; - -public class ShortestPathOptions { - - private Direction direction; - private List edgeCollectionRestriction; - private List startVertexCollectionRestriction; - private List endVertexCollectionRestriction; - private String weight; - private Long defaultWeight; - private Boolean includeData = Boolean.TRUE; - - /** - * The direction of the edges as a string. Possible values are outbound, - * inbound and any (default). - * - * @return the direction - */ - public Direction getDirection() { - return direction; - } - - /** - * The direction of the edges as a string. Possible values are outbound, - * inbound and any (default). - * - * @param direction - * @return this - */ - public ShortestPathOptions setDirection(Direction direction) { - this.direction = direction; - return this; - } - - /** - * One or multiple edge collection names. Only edges from these collections - * will be considered for the path. - * - * @return One or multiple edge collection names. - */ - public List getEdgeCollectionRestriction() { - return edgeCollectionRestriction; - } - - /** - * One or multiple edge collection names. Only edges from these collections - * will be considered for the path. - * - * @param edgeCollectionRestriction - * @return this - */ - public ShortestPathOptions setEdgeCollectionRestriction(List edgeCollectionRestriction) { - this.edgeCollectionRestriction = edgeCollectionRestriction; - return this; - } - - /** - * One or multiple vertex collection names. Only vertices from these - * collections will be considered as start vertex of a path. - * - * @return One or multiple vertex collection names. - */ - public List getStartVertexCollectionRestriction() { - return startVertexCollectionRestriction; - } - - /** - * One or multiple vertex collection names. Only vertices from these - * collections will be considered as start vertex of a path. - * - * @param startVertexCollectionRestriction - * @return this - */ - public ShortestPathOptions setStartVertexCollectionRestriction(List startVertexCollectionRestriction) { - this.startVertexCollectionRestriction = startVertexCollectionRestriction; - return this; - } - - /** - * One or multiple vertex collection names. Only vertices from these - * collections will be considered as end vertex of a path. - * - * @return One or multiple vertex collection names. - */ - public List getEndVertexCollectionRestriction() { - return endVertexCollectionRestriction; - } - - /** - * One or multiple vertex collection names. Only vertices from these - * collections will be considered as end vertex of a path. - * - * @param endVertexCollectionRestriction - * @return this - */ - public ShortestPathOptions setEndVertexCollectionRestriction(List endVertexCollectionRestriction) { - this.endVertexCollectionRestriction = endVertexCollectionRestriction; - return this; - } - - /** - * The name of the attribute of the edges containing the length as a string. - * - * @return The name of the attribute - */ - public String getWeight() { - return weight; - } - - /** - * The name of the attribute of the edges containing the length as a string. - * - * @param weight - * @return this - */ - public ShortestPathOptions setWeight(String weight) { - this.weight = weight; - return this; - } - - /** - * Only used with the option weight. If an edge does not have the attribute - * named as defined in option weight this default is used as length. If no - * default is supplied the default would be positive Infinity so the path - * could not be calculated. - * - * @return a default weight - */ - public Long getDefaultWeight() { - return defaultWeight; - } - - /** - * Only used with the option weight. If an edge does not have the attribute - * named as defined in option weight this default is used as length. If no - * default is supplied the default would be positive Infinity so the path - * could not be calculated. - * - * @param defaultWeight - * @return this - */ - public ShortestPathOptions setDefaultWeight(Long defaultWeight) { - this.defaultWeight = defaultWeight; - return this; - } - - /** - * Get include data - * - * @return returns true, if the return values are compatible with older - * versions of AnrangoDB - */ - public Boolean getIncludeData() { - return includeData; - } - - /** - * set include data to be compatible with older versions of AnrangoDB - * - * @param includeData - * - * @since ArangoDB 2.6 - */ - public ShortestPathOptions setIncludeData(Boolean includeData) { - this.includeData = includeData; - return this; - } -} diff --git a/src/main/java/com/arangodb/util/StringUtils.java b/src/main/java/com/arangodb/util/StringUtils.java deleted file mode 100644 index dea4b6618..000000000 --- a/src/main/java/com/arangodb/util/StringUtils.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Copyright (C) 2012 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.util; - -import java.io.UnsupportedEncodingException; -import java.net.URLEncoder; -import java.util.Arrays; -import java.util.Collection; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * @author tamtam180 - kirscheless at gmail.com - * - */ -public class StringUtils { - - private static Logger logger = LoggerFactory.getLogger(StringUtils.class); - - private StringUtils() { - // this is a helper class - } - - public static String encodeUrl(String text) { - if (text != null) { - try { - return URLEncoder.encode(text, "UTF-8"); - } catch (UnsupportedEncodingException e) { - logger.error("could not encode an URL", e); - } - } - return null; - } - - public static boolean isNotEmpty(String str) { - return str != null && str.length() > 0; - } - - public static boolean isEmpty(String str) { - return str == null || str.length() == 0; - } - - public static boolean isCurlyBracketStart(String text) { - - if (text == null || "".equals(text)) { - return false; - } - - int i = 0; - while (i < text.length() && Character.isWhitespace(text.charAt(i))) { - i++; - } - return i < text.length() && text.charAt(i) == '{'; - - } - - public static String join(String... params) { - if (params == null) { - return null; - } - return join(false, Arrays.asList(params)); - } - - public static String join(boolean endSlash, Collection paths) { - if (CollectionUtils.isNotEmpty(paths)) { - return joinCollection(endSlash, paths); - } - return null; - } - - private static String joinCollection(boolean endSlash, Collection paths) { - boolean prevLastSlash = false; - StringBuilder buffer = new StringBuilder(); - for (String param : paths) { - if (param == null) - continue; - if (!prevLastSlash && !param.startsWith("/")) { - buffer.append('/'); - } - if (prevLastSlash && param.startsWith("/")) { - buffer.append(param.substring(1)); - } else { - buffer.append(param); - } - prevLastSlash = param.endsWith("/"); - } - if (endSlash && !prevLastSlash) { - buffer.append('/'); - } - return buffer.toString(); - } - -} diff --git a/src/main/java/com/arangodb/util/TraversalQueryOptions.java b/src/main/java/com/arangodb/util/TraversalQueryOptions.java deleted file mode 100644 index b8572d360..000000000 --- a/src/main/java/com/arangodb/util/TraversalQueryOptions.java +++ /dev/null @@ -1,382 +0,0 @@ -package com.arangodb.util; - -import java.util.HashMap; -import java.util.Map; - -import com.arangodb.Direction; -import com.arangodb.InternalTraversalDriver.ItemOrder; -import com.arangodb.InternalTraversalDriver.Order; -import com.arangodb.InternalTraversalDriver.Strategy; -import com.arangodb.InternalTraversalDriver.Uniqueness; - -public class TraversalQueryOptions extends AbstractOptions implements OptionsInterface { - - // (optional) 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. - private String graphName; - - // (optional) name of the collection that contains the edges. - private String edgeCollection; - - // id of the startVertex, e.g. "users/foo". - private String startVertex; - - // (optional, default is to include all nodes): body (JavaScript code) of - // custom filter function function - private String filter; - - // (optional, ANDed with any existing filters): visits only nodes in at - // least the given depth - private Long minDepth; - - // (optional, ANDed with any existing filters): visits only nodes in at most - // the given depth - private Long maxDepth; - - // (optional): body (JavaScript) code of custom visitor function - private String visitor; - - // (optional): direction for traversal - private Direction direction; - - // (optional): body (JavaScript) code of custom result initialisation - // function - private String init; - - // (optional): body (JavaScript) code of custom expander function - private String expander; - - // (optional): body (JavaScript) code of a custom comparison function - private String sort; - - // (optional): traversal strategy - private Strategy strategy; - - // (optional): traversal order - private Order order; - - // (optional): item iteration order - private ItemOrder itemOrder; - - // (optional): specifies uniqueness for vertices visited if set - private Uniqueness verticesUniqueness; - - // (optional): specifies uniqueness for edges visited if set - private Uniqueness edgesUniqueness; - - // (optional): Maximum number of iterations in each traversal - private Long maxIterations; - - public String getGraphName() { - return graphName; - } - - /** - * Set the (optional) 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. - * - * @param graphName - * @return this - */ - public TraversalQueryOptions setGraphName(String graphName) { - this.graphName = graphName; - return this; - } - - public String getEdgeCollection() { - return edgeCollection; - } - - /** - * Set (optional) name of the collection that contains the edges. - * - * @param edgeCollection - * @return this - */ - public TraversalQueryOptions setEdgeCollection(String edgeCollection) { - this.edgeCollection = edgeCollection; - return this; - } - - public String getStartVertex() { - return startVertex; - } - - /** - * Set id of the startVertex, e.g. "users/foo". - * - * @param startVertex - * @return this - */ - public TraversalQueryOptions setStartVertex(String startVertex) { - this.startVertex = startVertex; - return this; - } - - public String getFilter() { - return filter; - } - - /** - * Set a filter. - * - * (optional, default is to include all nodes): body (JavaScript code) of - * custom filter function function - * - * @param filter - * @return this - */ - public TraversalQueryOptions setFilter(String filter) { - this.filter = filter; - return this; - } - - public Long getMinDepth() { - return minDepth; - } - - /** - * Set a minimal depth. - * - * (optional, ANDed with any existing filters): visits only nodes in at - * least the given depth - * - * @param minDepth - * @return this - */ - public TraversalQueryOptions setMinDepth(Long minDepth) { - this.minDepth = minDepth; - return this; - } - - public Long getMaxDepth() { - return maxDepth; - } - - /** - * Set a maximal depth. - * - * (optional, ANDed with any existing filters): visits only nodes in at most - * the given depth - * - * @param maxDepth - * @return this - */ - public TraversalQueryOptions setMaxDepth(Long maxDepth) { - this.maxDepth = maxDepth; - return this; - } - - public String getVisitor() { - return visitor; - } - - /** - * Set visitor function. - * - * (optional): body (JavaScript) code of custom visitor function - * - * @param visitor - * @return this - */ - public TraversalQueryOptions setVisitor(String visitor) { - this.visitor = visitor; - return this; - } - - public Direction getDirection() { - return direction; - } - - /** - * Set (optional) direction for traversal - * - * @param direction - * @return this - */ - public TraversalQueryOptions setDirection(Direction direction) { - this.direction = direction; - return this; - } - - public String getInit() { - return init; - } - - /** - * Set an initialisation function. - * - * (optional): body (JavaScript) code of custom result initialisation - * function - * - * @param init - * @return this - */ - public TraversalQueryOptions setInit(String init) { - this.init = init; - return this; - } - - public String getExpander() { - return expander; - } - - /** - * Set an expander function. - * - * (optional): body (JavaScript) code of custom expander function - * - * @param expander - * @return this - */ - public TraversalQueryOptions setExpander(String expander) { - this.expander = expander; - return this; - } - - public String getSort() { - return sort; - } - - /** - * Set a comparison function. - * - * (optional): body (JavaScript) code of a custom comparison function - * - * @param sort - * @return this - */ - public TraversalQueryOptions setSort(String sort) { - this.sort = sort; - return this; - } - - public Strategy getStrategy() { - return strategy; - } - - /** - * Set (optional) traversal strategy. - * - * @param strategy - * @return this - */ - public TraversalQueryOptions setStrategy(Strategy strategy) { - this.strategy = strategy; - return this; - } - - public Order getOrder() { - return order; - } - - /** - * Set the (optional) traversal order - * - * @param order - * @return this - */ - public TraversalQueryOptions setOrder(Order order) { - this.order = order; - return this; - } - - public ItemOrder getItemOrder() { - return itemOrder; - } - - /** - * Set the (optional) item iteration order - * - * @param itemOrder - * @return this - */ - public TraversalQueryOptions setItemOrder(ItemOrder itemOrder) { - this.itemOrder = itemOrder; - return this; - } - - public Uniqueness getVerticesUniqueness() { - return verticesUniqueness; - } - - /** - * Set the (optional) uniqueness type for vertices visited if set - * - * @param verticesUniqueness - * @return this - */ - public TraversalQueryOptions setVerticesUniqueness(Uniqueness verticesUniqueness) { - this.verticesUniqueness = verticesUniqueness; - return this; - } - - public Uniqueness getEdgesUniqueness() { - return edgesUniqueness; - } - - /** - * Set the (optional) uniqueness type for edges visited if set - * - * @param edgesUniqueness - * @return this - */ - public TraversalQueryOptions setEdgesUniqueness(Uniqueness edgesUniqueness) { - this.edgesUniqueness = edgesUniqueness; - return this; - } - - public Long getMaxIterations() { - return maxIterations; - } - - /** - * Set the (optional) maximum number of iterations in each traversal - * - * @param maxIterations - * @return this - */ - public TraversalQueryOptions setMaxIterations(Long maxIterations) { - this.maxIterations = maxIterations; - return this; - } - - @Override - public Map toMap() { - Map object = new HashMap(); - - putAttribute(object, "graphName", graphName); - putAttribute(object, "edgeCollection", edgeCollection); - putAttribute(object, "startVertex", startVertex); - putAttribute(object, "filter", filter); - - putAttribute(object, "minDepth", minDepth); - putAttribute(object, "maxDepth", maxDepth); - putAttribute(object, "visitor", visitor); - putAttributeToLower(object, "direction", direction); - - putAttribute(object, "init", init); - putAttribute(object, "expander", expander); - putAttribute(object, "sort", sort); - - putAttributeToLower(object, "strategy", strategy); - putAttributeToLower(object, "order", order); - putAttributeToLower(object, "itemOrder", itemOrder); - - if (verticesUniqueness != null || edgesUniqueness != null) { - Map uniqueness = new HashMap(); - - putAttributeToLower(uniqueness, "vertices", verticesUniqueness); - putAttributeToLower(uniqueness, "edges", edgesUniqueness); - - object.put("uniqueness", uniqueness); - } - - putAttribute(object, "maxIterations", maxIterations); - - return object; - } - -} diff --git a/src/main/java/com/arangodb/velocypack/ArrayIterator.java b/src/main/java/com/arangodb/velocypack/ArrayIterator.java new file mode 100644 index 000000000..f2822c5c0 --- /dev/null +++ b/src/main/java/com/arangodb/velocypack/ArrayIterator.java @@ -0,0 +1,56 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.velocypack; + +import java.util.NoSuchElementException; + +import com.arangodb.velocypack.exception.VPackValueTypeException; + +/** + * @author Mark - mark at arangodb.com + * + */ +public class ArrayIterator extends SliceIterator { + + public ArrayIterator(final VPackSlice slice) throws VPackValueTypeException { + super(slice); + if (!slice.isArray()) { + throw new VPackValueTypeException(ValueType.ARRAY); + } + } + + @Override + public VPackSlice next() { + final VPackSlice next; + if (hasNext()) { + next = slice.get((int) position++); + } else { + throw new NoSuchElementException(); + } + return next; + } + + @Override + public void remove() { + throw new UnsupportedOperationException(); + } + +} diff --git a/src/main/java/com/arangodb/velocypack/ObjectIterator.java b/src/main/java/com/arangodb/velocypack/ObjectIterator.java new file mode 100644 index 000000000..a99785bac --- /dev/null +++ b/src/main/java/com/arangodb/velocypack/ObjectIterator.java @@ -0,0 +1,93 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.velocypack; + +import java.util.Map.Entry; +import java.util.NoSuchElementException; + +import com.arangodb.velocypack.exception.VPackKeyTypeException; +import com.arangodb.velocypack.exception.VPackNeedAttributeTranslatorException; +import com.arangodb.velocypack.exception.VPackValueTypeException; + +/** + * @author Mark - mark at arangodb.com + * + */ +public class ObjectIterator extends SliceIterator> { + + public ObjectIterator(final VPackSlice slice) throws VPackValueTypeException { + super(slice); + if (!slice.isObject()) { + throw new VPackValueTypeException(ValueType.OBJECT); + } + if (size > 0) { + final byte head = slice.head(); + if (head == 0x14) { + current = slice.keyAt(0).getStart(); + } else { + current = slice.getStart() + slice.findDataOffset(); + } + } + } + + @Override + public Entry next() { + if (position++ > 0) { + if (position <= size && current != 0) { + // skip over key + current += getCurrent().getByteSize(); + // skip over value + current += getCurrent().getByteSize(); + } else { + throw new NoSuchElementException(); + } + } + final VPackSlice currentField = getCurrent(); + return new Entry() { + @Override + public VPackSlice setValue(final VPackSlice value) { + throw new UnsupportedOperationException(); + } + + @Override + public VPackSlice getValue() { + return new VPackSlice(currentField.getBuffer(), currentField.getStart() + currentField.getByteSize()); + } + + @Override + public String getKey() { + try { + return currentField.makeKey().getAsString(); + } catch (final VPackKeyTypeException e) { + throw new NoSuchElementException(); + } catch (final VPackNeedAttributeTranslatorException e) { + throw new NoSuchElementException(); + } + } + }; + } + + @Override + public void remove() { + throw new UnsupportedOperationException(); + } + +} diff --git a/src/main/java/com/arangodb/velocypack/SliceIterator.java b/src/main/java/com/arangodb/velocypack/SliceIterator.java new file mode 100644 index 000000000..3e6c817db --- /dev/null +++ b/src/main/java/com/arangodb/velocypack/SliceIterator.java @@ -0,0 +1,54 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.velocypack; + +import java.util.Iterator; + +import com.arangodb.velocypack.exception.VPackValueTypeException; + +/** + * @author Mark - mark at arangodb.com + * + */ +public abstract class SliceIterator implements Iterator { + + protected final VPackSlice slice; + protected final long size; + protected long position; + protected long current; + + protected SliceIterator(final VPackSlice slice) throws VPackValueTypeException { + super(); + this.slice = slice; + size = slice.getLength(); + position = 0; + } + + @Override + public boolean hasNext() { + return position < size; + } + + protected VPackSlice getCurrent() { + return new VPackSlice(slice.getBuffer(), (int) current); + } + +} diff --git a/src/main/java/com/arangodb/velocypack/Type.java b/src/main/java/com/arangodb/velocypack/Type.java new file mode 100644 index 000000000..e7964edf0 --- /dev/null +++ b/src/main/java/com/arangodb/velocypack/Type.java @@ -0,0 +1,55 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.velocypack; + +import java.lang.reflect.ParameterizedType; + +/** + * @author Mark - mark at arangodb.com + * + */ +public class Type { + + private final java.lang.reflect.Type type; + + protected Type() { + super(); + type = getTypeParameter(getClass()); + } + + protected Type(final java.lang.reflect.Type type) { + super(); + this.type = type; + } + + private static java.lang.reflect.Type getTypeParameter(final Class clazz) { + final java.lang.reflect.Type superclass = clazz.getGenericSuperclass(); + if (superclass instanceof Class) { + throw new RuntimeException("Missing type parameter."); + } + return ParameterizedType.class.cast(superclass).getActualTypeArguments()[0]; + } + + public java.lang.reflect.Type getType() { + return type; + } + +} diff --git a/src/main/java/com/arangodb/velocypack/VPack.java b/src/main/java/com/arangodb/velocypack/VPack.java new file mode 100644 index 000000000..b5fdb3c8c --- /dev/null +++ b/src/main/java/com/arangodb/velocypack/VPack.java @@ -0,0 +1,643 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.velocypack; + +import java.lang.reflect.Array; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.util.Collection; +import java.util.Date; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +import com.arangodb.velocypack.VPackBuilder.BuilderOptions; +import com.arangodb.velocypack.exception.VPackException; +import com.arangodb.velocypack.exception.VPackParserException; +import com.arangodb.velocypack.internal.DefaultVPackBuilderOptions; +import com.arangodb.velocypack.internal.VPackCache; +import com.arangodb.velocypack.internal.VPackCache.FieldInfo; +import com.arangodb.velocypack.internal.VPackDeserializers; +import com.arangodb.velocypack.internal.VPackInstanceCreators; +import com.arangodb.velocypack.internal.VPackKeyMapAdapters; +import com.arangodb.velocypack.internal.VPackSerializers; + +/** + * @author Mark - mark at arangodb.com + * + */ +@SuppressWarnings({ "unchecked", "rawtypes" }) +public class VPack { + + private static final String ATTR_KEY = "key"; + private static final String ATTR_VALUE = "value"; + + private final Map> serializers; + private final Map> deserializers; + private final Map>> deserializersByName; + private final Map> instanceCreators; + private final Map> keyMapAdapters; + + private final BuilderOptions builderOptions; + private final VPackCache cache; + private final VPackSerializationContext serializationContext; + private final VPackDeserializationContext deserializationContext; + private final boolean serializeNullValues; + + public static class Builder { + private final Map> serializers; + private final Map> deserializers; + private final Map>> deserializersByName; + private final Map> instanceCreators; + private final BuilderOptions builderOptions; + private boolean serializeNullValues; + private VPackFieldNamingStrategy fieldNamingStrategy; + + public Builder() { + super(); + serializers = new HashMap>(); + deserializers = new HashMap>(); + deserializersByName = new HashMap>>(); + instanceCreators = new HashMap>(); + builderOptions = new DefaultVPackBuilderOptions(); + serializeNullValues = false; + + instanceCreators.put(Collection.class, VPackInstanceCreators.COLLECTION); + instanceCreators.put(List.class, VPackInstanceCreators.LIST); + instanceCreators.put(Set.class, VPackInstanceCreators.SET); + instanceCreators.put(Map.class, VPackInstanceCreators.MAP); + + serializers.put(String.class, VPackSerializers.STRING); + serializers.put(Boolean.class, VPackSerializers.BOOLEAN); + serializers.put(boolean.class, VPackSerializers.BOOLEAN); + serializers.put(Integer.class, VPackSerializers.INTEGER); + serializers.put(int.class, VPackSerializers.INTEGER); + serializers.put(Long.class, VPackSerializers.LONG); + serializers.put(long.class, VPackSerializers.LONG); + serializers.put(Short.class, VPackSerializers.SHORT); + serializers.put(short.class, VPackSerializers.SHORT); + serializers.put(Double.class, VPackSerializers.DOUBLE); + serializers.put(double.class, VPackSerializers.DOUBLE); + serializers.put(Float.class, VPackSerializers.FLOAT); + serializers.put(float.class, VPackSerializers.FLOAT); + serializers.put(BigInteger.class, VPackSerializers.BIG_INTEGER); + serializers.put(BigDecimal.class, VPackSerializers.BIG_DECIMAL); + serializers.put(Number.class, VPackSerializers.NUMBER); + serializers.put(Character.class, VPackSerializers.CHARACTER); + serializers.put(char.class, VPackSerializers.CHARACTER); + serializers.put(Date.class, VPackSerializers.DATE); + serializers.put(java.sql.Date.class, VPackSerializers.SQL_DATE); + serializers.put(java.sql.Timestamp.class, VPackSerializers.SQL_TIMESTAMP); + serializers.put(VPackSlice.class, VPackSerializers.VPACK); + + deserializers.put(String.class, VPackDeserializers.STRING); + deserializers.put(Boolean.class, VPackDeserializers.BOOLEAN); + deserializers.put(boolean.class, VPackDeserializers.BOOLEAN); + deserializers.put(Integer.class, VPackDeserializers.INTEGER); + deserializers.put(int.class, VPackDeserializers.INTEGER); + deserializers.put(Long.class, VPackDeserializers.LONG); + deserializers.put(long.class, VPackDeserializers.LONG); + deserializers.put(Short.class, VPackDeserializers.SHORT); + deserializers.put(short.class, VPackDeserializers.SHORT); + deserializers.put(Double.class, VPackDeserializers.DOUBLE); + deserializers.put(double.class, VPackDeserializers.DOUBLE); + deserializers.put(Float.class, VPackDeserializers.FLOAT); + deserializers.put(float.class, VPackDeserializers.FLOAT); + deserializers.put(BigInteger.class, VPackDeserializers.BIG_INTEGER); + deserializers.put(BigDecimal.class, VPackDeserializers.BIG_DECIMAL); + deserializers.put(Number.class, VPackDeserializers.NUMBER); + deserializers.put(Character.class, VPackDeserializers.CHARACTER); + deserializers.put(char.class, VPackDeserializers.CHARACTER); + deserializers.put(Date.class, VPackDeserializers.DATE); + deserializers.put(java.sql.Date.class, VPackDeserializers.SQL_DATE); + deserializers.put(java.sql.Timestamp.class, VPackDeserializers.SQL_TIMESTAMP); + deserializers.put(VPackSlice.class, VPackDeserializers.VPACK); + } + + public VPack.Builder registerSerializer(final Type type, final VPackSerializer serializer) { + serializers.put(type, serializer); + return this; + } + + public VPack.Builder registerDeserializer(final Type type, final VPackDeserializer deserializer) { + deserializers.put(type, deserializer); + return this; + } + + public VPack.Builder registerDeserializer( + final String fieldName, + final Type type, + final VPackDeserializer deserializer) { + Map> byName = deserializersByName.get(fieldName); + if (byName == null) { + byName = new HashMap>(); + deserializersByName.put(fieldName, byName); + } + byName.put(type, deserializer); + return this; + } + + public VPack.Builder regitserInstanceCreator(final Type type, final VPackInstanceCreator creator) { + instanceCreators.put(type, creator); + return this; + } + + public VPack.Builder buildUnindexedArrays(final boolean buildUnindexedArrays) { + builderOptions.setBuildUnindexedArrays(buildUnindexedArrays); + return this; + } + + public VPack.Builder buildUnindexedObjects(final boolean buildUnindexedObjects) { + builderOptions.setBuildUnindexedObjects(buildUnindexedObjects); + return this; + } + + public VPack.Builder serializeNullValues(final boolean serializeNullValues) { + this.serializeNullValues = serializeNullValues; + return this; + } + + public VPack.Builder fieldNamingStrategy(final VPackFieldNamingStrategy fieldNamingStrategy) { + this.fieldNamingStrategy = fieldNamingStrategy; + return this; + } + + public VPack build() { + return new VPack(serializers, deserializers, instanceCreators, builderOptions, serializeNullValues, + fieldNamingStrategy, deserializersByName); + } + + } + + private VPack(final Map> serializers, final Map> deserializers, + final Map> instanceCreators, final BuilderOptions builderOptions, + final boolean serializeNullValues, final VPackFieldNamingStrategy fieldNamingStrategy, + final Map>> deserializersByName) { + super(); + this.serializers = serializers; + this.deserializers = deserializers; + this.instanceCreators = instanceCreators; + this.builderOptions = builderOptions; + this.serializeNullValues = serializeNullValues; + this.deserializersByName = deserializersByName; + keyMapAdapters = new HashMap>(); + cache = new VPackCache(fieldNamingStrategy); + serializationContext = new VPackSerializationContext() { + @Override + public void serialize(final VPackBuilder builder, final String attribute, final Object entity) + throws VPackParserException { + VPack.this.serialize(attribute, entity, entity.getClass(), builder, new HashMap()); + } + }; + deserializationContext = new VPackDeserializationContext() { + @Override + public T deserialize(final VPackSlice vpack, final Class type) throws VPackParserException { + return VPack.this.deserialize(vpack, type); + } + }; + keyMapAdapters.put(String.class, VPackKeyMapAdapters.STRING); + keyMapAdapters.put(Boolean.class, VPackKeyMapAdapters.BOOLEAN); + keyMapAdapters.put(Integer.class, VPackKeyMapAdapters.INTEGER); + keyMapAdapters.put(Long.class, VPackKeyMapAdapters.LONG); + keyMapAdapters.put(Short.class, VPackKeyMapAdapters.SHORT); + keyMapAdapters.put(Double.class, VPackKeyMapAdapters.DOUBLE); + keyMapAdapters.put(Float.class, VPackKeyMapAdapters.FLOAT); + keyMapAdapters.put(BigInteger.class, VPackKeyMapAdapters.BIG_INTEGER); + keyMapAdapters.put(BigDecimal.class, VPackKeyMapAdapters.BIG_DECIMAL); + keyMapAdapters.put(Number.class, VPackKeyMapAdapters.NUMBER); + keyMapAdapters.put(Character.class, VPackKeyMapAdapters.CHARACTER); + } + + public T deserialize(final VPackSlice vpack, final Type type) throws VPackParserException { + if (type == VPackSlice.class) { + return (T) vpack; + } + final T entity; + try { + entity = (T) getValue(null, vpack, type, null); + } catch (final Exception e) { + throw new VPackParserException(e); + } + return entity; + } + + private VPackDeserializer getDeserializer(final String fieldName, final Type type) { + VPackDeserializer deserializer = null; + final Map> byName = deserializersByName.get(fieldName); + if (byName != null) { + deserializer = byName.get(type); + } + if (deserializer == null) { + deserializer = deserializers.get(type); + } + return deserializer; + } + + private T deserializeObject( + final VPackSlice parent, + final VPackSlice vpack, + final Type type, + final String fieldName) throws InstantiationException, IllegalAccessException, NoSuchMethodException, + InvocationTargetException, VPackException { + final T entity; + final VPackDeserializer deserializer = getDeserializer(fieldName, type); + if (deserializer != null) { + entity = ((VPackDeserializer) deserializer).deserialize(parent, vpack, deserializationContext); + } else if (type == Object.class) { + entity = (T) getValue(parent, vpack, getType(vpack), fieldName); + } else { + entity = createInstance(type); + deserializeFields(entity, vpack); + } + return entity; + } + + private Type getType(final VPackSlice vpack) { + final Type type; + if (vpack.isObject()) { + type = Map.class; + } else if (vpack.isString()) { + type = String.class; + } else if (vpack.isBoolean()) { + type = Boolean.class; + } else if (vpack.isArray()) { + type = Collection.class; + } else if (vpack.isDate()) { + type = Date.class; + } else if (vpack.isDouble()) { + type = Double.class; + } else if (vpack.isNumber()) { + type = Number.class; + } else if (vpack.isCustom()) { + type = String.class; + } else { + type = null; + } + return type; + } + + private T createInstance(final Type type) throws InstantiationException, IllegalAccessException { + final T entity; + final VPackInstanceCreator creator = instanceCreators.get(type); + if (creator != null) { + entity = (T) creator.createInstance(); + } else if (type instanceof ParameterizedType) { + entity = createInstance(((ParameterizedType) type).getRawType()); + } else { + entity = ((Class) type).newInstance(); + } + return entity; + } + + private void deserializeFields(final Object entity, final VPackSlice vpack) throws NoSuchMethodException, + IllegalAccessException, InvocationTargetException, InstantiationException, VPackException { + final Map fields = cache.getFields(entity.getClass()); + for (final Iterator> iterator = vpack.objectIterator(); iterator.hasNext();) { + final Entry next = iterator.next(); + final FieldInfo fieldInfo = fields.get(next.getKey()); + if (fieldInfo != null && fieldInfo.isDeserialize()) { + deserializeField(vpack, next.getValue(), entity, fieldInfo); + } + } + } + + private void deserializeField( + final VPackSlice parent, + final VPackSlice vpack, + final Object entity, + final FieldInfo fieldInfo) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, + InstantiationException, VPackException { + if (!vpack.isNone()) { + final Object value = getValue(parent, vpack, fieldInfo.getType(), fieldInfo.getFieldName()); + fieldInfo.set(entity, value); + } + } + + private Object getValue( + final VPackSlice parent, + final VPackSlice vpack, + final Type type, + final String fieldName) throws InstantiationException, IllegalAccessException, NoSuchMethodException, + InvocationTargetException, VPackException { + final Object value; + if (vpack.isNull()) { + value = null; + } else { + final VPackDeserializer deserializer = getDeserializer(fieldName, type); + if (deserializer != null) { + value = ((VPackDeserializer) deserializer).deserialize(parent, vpack, deserializationContext); + } else if (type instanceof ParameterizedType) { + final ParameterizedType pType = ParameterizedType.class.cast(type); + final Type rawType = pType.getRawType(); + if (Collection.class.isAssignableFrom((Class) rawType)) { + value = deserializeCollection(parent, vpack, type, pType.getActualTypeArguments()[0]); + } else if (Map.class.isAssignableFrom((Class) rawType)) { + final Type[] parameterizedTypes = pType.getActualTypeArguments(); + value = deserializeMap(parent, vpack, type, parameterizedTypes[0], parameterizedTypes[1]); + } else { + value = deserializeObject(parent, vpack, type, fieldName); + } + } else if (Collection.class.isAssignableFrom((Class) type)) { + value = deserializeCollection(parent, vpack, type, Object.class); + } else if (Map.class.isAssignableFrom((Class) type)) { + value = deserializeMap(parent, vpack, type, String.class, Object.class); + } else if (((Class) type).isArray()) { + value = deserializeArray(parent, vpack, type); + } else if (((Class) type).isEnum()) { + value = Enum.valueOf((Class) type, vpack.getAsString()); + } else { + value = deserializeObject(parent, vpack, type, fieldName); + } + } + return value; + } + + private Object deserializeArray(final VPackSlice parent, final VPackSlice vpack, final Type type) + throws InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException, + VPackException { + final int length = (int) vpack.getLength(); + final Class componentType = ((Class) type).getComponentType(); + final Object value = Array.newInstance(componentType, length); + for (int i = 0; i < length; i++) { + Array.set(value, i, getValue(parent, vpack.get(i), componentType, null)); + } + return value; + } + + private Object deserializeCollection( + final VPackSlice parent, + final VPackSlice vpack, + final Type type, + final Type contentType) throws InstantiationException, IllegalAccessException, NoSuchMethodException, + InvocationTargetException, VPackException { + final Collection value = (Collection) createInstance(type); + final long length = vpack.getLength(); + if (length > 0) { + for (int i = 0; i < length; i++) { + value.add(getValue(parent, vpack.get(i), contentType, null)); + } + } + return value; + } + + private Object deserializeMap( + final VPackSlice parent, + final VPackSlice vpack, + final Type type, + final Type keyType, + final Type valueType) throws InstantiationException, IllegalAccessException, NoSuchMethodException, + InvocationTargetException, VPackException { + final int length = (int) vpack.getLength(); + final Map value = (Map) createInstance(type); + if (length > 0) { + final VPackKeyMapAdapter keyMapAdapter = getKeyMapAdapter(keyType); + if (keyMapAdapter != null) { + for (final Iterator> iterator = vpack.objectIterator(); iterator.hasNext();) { + final Entry next = iterator.next(); + final Object name = keyMapAdapter.deserialize(next.getKey()); + value.put(name, getValue(vpack, next.getValue(), valueType, name.toString())); + } + } else { + for (int i = 0; i < vpack.getLength(); i++) { + final VPackSlice entry = vpack.get(i); + final Object mapKey = getValue(parent, entry.get(ATTR_KEY), keyType, null); + final Object mapValue = getValue(parent, entry.get(ATTR_VALUE), valueType, null); + value.put(mapKey, mapValue); + } + } + } + return value; + } + + public VPackSlice serialize(final Object entity) throws VPackParserException { + return serialize(entity, entity.getClass(), new HashMap()); + } + + public VPackSlice serialize(final Object entity, final Map additionalFields) + throws VPackParserException { + return serialize(entity, entity.getClass(), additionalFields); + } + + public VPackSlice serialize(final Object entity, final Type type) throws VPackParserException { + return serialize(entity, type, new HashMap()); + } + + public VPackSlice serialize(final Object entity, final Type type, final Map additionalFields) + throws VPackParserException { + if (type == VPackSlice.class) { + return (VPackSlice) entity; + } + final VPackBuilder builder = new VPackBuilder(builderOptions); + serialize(null, entity, type, builder, new HashMap(additionalFields)); + return builder.slice(); + } + + private void serialize( + final String name, + final Object entity, + final Type type, + final VPackBuilder builder, + final Map additionalFields) throws VPackParserException { + try { + addValue(name, type, entity, builder, null, additionalFields); + } catch (final Exception e) { + throw new VPackParserException(e); + } + } + + private void serializeObject( + final String name, + final Object entity, + final VPackBuilder builder, + final Map additionalFields) + throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, VPackException { + + final VPackSerializer serializer = serializers.get(entity.getClass()); + if (serializer != null) { + ((VPackSerializer) serializer).serialize(builder, name, entity, serializationContext); + } else { + builder.add(name, ValueType.OBJECT); + serializeFields(entity, builder, additionalFields); + if (!additionalFields.isEmpty()) { + additionalFields.clear(); + builder.close(true); + } else { + builder.close(false); + } + } + } + + private void serializeFields( + final Object entity, + final VPackBuilder builder, + final Map additionalFields) + throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, VPackException { + final Map fields = cache.getFields(entity.getClass()); + for (final FieldInfo fieldInfo : fields.values()) { + if (fieldInfo.isSerialize()) { + serializeField(entity, builder, fieldInfo, additionalFields); + } + } + for (final Entry entry : additionalFields.entrySet()) { + final String key = entry.getKey(); + if (!fields.containsKey(key)) { + final Object value = entry.getValue(); + addValue(key, value != null ? value.getClass() : null, value, builder, null, additionalFields); + } + } + } + + private void serializeField( + final Object entity, + final VPackBuilder builder, + final FieldInfo fieldInfo, + final Map additionalFields) + throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, VPackException { + + final String fieldName = fieldInfo.getFieldName(); + final Type type = fieldInfo.getType(); + final Object value = fieldInfo.get(entity); + addValue(fieldName, type, value, builder, fieldInfo, additionalFields); + } + + private void addValue( + final String name, + final Type type, + final Object value, + final VPackBuilder builder, + final FieldInfo fieldInfo, + final Map additionalFields) + throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, VPackException { + + if (value == null) { + if (serializeNullValues) { + builder.add(name, ValueType.NULL); + } + } else { + final VPackSerializer serializer = serializers.get(type); + if (serializer != null) { + ((VPackSerializer) serializer).serialize(builder, name, value, serializationContext); + } else if (type instanceof ParameterizedType) { + final ParameterizedType pType = ParameterizedType.class.cast(type); + final Type rawType = pType.getRawType(); + if (Iterable.class.isAssignableFrom((Class) rawType)) { + serializeIterable(name, value, builder, additionalFields); + } else if (Map.class.isAssignableFrom((Class) rawType)) { + serializeMap(name, value, builder, pType.getActualTypeArguments()[0], additionalFields); + } else { + serializeObject(name, value, builder, additionalFields); + } + } else if (Iterable.class.isAssignableFrom((Class) type)) { + serializeIterable(name, value, builder, additionalFields); + } else if (Map.class.isAssignableFrom((Class) type)) { + serializeMap(name, value, builder, String.class, additionalFields); + } else if (((Class) type).isArray()) { + serializeArray(name, value, builder, additionalFields); + } else if (((Class) type).isEnum()) { + builder.add(name, Enum.class.cast(value).name()); + } else { + serializeObject(name, value, builder, additionalFields); + } + } + } + + private void serializeArray( + final String name, + final Object value, + final VPackBuilder builder, + final Map additionalFields) + throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, VPackException { + builder.add(name, ValueType.ARRAY); + for (int i = 0; i < Array.getLength(value); i++) { + final Object element = Array.get(value, i); + addValue(null, element.getClass(), element, builder, null, additionalFields); + } + builder.close(); + } + + private void serializeIterable( + final String name, + final Object value, + final VPackBuilder builder, + final Map additionalFields) + throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, VPackException { + builder.add(name, ValueType.ARRAY); + for (final Iterator iterator = Iterable.class.cast(value).iterator(); iterator.hasNext();) { + final Object element = iterator.next(); + addValue(null, element.getClass(), element, builder, null, additionalFields); + } + builder.close(); + } + + private void serializeMap( + final String name, + final Object value, + final VPackBuilder builder, + final Type keyType, + final Map additionalFields) + throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, VPackException { + final Map map = Map.class.cast(value); + if (map.size() > 0) { + final VPackKeyMapAdapter keyMapAdapter = getKeyMapAdapter(keyType); + if (keyMapAdapter != null) { + builder.add(name, ValueType.OBJECT); + final Set> entrySet = map.entrySet(); + for (final Entry entry : entrySet) { + final Object entryValue = entry.getValue(); + addValue(keyMapAdapter.serialize(entry.getKey()), + entryValue != null ? entryValue.getClass() : Object.class, entry.getValue(), builder, null, + additionalFields); + } + builder.close(); + } else { + builder.add(name, ValueType.ARRAY); + final Set> entrySet = map.entrySet(); + for (final Entry entry : entrySet) { + final String s = null; + builder.add(s, ValueType.OBJECT); + addValue(ATTR_KEY, entry.getKey().getClass(), entry.getKey(), builder, null, additionalFields); + addValue(ATTR_VALUE, entry.getValue().getClass(), entry.getValue(), builder, null, + additionalFields); + builder.close(); + } + builder.close(); + } + } else { + builder.add(name, ValueType.OBJECT); + builder.close(); + } + } + + private VPackKeyMapAdapter getKeyMapAdapter(final Type type) { + VPackKeyMapAdapter adapter = keyMapAdapters.get(type); + if (adapter == null && Enum.class.isAssignableFrom((Class) type)) { + adapter = VPackKeyMapAdapters.createEnumAdapter(type); + } + return (VPackKeyMapAdapter) adapter; + } + +} diff --git a/src/main/java/com/arangodb/velocypack/VPackAttributeTranslator.java b/src/main/java/com/arangodb/velocypack/VPackAttributeTranslator.java new file mode 100644 index 000000000..601655fac --- /dev/null +++ b/src/main/java/com/arangodb/velocypack/VPackAttributeTranslator.java @@ -0,0 +1,39 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.velocypack; + +import com.arangodb.velocypack.exception.VPackException; + +/** + * @author Mark - mark at arangodb.com + * + */ +public interface VPackAttributeTranslator { + + void add(String attribute, int key) throws VPackException; + + void seal() throws VPackException; + + VPackSlice translate(String attribute); + + VPackSlice translate(int key); + +} diff --git a/src/main/java/com/arangodb/velocypack/VPackBuilder.java b/src/main/java/com/arangodb/velocypack/VPackBuilder.java new file mode 100644 index 000000000..80fe26f85 --- /dev/null +++ b/src/main/java/com/arangodb/velocypack/VPackBuilder.java @@ -0,0 +1,1050 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.velocypack; + +import java.io.UnsupportedEncodingException; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.sql.Timestamp; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.Comparator; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import com.arangodb.velocypack.exception.VPackBuilderException; +import com.arangodb.velocypack.exception.VPackBuilderKeyAlreadyWrittenException; +import com.arangodb.velocypack.exception.VPackBuilderNeedOpenCompoundException; +import com.arangodb.velocypack.exception.VPackBuilderNeedOpenObjectException; +import com.arangodb.velocypack.exception.VPackBuilderNumberOutOfRangeException; +import com.arangodb.velocypack.exception.VPackBuilderUnexpectedValueException; +import com.arangodb.velocypack.exception.VPackKeyTypeException; +import com.arangodb.velocypack.exception.VPackNeedAttributeTranslatorException; +import com.arangodb.velocypack.exception.VPackValueTypeException; +import com.arangodb.velocypack.internal.DefaultVPackBuilderOptions; +import com.arangodb.velocypack.internal.Value; +import com.arangodb.velocypack.internal.util.NumberUtil; + +/** + * @author Mark - mark at arangodb.com + * + */ +public class VPackBuilder { + + private static final int INTEGER_BYTES = Integer.SIZE / Byte.SIZE; + private static final int LONG_BYTES = Long.SIZE / Byte.SIZE; + private static final int DOUBLE_BYTES = Double.SIZE / Byte.SIZE; + + public static interface BuilderOptions { + boolean isBuildUnindexedArrays(); + + void setBuildUnindexedArrays(boolean buildUnindexedArrays); + + boolean isBuildUnindexedObjects(); + + void setBuildUnindexedObjects(boolean buildUnindexedObjects); + } + + public static interface Appender { + void append(VPackBuilder builder, T value) throws VPackBuilderException; + } + + private static final Appender VALUE = new Appender() { + @Override + public void append(final VPackBuilder builder, final Value value) throws VPackBuilderException { + builder.set(value); + } + }; + private static final Appender VALUE_TYPE = new Appender() { + @Override + public void append(final VPackBuilder builder, final ValueType value) throws VPackBuilderException { + switch (value) { + case NULL: + builder.appendNull(); + break; + case ARRAY: + builder.addArray(false); + break; + case OBJECT: + builder.addObject(false); + break; + default: + throw new VPackValueTypeException(ValueType.ARRAY, ValueType.OBJECT, ValueType.NULL); + } + } + }; + private static final Appender BOOLEAN = new Appender() { + @Override + public void append(final VPackBuilder builder, final Boolean value) throws VPackBuilderException { + builder.appendBoolean(value); + } + }; + private static final Appender DOUBLE = new Appender() { + @Override + public void append(final VPackBuilder builder, final Double value) throws VPackBuilderException { + builder.appendDouble(value); + } + }; + private static final Appender FLOAT = new Appender() { + @Override + public void append(final VPackBuilder builder, final Float value) throws VPackBuilderException { + builder.appendDouble(value); + } + }; + private static final Appender BIG_DECIMAL = new Appender() { + @Override + public void append(final VPackBuilder builder, final BigDecimal value) throws VPackBuilderException { + builder.appendDouble(value.doubleValue()); + } + }; + private static final Appender LONG = new Appender() { + @Override + public void append(final VPackBuilder builder, final Long value) throws VPackBuilderException { + if (value <= 9 && value >= -6) { + builder.appendSmallInt(value); + } else { + builder.add((byte) 0x23); + builder.append(value, INTEGER_BYTES); + } + } + }; + private static final Appender INTEGER = new Appender() { + @Override + public void append(final VPackBuilder builder, final Integer value) throws VPackBuilderException { + if (value <= 9 && value >= -6) { + builder.appendSmallInt(value); + } else { + builder.add((byte) 0x23); + builder.append(value, INTEGER_BYTES); + } + } + }; + private static final Appender SHORT = new Appender() { + @Override + public void append(final VPackBuilder builder, final Short value) throws VPackBuilderException { + if (value <= 9 && value >= -6) { + builder.appendSmallInt(value); + } else { + builder.add((byte) 0x23); + builder.append(value, INTEGER_BYTES); + } + } + }; + private static final Appender BIG_INTEGER = new Appender() { + @Override + public void append(final VPackBuilder builder, final BigInteger value) throws VPackBuilderException { + if (value.longValue() <= 9 && value.longValue() >= -6) { + builder.appendSmallInt(value.longValue()); + } else { + builder.add((byte) 0x23); + builder.append(value, INTEGER_BYTES); + } + } + }; + private static final Appender DATE = new Appender() { + @Override + public void append(final VPackBuilder builder, final Date value) throws VPackBuilderException { + builder.appendDate(value); + } + }; + private static final Appender SQL_DATE = new Appender() { + @Override + public void append(final VPackBuilder builder, final java.sql.Date value) throws VPackBuilderException { + builder.appendSQLDate(value); + } + }; + private static final Appender SQL_TIMESTAMP = new Appender() { + @Override + public void append(final VPackBuilder builder, final Timestamp value) throws VPackBuilderException { + builder.appendSQLTimestamp(value); + } + }; + private static final Appender STRING = new Appender() { + @Override + public void append(final VPackBuilder builder, final String value) throws VPackBuilderException { + builder.appendString(value); + } + }; + private static final Appender CHARACTER = new Appender() { + @Override + public void append(final VPackBuilder builder, final Character value) throws VPackBuilderException { + builder.appendString(String.valueOf(value)); + } + }; + private static final Appender BYTE_ARRAY = new Appender() { + @Override + public void append(final VPackBuilder builder, final byte[] value) throws VPackBuilderException { + builder.appendBinary(value); + } + }; + private static final Appender VPACK = new Appender() { + @Override + public void append(final VPackBuilder builder, final VPackSlice value) throws VPackBuilderException { + builder.appendVPack(value); + } + }; + + private byte[] buffer; // Here we collect the result + private int size; + private final List stack; // Start positions of open + // objects/arrays + private final Map> index; // Indices for starts + // of + // subindex + private boolean keyWritten; // indicates that in the current object the key + // has been written but the value not yet + private final BuilderOptions options; + + public VPackBuilder() { + this(new DefaultVPackBuilderOptions()); + } + + public VPackBuilder(final BuilderOptions options) { + super(); + this.options = options; + size = 0; + buffer = new byte[10]; + stack = new ArrayList(); + index = new HashMap>(); + } + + public BuilderOptions getOptions() { + return options; + } + + private void add(final byte b) { + ensureCapacity(size + 1); + buffer[size++] = b; + } + + private void addUnchecked(final byte b) { + buffer[size++] = b; + } + + private void remove(final int index) { + final int numMoved = size - index - 1; + if (numMoved > 0) { + System.arraycopy(buffer, index + 1, buffer, index, numMoved); + } + buffer[--size] = 0; + } + + private void ensureCapacity(final int minCapacity) { + final int oldCapacity = buffer.length; + if (minCapacity > oldCapacity) { + final byte[] oldData = buffer; + int newCapacity = (oldCapacity * 3) / 2 + 1; + if (newCapacity < minCapacity) { + newCapacity = minCapacity; + } + buffer = Arrays.copyOf(oldData, newCapacity); + } + } + + public VPackBuilder add(final ValueType value) throws VPackBuilderException { + return addInternal(VALUE_TYPE, value); + } + + public VPackBuilder add(final ValueType value, final boolean unindexed) throws VPackBuilderException { + return addInternal(VALUE, new Value(value, unindexed)); + } + + public VPackBuilder add(final Boolean value) throws VPackBuilderException { + return addInternal(BOOLEAN, value); + } + + public VPackBuilder add(final Double value) throws VPackBuilderException { + return addInternal(DOUBLE, value); + } + + public VPackBuilder add(final Float value) throws VPackBuilderException { + return addInternal(FLOAT, value); + } + + public VPackBuilder add(final BigDecimal value) throws VPackBuilderException { + return addInternal(BIG_DECIMAL, value); + } + + public VPackBuilder add(final Long value) throws VPackBuilderException { + return addInternal(LONG, value); + } + + public VPackBuilder add(final Long value, final ValueType type) throws VPackBuilderException { + return addInternal(VALUE, new Value(value, type)); + } + + public VPackBuilder add(final Integer value) throws VPackBuilderException { + return addInternal(INTEGER, value); + } + + public VPackBuilder add(final Short value) throws VPackBuilderException { + return addInternal(SHORT, value); + } + + public VPackBuilder add(final BigInteger value) throws VPackBuilderException { + return addInternal(BIG_INTEGER, value); + } + + public VPackBuilder add(final BigInteger value, final ValueType type) throws VPackBuilderException { + return addInternal(VALUE, new Value(value, type)); + } + + public VPackBuilder add(final Date value) throws VPackBuilderException { + return addInternal(DATE, value); + } + + public VPackBuilder add(final java.sql.Date value) throws VPackBuilderException { + return addInternal(SQL_DATE, value); + } + + public VPackBuilder add(final java.sql.Timestamp value) throws VPackBuilderException { + return addInternal(SQL_TIMESTAMP, value); + } + + public VPackBuilder add(final String value) throws VPackBuilderException { + return addInternal(STRING, value); + } + + public VPackBuilder add(final Character value) throws VPackBuilderException { + return addInternal(CHARACTER, value); + } + + public VPackBuilder add(final byte[] value) throws VPackBuilderException { + return addInternal(BYTE_ARRAY, value); + } + + public VPackBuilder add(final VPackSlice value) throws VPackBuilderException { + return addInternal(VPACK, value); + } + + public VPackBuilder add(final String attribute, final ValueType value) throws VPackBuilderException { + return addInternal(attribute, VALUE_TYPE, value); + } + + public VPackBuilder add(final String attribute, final ValueType value, final boolean unindexed) + throws VPackBuilderException { + return addInternal(attribute, VALUE, new Value(value, unindexed)); + } + + public VPackBuilder add(final String attribute, final Boolean value) throws VPackBuilderException { + return addInternal(attribute, BOOLEAN, value); + } + + public VPackBuilder add(final String attribute, final Double value) throws VPackBuilderException { + return addInternal(attribute, DOUBLE, value); + } + + public VPackBuilder add(final String attribute, final Float value) throws VPackBuilderException { + return addInternal(attribute, FLOAT, value); + } + + public VPackBuilder add(final String attribute, final BigDecimal value) throws VPackBuilderException { + return addInternal(attribute, BIG_DECIMAL, value); + } + + public VPackBuilder add(final String attribute, final Long value) throws VPackBuilderException { + return addInternal(attribute, LONG, value); + } + + public VPackBuilder add(final String attribute, final Long value, final ValueType type) + throws VPackBuilderException { + return addInternal(attribute, VALUE, new Value(value, type)); + } + + public VPackBuilder add(final String attribute, final Integer value) throws VPackBuilderException { + return addInternal(attribute, INTEGER, value); + } + + public VPackBuilder add(final String attribute, final Short value) throws VPackBuilderException { + return addInternal(attribute, SHORT, value); + } + + public VPackBuilder add(final String attribute, final BigInteger value) throws VPackBuilderException { + return addInternal(attribute, BIG_INTEGER, value); + } + + public VPackBuilder add(final String attribute, final BigInteger value, final ValueType type) + throws VPackBuilderException { + return addInternal(attribute, VALUE, new Value(value, type)); + } + + public VPackBuilder add(final String attribute, final String value) throws VPackBuilderException { + return addInternal(attribute, STRING, value); + } + + public VPackBuilder add(final String attribute, final Character value) throws VPackBuilderException { + return addInternal(attribute, CHARACTER, value); + } + + public VPackBuilder add(final String attribute, final Date value) throws VPackBuilderException { + return addInternal(attribute, DATE, value); + } + + public VPackBuilder add(final String attribute, final java.sql.Date value) throws VPackBuilderException { + return addInternal(attribute, SQL_DATE, value); + } + + public VPackBuilder add(final String attribute, final java.sql.Timestamp value) throws VPackBuilderException { + return addInternal(attribute, SQL_TIMESTAMP, value); + } + + public VPackBuilder add(final String attribute, final byte[] value) throws VPackBuilderException { + return addInternal(attribute, BYTE_ARRAY, value); + } + + public VPackBuilder add(final String attribute, final VPackSlice value) throws VPackBuilderException { + return addInternal(attribute, VPACK, value); + } + + private VPackBuilder addInternal(final Appender appender, final T value) throws VPackBuilderException { + boolean haveReported = false; + if (!stack.isEmpty() && !keyWritten) { + reportAdd(); + haveReported = true; + } + try { + if (value == null) { + appendNull(); + } else { + appender.append(this, value); + } + } catch (final VPackBuilderException e) { + // clean up in case of an exception + if (haveReported) { + cleanupAdd(); + } + throw e; + } + return this; + } + + private VPackBuilder addInternal(final String attribute, final Appender appender, final T value) + throws VPackBuilderException { + if (attribute != null) { + boolean haveReported = false; + if (!stack.isEmpty()) { + final byte head = head(); + if (head != 0x0b && head != 0x14) { + throw new VPackBuilderNeedOpenObjectException(); + } + if (keyWritten) { + throw new VPackBuilderKeyAlreadyWrittenException(); + } + reportAdd(); + haveReported = true; + } + try { + if (VPackSlice.attributeTranslator != null) { + final VPackSlice translate = VPackSlice.attributeTranslator.translate(attribute); + if (translate != null) { + final byte[] trValue = translate.getRawVPack(); + ensureCapacity(size + trValue.length); + for (int i = 0; i < trValue.length; i++) { + addUnchecked(trValue[i]); + } + keyWritten = true; + if (value == null) { + appendNull(); + } else { + appender.append(this, value); + } + return this; + } + // otherwise fall through to regular behavior + } + STRING.append(this, attribute); + keyWritten = true; + if (value == null) { + appendNull(); + } else { + appender.append(this, value); + } + } catch (final VPackBuilderException e) { + // clean up in case of an exception + if (haveReported) { + cleanupAdd(); + } + throw e; + } finally { + keyWritten = false; + } + } else { + addInternal(appender, value); + } + return this; + } + + private void set(final Value item) throws VPackBuilderException { + final Class clazz = item.getClazz(); + switch (item.getType()) { + case NULL: + appendNull(); + break; + case ARRAY: + addArray(item.isUnindexed()); + break; + case OBJECT: + addObject(item.isUnindexed()); + break; + case SMALLINT: + final long vSmallInt = item.getNumber().longValue(); + if (vSmallInt < -6 || vSmallInt > 9) { + throw new VPackBuilderNumberOutOfRangeException(ValueType.SMALLINT); + } + appendSmallInt(vSmallInt); + break; + case INT: + final int length; + if (clazz == Long.class || clazz == BigInteger.class) { + add((byte) 0x27); + length = LONG_BYTES; + } else { + throw new VPackBuilderUnexpectedValueException(ValueType.INT, Long.class, Integer.class, + BigInteger.class, Short.class); + } + append(item.getNumber().longValue(), length); + break; + case UINT: + final BigInteger vUInt; + if (clazz == Long.class) { + vUInt = BigInteger.valueOf(item.getLong()); + } else if (clazz == BigInteger.class) { + vUInt = item.getBigInteger(); + } else { + throw new VPackBuilderUnexpectedValueException(ValueType.UINT, Long.class, Integer.class, + BigInteger.class); + } + if (-1 == vUInt.compareTo(BigInteger.ZERO)) { + throw new VPackBuilderUnexpectedValueException(ValueType.UINT, "non-negative", Long.class, + Integer.class, BigInteger.class); + } + appendUInt(vUInt); + break; + default: + break; + } + } + + private void appendNull() { + add((byte) 0x18); + } + + private void appendBoolean(final boolean value) { + if (value) { + add((byte) 0x1a); + } else { + add((byte) 0x19); + } + } + + private void appendDouble(final double value) { + add((byte) 0x1b); + append(value); + } + + private void append(final double value) { + append(Double.doubleToRawLongBits(value), DOUBLE_BYTES); + } + + private void appendSmallInt(final long value) { + if (value >= 0) { + add((byte) (value + 0x30)); + } else { + add((byte) (value + 0x40)); + } + } + + private void appendUInt(final BigInteger value) { + add((byte) 0x2f); + append(value, LONG_BYTES); + } + + private void append(final long value, final int length) { + ensureCapacity(size + length); + for (int i = length - 1; i >= 0; i--) { + addUnchecked((byte) (value >> (length - i - 1 << 3))); + } + } + + private void append(final BigInteger value, final int length) { + ensureCapacity(size + length); + for (int i = length - 1; i >= 0; i--) { + addUnchecked(value.shiftRight(length - i - 1 << 3).byteValue()); + } + } + + private void appendDate(final Date value) { + add((byte) 0x1c); + append(value.getTime(), LONG_BYTES); + } + + private void appendSQLDate(final java.sql.Date value) { + add((byte) 0x1c); + append(value.getTime(), LONG_BYTES); + } + + private void appendSQLTimestamp(final Timestamp value) { + add((byte) 0x1c); + append(value.getTime(), LONG_BYTES); + } + + private void appendString(final String value) throws VPackBuilderException { + final int length = value.length(); + if (length <= 126) { + // short string + add((byte) (0x40 + length)); + } else { + // long string + add((byte) 0xbf); + appendLength(length); + } + try { + append(value); + } catch (final UnsupportedEncodingException e) { + throw new VPackBuilderException(e); + } + } + + private void appendBinary(final byte[] value) { + add((byte) 0xc3); + append(value.length, INTEGER_BYTES); + ensureCapacity(size + value.length); + System.arraycopy(value, 0, buffer, size, value.length); + size += value.length; + } + + private void appendVPack(final VPackSlice value) { + final byte[] vpack = value.getRawVPack(); + ensureCapacity(size + vpack.length); + System.arraycopy(vpack, 0, buffer, size, vpack.length); + size += vpack.length; + } + + private void append(final String value) throws UnsupportedEncodingException { + final byte[] bytes = value.getBytes("UTF-8"); + ensureCapacity(size + bytes.length); + System.arraycopy(bytes, 0, buffer, size, bytes.length); + size += bytes.length; + } + + private void addArray(final boolean unindexed) { + addCompoundValue((byte) (unindexed ? 0x13 : 0x06)); + } + + private void addObject(final boolean unindexed) { + addCompoundValue((byte) (unindexed ? 0x14 : 0x0b)); + } + + private void addCompoundValue(final byte head) { + // an Array or Object is started: + stack.add(size); + index.put(stack.size() - 1, new ArrayList()); + add(head); + // Will be filled later with bytelength and nr subs + size += 8; + ensureCapacity(size); + } + + private void appendLength(final long length) { + append(length, LONG_BYTES); + } + + private void reportAdd() { + final Collection depth = index.get(stack.size() - 1); + depth.add(size - stack.get(stack.size() - 1)); + } + + private void cleanupAdd() { + final List depth = index.get(stack.size() - 1); + depth.remove(depth.size() - 1); + } + + public VPackBuilder close() throws VPackBuilderException { + try { + return close(true); + } catch (final VPackKeyTypeException e) { + throw new VPackBuilderException(e); + } catch (final VPackNeedAttributeTranslatorException e) { + throw new VPackBuilderException(e); + } + } + + protected VPackBuilder close(final boolean sort) + throws VPackBuilderNeedOpenCompoundException, VPackKeyTypeException, VPackNeedAttributeTranslatorException { + if (isClosed()) { + throw new VPackBuilderNeedOpenCompoundException(); + } + final byte head = head(); + final boolean isArray = head == 0x06 || head == 0x13; + final List in = index.get(stack.size() - 1); + final int tos = stack.get(stack.size() - 1); + if (in.isEmpty()) { + return closeEmptyArrayOrObject(tos, isArray); + } + if (head == 0x13 || head == 0x14 || (head == 0x06 && options.isBuildUnindexedArrays()) + || head == 0x0b && (options.isBuildUnindexedObjects() || in.size() == 1)) { + if (closeCompactArrayOrObject(tos, isArray, in)) { + return this; + } + // This might fall through, if closeCompactArrayOrObject gave up! + } + if (isArray) { + return closeArray(tos, in); + } + // fix head byte in case a compact Array / Object was originally + // requested + buffer[tos] = (byte) 0x0b; + + // First determine byte length and its format: + final int offsetSize; + // can be 1, 2, 4 or 8 for the byte width of the offsets, + // the byte length and the number of subvalues: + if ((size - 1 - tos) + in.size() - 6 <= 0xff) { + // We have so far used _pos - tos bytes, including the reserved 8 + // bytes for byte length and number of subvalues. In the 1-byte + // number + // case we would win back 6 bytes but would need one byte per + // subvalue + // for the index table + offsetSize = 1; + } else if ((size - 1 - tos) + 2 * in.size() <= 0xffff) { + offsetSize = 2; + } else if (((size - 1 - tos) / 2) + 4 * in.size() / 2 <= Integer.MAX_VALUE/* 0xffffffffu */) { + offsetSize = 4; + } else { + offsetSize = 8; + } + // Maybe we need to move down data + if (offsetSize == 1) { + final int targetPos = 3; + if ((size - 1) > (tos + 9)) { + for (int i = tos + targetPos; i < tos + 9; i++) { + remove(tos + targetPos); + } + } + final int diff = 9 - targetPos; + final int n = in.size(); + for (int i = 0; i < n; i++) { + in.set(i, in.get(i) - diff); + } + } + // One could move down things in the offsetSize == 2 case as well, + // since we only need 4 bytes in the beginning. However, saving these + // 4 bytes has been sacrificed on the Altar of Performance. + + // Now build the table: + if (sort && in.size() >= 2) { + // Object + sortObjectIndex(tos, in); + } + // final int tableBase = size; + for (int i = 0; i < in.size(); i++) { + long x = in.get(i); + ensureCapacity(size + offsetSize); + for (int j = 0; j < offsetSize; j++) { + addUnchecked(/* tableBase + offsetSize * i + j, */ (byte) (x & 0xff)); + x >>= 8; + } + } + // Finally fix the byte width in the type byte: + if (offsetSize > 1) { + if (offsetSize == 2) { + buffer[tos] = (byte) (buffer[tos] + 1); + } else if (offsetSize == 4) { + buffer[tos] = (byte) (buffer[tos] + 2); + } else { // offsetSize == 8 + buffer[tos] = (byte) (buffer[tos] + 3); + appendLength(in.size()); + } + } + // Fix the byte length in the beginning + long x = size - tos; + for (int i = 1; i <= offsetSize; i++) { + buffer[tos + i] = (byte) (x & 0xff); + x >>= 8; + } + // set the number of items in the beginning + if (offsetSize < 8) { + x = in.size(); + for (int i = offsetSize + 1; i <= 2 * offsetSize; i++) { + buffer[tos + i] = (byte) (x & 0xff); + x >>= 8; + } + } + stack.remove(stack.size() - 1); + return this; + } + + private VPackBuilder closeEmptyArrayOrObject(final int tos, final boolean isArray) { + // empty Array or Object + buffer[tos] = (byte) (isArray ? 0x01 : 0x0a); + // no bytelength and number subvalues needed + for (int i = 1; i <= 8; i++) { + remove(tos + 1); + } + stack.remove(stack.size() - 1); + return this; + } + + private boolean closeCompactArrayOrObject(final int tos, final boolean isArray, final List in) { + // use the compact Array / Object format + final long nLen = NumberUtil.getVariableValueLength(in.size()); + long byteSize = size - (tos + 8) + nLen; + long bLen = NumberUtil.getVariableValueLength(byteSize); + byteSize += bLen; + if (NumberUtil.getVariableValueLength(byteSize) != bLen) { + byteSize += 1; + bLen += 1; + } + if (bLen < 9) { + // can only use compact notation if total byte length is at most + // 8 bytes long + buffer[tos] = (byte) (isArray ? 0x13 : 0x14); + final int targetPos = (int) (1 + bLen); + if (size - 1 > (tos + 9)) { + for (int i = tos + targetPos; i < tos + 9; i++) { + remove(tos + targetPos); + } + } + // store byte length + storeVariableValueLength(tos, byteSize, false); + // need additional memory for storing the number of values + if (nLen > 8 - bLen) { + ensureCapacity((int) (size + nLen)); + } + // store number of values + storeVariableValueLength((int) (tos + byteSize), in.size(), true); + size += nLen; + stack.remove(stack.size() - 1); + return true; + } + return false; + } + + private void storeVariableValueLength(final int offset, final long value, final boolean reverse) { + int i = offset; + long val = value; + if (reverse) { + while (val >= 0x80) { + buffer[--i] = (byte) ((byte) (val & 0x7f) | (byte) 0x80); + val >>= 7; + } + buffer[--i] = (byte) (val & 0x7f); + } else { + while (val >= 0x80) { + buffer[++i] = (byte) ((byte) (val & 0x7f) | (byte) 0x80); + val >>= 7; + } + buffer[++i] = (byte) (val & 0x7f); + } + } + + private VPackBuilder closeArray(final int tos, final List in) { + // fix head byte in case a compact Array was originally + // requested + buffer[tos] = (byte) 0x06; + + boolean needIndexTable = true; + boolean needNrSubs = true; + final int n = in.size(); + if (n == 1) { + needIndexTable = false; + needNrSubs = false; + } else if ((size - tos) - in.get(0) == n * (in.get(1) - in.get(0))) { + // In this case it could be that all entries have the same length + // and we do not need an offset table at all: + boolean noTable = true; + final int subLen = in.get(1) - in.get(0); + if ((size - tos) - in.get(n - 1) != subLen) { + noTable = false; + } else { + for (int i = 1; i < n - 1; i++) { + if (in.get(i + 1) - in.get(i) != subLen) { + noTable = false; + break; + } + } + } + if (noTable) { + needIndexTable = false; + needNrSubs = false; + } + } + + // First determine byte length and its format: + final int offsetSize; + // can be 1, 2, 4 or 8 for the byte width of the offsets, + // the byte length and the number of subvalues: + if ((size - 1 - tos) + (needIndexTable ? n : 0) - (needNrSubs ? 6 : 7) <= 0xff) { + // We have so far used _pos - tos bytes, including the reserved 8 + // bytes for byte length and number of subvalues. In the 1-byte + // number + // case we would win back 6 bytes but would need one byte per + // subvalue + // for the index table + offsetSize = 1; + } else if ((size - 1 - tos) + (needIndexTable ? 2 * n : 0) <= 0xffff) { + offsetSize = 2; + } else if (((size - 1 - tos) / 2) + ((needIndexTable ? 4 * n : 0) / 2) <= Integer.MAX_VALUE/* 0xffffffffu */) { + offsetSize = 4; + } else { + offsetSize = 8; + } + // Maybe we need to move down data + if (offsetSize == 1) { + int targetPos = 3; + if (!needIndexTable) { + targetPos = 2; + } + if ((size - 1) > (tos + 9)) { + for (int i = tos + targetPos; i < tos + 9; i++) { + remove(tos + targetPos); + } + } + final int diff = 9 - targetPos; + if (needIndexTable) { + for (int i = 0; i < n; i++) { + in.set(i, in.get(i) - diff); + } + } // Note: if !needIndexTable the index is now wrong! + } + // One could move down things in the offsetSize == 2 case as well, + // since we only need 4 bytes in the beginning. However, saving these + // 4 bytes has been sacrificed on the Altar of Performance. + + // Now build the table: + if (needIndexTable) { + // final int tableBase = size; + for (int i = 0; i < n; i++) { + long x = in.get(i); + ensureCapacity(size + offsetSize); + for (int j = 0; j < offsetSize; j++) { + addUnchecked(/* tableBase + offsetSize * i + j, */ (byte) (x & 0xff)); + x >>= 8; + } + } + } else { // no index table + buffer[tos] = (byte) 0x02; + } + // Finally fix the byte width in the type byte: + if (offsetSize > 1) { + if (offsetSize == 2) { + buffer[tos] = (byte) (buffer[tos] + 1); + } else if (offsetSize == 4) { + buffer[tos] = (byte) (buffer[tos] + 2); + } else { // offsetSize == 8 + buffer[tos] = (byte) (buffer[tos] + 3); + if (needNrSubs) { + appendLength(n); + } + } + } + // Fix the byte length in the beginning + long x = size - tos; + for (int i = 1; i <= offsetSize; i++) { + buffer[tos + i] = (byte) (x & 0xff); + x >>= 8; + } + // set the number of items in the beginning + if (offsetSize < 8 && needNrSubs) { + x = n; + for (int i = offsetSize + 1; i <= 2 * offsetSize; i++) { + buffer[tos + i] = (byte) (x & 0xff); + x >>= 8; + } + } + stack.remove(stack.size() - 1); + return this; + } + + private static class SortEntry { + private final VPackSlice slice; + private final int offset; + + public SortEntry(final VPackSlice slice, final int offset) { + super(); + this.slice = slice; + this.offset = offset; + } + } + + private void sortObjectIndex(final int start, final List offsets) + throws VPackKeyTypeException, VPackNeedAttributeTranslatorException { + final List attributes = new ArrayList(); + for (final Integer offset : offsets) { + attributes.add(new SortEntry(new VPackSlice(buffer, start + offset).makeKey(), offset)); + } + final Comparator comparator = new Comparator() { + @Override + public int compare(final SortEntry o1, final SortEntry o2) { + return o1.slice.getAsString().compareTo(o2.slice.getAsString()); + } + }; + Collections.sort(attributes, comparator); + offsets.clear(); + for (final SortEntry sortEntry : attributes) { + offsets.add(sortEntry.offset); + } + } + + public static int compareTo( + final byte[] b1, + final int b1Index, + final int b1Length, + final byte[] b2, + final int b2Index, + final int b2Length) { + final int commonLength = Math.min(b1Length, b2Length); + for (int i = 0; i < commonLength; i++) { + final byte byte1 = b1[b1Index + i]; + final byte byte2 = b2[b2Index + i]; + if (byte1 != byte2) { + return (byte1 < byte2) ? -1 : 1; + } + } + if (b1Length != b2Length) { + return (b1Length < b2Length) ? -2 : 2; + } + return 0; + } + + private boolean isClosed() { + return stack.isEmpty(); + } + + private byte head() { + final Integer in = stack.get(stack.size() - 1); + return buffer[in]; + } + + public VPackSlice slice() { + return new VPackSlice(buffer); + } + + public int getVpackSize() { + return size; + } + +} diff --git a/src/main/java/com/arangodb/entity/DeletedEntity.java b/src/main/java/com/arangodb/velocypack/VPackDeserializationContext.java similarity index 53% rename from src/main/java/com/arangodb/entity/DeletedEntity.java rename to src/main/java/com/arangodb/velocypack/VPackDeserializationContext.java index 6c40c6a2f..48b39d640 100644 --- a/src/main/java/com/arangodb/entity/DeletedEntity.java +++ b/src/main/java/com/arangodb/velocypack/VPackDeserializationContext.java @@ -1,41 +1,33 @@ -/* - * Copyright (C) 2012,2013 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.entity; - -/** - * - * An entity used as a result for deletions. - * - * @author tamtam180 - kirscheless at gmail.com - * - */ -public class DeletedEntity extends DefaultEntity { - - /** - * if true the deletion has been executed successfully - */ - Boolean deleted; - - public Boolean getDeleted() { - return deleted; - } - - public void setDeleted(Boolean deleted) { - this.deleted = deleted; - } - -} +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.velocypack; + +import com.arangodb.velocypack.exception.VPackParserException; + +/** + * @author Mark - mark at arangodb.com + * + */ +public interface VPackDeserializationContext { + + T deserialize(final VPackSlice vpack, final Class type) throws VPackParserException; + +} diff --git a/src/main/java/com/arangodb/entity/DocumentHolder.java b/src/main/java/com/arangodb/velocypack/VPackDeserializer.java similarity index 52% rename from src/main/java/com/arangodb/entity/DocumentHolder.java rename to src/main/java/com/arangodb/velocypack/VPackDeserializer.java index 47265f076..c0bb1ebe8 100644 --- a/src/main/java/com/arangodb/entity/DocumentHolder.java +++ b/src/main/java/com/arangodb/velocypack/VPackDeserializer.java @@ -1,37 +1,33 @@ -/* - * Copyright (C) 2012,2013 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.entity; - -/** - * @author tamtam180 - kirscheless at gmail.com - * - */ -public interface DocumentHolder { - - public String getDocumentRevision(); - - public String getDocumentHandle(); - - public String getDocumentKey(); - - public void setDocumentRevision(String documentRevision); - - public void setDocumentHandle(String documentHandle); - - public void setDocumentKey(String documentKey); - -} +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.velocypack; + +import com.arangodb.velocypack.exception.VPackException; + +/** + * @author Mark - mark at arangodb.com + * + */ +public interface VPackDeserializer { + + T deserialize(VPackSlice parent, VPackSlice vpack, VPackDeserializationContext context) throws VPackException; + +} diff --git a/src/main/java/com/arangodb/entity/MapAsEntity.java b/src/main/java/com/arangodb/velocypack/VPackFieldNamingStrategy.java similarity index 57% rename from src/main/java/com/arangodb/entity/MapAsEntity.java rename to src/main/java/com/arangodb/velocypack/VPackFieldNamingStrategy.java index a41565ef6..a8073be75 100644 --- a/src/main/java/com/arangodb/entity/MapAsEntity.java +++ b/src/main/java/com/arangodb/velocypack/VPackFieldNamingStrategy.java @@ -1,37 +1,33 @@ -/* - * Copyright (C) 2012,2013 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.entity; - -import java.util.Map; - -/** - * @author tamtam180 - kirscheless at gmail.com - * - */ -public class MapAsEntity extends BaseEntity { - - Map map; - - public Map getMap() { - return map; - } - - public void setMap(Map map) { - this.map = map; - } - -} +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.velocypack; + +import java.lang.reflect.Field; + +/** + * @author Mark - mark at arangodb.com + * + */ +public interface VPackFieldNamingStrategy { + + String translateName(Field field); + +} diff --git a/src/main/java/com/arangodb/entity/marker/VertexEntity.java b/src/main/java/com/arangodb/velocypack/VPackInstanceCreator.java similarity index 60% rename from src/main/java/com/arangodb/entity/marker/VertexEntity.java rename to src/main/java/com/arangodb/velocypack/VPackInstanceCreator.java index 9d2238906..91a85eb45 100644 --- a/src/main/java/com/arangodb/entity/marker/VertexEntity.java +++ b/src/main/java/com/arangodb/velocypack/VPackInstanceCreator.java @@ -1,27 +1,31 @@ -/* - * Copyright (C) 2012,2013 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.entity.marker; - -import com.arangodb.entity.DocumentEntity; - -/** - * @author tamtam180 - kirscheless at gmail.com - * @since 1.4.0 - */ -public class VertexEntity extends DocumentEntity { - -} +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.velocypack; + +/** + * @author Mark - mark at arangodb.com + * + */ +public interface VPackInstanceCreator { + + T createInstance(); + +} diff --git a/src/main/java/com/arangodb/velocypack/VPackJsonDeserializer.java b/src/main/java/com/arangodb/velocypack/VPackJsonDeserializer.java new file mode 100644 index 000000000..eb3c6407f --- /dev/null +++ b/src/main/java/com/arangodb/velocypack/VPackJsonDeserializer.java @@ -0,0 +1,33 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.velocypack; + +import com.arangodb.velocypack.exception.VPackException; + +/** + * @author Mark - mark at arangodb.com + * + */ +public interface VPackJsonDeserializer { + + void deserialize(VPackSlice parent, String attribute, VPackSlice vpack, StringBuilder json) throws VPackException; + +} diff --git a/src/test/java/com/arangodb/TestInterfaceImpl.java b/src/main/java/com/arangodb/velocypack/VPackKeyMapAdapter.java similarity index 58% rename from src/test/java/com/arangodb/TestInterfaceImpl.java rename to src/main/java/com/arangodb/velocypack/VPackKeyMapAdapter.java index f0b373330..1ab0e713a 100644 --- a/src/test/java/com/arangodb/TestInterfaceImpl.java +++ b/src/main/java/com/arangodb/velocypack/VPackKeyMapAdapter.java @@ -1,34 +1,33 @@ -/* - * Copyright (C) 2015 tporadowski - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb; - -/** - * @author tporadowski - tomasz at poradowski.com - */ -public class TestInterfaceImpl implements TestInterface { - private String name; - - public TestInterfaceImpl(String name) { - this.name = name; - } - - @Override - public String getName() { - return name; - } - -} +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.velocypack; + +/** + * @author Mark - mark at arangodb.com + * + */ +public interface VPackKeyMapAdapter { + + String serialize(T key); + + T deserialize(String key); + +} diff --git a/src/main/java/com/arangodb/velocypack/VPackParser.java b/src/main/java/com/arangodb/velocypack/VPackParser.java new file mode 100644 index 000000000..9ac9abafe --- /dev/null +++ b/src/main/java/com/arangodb/velocypack/VPackParser.java @@ -0,0 +1,314 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.velocypack; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.Map.Entry; + +import org.json.simple.JSONValue; +import org.json.simple.parser.ContentHandler; +import org.json.simple.parser.JSONParser; +import org.json.simple.parser.ParseException; + +import com.arangodb.velocypack.exception.VPackBuilderException; +import com.arangodb.velocypack.exception.VPackException; + +/** + * @author Mark - mark at arangodb.com + * + */ +public class VPackParser { + + private static final char OBJECT_OPEN = '{'; + private static final char OBJECT_CLOSE = '}'; + private static final char ARRAY_OPEN = '['; + private static final char ARRAY_CLOSE = ']'; + private static final char FIELD = ':'; + private static final char SEPARATOR = ','; + private static final String NULL = "null"; + private final Map deserializers; + private final Map> deserializersByName; + + public VPackParser() { + super(); + deserializers = new HashMap(); + deserializersByName = new HashMap>(); + } + + public String toJson(final VPackSlice vpack) throws VPackException { + return toJson(vpack, false); + } + + public String toJson(final VPackSlice vpack, final boolean includeNullValues) throws VPackException { + final StringBuilder json = new StringBuilder(); + parse(null, null, vpack, json, includeNullValues); + return json.toString(); + } + + public VPackParser registerDeserializer( + final String attribute, + final ValueType type, + final VPackJsonDeserializer deserializer) { + Map byName = deserializersByName.get(attribute); + if (byName == null) { + byName = new HashMap(); + deserializersByName.put(attribute, byName); + } + byName.put(type, deserializer); + return this; + } + + public VPackParser registerDeserializer(final ValueType type, final VPackJsonDeserializer deserializer) { + deserializers.put(type, deserializer); + return this; + } + + private VPackJsonDeserializer getDeserializer(final String attribute, final ValueType type) { + VPackJsonDeserializer deserializer = null; + final Map byName = deserializersByName.get(attribute); + if (byName != null) { + deserializer = byName.get(type); + } + if (deserializer == null) { + deserializer = deserializers.get(type); + } + return deserializer; + } + + private void parse( + final VPackSlice parent, + final String attribute, + final VPackSlice value, + final StringBuilder json, + final boolean includeNullValues) throws VPackException { + + VPackJsonDeserializer deserializer = null; + if (attribute != null) { + appendField(attribute, json); + deserializer = getDeserializer(attribute, value.type()); + } + if (deserializer != null) { + deserializer.deserialize(parent, attribute, value, json); + } else { + if (value.isObject()) { + parseObject(value, json, includeNullValues); + } else if (value.isArray()) { + parseArray(value, json, includeNullValues); + } else if (value.isBoolean()) { + json.append(value.getAsBoolean()); + } else if (value.isString()) { + json.append(JSONValue.toJSONString(value.getAsString())); + } else if (value.isNumber()) { + json.append(value.getAsNumber()); + } else if (value.isNull()) { + json.append(NULL); + } else { + json.append(NULL); + } + } + } + + private static void appendField(final String attribute, final StringBuilder json) { + json.append(JSONValue.toJSONString(attribute)); + json.append(FIELD); + } + + private void parseObject(final VPackSlice value, final StringBuilder json, final boolean includeNullValues) + throws VPackException { + json.append(OBJECT_OPEN); + int added = 0; + for (final Iterator> iterator = value.objectIterator(); iterator.hasNext();) { + final Entry next = iterator.next(); + final VPackSlice nextValue = next.getValue(); + if (!nextValue.isNull() || includeNullValues) { + if (added++ > 0) { + json.append(SEPARATOR); + } + parse(value, next.getKey(), nextValue, json, includeNullValues); + } + } + json.append(OBJECT_CLOSE); + } + + private void parseArray(final VPackSlice value, final StringBuilder json, final boolean includeNullValues) + throws VPackException { + json.append(ARRAY_OPEN); + int added = 0; + for (int i = 0; i < value.getLength(); i++) { + final VPackSlice valueAt = value.get(i); + if (!valueAt.isNull() || includeNullValues) { + if (added++ > 0) { + json.append(SEPARATOR); + } + parse(value, null, valueAt, json, includeNullValues); + } + } + json.append(ARRAY_CLOSE); + } + + public VPackSlice fromJson(final String json) throws VPackException { + return fromJson(json, false); + } + + public VPackSlice fromJson(final String json, final boolean includeNullValues) throws VPackException { + final VPackBuilder builder = new VPackBuilder(); + final JSONParser parser = new JSONParser(); + final ContentHandler contentHandler = new VPackContentHandler(builder, includeNullValues); + try { + parser.parse(json, contentHandler); + } catch (final ParseException e) { + throw new VPackBuilderException(e); + } + return builder.slice(); + } + + private static class VPackContentHandler implements ContentHandler { + + private final VPackBuilder builder; + private String attribute; + private final boolean includeNullValues; + + public VPackContentHandler(final VPackBuilder builder, final boolean includeNullValues) { + this.builder = builder; + this.includeNullValues = includeNullValues; + attribute = null; + } + + private void add(final ValueType value) throws ParseException { + try { + builder.add(attribute, value); + attribute = null; + } catch (final VPackBuilderException e) { + throw new ParseException(ParseException.ERROR_UNEXPECTED_EXCEPTION); + } + } + + private void add(final String value) throws ParseException { + try { + builder.add(attribute, value); + attribute = null; + } catch (final VPackBuilderException e) { + throw new ParseException(ParseException.ERROR_UNEXPECTED_EXCEPTION); + } + } + + private void add(final Boolean value) throws ParseException { + try { + builder.add(attribute, value); + attribute = null; + } catch (final VPackBuilderException e) { + throw new ParseException(ParseException.ERROR_UNEXPECTED_EXCEPTION); + } + } + + private void add(final Double value) throws ParseException { + try { + builder.add(attribute, value); + attribute = null; + } catch (final VPackBuilderException e) { + throw new ParseException(ParseException.ERROR_UNEXPECTED_EXCEPTION); + } + } + + private void add(final Long value) throws ParseException { + try { + builder.add(attribute, value); + attribute = null; + } catch (final VPackBuilderException e) { + throw new ParseException(ParseException.ERROR_UNEXPECTED_EXCEPTION); + } + } + + private void close() throws ParseException { + try { + builder.close(); + } catch (final VPackBuilderException e) { + throw new ParseException(ParseException.ERROR_UNEXPECTED_EXCEPTION); + } + } + + @Override + public void startJSON() throws ParseException, IOException { + } + + @Override + public void endJSON() throws ParseException, IOException { + } + + @Override + public boolean startObject() throws ParseException, IOException { + add(ValueType.OBJECT); + return true; + } + + @Override + public boolean endObject() throws ParseException, IOException { + close(); + return true; + } + + @Override + public boolean startObjectEntry(final String key) throws ParseException, IOException { + attribute = key; + return true; + } + + @Override + public boolean endObjectEntry() throws ParseException, IOException { + return true; + } + + @Override + public boolean startArray() throws ParseException, IOException { + add(ValueType.ARRAY); + return true; + } + + @Override + public boolean endArray() throws ParseException, IOException { + close(); + return true; + } + + @Override + public boolean primitive(final Object value) throws ParseException, IOException { + if (value == null) { + if (includeNullValues) { + add(ValueType.NULL); + } + } else if (String.class.isAssignableFrom(value.getClass())) { + add(String.class.cast(value)); + } else if (Boolean.class.isAssignableFrom(value.getClass())) { + add(Boolean.class.cast(value)); + } else if (Double.class.isAssignableFrom(value.getClass())) { + add(Double.class.cast(value)); + } else if (Number.class.isAssignableFrom(value.getClass())) { + add(Long.class.cast(value)); + } + return true; + } + + } + +} \ No newline at end of file diff --git a/src/main/java/com/arangodb/velocypack/VPackSerializationContext.java b/src/main/java/com/arangodb/velocypack/VPackSerializationContext.java new file mode 100644 index 000000000..af1c3fbe8 --- /dev/null +++ b/src/main/java/com/arangodb/velocypack/VPackSerializationContext.java @@ -0,0 +1,33 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.velocypack; + +import com.arangodb.velocypack.exception.VPackParserException; + +/** + * @author Mark - mark at arangodb.com + * + */ +public interface VPackSerializationContext { + + void serialize(final VPackBuilder builder, final String attribute, final Object entity) throws VPackParserException; + +} diff --git a/src/main/java/com/arangodb/velocypack/VPackSerializer.java b/src/main/java/com/arangodb/velocypack/VPackSerializer.java new file mode 100644 index 000000000..dc42e5cd9 --- /dev/null +++ b/src/main/java/com/arangodb/velocypack/VPackSerializer.java @@ -0,0 +1,34 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.velocypack; + +import com.arangodb.velocypack.exception.VPackException; + +/** + * @author Mark - mark at arangodb.com + * + */ +public interface VPackSerializer { + + void serialize(VPackBuilder builder, String attribute, T value, VPackSerializationContext context) + throws VPackException; + +} diff --git a/src/main/java/com/arangodb/velocypack/VPackSlice.java b/src/main/java/com/arangodb/velocypack/VPackSlice.java new file mode 100644 index 000000000..f3b76c260 --- /dev/null +++ b/src/main/java/com/arangodb/velocypack/VPackSlice.java @@ -0,0 +1,810 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.velocypack; + +import java.io.Serializable; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.util.Arrays; +import java.util.Date; +import java.util.Iterator; +import java.util.Map.Entry; + +import com.arangodb.velocypack.exception.VPackException; +import com.arangodb.velocypack.exception.VPackKeyTypeException; +import com.arangodb.velocypack.exception.VPackNeedAttributeTranslatorException; +import com.arangodb.velocypack.exception.VPackValueTypeException; +import com.arangodb.velocypack.internal.VPackAttributeTranslatorImpl; +import com.arangodb.velocypack.internal.util.BinaryUtil; +import com.arangodb.velocypack.internal.util.DateUtil; +import com.arangodb.velocypack.internal.util.NumberUtil; +import com.arangodb.velocypack.internal.util.ObjectArrayUtil; +import com.arangodb.velocypack.internal.util.StringUtil; +import com.arangodb.velocypack.internal.util.ValueLengthUtil; +import com.arangodb.velocypack.internal.util.ValueTypeUtil; + +/** + * @author Mark - mark at arangodb.com + * + */ +public class VPackSlice implements Serializable { + + private static final long serialVersionUID = -3452953589283603980L; + + public static final VPackAttributeTranslator attributeTranslator = new VPackAttributeTranslatorImpl(); + + private final byte[] vpack; + private final int start; + + protected VPackSlice() { + this(new byte[] { 0x00 }, 0); + } + + public VPackSlice(final byte[] vpack) { + this(vpack, 0); + } + + public VPackSlice(final byte[] vpack, final int start) { + super(); + this.vpack = vpack; + this.start = start; + } + + public byte head() { + return vpack[start]; + } + + public byte[] getBuffer() { + return vpack; + } + + public int getStart() { + return start; + } + + protected ValueType type() { + return ValueTypeUtil.get(head()); + } + + private int length() { + return ValueLengthUtil.get(head()) - 1; + } + + private boolean isType(final ValueType type) { + return type() == type; + } + + public boolean isNone() { + return isType(ValueType.NONE); + } + + public boolean isNull() { + return isType(ValueType.NULL); + } + + public boolean isIllegal() { + return isType(ValueType.ILLEGAL); + } + + public boolean isBoolean() { + return isType(ValueType.BOOL); + } + + public boolean isTrue() { + return head() == 0x1a; + } + + public boolean isFalse() { + return head() == 0x19; + } + + public boolean isArray() { + return isType(ValueType.ARRAY); + } + + public boolean isObject() { + return isType(ValueType.OBJECT); + } + + public boolean isDouble() { + return isType(ValueType.DOUBLE); + } + + public boolean isDate() { + return isType(ValueType.UTC_DATE); + } + + public boolean isExternal() { + return isType(ValueType.EXTERNAL); + } + + public boolean isMinKey() { + return isType(ValueType.MIN_KEY); + } + + public boolean isMaxKey() { + return isType(ValueType.MAX_KEY); + } + + public boolean isInt() { + return isType(ValueType.INT); + } + + public boolean isUInt() { + return isType(ValueType.UINT); + } + + public boolean isSmallInt() { + return isType(ValueType.SMALLINT); + } + + public boolean isInteger() { + return isInt() || isUInt() || isSmallInt(); + } + + public boolean isNumber() { + return isInteger() || isDouble(); + } + + public boolean isString() { + return isType(ValueType.STRING); + } + + public boolean isBinary() { + return isType(ValueType.BINARY); + } + + public boolean isBCD() { + return isType(ValueType.BCD); + } + + public boolean isCustom() { + return isType(ValueType.CUSTOM); + } + + public boolean getAsBoolean() { + if (!isBoolean()) { + throw new VPackValueTypeException(ValueType.BOOL); + } + return isTrue(); + } + + public double getAsDouble() { + if (!isDouble()) { + throw new VPackValueTypeException(ValueType.DOUBLE); + } + return getAsDoubleUnchecked(); + } + + private double getAsDoubleUnchecked() { + return NumberUtil.toDouble(vpack, start + 1, length()); + } + + public BigDecimal getAsBigDecimal() { + return new BigDecimal(getAsDouble()); + } + + private long getSmallInt() { + final byte head = head(); + final long smallInt; + if (head >= 0x30 && head <= 0x39) { + smallInt = head - 0x30; + } else /* if (head >= 0x3a && head <= 0x3f) */ { + smallInt = head - 0x3a - 6; + } + return smallInt; + } + + private long getInt() { + return NumberUtil.toLong(vpack, start + 1, length()); + } + + private long getUInt() { + return NumberUtil.toLong(vpack, start + 1, length()); + } + + public Number getAsNumber() { + final Number result; + if (isSmallInt()) { + result = getSmallInt(); + } else if (isInt()) { + result = getInt(); + } else if (isUInt()) { + result = getUInt(); + } else if (isDouble()) { + result = getAsDouble(); + } else { + throw new VPackValueTypeException(ValueType.INT, ValueType.UINT, ValueType.SMALLINT); + } + return result; + } + + public long getAsLong() { + return getAsNumber().longValue(); + } + + public int getAsInt() { + return getAsNumber().intValue(); + } + + public float getAsFloat() { + return (float) getAsDoubleUnchecked(); + } + + public short getAsShort() { + return getAsNumber().shortValue(); + } + + public BigInteger getAsBigInteger() { + if (isSmallInt() || isInt()) { + return BigInteger.valueOf(getAsLong()); + } else if (isUInt()) { + return NumberUtil.toBigInteger(vpack, start + 1, length()); + } else { + throw new VPackValueTypeException(ValueType.INT, ValueType.UINT, ValueType.SMALLINT); + } + } + + public Date getAsDate() { + if (!isDate()) { + throw new VPackValueTypeException(ValueType.UTC_DATE); + } + return DateUtil.toDate(vpack, start + 1, length()); + } + + public java.sql.Date getAsSQLDate() { + if (!isDate()) { + throw new VPackValueTypeException(ValueType.UTC_DATE); + } + return DateUtil.toSQLDate(vpack, start + 1, length()); + } + + public java.sql.Timestamp getAsSQLTimestamp() { + if (!isDate()) { + throw new VPackValueTypeException(ValueType.UTC_DATE); + } + return DateUtil.toSQLTimestamp(vpack, start + 1, length()); + } + + public String getAsString() { + if (!isString()) { + throw new VPackValueTypeException(ValueType.STRING); + } + return isLongString() ? getLongString() : getShortString(); + } + + public char getAsChar() { + return getAsString().charAt(0); + } + + private boolean isLongString() { + return head() == (byte) 0xbf; + } + + private String getShortString() { + return StringUtil.toString(vpack, start + 1, length()); + } + + private String getLongString() { + return StringUtil.toString(vpack, start + 9, getLongStringLength()); + } + + private int getLongStringLength() { + return (int) NumberUtil.toLong(vpack, start + 1, 8); + } + + private int getStringLength() { + return isLongString() ? getLongStringLength() : head() - 0x40; + } + + public byte[] getAsBinary() { + if (!isBinary()) { + throw new VPackValueTypeException(ValueType.BINARY); + } + final byte[] binary = BinaryUtil.toBinary(vpack, start + 1 + head() - ((byte) 0xbf), getBinaryLength()); + return binary; + } + + public int getBinaryLength() { + if (!isBinary()) { + throw new VPackValueTypeException(ValueType.BINARY); + } + return getBinaryLengthUnchecked(); + } + + private int getBinaryLengthUnchecked() { + return (int) NumberUtil.toLong(vpack, start + 1, head() - ((byte) 0xbf)); + } + + /** + * @return the number of members for an Array, Object or String + */ + public int getLength() { + final long length; + if (isString()) { + length = getStringLength(); + } else if (!isArray() && !isObject()) { + throw new VPackValueTypeException(ValueType.ARRAY, ValueType.OBJECT, ValueType.STRING); + } else { + final byte head = head(); + if (head == 0x01 || head == 0x0a) { + // empty + length = 0; + } else if (head == 0x13 || head == 0x14) { + // compact array or object + final long end = NumberUtil.readVariableValueLength(vpack, start + 1, false); + length = NumberUtil.readVariableValueLength(vpack, (int) (start + end - 1), true); + } else { + final int offsetsize = ObjectArrayUtil.getOffsetSize(head); + final long end = NumberUtil.toLong(vpack, start + 1, offsetsize); + if (head <= 0x05) { + // array with no offset table or length + final int dataOffset = findDataOffset(); + final VPackSlice first = new VPackSlice(vpack, start + dataOffset); + length = (end - dataOffset) / first.getByteSize(); + } else if (offsetsize < 8) { + length = NumberUtil.toLong(vpack, start + 1 + offsetsize, offsetsize); + } else { + length = NumberUtil.toLong(vpack, (int) (start + end - offsetsize), offsetsize); + } + } + } + return (int) length; + } + + public int size() { + return getLength(); + } + + /** + * Must be called for a nonempty array or object at start(): + */ + protected int findDataOffset() { + final int fsm = ObjectArrayUtil.getFirstSubMap(head()); + final int offset; + if (fsm <= 2 && vpack[start + 2] != 0) { + offset = 2; + } else if (fsm <= 3 && vpack[start + 3] != 0) { + offset = 3; + } else if (fsm <= 5 && vpack[start + 6] != 0) { + offset = 5; + } else { + offset = 9; + } + return offset; + } + + public int getByteSize() { + final long size; + final byte head = head(); + final int valueLength = ValueLengthUtil.get(head); + if (valueLength != 0) { + size = valueLength; + } else { + switch (type()) { + case ARRAY: + case OBJECT: + if (head == 0x13 || head == 0x14) { + // compact Array or Object + size = NumberUtil.readVariableValueLength(vpack, start + 1, false); + } else /* if (head <= 0x14) */ { + size = NumberUtil.toLong(vpack, start + 1, ObjectArrayUtil.getOffsetSize(head)); + } + break; + case STRING: + // long UTF-8 String + size = getLongStringLength() + 1 + 8; + break; + case BINARY: + size = 1 + head - ((byte) 0xbf) + getBinaryLengthUnchecked(); + break; + case BCD: + if (head <= 0xcf) { + size = 1 + head + ((byte) 0xc7) + NumberUtil.toLong(vpack, start + 1, head - ((byte) 0xc7)); + } else { + size = 1 + head - ((byte) 0xcf) + NumberUtil.toLong(vpack, start + 1, head - ((byte) 0xcf)); + } + break; + case CUSTOM: + if (head == 0xf4 || head == 0xf5 || head == 0xf6) { + size = 2 + NumberUtil.toLong(vpack, start + 1, 1); + } else if (head == 0xf7 || head == 0xf8 || head == 0xf9) { + size = 3 + NumberUtil.toLong(vpack, start + 1, 2); + } else if (head == 0xfa || head == 0xfb || head == 0xfc) { + size = 5 + NumberUtil.toLong(vpack, start + 1, 4); + } else /* if (head == 0xfd || head == 0xfe || head == 0xff) */ { + size = 9 + NumberUtil.toLong(vpack, start + 1, 8); + } + break; + default: + // TODO + throw new InternalError(); + } + } + return (int) size; + } + + /** + * @return array value at the specified index + * @throws VPackValueTypeException + */ + public VPackSlice get(final int index) { + if (!isArray()) { + throw new VPackValueTypeException(ValueType.ARRAY); + } + return getNth(index); + } + + public VPackSlice get(final String attribute) throws VPackException { + if (!isObject()) { + throw new VPackValueTypeException(ValueType.OBJECT); + } + final byte head = head(); + VPackSlice result = new VPackSlice(); + if (head == 0x0a) { + // special case, empty object + result = new VPackSlice(); + } else if (head == 0x14) { + // compact Object + result = getFromCompactObject(attribute); + } else { + final int offsetsize = ObjectArrayUtil.getOffsetSize(head); + final long end = NumberUtil.toLong(vpack, start + 1, offsetsize); + final long n; + if (offsetsize < 8) { + n = NumberUtil.toLong(vpack, start + 1 + offsetsize, offsetsize); + } else { + n = NumberUtil.toLong(vpack, (int) (start + end - offsetsize), offsetsize); + } + if (n == 1) { + // Just one attribute, there is no index table! + final VPackSlice key = new VPackSlice(vpack, start + findDataOffset()); + + if (key.isString()) { + if (key.isEqualString(attribute)) { + result = new VPackSlice(vpack, key.start + key.getByteSize()); + } else { + // no match + result = new VPackSlice(); + } + } else if (key.isInteger()) { + // translate key + if (VPackSlice.attributeTranslator == null) { + throw new VPackNeedAttributeTranslatorException(); + } + if (key.translateUnchecked().isEqualString(attribute)) { + result = new VPackSlice(vpack, key.start + key.getByteSize()); + } else { + // no match + result = new VPackSlice(); + } + } else { + // no match + result = new VPackSlice(); + } + } else { + final long ieBase = end - n * offsetsize - (offsetsize == 8 ? 8 : 0); + + // only use binary search for attributes if we have at least + // this many entries + // otherwise we'll always use the linear search + final long sortedSearchEntriesThreshold = 4; + + final boolean sorted = head >= 0x0b && head <= 0x0e; + if (sorted && n >= sortedSearchEntriesThreshold) { + // This means, we have to handle the special case n == 1 + // only in the linear search! + result = searchObjectKeyBinary(attribute, ieBase, offsetsize, n); + } else { + result = searchObjectKeyLinear(attribute, ieBase, offsetsize, n); + } + } + } + return result; + } + + /** + * translates an integer key into a string, without checks + */ + protected VPackSlice translateUnchecked() { + final VPackSlice result = attributeTranslator.translate(getAsInt()); + return result != null ? result : new VPackSlice(); + } + + protected VPackSlice makeKey() throws VPackKeyTypeException, VPackNeedAttributeTranslatorException { + if (isString()) { + return this; + } + if (isInteger()) { + if (VPackSlice.attributeTranslator == null) { + throw new VPackNeedAttributeTranslatorException(); + } + return translateUnchecked(); + } + throw new VPackKeyTypeException("Cannot translate key of this type"); + } + + private VPackSlice getFromCompactObject(final String attribute) + throws VPackKeyTypeException, VPackNeedAttributeTranslatorException { + for (final Iterator> iterator = objectIterator(); iterator.hasNext();) { + final Entry next = iterator.next(); + if (next.getKey().equals(attribute)) { + return next.getValue(); + } + } + // not found + return new VPackSlice(); + } + + private VPackSlice searchObjectKeyBinary( + final String attribute, + final long ieBase, + final int offsetsize, + final long n) throws VPackValueTypeException, VPackNeedAttributeTranslatorException { + + final boolean useTranslator = VPackSlice.attributeTranslator != null; + VPackSlice result; + long l = 0; + long r = n - 1; + + for (;;) { + // midpoint + final long index = l + ((r - l) / 2); + final long offset = ieBase + index * offsetsize; + final long keyIndex = NumberUtil.toLong(vpack, (int) (start + offset), offsetsize); + final VPackSlice key = new VPackSlice(vpack, (int) (start + keyIndex)); + int res = 0; + if (key.isString()) { + res = key.compareString(attribute); + } else if (key.isInteger()) { + // translate key + if (!useTranslator) { + // no attribute translator + throw new VPackNeedAttributeTranslatorException(); + } + res = key.translateUnchecked().compareString(attribute); + } else { + // invalid key + result = new VPackSlice(); + break; + } + if (res == 0) { + // found + result = new VPackSlice(vpack, key.start + key.getByteSize()); + break; + } + if (res > 0) { + if (index == 0) { + result = new VPackSlice(); + break; + } + r = index - 1; + } else { + l = index + 1; + } + if (r < l) { + result = new VPackSlice(); + break; + } + } + return result; + } + + private VPackSlice searchObjectKeyLinear( + final String attribute, + final long ieBase, + final int offsetsize, + final long n) throws VPackValueTypeException, VPackNeedAttributeTranslatorException { + + final boolean useTranslator = VPackSlice.attributeTranslator != null; + VPackSlice result = new VPackSlice(); + for (long index = 0; index < n; index++) { + final long offset = ieBase + index * offsetsize; + final long keyIndex = NumberUtil.toLong(vpack, (int) (start + offset), offsetsize); + final VPackSlice key = new VPackSlice(vpack, (int) (start + keyIndex)); + if (key.isString()) { + if (!key.isEqualString(attribute)) { + continue; + } + } else if (key.isInteger()) { + // translate key + if (!useTranslator) { + // no attribute translator + throw new VPackNeedAttributeTranslatorException(); + } + if (!key.translateUnchecked().isEqualString(attribute)) { + continue; + } + } else { + // invalid key type + result = new VPackSlice(); + break; + } + // key is identical. now return value + result = new VPackSlice(vpack, key.start + key.getByteSize()); + break; + } + return result; + + } + + public VPackSlice keyAt(final int index) { + if (!isObject()) { + throw new VPackValueTypeException(ValueType.OBJECT); + } + return getNthKey(index); + } + + public VPackSlice valueAt(final int index) { + if (!isObject()) { + throw new VPackValueTypeException(ValueType.OBJECT); + } + final VPackSlice key = getNthKey(index); + return new VPackSlice(vpack, key.start + key.getByteSize()); + } + + private VPackSlice getNthKey(final int index) { + return new VPackSlice(vpack, start + getNthOffset(index)); + } + + private VPackSlice getNth(final int index) { + return new VPackSlice(vpack, start + getNthOffset(index)); + } + + /** + * + * @return the offset for the nth member from an Array or Object type + */ + private int getNthOffset(final int index) { + final int offset; + final byte head = head(); + if (head == 0x13 || head == 0x14) { + // compact Array or Object + offset = getNthOffsetFromCompact(index); + } else if (head == 0x01 || head == 0x0a) { + // special case: empty Array or empty Object + throw new IndexOutOfBoundsException(); + } else { + final long n; + final int offsetsize = ObjectArrayUtil.getOffsetSize(head); + final long end = NumberUtil.toLong(vpack, start + 1, offsetsize); + int dataOffset = findDataOffset(); + if (head <= 0x05) { + // array with no offset table or length + final VPackSlice first = new VPackSlice(vpack, start + dataOffset); + n = (end - dataOffset) / first.getByteSize(); + } else if (offsetsize < 8) { + n = NumberUtil.toLong(vpack, start + 1 + offsetsize, offsetsize); + } else { + n = NumberUtil.toLong(vpack, (int) (start + end - offsetsize), offsetsize); + } + if (index >= n) { + throw new IndexOutOfBoundsException(); + } + if (head <= 0x05 || n == 1) { + // no index table, but all array items have the same length + // or only one item is in the array + // now fetch first item and determine its length + if (dataOffset == 0) { + dataOffset = findDataOffset(); + } + offset = dataOffset + index * new VPackSlice(vpack, start + dataOffset).getByteSize(); + } else { + final long ieBase = end - n * offsetsize + index * offsetsize - (offsetsize == 8 ? 8 : 0); + offset = (int) NumberUtil.toLong(vpack, (int) (start + ieBase), offsetsize); + } + } + return offset; + } + + /** + * @return the offset for the nth member from a compact Array or Object type + */ + private int getNthOffsetFromCompact(final int index) { + final long end = NumberUtil.readVariableValueLength(vpack, start + 1, false); + final long n = NumberUtil.readVariableValueLength(vpack, (int) (start + end - 1), true); + if (index >= n) { + throw new IndexOutOfBoundsException(); + } + final byte head = head(); + long offset = 1 + NumberUtil.getVariableValueLength(end); + long current = 0; + while (current != index) { + final long byteSize = new VPackSlice(vpack, (int) (start + offset)).getByteSize(); + offset += byteSize; + if (head == 0x14) { + offset += byteSize; + } + ++current; + } + return (int) offset; + } + + private boolean isEqualString(final String s) { + final String string = getAsString(); + return string.equals(s); + } + + private int compareString(final String s) { + final String string = getAsString(); + return string.compareTo(s); + } + + public Iterator arrayIterator() { + if (isArray()) { + return new ArrayIterator(this); + } else { + throw new VPackValueTypeException(ValueType.ARRAY); + } + } + + public Iterator> objectIterator() { + if (isObject()) { + return new ObjectIterator(this); + } else { + throw new VPackValueTypeException(ValueType.OBJECT); + } + } + + protected byte[] getRawVPack() { + return Arrays.copyOfRange(vpack, start, start + getByteSize()); + } + + @Override + public String toString() { + try { + return new VPackParser().toJson(this, true); + } catch (final VPackException e) { + return super.toString(); + } + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + start; + result = prime * result + Arrays.hashCode(getRawVPack()); + 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 VPackSlice other = (VPackSlice) obj; + if (start != other.start) { + return false; + } + if (!Arrays.equals(getRawVPack(), other.getRawVPack())) { + return false; + } + return true; + } + +} diff --git a/src/main/java/com/arangodb/velocypack/ValueType.java b/src/main/java/com/arangodb/velocypack/ValueType.java new file mode 100644 index 000000000..d07174772 --- /dev/null +++ b/src/main/java/com/arangodb/velocypack/ValueType.java @@ -0,0 +1,47 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.velocypack; + +/** + * @author Mark - mark at arangodb.com + * + */ +public enum ValueType { + NONE, // not yet initialized + ILLEGAL, // illegal value + NULL, // JSON null + BOOL, + ARRAY, + OBJECT, + DOUBLE, + UTC_DATE, // UTC Date + EXTERNAL, + MIN_KEY, + MAX_KEY, + INT, + UINT, + SMALLINT, + STRING, + BINARY, + BCD, + CUSTOM, + VPACK +} diff --git a/src/main/java/com/arangodb/annotations/Exclude.java b/src/main/java/com/arangodb/velocypack/annotations/Expose.java similarity index 65% rename from src/main/java/com/arangodb/annotations/Exclude.java rename to src/main/java/com/arangodb/velocypack/annotations/Expose.java index 37e5f3998..83bb7f663 100644 --- a/src/main/java/com/arangodb/annotations/Exclude.java +++ b/src/main/java/com/arangodb/velocypack/annotations/Expose.java @@ -1,35 +1,40 @@ -/* - * Copyright (C) 2012,2013 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.annotations; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * @author tamtam180 - kirscheless at gmail.com - * @since 1.4.0 - */ -@Retention(RetentionPolicy.RUNTIME) -@Target(ElementType.FIELD) -public @interface Exclude { - - public boolean serialize() default true; - public boolean deserialize() default true; - -} +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.velocypack.annotations; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * @author Mark - mark at arangodb.com + * + */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.FIELD) +public @interface Expose { + + boolean serialize() default true; + + boolean deserialize() default true; + +} diff --git a/src/main/java/com/arangodb/annotations/DocumentKey.java b/src/main/java/com/arangodb/velocypack/annotations/SerializedName.java similarity index 65% rename from src/main/java/com/arangodb/annotations/DocumentKey.java rename to src/main/java/com/arangodb/velocypack/annotations/SerializedName.java index abed0420d..2a41d501a 100644 --- a/src/main/java/com/arangodb/annotations/DocumentKey.java +++ b/src/main/java/com/arangodb/velocypack/annotations/SerializedName.java @@ -1,35 +1,38 @@ -/* - * Copyright (C) 2012,2013 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.annotations; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * @author tamtam180 - kirscheless at gmail.com - * @since 1.4.1 - */ -@Retention(RetentionPolicy.RUNTIME) -@Target(ElementType.FIELD) -public @interface DocumentKey { - - public boolean serialize() default true; - public boolean deserialize() default true; - -} +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.velocypack.annotations; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * @author Mark - mark at arangodb.com + * + */ +@Retention(RetentionPolicy.RUNTIME) +@Target({ ElementType.FIELD }) +public @interface SerializedName { + + String value(); + +} diff --git a/src/main/java/com/arangodb/velocypack/exception/VPackBuilderException.java b/src/main/java/com/arangodb/velocypack/exception/VPackBuilderException.java new file mode 100644 index 000000000..257dac356 --- /dev/null +++ b/src/main/java/com/arangodb/velocypack/exception/VPackBuilderException.java @@ -0,0 +1,43 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.velocypack.exception; + +/** + * @author Mark - mark at arangodb.com + * + */ +public class VPackBuilderException extends VPackException { + + private static final long serialVersionUID = -8439245715363257017L; + + public VPackBuilderException() { + super(); + } + + public VPackBuilderException(final String message) { + super(message); + } + + public VPackBuilderException(final Throwable cause) { + super(cause); + } + +} diff --git a/src/main/java/com/arangodb/velocypack/exception/VPackBuilderKeyAlreadyWrittenException.java b/src/main/java/com/arangodb/velocypack/exception/VPackBuilderKeyAlreadyWrittenException.java new file mode 100644 index 000000000..fb2515702 --- /dev/null +++ b/src/main/java/com/arangodb/velocypack/exception/VPackBuilderKeyAlreadyWrittenException.java @@ -0,0 +1,35 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.velocypack.exception; + +/** + * @author Mark - mark at arangodb.com + * + */ +public class VPackBuilderKeyAlreadyWrittenException extends VPackBuilderException { + + private static final long serialVersionUID = -1958878757748616132L; + + public VPackBuilderKeyAlreadyWrittenException() { + super(); + } + +} diff --git a/src/main/java/com/arangodb/velocypack/exception/VPackBuilderNeedOpenCompoundException.java b/src/main/java/com/arangodb/velocypack/exception/VPackBuilderNeedOpenCompoundException.java new file mode 100644 index 000000000..c1af26fc9 --- /dev/null +++ b/src/main/java/com/arangodb/velocypack/exception/VPackBuilderNeedOpenCompoundException.java @@ -0,0 +1,35 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.velocypack.exception; + +/** + * @author Mark - mark at arangodb.com + * + */ +public class VPackBuilderNeedOpenCompoundException extends VPackBuilderException { + + private static final long serialVersionUID = 7985444459377106986L; + + public VPackBuilderNeedOpenCompoundException() { + super(); + } + +} diff --git a/src/main/java/com/arangodb/velocypack/exception/VPackBuilderNeedOpenObjectException.java b/src/main/java/com/arangodb/velocypack/exception/VPackBuilderNeedOpenObjectException.java new file mode 100644 index 000000000..3c157b8f6 --- /dev/null +++ b/src/main/java/com/arangodb/velocypack/exception/VPackBuilderNeedOpenObjectException.java @@ -0,0 +1,55 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.velocypack.exception; + +/** + * @author Mark - mark at arangodb.com + * + */ +public class VPackBuilderNeedOpenObjectException extends VPackBuilderNeedOpenCompoundException { + + private static final long serialVersionUID = 7005556054918252752L; + + public VPackBuilderNeedOpenObjectException() { + super(); + } + +} diff --git a/src/main/java/com/arangodb/velocypack/exception/VPackBuilderNumberOutOfRangeException.java b/src/main/java/com/arangodb/velocypack/exception/VPackBuilderNumberOutOfRangeException.java new file mode 100644 index 000000000..09a803c16 --- /dev/null +++ b/src/main/java/com/arangodb/velocypack/exception/VPackBuilderNumberOutOfRangeException.java @@ -0,0 +1,37 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.velocypack.exception; + +import com.arangodb.velocypack.ValueType; + +/** + * @author Mark - mark at arangodb.com + * + */ +public class VPackBuilderNumberOutOfRangeException extends VPackBuilderException { + + private static final long serialVersionUID = 7173727199390076286L; + + public VPackBuilderNumberOutOfRangeException(final ValueType type) { + super(String.format("Number out of range of %s.%s", type.getClass().getSimpleName(), type.name())); + } + +} diff --git a/src/main/java/com/arangodb/velocypack/exception/VPackBuilderUnexpectedValueException.java b/src/main/java/com/arangodb/velocypack/exception/VPackBuilderUnexpectedValueException.java new file mode 100644 index 000000000..35a726fc3 --- /dev/null +++ b/src/main/java/com/arangodb/velocypack/exception/VPackBuilderUnexpectedValueException.java @@ -0,0 +1,61 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.velocypack.exception; + +import com.arangodb.velocypack.ValueType; + +/** + * @author Mark - mark at arangodb.com + * + */ +public class VPackBuilderUnexpectedValueException extends VPackBuilderException { + + private static final long serialVersionUID = -7365305871886897353L; + + public VPackBuilderUnexpectedValueException(final ValueType type, final Class... classes) { + super(createMessage(type, null, classes)); + } + + public VPackBuilderUnexpectedValueException(final ValueType type, final String specify, final Class... classes) { + super(createMessage(type, specify, classes)); + } + + private static String createMessage(final ValueType type, final String specify, final Class... classes) { + final StringBuilder sb = new StringBuilder(); + sb.append("Must give "); + if (specify != null) { + sb.append(specify); + sb.append(" "); + } + for (int i = 0; i < classes.length; i++) { + if (i > 0) { + sb.append(" or "); + } + sb.append(classes[i].getSimpleName()); + } + sb.append(" for "); + sb.append(type.getClass().getSimpleName()); + sb.append("."); + sb.append(type.name()); + return sb.toString(); + } + +} diff --git a/src/main/java/com/arangodb/velocypack/exception/VPackException.java b/src/main/java/com/arangodb/velocypack/exception/VPackException.java new file mode 100644 index 000000000..bee1b2ee5 --- /dev/null +++ b/src/main/java/com/arangodb/velocypack/exception/VPackException.java @@ -0,0 +1,43 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.velocypack.exception; + +/** + * @author Mark - mark at arangodb.com + * + */ +public abstract class VPackException extends RuntimeException { + + private static final long serialVersionUID = 3547943271830879415L; + + protected VPackException() { + super(); + } + + protected VPackException(final String message) { + super(message); + } + + protected VPackException(final Throwable cause) { + super(cause); + } + +} diff --git a/src/main/java/com/arangodb/velocypack/exception/VPackKeyTypeException.java b/src/main/java/com/arangodb/velocypack/exception/VPackKeyTypeException.java new file mode 100644 index 000000000..49a25216f --- /dev/null +++ b/src/main/java/com/arangodb/velocypack/exception/VPackKeyTypeException.java @@ -0,0 +1,35 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.velocypack.exception; + +/** + * @author Mark - mark at arangodb.com + * + */ +public class VPackKeyTypeException extends VPackException { + + private static final long serialVersionUID = 1328826711387001473L; + + public VPackKeyTypeException(final String message) { + super(message); + } + +} diff --git a/src/main/java/com/arangodb/entity/BooleanResultEntity.java b/src/main/java/com/arangodb/velocypack/exception/VPackNeedAttributeTranslatorException.java similarity index 55% rename from src/main/java/com/arangodb/entity/BooleanResultEntity.java rename to src/main/java/com/arangodb/velocypack/exception/VPackNeedAttributeTranslatorException.java index 2451412b9..24147eed7 100644 --- a/src/main/java/com/arangodb/entity/BooleanResultEntity.java +++ b/src/main/java/com/arangodb/velocypack/exception/VPackNeedAttributeTranslatorException.java @@ -1,41 +1,31 @@ -/* - * Copyright (C) 2012,2013 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.entity; - -/** - * - * Entity representing a boolean result. - * - * @author tamtam180 - kirscheless at gmail.com - * - */ -public class BooleanResultEntity extends BaseEntity { - - /** - * The result - */ - Boolean result; - - public Boolean getResult() { - return result; - } - - public void setResult(Boolean result) { - this.result = result; - } - -} +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.velocypack.exception; + +/** + * @author Mark - mark at arangodb.com + * + */ +public class VPackNeedAttributeTranslatorException extends VPackException { + + private static final long serialVersionUID = -676583112112943083L; + +} diff --git a/src/main/java/com/arangodb/util/DumpHandlerAdapter.java b/src/main/java/com/arangodb/velocypack/exception/VPackParserException.java similarity index 52% rename from src/main/java/com/arangodb/util/DumpHandlerAdapter.java rename to src/main/java/com/arangodb/velocypack/exception/VPackParserException.java index 43e3fed19..ea0efe8c9 100644 --- a/src/main/java/com/arangodb/util/DumpHandlerAdapter.java +++ b/src/main/java/com/arangodb/velocypack/exception/VPackParserException.java @@ -1,38 +1,35 @@ -/* - * Copyright (C) 2012,2013 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.util; - -import com.arangodb.entity.ReplicationDumpHeader; -import com.arangodb.entity.ReplicationDumpRecord; - -/** - * @author tamtam180 - kirscheless at gmail.com - * - */ -public class DumpHandlerAdapter implements DumpHandler { - - @Override - public boolean head(ReplicationDumpHeader header) { - return true; - } - - @Override - public boolean handle(ReplicationDumpRecord entity) { - return false; - } - -} +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.velocypack.exception; + +/** + * @author Mark - mark at arangodb.com + * + */ +public class VPackParserException extends VPackException { + + private static final long serialVersionUID = 2374233320699603759L; + + public VPackParserException(final Throwable cause) { + super(cause); + } + +} diff --git a/src/main/java/com/arangodb/velocypack/exception/VPackValueTypeException.java b/src/main/java/com/arangodb/velocypack/exception/VPackValueTypeException.java new file mode 100644 index 000000000..48aab5760 --- /dev/null +++ b/src/main/java/com/arangodb/velocypack/exception/VPackValueTypeException.java @@ -0,0 +1,49 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.velocypack.exception; + +import com.arangodb.velocypack.ValueType; + +/** + * @author Mark - mark at arangodb.com + * + */ +public class VPackValueTypeException extends VPackException { + + private static final long serialVersionUID = 8128171173539033177L; + + public VPackValueTypeException(final ValueType... types) { + super(createMessage(types)); + } + + private static String createMessage(final ValueType... types) { + final StringBuilder sb = new StringBuilder(); + sb.append("Expecting type "); + for (int i = 0; i < types.length; i++) { + if (i > 0) { + sb.append(" or "); + } + sb.append(types[i].name()); + } + return sb.toString(); + } + +} diff --git a/src/main/java/com/arangodb/velocypack/internal/DefaultVPackBuilderOptions.java b/src/main/java/com/arangodb/velocypack/internal/DefaultVPackBuilderOptions.java new file mode 100644 index 000000000..264536e7b --- /dev/null +++ b/src/main/java/com/arangodb/velocypack/internal/DefaultVPackBuilderOptions.java @@ -0,0 +1,60 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.velocypack.internal; + +import com.arangodb.velocypack.VPackBuilder.BuilderOptions; + +/** + * @author Mark - mark at arangodb.com + * + */ +public class DefaultVPackBuilderOptions implements BuilderOptions { + + private boolean buildUnindexedArrays; + private boolean buildUnindexedObjects; + + public DefaultVPackBuilderOptions() { + super(); + buildUnindexedArrays = false; + buildUnindexedObjects = false; + } + + @Override + public boolean isBuildUnindexedArrays() { + return buildUnindexedArrays; + } + + @Override + public void setBuildUnindexedArrays(final boolean buildUnindexedArrays) { + this.buildUnindexedArrays = buildUnindexedArrays; + } + + @Override + public boolean isBuildUnindexedObjects() { + return buildUnindexedObjects; + } + + @Override + public void setBuildUnindexedObjects(final boolean buildUnindexedObjects) { + this.buildUnindexedObjects = buildUnindexedObjects; + } + +} diff --git a/src/main/java/com/arangodb/velocypack/internal/VPackAttributeTranslatorImpl.java b/src/main/java/com/arangodb/velocypack/internal/VPackAttributeTranslatorImpl.java new file mode 100644 index 000000000..0b88f9b3d --- /dev/null +++ b/src/main/java/com/arangodb/velocypack/internal/VPackAttributeTranslatorImpl.java @@ -0,0 +1,106 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.velocypack.internal; + +import java.util.HashMap; +import java.util.Map; + +import com.arangodb.velocypack.VPackAttributeTranslator; +import com.arangodb.velocypack.VPackBuilder; +import com.arangodb.velocypack.VPackSlice; +import com.arangodb.velocypack.ValueType; +import com.arangodb.velocypack.exception.VPackException; + +/** + * @author Mark - mark at arangodb.com + * + */ +public class VPackAttributeTranslatorImpl implements VPackAttributeTranslator { + + private static final String KEY = "_key"; + private static final String REV = "_rev"; + private static final String ID = "_id"; + private static final String FROM = "_from"; + private static final String TO = "_to"; + + private static final byte KEY_ATTRIBUTE = 0x31; + private static final byte REV_ATTRIBUTE = 0x32; + private static final byte ID_ATTRIBUTE = 0x33; + private static final byte FROM_ATTRIBUTE = 0x34; + private static final byte TO_ATTRIBUTE = 0x35; + private static final byte ATTRIBUTE_BASE = 0x30; + + private VPackBuilder builder; + private final Map attributeToKey; + private final Map keyToAttribute; + + public VPackAttributeTranslatorImpl() { + super(); + builder = null; + attributeToKey = new HashMap(); + keyToAttribute = new HashMap(); + try { + add(KEY, KEY_ATTRIBUTE - ATTRIBUTE_BASE); + add(REV, REV_ATTRIBUTE - ATTRIBUTE_BASE); + add(ID, ID_ATTRIBUTE - ATTRIBUTE_BASE); + add(FROM, FROM_ATTRIBUTE - ATTRIBUTE_BASE); + add(TO, TO_ATTRIBUTE - ATTRIBUTE_BASE); + seal(); + } catch (final VPackException e) { + throw new RuntimeException(e); + } + } + + @Override + public void add(final String attribute, final int key) throws VPackException { + if (builder == null) { + builder = new VPackBuilder(); + builder.add(ValueType.OBJECT); + } + builder.add(attribute, key); + } + + @Override + public void seal() throws VPackException { + if (builder == null) { + return; + } + builder.close(); + final VPackSlice slice = builder.slice(); + for (int i = 0; i < slice.getLength(); i++) { + final VPackSlice key = slice.keyAt(i); + final VPackSlice value = slice.valueAt(i); + attributeToKey.put(key.getAsString(), value); + keyToAttribute.put(value.getAsInt(), key); + } + } + + @Override + public VPackSlice translate(final String attribute) { + return attributeToKey.get(attribute); + } + + @Override + public VPackSlice translate(final int key) { + return keyToAttribute.get(key); + } + +} diff --git a/src/main/java/com/arangodb/velocypack/internal/VPackCache.java b/src/main/java/com/arangodb/velocypack/internal/VPackCache.java new file mode 100644 index 000000000..ac256e287 --- /dev/null +++ b/src/main/java/com/arangodb/velocypack/internal/VPackCache.java @@ -0,0 +1,166 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.velocypack.internal; + +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; + +import com.arangodb.velocypack.VPackFieldNamingStrategy; +import com.arangodb.velocypack.annotations.Expose; +import com.arangodb.velocypack.annotations.SerializedName; + +/** + * @author Mark - mark at arangodb.com + * + */ +public class VPackCache { + + public abstract static class FieldInfo { + private final Type type; + private final String fieldName; + private final boolean serialize; + private final boolean deserialize; + + private FieldInfo(final Type type, final String fieldName, final boolean serialize, final boolean deserialize) { + super(); + this.type = type; + this.fieldName = fieldName; + this.serialize = serialize; + this.deserialize = deserialize; + } + + public Type getType() { + return type; + } + + public String getFieldName() { + return fieldName; + } + + public boolean isSerialize() { + return serialize; + } + + public boolean isDeserialize() { + return deserialize; + } + + public abstract void set(Object obj, Object value) throws IllegalAccessException; + + public abstract Object get(Object obj) throws IllegalAccessException; + } + + private final Map> cache; + private final Comparator> fieldComparator; + private final VPackFieldNamingStrategy fieldNamingStrategy; + + public VPackCache(final VPackFieldNamingStrategy fieldNamingStrategy) { + super(); + cache = new ConcurrentHashMap>(); + fieldComparator = new Comparator>() { + @Override + public int compare(final Entry o1, final Entry o2) { + return o1.getKey().compareTo(o2.getKey()); + } + }; + this.fieldNamingStrategy = fieldNamingStrategy; + } + + public Map getFields(final Type entityClass) { + Map fields = cache.get(entityClass); + if (fields == null) { + fields = new HashMap(); + Class tmp = (Class) entityClass; + while (tmp != null && tmp != Object.class) { + final Field[] declaredFields = tmp.getDeclaredFields(); + for (final Field field : declaredFields) { + if (!field.isSynthetic() && !Modifier.isStatic(field.getModifiers())) { + field.setAccessible(true); + final FieldInfo fieldInfo = createFieldInfo(field); + if (fieldInfo.serialize || fieldInfo.deserialize) { + fields.put(fieldInfo.getFieldName(), fieldInfo); + } + } + } + tmp = tmp.getSuperclass(); + } + fields = sort(fields.entrySet()); + cache.put(entityClass, fields); + } + return fields; + } + + private Map sort(final Set> entrySet) { + final Map sorted = new LinkedHashMap(); + final List> tmp = new ArrayList>(entrySet); + Collections.sort(tmp, fieldComparator); + for (final Entry entry : tmp) { + sorted.put(entry.getKey(), entry.getValue()); + } + return sorted; + } + + private FieldInfo createFieldInfo(final Field field) { + String fieldName = field.getName(); + if (fieldNamingStrategy != null) { + fieldName = fieldNamingStrategy.translateName(field); + } + final SerializedName annotationName = field.getAnnotation(SerializedName.class); + if (annotationName != null) { + fieldName = annotationName.value(); + } + final Expose expose = field.getAnnotation(Expose.class); + final boolean serialize = expose != null ? expose.serialize() : true; + final boolean deserialize = expose != null ? expose.deserialize() : true; + final Class clazz = field.getType(); + final Type type; + if (Collection.class.isAssignableFrom(clazz) || Map.class.isAssignableFrom(clazz)) { + type = (ParameterizedType) field.getGenericType(); + } else { + type = clazz; + } + return new FieldInfo(type, fieldName, serialize, deserialize) { + @Override + public void set(final Object obj, final Object value) throws IllegalAccessException { + field.set(obj, value); + } + + @Override + public Object get(final Object obj) throws IllegalAccessException { + return field.get(obj); + } + }; + } + +} diff --git a/src/main/java/com/arangodb/velocypack/internal/VPackDeserializers.java b/src/main/java/com/arangodb/velocypack/internal/VPackDeserializers.java new file mode 100644 index 000000000..614416b8b --- /dev/null +++ b/src/main/java/com/arangodb/velocypack/internal/VPackDeserializers.java @@ -0,0 +1,179 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.velocypack.internal; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.sql.Timestamp; +import java.util.Date; + +import com.arangodb.velocypack.VPackDeserializationContext; +import com.arangodb.velocypack.VPackDeserializer; +import com.arangodb.velocypack.VPackSlice; +import com.arangodb.velocypack.exception.VPackException; + +/** + * @author Mark - mark at arangodb.com + * + */ +public class VPackDeserializers { + + private VPackDeserializers() { + super(); + } + + public static final VPackDeserializer STRING = new VPackDeserializer() { + @Override + public String deserialize( + final VPackSlice parent, + final VPackSlice vpack, + final VPackDeserializationContext context) throws VPackException { + return vpack.getAsString(); + } + }; + public static final VPackDeserializer BOOLEAN = new VPackDeserializer() { + @Override + public Boolean deserialize( + final VPackSlice parent, + final VPackSlice vpack, + final VPackDeserializationContext context) throws VPackException { + return vpack.getAsBoolean(); + } + }; + public static final VPackDeserializer INTEGER = new VPackDeserializer() { + @Override + public Integer deserialize( + final VPackSlice parent, + final VPackSlice vpack, + final VPackDeserializationContext context) throws VPackException { + return vpack.getAsInt(); + } + }; + public static final VPackDeserializer LONG = new VPackDeserializer() { + @Override + public Long deserialize( + final VPackSlice parent, + final VPackSlice vpack, + final VPackDeserializationContext context) throws VPackException { + return vpack.getAsLong(); + } + }; + public static final VPackDeserializer SHORT = new VPackDeserializer() { + @Override + public Short deserialize( + final VPackSlice parent, + final VPackSlice vpack, + final VPackDeserializationContext context) throws VPackException { + return vpack.getAsShort(); + } + }; + public static final VPackDeserializer DOUBLE = new VPackDeserializer() { + @Override + public Double deserialize( + final VPackSlice parent, + final VPackSlice vpack, + final VPackDeserializationContext context) throws VPackException { + return vpack.getAsDouble(); + } + }; + public static final VPackDeserializer FLOAT = new VPackDeserializer() { + @Override + public Float deserialize( + final VPackSlice parent, + final VPackSlice vpack, + final VPackDeserializationContext context) throws VPackException { + return vpack.getAsFloat(); + } + }; + public static final VPackDeserializer BIG_INTEGER = new VPackDeserializer() { + @Override + public BigInteger deserialize( + final VPackSlice parent, + final VPackSlice vpack, + final VPackDeserializationContext context) throws VPackException { + return vpack.getAsBigInteger(); + } + }; + public static final VPackDeserializer BIG_DECIMAL = new VPackDeserializer() { + @Override + public BigDecimal deserialize( + final VPackSlice parent, + final VPackSlice vpack, + final VPackDeserializationContext context) throws VPackException { + return vpack.getAsBigDecimal(); + } + }; + public static final VPackDeserializer NUMBER = new VPackDeserializer() { + @Override + public Number deserialize( + final VPackSlice parent, + final VPackSlice vpack, + final VPackDeserializationContext context) throws VPackException { + return vpack.getAsNumber(); + } + }; + public static final VPackDeserializer CHARACTER = new VPackDeserializer() { + @Override + public Character deserialize( + final VPackSlice parent, + final VPackSlice vpack, + final VPackDeserializationContext context) throws VPackException { + return vpack.getAsChar(); + } + }; + public static final VPackDeserializer DATE = new VPackDeserializer() { + @Override + public Date deserialize( + final VPackSlice parent, + final VPackSlice vpack, + final VPackDeserializationContext context) throws VPackException { + return vpack.getAsDate(); + } + }; + public static final VPackDeserializer SQL_DATE = new VPackDeserializer() { + @Override + public java.sql.Date deserialize( + final VPackSlice parent, + final VPackSlice vpack, + final VPackDeserializationContext context) throws VPackException { + return vpack.getAsSQLDate(); + } + }; + public static final VPackDeserializer SQL_TIMESTAMP = new VPackDeserializer() { + @Override + public Timestamp deserialize( + final VPackSlice parent, + final VPackSlice vpack, + final VPackDeserializationContext context) throws VPackException { + return vpack.getAsSQLTimestamp(); + } + }; + public static final VPackDeserializer VPACK = new VPackDeserializer() { + @Override + public VPackSlice deserialize( + final VPackSlice parent, + final VPackSlice vpack, + final VPackDeserializationContext context) throws VPackException { + return vpack; + } + }; + +} diff --git a/src/main/java/com/arangodb/velocypack/internal/VPackInstanceCreators.java b/src/main/java/com/arangodb/velocypack/internal/VPackInstanceCreators.java new file mode 100644 index 000000000..2695d7d03 --- /dev/null +++ b/src/main/java/com/arangodb/velocypack/internal/VPackInstanceCreators.java @@ -0,0 +1,69 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.velocypack.internal; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.arangodb.velocypack.VPackInstanceCreator; + +/** + * @author Mark - mark at arangodb.com + * + */ +@SuppressWarnings("rawtypes") +public class VPackInstanceCreators { + + private VPackInstanceCreators() { + super(); + } + + public static final VPackInstanceCreator COLLECTION = new VPackInstanceCreator() { + @Override + public Collection createInstance() { + return new ArrayList(); + } + }; + public static final VPackInstanceCreator LIST = new VPackInstanceCreator() { + @Override + public List createInstance() { + return new ArrayList(); + } + }; + public static final VPackInstanceCreator SET = new VPackInstanceCreator() { + @Override + public Set createInstance() { + return new HashSet(); + } + }; + public static final VPackInstanceCreator MAP = new VPackInstanceCreator() { + @Override + public Map createInstance() { + return new HashMap(); + } + }; + +} diff --git a/src/main/java/com/arangodb/velocypack/internal/VPackKeyMapAdapters.java b/src/main/java/com/arangodb/velocypack/internal/VPackKeyMapAdapters.java new file mode 100644 index 000000000..2a7b75549 --- /dev/null +++ b/src/main/java/com/arangodb/velocypack/internal/VPackKeyMapAdapters.java @@ -0,0 +1,176 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.velocypack.internal; + +import java.lang.reflect.Type; +import java.math.BigDecimal; +import java.math.BigInteger; + +import com.arangodb.velocypack.VPackKeyMapAdapter; + +/** + * @author Mark - mark at arangodb.com + * + */ +public class VPackKeyMapAdapters { + + private VPackKeyMapAdapters() { + super(); + } + + public static final VPackKeyMapAdapter> createEnumAdapter(final Type type) { + return new VPackKeyMapAdapter>() { + @Override + public String serialize(final Enum key) { + return key.name(); + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + @Override + public Enum deserialize(final String key) { + final Class enumType = (Class) type; + return Enum.valueOf(enumType, key); + } + }; + } + + public static final VPackKeyMapAdapter STRING = new VPackKeyMapAdapter() { + @Override + public String serialize(final String key) { + return key; + } + + @Override + public String deserialize(final String key) { + return key; + } + }; + public static final VPackKeyMapAdapter BOOLEAN = new VPackKeyMapAdapter() { + @Override + public String serialize(final Boolean key) { + return key.toString(); + } + + @Override + public Boolean deserialize(final String key) { + return Boolean.valueOf(key); + } + }; + public static final VPackKeyMapAdapter INTEGER = new VPackKeyMapAdapter() { + @Override + public String serialize(final Integer key) { + return key.toString(); + } + + @Override + public Integer deserialize(final String key) { + return Integer.valueOf(key); + } + }; + public static final VPackKeyMapAdapter LONG = new VPackKeyMapAdapter() { + @Override + public String serialize(final Long key) { + return key.toString(); + } + + @Override + public Long deserialize(final String key) { + return Long.valueOf(key); + } + }; + public static final VPackKeyMapAdapter SHORT = new VPackKeyMapAdapter() { + @Override + public String serialize(final Short key) { + return key.toString(); + } + + @Override + public Short deserialize(final String key) { + return Short.valueOf(key); + } + }; + public static final VPackKeyMapAdapter DOUBLE = new VPackKeyMapAdapter() { + @Override + public String serialize(final Double key) { + return key.toString(); + } + + @Override + public Double deserialize(final String key) { + return Double.valueOf(key); + } + }; + public static final VPackKeyMapAdapter FLOAT = new VPackKeyMapAdapter() { + @Override + public String serialize(final Float key) { + return key.toString(); + } + + @Override + public Float deserialize(final String key) { + return Float.valueOf(key); + } + }; + public static final VPackKeyMapAdapter BIG_INTEGER = new VPackKeyMapAdapter() { + @Override + public String serialize(final BigInteger key) { + return key.toString(); + } + + @Override + public BigInteger deserialize(final String key) { + return new BigInteger(key); + } + }; + public static final VPackKeyMapAdapter BIG_DECIMAL = new VPackKeyMapAdapter() { + @Override + public String serialize(final BigDecimal key) { + return key.toString(); + } + + @Override + public BigDecimal deserialize(final String key) { + return new BigDecimal(key); + } + }; + public static final VPackKeyMapAdapter NUMBER = new VPackKeyMapAdapter() { + @Override + public String serialize(final Number key) { + return key.toString(); + } + + @Override + public Number deserialize(final String key) { + return Double.valueOf(key); + } + }; + public static final VPackKeyMapAdapter CHARACTER = new VPackKeyMapAdapter() { + @Override + public String serialize(final Character key) { + return key.toString(); + } + + @Override + public Character deserialize(final String key) { + return key.charAt(0); + } + }; +} diff --git a/src/main/java/com/arangodb/velocypack/internal/VPackSerializers.java b/src/main/java/com/arangodb/velocypack/internal/VPackSerializers.java new file mode 100644 index 000000000..ac6585276 --- /dev/null +++ b/src/main/java/com/arangodb/velocypack/internal/VPackSerializers.java @@ -0,0 +1,194 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.velocypack.internal; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.sql.Timestamp; +import java.util.Date; + +import com.arangodb.velocypack.VPackBuilder; +import com.arangodb.velocypack.VPackSerializationContext; +import com.arangodb.velocypack.VPackSerializer; +import com.arangodb.velocypack.VPackSlice; +import com.arangodb.velocypack.exception.VPackException; + +/** + * @author Mark - mark at arangodb.com + * + */ +public class VPackSerializers { + + private VPackSerializers() { + super(); + } + + public static VPackSerializer STRING = new VPackSerializer() { + @Override + public void serialize( + final VPackBuilder builder, + final String attribute, + final String value, + final VPackSerializationContext context) throws VPackException { + builder.add(attribute, value); + } + }; + public static VPackSerializer BOOLEAN = new VPackSerializer() { + @Override + public void serialize( + final VPackBuilder builder, + final String attribute, + final Boolean value, + final VPackSerializationContext context) throws VPackException { + builder.add(attribute, value); + } + }; + public static VPackSerializer INTEGER = new VPackSerializer() { + @Override + public void serialize( + final VPackBuilder builder, + final String attribute, + final Integer value, + final VPackSerializationContext context) throws VPackException { + builder.add(attribute, value); + } + }; + public static VPackSerializer LONG = new VPackSerializer() { + @Override + public void serialize( + final VPackBuilder builder, + final String attribute, + final Long value, + final VPackSerializationContext context) throws VPackException { + builder.add(attribute, value); + } + }; + public static VPackSerializer SHORT = new VPackSerializer() { + @Override + public void serialize( + final VPackBuilder builder, + final String attribute, + final Short value, + final VPackSerializationContext context) throws VPackException { + builder.add(attribute, value); + } + }; + public static VPackSerializer DOUBLE = new VPackSerializer() { + @Override + public void serialize( + final VPackBuilder builder, + final String attribute, + final Double value, + final VPackSerializationContext context) throws VPackException { + builder.add(attribute, value); + } + }; + public static VPackSerializer FLOAT = new VPackSerializer() { + @Override + public void serialize( + final VPackBuilder builder, + final String attribute, + final Float value, + final VPackSerializationContext context) throws VPackException { + builder.add(attribute, value); + } + }; + public static VPackSerializer BIG_INTEGER = new VPackSerializer() { + @Override + public void serialize( + final VPackBuilder builder, + final String attribute, + final BigInteger value, + final VPackSerializationContext context) throws VPackException { + builder.add(attribute, value); + } + }; + public static VPackSerializer BIG_DECIMAL = new VPackSerializer() { + @Override + public void serialize( + final VPackBuilder builder, + final String attribute, + final BigDecimal value, + final VPackSerializationContext context) throws VPackException { + builder.add(attribute, value); + } + }; + public static VPackSerializer NUMBER = new VPackSerializer() { + @Override + public void serialize( + final VPackBuilder builder, + final String attribute, + final Number value, + final VPackSerializationContext context) throws VPackException { + builder.add(attribute, Double.class.cast(value)); + } + }; + public static VPackSerializer CHARACTER = new VPackSerializer() { + @Override + public void serialize( + final VPackBuilder builder, + final String attribute, + final Character value, + final VPackSerializationContext context) throws VPackException { + builder.add(attribute, value); + } + }; + public static VPackSerializer DATE = new VPackSerializer() { + @Override + public void serialize( + final VPackBuilder builder, + final String attribute, + final Date value, + final VPackSerializationContext context) throws VPackException { + builder.add(attribute, value); + } + }; + public static VPackSerializer SQL_DATE = new VPackSerializer() { + @Override + public void serialize( + final VPackBuilder builder, + final String attribute, + final java.sql.Date value, + final VPackSerializationContext context) throws VPackException { + builder.add(attribute, value); + } + }; + public static VPackSerializer SQL_TIMESTAMP = new VPackSerializer() { + @Override + public void serialize( + final VPackBuilder builder, + final String attribute, + final Timestamp value, + final VPackSerializationContext context) throws VPackException { + builder.add(attribute, value); + } + }; + public static VPackSerializer VPACK = new VPackSerializer() { + @Override + public void serialize( + final VPackBuilder builder, + final String attribute, + final VPackSlice value, + final VPackSerializationContext context) throws VPackException { + builder.add(attribute, value); + } + }; +} diff --git a/src/main/java/com/arangodb/velocypack/internal/Value.java b/src/main/java/com/arangodb/velocypack/internal/Value.java new file mode 100644 index 000000000..d3a0528d5 --- /dev/null +++ b/src/main/java/com/arangodb/velocypack/internal/Value.java @@ -0,0 +1,101 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.velocypack.internal; + +import java.math.BigInteger; + +import com.arangodb.velocypack.ValueType; +import com.arangodb.velocypack.exception.VPackValueTypeException; + +/** + * @author Mark - mark at arangodb.com + * + */ +public class Value { + + private final Object value; + + private final ValueType type; + private final Class clazz; + private final boolean unindexed; + + private Value(final Object value, final ValueType type, final Class clazz) { + this(value, type, clazz, false); + } + + private Value(final Object value, final ValueType type, final Class clazz, final boolean unindexed) { + super(); + this.value = value; + this.type = type; + this.clazz = clazz; + this.unindexed = unindexed; + } + + public Value(final ValueType type) { + this(type, false); + } + + public Value(final ValueType type, final boolean unindexed) throws VPackValueTypeException { + this(null, type, null, unindexed); + if (type != ValueType.ARRAY && type != ValueType.OBJECT && type != ValueType.NULL) { + throw new VPackValueTypeException(ValueType.ARRAY, ValueType.OBJECT, ValueType.NULL); + } + } + + public Value(final Long value, final ValueType type) throws VPackValueTypeException { + this(value, type, Long.class); + if (type != ValueType.INT && type != ValueType.UINT && type != ValueType.SMALLINT) { + throw new VPackValueTypeException(ValueType.INT, ValueType.UINT, ValueType.SMALLINT); + } + } + + public Value(final BigInteger value, final ValueType type) throws VPackValueTypeException { + this(value, type, BigInteger.class); + if (type != ValueType.INT && type != ValueType.UINT && type != ValueType.SMALLINT) { + throw new VPackValueTypeException(ValueType.INT, ValueType.UINT, ValueType.SMALLINT); + } + } + + public ValueType getType() { + return type; + } + + public Class getClazz() { + return clazz; + } + + public boolean isUnindexed() { + return unindexed; + } + + public Number getNumber() { + return (Number) value; + } + + public Long getLong() { + return (Long) value; + } + + public BigInteger getBigInteger() { + return (BigInteger) value; + } + +} diff --git a/src/main/java/com/arangodb/velocypack/internal/util/BinaryUtil.java b/src/main/java/com/arangodb/velocypack/internal/util/BinaryUtil.java new file mode 100644 index 000000000..e29adcff6 --- /dev/null +++ b/src/main/java/com/arangodb/velocypack/internal/util/BinaryUtil.java @@ -0,0 +1,41 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.velocypack.internal.util; + +/** + * @author Mark - mark at arangodb.com + * + */ +public class BinaryUtil { + + private BinaryUtil() { + super(); + } + + public static byte[] toBinary(final byte[] array, final int offset, final int length) { + final byte[] result = new byte[length]; + for (int i = offset, j = 0; j < length; i++, j++) { + result[j] = array[i]; + } + return result; + } + +} diff --git a/src/main/java/com/arangodb/velocypack/internal/util/DateUtil.java b/src/main/java/com/arangodb/velocypack/internal/util/DateUtil.java new file mode 100644 index 000000000..9d6103638 --- /dev/null +++ b/src/main/java/com/arangodb/velocypack/internal/util/DateUtil.java @@ -0,0 +1,48 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.velocypack.internal.util; + +/** + * @author Mark - mark at arangodb.com + * + */ +public class DateUtil { + + private DateUtil() { + super(); + } + + public static java.util.Date toDate(final byte[] array, final int offset, final int length) { + final long milliseconds = NumberUtil.toLong(array, offset, length); + return new java.util.Date(milliseconds); + } + + public static java.sql.Date toSQLDate(final byte[] array, final int offset, final int length) { + final long milliseconds = NumberUtil.toLong(array, offset, length); + return new java.sql.Date(milliseconds); + } + + public static java.sql.Timestamp toSQLTimestamp(final byte[] array, final int offset, final int length) { + final long milliseconds = NumberUtil.toLong(array, offset, length); + return new java.sql.Timestamp(milliseconds); + } + +} diff --git a/src/main/java/com/arangodb/velocypack/internal/util/NumberUtil.java b/src/main/java/com/arangodb/velocypack/internal/util/NumberUtil.java new file mode 100644 index 000000000..54505d001 --- /dev/null +++ b/src/main/java/com/arangodb/velocypack/internal/util/NumberUtil.java @@ -0,0 +1,93 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.velocypack.internal.util; + +import java.math.BigInteger; + +/** + * @author Mark - mark at arangodb.com + * + */ +public class NumberUtil { + + private static final int DOUBLE_BYTES = 8; + + private NumberUtil() { + super(); + } + + public static double toDouble(final byte[] array, final int offset, final int length) { + return Double.longBitsToDouble(toLong(array, offset, DOUBLE_BYTES)); + } + + public static long toLong(final byte[] array, final int offset, final int length) { + long result = 0; + for (int i = (offset + length - 1); i >= offset; i--) { + result <<= 8; + result |= (array[i] & 0xFF); + } + return result; + } + + public static BigInteger toBigInteger(final byte[] array, final int offset, final int length) { + BigInteger result = new BigInteger(1, new byte[] {}); + for (int i = (offset + length - 1); i >= offset; i--) { + result = result.shiftLeft(8); + result = result.or(BigInteger.valueOf(array[i] & 0xFF)); + } + return result; + } + + /** + * read a variable length integer in unsigned LEB128 format + */ + public static long readVariableValueLength(final byte[] array, final int offset, final boolean reverse) { + long len = 0; + byte v; + long p = 0; + int i = offset; + do { + v = array[i]; + len += ((long) (v & (byte) 0x7f)) << p; + p += 7; + if (reverse) { + --i; + } else { + ++i; + } + } while ((v & (byte) 0x80) != 0); + return len; + } + + /** + * calculate the length of a variable length integer in unsigned LEB128 format + */ + public static long getVariableValueLength(final long value) { + long len = 1; + long val = value; + while (val >= 0x80) { + val >>= 7; + ++len; + } + return len; + } + +} diff --git a/src/main/java/com/arangodb/velocypack/internal/util/ObjectArrayUtil.java b/src/main/java/com/arangodb/velocypack/internal/util/ObjectArrayUtil.java new file mode 100644 index 000000000..eb0a5fc27 --- /dev/null +++ b/src/main/java/com/arangodb/velocypack/internal/util/ObjectArrayUtil.java @@ -0,0 +1,94 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.velocypack.internal.util; + +import java.util.HashMap; +import java.util.Map; + +/** + * @author Mark - mark at arangodb.com + * + */ +public class ObjectArrayUtil { + + private static final Map FIRST_SUB_MAP; + + static { + FIRST_SUB_MAP = new HashMap(); + + FIRST_SUB_MAP.put((byte) 0x00, 0); // None + FIRST_SUB_MAP.put((byte) 0x01, 1); // empty array + FIRST_SUB_MAP.put((byte) 0x02, 2); // array without index table + FIRST_SUB_MAP.put((byte) 0x03, 3); // array without index table + FIRST_SUB_MAP.put((byte) 0x04, 5); // array without index table + FIRST_SUB_MAP.put((byte) 0x05, 9); // array without index table + FIRST_SUB_MAP.put((byte) 0x06, 3); // array with index table + FIRST_SUB_MAP.put((byte) 0x07, 5); // array with index table + FIRST_SUB_MAP.put((byte) 0x08, 9); // array with index table + FIRST_SUB_MAP.put((byte) 0x09, 9); // array with index table + FIRST_SUB_MAP.put((byte) 0x0a, 1); // empty object + FIRST_SUB_MAP.put((byte) 0x0b, 3); // object with sorted index table + FIRST_SUB_MAP.put((byte) 0x0c, 5); // object with sorted index table + FIRST_SUB_MAP.put((byte) 0x0d, 9); // object with sorted index table + FIRST_SUB_MAP.put((byte) 0x0e, 9); // object with sorted index table + FIRST_SUB_MAP.put((byte) 0x0f, 3); // object with unsorted index table + FIRST_SUB_MAP.put((byte) 0x10, 5); // object with unsorted index table + FIRST_SUB_MAP.put((byte) 0x11, 9); // object with unsorted index table + FIRST_SUB_MAP.put((byte) 0x12, 9); // object with unsorted index table + } + + public static int getFirstSubMap(final byte key) { + return FIRST_SUB_MAP.get(key); + } + + private static final Map OFFSET_SIZE; + static { + OFFSET_SIZE = new HashMap(); + + OFFSET_SIZE.put((byte) 0x00, 0); // None + OFFSET_SIZE.put((byte) 0x01, 1); // empty array + OFFSET_SIZE.put((byte) 0x02, 1); // array without index table + OFFSET_SIZE.put((byte) 0x03, 2); // array without index table + OFFSET_SIZE.put((byte) 0x04, 4); // array without index table + OFFSET_SIZE.put((byte) 0x05, 8); // array without index table + OFFSET_SIZE.put((byte) 0x06, 1); // array with index table + OFFSET_SIZE.put((byte) 0x07, 2); // array with index table + OFFSET_SIZE.put((byte) 0x08, 4); // array with index table + OFFSET_SIZE.put((byte) 0x09, 8); // array with index table + OFFSET_SIZE.put((byte) 0x0a, 1); // empty object + OFFSET_SIZE.put((byte) 0x0b, 1); // object with sorted index table + OFFSET_SIZE.put((byte) 0x0c, 2); // object with sorted index table + OFFSET_SIZE.put((byte) 0x0d, 4); // object with sorted index table + OFFSET_SIZE.put((byte) 0x0e, 8); // object with sorted index table + OFFSET_SIZE.put((byte) 0x0f, 1); // object with unsorted index table + OFFSET_SIZE.put((byte) 0x10, 2); // object with unsorted index table + OFFSET_SIZE.put((byte) 0x11, 4); // object with unsorted index table + OFFSET_SIZE.put((byte) 0x12, 8); // object with unsorted index table + } + + private ObjectArrayUtil() { + super(); + } + + public static int getOffsetSize(final byte key) { + return OFFSET_SIZE.get(key); + } +} diff --git a/src/main/java/com/arangodb/velocypack/internal/util/StringUtil.java b/src/main/java/com/arangodb/velocypack/internal/util/StringUtil.java new file mode 100644 index 000000000..308bcfcb4 --- /dev/null +++ b/src/main/java/com/arangodb/velocypack/internal/util/StringUtil.java @@ -0,0 +1,37 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.velocypack.internal.util; + +/** + * @author Mark - mark at arangodb.com + * + */ +public class StringUtil { + + private StringUtil() { + super(); + } + + public static String toString(final byte[] array, final int offset, final int length) { + return new String(array, offset, length); + } + +} diff --git a/src/main/java/com/arangodb/velocypack/internal/util/ValueLengthUtil.java b/src/main/java/com/arangodb/velocypack/internal/util/ValueLengthUtil.java new file mode 100644 index 000000000..2f3d9cbf8 --- /dev/null +++ b/src/main/java/com/arangodb/velocypack/internal/util/ValueLengthUtil.java @@ -0,0 +1,306 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.velocypack.internal.util; + +import java.util.HashMap; +import java.util.Map; + +/** + * @author Mark - mark at arangodb.com + * + */ +public class ValueLengthUtil { + + private static final int DOUBLE_BYTES = 8; + private static final int LONG_BYTES = 8; + private static final int CHARACTER_BYTES = 2; + + private static final Map MAP; + + static { + MAP = new HashMap(); + MAP.put((byte) 0x00, 1); + MAP.put((byte) 0x01, 1); + MAP.put((byte) 0x02, 0); + MAP.put((byte) 0x03, 0); + MAP.put((byte) 0x04, 0); + MAP.put((byte) 0x05, 0); + MAP.put((byte) 0x06, 0); + MAP.put((byte) 0x07, 0); + MAP.put((byte) 0x08, 0); + MAP.put((byte) 0x09, 0); + MAP.put((byte) 0x0a, 1); + MAP.put((byte) 0x0b, 0); + MAP.put((byte) 0x0c, 0); + MAP.put((byte) 0x0d, 0); + MAP.put((byte) 0x0e, 0); + MAP.put((byte) 0x0f, 0); + MAP.put((byte) 0x10, 0); + MAP.put((byte) 0x11, 0); + MAP.put((byte) 0x12, 0); + MAP.put((byte) 0x13, 0); + MAP.put((byte) 0x14, 0); + MAP.put((byte) 0x15, 0); + MAP.put((byte) 0x16, 0); + MAP.put((byte) 0x17, 1); + MAP.put((byte) 0x18, 1); + MAP.put((byte) 0x19, 1); + MAP.put((byte) 0x1a, 1); + MAP.put((byte) 0x1b, 1 + DOUBLE_BYTES); + MAP.put((byte) 0x1c, 1 + LONG_BYTES); + MAP.put((byte) 0x1d, 1 + CHARACTER_BYTES); + MAP.put((byte) 0x1e, 1); + MAP.put((byte) 0x1f, 1); + MAP.put((byte) 0x20, 2); + MAP.put((byte) 0x21, 3); + MAP.put((byte) 0x22, 4); + MAP.put((byte) 0x23, 5); + MAP.put((byte) 0x24, 6); + MAP.put((byte) 0x25, 7); + MAP.put((byte) 0x26, 8); + MAP.put((byte) 0x27, 9); + MAP.put((byte) 0x28, 2); + MAP.put((byte) 0x29, 3); + MAP.put((byte) 0x2a, 4); + MAP.put((byte) 0x2b, 5); + MAP.put((byte) 0x2c, 6); + MAP.put((byte) 0x2d, 7); + MAP.put((byte) 0x2e, 8); + MAP.put((byte) 0x2f, 9); + MAP.put((byte) 0x30, 1); + MAP.put((byte) 0x31, 1); + MAP.put((byte) 0x32, 1); + MAP.put((byte) 0x33, 1); + MAP.put((byte) 0x34, 1); + MAP.put((byte) 0x35, 1); + MAP.put((byte) 0x36, 1); + MAP.put((byte) 0x37, 1); + MAP.put((byte) 0x38, 1); + MAP.put((byte) 0x39, 1); + MAP.put((byte) 0x3a, 1); + MAP.put((byte) 0x3b, 1); + MAP.put((byte) 0x3c, 1); + MAP.put((byte) 0x3d, 1); + MAP.put((byte) 0x3e, 1); + MAP.put((byte) 0x3f, 1); + MAP.put((byte) 0x40, 1); + MAP.put((byte) 0x41, 2); + MAP.put((byte) 0x42, 3); + MAP.put((byte) 0x43, 4); + MAP.put((byte) 0x44, 5); + MAP.put((byte) 0x45, 6); + MAP.put((byte) 0x46, 7); + MAP.put((byte) 0x47, 8); + MAP.put((byte) 0x48, 9); + MAP.put((byte) 0x49, 10); + MAP.put((byte) 0x4a, 11); + MAP.put((byte) 0x4b, 12); + MAP.put((byte) 0x4c, 13); + MAP.put((byte) 0x4d, 14); + MAP.put((byte) 0x4e, 15); + MAP.put((byte) 0x4f, 16); + MAP.put((byte) 0x50, 17); + MAP.put((byte) 0x51, 18); + MAP.put((byte) 0x52, 19); + MAP.put((byte) 0x53, 20); + MAP.put((byte) 0x54, 21); + MAP.put((byte) 0x55, 22); + MAP.put((byte) 0x56, 23); + MAP.put((byte) 0x57, 24); + MAP.put((byte) 0x58, 25); + MAP.put((byte) 0x59, 26); + MAP.put((byte) 0x5a, 27); + MAP.put((byte) 0x5b, 28); + MAP.put((byte) 0x5c, 29); + MAP.put((byte) 0x5d, 30); + MAP.put((byte) 0x5e, 31); + MAP.put((byte) 0x5f, 32); + MAP.put((byte) 0x60, 33); + MAP.put((byte) 0x61, 34); + MAP.put((byte) 0x62, 35); + MAP.put((byte) 0x63, 36); + MAP.put((byte) 0x64, 37); + MAP.put((byte) 0x65, 38); + MAP.put((byte) 0x66, 39); + MAP.put((byte) 0x67, 40); + MAP.put((byte) 0x68, 41); + MAP.put((byte) 0x69, 42); + MAP.put((byte) 0x6a, 43); + MAP.put((byte) 0x6b, 44); + MAP.put((byte) 0x6c, 45); + MAP.put((byte) 0x6d, 46); + MAP.put((byte) 0x6e, 47); + MAP.put((byte) 0x6f, 48); + MAP.put((byte) 0x70, 49); + MAP.put((byte) 0x71, 50); + MAP.put((byte) 0x72, 51); + MAP.put((byte) 0x73, 52); + MAP.put((byte) 0x74, 53); + MAP.put((byte) 0x75, 54); + MAP.put((byte) 0x76, 55); + MAP.put((byte) 0x77, 56); + MAP.put((byte) 0x78, 57); + MAP.put((byte) 0x79, 58); + MAP.put((byte) 0x7a, 59); + MAP.put((byte) 0x7b, 60); + MAP.put((byte) 0x7c, 61); + MAP.put((byte) 0x7d, 62); + MAP.put((byte) 0x7e, 63); + MAP.put((byte) 0x7f, 64); + MAP.put((byte) 0x80, 65); + MAP.put((byte) 0x81, 66); + MAP.put((byte) 0x82, 67); + MAP.put((byte) 0x83, 68); + MAP.put((byte) 0x84, 69); + MAP.put((byte) 0x85, 70); + MAP.put((byte) 0x86, 71); + MAP.put((byte) 0x87, 72); + MAP.put((byte) 0x88, 73); + MAP.put((byte) 0x89, 74); + MAP.put((byte) 0x8a, 75); + MAP.put((byte) 0x8b, 76); + MAP.put((byte) 0x8c, 77); + MAP.put((byte) 0x8d, 78); + MAP.put((byte) 0x8e, 79); + MAP.put((byte) 0x8f, 80); + MAP.put((byte) 0x90, 81); + MAP.put((byte) 0x91, 82); + MAP.put((byte) 0x92, 83); + MAP.put((byte) 0x93, 84); + MAP.put((byte) 0x94, 85); + MAP.put((byte) 0x95, 86); + MAP.put((byte) 0x96, 87); + MAP.put((byte) 0x97, 88); + MAP.put((byte) 0x98, 89); + MAP.put((byte) 0x99, 90); + MAP.put((byte) 0x9a, 91); + MAP.put((byte) 0x9b, 92); + MAP.put((byte) 0x9c, 93); + MAP.put((byte) 0x9d, 94); + MAP.put((byte) 0x9e, 95); + MAP.put((byte) 0x9f, 96); + MAP.put((byte) 0xa0, 97); + MAP.put((byte) 0xa1, 98); + MAP.put((byte) 0xa2, 99); + MAP.put((byte) 0xa3, 100); + MAP.put((byte) 0xa4, 101); + MAP.put((byte) 0xa5, 102); + MAP.put((byte) 0xa6, 103); + MAP.put((byte) 0xa7, 104); + MAP.put((byte) 0xa8, 105); + MAP.put((byte) 0xa9, 106); + MAP.put((byte) 0xaa, 107); + MAP.put((byte) 0xab, 108); + MAP.put((byte) 0xac, 109); + MAP.put((byte) 0xad, 110); + MAP.put((byte) 0xae, 111); + MAP.put((byte) 0xaf, 112); + MAP.put((byte) 0xb0, 113); + MAP.put((byte) 0xb1, 114); + MAP.put((byte) 0xb2, 115); + MAP.put((byte) 0xb3, 116); + MAP.put((byte) 0xb4, 117); + MAP.put((byte) 0xb5, 118); + MAP.put((byte) 0xb6, 119); + MAP.put((byte) 0xb7, 120); + MAP.put((byte) 0xb8, 121); + MAP.put((byte) 0xb9, 122); + MAP.put((byte) 0xba, 123); + MAP.put((byte) 0xbb, 124); + MAP.put((byte) 0xbc, 125); + MAP.put((byte) 0xbd, 126); + MAP.put((byte) 0xbe, 127); + MAP.put((byte) 0xbf, 0); + MAP.put((byte) 0xc0, 0); + MAP.put((byte) 0xc1, 0); + MAP.put((byte) 0xc2, 0); + MAP.put((byte) 0xc3, 0); + MAP.put((byte) 0xc4, 0); + MAP.put((byte) 0xc5, 0); + MAP.put((byte) 0xc6, 0); + MAP.put((byte) 0xc7, 0); + MAP.put((byte) 0xc8, 0); + MAP.put((byte) 0xc9, 0); + MAP.put((byte) 0xca, 0); + MAP.put((byte) 0xcb, 0); + MAP.put((byte) 0xcc, 0); + MAP.put((byte) 0xcd, 0); + MAP.put((byte) 0xce, 0); + MAP.put((byte) 0xcf, 0); + MAP.put((byte) 0xd0, 0); + MAP.put((byte) 0xd1, 0); + MAP.put((byte) 0xd2, 0); + MAP.put((byte) 0xd3, 0); + MAP.put((byte) 0xd4, 0); + MAP.put((byte) 0xd5, 0); + MAP.put((byte) 0xd6, 0); + MAP.put((byte) 0xd7, 0); + MAP.put((byte) 0xd8, 0); + MAP.put((byte) 0xd9, 0); + MAP.put((byte) 0xda, 0); + MAP.put((byte) 0xdb, 0); + MAP.put((byte) 0xdc, 0); + MAP.put((byte) 0xdd, 0); + MAP.put((byte) 0xde, 0); + MAP.put((byte) 0xdf, 0); + MAP.put((byte) 0xe0, 0); + MAP.put((byte) 0xe1, 0); + MAP.put((byte) 0xe2, 0); + MAP.put((byte) 0xe3, 0); + MAP.put((byte) 0xe4, 0); + MAP.put((byte) 0xe5, 0); + MAP.put((byte) 0xe6, 0); + MAP.put((byte) 0xe7, 0); + MAP.put((byte) 0xe8, 0); + MAP.put((byte) 0xe9, 0); + MAP.put((byte) 0xea, 0); + MAP.put((byte) 0xeb, 0); + MAP.put((byte) 0xec, 0); + MAP.put((byte) 0xed, 0); + MAP.put((byte) 0xee, 0); + MAP.put((byte) 0xef, 0); + MAP.put((byte) 0xf0, 2); + MAP.put((byte) 0xf1, 3); + MAP.put((byte) 0xf2, 5); + MAP.put((byte) 0xf3, 9); + MAP.put((byte) 0xf4, 0); + MAP.put((byte) 0xf5, 0); + MAP.put((byte) 0xf6, 0); + MAP.put((byte) 0xf7, 0); + MAP.put((byte) 0xf8, 0); + MAP.put((byte) 0xf9, 0); + MAP.put((byte) 0xfa, 0); + MAP.put((byte) 0xfb, 0); + MAP.put((byte) 0xfc, 0); + MAP.put((byte) 0xfd, 0); + MAP.put((byte) 0xfe, 0); + MAP.put((byte) 0xff, 0); + } + + private ValueLengthUtil() { + super(); + } + + public static int get(final byte key) { + return MAP.get(key); + } + +} diff --git a/src/main/java/com/arangodb/velocypack/internal/util/ValueTypeUtil.java b/src/main/java/com/arangodb/velocypack/internal/util/ValueTypeUtil.java new file mode 100644 index 000000000..0a83d9ac7 --- /dev/null +++ b/src/main/java/com/arangodb/velocypack/internal/util/ValueTypeUtil.java @@ -0,0 +1,305 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.velocypack.internal.util; + +import java.util.HashMap; +import java.util.Map; + +import com.arangodb.velocypack.ValueType; + +/** + * @author Mark - mark at arangodb.com + * + */ +public class ValueTypeUtil { + + private static final Map MAP; + + static { + MAP = new HashMap(); + + MAP.put((byte) 0x00, ValueType.NONE); + MAP.put((byte) 0x01, ValueType.ARRAY); + MAP.put((byte) 0x02, ValueType.ARRAY); + MAP.put((byte) 0x03, ValueType.ARRAY); + MAP.put((byte) 0x04, ValueType.ARRAY); + MAP.put((byte) 0x05, ValueType.ARRAY); + MAP.put((byte) 0x06, ValueType.ARRAY); + MAP.put((byte) 0x07, ValueType.ARRAY); + MAP.put((byte) 0x08, ValueType.ARRAY); + MAP.put((byte) 0x09, ValueType.ARRAY); + MAP.put((byte) 0x0a, ValueType.OBJECT); + MAP.put((byte) 0x0b, ValueType.OBJECT); + MAP.put((byte) 0x0c, ValueType.OBJECT); + MAP.put((byte) 0x0d, ValueType.OBJECT); + MAP.put((byte) 0x0e, ValueType.OBJECT); + MAP.put((byte) 0x0f, ValueType.OBJECT); + MAP.put((byte) 0x10, ValueType.OBJECT); + MAP.put((byte) 0x11, ValueType.OBJECT); + MAP.put((byte) 0x12, ValueType.OBJECT); + MAP.put((byte) 0x13, ValueType.ARRAY); + MAP.put((byte) 0x14, ValueType.OBJECT); + MAP.put((byte) 0x15, ValueType.NONE); + MAP.put((byte) 0x16, ValueType.NONE); + MAP.put((byte) 0x17, ValueType.ILLEGAL); + MAP.put((byte) 0x18, ValueType.NULL); + MAP.put((byte) 0x19, ValueType.BOOL); + MAP.put((byte) 0x1a, ValueType.BOOL); + MAP.put((byte) 0x1b, ValueType.DOUBLE); + MAP.put((byte) 0x1c, ValueType.UTC_DATE); + MAP.put((byte) 0x1d, ValueType.EXTERNAL); + MAP.put((byte) 0x1e, ValueType.MIN_KEY); + MAP.put((byte) 0x1f, ValueType.MAX_KEY); + MAP.put((byte) 0x20, ValueType.INT); + MAP.put((byte) 0x21, ValueType.INT); + MAP.put((byte) 0x22, ValueType.INT); + MAP.put((byte) 0x23, ValueType.INT); + MAP.put((byte) 0x24, ValueType.INT); + MAP.put((byte) 0x25, ValueType.INT); + MAP.put((byte) 0x26, ValueType.INT); + MAP.put((byte) 0x27, ValueType.INT); + MAP.put((byte) 0x28, ValueType.UINT); + MAP.put((byte) 0x29, ValueType.UINT); + MAP.put((byte) 0x2a, ValueType.UINT); + MAP.put((byte) 0x2b, ValueType.UINT); + MAP.put((byte) 0x2c, ValueType.UINT); + MAP.put((byte) 0x2d, ValueType.UINT); + MAP.put((byte) 0x2e, ValueType.UINT); + MAP.put((byte) 0x2f, ValueType.UINT); + MAP.put((byte) 0x30, ValueType.SMALLINT); + MAP.put((byte) 0x31, ValueType.SMALLINT); + MAP.put((byte) 0x32, ValueType.SMALLINT); + MAP.put((byte) 0x33, ValueType.SMALLINT); + MAP.put((byte) 0x34, ValueType.SMALLINT); + MAP.put((byte) 0x35, ValueType.SMALLINT); + MAP.put((byte) 0x36, ValueType.SMALLINT); + MAP.put((byte) 0x37, ValueType.SMALLINT); + MAP.put((byte) 0x38, ValueType.SMALLINT); + MAP.put((byte) 0x39, ValueType.SMALLINT); + MAP.put((byte) 0x3a, ValueType.SMALLINT); + MAP.put((byte) 0x3b, ValueType.SMALLINT); + MAP.put((byte) 0x3c, ValueType.SMALLINT); + MAP.put((byte) 0x3d, ValueType.SMALLINT); + MAP.put((byte) 0x3e, ValueType.SMALLINT); + MAP.put((byte) 0x3f, ValueType.SMALLINT); + MAP.put((byte) 0x40, ValueType.STRING); + MAP.put((byte) 0x41, ValueType.STRING); + MAP.put((byte) 0x42, ValueType.STRING); + MAP.put((byte) 0x43, ValueType.STRING); + MAP.put((byte) 0x44, ValueType.STRING); + MAP.put((byte) 0x45, ValueType.STRING); + MAP.put((byte) 0x46, ValueType.STRING); + MAP.put((byte) 0x47, ValueType.STRING); + MAP.put((byte) 0x48, ValueType.STRING); + MAP.put((byte) 0x49, ValueType.STRING); + MAP.put((byte) 0x4a, ValueType.STRING); + MAP.put((byte) 0x4b, ValueType.STRING); + MAP.put((byte) 0x4c, ValueType.STRING); + MAP.put((byte) 0x4d, ValueType.STRING); + MAP.put((byte) 0x4e, ValueType.STRING); + MAP.put((byte) 0x4f, ValueType.STRING); + MAP.put((byte) 0x50, ValueType.STRING); + MAP.put((byte) 0x51, ValueType.STRING); + MAP.put((byte) 0x52, ValueType.STRING); + MAP.put((byte) 0x53, ValueType.STRING); + MAP.put((byte) 0x54, ValueType.STRING); + MAP.put((byte) 0x55, ValueType.STRING); + MAP.put((byte) 0x56, ValueType.STRING); + MAP.put((byte) 0x57, ValueType.STRING); + MAP.put((byte) 0x58, ValueType.STRING); + MAP.put((byte) 0x59, ValueType.STRING); + MAP.put((byte) 0x5a, ValueType.STRING); + MAP.put((byte) 0x5b, ValueType.STRING); + MAP.put((byte) 0x5c, ValueType.STRING); + MAP.put((byte) 0x5d, ValueType.STRING); + MAP.put((byte) 0x5e, ValueType.STRING); + MAP.put((byte) 0x5f, ValueType.STRING); + MAP.put((byte) 0x60, ValueType.STRING); + MAP.put((byte) 0x61, ValueType.STRING); + MAP.put((byte) 0x62, ValueType.STRING); + MAP.put((byte) 0x63, ValueType.STRING); + MAP.put((byte) 0x64, ValueType.STRING); + MAP.put((byte) 0x65, ValueType.STRING); + MAP.put((byte) 0x66, ValueType.STRING); + MAP.put((byte) 0x67, ValueType.STRING); + MAP.put((byte) 0x68, ValueType.STRING); + MAP.put((byte) 0x69, ValueType.STRING); + MAP.put((byte) 0x6a, ValueType.STRING); + MAP.put((byte) 0x6b, ValueType.STRING); + MAP.put((byte) 0x6c, ValueType.STRING); + MAP.put((byte) 0x6d, ValueType.STRING); + MAP.put((byte) 0x6e, ValueType.STRING); + MAP.put((byte) 0x6f, ValueType.STRING); + MAP.put((byte) 0x70, ValueType.STRING); + MAP.put((byte) 0x71, ValueType.STRING); + MAP.put((byte) 0x72, ValueType.STRING); + MAP.put((byte) 0x73, ValueType.STRING); + MAP.put((byte) 0x74, ValueType.STRING); + MAP.put((byte) 0x75, ValueType.STRING); + MAP.put((byte) 0x76, ValueType.STRING); + MAP.put((byte) 0x77, ValueType.STRING); + MAP.put((byte) 0x78, ValueType.STRING); + MAP.put((byte) 0x79, ValueType.STRING); + MAP.put((byte) 0x7a, ValueType.STRING); + MAP.put((byte) 0x7b, ValueType.STRING); + MAP.put((byte) 0x7c, ValueType.STRING); + MAP.put((byte) 0x7d, ValueType.STRING); + MAP.put((byte) 0x7e, ValueType.STRING); + MAP.put((byte) 0x7f, ValueType.STRING); + MAP.put((byte) 0x80, ValueType.STRING); + MAP.put((byte) 0x81, ValueType.STRING); + MAP.put((byte) 0x82, ValueType.STRING); + MAP.put((byte) 0x83, ValueType.STRING); + MAP.put((byte) 0x84, ValueType.STRING); + MAP.put((byte) 0x85, ValueType.STRING); + MAP.put((byte) 0x86, ValueType.STRING); + MAP.put((byte) 0x87, ValueType.STRING); + MAP.put((byte) 0x88, ValueType.STRING); + MAP.put((byte) 0x89, ValueType.STRING); + MAP.put((byte) 0x8a, ValueType.STRING); + MAP.put((byte) 0x8b, ValueType.STRING); + MAP.put((byte) 0x8c, ValueType.STRING); + MAP.put((byte) 0x8d, ValueType.STRING); + MAP.put((byte) 0x8e, ValueType.STRING); + MAP.put((byte) 0x8f, ValueType.STRING); + MAP.put((byte) 0x90, ValueType.STRING); + MAP.put((byte) 0x91, ValueType.STRING); + MAP.put((byte) 0x92, ValueType.STRING); + MAP.put((byte) 0x93, ValueType.STRING); + MAP.put((byte) 0x94, ValueType.STRING); + MAP.put((byte) 0x95, ValueType.STRING); + MAP.put((byte) 0x96, ValueType.STRING); + MAP.put((byte) 0x97, ValueType.STRING); + MAP.put((byte) 0x98, ValueType.STRING); + MAP.put((byte) 0x99, ValueType.STRING); + MAP.put((byte) 0x9a, ValueType.STRING); + MAP.put((byte) 0x9b, ValueType.STRING); + MAP.put((byte) 0x9c, ValueType.STRING); + MAP.put((byte) 0x9d, ValueType.STRING); + MAP.put((byte) 0x9e, ValueType.STRING); + MAP.put((byte) 0x9f, ValueType.STRING); + MAP.put((byte) 0xa0, ValueType.STRING); + MAP.put((byte) 0xa1, ValueType.STRING); + MAP.put((byte) 0xa2, ValueType.STRING); + MAP.put((byte) 0xa3, ValueType.STRING); + MAP.put((byte) 0xa4, ValueType.STRING); + MAP.put((byte) 0xa5, ValueType.STRING); + MAP.put((byte) 0xa6, ValueType.STRING); + MAP.put((byte) 0xa7, ValueType.STRING); + MAP.put((byte) 0xa8, ValueType.STRING); + MAP.put((byte) 0xa9, ValueType.STRING); + MAP.put((byte) 0xaa, ValueType.STRING); + MAP.put((byte) 0xab, ValueType.STRING); + MAP.put((byte) 0xac, ValueType.STRING); + MAP.put((byte) 0xad, ValueType.STRING); + MAP.put((byte) 0xae, ValueType.STRING); + MAP.put((byte) 0xaf, ValueType.STRING); + MAP.put((byte) 0xb0, ValueType.STRING); + MAP.put((byte) 0xb1, ValueType.STRING); + MAP.put((byte) 0xb2, ValueType.STRING); + MAP.put((byte) 0xb3, ValueType.STRING); + MAP.put((byte) 0xb4, ValueType.STRING); + MAP.put((byte) 0xb5, ValueType.STRING); + MAP.put((byte) 0xb6, ValueType.STRING); + MAP.put((byte) 0xb7, ValueType.STRING); + MAP.put((byte) 0xb8, ValueType.STRING); + MAP.put((byte) 0xb9, ValueType.STRING); + MAP.put((byte) 0xba, ValueType.STRING); + MAP.put((byte) 0xbb, ValueType.STRING); + MAP.put((byte) 0xbc, ValueType.STRING); + MAP.put((byte) 0xbd, ValueType.STRING); + MAP.put((byte) 0xbe, ValueType.STRING); + MAP.put((byte) 0xbf, ValueType.STRING); + MAP.put((byte) 0xc0, ValueType.BINARY); + MAP.put((byte) 0xc1, ValueType.BINARY); + MAP.put((byte) 0xc2, ValueType.BINARY); + MAP.put((byte) 0xc3, ValueType.BINARY); + MAP.put((byte) 0xc4, ValueType.BINARY); + MAP.put((byte) 0xc5, ValueType.BINARY); + MAP.put((byte) 0xc6, ValueType.BINARY); + MAP.put((byte) 0xc7, ValueType.BINARY); + MAP.put((byte) 0xc8, ValueType.BCD); + MAP.put((byte) 0xc9, ValueType.BCD); + MAP.put((byte) 0xca, ValueType.BCD); + MAP.put((byte) 0xcb, ValueType.BCD); + MAP.put((byte) 0xcc, ValueType.BCD); + MAP.put((byte) 0xcd, ValueType.BCD); + MAP.put((byte) 0xce, ValueType.BCD); + MAP.put((byte) 0xcf, ValueType.BCD); + MAP.put((byte) 0xd0, ValueType.BCD); + MAP.put((byte) 0xd1, ValueType.BCD); + MAP.put((byte) 0xd2, ValueType.BCD); + MAP.put((byte) 0xd3, ValueType.BCD); + MAP.put((byte) 0xd4, ValueType.BCD); + MAP.put((byte) 0xd5, ValueType.BCD); + MAP.put((byte) 0xd6, ValueType.BCD); + MAP.put((byte) 0xd7, ValueType.BCD); + MAP.put((byte) 0xd8, ValueType.NONE); + MAP.put((byte) 0xd9, ValueType.NONE); + MAP.put((byte) 0xda, ValueType.NONE); + MAP.put((byte) 0xdb, ValueType.NONE); + MAP.put((byte) 0xdc, ValueType.NONE); + MAP.put((byte) 0xdd, ValueType.NONE); + MAP.put((byte) 0xde, ValueType.NONE); + MAP.put((byte) 0xdf, ValueType.NONE); + MAP.put((byte) 0xe0, ValueType.NONE); + MAP.put((byte) 0xe1, ValueType.NONE); + MAP.put((byte) 0xe2, ValueType.NONE); + MAP.put((byte) 0xe3, ValueType.NONE); + MAP.put((byte) 0xe4, ValueType.NONE); + MAP.put((byte) 0xe5, ValueType.NONE); + MAP.put((byte) 0xe6, ValueType.NONE); + MAP.put((byte) 0xe7, ValueType.NONE); + MAP.put((byte) 0xe8, ValueType.NONE); + MAP.put((byte) 0xe9, ValueType.NONE); + MAP.put((byte) 0xea, ValueType.NONE); + MAP.put((byte) 0xeb, ValueType.NONE); + MAP.put((byte) 0xec, ValueType.NONE); + MAP.put((byte) 0xed, ValueType.NONE); + MAP.put((byte) 0xee, ValueType.NONE); + MAP.put((byte) 0xef, ValueType.NONE); + MAP.put((byte) 0xf0, ValueType.CUSTOM); + MAP.put((byte) 0xf1, ValueType.CUSTOM); + MAP.put((byte) 0xf2, ValueType.CUSTOM); + MAP.put((byte) 0xf3, ValueType.CUSTOM); + MAP.put((byte) 0xf4, ValueType.CUSTOM); + MAP.put((byte) 0xf5, ValueType.CUSTOM); + MAP.put((byte) 0xf6, ValueType.CUSTOM); + MAP.put((byte) 0xf7, ValueType.CUSTOM); + MAP.put((byte) 0xf8, ValueType.CUSTOM); + MAP.put((byte) 0xf9, ValueType.CUSTOM); + MAP.put((byte) 0xfa, ValueType.CUSTOM); + MAP.put((byte) 0xfb, ValueType.CUSTOM); + MAP.put((byte) 0xfc, ValueType.CUSTOM); + MAP.put((byte) 0xfd, ValueType.CUSTOM); + MAP.put((byte) 0xfe, ValueType.CUSTOM); + MAP.put((byte) 0xff, ValueType.CUSTOM); + } + + private ValueTypeUtil() { + super(); + } + + public static ValueType get(final byte key) { + return MAP.get(key); + } + +} diff --git a/src/main/java/com/arangodb/velocystream/Request.java b/src/main/java/com/arangodb/velocystream/Request.java new file mode 100644 index 000000000..d3c8385e2 --- /dev/null +++ b/src/main/java/com/arangodb/velocystream/Request.java @@ -0,0 +1,122 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.velocystream; + +import java.util.HashMap; +import java.util.Map; + +import com.arangodb.velocypack.VPackSlice; +import com.arangodb.velocypack.annotations.Expose; + +/** + * @author Mark - mark at arangodb.com + * + */ +public class Request { + + private int version = 1; + private int type = 1; + private final String database; + private final RequestType requestType; + private final String request; + private Map queryParam; + private 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() { + if (queryParam == null) { + queryParam = new HashMap(); + } + return queryParam; + } + + public Request putQueryParam(final String key, final Object value) { + if (value != null) { + getQueryParam().put(key, value.toString()); + } + return this; + } + + public Map getHeaderParam() { + if (headerParam == null) { + headerParam = new HashMap(); + } + return headerParam; + } + + public Request putHeaderParam(final String key, final String value) { + if (value != null) { + getHeaderParam().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 new file mode 100644 index 000000000..849a561d4 --- /dev/null +++ b/src/main/java/com/arangodb/velocystream/RequestType.java @@ -0,0 +1,59 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.velocystream; + +/** + * @author Mark - mark at arangodb.com + * + */ +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); + + private final int type; + + private RequestType(final int type) { + this.type = 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; + } +} diff --git a/src/main/java/com/arangodb/velocystream/Response.java b/src/main/java/com/arangodb/velocystream/Response.java new file mode 100644 index 000000000..fa5a66373 --- /dev/null +++ b/src/main/java/com/arangodb/velocystream/Response.java @@ -0,0 +1,74 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.velocystream; + +import com.arangodb.velocypack.VPackSlice; +import com.arangodb.velocypack.annotations.Expose; + +/** + * @author Mark - mark at arangodb.com + * + */ +public class Response { + + private int version = 1; + private int type = 2; + private int responseCode; + @Expose(deserialize = false) + private VPackSlice body = null; + + public Response() { + super(); + } + + public int getVersion() { + return version; + } + + public void setVersion(final int version) { + this.version = version; + } + + public int getType() { + return type; + } + + public void setType(final int type) { + this.type = type; + } + + public int getResponseCode() { + return responseCode; + } + + public void setResponseCode(final int responseCode) { + this.responseCode = responseCode; + } + + public VPackSlice getBody() { + return body; + } + + public void setBody(final VPackSlice body) { + this.body = body; + } + +} diff --git a/src/main/main.iml b/src/main/main.iml deleted file mode 100644 index 953970eb6..000000000 --- a/src/main/main.iml +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - - - - - - - - - - - diff --git a/src/test/java/com/arangodb/ArangoBaseParameterTest.java b/src/test/java/com/arangodb/ArangoBaseParameterTest.java deleted file mode 100644 index 793254d6e..000000000 --- a/src/test/java/com/arangodb/ArangoBaseParameterTest.java +++ /dev/null @@ -1,72 +0,0 @@ -package com.arangodb; - -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertThat; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import com.arangodb.entity.DocumentEntity; - -/** - * - * @author gschwab - * - */ -public class ArangoBaseParameterTest extends BaseTest { - - final String collectionName = "unit_test_base_parameter"; - - @Before - public void before() throws ArangoException { - try { - driver.deleteCollection(collectionName); - } catch (final ArangoException e) { - - } - try { - driver.createCollection(collectionName); - } catch (final ArangoException e) { - - } - } - - @After - public void after() throws ArangoException { - } - - @Test - public void test_base_parameters_1() { - final String errorMessage = "some message"; - final TestBaseParameters testBaseParameters = new TestBaseParameters(true, 500, 4711, errorMessage, -1); - - DocumentEntity documentEntity1 = null; - DocumentEntity documentEntity2 = null; - - try { - documentEntity1 = driver.createDocument(collectionName, testBaseParameters); - } catch (final ArangoException e) { - e.printStackTrace(); - } - - try { - documentEntity2 = driver.getDocument(documentEntity1.getDocumentHandle(), TestBaseParameters.class); - } catch (final ArangoException e) { - e.printStackTrace(); - } - - assertThat(documentEntity2.getEntity().isError(), is(true)); - assertThat(documentEntity2.getEntity().getCode(), is(500)); - assertThat(documentEntity2.getEntity().getErrorNum(), is(4711)); - assertThat(documentEntity2.getEntity().getErrorMessage(), is(errorMessage)); - - assertThat(documentEntity2.isError(), is(false)); - assertThat(documentEntity2.getCode(), is(200)); - assertThat(documentEntity2.getErrorNumber(), is(0)); - assertThat(documentEntity2.getErrorMessage(), is(nullValue())); - - } - -} diff --git a/src/test/java/com/arangodb/ArangoCollectionTest.java b/src/test/java/com/arangodb/ArangoCollectionTest.java new file mode 100644 index 000000000..0e068617f --- /dev/null +++ b/src/test/java/com/arangodb/ArangoCollectionTest.java @@ -0,0 +1,1176 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb; + +import static org.hamcrest.Matchers.anyOf; +import static org.hamcrest.Matchers.hasItem; +import static org.hamcrest.Matchers.instanceOf; +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.hamcrest.Matchers.startsWith; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.fail; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import com.arangodb.entity.BaseDocument; +import com.arangodb.entity.CollectionEntity; +import com.arangodb.entity.CollectionPropertiesEntity; +import com.arangodb.entity.CollectionRevisionEntity; +import com.arangodb.entity.DocumentCreateEntity; +import com.arangodb.entity.DocumentDeleteEntity; +import com.arangodb.entity.DocumentUpdateEntity; +import com.arangodb.entity.IndexEntity; +import com.arangodb.entity.IndexType; +import com.arangodb.entity.MultiDocumentEntity; +import com.arangodb.model.CollectionPropertiesOptions; +import com.arangodb.model.DocumentCreateOptions; +import com.arangodb.model.DocumentDeleteOptions; +import com.arangodb.model.DocumentExistsOptions; +import com.arangodb.model.DocumentReadOptions; +import com.arangodb.model.DocumentReplaceOptions; +import com.arangodb.model.DocumentUpdateOptions; + +/** + * @author Mark - mark at arangodb.com + * + */ +public class ArangoCollectionTest extends BaseTest { + + private static final String COLLECTION_NAME = "db_collection_test"; + + @Before + public void setup() { + db.createCollection(COLLECTION_NAME, null); + } + + @After + public void teardown() { + db.collection(COLLECTION_NAME).drop(); + } + + @Test + public void insertDocument() { + final DocumentCreateEntity doc = db.collection(COLLECTION_NAME).insertDocument(new BaseDocument(), + null); + assertThat(doc, is(notNullValue())); + assertThat(doc.getId(), is(notNullValue())); + assertThat(doc.getKey(), is(notNullValue())); + assertThat(doc.getRev(), is(notNullValue())); + assertThat(doc.getNew(), is(nullValue())); + assertThat(doc.getId(), is(COLLECTION_NAME + "/" + doc.getKey())); + } + + @Test + public void insertDocumentReturnNew() { + final DocumentCreateOptions options = new DocumentCreateOptions().returnNew(true); + final DocumentCreateEntity doc = db.collection(COLLECTION_NAME).insertDocument(new BaseDocument(), + options); + assertThat(doc, is(notNullValue())); + assertThat(doc.getId(), is(notNullValue())); + assertThat(doc.getKey(), is(notNullValue())); + assertThat(doc.getRev(), is(notNullValue())); + assertThat(doc.getNew(), is(notNullValue())); + } + + @Test + public void insertDocumentWaitForSync() { + final DocumentCreateOptions options = new DocumentCreateOptions().waitForSync(true); + final DocumentCreateEntity doc = db.collection(COLLECTION_NAME).insertDocument(new BaseDocument(), + options); + assertThat(doc, is(notNullValue())); + assertThat(doc.getId(), is(notNullValue())); + assertThat(doc.getKey(), is(notNullValue())); + assertThat(doc.getRev(), is(notNullValue())); + assertThat(doc.getNew(), is(nullValue())); + } + + @Test + public void insertDocumentAsJson() { + final DocumentCreateEntity doc = db.collection(COLLECTION_NAME) + .insertDocument("{\"_key\":\"docRaw\",\"a\":\"test\"}", null); + assertThat(doc, is(notNullValue())); + assertThat(doc.getId(), is(notNullValue())); + assertThat(doc.getKey(), is(notNullValue())); + assertThat(doc.getRev(), is(notNullValue())); + } + + @Test + public void getDocument() { + final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) + .insertDocument(new BaseDocument(), null); + assertThat(createResult.getKey(), is(notNullValue())); + final BaseDocument readResult = db.collection(COLLECTION_NAME).getDocument(createResult.getKey(), + BaseDocument.class, null); + assertThat(readResult.getKey(), is(createResult.getKey())); + assertThat(readResult.getId(), is(COLLECTION_NAME + "/" + createResult.getKey())); + } + + @Test + public void getDocumentIfMatch() { + final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) + .insertDocument(new BaseDocument(), null); + assertThat(createResult.getKey(), is(notNullValue())); + final DocumentReadOptions options = new DocumentReadOptions().ifMatch(createResult.getRev()); + final BaseDocument readResult = db.collection(COLLECTION_NAME).getDocument(createResult.getKey(), + BaseDocument.class, options); + assertThat(readResult.getKey(), is(createResult.getKey())); + assertThat(readResult.getId(), is(COLLECTION_NAME + "/" + createResult.getKey())); + } + + @Test + public void getDocumentIfMatchFail() { + final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) + .insertDocument(new BaseDocument(), null); + assertThat(createResult.getKey(), is(notNullValue())); + final DocumentReadOptions options = new DocumentReadOptions().ifMatch("no"); + final BaseDocument document = db.collection(COLLECTION_NAME).getDocument(createResult.getKey(), + BaseDocument.class, options); + assertThat(document, is(nullValue())); + } + + @Test + public void getDocumentIfNoneMatch() { + final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) + .insertDocument(new BaseDocument(), null); + assertThat(createResult.getKey(), is(notNullValue())); + final DocumentReadOptions options = new DocumentReadOptions().ifNoneMatch("no"); + final BaseDocument readResult = db.collection(COLLECTION_NAME).getDocument(createResult.getKey(), + BaseDocument.class, options); + assertThat(readResult.getKey(), is(createResult.getKey())); + assertThat(readResult.getId(), is(COLLECTION_NAME + "/" + createResult.getKey())); + } + + @Test + public void getDocumentIfNoneMatchFail() { + final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) + .insertDocument(new BaseDocument(), null); + assertThat(createResult.getKey(), is(notNullValue())); + final DocumentReadOptions options = new DocumentReadOptions().ifNoneMatch(createResult.getRev()); + final BaseDocument document = db.collection(COLLECTION_NAME).getDocument(createResult.getKey(), + BaseDocument.class, options); + assertThat(document, is(nullValue())); + } + + @Test + public void getDocumentAsJson() { + db.collection(COLLECTION_NAME).insertDocument("{\"_key\":\"docRaw\",\"a\":\"test\"}", null); + final String readResult = db.collection(COLLECTION_NAME).getDocument("docRaw", String.class, null); + assertThat(readResult.contains("\"_key\":\"docRaw\""), is(true)); + assertThat(readResult.contains("\"_id\":\"db_collection_test\\/docRaw\""), is(true)); + } + + @Test + public void getDocumentNotFound() { + final BaseDocument document = db.collection(COLLECTION_NAME).getDocument("no", BaseDocument.class); + assertThat(document, is(nullValue())); + } + + @Test(expected = ArangoDBException.class) + public void getDocumentWrongKey() { + db.collection(COLLECTION_NAME).getDocument("no/no", BaseDocument.class); + } + + @Test + public void updateDocument() { + final BaseDocument doc = new BaseDocument(); + doc.addAttribute("a", "test"); + doc.addAttribute("c", "test"); + final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME).insertDocument(doc, + null); + doc.updateAttribute("a", "test1"); + doc.addAttribute("b", "test"); + doc.updateAttribute("c", null); + final DocumentUpdateEntity updateResult = db.collection(COLLECTION_NAME) + .updateDocument(createResult.getKey(), doc, null); + assertThat(updateResult, is(notNullValue())); + assertThat(updateResult.getId(), is(createResult.getId())); + assertThat(updateResult.getNew(), is(nullValue())); + assertThat(updateResult.getOld(), is(nullValue())); + assertThat(updateResult.getRev(), is(not(updateResult.getOldRev()))); + assertThat(updateResult.getOldRev(), is(createResult.getRev())); + + final BaseDocument readResult = db.collection(COLLECTION_NAME).getDocument(createResult.getKey(), + BaseDocument.class, null); + assertThat(readResult.getKey(), is(createResult.getKey())); + assertThat(readResult.getAttribute("a"), is(notNullValue())); + assertThat(String.valueOf(readResult.getAttribute("a")), is("test1")); + assertThat(readResult.getAttribute("b"), is(notNullValue())); + assertThat(String.valueOf(readResult.getAttribute("b")), is("test")); + assertThat(readResult.getRevision(), is(updateResult.getRev())); + assertThat(readResult.getProperties().keySet(), hasItem("c")); + } + + @Test + public void updateDocumentIfMatch() { + final BaseDocument doc = new BaseDocument(); + doc.addAttribute("a", "test"); + doc.addAttribute("c", "test"); + final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME).insertDocument(doc, + null); + doc.updateAttribute("a", "test1"); + doc.addAttribute("b", "test"); + doc.updateAttribute("c", null); + final DocumentUpdateOptions options = new DocumentUpdateOptions().ifMatch(createResult.getRev()); + final DocumentUpdateEntity updateResult = db.collection(COLLECTION_NAME) + .updateDocument(createResult.getKey(), doc, options); + assertThat(updateResult, is(notNullValue())); + assertThat(updateResult.getId(), is(createResult.getId())); + assertThat(updateResult.getRev(), is(not(updateResult.getOldRev()))); + assertThat(updateResult.getOldRev(), is(createResult.getRev())); + + final BaseDocument readResult = db.collection(COLLECTION_NAME).getDocument(createResult.getKey(), + BaseDocument.class, null); + assertThat(readResult.getKey(), is(createResult.getKey())); + assertThat(readResult.getAttribute("a"), is(notNullValue())); + assertThat(String.valueOf(readResult.getAttribute("a")), is("test1")); + assertThat(readResult.getAttribute("b"), is(notNullValue())); + assertThat(String.valueOf(readResult.getAttribute("b")), is("test")); + assertThat(readResult.getRevision(), is(updateResult.getRev())); + assertThat(readResult.getProperties().keySet(), hasItem("c")); + } + + @Test + public void updateDocumentIfMatchFail() { + final BaseDocument doc = new BaseDocument(); + doc.addAttribute("a", "test"); + doc.addAttribute("c", "test"); + final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME).insertDocument(doc, + null); + doc.updateAttribute("a", "test1"); + doc.addAttribute("b", "test"); + doc.updateAttribute("c", null); + try { + final DocumentUpdateOptions options = new DocumentUpdateOptions().ifMatch("no"); + db.collection(COLLECTION_NAME).updateDocument(createResult.getKey(), doc, options); + fail(); + } catch (final ArangoDBException e) { + } + } + + @Test + public void updateDocumentReturnNew() { + final BaseDocument doc = new BaseDocument(); + doc.addAttribute("a", "test"); + final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME).insertDocument(doc, + null); + doc.updateAttribute("a", "test1"); + doc.addAttribute("b", "test"); + final DocumentUpdateOptions options = new DocumentUpdateOptions().returnNew(true); + final DocumentUpdateEntity updateResult = db.collection(COLLECTION_NAME) + .updateDocument(createResult.getKey(), doc, options); + assertThat(updateResult, is(notNullValue())); + assertThat(updateResult.getId(), is(createResult.getId())); + assertThat(updateResult.getOldRev(), is(createResult.getRev())); + assertThat(updateResult.getNew(), is(notNullValue())); + assertThat(updateResult.getNew().getKey(), is(createResult.getKey())); + assertThat(updateResult.getNew().getRevision(), is(not(createResult.getRev()))); + assertThat(updateResult.getNew().getAttribute("a"), is(notNullValue())); + assertThat(String.valueOf(updateResult.getNew().getAttribute("a")), is("test1")); + assertThat(updateResult.getNew().getAttribute("b"), is(notNullValue())); + assertThat(String.valueOf(updateResult.getNew().getAttribute("b")), is("test")); + } + + @Test + public void updateDocumentReturnOld() { + final BaseDocument doc = new BaseDocument(); + doc.addAttribute("a", "test"); + final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME).insertDocument(doc, + null); + doc.updateAttribute("a", "test1"); + doc.addAttribute("b", "test"); + final DocumentUpdateOptions options = new DocumentUpdateOptions().returnOld(true); + final DocumentUpdateEntity updateResult = db.collection(COLLECTION_NAME) + .updateDocument(createResult.getKey(), doc, options); + assertThat(updateResult, is(notNullValue())); + assertThat(updateResult.getId(), is(createResult.getId())); + assertThat(updateResult.getOldRev(), is(createResult.getRev())); + assertThat(updateResult.getOld(), is(notNullValue())); + assertThat(updateResult.getOld().getKey(), is(createResult.getKey())); + assertThat(updateResult.getOld().getRevision(), is(createResult.getRev())); + assertThat(updateResult.getOld().getAttribute("a"), is(notNullValue())); + assertThat(String.valueOf(updateResult.getOld().getAttribute("a")), is("test")); + assertThat(updateResult.getOld().getProperties().keySet(), not(hasItem("b"))); + } + + @Test + public void updateDocumentKeepNullTrue() { + final BaseDocument doc = new BaseDocument(); + doc.addAttribute("a", "test"); + final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME).insertDocument(doc, + null); + doc.updateAttribute("a", null); + final DocumentUpdateOptions options = new DocumentUpdateOptions().keepNull(true); + final DocumentUpdateEntity updateResult = db.collection(COLLECTION_NAME) + .updateDocument(createResult.getKey(), doc, options); + assertThat(updateResult, is(notNullValue())); + assertThat(updateResult.getId(), is(createResult.getId())); + assertThat(updateResult.getRev(), is(not(updateResult.getOldRev()))); + assertThat(updateResult.getOldRev(), is(createResult.getRev())); + + final BaseDocument readResult = db.collection(COLLECTION_NAME).getDocument(createResult.getKey(), + BaseDocument.class, null); + assertThat(readResult.getKey(), is(createResult.getKey())); + assertThat(readResult.getProperties().keySet(), hasItem("a")); + } + + @Test + public void updateDocumentKeepNullFalse() { + final BaseDocument doc = new BaseDocument(); + doc.addAttribute("a", "test"); + final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME).insertDocument(doc, + null); + doc.updateAttribute("a", null); + final DocumentUpdateOptions options = new DocumentUpdateOptions().keepNull(false); + final DocumentUpdateEntity updateResult = db.collection(COLLECTION_NAME) + .updateDocument(createResult.getKey(), doc, options); + assertThat(updateResult, is(notNullValue())); + assertThat(updateResult.getId(), is(createResult.getId())); + assertThat(updateResult.getRev(), is(not(updateResult.getOldRev()))); + assertThat(updateResult.getOldRev(), is(createResult.getRev())); + + final BaseDocument readResult = db.collection(COLLECTION_NAME).getDocument(createResult.getKey(), + BaseDocument.class, null); + assertThat(readResult.getKey(), is(createResult.getKey())); + assertThat(readResult.getId(), is(createResult.getId())); + assertThat(readResult.getRevision(), is(notNullValue())); + assertThat(readResult.getProperties().keySet(), not(hasItem("a"))); + } + + @SuppressWarnings("unchecked") + @Test + public void updateDocumentMergeObjectsTrue() { + final BaseDocument doc = new BaseDocument(); + final Map a = new HashMap(); + a.put("a", "test"); + doc.addAttribute("a", a); + final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME).insertDocument(doc, + null); + a.clear(); + a.put("b", "test"); + doc.updateAttribute("a", a); + final DocumentUpdateOptions options = new DocumentUpdateOptions().mergeObjects(true); + final DocumentUpdateEntity updateResult = db.collection(COLLECTION_NAME) + .updateDocument(createResult.getKey(), doc, options); + assertThat(updateResult, is(notNullValue())); + assertThat(updateResult.getId(), is(createResult.getId())); + assertThat(updateResult.getRev(), is(not(updateResult.getOldRev()))); + assertThat(updateResult.getOldRev(), is(createResult.getRev())); + + final BaseDocument readResult = db.collection(COLLECTION_NAME).getDocument(createResult.getKey(), + BaseDocument.class, null); + assertThat(readResult.getKey(), is(createResult.getKey())); + final Object aResult = readResult.getAttribute("a"); + assertThat(aResult, instanceOf(Map.class)); + final Map aMap = (Map) aResult; + assertThat(aMap.keySet(), hasItem("a")); + assertThat(aMap.keySet(), hasItem("b")); + } + + @SuppressWarnings("unchecked") + @Test + public void updateDocumentMergeObjectsFalse() { + final BaseDocument doc = new BaseDocument(); + final Map a = new HashMap(); + a.put("a", "test"); + doc.addAttribute("a", a); + final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME).insertDocument(doc, + null); + a.clear(); + a.put("b", "test"); + doc.updateAttribute("a", a); + final DocumentUpdateOptions options = new DocumentUpdateOptions().mergeObjects(false); + final DocumentUpdateEntity updateResult = db.collection(COLLECTION_NAME) + .updateDocument(createResult.getKey(), doc, options); + assertThat(updateResult, is(notNullValue())); + assertThat(updateResult.getId(), is(createResult.getId())); + assertThat(updateResult.getRev(), is(not(updateResult.getOldRev()))); + assertThat(updateResult.getOldRev(), is(createResult.getRev())); + + final BaseDocument readResult = db.collection(COLLECTION_NAME).getDocument(createResult.getKey(), + BaseDocument.class, null); + assertThat(readResult.getKey(), is(createResult.getKey())); + final Object aResult = readResult.getAttribute("a"); + assertThat(aResult, instanceOf(Map.class)); + final Map aMap = (Map) aResult; + assertThat(aMap.keySet(), not(hasItem("a"))); + assertThat(aMap.keySet(), hasItem("b")); + } + + @Test + public void updateDocumentIgnoreRevsFalse() { + final BaseDocument doc = new BaseDocument(); + doc.addAttribute("a", "test"); + final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME).insertDocument(doc, + null); + doc.updateAttribute("a", "test1"); + doc.setRevision("no"); + try { + final DocumentUpdateOptions options = new DocumentUpdateOptions().ignoreRevs(false); + db.collection(COLLECTION_NAME).updateDocument(createResult.getKey(), doc, options); + fail(); + } catch (final ArangoDBException e) { + } + } + + @Test + public void replaceDocument() { + final BaseDocument doc = new BaseDocument(); + doc.addAttribute("a", "test"); + final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME).insertDocument(doc, + null); + doc.getProperties().clear(); + doc.addAttribute("b", "test"); + final DocumentUpdateEntity replaceResult = db.collection(COLLECTION_NAME) + .replaceDocument(createResult.getKey(), doc, null); + assertThat(replaceResult, is(notNullValue())); + assertThat(replaceResult.getId(), is(createResult.getId())); + assertThat(replaceResult.getNew(), is(nullValue())); + assertThat(replaceResult.getOld(), is(nullValue())); + assertThat(replaceResult.getRev(), is(not(replaceResult.getOldRev()))); + assertThat(replaceResult.getOldRev(), is(createResult.getRev())); + + final BaseDocument readResult = db.collection(COLLECTION_NAME).getDocument(createResult.getKey(), + BaseDocument.class, null); + assertThat(readResult.getKey(), is(createResult.getKey())); + assertThat(readResult.getRevision(), is(replaceResult.getRev())); + assertThat(readResult.getProperties().keySet(), not(hasItem("a"))); + assertThat(readResult.getAttribute("b"), is(notNullValue())); + assertThat(String.valueOf(readResult.getAttribute("b")), is("test")); + } + + @Test + public void replaceDocumentIfMatch() { + final BaseDocument doc = new BaseDocument(); + doc.addAttribute("a", "test"); + final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME).insertDocument(doc, + null); + doc.getProperties().clear(); + doc.addAttribute("b", "test"); + final DocumentReplaceOptions options = new DocumentReplaceOptions().ifMatch(createResult.getRev()); + final DocumentUpdateEntity replaceResult = db.collection(COLLECTION_NAME) + .replaceDocument(createResult.getKey(), doc, options); + assertThat(replaceResult, is(notNullValue())); + assertThat(replaceResult.getId(), is(createResult.getId())); + assertThat(replaceResult.getRev(), is(not(replaceResult.getOldRev()))); + assertThat(replaceResult.getOldRev(), is(createResult.getRev())); + + final BaseDocument readResult = db.collection(COLLECTION_NAME).getDocument(createResult.getKey(), + BaseDocument.class, null); + assertThat(readResult.getKey(), is(createResult.getKey())); + assertThat(readResult.getRevision(), is(replaceResult.getRev())); + assertThat(readResult.getProperties().keySet(), not(hasItem("a"))); + assertThat(readResult.getAttribute("b"), is(notNullValue())); + assertThat(String.valueOf(readResult.getAttribute("b")), is("test")); + } + + @Test + public void replaceDocumentIfMatchFail() { + final BaseDocument doc = new BaseDocument(); + doc.addAttribute("a", "test"); + final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME).insertDocument(doc, + null); + doc.getProperties().clear(); + doc.addAttribute("b", "test"); + try { + final DocumentReplaceOptions options = new DocumentReplaceOptions().ifMatch("no"); + db.collection(COLLECTION_NAME).replaceDocument(createResult.getKey(), doc, options); + fail(); + } catch (final ArangoDBException e) { + } + } + + @Test + public void replaceDocumentIgnoreRevsFalse() { + final BaseDocument doc = new BaseDocument(); + doc.addAttribute("a", "test"); + final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME).insertDocument(doc, + null); + doc.getProperties().clear(); + doc.addAttribute("b", "test"); + doc.setRevision("no"); + try { + final DocumentReplaceOptions options = new DocumentReplaceOptions().ignoreRevs(false); + db.collection(COLLECTION_NAME).replaceDocument(createResult.getKey(), doc, options); + fail(); + } catch (final ArangoDBException e) { + } + } + + @Test + public void replaceDocumentReturnNew() { + final BaseDocument doc = new BaseDocument(); + doc.addAttribute("a", "test"); + final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME).insertDocument(doc, + null); + doc.getProperties().clear(); + doc.addAttribute("b", "test"); + final DocumentReplaceOptions options = new DocumentReplaceOptions().returnNew(true); + final DocumentUpdateEntity replaceResult = db.collection(COLLECTION_NAME) + .replaceDocument(createResult.getKey(), doc, options); + assertThat(replaceResult, is(notNullValue())); + assertThat(replaceResult.getId(), is(createResult.getId())); + assertThat(replaceResult.getOldRev(), is(createResult.getRev())); + assertThat(replaceResult.getNew(), is(notNullValue())); + assertThat(replaceResult.getNew().getKey(), is(createResult.getKey())); + assertThat(replaceResult.getNew().getRevision(), is(not(createResult.getRev()))); + assertThat(replaceResult.getNew().getProperties().keySet(), not(hasItem("a"))); + assertThat(replaceResult.getNew().getAttribute("b"), is(notNullValue())); + assertThat(String.valueOf(replaceResult.getNew().getAttribute("b")), is("test")); + } + + @Test + public void replaceDocumentReturnOld() { + final BaseDocument doc = new BaseDocument(); + doc.addAttribute("a", "test"); + final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME).insertDocument(doc, + null); + doc.getProperties().clear(); + doc.addAttribute("b", "test"); + final DocumentReplaceOptions options = new DocumentReplaceOptions().returnOld(true); + final DocumentUpdateEntity replaceResult = db.collection(COLLECTION_NAME) + .replaceDocument(createResult.getKey(), doc, options); + assertThat(replaceResult, is(notNullValue())); + assertThat(replaceResult.getId(), is(createResult.getId())); + assertThat(replaceResult.getOldRev(), is(createResult.getRev())); + assertThat(replaceResult.getOld(), is(notNullValue())); + assertThat(replaceResult.getOld().getKey(), is(createResult.getKey())); + assertThat(replaceResult.getOld().getRevision(), is(createResult.getRev())); + assertThat(replaceResult.getOld().getAttribute("a"), is(notNullValue())); + assertThat(String.valueOf(replaceResult.getOld().getAttribute("a")), is("test")); + assertThat(replaceResult.getOld().getProperties().keySet(), not(hasItem("b"))); + } + + @Test + public void deleteDocument() { + final BaseDocument doc = new BaseDocument(); + final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME).insertDocument(doc, + null); + db.collection(COLLECTION_NAME).deleteDocument(createResult.getKey(), null, null); + final BaseDocument document = db.collection(COLLECTION_NAME).getDocument(createResult.getKey(), + BaseDocument.class, null); + assertThat(document, is(nullValue())); + } + + @Test + public void deleteDocumentReturnOld() { + final BaseDocument doc = new BaseDocument(); + doc.addAttribute("a", "test"); + final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME).insertDocument(doc, + null); + final DocumentDeleteOptions options = new DocumentDeleteOptions().returnOld(true); + final DocumentDeleteEntity deleteResult = db.collection(COLLECTION_NAME) + .deleteDocument(createResult.getKey(), BaseDocument.class, options); + assertThat(deleteResult.getOld(), is(notNullValue())); + assertThat(deleteResult.getOld(), instanceOf(BaseDocument.class)); + assertThat(deleteResult.getOld().getAttribute("a"), is(notNullValue())); + assertThat(String.valueOf(deleteResult.getOld().getAttribute("a")), is("test")); + } + + @Test + public void deleteDocumentIfMatch() { + final BaseDocument doc = new BaseDocument(); + final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME).insertDocument(doc, + null); + final DocumentDeleteOptions options = new DocumentDeleteOptions().ifMatch(createResult.getRev()); + db.collection(COLLECTION_NAME).deleteDocument(createResult.getKey(), null, options); + final BaseDocument document = db.collection(COLLECTION_NAME).getDocument(createResult.getKey(), + BaseDocument.class, null); + assertThat(document, is(nullValue())); + } + + @Test + public void deleteDocumentIfMatchFail() { + final BaseDocument doc = new BaseDocument(); + final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME).insertDocument(doc, + null); + final DocumentDeleteOptions options = new DocumentDeleteOptions().ifMatch("no"); + try { + db.collection(COLLECTION_NAME).deleteDocument(createResult.getKey(), null, options); + fail(); + } catch (final ArangoDBException e) { + } + } + + @Test + public void createHashIndex() { + final Collection fields = new ArrayList(); + fields.add("a"); + fields.add("b"); + final IndexEntity indexResult = db.collection(COLLECTION_NAME).createHashIndex(fields, null); + assertThat(indexResult, is(notNullValue())); + assertThat(indexResult.getConstraint(), is(nullValue())); + assertThat(indexResult.getFields(), hasItem("a")); + assertThat(indexResult.getFields(), hasItem("b")); + assertThat(indexResult.getGeoJson(), is(nullValue())); + assertThat(indexResult.getId(), startsWith(COLLECTION_NAME)); + assertThat(indexResult.getIsNewlyCreated(), is(true)); + assertThat(indexResult.getMinLength(), is(nullValue())); + assertThat(indexResult.getSelectivityEstimate(), is(1)); + assertThat(indexResult.getSparse(), is(false)); + assertThat(indexResult.getType(), is(IndexType.hash)); + assertThat(indexResult.getUnique(), is(false)); + } + + @Test + public void createGeoIndex() { + final Collection fields = new ArrayList(); + fields.add("a"); + final IndexEntity indexResult = db.collection(COLLECTION_NAME).createGeoIndex(fields, null); + assertThat(indexResult, is(notNullValue())); + assertThat(indexResult.getConstraint(), is(false)); + assertThat(indexResult.getFields(), hasItem("a")); + assertThat(indexResult.getGeoJson(), is(false)); + assertThat(indexResult.getId(), startsWith(COLLECTION_NAME)); + assertThat(indexResult.getIsNewlyCreated(), is(true)); + assertThat(indexResult.getMinLength(), is(nullValue())); + assertThat(indexResult.getSelectivityEstimate(), is(nullValue())); + assertThat(indexResult.getSparse(), is(true)); + assertThat(indexResult.getType(), is(IndexType.geo1)); + assertThat(indexResult.getUnique(), is(false)); + } + + @Test + public void createGeo2Index() { + final Collection fields = new ArrayList(); + fields.add("a"); + fields.add("b"); + final IndexEntity indexResult = db.collection(COLLECTION_NAME).createGeoIndex(fields, null); + assertThat(indexResult, is(notNullValue())); + assertThat(indexResult.getConstraint(), is(false)); + assertThat(indexResult.getFields(), hasItem("a")); + assertThat(indexResult.getFields(), hasItem("b")); + assertThat(indexResult.getGeoJson(), is(nullValue())); + assertThat(indexResult.getId(), startsWith(COLLECTION_NAME)); + assertThat(indexResult.getIsNewlyCreated(), is(true)); + assertThat(indexResult.getMinLength(), is(nullValue())); + assertThat(indexResult.getSelectivityEstimate(), is(nullValue())); + assertThat(indexResult.getSparse(), is(true)); + assertThat(indexResult.getType(), is(IndexType.geo2)); + assertThat(indexResult.getUnique(), is(false)); + } + + @Test + public void createSkiplistIndex() { + final Collection fields = new ArrayList(); + fields.add("a"); + fields.add("b"); + final IndexEntity indexResult = db.collection(COLLECTION_NAME).createSkiplistIndex(fields, null); + assertThat(indexResult, is(notNullValue())); + assertThat(indexResult.getConstraint(), is(nullValue())); + assertThat(indexResult.getFields(), hasItem("a")); + assertThat(indexResult.getFields(), hasItem("b")); + assertThat(indexResult.getGeoJson(), is(nullValue())); + assertThat(indexResult.getId(), startsWith(COLLECTION_NAME)); + assertThat(indexResult.getIsNewlyCreated(), is(true)); + assertThat(indexResult.getMinLength(), is(nullValue())); + assertThat(indexResult.getSelectivityEstimate(), is(nullValue())); + assertThat(indexResult.getSparse(), is(false)); + assertThat(indexResult.getType(), is(IndexType.skiplist)); + assertThat(indexResult.getUnique(), is(false)); + } + + @Test + public void createPersistentIndex() { + final Collection fields = new ArrayList(); + fields.add("a"); + fields.add("b"); + final IndexEntity indexResult = db.collection(COLLECTION_NAME).createPersistentIndex(fields, null); + assertThat(indexResult, is(notNullValue())); + assertThat(indexResult.getConstraint(), is(nullValue())); + assertThat(indexResult.getFields(), hasItem("a")); + assertThat(indexResult.getFields(), hasItem("b")); + assertThat(indexResult.getGeoJson(), is(nullValue())); + assertThat(indexResult.getId(), startsWith(COLLECTION_NAME)); + assertThat(indexResult.getIsNewlyCreated(), is(true)); + assertThat(indexResult.getMinLength(), is(nullValue())); + assertThat(indexResult.getSelectivityEstimate(), is(nullValue())); + assertThat(indexResult.getSparse(), is(false)); + assertThat(indexResult.getType(), is(IndexType.persistent)); + assertThat(indexResult.getUnique(), is(false)); + } + + @Test + public void createFulltextIndex() { + final Collection fields = new ArrayList(); + fields.add("a"); + final IndexEntity indexResult = db.collection(COLLECTION_NAME).createFulltextIndex(fields, null); + assertThat(indexResult, is(notNullValue())); + assertThat(indexResult.getConstraint(), is(nullValue())); + assertThat(indexResult.getFields(), hasItem("a")); + assertThat(indexResult.getGeoJson(), is(nullValue())); + assertThat(indexResult.getId(), startsWith(COLLECTION_NAME)); + assertThat(indexResult.getIsNewlyCreated(), is(true)); + assertThat(indexResult.getSelectivityEstimate(), is(nullValue())); + assertThat(indexResult.getSparse(), is(true)); + assertThat(indexResult.getType(), is(IndexType.fulltext)); + assertThat(indexResult.getUnique(), is(false)); + } + + @Test + public void getIndexes() { + final Collection fields = new ArrayList(); + fields.add("a"); + db.collection(COLLECTION_NAME).createHashIndex(fields, null); + final Collection indexes = db.collection(COLLECTION_NAME).getIndexes(); + assertThat(indexes, is(notNullValue())); + assertThat(indexes.size(), is(2)); + for (final IndexEntity i : indexes) { + assertThat(i.getType(), anyOf(is(IndexType.primary), is(IndexType.hash))); + if (i.getType() == IndexType.hash) { + assertThat(i.getFields().size(), is(1)); + assertThat(i.getFields(), hasItem("a")); + } + } + } + + @Test + public void truncate() { + final BaseDocument doc = new BaseDocument(); + db.collection(COLLECTION_NAME).insertDocument(doc, null); + final BaseDocument readResult = db.collection(COLLECTION_NAME).getDocument(doc.getKey(), BaseDocument.class, + null); + assertThat(readResult.getKey(), is(doc.getKey())); + final CollectionEntity truncateResult = db.collection(COLLECTION_NAME).truncate(); + assertThat(truncateResult, is(notNullValue())); + assertThat(truncateResult.getId(), is(notNullValue())); + final BaseDocument document = db.collection(COLLECTION_NAME).getDocument(doc.getKey(), BaseDocument.class, + null); + assertThat(document, is(nullValue())); + } + + @Test + public void getCount() { + final CollectionPropertiesEntity countEmpty = db.collection(COLLECTION_NAME).count(); + assertThat(countEmpty, is(notNullValue())); + assertThat(countEmpty.getCount(), is(0L)); + db.collection(COLLECTION_NAME).insertDocument("{}", null); + final CollectionPropertiesEntity count = db.collection(COLLECTION_NAME).count(); + assertThat(count.getCount(), is(1L)); + } + + @Test + public void documentExists() { + final Boolean existsNot = db.collection(COLLECTION_NAME).documentExists("no", null); + assertThat(existsNot, is(false)); + db.collection(COLLECTION_NAME).insertDocument("{\"_key\":\"abc\"}", null); + final Boolean exists = db.collection(COLLECTION_NAME).documentExists("abc", null); + assertThat(exists, is(true)); + } + + @Test + public void documentExistsIfMatch() { + final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) + .insertDocument("{\"_key\":\"abc\"}", null); + final DocumentExistsOptions options = new DocumentExistsOptions().ifMatch(createResult.getRev()); + final Boolean exists = db.collection(COLLECTION_NAME).documentExists("abc", options); + assertThat(exists, is(true)); + } + + @Test + public void documentExistsIfMatchFail() { + db.collection(COLLECTION_NAME).insertDocument("{\"_key\":\"abc\"}", null); + final DocumentExistsOptions options = new DocumentExistsOptions().ifMatch("no"); + final Boolean exists = db.collection(COLLECTION_NAME).documentExists("abc", options); + assertThat(exists, is(false)); + } + + @Test + public void documentExistsIfNoneMatch() { + db.collection(COLLECTION_NAME).insertDocument("{\"_key\":\"abc\"}", null); + final DocumentExistsOptions options = new DocumentExistsOptions().ifNoneMatch("no"); + final Boolean exists = db.collection(COLLECTION_NAME).documentExists("abc", options); + assertThat(exists, is(true)); + } + + @Test + public void documentExistsIfNoneMatchFail() { + final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) + .insertDocument("{\"_key\":\"abc\"}", null); + final DocumentExistsOptions options = new DocumentExistsOptions().ifNoneMatch(createResult.getRev()); + final Boolean exists = db.collection(COLLECTION_NAME).documentExists("abc", options); + assertThat(exists, is(false)); + } + + @Test + public void insertDocuments() { + final Collection values = new ArrayList(); + values.add(new BaseDocument()); + values.add(new BaseDocument()); + values.add(new BaseDocument()); + final MultiDocumentEntity> docs = db.collection(COLLECTION_NAME) + .insertDocuments(values, null); + assertThat(docs, is(notNullValue())); + assertThat(docs.getDocuments(), is(notNullValue())); + assertThat(docs.getDocuments().size(), is(3)); + assertThat(docs.getErrors(), is(notNullValue())); + assertThat(docs.getErrors().size(), is(0)); + } + + @Test + public void insertDocumentsOne() { + final Collection values = new ArrayList(); + values.add(new BaseDocument()); + final MultiDocumentEntity> docs = db.collection(COLLECTION_NAME) + .insertDocuments(values, null); + assertThat(docs, is(notNullValue())); + assertThat(docs.getDocuments(), is(notNullValue())); + assertThat(docs.getDocuments().size(), is(1)); + assertThat(docs.getErrors(), is(notNullValue())); + assertThat(docs.getErrors().size(), is(0)); + } + + @Test + public void insertDocumentsEmpty() { + final Collection values = new ArrayList(); + final MultiDocumentEntity> docs = db.collection(COLLECTION_NAME) + .insertDocuments(values, null); + assertThat(docs, is(notNullValue())); + assertThat(docs.getDocuments(), is(notNullValue())); + assertThat(docs.getDocuments().size(), is(0)); + assertThat(docs.getErrors(), is(notNullValue())); + assertThat(docs.getErrors().size(), is(0)); + } + + @Test + public void insertDocumentsReturnNew() { + final Collection values = new ArrayList(); + values.add(new BaseDocument()); + values.add(new BaseDocument()); + values.add(new BaseDocument()); + final DocumentCreateOptions options = new DocumentCreateOptions().returnNew(true); + final MultiDocumentEntity> docs = db.collection(COLLECTION_NAME) + .insertDocuments(values, options); + assertThat(docs, is(notNullValue())); + assertThat(docs.getDocuments(), is(notNullValue())); + assertThat(docs.getDocuments().size(), is(3)); + assertThat(docs.getErrors(), is(notNullValue())); + assertThat(docs.getErrors().size(), is(0)); + for (final DocumentCreateEntity doc : docs.getDocuments()) { + assertThat(doc.getNew(), is(notNullValue())); + final BaseDocument baseDocument = doc.getNew(); + assertThat(baseDocument.getKey(), is(notNullValue())); + } + + } + + @Test + public void insertDocumentsFail() { + final Collection values = new ArrayList(); + values.add(new BaseDocument("1")); + values.add(new BaseDocument("2")); + values.add(new BaseDocument("2")); + final MultiDocumentEntity> docs = db.collection(COLLECTION_NAME) + .insertDocuments(values); + assertThat(docs, is(notNullValue())); + assertThat(docs.getDocuments(), is(notNullValue())); + assertThat(docs.getDocuments().size(), is(2)); + assertThat(docs.getErrors(), is(notNullValue())); + assertThat(docs.getErrors().size(), is(1)); + assertThat(docs.getErrors().iterator().next().getErrorNum(), is(1210)); + } + + @Test + public void deleteDocuments() { + final Collection values = new ArrayList(); + { + final BaseDocument e = new BaseDocument(); + e.setKey("1"); + values.add(e); + } + { + final BaseDocument e = new BaseDocument(); + e.setKey("2"); + values.add(e); + } + db.collection(COLLECTION_NAME).insertDocuments(values, null); + final Collection keys = new ArrayList(); + keys.add("1"); + keys.add("2"); + final MultiDocumentEntity> deleteResult = db.collection(COLLECTION_NAME) + .deleteDocuments(keys, null, null); + assertThat(deleteResult, is(notNullValue())); + assertThat(deleteResult.getDocuments().size(), is(2)); + for (final DocumentDeleteEntity i : deleteResult.getDocuments()) { + assertThat(i.getKey(), anyOf(is("1"), is("2"))); + } + assertThat(deleteResult.getErrors().size(), is(0)); + } + + @Test + public void deleteDocumentsOne() { + final Collection values = new ArrayList(); + { + final BaseDocument e = new BaseDocument(); + e.setKey("1"); + values.add(e); + } + db.collection(COLLECTION_NAME).insertDocuments(values, null); + final Collection keys = new ArrayList(); + keys.add("1"); + final MultiDocumentEntity> deleteResult = db.collection(COLLECTION_NAME) + .deleteDocuments(keys, null, null); + assertThat(deleteResult, is(notNullValue())); + assertThat(deleteResult.getDocuments().size(), is(1)); + for (final DocumentDeleteEntity i : deleteResult.getDocuments()) { + assertThat(i.getKey(), is("1")); + } + assertThat(deleteResult.getErrors().size(), is(0)); + } + + @Test + public void deleteDocumentsEmpty() { + final Collection values = new ArrayList(); + db.collection(COLLECTION_NAME).insertDocuments(values, null); + final Collection keys = new ArrayList(); + final MultiDocumentEntity> deleteResult = db.collection(COLLECTION_NAME) + .deleteDocuments(keys, null, null); + assertThat(deleteResult, is(notNullValue())); + assertThat(deleteResult.getDocuments().size(), is(0)); + assertThat(deleteResult.getErrors().size(), is(0)); + } + + @Test + public void deleteDocumentsNotExisting() { + final Collection values = new ArrayList(); + db.collection(COLLECTION_NAME).insertDocuments(values, null); + final Collection keys = new ArrayList(); + keys.add("1"); + keys.add("2"); + final MultiDocumentEntity> deleteResult = db.collection(COLLECTION_NAME) + .deleteDocuments(keys, null, null); + assertThat(deleteResult, is(notNullValue())); + assertThat(deleteResult.getDocuments().size(), is(0)); + assertThat(deleteResult.getErrors().size(), is(2)); + } + + @Test + public void updateDocuments() { + final Collection values = new ArrayList(); + { + final BaseDocument e = new BaseDocument(); + e.setKey("1"); + values.add(e); + } + { + final BaseDocument e = new BaseDocument(); + e.setKey("2"); + values.add(e); + } + db.collection(COLLECTION_NAME).insertDocuments(values, null); + final Collection updatedValues = new ArrayList(); + for (final BaseDocument i : values) { + i.addAttribute("a", "test"); + updatedValues.add(i); + } + final MultiDocumentEntity> updateResult = db.collection(COLLECTION_NAME) + .updateDocuments(updatedValues, null); + assertThat(updateResult.getDocuments().size(), is(2)); + assertThat(updateResult.getErrors().size(), is(0)); + } + + @Test + public void updateDocumentsOne() { + final Collection values = new ArrayList(); + { + final BaseDocument e = new BaseDocument(); + e.setKey("1"); + values.add(e); + } + db.collection(COLLECTION_NAME).insertDocuments(values, null); + final Collection updatedValues = new ArrayList(); + final BaseDocument first = values.iterator().next(); + first.addAttribute("a", "test"); + updatedValues.add(first); + final MultiDocumentEntity> updateResult = db.collection(COLLECTION_NAME) + .updateDocuments(updatedValues, null); + assertThat(updateResult.getDocuments().size(), is(1)); + assertThat(updateResult.getErrors().size(), is(0)); + } + + @Test + public void updateDocumentsEmpty() { + final Collection values = new ArrayList(); + final MultiDocumentEntity> updateResult = db.collection(COLLECTION_NAME) + .updateDocuments(values, null); + assertThat(updateResult.getDocuments().size(), is(0)); + assertThat(updateResult.getErrors().size(), is(0)); + } + + @Test + public void updateDocumentsWithoutKey() { + final Collection values = new ArrayList(); + { + values.add(new BaseDocument("1")); + } + db.collection(COLLECTION_NAME).insertDocuments(values, null); + final Collection updatedValues = new ArrayList(); + for (final BaseDocument i : values) { + i.addAttribute("a", "test"); + updatedValues.add(i); + } + updatedValues.add(new BaseDocument()); + final MultiDocumentEntity> updateResult = db.collection(COLLECTION_NAME) + .updateDocuments(updatedValues, null); + assertThat(updateResult.getDocuments().size(), is(1)); + assertThat(updateResult.getErrors().size(), is(1)); + } + + @Test + public void replaceDocuments() { + final Collection values = new ArrayList(); + { + values.add(new BaseDocument("1")); + values.add(new BaseDocument("2")); + } + db.collection(COLLECTION_NAME).insertDocuments(values, null); + final Collection updatedValues = new ArrayList(); + for (final BaseDocument i : values) { + i.addAttribute("a", "test"); + updatedValues.add(i); + } + final MultiDocumentEntity> updateResult = db.collection(COLLECTION_NAME) + .replaceDocuments(updatedValues, null); + assertThat(updateResult.getDocuments().size(), is(2)); + assertThat(updateResult.getErrors().size(), is(0)); + } + + @Test + public void replaceDocumentsOne() { + final Collection values = new ArrayList(); + { + final BaseDocument e = new BaseDocument(); + e.setKey("1"); + values.add(e); + } + db.collection(COLLECTION_NAME).insertDocuments(values, null); + final Collection updatedValues = new ArrayList(); + final BaseDocument first = values.iterator().next(); + first.addAttribute("a", "test"); + updatedValues.add(first); + final MultiDocumentEntity> updateResult = db.collection(COLLECTION_NAME) + .updateDocuments(updatedValues, null); + assertThat(updateResult.getDocuments().size(), is(1)); + assertThat(updateResult.getErrors().size(), is(0)); + } + + @Test + public void replaceDocumentsEmpty() { + final Collection values = new ArrayList(); + final MultiDocumentEntity> updateResult = db.collection(COLLECTION_NAME) + .updateDocuments(values, null); + assertThat(updateResult.getDocuments().size(), is(0)); + assertThat(updateResult.getErrors().size(), is(0)); + } + + @Test + public void replaceDocumentsWithoutKey() { + final Collection values = new ArrayList(); + { + values.add(new BaseDocument("1")); + } + db.collection(COLLECTION_NAME).insertDocuments(values, null); + final Collection updatedValues = new ArrayList(); + for (final BaseDocument i : values) { + i.addAttribute("a", "test"); + updatedValues.add(i); + } + updatedValues.add(new BaseDocument()); + final MultiDocumentEntity> updateResult = db.collection(COLLECTION_NAME) + .updateDocuments(updatedValues, null); + assertThat(updateResult.getDocuments().size(), is(1)); + assertThat(updateResult.getErrors().size(), is(1)); + } + + @Test + public void load() { + final CollectionEntity result = db.collection(COLLECTION_NAME).load(); + assertThat(result.getName(), is(COLLECTION_NAME)); + } + + @Test + public void unload() { + final CollectionEntity result = db.collection(COLLECTION_NAME).unload(); + assertThat(result.getName(), is(COLLECTION_NAME)); + } + + @Test + public void getInfo() { + final CollectionEntity result = db.collection(COLLECTION_NAME).getInfo(); + assertThat(result.getName(), is(COLLECTION_NAME)); + } + + @Test + public void getPropeties() { + final CollectionPropertiesEntity result = db.collection(COLLECTION_NAME).getProperties(); + assertThat(result.getName(), is(COLLECTION_NAME)); + assertThat(result.getCount(), is(nullValue())); + } + + @Test + public void changeProperties() { + final CollectionPropertiesEntity properties = db.collection(COLLECTION_NAME).getProperties(); + assertThat(properties.getWaitForSync(), is(notNullValue())); + final CollectionPropertiesOptions options = new CollectionPropertiesOptions(); + options.waitForSync(!properties.getWaitForSync()); + options.journalSize(2000000L); + final CollectionPropertiesEntity changedProperties = db.collection(COLLECTION_NAME).changeProperties(options); + assertThat(changedProperties.getWaitForSync(), is(notNullValue())); + assertThat(changedProperties.getWaitForSync(), is(not(properties.getWaitForSync()))); + assertThat(changedProperties.getJournalSize(), is(options.getJournalSize())); + } + + @Test + public void rename() { + try { + final CollectionEntity result = db.collection(COLLECTION_NAME).rename(COLLECTION_NAME + "1"); + assertThat(result, is(notNullValue())); + assertThat(result.getName(), is(COLLECTION_NAME + "1")); + final CollectionEntity info = db.collection(COLLECTION_NAME + "1").getInfo(); + assertThat(info.getName(), is(COLLECTION_NAME + "1")); + try { + db.collection(COLLECTION_NAME).getInfo(); + fail(); + } catch (final ArangoDBException e) { + } + } finally { + db.collection(COLLECTION_NAME + "1").rename(COLLECTION_NAME); + } + } + + @Test + public void getRevision() { + final CollectionRevisionEntity result = db.collection(COLLECTION_NAME).getRevision(); + assertThat(result, is(notNullValue())); + assertThat(result.getName(), is(COLLECTION_NAME)); + assertThat(result.getRevision(), is(notNullValue())); + } + +} diff --git a/src/test/java/com/arangodb/ArangoConfigureTest.java b/src/test/java/com/arangodb/ArangoConfigureTest.java deleted file mode 100644 index 94df7f397..000000000 --- a/src/test/java/com/arangodb/ArangoConfigureTest.java +++ /dev/null @@ -1,181 +0,0 @@ -/* - * Copyright (C) 2012,2013 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb; - -import static org.hamcrest.CoreMatchers.instanceOf; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.notNullValue; -import static org.hamcrest.CoreMatchers.nullValue; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; - -import java.io.File; -import java.io.IOException; -import java.net.SocketTimeoutException; -import java.net.URISyntaxException; -import java.net.URL; -import java.security.KeyManagementException; -import java.security.KeyStoreException; -import java.security.NoSuchAlgorithmException; -import java.security.cert.CertificateException; - -import javax.net.ssl.SSLContext; - -import org.apache.http.conn.ConnectTimeoutException; -import org.apache.http.ssl.SSLContexts; -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; - -import com.arangodb.entity.ArangoVersion; - -/** - * UnitTest for ArangoConfigure. - * - * @author tamtam180 - kirscheless at gmail.com - * - */ -public class ArangoConfigureTest { - - 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 - * - * https://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/ - * apache/http/conn/ssl/SSLSocketFactory.html - */ - private static final String SSL_TRUSTSTORE = "/example.truststore"; - - @Test - public void load_from_property_file() { - // validate file in classpath. - assertThat(getClass().getResource("/arangodb.properties"), is(notNullValue())); - - final ArangoConfigure configure = new ArangoConfigure(); - assertThat(configure.getArangoHost().getPort(), is(8529)); - assertThat(configure.getArangoHost().getHost(), is(notNullValue())); - assertThat(configure.getDefaultDatabase(), is(nullValue())); - - } - - @Test - public void load_from_proerty_file2() { - - final ArangoConfigure configure = new ArangoConfigure(); - configure.loadProperties("/arangodb-test.properties"); - - assertThat(configure.getRetryCount(), is(10)); - assertThat(configure.getDefaultDatabase(), is("mydb2")); - - final ArangoHost arangoHost = configure.getArangoHost(); - assertThat(arangoHost.getPort(), is(9999)); - assertThat(arangoHost.getHost(), is(notNullValue())); - - assertThat(configure.hasFallbackHost(), is(true)); - } - - @Test - public void connect_timeout() throws ArangoException { - - final ArangoConfigure configure = new ArangoConfigure(); - configure.getArangoHost().setHost("1.0.0.200"); - configure.setConnectionTimeout(1); // 1ms - configure.init(); - - final ArangoDriver driver = new ArangoDriver(configure); - - try { - driver.getCollections(); - fail("did no timeout"); - } catch (final ArangoException e) { - assertThat(e.getCause(), instanceOf(ConnectTimeoutException.class)); - } - - configure.shutdown(); - - } - - @Test - @Ignore(value = "this fails some times") - public void so_connect_timeout() throws ArangoException { - - final ArangoConfigure configure = new ArangoConfigure(); - configure.setConnectionTimeout(5000); - configure.setTimeout(1); // 1ms - configure.init(); - - final ArangoDriver driver = new ArangoDriver(configure); - - try { - driver.getCollections(); - fail("did no timeout"); - } catch (final ArangoException e) { - assertThat(e.getCause(), instanceOf(SocketTimeoutException.class)); - } - - configure.shutdown(); - - } - - @Test - public void reconnectFallbackArangoHost() throws ArangoException { - - final ArangoConfigure configure = new ArangoConfigure(); - - // copy default arango host to fallback - final ArangoHost arangoHost = configure.getArangoHost(); - final ArangoHost ah = new ArangoHost(arangoHost.getHost(), arangoHost.getPort()); - configure.addFallbackArangoHost(ah); - - // change default port to wrong port - arangoHost.setPort(1025); - configure.init(); - - final ArangoDriver driver = new ArangoDriver(configure); - - driver.getCollections(); - - configure.shutdown(); - - } - - @Test - public void sslWithSelfSignedCertificateTest() throws ArangoException, KeyManagementException, - NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException, URISyntaxException { - - // create a sslContext for the self signed certificate - final URL resource = this.getClass().getResource(SSL_TRUSTSTORE); - final SSLContext sslContext = SSLContexts.custom() - .loadTrustMaterial(new File(resource.toURI()), SSL_TRUSTSTORE_PASSWORD.toCharArray()).build(); - - final ArangoConfigure configuration = new ArangoConfigure("/ssl-arangodb.properties"); - configuration.setSslContext(sslContext); - configuration.init(); - - final ArangoDriver arangoDriver = new ArangoDriver(configuration); - - final ArangoVersion version = arangoDriver.getVersion(); - - Assert.assertNotNull(version); - } - -} diff --git a/src/test/java/com/arangodb/ArangoDBTest.java b/src/test/java/com/arangodb/ArangoDBTest.java new file mode 100644 index 000000000..6ec0d2013 --- /dev/null +++ b/src/test/java/com/arangodb/ArangoDBTest.java @@ -0,0 +1,364 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb; + +import static org.hamcrest.Matchers.anyOf; +import static org.hamcrest.Matchers.contains; +import static org.hamcrest.Matchers.empty; +import static org.hamcrest.Matchers.everyItem; +import static org.hamcrest.Matchers.greaterThan; +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.junit.Assert.assertThat; +import static org.junit.Assert.fail; + +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; + +import org.junit.Test; + +import com.arangodb.entity.ArangoDBVersion; +import com.arangodb.entity.LogEntity; +import com.arangodb.entity.LogLevel; +import com.arangodb.entity.UserEntity; +import com.arangodb.model.LogOptions; +import com.arangodb.model.LogOptions.SortOrder; +import com.arangodb.model.UserCreateOptions; +import com.arangodb.model.UserUpdateOptions; +import com.arangodb.velocypack.exception.VPackException; +import com.arangodb.velocystream.Request; +import com.arangodb.velocystream.RequestType; +import com.arangodb.velocystream.Response; + +/** + * @author Mark - mark at arangodb.com + * + */ +public class ArangoDBTest { + + private static final String ROOT = "root"; + private static final String USER = "mit dem mund"; + private static final String PW = "machts der hund"; + + @Test + public void getVersion() { + final ArangoDB arangoDB = new ArangoDB.Builder().build(); + final ArangoDBVersion version = arangoDB.getVersion(); + assertThat(version, is(notNullValue())); + assertThat(version.getServer(), is(notNullValue())); + assertThat(version.getVersion(), is(notNullValue())); + } + + @Test + public void createDatabase() { + final ArangoDB arangoDB = new ArangoDB.Builder().build(); + final Boolean result = arangoDB.createDatabase(BaseTest.TEST_DB); + assertThat(result, is(true)); + try { + arangoDB.db(BaseTest.TEST_DB).drop(); + } catch (final ArangoDBException e) { + } + } + + @Test + public void deleteDatabase() { + final ArangoDB arangoDB = new ArangoDB.Builder().build(); + final Boolean resultCreate = arangoDB.createDatabase(BaseTest.TEST_DB); + assertThat(resultCreate, is(true)); + final Boolean resultDelete = arangoDB.db(BaseTest.TEST_DB).drop(); + assertThat(resultDelete, is(true)); + } + + @Test + public void getDatabases() { + final ArangoDB arangoDB = new ArangoDB.Builder().build(); + try { + Collection dbs = arangoDB.getDatabases(); + assertThat(dbs, is(notNullValue())); + assertThat(dbs.size(), is(1)); + assertThat(dbs.iterator().next(), is("_system")); + arangoDB.createDatabase(BaseTest.TEST_DB); + dbs = arangoDB.getDatabases(); + assertThat(dbs.size(), is(2)); + assertThat(dbs, hasItem("_system")); + assertThat(dbs, hasItem(BaseTest.TEST_DB)); + } finally { + arangoDB.db(BaseTest.TEST_DB).drop(); + } + } + + @Test + public void getAccessibleDatabases() { + final ArangoDB arangoDB = new ArangoDB.Builder().build(); + final Collection dbs = arangoDB.getAccessibleDatabases(); + assertThat(dbs, is(notNullValue())); + assertThat(dbs.size(), is(1)); + assertThat(dbs.iterator().next(), is("_system")); + } + + @Test + public void createUser() { + final ArangoDB arangoDB = new ArangoDB.Builder().build(); + try { + final UserEntity result = arangoDB.createUser(USER, PW, null); + assertThat(result, is(notNullValue())); + assertThat(result.getUser(), is(USER)); + assertThat(result.getChangePassword(), is(false)); + } finally { + arangoDB.deleteUser(USER); + } + } + + @Test + public void deleteUser() { + final ArangoDB arangoDB = new ArangoDB.Builder().build(); + arangoDB.createUser(USER, PW, null); + arangoDB.deleteUser(USER); + } + + @Test + public void getUserRoot() { + final ArangoDB arangoDB = new ArangoDB.Builder().build(); + final UserEntity user = arangoDB.getUser(ROOT); + assertThat(user, is(notNullValue())); + assertThat(user.getUser(), is(ROOT)); + } + + @Test + public void getUser() { + final ArangoDB arangoDB = new ArangoDB.Builder().build(); + try { + arangoDB.createUser(USER, PW, null); + final UserEntity user = arangoDB.getUser(USER); + assertThat(user.getUser(), is(USER)); + } finally { + arangoDB.deleteUser(USER); + } + + } + + @Test + public void getUsersOnlyRoot() { + final ArangoDB arangoDB = new ArangoDB.Builder().build(); + final Collection users = arangoDB.getUsers(); + assertThat(users, is(notNullValue())); + assertThat(users.size(), is(1)); + assertThat(users.iterator().next().getUser(), is(ROOT)); + } + + @Test + public void getUsers() { + final ArangoDB arangoDB = new ArangoDB.Builder().build(); + try { + arangoDB.createUser(USER, PW, null); + final Collection users = arangoDB.getUsers(); + assertThat(users, is(notNullValue())); + assertThat(users.size(), is(2)); + for (final UserEntity user : users) { + assertThat(user.getUser(), anyOf(is(ROOT), is(USER))); + } + } finally { + arangoDB.deleteUser(USER); + } + } + + @Test + public void updateUserNoOptions() { + final ArangoDB arangoDB = new ArangoDB.Builder().build(); + try { + arangoDB.createUser(USER, PW, null); + arangoDB.updateUser(USER, null); + } finally { + arangoDB.deleteUser(USER); + } + } + + @Test + public void updateUser() { + final ArangoDB arangoDB = new ArangoDB.Builder().build(); + try { + final Map extra = new HashMap(); + extra.put("hund", false); + arangoDB.createUser(USER, PW, new UserCreateOptions().extra(extra)); + extra.put("hund", true); + extra.put("mund", true); + final UserEntity user = arangoDB.updateUser(USER, new UserUpdateOptions().extra(extra)); + assertThat(user, is(notNullValue())); + assertThat(user.getExtra().size(), is(2)); + assertThat(user.getExtra().get("hund"), is(notNullValue())); + assertThat(Boolean.valueOf(String.valueOf(user.getExtra().get("hund"))), is(true)); + final UserEntity user2 = arangoDB.getUser(USER); + assertThat(user2.getExtra().size(), is(2)); + assertThat(user2.getExtra().get("hund"), is(notNullValue())); + assertThat(Boolean.valueOf(String.valueOf(user2.getExtra().get("hund"))), is(true)); + } finally { + arangoDB.deleteUser(USER); + } + } + + @Test + public void replaceUser() { + final ArangoDB arangoDB = new ArangoDB.Builder().build(); + try { + final Map extra = new HashMap(); + extra.put("hund", false); + arangoDB.createUser(USER, PW, new UserCreateOptions().extra(extra)); + extra.remove("hund"); + extra.put("mund", true); + final UserEntity user = arangoDB.replaceUser(USER, new UserUpdateOptions().extra(extra)); + assertThat(user, is(notNullValue())); + assertThat(user.getExtra().size(), is(1)); + assertThat(user.getExtra().get("mund"), is(notNullValue())); + assertThat(Boolean.valueOf(String.valueOf(user.getExtra().get("mund"))), is(true)); + final UserEntity user2 = arangoDB.getUser(USER); + assertThat(user2.getExtra().size(), is(1)); + assertThat(user2.getExtra().get("mund"), is(notNullValue())); + assertThat(Boolean.valueOf(String.valueOf(user2.getExtra().get("mund"))), is(true)); + } finally { + arangoDB.deleteUser(USER); + } + } + + @Test + public void authenticationFailPassword() { + final ArangoDB arangoDB = new ArangoDB.Builder().password("no").build(); + try { + arangoDB.getVersion(); + fail(); + } catch (final ArangoDBException e) { + + } + } + + @Test + public void authenticationFailUser() { + final ArangoDB arangoDB = new ArangoDB.Builder().user("no").build(); + try { + arangoDB.getVersion(); + fail(); + } catch (final ArangoDBException e) { + + } + } + + @Test + public void execute() throws VPackException { + final ArangoDB arangoDB = new ArangoDB.Builder().build(); + final Response response = arangoDB.execute(new Request("_system", RequestType.GET, "/_api/version")); + assertThat(response.getBody(), is(notNullValue())); + assertThat(response.getBody().get("version").isString(), is(true)); + } + + @Test + public void getLogs() { + final ArangoDB arangoDB = new ArangoDB.Builder().build(); + final LogEntity logs = arangoDB.getLogs(null); + assertThat(logs, is(notNullValue())); + assertThat(logs.getTotalAmount(), greaterThan(0L)); + assertThat((long) logs.getLid().size(), is(logs.getTotalAmount())); + assertThat((long) logs.getLevel().size(), is(logs.getTotalAmount())); + assertThat((long) logs.getTimestamp().size(), is(logs.getTotalAmount())); + assertThat((long) logs.getText().size(), is(logs.getTotalAmount())); + } + + @Test + public void getLogsUpto() { + final ArangoDB arangoDB = new ArangoDB.Builder().build(); + final LogEntity logsUpto = arangoDB.getLogs(new LogOptions().upto(LogLevel.WARNING)); + assertThat(logsUpto, is(notNullValue())); + assertThat(logsUpto.getLevel(), not(contains(LogLevel.INFO))); + } + + @Test + public void getLogsLevel() { + final ArangoDB arangoDB = new ArangoDB.Builder().build(); + final LogEntity logsInfo = arangoDB.getLogs(new LogOptions().level(LogLevel.INFO)); + assertThat(logsInfo, is(notNullValue())); + assertThat(logsInfo.getLevel(), everyItem(is(LogLevel.INFO))); + } + + @Test + public void getLogsStart() { + final ArangoDB arangoDB = new ArangoDB.Builder().build(); + final LogEntity logs = arangoDB.getLogs(null); + assertThat(logs.getLid(), not(empty())); + final LogEntity logsStart = arangoDB.getLogs(new LogOptions().start(logs.getLid().get(0) + 1)); + assertThat(logsStart, is(notNullValue())); + assertThat(logsStart.getLid(), not(contains(logs.getLid().get(0)))); + } + + @Test + public void getLogsSize() { + final ArangoDB arangoDB = new ArangoDB.Builder().build(); + final LogEntity logs = arangoDB.getLogs(null); + assertThat(logs.getLid().size(), greaterThan(0)); + final LogEntity logsSize = arangoDB.getLogs(new LogOptions().size(logs.getLid().size() - 1)); + assertThat(logsSize, is(notNullValue())); + assertThat(logsSize.getLid().size(), is(logs.getLid().size() - 1)); + } + + @Test + public void getLogsOffset() { + final ArangoDB arangoDB = new ArangoDB.Builder().build(); + final LogEntity logs = arangoDB.getLogs(null); + assertThat(logs.getTotalAmount(), greaterThan(0L)); + final LogEntity logsOffset = arangoDB.getLogs(new LogOptions().offset(1)); + assertThat(logsOffset, is(notNullValue())); + assertThat(logsOffset.getLid(), not(hasItem(logs.getLid().get(0)))); + } + + @Test + public void getLogsSearch() { + final ArangoDB arangoDB = new ArangoDB.Builder().build(); + final LogEntity logs = arangoDB.getLogs(null); + final LogEntity logsSearch = arangoDB.getLogs(new LogOptions().search(BaseTest.TEST_DB)); + assertThat(logsSearch, is(notNullValue())); + assertThat(logs.getTotalAmount(), greaterThan(logsSearch.getTotalAmount())); + } + + @Test + public void getLogsSortAsc() { + final ArangoDB arangoDB = new ArangoDB.Builder().build(); + final LogEntity logs = arangoDB.getLogs(new LogOptions().sort(SortOrder.asc)); + assertThat(logs, is(notNullValue())); + long lastId = -1; + for (final Long id : logs.getLid()) { + assertThat(id, greaterThan(lastId)); + lastId = id; + } + } + + @Test + public void getLogsSortDesc() { + final ArangoDB arangoDB = new ArangoDB.Builder().build(); + final LogEntity logs = arangoDB.getLogs(new LogOptions().sort(SortOrder.desc)); + assertThat(logs, is(notNullValue())); + long lastId = Long.MAX_VALUE; + for (final Long id : logs.getLid()) { + assertThat(lastId, greaterThan(id)); + lastId = id; + } + } + +} diff --git a/src/test/java/com/arangodb/ArangoDatabaseTest.java b/src/test/java/com/arangodb/ArangoDatabaseTest.java new file mode 100644 index 000000000..9c5d2cc23 --- /dev/null +++ b/src/test/java/com/arangodb/ArangoDatabaseTest.java @@ -0,0 +1,832 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb; + +import static org.hamcrest.CoreMatchers.notNullValue; +import static org.hamcrest.CoreMatchers.nullValue; +import static org.hamcrest.Matchers.empty; +import static org.hamcrest.Matchers.greaterThan; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.not; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.fail; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.atomic.AtomicInteger; + +import org.junit.Ignore; +import org.junit.Test; + +import com.arangodb.entity.AqlExecutionExplainEntity; +import com.arangodb.entity.AqlExecutionExplainEntity.ExecutionNode; +import com.arangodb.entity.AqlExecutionExplainEntity.ExecutionPlan; +import com.arangodb.entity.AqlFunctionEntity; +import com.arangodb.entity.AqlParseEntity; +import com.arangodb.entity.AqlParseEntity.AstNode; +import com.arangodb.entity.BaseDocument; +import com.arangodb.entity.BaseEdgeDocument; +import com.arangodb.entity.CollectionEntity; +import com.arangodb.entity.CollectionType; +import com.arangodb.entity.DatabaseEntity; +import com.arangodb.entity.GraphEntity; +import com.arangodb.entity.IndexEntity; +import com.arangodb.entity.PathEntity; +import com.arangodb.entity.QueryCachePropertiesEntity; +import com.arangodb.entity.QueryCachePropertiesEntity.CacheMode; +import com.arangodb.entity.QueryEntity; +import com.arangodb.entity.QueryTrackingPropertiesEntity; +import com.arangodb.entity.TraversalEntity; +import com.arangodb.model.AqlFunctionDeleteOptions; +import com.arangodb.model.AqlQueryOptions; +import com.arangodb.model.CollectionCreateOptions; +import com.arangodb.model.CollectionsReadOptions; +import com.arangodb.model.TransactionOptions; +import com.arangodb.model.TraversalOptions; +import com.arangodb.model.TraversalOptions.Direction; +import com.arangodb.velocypack.VPackBuilder; +import com.arangodb.velocypack.VPackSlice; +import com.arangodb.velocypack.exception.VPackException; + +/** + * @author Mark - mark at arangodb.com + * + */ +public class ArangoDatabaseTest extends BaseTest { + + private static final String COLLECTION_NAME = "db_test"; + private static final String GRAPH_NAME = "graph_test"; + + @Test + public void createCollection() { + try { + final CollectionEntity result = db.createCollection(COLLECTION_NAME, null); + assertThat(result, is(notNullValue())); + assertThat(result.getId(), is(notNullValue())); + } finally { + db.collection(COLLECTION_NAME).drop(); + } + } + + @Test + public void deleteCollection() { + db.createCollection(COLLECTION_NAME, null); + db.collection(COLLECTION_NAME).drop(); + try { + db.collection(COLLECTION_NAME).getInfo(); + fail(); + } catch (final ArangoDBException e) { + } + } + + @Test + public void getIndex() { + try { + db.createCollection(COLLECTION_NAME, null); + final Collection fields = new ArrayList(); + fields.add("a"); + final IndexEntity createResult = db.collection(COLLECTION_NAME).createHashIndex(fields, null); + final IndexEntity readResult = db.getIndex(createResult.getId()); + assertThat(readResult.getId(), is(createResult.getId())); + assertThat(readResult.getType(), is(createResult.getType())); + } finally { + db.collection(COLLECTION_NAME).drop(); + } + } + + @Test + public void deleteIndex() { + try { + db.createCollection(COLLECTION_NAME, null); + final Collection fields = new ArrayList(); + fields.add("a"); + final IndexEntity createResult = db.collection(COLLECTION_NAME).createHashIndex(fields, null); + final String id = db.deleteIndex(createResult.getId()); + assertThat(id, is(createResult.getId())); + try { + db.getIndex(id); + fail(); + } catch (final ArangoDBException e) { + } + } finally { + db.collection(COLLECTION_NAME).drop(); + } + } + + @Test + public void getCollections() { + try { + final Collection systemCollections = db.getCollections(null); + db.createCollection(COLLECTION_NAME + "1", null); + db.createCollection(COLLECTION_NAME + "2", null); + final Collection collections = db.getCollections(null); + assertThat(collections.size(), is(2 + systemCollections.size())); + assertThat(collections, is(notNullValue())); + } finally { + db.collection(COLLECTION_NAME + "1").drop(); + db.collection(COLLECTION_NAME + "2").drop(); + } + } + + @Test + public void getCollectionsExcludeSystem() { + try { + final CollectionsReadOptions options = new CollectionsReadOptions().excludeSystem(true); + final Collection systemCollections = db.getCollections(options); + assertThat(systemCollections.size(), is(0)); + db.createCollection(COLLECTION_NAME + "1", null); + db.createCollection(COLLECTION_NAME + "2", null); + final Collection collections = db.getCollections(options); + assertThat(collections.size(), is(2)); + assertThat(collections, is(notNullValue())); + } finally { + db.collection(COLLECTION_NAME + "1").drop(); + db.collection(COLLECTION_NAME + "2").drop(); + } + } + + @Test + public void grantAccess() { + try { + arangoDB.createUser("user1", "1234", null); + db.grantAccess("user1"); + } finally { + arangoDB.deleteUser("user1"); + } + } + + @Test(expected = ArangoDBException.class) + public void grantAccessUserNotFound() { + db.grantAccess("user1"); + } + + @Test + public void revokeAccess() { + try { + arangoDB.createUser("user1", "1234", null); + db.revokeAccess("user1"); + } finally { + arangoDB.deleteUser("user1"); + } + } + + @Test(expected = ArangoDBException.class) + public void revokeAccessUserNotFound() { + db.revokeAccess("user1"); + } + + @Test + public void query() { + try { + db.createCollection(COLLECTION_NAME, null); + for (int i = 0; i < 10; i++) { + db.collection(COLLECTION_NAME).insertDocument(new BaseDocument(), null); + } + final ArangoCursor cursor = db.query("for i in db_test return i._id", null, null, String.class); + assertThat(cursor, is(notNullValue())); + for (int i = 0; i < 10; i++, cursor.next()) { + assertThat(cursor.hasNext(), is(i != 10)); + } + } finally { + db.collection(COLLECTION_NAME).drop(); + } + } + + @Test + public void queryForEach() { + try { + db.createCollection(COLLECTION_NAME, null); + for (int i = 0; i < 10; i++) { + db.collection(COLLECTION_NAME).insertDocument(new BaseDocument(), null); + } + final ArangoCursor cursor = db.query("for i in db_test return i._id", null, null, String.class); + assertThat(cursor, is(notNullValue())); + final AtomicInteger i = new AtomicInteger(0); + for (; cursor.hasNext(); cursor.next()) { + i.incrementAndGet(); + } + assertThat(i.get(), is(10)); + } finally { + db.collection(COLLECTION_NAME).drop(); + } + } + + @Test + public void queryStream() { + try { + db.createCollection(COLLECTION_NAME, null); + for (int i = 0; i < 10; i++) { + db.collection(COLLECTION_NAME).insertDocument(new BaseDocument(), null); + } + final ArangoCursor cursor = db.query("for i in db_test return i._id", null, null, String.class); + assertThat(cursor, is(notNullValue())); + final AtomicInteger i = new AtomicInteger(0); + for (; cursor.hasNext(); cursor.next()) { + i.incrementAndGet(); + } + assertThat(i.get(), is(10)); + } finally { + db.collection(COLLECTION_NAME).drop(); + } + } + + @Test + public void queryWithCount() { + try { + db.createCollection(COLLECTION_NAME, null); + for (int i = 0; i < 10; i++) { + db.collection(COLLECTION_NAME).insertDocument(new BaseDocument(), null); + } + + final ArangoCursor cursor = db.query("for i in db_test Limit 6 return i._id", null, + new AqlQueryOptions().count(true), String.class); + assertThat(cursor, is(notNullValue())); + for (int i = 0; i < 6; i++, cursor.next()) { + assertThat(cursor.hasNext(), is(i != 6)); + } + assertThat(cursor.getCount(), is(6)); + + } finally { + db.collection(COLLECTION_NAME).drop(); + } + } + + @Test + public void queryWithLimitAndFullCount() { + try { + db.createCollection(COLLECTION_NAME, null); + for (int i = 0; i < 10; i++) { + db.collection(COLLECTION_NAME).insertDocument(new BaseDocument(), null); + } + + final ArangoCursor cursor = db.query("for i in db_test Limit 5 return i._id", null, + new AqlQueryOptions().fullCount(true), String.class); + assertThat(cursor, is(notNullValue())); + for (int i = 0; i < 5; i++, cursor.next()) { + assertThat(cursor.hasNext(), is(i != 5)); + } + assertThat(cursor.getStats(), is(notNullValue())); + assertThat(cursor.getStats().getFullCount(), is(10L)); + + } finally { + db.collection(COLLECTION_NAME).drop(); + } + } + + @Test + public void queryWithBatchSize() { + try { + db.createCollection(COLLECTION_NAME, null); + for (int i = 0; i < 10; i++) { + db.collection(COLLECTION_NAME).insertDocument(new BaseDocument(), null); + } + + final ArangoCursor cursor = db.query("for i in db_test return i._id", null, + new AqlQueryOptions().batchSize(5).count(true), String.class); + + assertThat(cursor, is(notNullValue())); + for (int i = 0; i < 10; i++, cursor.next()) { + assertThat(cursor.hasNext(), is(i != 10)); + } + + } finally { + db.collection(COLLECTION_NAME).drop(); + } + } + + @Test + public void queryStreamWithBatchSize() { + try { + db.createCollection(COLLECTION_NAME, null); + for (int i = 0; i < 10; i++) { + db.collection(COLLECTION_NAME).insertDocument(new BaseDocument(), null); + } + + final ArangoCursor cursor = db.query("for i in db_test return i._id", null, + new AqlQueryOptions().batchSize(5).count(true), String.class); + + assertThat(cursor, is(notNullValue())); + final AtomicInteger i = new AtomicInteger(0); + for (; cursor.hasNext(); cursor.next()) { + i.incrementAndGet(); + } + assertThat(i.get(), is(10)); + } finally { + db.collection(COLLECTION_NAME).drop(); + } + } + + /** + * ignored. takes to long + */ + @Test + @Ignore + public void queryWithTTL() throws InterruptedException { + // set TTL to 1 seconds and get the second batch after 2 seconds! + final int ttl = 1; + final int wait = 2; + try { + db.createCollection(COLLECTION_NAME, null); + for (int i = 0; i < 10; i++) { + db.collection(COLLECTION_NAME).insertDocument(new BaseDocument(), null); + } + + final ArangoCursor cursor = db.query("for i in db_test return i._id", null, + new AqlQueryOptions().batchSize(5).ttl(ttl), String.class); + + assertThat(cursor, is(notNullValue())); + + for (int i = 0; i < 10; i++, cursor.next()) { + assertThat(cursor.hasNext(), is(i != 10)); + if (i == 1) { + Thread.sleep(wait * 1000); + } + } + fail("this should fail"); + } catch (final ArangoDBException ex) { + assertThat(ex.getMessage(), is("Response: 404, Error: 1600 - cursor not found")); + } finally { + db.collection(COLLECTION_NAME).drop(); + } + } + + @Test + public void changeQueryCache() { + try { + QueryCachePropertiesEntity properties = db.getQueryCacheProperties(); + assertThat(properties, is(notNullValue())); + assertThat(properties.getMode(), is(CacheMode.off)); + assertThat(properties.getMaxResults(), greaterThan(0L)); + + properties.setMode(CacheMode.on); + properties = db.setQueryCacheProperties(properties); + assertThat(properties, is(notNullValue())); + assertThat(properties.getMode(), is(CacheMode.on)); + + properties = db.getQueryCacheProperties(); + assertThat(properties.getMode(), is(CacheMode.on)); + } finally { + final QueryCachePropertiesEntity properties = new QueryCachePropertiesEntity(); + properties.setMode(CacheMode.off); + db.setQueryCacheProperties(properties); + } + } + + @Test + public void queryWithCache() throws InterruptedException { + try { + db.createCollection(COLLECTION_NAME, null); + for (int i = 0; i < 10; i++) { + db.collection(COLLECTION_NAME).insertDocument(new BaseDocument(), null); + } + + final QueryCachePropertiesEntity properties = new QueryCachePropertiesEntity(); + properties.setMode(CacheMode.on); + db.setQueryCacheProperties(properties); + + final ArangoCursor cursor = db.query("FOR t IN db_test FILTER t.age >= 10 SORT t.age RETURN t._id", + null, new AqlQueryOptions().cache(true), String.class); + + assertThat(cursor, is(notNullValue())); + assertThat(cursor.isCached(), is(false)); + + final ArangoCursor cachedCursor = db.query( + "FOR t IN db_test FILTER t.age >= 10 SORT t.age RETURN t._id", null, new AqlQueryOptions().cache(true), + String.class); + + assertThat(cachedCursor, is(notNullValue())); + assertThat(cachedCursor.isCached(), is(true)); + + } finally { + db.collection(COLLECTION_NAME).drop(); + final QueryCachePropertiesEntity properties = new QueryCachePropertiesEntity(); + properties.setMode(CacheMode.off); + db.setQueryCacheProperties(properties); + } + } + + @Test + public void changeQueryTrackingProperties() { + try { + QueryTrackingPropertiesEntity properties = db.getQueryTrackingProperties(); + assertThat(properties, is(notNullValue())); + assertThat(properties.getEnabled(), is(true)); + assertThat(properties.getTrackSlowQueries(), is(true)); + assertThat(properties.getMaxQueryStringLength(), greaterThan(0L)); + assertThat(properties.getMaxSlowQueries(), greaterThan(0L)); + assertThat(properties.getSlowQueryThreshold(), greaterThan(0L)); + properties.setEnabled(false); + properties = db.setQueryTrackingProperties(properties); + assertThat(properties, is(notNullValue())); + assertThat(properties.getEnabled(), is(false)); + properties = db.getQueryTrackingProperties(); + assertThat(properties.getEnabled(), is(false)); + } finally { + final QueryTrackingPropertiesEntity properties = new QueryTrackingPropertiesEntity(); + properties.setEnabled(true); + db.setQueryTrackingProperties(properties); + } + } + + @Test + public void queryWithBindVars() throws InterruptedException { + try { + db.createCollection(COLLECTION_NAME, null); + for (int i = 0; i < 10; i++) { + final BaseDocument baseDocument = new BaseDocument(); + baseDocument.addAttribute("age", 20 + i); + db.collection(COLLECTION_NAME).insertDocument(baseDocument, null); + } + final Map bindVars = new HashMap(); + bindVars.put("@coll", COLLECTION_NAME); + bindVars.put("age", 25); + + final ArangoCursor cursor = db.query("FOR t IN @@coll FILTER t.age >= @age SORT t.age RETURN t._id", + bindVars, null, String.class); + + assertThat(cursor, is(notNullValue())); + + for (int i = 0; i < 5; i++, cursor.next()) { + assertThat(cursor.hasNext(), is(i != 5)); + } + + } finally { + db.collection(COLLECTION_NAME).drop(); + } + } + + @Test + public void queryWithWarning() { + final ArangoCursor cursor = arangoDB.db().query("return _users + 1", null, null, String.class); + + assertThat(cursor, is(notNullValue())); + assertThat(cursor.getWarnings(), is(notNullValue())); + assertThat(cursor.getWarnings(), is(not(empty()))); + } + + @Test + public void queryClose() throws IOException { + final ArangoCursor cursor = arangoDB.db().query("for i in _apps return i._id", null, + new AqlQueryOptions().batchSize(1), String.class); + cursor.close(); + int count = 0; + try { + for (; cursor.hasNext(); cursor.next(), count++) { + } + fail(); + } catch (final ArangoDBException e) { + assertThat(count, is(1)); + } + + } + + @Test + public void explainQuery() { + final AqlExecutionExplainEntity explain = arangoDB.db().explainQuery("for i in _apps return i", null, null); + assertThat(explain, is(notNullValue())); + assertThat(explain.getPlan(), is(notNullValue())); + assertThat(explain.getPlans(), is(nullValue())); + final ExecutionPlan plan = explain.getPlan(); + assertThat(plan.getCollections().size(), is(1)); + assertThat(plan.getCollections().iterator().next().getName(), is("_apps")); + assertThat(plan.getCollections().iterator().next().getType(), is("read")); + assertThat(plan.getEstimatedCost(), is(5)); + assertThat(plan.getEstimatedNrItems(), is(2)); + assertThat(plan.getVariables().size(), is(1)); + assertThat(plan.getVariables().iterator().next().getName(), is("i")); + assertThat(plan.getNodes().size(), is(3)); + final Iterator iterator = plan.getNodes().iterator(); + final ExecutionNode singletonNode = iterator.next(); + assertThat(singletonNode.getType(), is("SingletonNode")); + final ExecutionNode collectionNode = iterator.next(); + assertThat(collectionNode.getType(), is("EnumerateCollectionNode")); + assertThat(collectionNode.getDatabase(), is("_system")); + assertThat(collectionNode.getCollection(), is("_apps")); + assertThat(collectionNode.getOutVariable(), is(notNullValue())); + assertThat(collectionNode.getOutVariable().getName(), is("i")); + final ExecutionNode returnNode = iterator.next(); + assertThat(returnNode.getType(), is("ReturnNode")); + assertThat(returnNode.getInVariable(), is(notNullValue())); + assertThat(returnNode.getInVariable().getName(), is("i")); + } + + @Test + public void parseQuery() { + final AqlParseEntity parse = arangoDB.db().parseQuery("for i in _apps return i"); + assertThat(parse, is(notNullValue())); + assertThat(parse.getBindVars(), is(empty())); + assertThat(parse.getCollections().size(), is(1)); + assertThat(parse.getCollections().iterator().next(), is("_apps")); + assertThat(parse.getAst().size(), is(1)); + final AstNode root = parse.getAst().iterator().next(); + assertThat(root.getType(), is("root")); + assertThat(root.getName(), is(nullValue())); + assertThat(root.getSubNodes(), is(notNullValue())); + assertThat(root.getSubNodes().size(), is(2)); + final Iterator iterator = root.getSubNodes().iterator(); + final AstNode for_ = iterator.next(); + assertThat(for_.getType(), is("for")); + assertThat(for_.getSubNodes(), is(notNullValue())); + assertThat(for_.getSubNodes().size(), is(2)); + final Iterator iterator2 = for_.getSubNodes().iterator(); + final AstNode first = iterator2.next(); + assertThat(first.getType(), is("variable")); + assertThat(first.getName(), is("i")); + final AstNode second = iterator2.next(); + assertThat(second.getType(), is("collection")); + assertThat(second.getName(), is("_apps")); + final AstNode return_ = iterator.next(); + assertThat(return_.getType(), is("return")); + assertThat(return_.getSubNodes(), is(notNullValue())); + assertThat(return_.getSubNodes().size(), is(1)); + assertThat(return_.getSubNodes().iterator().next().getType(), is("reference")); + assertThat(return_.getSubNodes().iterator().next().getName(), is("i")); + } + + @Test + @Ignore + public void getCurrentlyRunningQueries() throws InterruptedException, ExecutionException { + final Thread t = new Thread() { + @Override + public void run() { + super.run(); + db.query("return sleep(0.2)", null, null, Void.class); + } + }; + t.start(); + Thread.sleep(100); + try { + final Collection currentlyRunningQueries = db.getCurrentlyRunningQueries(); + assertThat(currentlyRunningQueries, is(notNullValue())); + assertThat(currentlyRunningQueries.size(), is(1)); + final QueryEntity queryEntity = currentlyRunningQueries.iterator().next(); + assertThat(queryEntity.getQuery(), is("return sleep(0.2)")); + } finally { + t.join(); + } + } + + @Test + @Ignore + public void getAndClearSlowQueries() throws InterruptedException, ExecutionException { + final QueryTrackingPropertiesEntity properties = db.getQueryTrackingProperties(); + final Long slowQueryThreshold = properties.getSlowQueryThreshold(); + try { + properties.setSlowQueryThreshold(1L); + db.setQueryTrackingProperties(properties); + + db.query("return sleep(1.1)", null, null, Void.class); + final Collection slowQueries = db.getSlowQueries(); + assertThat(slowQueries, is(notNullValue())); + assertThat(slowQueries.size(), is(1)); + final QueryEntity queryEntity = slowQueries.iterator().next(); + assertThat(queryEntity.getQuery(), is("return sleep(1.1)")); + + db.clearSlowQueries(); + assertThat(db.getSlowQueries().size(), is(0)); + } finally { + properties.setSlowQueryThreshold(slowQueryThreshold); + db.setQueryTrackingProperties(properties); + } + } + + @Test + @Ignore + public void killQuery() throws InterruptedException, ExecutionException { + final Thread t = new Thread() { + @Override + public void run() { + super.run(); + try { + db.query("return sleep(0.2)", null, null, Void.class); + fail(); + } catch (final ArangoDBException e) { + } + } + }; + t.start(); + Thread.sleep(100); + final Collection currentlyRunningQueries = db.getCurrentlyRunningQueries(); + assertThat(currentlyRunningQueries, is(notNullValue())); + assertThat(currentlyRunningQueries.size(), is(1)); + + final QueryEntity queryEntity = currentlyRunningQueries.iterator().next(); + db.killQuery(queryEntity.getId()); + } + + @Test + public void createGetDeleteAqlFunction() { + final Collection aqlFunctionsInitial = db.getAqlFunctions(null); + assertThat(aqlFunctionsInitial, is(empty())); + try { + db.createAqlFunction("myfunctions::temperature::celsiustofahrenheit", + "function (celsius) { return celsius * 1.8 + 32; }", null); + + final Collection aqlFunctions = db.getAqlFunctions(null); + assertThat(aqlFunctions.size(), is(greaterThan(aqlFunctionsInitial.size()))); + } finally { + db.deleteAqlFunction("myfunctions::temperature::celsiustofahrenheit", null); + + final Collection aqlFunctions = db.getAqlFunctions(null); + assertThat(aqlFunctions.size(), is(aqlFunctionsInitial.size())); + } + } + + @Test + public void createGetDeleteAqlFunctionWithNamespace() { + final Collection aqlFunctionsInitial = db.getAqlFunctions(null); + assertThat(aqlFunctionsInitial, is(empty())); + try { + db.createAqlFunction("myfunctions::temperature::celsiustofahrenheit1", + "function (celsius) { return celsius * 1.8 + 32; }", null); + db.createAqlFunction("myfunctions::temperature::celsiustofahrenheit2", + "function (celsius) { return celsius * 1.8 + 32; }", null); + + } finally { + db.deleteAqlFunction("myfunctions::temperature", new AqlFunctionDeleteOptions().group(true)); + + final Collection aqlFunctions = db.getAqlFunctions(null); + assertThat(aqlFunctions.size(), is(aqlFunctionsInitial.size())); + } + } + + @Test + public void createGraph() { + try { + final GraphEntity result = db.createGraph(GRAPH_NAME, null, null); + assertThat(result, is(notNullValue())); + assertThat(result.getName(), is(GRAPH_NAME)); + } finally { + db.graph(GRAPH_NAME).drop(); + } + } + + @Test + public void getGraphs() { + try { + db.createGraph(GRAPH_NAME, null, null); + final Collection graphs = db.getGraphs(); + assertThat(graphs, is(notNullValue())); + assertThat(graphs.size(), is(1)); + } finally { + db.graph(GRAPH_NAME).drop(); + } + } + + @Test + public void transactionString() { + final TransactionOptions options = new TransactionOptions().params("test"); + final String result = db.transaction("function (params) {return params;}", String.class, options); + assertThat(result, is("test")); + } + + @Test + public void transactionNumber() { + final TransactionOptions options = new TransactionOptions().params(5); + final Integer result = db.transaction("function (params) {return params;}", Integer.class, options); + assertThat(result, is(5)); + } + + @Test + public void transactionVPack() throws VPackException { + final TransactionOptions options = new TransactionOptions().params(new VPackBuilder().add("test").slice()); + final VPackSlice result = db.transaction("function (params) {return params;}", VPackSlice.class, options); + assertThat(result.isString(), is(true)); + assertThat(result.getAsString(), is("test")); + } + + @Test + public void transactionEmpty() { + db.transaction("function () {}", null, null); + } + + @Test + public void transactionallowImplicit() { + try { + db.createCollection("someCollection", null); + db.createCollection("someOtherCollection", null); + final String action = "function (params) {" + "var db = require('internal').db;" + + "return {'a':db.someCollection.all().toArray()[0], 'b':db.someOtherCollection.all().toArray()[0]};" + + "}"; + final TransactionOptions options = new TransactionOptions().readCollections("someCollection"); + db.transaction(action, VPackSlice.class, options); + try { + options.allowImplicit(false); + db.transaction(action, VPackSlice.class, options); + fail(); + } catch (final ArangoDBException e) { + } + } finally { + db.collection("someCollection").drop(); + db.collection("someOtherCollection").drop(); + } + } + + @Test + public void getInfo() { + final DatabaseEntity info = db.getInfo(); + assertThat(info, is(notNullValue())); + assertThat(info.getId(), is(notNullValue())); + assertThat(info.getName(), is(TEST_DB)); + assertThat(info.getPath(), is(notNullValue())); + assertThat(info.getIsSystem(), is(false)); + } + + @Test + public void executeTraversal() { + try { + db.createCollection("person", null); + db.createCollection("knows", new CollectionCreateOptions().type(CollectionType.EDGES)); + for (final String e : new String[] { "Alice", "Bob", "Charlie", "Dave", "Eve" }) { + final BaseDocument doc = new BaseDocument(); + doc.setKey(e); + db.collection("person").insertDocument(doc, null); + } + for (final String[] e : new String[][] { new String[] { "Alice", "Bob" }, new String[] { "Bob", "Charlie" }, + new String[] { "Bob", "Dave" }, new String[] { "Eve", "Alice" }, new String[] { "Eve", "Bob" } }) { + final BaseEdgeDocument edge = new BaseEdgeDocument(); + edge.setKey(e[0] + "_knows_" + e[1]); + edge.setFrom("person/" + e[0]); + edge.setTo("person/" + e[1]); + db.collection("knows").insertDocument(edge, null); + } + final TraversalOptions options = new TraversalOptions().edgeCollection("knows").startVertex("person/Alice") + .direction(Direction.outbound); + final TraversalEntity traversal = db.executeTraversal(BaseDocument.class, + BaseEdgeDocument.class, options); + + assertThat(traversal, is(notNullValue())); + + final Collection vertices = traversal.getVertices(); + assertThat(vertices, is(notNullValue())); + assertThat(vertices.size(), is(4)); + + final Iterator verticesIterator = vertices.iterator(); + for (final String e : new String[] { "Alice", "Bob", "Charlie", "Dave" }) { + assertThat(verticesIterator.next().getKey(), is(e)); + } + + final Collection> paths = traversal.getPaths(); + assertThat(paths, is(notNullValue())); + assertThat(paths.size(), is(4)); + + assertThat(paths.iterator().hasNext(), is(true)); + final PathEntity first = paths.iterator().next(); + assertThat(first, is(notNullValue())); + assertThat(first.getEdges().size(), is(0)); + assertThat(first.getVertices().size(), is(1)); + assertThat(first.getVertices().iterator().next().getKey(), is("Alice")); + } finally { + db.collection("person").drop(); + db.collection("knows").drop(); + } + } + + @Test + public void getDocument() { + try { + db.createCollection(COLLECTION_NAME); + final BaseDocument value = new BaseDocument(); + value.setKey("123"); + db.collection(COLLECTION_NAME).insertDocument(value); + final BaseDocument document = db.getDocument(COLLECTION_NAME + "/123", BaseDocument.class); + assertThat(document, is(notNullValue())); + assertThat(document.getKey(), is("123")); + } finally { + db.collection(COLLECTION_NAME).drop(); + } + } + + @Test(expected = ArangoDBException.class) + public void getDocumentWrongId() { + db.getDocument("123", BaseDocument.class); + } + + @Test + public void reloadRouting() { + db.reloadRouting(); + } +} diff --git a/src/test/java/com/arangodb/ArangoDriverAdminTest.java b/src/test/java/com/arangodb/ArangoDriverAdminTest.java deleted file mode 100644 index b63dbf994..000000000 --- a/src/test/java/com/arangodb/ArangoDriverAdminTest.java +++ /dev/null @@ -1,200 +0,0 @@ -/* - * Copyright (C) 2012 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb; - -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.not; -import static org.hamcrest.CoreMatchers.notNullValue; -import static org.hamcrest.CoreMatchers.startsWith; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.arangodb.entity.AdminLogEntity; -import com.arangodb.entity.ArangoUnixTime; -import com.arangodb.entity.ArangoVersion; -import com.arangodb.entity.DefaultEntity; -import com.arangodb.entity.StatisticsDescriptionEntity; -import com.arangodb.entity.StatisticsEntity; -import com.google.gson.Gson; - -/** - * @author tamtam180 - kirscheless at gmail.com - * - */ -public class ArangoDriverAdminTest extends BaseTest { - - private static Logger logger = LoggerFactory.getLogger(ArangoDriverAdminTest.class); - - @Test - public void test_version() throws ArangoException { - - final ArangoVersion version = driver.getVersion(); - assertEquals("arango", version.getServer()); - assertNotNull(version.getVersion()); - assertTrue(version.getVersion().startsWith("2.") || version.getVersion().startsWith("3.")); - } - - @Test - public void test_time() throws ArangoException { - - final ArangoUnixTime time = driver.getTime(); - assertThat(time.getSecond(), is(not(0))); - assertThat(time.getMicrosecond(), is(not(0))); - - logger.debug("unixtime=" + time.getSecond()); - logger.debug("unixtime_micros=" + time.getMicrosecond()); - logger.debug("unixtime_millis=" + time.getTimeMillis()); - - } - - @Test - public void test_log_all() throws ArangoException { - - final AdminLogEntity entity = driver.getServerLog(null, null, null, null, null, null, null); - - assertThat(entity, is(notNullValue())); - assertThat(entity.getTotalAmount(), is(not(0))); - assertThat(entity.getLogs().size(), is(entity.getTotalAmount())); - - // debug - for (final AdminLogEntity.LogEntry log : entity.getLogs()) { - logger.debug("%d\t%d\t%tF % it = res.getAqlFunctions().keySet().iterator(); - while (it.hasNext()) { - driver.deleteAqlFunction(it.next(), false); - } - } - - @After - public void after() { - } - - @Test - public void test_AqlFunctions() throws ArangoException { - { - final CollectionEntity count = driver.getCollectionCount("_aqlfunctions"); - Assert.assertEquals(0, count.getCount()); - } - - DefaultEntity res = driver.createAqlFunction("someNamespace::testCode", - "function (celsius) { return celsius * 2.8 + 32; }"); - assertThat(res.getCode(), is(201)); - assertThat(res.getErrorMessage(), is((String) null)); - - try { - res = driver.createAqlFunction("someNamespace::testC&&&&&&&&&&de", - "function (celsius) { return celsius * 2.8 + 32; }"); - } catch (final ArangoException e) { - assertThat(e.getCode(), is(400)); - assertThat(e.getErrorMessage(), is("invalid user function name")); - } - - res = driver.createAqlFunction("anotherNamespace::testCode", - "function (celsius) { return celsius * 2.8 + 32; }"); - assertThat(res.getCode(), is(201)); - assertThat(res.getErrorMessage(), is((String) null)); - res = driver.createAqlFunction("anotherNamespace::testCode2", - "function (celsius) { return celsius * 2.8 + 32; }"); - assertThat(res.getCode(), is(201)); - assertThat(res.getErrorMessage(), is((String) null)); - - { - final CollectionEntity count = driver.getCollectionCount("_aqlfunctions"); - Assert.assertEquals(3, count.getCount()); - } - - AqlFunctionsEntity r = driver.getAqlFunctions(null); - assertThat(r.size(), is(3)); - assertTrue(r.getAqlFunctions().keySet().contains("anotherNamespace::testCode")); - assertTrue(r.getAqlFunctions().keySet().contains("someNamespace::testCode")); - - r = driver.getAqlFunctions("someNamespace"); - assertThat(r.size(), is(1)); - assertFalse(r.getAqlFunctions().keySet().contains("anotherNamespace::testCode")); - assertTrue(r.getAqlFunctions().keySet().contains("someNamespace::testCode")); - - res = driver.deleteAqlFunction("someNamespace::testCode", false); - assertThat(res.getCode(), is(200)); - assertThat(res.getErrorMessage(), is((String) null)); - - res = driver.deleteAqlFunction("anotherNamespace", true); - assertThat(res.getCode(), is(200)); - assertThat(res.getErrorMessage(), is((String) null)); - - final AqlFunctionsEntity c = driver.getAqlFunctions("someNamespace"); - assertThat(c.size(), is(0)); - } - -} diff --git a/src/test/java/com/arangodb/ArangoDriverAsyncTest.java b/src/test/java/com/arangodb/ArangoDriverAsyncTest.java deleted file mode 100644 index 5545a9e8c..000000000 --- a/src/test/java/com/arangodb/ArangoDriverAsyncTest.java +++ /dev/null @@ -1,241 +0,0 @@ -/* - * Copyright (C) 2012 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb; - -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import com.arangodb.entity.AqlFunctionsEntity; -import com.arangodb.entity.DefaultEntity; -import com.arangodb.entity.DocumentEntity; -import com.arangodb.entity.JobsEntity; - -/** - * @author tamtam180 - kirscheless at gmail.com - * - */ -public class ArangoDriverAsyncTest extends BaseTest { - - @Before - public void before() throws ArangoException { - for (final String col : new String[] { "blub" }) { - try { - driver.deleteCollection(col); - } catch (final ArangoException e) { - } - try { - driver.createCollection(col); - } catch (final ArangoException e) { - } - try { - driver.stopAsyncMode(); - } catch (final ArangoException e) { - - } - final AqlFunctionsEntity res = driver.getAqlFunctions(null); - final Iterator it = res.getAqlFunctions().keySet().iterator(); - while (it.hasNext()) { - driver.deleteAqlFunction(it.next(), false); - } - } - } - - @After - public void after() { - } - - @Test - public void test_StartCancelExecuteAsyncMode() throws ArangoException { - - driver.startAsyncMode(false); - String msg = ""; - try { - driver.startAsyncMode(false); - } catch (final ArangoException e) { - msg = e.getErrorMessage(); - } - assertThat(msg, is("Arango driver already set to asynchronous mode.")); - - driver.stopAsyncMode(); - msg = ""; - try { - driver.stopAsyncMode(); - } catch (final ArangoException e) { - msg = e.getErrorMessage(); - } - assertThat(msg, is("Arango driver already set to synchronous mode.")); - - } - - @Test - public void test_execAsyncMode() throws ArangoException { - - driver.startAsyncMode(false); - - driver.createAqlFunction("someNamespace::testCode", "function (celsius) { return celsius * 2.8 + 32; }"); - - assertNotNull(driver.getLastJobId()); - - driver.createAqlFunction("someNamespace::testC&&&&&&&&&&de", - "function (celsius) { return celsius * 2.8 + 32; }"); - - assertThat(driver.getJobIds().size(), is(2)); - - driver.getAqlFunctions(null); - - assertThat(driver.getJobIds().size(), is(3)); - - for (int i = 0; i < 10; i++) { - final TestComplexEntity01 value = new TestComplexEntity01("user-" + i, "data:" + i, i); - driver.createDocument("blub", value, false); - assertThat(driver.getJobIds().size(), is(4 + i)); - } - - driver.stopAsyncMode(); - - assertThat(driver.getJobIds().size(), is(13)); - - } - - @Test - public void test_execFireAndForgetMode() throws ArangoException { - - driver.startAsyncMode(true); - - assertThat(driver.getJobIds().size(), is(0)); - - driver.createAqlFunction("someNamespace::testCode", "function (celsius) { return celsius * 2.8 + 32; }"); - - assertThat(driver.getJobIds().size(), is(0)); - - driver.createAqlFunction("someNamespace::testC&&&&&&&&&&de", - "function (celsius) { return celsius * 2.8 + 32; }"); - - assertThat(driver.getJobIds().size(), is(0)); - - driver.stopAsyncMode(); - - } - - @Test - public void test_GetJobsMode() throws ArangoException { - - driver.deleteAllJobs(); - - driver.startAsyncMode(false); - - driver.createAqlFunction("someNamespace::testCode", "function (celsius) { return celsius * 2.8 + 32; }"); - - assertNotNull(driver.getLastJobId()); - - driver.createAqlFunction("someNamespace::testC&&&&&&&&&&de", - "function (celsius) { return celsius * 2.8 + 32; }"); - - assertThat(driver.getJobIds().size(), is(2)); - - driver.getAqlFunctions(null); - - assertThat(driver.getJobIds().size(), is(3)); - - for (int i = 0; i < 10; i++) { - final TestComplexEntity01 value = new TestComplexEntity01("user-" + i, "data:" + i, i); - driver.createDocument("blub", value, false); - assertThat(driver.getJobIds().size(), is(4 + i)); - } - - driver.stopAsyncMode(); - driver.getJobs(JobsEntity.JobState.DONE, 10); - driver.getJobs(JobsEntity.JobState.PENDING, 10); - - driver.getJobs(JobsEntity.JobState.DONE); - - driver.startAsyncMode(false); - for (int i = 0; i < 100; i++) { - final TestComplexEntity01 value = new TestComplexEntity01("user-" + i, "data:" + i, i); - driver.createDocument("blub", value, false); - } - driver.stopAsyncMode(); - driver.deleteExpiredJobs((int) (System.currentTimeMillis() / 2000L)); - driver.getJobs(JobsEntity.JobState.PENDING); - - } - - @Test - public void test_GetJobsResult() throws ArangoException { - - driver.deleteAllJobs(); - - driver.startAsyncMode(false); - - driver.createAqlFunction("someNamespace::testCode", "function (celsius) { return celsius * 2.8 + 32; }"); - - final String id1 = driver.getLastJobId(); - - driver.createAqlFunction("someNamespace::testC&&&&&&&&&&de", - "function (celsius) { return celsius * 2.8 + 32; }"); - - final String id2 = driver.getLastJobId(); - - driver.getAqlFunctions(null); - - final String id3 = driver.getLastJobId(); - - final List ids = new ArrayList(); - for (int i = 0; i < 10; i++) { - final TestComplexEntity01 value = new TestComplexEntity01("user-" + i, "data:" + i, i); - driver.createDocument("blub", value, false); - ids.add(driver.getLastJobId()); - } - - driver.stopAsyncMode(); - try { - Thread.sleep(2000); - } catch (final InterruptedException e) { - e.printStackTrace(); - } - final DefaultEntity de = driver.getJobResult(id1); - assertThat(de.getStatusCode(), is(201)); - - try { - driver.getJobResult(id2); - } catch (final ArangoException e) { - assertTrue(e.getErrorMessage().equals("java.lang.reflect.InvocationTargetException")); - } - - final AqlFunctionsEntity functions = driver.getJobResult(id3); - assertThat(functions.getStatusCode(), is(200)); - - DocumentEntity resultComplex; - - for (final String id : ids) { - resultComplex = driver.getJobResult(id); - assertThat(resultComplex.getStatusCode(), is(202)); - } - - } - -} diff --git a/src/test/java/com/arangodb/ArangoDriverAuthTest.java b/src/test/java/com/arangodb/ArangoDriverAuthTest.java deleted file mode 100644 index d31777410..000000000 --- a/src/test/java/com/arangodb/ArangoDriverAuthTest.java +++ /dev/null @@ -1,230 +0,0 @@ -/* - * Copyright (C) 2012,2013 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb; - -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; - -import org.junit.After; -import org.junit.Test; - -/** - * Basic Auth test. Must "disable-authentication=no" in server configure. - * - * @author tamtam180 - kirscheless at gmail.com - * - */ -public class ArangoDriverAuthTest { - - private static final String USER_MIN_A = "user-A"; - private static final String USER_A = "userA"; - private static final String USER_B = "userB"; - private static final String USER_JAP_A = "ゆーざーA"; - - @After - public void after() { - ArangoConfigure configure = new ArangoConfigure(); - configure.init(); - ArangoDriver driver = new ArangoDriver(configure); - for (String username : new String[] { USER_A, USER_B, USER_MIN_A, USER_JAP_A }) { - try { - driver.deleteUser(username); - } catch (ArangoException e) { - } - } - } - - @Test - public void test_auth() throws ArangoException { - - ArangoConfigure configure = new ArangoConfigure(); - configure.setUser(null); - configure.setPassword(null); - configure.init(); - - ArangoDriver driver = new ArangoDriver(configure); - try { - driver.getTime(); - fail(); - } catch (ArangoException e) { - assertThat(e.isUnauthorized(), is(true)); - assertThat(e.getEntity().getStatusCode(), is(401)); - assertThat(e.getErrorMessage(), containsString("Unauthorized")); - } - - configure.shutdown(); - } - - @Test - public void test_auth_root() throws ArangoException { - - ArangoConfigure configure = new ArangoConfigure(); - configure.setUser("root"); - configure.setPassword(""); - configure.init(); - - ArangoDriver driver = new ArangoDriver(configure); - driver.getTime(); - - configure.shutdown(); - } - - @Test - public void test_auth_added_user() throws ArangoException { - - ArangoConfigure configure = new ArangoConfigure(); - configure.setUser("root"); - configure.setPassword(""); - configure.init(); - - ArangoDriver driver = new ArangoDriver(configure); - - // Create User - final String username = USER_A; - try { - driver.createUser(username, "passA", true, null); - } catch (ArangoException e) { - driver.replaceUser(username, "passA", true, null); - } - driver.grantDatabaseAccess(username, "_system"); - configure.shutdown(); - - configure = new ArangoConfigure(); - configure.setUser(username); - configure.setPassword("passA"); - configure.init(); - driver = new ArangoDriver(configure); - driver.getTime(); - configure.shutdown(); - - } - - @Test - public void test_auth_added_user_inactive() throws ArangoException { - - ArangoConfigure configure = new ArangoConfigure(); - configure.setUser("root"); - configure.setPassword(""); - configure.init(); - - ArangoDriver driver = new ArangoDriver(configure); - - // Create User - try { - driver.createUser(USER_B, "passB", false, null); - } catch (ArangoException e) { - driver.replaceUser(USER_B, "passB", false, null); - } - - configure.shutdown(); - - configure = new ArangoConfigure(); - configure.setUser(USER_B); - configure.setPassword("passB"); - configure.init(); - driver = new ArangoDriver(configure); - - // Memo: Failed version 1.2.3 - try { - driver.getTime(); - fail(""); - } catch (ArangoException e) { - assertThat(e.getCode(), is(401)); - assertThat(e.getErrorNumber(), is(0)); - assertThat(e.getErrorMessage(), containsString("Unauthorized")); - } - configure.shutdown(); - - } - - @Test - public void test_auth_multibyte_username() throws ArangoException { - - ArangoConfigure configure = new ArangoConfigure(); - configure.setUser("root"); - configure.setPassword(""); - configure.init(); - - ArangoDriver driver = new ArangoDriver(configure); - - // Create User - try { - driver.createUser(USER_JAP_A, "pass", false, null); - } catch (ArangoException e) { - driver.replaceUser(USER_JAP_A, "pass", false, null); - } - - configure.shutdown(); - - ArangoConfigure configure2 = new ArangoConfigure(); - configure2.setUser(USER_JAP_A); - configure2.setPassword("pass"); - configure2.init(); - ArangoDriver driver2 = new ArangoDriver(configure2); - - try { - driver2.getTime(); - fail(""); - } catch (ArangoException e) { - assertThat(e.getCode(), is(401)); - assertThat(e.getErrorNumber(), is(0)); - assertThat(e.getErrorMessage(), containsString("Unauthorized")); - } - - configure2.shutdown(); - } - - @Test - public void test_auth_multibyte_password() throws ArangoException { - - ArangoConfigure configure = new ArangoConfigure(); - configure.setUser("root"); - configure.setPassword(""); - configure.init(); - - ArangoDriver driver = new ArangoDriver(configure); - - // Create User - try { - driver.createUser(USER_MIN_A, "パスワード", false, null); - } catch (ArangoException e) { - driver.replaceUser(USER_MIN_A, "パスワード", false, null); - } - - configure.shutdown(); - - configure = new ArangoConfigure(); - configure.setUser(USER_MIN_A); - configure.setPassword("パスワード"); - configure.init(); - driver = new ArangoDriver(configure); - - try { - driver.getTime(); - fail(""); - } catch (ArangoException e) { - assertThat(e.getErrorNumber(), is(0)); - assertThat(e.getCode(), is(401)); - assertThat(e.getErrorMessage(), containsString("Unauthorized")); - } - configure.shutdown(); - - } - -} diff --git a/src/test/java/com/arangodb/ArangoDriverBatchGraphTest.java b/src/test/java/com/arangodb/ArangoDriverBatchGraphTest.java deleted file mode 100644 index 0d2e5dc1a..000000000 --- a/src/test/java/com/arangodb/ArangoDriverBatchGraphTest.java +++ /dev/null @@ -1,134 +0,0 @@ -package com.arangodb; - -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.notNullValue; -import static org.hamcrest.CoreMatchers.nullValue; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; - -import java.util.Map; - -import org.junit.Test; - -import com.arangodb.entity.DocumentEntity; -import com.arangodb.entity.EdgeEntity; -import com.arangodb.entity.GraphEntity; - -public class ArangoDriverBatchGraphTest extends BaseGraphTest { - - private final String graphName = "ArangoDriverBatchGraphTest"; - private final String edgeCollectionName = "edge-1"; - - @Test - public void createGraph() throws ArangoException { - driver.startBatchMode(); - final GraphEntity tmpResult = driver.createGraph(this.graphName, this.createEdgeDefinitions(2, 0), - this.createOrphanCollections(2), true); - assertThat(tmpResult, is(notNullValue())); - assertThat(tmpResult.getRequestId(), is(notNullValue())); - - driver.executeBatch(); - - final GraphEntity createGraph = driver.getBatchResponseByRequestId(tmpResult.getRequestId()); - assertThat(createGraph, is(notNullValue())); - assertThat(createGraph.getName(), is(this.graphName)); - assertThat(createGraph.getRequestId(), is(nullValue())); - } - - @Test - public void createGraphVertex() throws ArangoException { - driver.startBatchMode(); - driver.createGraph(this.graphName, this.createEdgeDefinitions(2, 0), this.createOrphanCollections(2), true); - - final DocumentEntity v1 = driver.graphCreateVertex(this.graphName, "from1-1", - new TestComplexEntity03("v1-user", "desc1", 10), null); - assertThat(v1, is(notNullValue())); - assertThat(v1.getRequestId(), is(notNullValue())); - - final DocumentEntity v2 = driver.graphCreateVertex(this.graphName, "to1-1", - new TestComplexEntity03("v2-user", "desc2", 12), null); - assertThat(v2, is(notNullValue())); - assertThat(v2.getRequestId(), is(notNullValue())); - - driver.executeBatch(); - - final DocumentEntity v3 = driver.getBatchResponseByRequestId(v1.getRequestId()); - assertThat(v3, is(notNullValue())); - assertThat(v3.getDocumentKey(), is(notNullValue())); - assertThat(v3.getRequestId(), is(nullValue())); - - final DocumentEntity v4 = driver.getBatchResponseByRequestId(v2.getRequestId()); - assertThat(v4, is(notNullValue())); - assertThat(v4.getDocumentKey(), is(notNullValue())); - assertThat(v4.getRequestId(), is(nullValue())); - } - - @SuppressWarnings("rawtypes") - @Test - public void createGraphEdge() throws ArangoException { - - driver.createGraph(this.graphName, this.createEdgeDefinitions(2, 0), this.createOrphanCollections(2), true); - - final DocumentEntity v1 = driver.graphCreateVertex(this.graphName, "from1-1", - new TestComplexEntity03("v1-user", "desc1", 10), null); - - final DocumentEntity v2 = driver.graphCreateVertex(this.graphName, "to1-1", - new TestComplexEntity03("v2-user", "desc2", 12), null); - - driver.startBatchMode(); - - driver.graphCreateEdge(this.graphName, edgeCollectionName, null, v1.getDocumentHandle(), v2.getDocumentHandle(), - null, null); - - driver.graphCreateEdge(this.graphName, edgeCollectionName, null, v1.getDocumentHandle(), v2.getDocumentHandle(), - null, null); - - final EdgeEntity e1 = driver.graphCreateEdge(this.graphName, edgeCollectionName, null, - v1.getDocumentHandle(), v2.getDocumentHandle(), null, null); - assertThat(e1, is(notNullValue())); - assertThat(e1.getRequestId(), is(notNullValue())); - - driver.executeBatch(); - - final EdgeEntity e2 = driver.getBatchResponseByRequestId(e1.getRequestId()); - assertThat(e2, is(notNullValue())); - assertThat(e2.getDocumentKey(), is(notNullValue())); - assertThat(e2.getRequestId(), is(nullValue())); - - EdgeEntity graphGetEdge = driver.graphGetEdge(graphName, edgeCollectionName, e2.getDocumentKey(), - Map.class, null, null); - assertThat(graphGetEdge, is(notNullValue())); - assertThat(graphGetEdge.getDocumentKey(), is(e2.getDocumentKey())); - } - - @Test - public void createGraphEdgeFail() throws ArangoException { - - driver.createGraph(this.graphName, this.createEdgeDefinitions(2, 0), this.createOrphanCollections(2), true); - - driver.startBatchMode(); - - final DocumentEntity v1 = driver.graphCreateVertex(this.graphName, "from1-1", - new TestComplexEntity03("v1-user", "desc1", 10), null); - - final DocumentEntity v2 = driver.graphCreateVertex(this.graphName, "to1-1", - new TestComplexEntity03("v2-user", "desc2", 12), null); - - final EdgeEntity e1 = driver.graphCreateEdge(this.graphName, edgeCollectionName, null, - v1.getDocumentHandle(), v2.getDocumentHandle(), null, null); - assertThat(e1, is(notNullValue())); - assertThat(e1.getRequestId(), is(notNullValue())); - - driver.executeBatch(); - - EdgeEntity e2 = null; - try { - e2 = driver.getBatchResponseByRequestId(e1.getRequestId()); - fail("this should fail"); - } catch (Exception ex) { - } - assertThat(e2, is(nullValue())); - - } - -} diff --git a/src/test/java/com/arangodb/ArangoDriverBatchTest.java b/src/test/java/com/arangodb/ArangoDriverBatchTest.java deleted file mode 100644 index 1043dfcee..000000000 --- a/src/test/java/com/arangodb/ArangoDriverBatchTest.java +++ /dev/null @@ -1,193 +0,0 @@ -/* - * Copyright (C) 2012 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb; - -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; - -import java.util.List; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import com.arangodb.entity.AqlFunctionsEntity; -import com.arangodb.entity.BaseEntity; -import com.arangodb.entity.DefaultEntity; -import com.arangodb.entity.DocumentEntity; - -/** - * @author tamtam180 - kirscheless at gmail.com - * - */ -public class ArangoDriverBatchTest extends BaseTest { - - private static final String COLLECTION_NAME = "unit_test_batchTest"; - - @Before - public void before() throws ArangoException { - try { - driver.cancelBatchMode(); - } catch (final ArangoException e) { - } - try { - driver.deleteCollection(COLLECTION_NAME); - } catch (final ArangoException e) { - } - try { - driver.createCollection(COLLECTION_NAME); - } catch (final Exception e) { - e.printStackTrace(); - } - - } - - @After - public void after() { - try { - driver.cancelBatchMode(); - } catch (final ArangoException e) { - } - try { - driver.deleteCollection(COLLECTION_NAME); - } catch (final ArangoException e) { - } - } - - @Test - public void test_StartCancelExecuteBatchMode() throws ArangoException { - - driver.startBatchMode(); - String msg = ""; - try { - driver.startBatchMode(); - } catch (final ArangoException e) { - msg = e.getErrorMessage(); - } - assertThat(msg, is("BatchMode is already active.")); - - driver.cancelBatchMode(); - msg = ""; - try { - driver.cancelBatchMode(); - } catch (final ArangoException e) { - msg = e.getErrorMessage(); - } - assertThat(msg, is("BatchMode is not active.")); - - msg = ""; - try { - driver.executeBatch(); - } catch (final ArangoException e) { - msg = e.getErrorMessage(); - } - assertThat(msg, is("BatchMode is not active.")); - - } - - @Test - public void test_execBatchMode() throws ArangoException { - - try { - driver.truncateCollection("_aqlfunctions"); - } catch (final Exception e) { - e.printStackTrace(); - } - - driver.startBatchMode(); - - BaseEntity res = driver.createAqlFunction("someNamespace::testCode", - "function (celsius) { return celsius * 2.8 + 32; }"); - - assertThat(res.getStatusCode(), is(206)); - assertThat(res.getRequestId(), is("request1")); - - res = driver.createAqlFunction("someNamespace::testC&&&&&&&&&&de", - "function (celsius) { return celsius * 2.8 + 32; }"); - - assertThat(res.getStatusCode(), is(206)); - assertThat(res.getRequestId(), is("request2")); - - res = driver.getAqlFunctions(null); - assertThat(res.getStatusCode(), is(206)); - assertThat(res.getRequestId(), is("request3")); - - for (int i = 0; i < 10; i++) { - final TestComplexEntity01 value = new TestComplexEntity01("user-" + i, "data:" + i, i); - res = driver.createDocument(COLLECTION_NAME, value, false); - - assertThat(res.getStatusCode(), is(206)); - assertThat(res.getRequestId(), is("request" + (4 + i))); - } - - driver.getDocuments(COLLECTION_NAME); - - driver.executeBatch(); - final DefaultEntity created = driver.getBatchResponseByRequestId("request1"); - assertThat(created.getStatusCode(), is(201)); - final AqlFunctionsEntity functions = driver.getBatchResponseByRequestId("request3"); - assertThat(functions.getStatusCode(), is(200)); - assertThat(String.valueOf(functions.getAqlFunctions().keySet().toArray()[0]), is("someNamespace::testCode")); - for (int i = 0; i < 10; i++) { - final DocumentEntity resultComplex = driver - .getBatchResponseByRequestId("request" + (4 + i)); - assertThat(resultComplex.getStatusCode(), is(202)); - } - - final List documents = driver.getBatchResponseByRequestId("request14"); - assertThat(documents.size(), is(10)); - - try { - driver.truncateCollection("_aqlfunctions"); - } catch (final Exception e) { - e.printStackTrace(); - } - - } - - @Test - public void test_execBatchMode_twice() throws ArangoException { - - driver.startBatchMode(); - - BaseEntity res; - - for (int i = 0; i < 10; i++) { - final TestComplexEntity01 value = new TestComplexEntity01("user-" + i, "data:" + i, i); - res = driver.createDocument(COLLECTION_NAME, value, false); - assertThat(res.getRequestId(), is("request" + (i + 1))); - } - - driver.executeBatch(); - - assertThat(driver.getDocuments(COLLECTION_NAME).size(), is(10)); - - driver.startBatchMode(); - - for (int i = 20; i < 30; i++) { - final TestComplexEntity01 value = new TestComplexEntity01("user-" + i, "data:" + i, i); - res = driver.createDocument(COLLECTION_NAME, value, false); - assertThat(res.getRequestId(), is("request" + (i + 1 - 20))); - } - - driver.executeBatch(); - - assertThat(driver.getDocuments(COLLECTION_NAME).size(), is(20)); - - } - -} diff --git a/src/test/java/com/arangodb/ArangoDriverCacheTest.java b/src/test/java/com/arangodb/ArangoDriverCacheTest.java deleted file mode 100644 index f6462718f..000000000 --- a/src/test/java/com/arangodb/ArangoDriverCacheTest.java +++ /dev/null @@ -1,133 +0,0 @@ -package com.arangodb; - -import java.util.Map; - -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Ignore; -import org.junit.Test; - -import com.arangodb.entity.QueryCachePropertiesEntity; -import com.arangodb.entity.QueryCachePropertiesEntity.CacheMode; -import com.arangodb.util.AqlQueryOptions; -import com.arangodb.util.MapBuilder; - -/** - * @author Mark - mark@arangodb.com - * - */ -@Ignore -public class ArangoDriverCacheTest { - - private static final String COLLECTION_NAME = "unitTestCollection"; - private static final String DATABASE_NAME = "unitTestDatabase"; - private static ArangoConfigure configure; - private static ArangoDriver driver; - - @BeforeClass - public static void setup() throws ArangoException { - - configure = new ArangoConfigure(); - configure.init(); - driver = new ArangoDriver(configure); - - // create test database - try { - driver.createDatabase(DATABASE_NAME); - } catch (ArangoException e) { - } - driver.setDefaultDatabase(DATABASE_NAME); - - // create test collection - try { - driver.createCollection(COLLECTION_NAME); - } catch (final ArangoException e) { - } - driver.truncateCollection(COLLECTION_NAME); - - // create some test data - for (int i = 0; i < 1000000; i++) { - final TestEntity value = new TestEntity("user_" + (i % 10), "desc" + (i % 10), i); - driver.createDocument(COLLECTION_NAME, value, null); - } - - } - - @AfterClass - public static void shutdown() { - try { - driver.deleteDatabase(DATABASE_NAME); - } catch (final ArangoException e) { - } - configure.shutdown(); - } - - private AqlQueryOptions createAqlQueryOptions( - final Boolean count, - final Integer batchSize, - final Boolean fullCount, - final Boolean cache) { - return new AqlQueryOptions().setCount(count).setBatchSize(batchSize).setFullCount(fullCount).setCache(cache); - } - - @Test - public void test_withoutCache() throws ArangoException { - // set cache mode off - final QueryCachePropertiesEntity properties = new QueryCachePropertiesEntity(); - properties.setMode(CacheMode.off); - driver.setQueryCacheProperties(properties); - - final AqlQueryOptions aqlQueryOptions = createAqlQueryOptions(true, 1000, null, false); - - exceuteQuery(aqlQueryOptions); - } - - @Test - public void test_withCache() throws ArangoException { - // set cache mode on - final QueryCachePropertiesEntity properties = new QueryCachePropertiesEntity(); - properties.setMode(CacheMode.on); - driver.setQueryCacheProperties(properties); - - // set caching to true for the query - final AqlQueryOptions aqlQueryOptions = createAqlQueryOptions(true, 1000, null, true); - - exceuteQuery(aqlQueryOptions); - } - - private void exceuteQuery(AqlQueryOptions aqlQueryOptions) throws ArangoException { - - final String query = "FOR t IN " + COLLECTION_NAME + " FILTER t.age >= @age SORT t.age RETURN t"; - final Map bindVars = new MapBuilder().put("age", 90).get(); - - DocumentCursor rs = driver.executeDocumentQuery(query, bindVars, aqlQueryOptions, TestEntity.class); - // first time, the query isn't cached - Assert.assertEquals(false, rs.isCached()); - - final long start = System.currentTimeMillis(); - - // query the cached value - rs = driver.executeDocumentQuery(query, bindVars, aqlQueryOptions, TestEntity.class); - Assert.assertEquals(aqlQueryOptions.getCache(), rs.isCached()); - - // load all results - rs.asEntityList(); - - final long time = System.currentTimeMillis() - start; - System.out.println(time); - } - - private static class TestEntity { - private String user; - private String desc; - private Integer age; - - public TestEntity(String user, String desc, Integer age) { - super(); - this.user = user; - this.desc = desc; - this.age = age; - } - } -} diff --git a/src/test/java/com/arangodb/ArangoDriverCollectionTest.java b/src/test/java/com/arangodb/ArangoDriverCollectionTest.java deleted file mode 100644 index fc8f49409..000000000 --- a/src/test/java/com/arangodb/ArangoDriverCollectionTest.java +++ /dev/null @@ -1,694 +0,0 @@ -/* - * Copyright (C) 2012 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb; - -import static org.hamcrest.Matchers.anyOf; -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.Map; -import java.util.TreeSet; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.arangodb.entity.CollectionEntity; -import com.arangodb.entity.CollectionKeyOption; -import com.arangodb.entity.CollectionOptions; -import com.arangodb.entity.CollectionStatus; -import com.arangodb.entity.CollectionType; -import com.arangodb.entity.CollectionsEntity; -import com.arangodb.entity.DocumentEntity; -import com.arangodb.util.MapBuilder; - -/** - * UnitTest for REST API "collections" - * - * @author tamtam180 - kirscheless at gmail.com - * @author gschwab - * - */ -public class ArangoDriverCollectionTest extends BaseTest { - - private static Logger logger = LoggerFactory.getLogger(ArangoDriverCollectionTest.class); - - private final String collectionName = "unit_test_arango_001"; // 通常ケースで使うコレクション名 - private final String collectionName2 = "unit_test_arango_002"; - private final String collectionName404 = "unit_test_arango_404"; // 存在しないコレクション名 - - @Before - public void before() throws ArangoException { - - logger.debug("----------"); - - // 事前に消しておく - for (final String col : new String[] { collectionName, collectionName2, collectionName404 }) { - try { - driver.deleteCollection(col); - } catch (final ArangoException e) { - } - } - - logger.debug("--"); - - } - - @After - public void after() { - logger.debug("----------"); - } - - /** - * system test - * - * @throws ArangoException - */ - @Test - public void test_create_document_collection() throws ArangoException { - - // DocumentCollection - final CollectionEntity res1 = driver.createCollection(collectionName); - assertThat(res1, is(notNullValue())); - assertThat(res1.getCode(), is(200)); - assertThat(res1.getId(), is(notNullValue())); - assertThat(res1.getName(), is(collectionName)); - assertThat(res1.getWaitForSync(), is(false)); - assertThat(res1.getIsVolatile(), is(false)); - assertThat(res1.getIsSystem(), is(false)); - assertThat(res1.getStatus(), is(CollectionStatus.LOADED)); - assertThat(res1.getType(), is(CollectionType.DOCUMENT)); - - } - - /** - * system test - * - * @throws ArangoException - */ - @Test - // @Parameters - public void test_create_edge_collection() throws ArangoException { - final CollectionOptions collectionOptions = new CollectionOptions(); - collectionOptions.setType(CollectionType.EDGE); - final CollectionEntity res2 = driver.createCollection(collectionName, collectionOptions); - assertThat(res2, is(notNullValue())); - assertThat(res2.getCode(), is(200)); - assertThat(res2.getId(), is(notNullValue())); - assertThat(res2.getName(), is(collectionName)); - assertThat(res2.getWaitForSync(), is(false)); - assertThat(res2.getIsVolatile(), is(false)); - assertThat(res2.getIsSystem(), is(false)); - assertThat(res2.getStatus(), is(CollectionStatus.LOADED)); - assertThat(res2.getType(), is(CollectionType.EDGE)); - - } - - /** - * Test for InMemory Document Collection. - * - * @throws ArangoException - */ - @Test - public void test_create_inmemory_document_collection() throws ArangoException { - - final CollectionOptions collectionOptions = new CollectionOptions(); - collectionOptions.setIsVolatile(true); - final CollectionEntity res = driver.createCollection(collectionName, collectionOptions); - assertThat(res, is(notNullValue())); - assertThat(res.getCode(), is(200)); - assertThat(res.getId(), is(not(0L))); - assertThat(res.getName(), is(collectionName)); - assertThat(res.getWaitForSync(), is(false)); - assertThat(res.getIsVolatile(), is(true)); - assertThat(res.getIsSystem(), is(false)); - assertThat(res.getStatus(), is(CollectionStatus.LOADED)); - assertThat(res.getType(), is(CollectionType.DOCUMENT)); - - } - - @Test - public void test_create_with_options() throws ArangoException { - - final CollectionKeyOption keyOptions = new CollectionKeyOption(); - keyOptions.setType("autoincrement"); - keyOptions.setAllowUserKeys(true); - keyOptions.setIncrement(10); - keyOptions.setOffset(200); - - final CollectionOptions collectionOptions = new CollectionOptions(); - collectionOptions.setKeyOptions(keyOptions); - final CollectionEntity res = driver.createCollection(collectionName, collectionOptions); - assertThat(res, is(notNullValue())); - assertThat(res.getCode(), is(200)); - assertThat(res.getId(), is(not(0L))); - assertThat(res.getName(), is(collectionName)); - assertThat(res.getWaitForSync(), is(false)); - assertThat(res.getIsVolatile(), is(false)); - assertThat(res.getIsSystem(), is(false)); - assertThat(res.getStatus(), is(CollectionStatus.LOADED)); - assertThat(res.getType(), is(CollectionType.DOCUMENT)); - - // 現状では戻り値でとれないので別のAPIで確認する - // // TODO 現状では戻ってこないことを確認する - assertThat(res.getKeyOptions(), is(nullValue())); - - // 別のAPIで確認する - final CollectionEntity ent = driver.getCollectionProperties(collectionName); - final CollectionKeyOption opt = ent.getKeyOptions(); - assertThat(opt.isAllowUserKeys(), is(true)); - assertThat(opt.getType(), is("autoincrement")); - assertThat(opt.getIncrement(), is(10L)); - assertThat(opt.getOffset(), is(200L)); - - } - - @Test - public void test_create_no_compact() throws ArangoException { - - // DocumentCollection - final CollectionEntity res1 = driver.createCollection(collectionName); - assertThat(res1, is(notNullValue())); - assertThat(res1.getCode(), is(200)); - assertThat(res1.getId(), is(notNullValue())); - assertThat(res1.getName(), is(collectionName)); - assertThat(res1.getWaitForSync(), is(false)); - assertThat(res1.getIsVolatile(), is(false)); - assertThat(res1.getIsSystem(), is(false)); - assertThat(res1.getStatus(), is(CollectionStatus.LOADED)); - assertThat(res1.getType(), is(CollectionType.DOCUMENT)); - - final CollectionEntity prop = driver.getCollectionProperties(collectionName); - assertThat(prop.getCode(), is(200)); - assertThat(prop.getId(), is(res1.getId())); - assertThat(prop.getDoCompact(), is(true)); - - } - - /** - * 既に存在する場合の挙動確認。 - * - * @throws ArangoException - */ - @Test - public void test_create_dup() throws ArangoException { - - final CollectionEntity res1 = driver.createCollection(collectionName); - assertThat(res1, is(notNullValue())); - assertThat(res1.getCode(), is(200)); - assertThat(res1.getId(), is(not(0L))); - assertThat(res1.getName(), is(collectionName)); - assertThat(res1.getWaitForSync(), is(false)); - assertThat(res1.getIsVolatile(), is(false)); - assertThat(res1.getIsSystem(), is(false)); - assertThat(res1.getStatus(), is(CollectionStatus.LOADED)); - - { - try { - driver.createCollection(collectionName); - fail("ここに来てはダメー!"); - } catch (final ArangoException e) { - assertThat(e.getCode(), is(409)); - assertThat(e.getErrorNumber(), is(1207)); - } - } - - } - - @Test - public void test_getCollection_01() throws ArangoException { - - final CollectionEntity res1 = driver.createCollection(collectionName); - assertThat(res1.getCode(), is(200)); - - final long collectionId = res1.getId(); - - // 名前で取得 - final CollectionEntity entity2 = driver.getCollection(collectionName); - assertThat(entity2.getId(), is(collectionId)); - assertThat(entity2.getName(), is(collectionName)); - - // Type確認 - assertThat(entity2.getType(), is(CollectionType.DOCUMENT)); - - } - - /** - * 存在しないコレクションを取得する場合 - * - * @throws ArangoException - */ - @Test - public void test_getCollection_404() throws ArangoException { - - try { - driver.getCollection(collectionName404); - fail("ここに来てはダメー!"); - } catch (final ArangoException e) { - assertThat(e.getCode(), is(404)); - assertThat(e.getErrorNumber(), is(1203)); - } - - } - - @Test - public void test_getCollectionProperties_01() throws ArangoException { - - final CollectionEntity res1 = driver.createCollection(collectionName); - assertThat(res1.getCode(), is(200)); - - final CollectionEntity collection = driver.getCollectionProperties(collectionName); - assertThat(collection.getCode(), is(200)); - assertThat(collection.getId(), is(res1.getId())); - assertThat(collection.getName(), is(collectionName)); - assertThat(collection.getWaitForSync(), is(Boolean.FALSE)); - assertThat(collection.getJournalSize(), is(32L * 1024 * 1024)); // 32MB - assertThat(collection.getIsSystem(), is(false)); - assertThat(collection.getIsVolatile(), is(false)); - - assertThat(collection.getStatus(), is(CollectionStatus.LOADED)); // 3 - assertThat(collection.getType(), is(CollectionType.DOCUMENT)); // 2 - assertThat(collection.getDoCompact(), is(true)); - - assertThat(collection.getKeyOptions().getType(), is("traditional")); - assertThat(collection.getKeyOptions().isAllowUserKeys(), is(true)); - - // Countがないこと - assertThat(collection.getCount(), is(0L)); - - } - - /** - * 存在しないコレクションを指定した場合。 - * - * @throws ArangoException - */ - @Test - public void test_getCollectionProperties_404() throws ArangoException { - - try { - driver.getCollectionProperties(collectionName404); - fail("ここに来てはダメー!"); - } catch (final ArangoException e) { - assertThat(e.getCode(), is(404)); - assertThat(e.getErrorNumber(), is(1203)); - } - - } - - @Test - public void test_getCollectionCount_01() throws ArangoException { - - final CollectionEntity res1 = driver.createCollection(collectionName); - assertThat(res1.getCode(), is(200)); - - CollectionEntity collection = driver.getCollectionCount(collectionName); - assertThat(collection.getCode(), is(200)); - assertThat(collection.getId(), is(res1.getId())); - assertThat(collection.getName(), is(collectionName)); - assertThat(collection.getWaitForSync(), is(Boolean.FALSE)); - assertThat(collection.getJournalSize(), is(32L * 1024 * 1024)); // 32MB - assertThat(collection.getCount(), is(0L)); // 何も入っていないのでゼロ - // TODO type, status - - // 100個ほどドキュメントを入れてみる - for (int i = 0; i < 100; i++) { - final TestComplexEntity01 value = new TestComplexEntity01("test_user" + i, "tes user:" + i, 20 + i); - driver.createDocument(collectionName, value, true); - } - - // もっかいアクセスして10になっているか確認する - collection = driver.getCollectionCount(collectionName); - assertThat(collection.getCount(), is(100L)); - - } - - /** - * 存在しないコレクションを指定した場合。 - * - * @throws ArangoException - */ - @Test - public void test_getCollectionCount_404() throws ArangoException { - - try { - driver.getCollectionCount(collectionName404); - fail("ここに来てはダメー!"); - } catch (final ArangoException e) { - assertThat(e.getCode(), is(404)); - assertThat(e.getErrorNumber(), is(1203)); - } - - } - - @Test - public void test_getCollectionFigures_01() throws ArangoException { - - // コレクションを作る - final CollectionEntity res1 = driver.createCollection(collectionName); - assertThat(res1.getCode(), is(200)); - - // 100個ほどドキュメントを入れてみる - for (int i = 0; i < 100; i++) { - final TestComplexEntity01 value = new TestComplexEntity01("test_user" + i, "test user:" + i, 20 + i); - final DocumentEntity entity = driver.createDocument(collectionName, value, true); - // 1個消す - if (i == 50) { - driver.deleteDocument(entity.getDocumentHandle()); - } - } - - final CollectionEntity collection = driver.getCollectionFigures(collectionName); - assertThat(collection.getCode(), is(200)); - assertThat(collection.getId(), is(res1.getId())); - assertThat(collection.getName(), is(collectionName)); - assertThat(collection.getWaitForSync(), is(Boolean.FALSE)); - assertThat(collection.getJournalSize(), is(32L * 1024 * 1024)); // 32MB - assertThat(collection.getCount(), is(99L)); - assertThat(collection.getType(), is(CollectionType.DOCUMENT)); - assertThat(collection.getStatus(), is(CollectionStatus.LOADED)); - - // It is not possible to check the numbers - // assertThat(collection.getFigures().getAliveCount(), is(99L)); - // assertThat(collection.getFigures().getAliveSize(), is(not(0L))); - // assertThat(collection.getFigures().getDeadCount(), is(1L)); - // assertThat(collection.getFigures().getDeadSize(), is(not(0L))); - // assertThat(collection.getFigures().getJournalsCount(), is(1L)); - // assertThat(collection.getFigures().getJournalsFileSize(), - // is(not(0L))); - // assertThat(collection.getFigures().getShapefilesCount(), is(1L)); - // assertThat(collection.getFigures().getShapefilesFileSize(), - // is(not(0L))); - // assertThat(collection.getFigures().getShapesCount(), is(not(0L))); - // assertThat(collection.getFigures().getAttributesCount(), - // is(not(0L))); - - assertThat(collection.getFigures().getIndexesCount(), is(1L)); - assertThat(collection.getFigures().getIndexesSize(), is(not(0L))); - // assertThat(collection.getFigures().getLastTick(), is(1L)); - assertThat(collection.getFigures().getUncollectedLogfileEntries(), is(not(0L))); - - } - - /** - * 存在しないコレクションを指定した場合。 - * - * @throws ArangoException - */ - @Test - public void test_getCollectionFigures_404() throws ArangoException { - - try { - driver.getCollectionFigures(collectionName404); - fail("ここに来てはダメー!"); - } catch (final ArangoException e) { - assertThat(e.getCode(), is(404)); - assertThat(e.getErrorNumber(), is(1203)); - } - - } - - @Test - public void test_getCollectionChecksum() throws ArangoException { - - // create collection. - final CollectionEntity res1 = driver.createCollection(collectionName); - assertThat(res1.getCode(), is(200)); - - // checksum - final CollectionEntity entity = driver.getCollectionChecksum(collectionName, true, true); - assertThat(entity.getCode(), is(200)); - assertThat(entity.isError(), is(false)); - assertThat(entity.getChecksum(), is(0L)); // 同上 - - } - - @Test - public void test_getCollections() throws ArangoException { - - for (int i = 0; i < 10; i++) { - try { - driver.createCollection("unit_test_arango_" + (1000 + i)); - } catch (final ArangoException e) { - } - } - - final CollectionsEntity collections = driver.getCollections(); - assertThat(collections.getCode(), is(200)); - final Map map = collections.getNames(); - for (int i = 0; i < 10; i++) { - final String collectionName = "unit_test_arango_" + (1000 + i); - final CollectionEntity collection = map.get(collectionName); - // id, name, status - assertThat(collection, is(notNullValue())); - assertThat(collection.getId(), is(not(0L))); - assertThat(collection.getName(), is(collectionName)); - } - - // with exluceSystem parameter. - final int allColCount = collections.getCollections().size(); - final int sysExcludeCount = driver.getCollections(true).getCollections().size(); - assertThat(allColCount > sysExcludeCount, is(true)); - - } - - @Test - public void test_load_unload() throws ArangoException { - - // create - final CollectionEntity collection = driver.createCollection(collectionName); - assertThat(collection, is(notNullValue())); - assertThat(collection.getCode(), is(200)); - - // add document, for count parameter test. - driver.createDocument(collectionName, new MapBuilder("hoge", "fuga").put("fuga", "piyoko").get(), null); - - CollectionEntity collection1 = driver.unloadCollection(collectionName); - assertThat(collection1, is(notNullValue())); - assertThat(collection1.getCode(), is(200)); - assertThat(collection1.getCount(), is(0L)); - - assertThat(collection1.getStatus(), - anyOf(is(CollectionStatus.UNLOADED), is(CollectionStatus.IN_THE_PROCESS_OF_BEING_UNLOADED))); - - final CollectionEntity collection2 = driver.loadCollection(collectionName); - assertThat(collection2, is(notNullValue())); - assertThat(collection2.getCode(), is(200)); - assertThat(collection2.getStatus(), is(CollectionStatus.LOADED)); - assertThat(collection2.getCount(), is(1L)); - - // unload again, for count parameter test. - collection1 = driver.unloadCollection(collectionName); - assertThat(collection1, is(notNullValue())); - assertThat(collection1.getCode(), is(200)); - assertThat(collection1.getCount(), is(0L)); - - // with count parameter - final CollectionEntity col3 = driver.loadCollection(collectionName, false); - assertThat(col3, is(notNullValue())); - assertThat(col3.getCode(), is(200)); - assertThat(col3.getStatus(), is(CollectionStatus.LOADED)); - assertThat(col3.getCount(), is(0L)); // Not contains count in response. - - } - - @Test - public void test_load_404() throws ArangoException { - - try { - driver.loadCollection(collectionName404); - fail("ここに来てはダメー!"); - } catch (final ArangoException e) { - assertThat(e.getCode(), is(404)); - assertThat(e.getErrorNumber(), is(1203)); - } - - } - - @Test - public void test_unload_404() throws ArangoException { - - try { - driver.unloadCollection(collectionName404); - fail("ここに来てはダメー!"); - } catch (final ArangoException e) { - assertThat(e.getCode(), is(404)); - assertThat(e.getErrorNumber(), is(1203)); - } - - } - - @Test - public void test_truncate() throws ArangoException { - - final CollectionEntity collection = driver.createCollection(collectionName); - assertThat(collection, is(notNullValue())); - assertThat(collection.getCode(), is(200)); - - // 100個ほどドキュメントを入れてみる - for (int i = 0; i < 100; i++) { - final TestComplexEntity01 value = new TestComplexEntity01("test_user" + i, "test user:" + i, 20 + i); - assertThat(driver.createDocument(collectionName, value, true).getStatusCode(), is(201)); - } - // 100個入ったよね? - assertThat(driver.getCollectionCount(collectionName).getCount(), is(100L)); - - // 抹殺じゃー! - final CollectionEntity collection2 = driver.truncateCollection(collectionName); - assertThat(collection2, is(notNullValue())); - assertThat(collection2.getCode(), is(200)); - - // 0件になってるか確認 - assertThat(driver.getCollectionCount(collectionName).getCount(), is(0L)); - - } - - @Test - public void test_truncate_404() throws ArangoException { - - try { - driver.unloadCollection(collectionName404); - fail("ここに来てはダメー!"); - } catch (final ArangoException e) { - assertThat(e.getCode(), is(404)); - assertThat(e.getErrorNumber(), is(1203)); - } - - } - - @Test - public void test_setCollectionProperties() throws ArangoException { - - final CollectionEntity collection = driver.createCollection(collectionName); - assertThat(collection, is(notNullValue())); - assertThat(collection.getCode(), is(200)); - assertThat(collection.getWaitForSync(), is(Boolean.FALSE)); - - // Change waitForSync: false -> true - CollectionEntity col = driver.setCollectionProperties(collectionName, true, null); - assertThat(col.getCode(), is(200)); - assertThat(col.getWaitForSync(), is(Boolean.TRUE)); - - // Change journalSize: default -> 1234567Byte - col = driver.setCollectionProperties(collectionName, null, 1234567L); - assertThat(col.getCode(), is(200)); - assertThat(col.getJournalSize(), is(1234567L)); - - } - - @Test - public void test_setCollectionProperties_404() throws ArangoException { - - try { - driver.setCollectionProperties(collectionName404, true, null); - fail("ここに来てはダメー!"); - } catch (final ArangoException e) { - assertThat(e.getCode(), is(404)); - assertThat(e.getErrorNumber(), is(1203)); - } - - } - - @Test - public void test_delete() throws ArangoException { - - // コレクションを適当に10個作る - final TreeSet collectionNames = new TreeSet(); - for (int i = 0; i < 10; i++) { - try { - final String collectionName = "unit_test_arango_" + (1000 + i); - final CollectionEntity col = driver.createCollection(collectionName); - final long collectionId = col.getId(); - if (i == 5) { - // 1個だけ消す - final CollectionEntity res = driver.deleteCollection(collectionName); - assertThat(res.getCode(), is(200)); - assertThat(res.getId(), is(collectionId)); - } else { - collectionNames.add(col.getName()); - } - } catch (final ArangoException e) { - } - } - - // 残りの9個は残っていること - final Map collections = driver.getCollections().getNames(); - for (final String name : collectionNames) { - assertThat(collections.containsKey(name), is(true)); - } - - } - - @Test - public void test_delete_404() throws ArangoException { - - try { - driver.deleteCollection(collectionName404); - fail("ここに来てはダメー!"); - } catch (final ArangoException e) { - assertThat(e.getCode(), is(404)); - assertThat(e.getErrorNumber(), is(1203)); - } - - } - - @Test - public void test_rename_404() throws ArangoException { - - final CollectionEntity collection = driver.createCollection(collectionName); - assertThat(collection.getCode(), is(200)); - - try { - driver.renameCollection(collectionName404, collectionName); - fail("ここに来てはダメー!"); - } catch (final ArangoException e) { - assertThat(e.getCode(), is(404)); - assertThat(e.getErrorNumber(), is(1203)); - } - - } - - /** - * Rename先が既に存在する場合 - * - * @throws ArangoException - */ - @Test - public void test_rename_dup() throws ArangoException { - - final CollectionEntity collection1 = driver.createCollection(collectionName); - assertThat(collection1.getCode(), is(200)); - - final CollectionEntity collection2 = driver.createCollection(collectionName2); - assertThat(collection2.getCode(), is(200)); - - try { - driver.renameCollection(collectionName, collectionName2); - fail("ここに来てはダメー!"); - } catch (final ArangoException e) { - assertThat(e.getCode(), is(409)); - assertThat(e.getErrorNumber(), is(1207)); - } - - } -} diff --git a/src/test/java/com/arangodb/ArangoDriverCursorResultSetTest.java b/src/test/java/com/arangodb/ArangoDriverCursorResultSetTest.java deleted file mode 100644 index fef8e8352..000000000 --- a/src/test/java/com/arangodb/ArangoDriverCursorResultSetTest.java +++ /dev/null @@ -1,238 +0,0 @@ -/* - * Copyright (C) 2012 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb; - -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; - -import java.util.Iterator; -import java.util.Map; - -import org.junit.Before; -import org.junit.Test; - -import com.arangodb.entity.DocumentEntity; -import com.arangodb.util.AqlQueryOptions; -import com.arangodb.util.MapBuilder; - -/** - * @author tamtam180 - kirscheless at gmail.com - * - */ -public class ArangoDriverCursorResultSetTest extends BaseTest { - - @Before - public void setup() throws ArangoException { - - // Collectionを作る - final String collectionName = "unit_test_query_test"; - try { - driver.createCollection(collectionName); - } catch (final ArangoException e) { - } - driver.truncateCollection(collectionName); - - // テストデータを作る - for (int i = 0; i < 100; i++) { - final TestComplexEntity01 value = new TestComplexEntity01("user_" + (i % 10), "desc" + (i % 10), i); - driver.createDocument(collectionName, value, null); - } - - } - - @Test - public void test1() throws ArangoException { - - // String query = "SELECT t FROM unit_test_query_test t WHERE t.age >= - // @age@ order by t.age"; - final String query = "FOR t IN unit_test_query_test FILTER t.age >= @age SORT t.age RETURN t"; - final Map bindVars = new MapBuilder().put("age", 90).get(); - - // 全件とれる範囲 - final AqlQueryOptions aqlQueryOptions = new AqlQueryOptions(); - aqlQueryOptions.setBatchSize(20); - aqlQueryOptions.setCount(true); - final DocumentCursor rs = driver.executeDocumentQuery(query, bindVars, aqlQueryOptions, - TestComplexEntity01.class); - - int count = 0; - for (final TestComplexEntity01 obj : rs.asEntityList()) { - assertThat(obj.getAge(), is(90 + count)); - count++; - } - assertThat(count, is(10)); - - } - - @Test - public void test2() throws ArangoException { - - // String query = "SELECT t FROM unit_test_query_test t WHERE t.age >= - // @age@ order by t.age"; - final String query = "FOR t IN unit_test_query_test FILTER t.age >= @age SORT t.age RETURN t"; - final Map bindVars = new MapBuilder().put("age", 90).get(); - - final AqlQueryOptions aqlQueryOptions = new AqlQueryOptions(); - aqlQueryOptions.setBatchSize(10); - aqlQueryOptions.setCount(true); - final DocumentCursor rs = driver.executeDocumentQuery(query, bindVars, aqlQueryOptions, - TestComplexEntity01.class); - - int count = 0; - for (final TestComplexEntity01 obj : rs.asEntityList()) { - assertThat(obj.getAge(), is(90 + count)); - count++; - } - assertThat(count, is(10)); - - } - - @Test - public void test3() throws ArangoException { - - // String query = "SELECT t FROM unit_test_query_test t WHERE t.age >= - // @age@ order by t.age"; - final String query = "FOR t IN unit_test_query_test FILTER t.age >= @age SORT t.age RETURN t"; - final Map bindVars = new MapBuilder().put("age", 90).get(); - - final AqlQueryOptions aqlQueryOptions = new AqlQueryOptions(); - aqlQueryOptions.setBatchSize(5); - aqlQueryOptions.setCount(true); - final DocumentCursor rs = driver.executeDocumentQuery(query, bindVars, aqlQueryOptions, - TestComplexEntity01.class); - - int count = 0; - for (final TestComplexEntity01 obj : rs.asEntityList()) { - assertThat(obj.getAge(), is(90 + count)); - count++; - } - assertThat(count, is(10)); - - } - - @Test - public void test4() throws ArangoException { - - // String query = "SELECT t FROM unit_test_query_test t WHERE t.age >= - // @age@ order by t.age"; - final String query = "FOR t IN unit_test_query_test FILTER t.age >= @age SORT t.age RETURN t"; - final Map bindVars = new MapBuilder().put("age", 90).get(); - - final AqlQueryOptions aqlQueryOptions = new AqlQueryOptions(); - aqlQueryOptions.setBatchSize(3); - aqlQueryOptions.setCount(true); - final DocumentCursor rs = driver.executeDocumentQuery(query, bindVars, aqlQueryOptions, - TestComplexEntity01.class); - - int count = 0; - for (final TestComplexEntity01 obj : rs.asEntityList()) { - assertThat(obj.getAge(), is(90 + count)); - count++; - } - assertThat(count, is(10)); - - } - - @Test - public void test5() throws ArangoException { - - // String query = "SELECT t FROM unit_test_query_test t WHERE t.age >= - // @age@ order by t.age"; - final String query = "FOR t IN unit_test_query_test FILTER t.age >= @age SORT t.age RETURN t"; - final Map bindVars = new MapBuilder().put("age", 90).get(); - - final AqlQueryOptions aqlQueryOptions = new AqlQueryOptions(); - aqlQueryOptions.setBatchSize(1); - aqlQueryOptions.setCount(true); - final DocumentCursor rs = driver.executeDocumentQuery(query, bindVars, aqlQueryOptions, - TestComplexEntity01.class); - - int count = 0; - for (final TestComplexEntity01 obj : rs.asEntityList()) { - assertThat(obj.getAge(), is(90 + count)); - count++; - } - assertThat(count, is(10)); - - } - - /** - * Iterableを使わないバージョン。 - * - * @throws ArangoException - */ - @Test - public void test6() throws ArangoException { - - // String query = "SELECT t FROM unit_test_query_test t WHERE t.age >= - // @age@ order by t.age"; - final String query = "FOR t IN unit_test_query_test FILTER t.age >= @age SORT t.age RETURN t"; - final Map bindVars = new MapBuilder().put("age", 90).get(); - - final AqlQueryOptions aqlQueryOptions = new AqlQueryOptions(); - aqlQueryOptions.setBatchSize(2); - aqlQueryOptions.setCount(true); - final DocumentCursor rs = driver.executeDocumentQuery(query, bindVars, aqlQueryOptions, - TestComplexEntity01.class); - - int count = 0; - final Iterator> iterator = rs.iterator(); - while (iterator.hasNext()) { - final TestComplexEntity01 obj = iterator.next().getEntity(); - assertThat(obj.getAge(), is(90 + count)); - count++; - } - rs.close(); - assertThat(count, is(10)); - - } - - /** - * Iterableを使わないバージョン。 途中で終了。 - * - * @throws ArangoException - */ - @Test - public void test7() throws ArangoException { - - // String query = "SELECT t FROM unit_test_query_test t WHERE t.age >= - // @age@ order by t.age"; - final String query = "FOR t IN unit_test_query_test FILTER t.age >= @age SORT t.age RETURN t"; - final Map bindVars = new MapBuilder().put("age", 90).get(); - - final AqlQueryOptions aqlQueryOptions = new AqlQueryOptions(); - aqlQueryOptions.setBatchSize(2); - aqlQueryOptions.setCount(true); - final DocumentCursor rs = driver.executeDocumentQuery(query, bindVars, aqlQueryOptions, - TestComplexEntity01.class); - - int count = 0; - final Iterator> iterator = rs.iterator(); - while (iterator.hasNext()) { - final TestComplexEntity01 obj = iterator.next().getEntity(); - assertThat(obj.getAge(), is(90 + count)); - count++; - if (count == 5) { - rs.close(); - break; - } - } - assertThat(count, is(5)); - - } - -} diff --git a/src/test/java/com/arangodb/ArangoDriverCursorTest.java b/src/test/java/com/arangodb/ArangoDriverCursorTest.java deleted file mode 100644 index 37eb9823c..000000000 --- a/src/test/java/com/arangodb/ArangoDriverCursorTest.java +++ /dev/null @@ -1,330 +0,0 @@ -/* - * Copyright (C) 2012 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb; - -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.hamcrest.core.StringStartsWith.startsWith; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThat; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import com.arangodb.entity.CursorEntity; -import com.arangodb.entity.WarningEntity; -import com.arangodb.util.AqlQueryOptions; -import com.arangodb.util.MapBuilder; - -/** - * @author tamtam180 - kirscheless at gmail.com - * @author mrbatista - */ -public class ArangoDriverCursorTest extends BaseTest { - - final static String collectionName = "unit_test_query_test"; - - @Before - public void setup() throws ArangoException { - try { - driver.createCollection(collectionName); - } catch (final ArangoException e) { - } - driver.truncateCollection(collectionName); - } - - @After - public void tearDown() { - try { - driver.deleteCollection(collectionName); - } catch (final ArangoException e) { - } - } - - @Test - public void test_validateQuery() throws ArangoException { - - final CursorEntity entity = driver.validateQuery( - // "SELECT t FROM unit_test_cursor t WHERE t.name == @name@ && t.age - // >= @age@" - "FOR t IN unit_test_cursor FILTER t.name == @name && t.age >= @age RETURN t"); - - assertThat(entity.getCode(), is(200)); - assertThat(entity.getBindVars().size(), is(2)); - assertFalse(entity.getBindVars().indexOf("name") == -1); - assertFalse(entity.getBindVars().indexOf("age") == -1); - - } - - @Test - public void test_validateQuery_400() throws ArangoException { - - // =じゃなくて==じゃないとダメ。文法間違いエラー - try { - driver.validateQuery( - // "SELECT t FROM unit_test_cursor t WHERE t.name = @name@" - "FOR t IN unit_test_cursor FILTER t.name = @name@"); - - } catch (final ArangoException e) { - assertThat(e.getCode(), is(400)); - assertThat(e.getErrorNumber(), is(1501)); - } - - } - - @Test - public void test_executeQuery() throws ArangoException { - // テストデータを作る - for (int i = 0; i < 100; i++) { - final TestComplexEntity01 value = new TestComplexEntity01("user_" + (i % 10), "desc" + (i % 10), i); - driver.createDocument(collectionName, value, null); - } - - // String query = - // "SELECT t FROM unit_test_query_test t WHERE t.age >= @age@"; - final String query = "FOR t IN unit_test_query_test FILTER t.age >= @age RETURN t"; - final Map bindVars = new MapBuilder().put("age", 90).get(); - - // 全件とれる範囲 - { - final AqlQueryOptions aqlQueryOptions = new AqlQueryOptions(); - aqlQueryOptions.setBatchSize(20); - aqlQueryOptions.setCount(true); - final DocumentCursor result = driver. executeDocumentQuery(query, - bindVars, aqlQueryOptions, TestComplexEntity01.class); - assertThat(result.asEntityList().size(), is(10)); - assertThat(result.getCount(), is(10)); - assertThat(result.hasMore(), is(false)); - } - - } - - @Test - public void test_executeQuery_2() throws ArangoException { - // テストデータを作る - for (int i = 0; i < 100; i++) { - final TestComplexEntity01 value = new TestComplexEntity01("user_" + (i % 10), "desc" + (i % 10), i); - driver.createDocument(collectionName, value, null); - } - - // String query = - // "SELECT t FROM unit_test_query_test t WHERE t.age >= @age@"; - final String query = "FOR t IN unit_test_query_test FILTER t.age >= @age RETURN t"; - final Map bindVars = new MapBuilder().put("age", 90).get(); - - // ちまちまとる範囲 - long cursorId; - { - final AqlQueryOptions aqlQueryOptions = new AqlQueryOptions(); - aqlQueryOptions.setBatchSize(3); - aqlQueryOptions.setCount(true); - final DocumentCursor result = driver.executeDocumentQuery(query, bindVars, - aqlQueryOptions, TestComplexEntity01.class); - assertThat(result.getCount(), is(10)); - assertThat(result.hasMore(), is(true)); - assertThat(result.getCursorId(), is(not(-1L))); - assertThat(result.getCursorId(), is(not(0L))); - - cursorId = result.getCursorId(); - } - - // 次のRoundTrip - { - final CursorEntity result = driver.continueQuery(cursorId, TestComplexEntity01.class); - assertThat(result.size(), is(3)); - assertThat(result.getCount(), is(10)); - assertThat(result.hasMore(), is(true)); - } - - // 次のRoundTrip - { - final CursorEntity result = driver.continueQuery(cursorId, TestComplexEntity01.class); - assertThat(result.size(), is(3)); - assertThat(result.getCount(), is(10)); - assertThat(result.hasMore(), is(true)); - } - - // 次のRoundTrip - { - final CursorEntity result = driver.continueQuery(cursorId, TestComplexEntity01.class); - assertThat(result.size(), is(1)); - assertThat(result.getCount(), is(10)); - assertThat(result.hasMore(), is(false)); - } - - // 削除 - { - driver.finishQuery(cursorId); - } - - } - - @Test - public void test_executeQueryFullCount() throws ArangoException { - // テストデータを作る - for (int i = 0; i < 100; i++) { - final TestComplexEntity01 value = new TestComplexEntity01("user_" + (i % 10), "desc" + (i % 10), i); - driver.createDocument(collectionName, value, null); - } - - // String query = - // "SELECT t FROM unit_test_query_test t WHERE t.age >= @age@"; - final String query = "FOR t IN unit_test_query_test FILTER t.age >= @age LIMIT 2 RETURN t"; - final Map bindVars = new MapBuilder().put("age", 10).get(); - - // 全件とれる範囲 - { - final AqlQueryOptions aqlQueryOptions = new AqlQueryOptions(); - aqlQueryOptions.setBatchSize(1); - aqlQueryOptions.setCount(true); - aqlQueryOptions.setFullCount(true); - final DocumentCursor result = driver. executeDocumentQuery(query, - bindVars, aqlQueryOptions, TestComplexEntity01.class); - assertThat(result.getCount(), is(2)); - assertThat(result.getFullCount(), is(90)); - assertThat(result.hasMore(), is(true)); - } - - } - - @Test - public void test_executeQueryUniqueResult() throws ArangoException { - // テストデータを作る - for (int i = 0; i < 100; i++) { - final TestComplexEntity01 value = new TestComplexEntity01("user_" + (i % 10), "desc" + (i % 10), i); - driver.createDocument(collectionName, value, null); - } - - // String query = - // "SELECT t FROM unit_test_query_test t WHERE t.age >= @age@"; - String query = "FOR t IN unit_test_query_test FILTER t.age >= @age LIMIT 2 RETURN t"; - final Map bindVars = new MapBuilder().put("age", 10).get(); - - // 全件とれる範囲 - { - final AqlQueryOptions aqlQueryOptions = new AqlQueryOptions(); - aqlQueryOptions.setBatchSize(2); - aqlQueryOptions.setCount(true); - final DocumentCursor result = driver. executeDocumentQuery(query, - bindVars, aqlQueryOptions, TestComplexEntity01.class); - assertThat(result.asEntityList().size(), is(2)); - assertThat(result.getCount(), is(2)); - String msg = ""; - try { - result.getUniqueResult(); - } catch (final NonUniqueResultException e) { - msg = e.getMessage(); - } - assertThat(msg, startsWith("Query did not return a unique result:")); - } - - // String query = - // "SELECT t FROM unit_test_query_test t WHERE t.age >= @age@"; - query = "FOR t IN unit_test_query_test FILTER t.age == @age LIMIT 2 RETURN t"; - { - final AqlQueryOptions aqlQueryOptions = new AqlQueryOptions(); - aqlQueryOptions.setBatchSize(2); - aqlQueryOptions.setCount(true); - final DocumentCursor result = driver. executeDocumentQuery(query, - bindVars, aqlQueryOptions, TestComplexEntity01.class); - assertThat(result.asEntityList().size(), is(1)); - assertThat(result.getCount(), is(1)); - final TestComplexEntity01 entity = result.getUniqueResult().getEntity(); - assertThat(entity.getAge(), is(10)); - } - } - - @Test - public void test_warning() throws ArangoException { - driver.setDefaultDatabase(null); - final String query = "return _users + 1"; - final Map bindVars = new HashMap(); - final CursorResult cursor = driver.executeAqlQuery(query, bindVars, null, Long.class); - assertThat(cursor.hasWarning(), is(true)); - - final List warnings = cursor.getWarnings(); - assertThat(warnings.size(), is(1)); - } - - @Test - public void test_CursorResult_profile() throws ArangoException { - driver.setDefaultDatabase(null); - final Map bindVars = new HashMap(); - final AqlQueryOptions aqlQueryOptions = new AqlQueryOptions(); - { - // without profiling - aqlQueryOptions.setProfile(false); - final String query = "for p in _users return p._key"; - final CursorResult cursor = driver.executeAqlQuery(query, bindVars, aqlQueryOptions, String.class); - Map extra = cursor.getExtra(); - assertThat(extra, is(notNullValue())); - Object object = extra.get("profile"); - // extra.profile has to be null - assertThat(object, is(nullValue())); - } - driver.deleteQueryCache(); - { - // with profiling - aqlQueryOptions.setProfile(true); - final String query = "for p in _users return p._id"; - final CursorResult cursor = driver.executeAqlQuery(query, bindVars, aqlQueryOptions, String.class); - Map extra = cursor.getExtra(); - assertThat(extra, is(notNullValue())); - Object object = extra.get("profile"); - assertThat(object, is(notNullValue())); - } - } - - @Test - public void test_DocumentCursor_profile() throws ArangoException { - driver.setDefaultDatabase(null); - final Map bindVars = new HashMap(); - final AqlQueryOptions aqlQueryOptions = new AqlQueryOptions(); - { - // without profiling - aqlQueryOptions.setProfile(false); - final String query = "for p in _users return p._key"; - final DocumentCursor cursor = driver.executeDocumentQuery(query, bindVars, aqlQueryOptions, - String.class); - Map extra = cursor.getExtra(); - assertThat(extra, is(notNullValue())); - Object object = extra.get("profile"); - // extra.profile has to be null - assertThat(object, is(nullValue())); - } - driver.deleteQueryCache(); - { - // with profiling - aqlQueryOptions.setProfile(true); - final String query = "for p in _users return p._id"; - final DocumentCursor cursor = driver.executeDocumentQuery(query, bindVars, aqlQueryOptions, - String.class); - Map extra = cursor.getExtra(); - assertThat(extra, is(notNullValue())); - Object object = extra.get("profile"); - assertThat(object, is(notNullValue())); - } - } - -} diff --git a/src/test/java/com/arangodb/ArangoDriverDatabaseAndUserTest.java b/src/test/java/com/arangodb/ArangoDriverDatabaseAndUserTest.java deleted file mode 100644 index f44def846..000000000 --- a/src/test/java/com/arangodb/ArangoDriverDatabaseAndUserTest.java +++ /dev/null @@ -1,127 +0,0 @@ -/* - * Copyright (C) 2012,2013 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb; - -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; - -import java.util.Arrays; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import com.arangodb.entity.BooleanResultEntity; -import com.arangodb.entity.StringsResultEntity; -import com.arangodb.entity.UserEntity; -import com.arangodb.util.MapBuilder; - -/** - * @author tamtam180 - kirscheless at gmail.com - * - */ -public class ArangoDriverDatabaseAndUserTest { - - private static final String _SYSTEM = "_system"; - - private static final String USER1 = "user1"; - private static final String USER2 = "user2"; - private static final String USER3 = "user3"; - private static final String USER4 = "user4"; - - private static final String PASS1 = "pass1"; - private static final String PASS2 = "pass2"; - private static final String PASS3 = "pass3"; - private static final String PASS4 = "pass4"; - - private ArangoConfigure configure; - private ArangoDriver driver; - private static final String DATABASE = "db-1"; - - @Before - public void before() { - - configure = new ArangoConfigure(); - configure.init(); - driver = new ArangoDriver(configure); - - } - - @After - public void after() { - try { - driver.deleteDatabase(DATABASE); - } catch (final ArangoException e) { - } - for (String username : new String[] { USER1, USER2, USER3, USER4 }) { - try { - driver.deleteUser(username); - } catch (ArangoException e) { - } - } - configure.shutdown(); - } - - @Test - public void test_create_database_with_users_and_database_user() throws ArangoException { - - try { - driver.deleteDatabase(DATABASE); - } catch (final ArangoException e) { - } - - try { - driver.deleteDatabase("unitTestDatabase"); - } catch (final ArangoException e) { - } - - final BooleanResultEntity entity = driver.createDatabase(DATABASE, new UserEntity(USER1, PASS1, true, null), - new UserEntity(USER2, PASS2, false, null), - new UserEntity(USER3, PASS3, true, new MapBuilder().put("attr1", "value1").get()), - new UserEntity(USER4, PASS4, false, new MapBuilder().put("attr2", "value2").get())); - assertThat(entity.getResult(), is(true)); - driver.grantDatabaseAccess(USER1, _SYSTEM); - driver.grantDatabaseAccess(USER4, DATABASE); - - // change default db - driver.setDefaultDatabase(DATABASE); - - // user1 can access - configure.setUser(USER1); - configure.setPassword(PASS1); - final StringsResultEntity res2 = driver.getDatabases(true); - assertThat(res2.getResult(), is(Arrays.asList(_SYSTEM, DATABASE))); - - // user2 cannot access (inactive) - configure.setUser(USER2); - configure.setPassword(PASS2); - try { - driver.getUsers(); - fail(); - } catch (final ArangoException e) { - assertThat(e.isUnauthorized(), is(true)); - } - - configure.setUser("root"); - configure.setPassword(""); - - final StringsResultEntity res3 = driver.getDatabases(USER1, PASS1); - assertThat(res3.getResult(), is(Arrays.asList(_SYSTEM, DATABASE))); - } - -} diff --git a/src/test/java/com/arangodb/ArangoDriverDatabaseTest.java b/src/test/java/com/arangodb/ArangoDriverDatabaseTest.java deleted file mode 100644 index 047d0a10e..000000000 --- a/src/test/java/com/arangodb/ArangoDriverDatabaseTest.java +++ /dev/null @@ -1,226 +0,0 @@ -/* - * Copyright (C) 2012,2013 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb; - -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.not; -import static org.hamcrest.Matchers.notNullValue; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; - -import java.util.Collections; - -import org.junit.AfterClass; -import org.junit.Test; - -import com.arangodb.entity.BooleanResultEntity; -import com.arangodb.entity.DatabaseEntity; -import com.arangodb.entity.StringsResultEntity; - -/** - * @author tamtam180 - kirscheless at gmail.com - * - */ -public class ArangoDriverDatabaseTest extends BaseTest { - - private static final String DB_NAME = "abcdefghi1abcdefghi2abcdefghi3abcdefghi4abcdefghi5abcdefghi61234"; - private static final String[] DATABASES = new String[] { "db-1", "db_2", "db-_-3", "mydb", // other - // testcase - "mydb2", // other testcase - "repl_scenario_test1", // other test case - "unitTestDatabase", // other test case - }; - - @AfterClass - public static void _afterClass() { - try { - driver.deleteDatabase(DB_NAME); - } catch (final ArangoException e) { - } - for (final String database : DATABASES) { - try { - driver.deleteDatabase(database); - } catch (final ArangoException e) { - } - } - } - - @Test - public void test_invalid_dbname1() throws ArangoException { - try { - driver.createDatabase(null); - fail(); - } catch (final ArangoException e) { - assertThat(e.getMessage(), is("invalid format database:null")); - } - } - - @Test - public void test_invalid_dbname2() throws ArangoException { - try { - driver.createDatabase("0"); - fail(); - } catch (final ArangoException e) { - assertThat(e.getMessage(), is("invalid format database:0")); - } - } - - @Test - public void test_invalid_dbname3() throws ArangoException { - try { - driver.createDatabase("abcdefghi1abcdefghi2abcdefghi3abcdefghi4abcdefghi5abcdefghi612345"); // len=65 - fail(); - } catch (final ArangoException e) { - assertThat(e.getMessage(), - is("invalid format database:abcdefghi1abcdefghi2abcdefghi3abcdefghi4abcdefghi5abcdefghi612345")); - } - } - - @Test - public void test_invalid_dbname_for_delete() throws ArangoException { - try { - driver.deleteDatabase("abcdefghi1abcdefghi2abcdefghi3abcdefghi4abcdefghi5abcdefghi612345"); // len=65 - fail(); - } catch (final ArangoException e) { - assertThat(e.getMessage(), - is("invalid format database:abcdefghi1abcdefghi2abcdefghi3abcdefghi4abcdefghi5abcdefghi612345")); - } - } - - @Test - public void test_current_database() throws ArangoException { - - final DatabaseEntity entity = driver.getCurrentDatabase(); - assertThat(entity.isError(), is(false)); - assertThat(entity.getCode(), is(200)); - assertThat(entity.getName(), is("_system")); - assertThat(entity.getId(), is(notNullValue())); - assertThat(entity.getPath(), is(notNullValue())); - assertThat(entity.isSystem(), is(true)); - - } - - @Test - public void test_createDatabase() throws ArangoException { - - final String database = DB_NAME; - - try { - driver.deleteDatabase(database); - } catch (final ArangoException e) { - } - - final BooleanResultEntity entity = driver.createDatabase(database); // len=64 - assertThat(entity.getResult(), is(true)); - - } - - @Test - public void test_createDatabase_duplicate() throws ArangoException { - - final String database = DB_NAME; - - try { - driver.deleteDatabase(database); - } catch (final ArangoException e) { - } - - final BooleanResultEntity entity = driver.createDatabase(database); // len=64 - assertThat(entity.getResult(), is(true)); - - try { - driver.createDatabase(database); - fail(); - } catch (final ArangoException e) { - assertThat(e.getCode(), is(409)); - assertThat(e.getErrorNumber(), is(1207)); - } - - } - - @Test - public void test_delete() throws ArangoException { - - final String database = DB_NAME; - - try { - driver.deleteDatabase(database); - } catch (final ArangoException e) { - } - - BooleanResultEntity entity = driver.createDatabase(database); // len=64 - assertThat(entity.getResult(), is(true)); - assertThat(entity.getCode(), is(201)); - assertThat(entity.isError(), is(false)); - - entity = driver.deleteDatabase(database); - assertThat(entity.getResult(), is(true)); - assertThat(entity.getCode(), is(200)); - assertThat(entity.isError(), is(false)); - - } - - @Test - public void test_delete_404() throws ArangoException { - - final String database = DB_NAME; - - try { - driver.deleteDatabase(database); - } catch (final ArangoException e) { - } - - try { - driver.deleteDatabase(database); - fail(); - } catch (final ArangoException e) { - assertThat(e.getCode(), is(404)); - assertThat(e.getErrorNumber(), is(1228)); - } - - } - - @Test - public void test_get_databases() throws ArangoException { - - for (final String database : DATABASES) { - try { - driver.deleteDatabase(database); - } catch (final ArangoException e) { - } - try { - driver.createDatabase(database); - } catch (final ArangoException e) { - } - } - - final StringsResultEntity entity = driver.getDatabases(); - assertThat(entity.isError(), is(false)); - assertThat(entity.getCode(), is(200)); - - Collections.sort(entity.getResult()); - assertThat(entity.getResult().indexOf("_system"), not(-1)); - assertThat(entity.getResult().indexOf("db-1"), not(-1)); - assertThat(entity.getResult().indexOf("db_2"), not(-1)); - assertThat(entity.getResult().indexOf("db-_-3"), not(-1)); - assertThat(entity.getResult().indexOf("mydb"), not(-1)); - assertThat(entity.getResult().indexOf("mydb2"), not(-1)); - assertThat(entity.getResult().indexOf("repl_scenario_test1"), not(-1)); - assertThat(entity.getResult().indexOf("unitTestDatabase"), not(-1)); - } - -} diff --git a/src/test/java/com/arangodb/ArangoDriverDocumentCursorEntityTest.java b/src/test/java/com/arangodb/ArangoDriverDocumentCursorEntityTest.java deleted file mode 100644 index d2b1bc2c3..000000000 --- a/src/test/java/com/arangodb/ArangoDriverDocumentCursorEntityTest.java +++ /dev/null @@ -1,215 +0,0 @@ -/* - * Copyright (C) 2012 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb; - -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.not; -import static org.hamcrest.core.StringStartsWith.startsWith; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThat; - -import java.util.Map; - -import org.junit.Before; -import org.junit.Test; - -import com.arangodb.entity.CursorEntity; -import com.arangodb.entity.DocumentEntity; -import com.arangodb.util.MapBuilder; - -/** - * @author tamtam180 - kirscheless at gmail.com - * @author mrbatista - * @author a-brandt - * - */ -public class ArangoDriverDocumentCursorEntityTest extends BaseTest { - - private static final String COLLECTION_NAME = "unit_test_query_test"; - - @Before - public void before() throws ArangoException { - - // create test collection - try { - driver.createCollection(COLLECTION_NAME); - } catch (final ArangoException e) { - } - driver.truncateCollection(COLLECTION_NAME); - - // create some test data - for (int i = 0; i < 100; i++) { - final TestComplexEntity01 value = new TestComplexEntity01("user_" + (i % 10), "desc" + (i % 10), i); - driver.createDocument(COLLECTION_NAME, value, null); - } - - } - - @Test - public void test_validateQuery() throws ArangoException { - final CursorEntity entity = driver - .validateQuery("FOR t IN unit_test_cursor FILTER t.name == @name && t.age >= @age RETURN t"); - - assertThat(entity.getCode(), is(200)); - assertThat(entity.getBindVars().size(), is(2)); - assertFalse(entity.getBindVars().indexOf("name") == -1); - assertFalse(entity.getBindVars().indexOf("age") == -1); - } - - @Test - public void test_validateQuery_400_1() throws ArangoException { - - // syntax error, unexpected assignment near '= @name@' - - try { - driver.validateQuery("FOR t IN unit_test_cursor FILTER t.name = @name@"); - } catch (final ArangoException e) { - assertThat(e.getCode(), is(400)); - assertThat(e.getErrorNumber(), is(1501)); - } - - } - - @Test - public void test_executeQuery() throws ArangoException { - // String query = - // "SELECT t FROM unit_test_query_test t WHERE t.age >= @age@"; - final String query = "FOR t IN unit_test_query_test FILTER t.age >= @age RETURN t"; - final Map bindVars = new MapBuilder().put("age", 90).get(); - - // 全件とれる範囲 - { - final CursorEntity result = driver.executeCursorEntityQuery(query, bindVars, true, 20, false, - TestComplexEntity01.class); - assertThat(result.size(), is(10)); - assertThat(result.getCount(), is(10)); - assertThat(result.hasMore(), is(false)); - } - - } - - @Test - public void test_executeQuery_2() throws ArangoException { - // String query = - // "SELECT t FROM unit_test_query_test t WHERE t.age >= @age@"; - final String query = "FOR t IN unit_test_query_test FILTER t.age >= @age RETURN t"; - final Map bindVars = new MapBuilder().put("age", 90).get(); - - // ちまちまとる範囲 - long cursorId; - { - final CursorEntity result = driver.executeCursorEntityQuery(query, bindVars, true, 3, false, - DocumentEntity.class, TestComplexEntity01.class); - assertThat(result.size(), is(3)); - assertThat(result.getCount(), is(10)); - assertThat(result.hasMore(), is(true)); - assertThat(result.getCursorId(), is(not(-1L))); - assertThat(result.getCursorId(), is(not(0L))); - - cursorId = result.getCursorId(); - } - - // 次のRoundTrip - { - final CursorEntity result = driver.continueQuery(cursorId, DocumentEntity.class, - TestComplexEntity01.class); - - assertThat(result.size(), is(3)); - assertThat(result.getCount(), is(10)); - assertThat(result.hasMore(), is(true)); - } - - // 次のRoundTrip - { - final CursorEntity result = driver.continueQuery(cursorId, DocumentEntity.class, - TestComplexEntity01.class); - assertThat(result.size(), is(3)); - assertThat(result.getCount(), is(10)); - assertThat(result.hasMore(), is(true)); - } - - // 次のRoundTrip - { - final CursorEntity result = driver.continueQuery(cursorId, DocumentEntity.class, - TestComplexEntity01.class); - assertThat(result.size(), is(1)); - assertThat(result.getCount(), is(10)); - assertThat(result.hasMore(), is(false)); - } - - // 削除 - { - driver.finishQuery(cursorId); - } - - } - - @Test - public void test_executeQueryFullCount() throws ArangoException { - // String query = - // "SELECT t FROM unit_test_query_test t WHERE t.age >= @age@"; - final String query = "FOR t IN unit_test_query_test FILTER t.age >= @age LIMIT 2 RETURN t"; - final Map bindVars = new MapBuilder().put("age", 10).get(); - - // 全件とれる範囲 - { - final CursorEntity result = driver.executeCursorEntityQuery(query, bindVars, true, 1, true, - DocumentEntity.class, TestComplexEntity01.class); - assertThat(result.size(), is(1)); - assertThat(result.getCount(), is(2)); - assertThat(result.getFullCount(), is(90)); - assertThat(result.hasMore(), is(true)); - } - - } - - @Test - public void test_executeQueryUniqueResult() throws ArangoException { - - // String query = - // "SELECT t FROM unit_test_query_test t WHERE t.age >= @age@"; - String query = "FOR t IN unit_test_query_test FILTER t.age >= @age LIMIT 2 RETURN t"; - final Map bindVars = new MapBuilder().put("age", 10).get(); - - // 全件とれる範囲 - { - final CursorEntity result = driver.executeCursorEntityQuery(query, bindVars, true, 2, false, - DocumentEntity.class, TestComplexEntity01.class); - assertThat(result.size(), is(2)); - assertThat(result.getCount(), is(2)); - String msg = ""; - try { - result.getUniqueResult(); - } catch (final NonUniqueResultException e) { - msg = e.getMessage(); - } - assertThat(msg, startsWith("Query did not return a unique result:")); - } - - // String query = - // "SELECT t FROM unit_test_query_test t WHERE t.age >= @age@"; - query = "FOR t IN unit_test_query_test FILTER t.age == @age LIMIT 2 RETURN t"; - { - final CursorEntity> result = driver.executeCursorEntityQuery(query, - bindVars, true, 2, false, DocumentEntity.class, TestComplexEntity01.class); - assertThat(result.size(), is(1)); - assertThat(result.getCount(), is(1)); - final DocumentEntity uniqueResult = result.getUniqueResult(); - assertThat(uniqueResult.getEntity().getAge(), is(10)); - } - } -} diff --git a/src/test/java/com/arangodb/ArangoDriverDocumentCursorTest.java b/src/test/java/com/arangodb/ArangoDriverDocumentCursorTest.java deleted file mode 100644 index 3b7911e9e..000000000 --- a/src/test/java/com/arangodb/ArangoDriverDocumentCursorTest.java +++ /dev/null @@ -1,362 +0,0 @@ -/* - * Copyright (C) 2012 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb; - -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; - -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import org.junit.Before; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.arangodb.entity.DocumentEntity; -import com.arangodb.entity.QueryCachePropertiesEntity; -import com.arangodb.entity.QueryCachePropertiesEntity.CacheMode; -import com.arangodb.util.AqlQueryOptions; -import com.arangodb.util.MapBuilder; -import com.arangodb.util.TestUtils; - -/** - * @author tamtam180 - kirscheless at gmail.com - * @author a-brandt - * - */ -public class ArangoDriverDocumentCursorTest extends BaseTest { - - private static Logger logger = LoggerFactory.getLogger(ArangoDriverDocumentCursorTest.class); - - private static final String COLLECTION_NAME = "unit_test_query_test"; - - @Before - public void setup() throws ArangoException { - - // create test collection - try { - driver.createCollection(COLLECTION_NAME); - } catch (final ArangoException e) { - } - driver.truncateCollection(COLLECTION_NAME); - - // create some test data - for (int i = 0; i < 100; i++) { - final TestComplexEntity01 value = new TestComplexEntity01("user_" + (i % 10), "desc" + (i % 10), i); - driver.createDocument(COLLECTION_NAME, value, null); - } - - } - - private AqlQueryOptions getAqlQueryOptions(final Boolean count, final Integer batchSize, final Boolean fullCount) { - return new AqlQueryOptions().setCount(count).setBatchSize(batchSize).setFullCount(fullCount); - } - - @Test - public void test1_WithIterator() throws ArangoException { - - // String query = - // "SELECT t FROM unit_test_query_test t WHERE t.age >= @age@ order by - // t.age"; - final String query = "FOR t IN unit_test_query_test FILTER t.age >= @age SORT t.age RETURN t"; - final Map bindVars = new MapBuilder().put("age", 90).get(); - - // 全件とれる範囲 - final DocumentCursor rs = driver.executeDocumentQuery(query, bindVars, - getAqlQueryOptions(true, 20, null), TestComplexEntity01.class); - - int count = 0; - final Iterator> iterator = rs.iterator(); - - while (iterator.hasNext()) { - final DocumentEntity next = iterator.next(); - final TestComplexEntity01 obj = next.getEntity(); - assertThat(obj.getAge(), is(90 + count)); - count++; - } - assertThat(count, is(10)); - } - - @Test - public void test1_WithList() throws ArangoException { - - final String query = "FOR t IN unit_test_query_test FILTER t.age >= @age SORT t.age RETURN t"; - final Map bindVars = new MapBuilder().put("age", 90).get(); - - final DocumentCursor rs = driver.executeDocumentQuery(query, bindVars, - getAqlQueryOptions(true, 20, null), TestComplexEntity01.class); - - int count = 0; - for (final DocumentEntity documentEntity : rs.asList()) { - final TestComplexEntity01 obj = documentEntity.getEntity(); - assertThat(obj.getAge(), is(90 + count)); - count++; - } - assertThat(count, is(10)); - - } - - @Test - public void test2_BatchSize10() throws ArangoException { - - final String query = "FOR t IN unit_test_query_test FILTER t.age >= @age SORT t.age RETURN t"; - final Map bindVars = new MapBuilder().put("age", 90).get(); - - final DocumentCursor rs = driver.executeDocumentQuery(query, bindVars, - getAqlQueryOptions(true, 10, null), TestComplexEntity01.class); - - int count = 0; - for (final DocumentEntity documentEntity : rs.asList()) { - final TestComplexEntity01 obj = documentEntity.getEntity(); - assertThat(obj.getAge(), is(90 + count)); - count++; - } - assertThat(count, is(10)); - - } - - @Test - public void test3_BatchSize5() throws ArangoException { - - final String query = "FOR t IN unit_test_query_test FILTER t.age >= @age SORT t.age RETURN t"; - final Map bindVars = new MapBuilder().put("age", 90).get(); - - final DocumentCursor rs = driver.executeDocumentQuery(query, bindVars, - getAqlQueryOptions(true, 5, null), TestComplexEntity01.class); - - int count = 0; - for (final DocumentEntity documentEntity : rs.asList()) { - final TestComplexEntity01 obj = documentEntity.getEntity(); - assertThat(obj.getAge(), is(90 + count)); - count++; - } - assertThat(count, is(10)); - - } - - @Test - public void test_withCache() throws ArangoException { - if (isMinimumVersion(TestUtils.VERSION_2_7)) { - // start caching - final QueryCachePropertiesEntity properties = new QueryCachePropertiesEntity(); - properties.setMode(CacheMode.on); - driver.setQueryCacheProperties(properties); - - final String query = "FOR t IN unit_test_query_test FILTER t.age >= @age SORT t.age RETURN t"; - final Map bindVars = new MapBuilder().put("age", 90).get(); - - // set caching to true for the query - final AqlQueryOptions aqlQueryOptions = getAqlQueryOptions(true, 5, null); - aqlQueryOptions.setCache(true); - - // query - DocumentCursor rs = driver.executeDocumentQuery(query, bindVars, aqlQueryOptions, - TestComplexEntity01.class); - - // query the cached value - rs = driver.executeDocumentQuery(query, bindVars, aqlQueryOptions, TestComplexEntity01.class); - assertThat(rs.isCached(), is(true)); - } - } - - @Test - public void test4_withIterator() throws ArangoException { - - final String query = "FOR t IN unit_test_query_test FILTER t.age >= @age SORT t.age RETURN t"; - final Map bindVars = new MapBuilder().put("age", 90).get(); - - final DocumentCursor rs = driver.executeDocumentQuery(query, bindVars, - getAqlQueryOptions(true, 3, null), TestComplexEntity01.class); - - int count = 0; - final Iterator> iterator = rs.iterator(); - - while (iterator.hasNext()) { - final DocumentEntity next = iterator.next(); - final TestComplexEntity01 obj = next.getEntity(); - assertThat(obj.getAge(), is(90 + count)); - count++; - } - assertThat(count, is(10)); - - } - - @Test - public void test4_withList() throws ArangoException { - - final String query = "FOR t IN unit_test_query_test FILTER t.age >= @age SORT t.age RETURN t"; - final Map bindVars = new MapBuilder().put("age", 90).get(); - - final DocumentCursor rs = driver.executeDocumentQuery(query, bindVars, - getAqlQueryOptions(true, 3, null), TestComplexEntity01.class); - - int count = 0; - for (final DocumentEntity documentEntity : rs.asList()) { - final TestComplexEntity01 obj = documentEntity.getEntity(); - assertThat(obj.getAge(), is(90 + count)); - count++; - } - assertThat(count, is(10)); - - } - - @Test - public void test5_BatchSize1_asList() throws ArangoException { - - final String query = "FOR t IN unit_test_query_test FILTER t.age >= @age SORT t.age RETURN t"; - final Map bindVars = new MapBuilder().put("age", 90).get(); - - final DocumentCursor rs = driver.executeDocumentQuery(query, bindVars, - getAqlQueryOptions(true, 1, null), TestComplexEntity01.class); - - int count = 0; - for (final DocumentEntity documentEntity : rs.asList()) { - final TestComplexEntity01 obj = documentEntity.getEntity(); - assertThat(obj.getAge(), is(90 + count)); - count++; - } - assertThat(count, is(10)); - - } - - @Test - public void test6_getCount() throws ArangoException { - - final String query = "FOR t IN unit_test_query_test FILTER t.age >= @age SORT t.age RETURN t"; - final Map bindVars = new MapBuilder().put("age", 90).get(); - - // get only two results but calculate the total number of results - final DocumentCursor rs = driver.executeDocumentQuery(query, bindVars, - getAqlQueryOptions(true, 2, null), TestComplexEntity01.class); - - // test total number of results - assertThat(rs.getCount(), is(10)); - - int count = 0; - for (final DocumentEntity documentEntity : rs.asList()) { - final TestComplexEntity01 obj = documentEntity.getEntity(); - assertThat(obj.getAge(), is(90 + count)); - count++; - } - rs.close(); - assertThat(count, is(10)); - - } - - @Test - public void test7_closeCursor() throws ArangoException { - - final String query = "FOR t IN unit_test_query_test FILTER t.age >= @age SORT t.age RETURN t"; - final Map bindVars = new MapBuilder().put("age", 90).get(); - - final DocumentCursor rs = driver.executeDocumentQuery(query, bindVars, - getAqlQueryOptions(true, 2, null), TestComplexEntity01.class); - - int count = 0; - final Iterator> iterator = rs.iterator(); - - while (iterator.hasNext()) { - final DocumentEntity next = iterator.next(); - final TestComplexEntity01 obj = next.getEntity(); - assertThat(obj.getAge(), is(90 + count)); - count++; - if (count == 5) { - rs.close(); - break; - } - } - assertThat(count, is(5)); - - } - - @Test - public void test7_EntityCursor() throws ArangoException { - - final String query = "FOR t IN unit_test_query_test FILTER t.age >= @age SORT t.age RETURN t"; - final Map bindVars = new MapBuilder().put("age", 90).get(); - - final DocumentCursor documentCursor = driver.executeDocumentQuery(query, bindVars, - getAqlQueryOptions(true, 1, null), TestComplexEntity01.class); - - final Iterator entityIterator = documentCursor.entityIterator(); - - int count = 0; - while (entityIterator.hasNext()) { - final TestComplexEntity01 obj = entityIterator.next(); - assertThat(obj.getAge(), is(90 + count)); - count++; - } - assertThat(count, is(10)); - - } - - @Test - public void test8_CursorResult_as_Map() throws ArangoException { - - final String query = "FOR t IN unit_test_query_test FILTER t.age >= @age SORT t.age RETURN t"; - final Map bindVars = new MapBuilder().put("age", 90).get(); - - @SuppressWarnings("rawtypes") - final CursorResult cursor = driver.executeAqlQuery(query, bindVars, getAqlQueryOptions(true, 1, false), - Map.class); - - @SuppressWarnings("rawtypes") - final Iterator iterator = cursor.iterator(); - - int count = 0; - while (iterator.hasNext()) { - final Map obj = iterator.next(); - final Double i = (Double) obj.get("age"); - assertThat(i, is(90.0 + count)); - count++; - } - assertThat(count, is(10)); - - } - - @Test - public void test8_CursorResult_as_List() throws ArangoException { - - final String query = "FOR t IN unit_test_query_test FILTER t.age >= @age SORT t.age RETURN [t._key, t.user]"; - final Map bindVars = new MapBuilder().put("age", 90).get(); - - @SuppressWarnings("rawtypes") - final CursorResult cursor = driver.executeAqlQuery(query, bindVars, getAqlQueryOptions(true, 1, false), - List.class); - - @SuppressWarnings("rawtypes") - final Iterator iterator = cursor.iterator(); - - int count = 0; - while (iterator.hasNext()) { - final List list = iterator.next(); - final String user = "user_" + count; - final String get1 = list.get(1).toString(); - assertThat(get1, is(user)); - - for (final Object obj : list) { - logger.debug("value " + obj); - } - count++; - } - assertThat(count, is(10)); - - } - -} diff --git a/src/test/java/com/arangodb/ArangoDriverDocumentKeyTest.java b/src/test/java/com/arangodb/ArangoDriverDocumentKeyTest.java deleted file mode 100644 index 74ae20f7c..000000000 --- a/src/test/java/com/arangodb/ArangoDriverDocumentKeyTest.java +++ /dev/null @@ -1,256 +0,0 @@ -/* - * Copyright (C) 2012,2013 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb; - -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.notNullValue; -import static org.hamcrest.CoreMatchers.nullValue; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; - -import java.util.Map; - -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; - -import com.arangodb.annotations.DocumentKey; -import com.arangodb.entity.DocumentEntity; - -/** - * @author tamtam180 - kirscheless at gmail.com - * - */ -public class ArangoDriverDocumentKeyTest { - - private static ArangoConfigure configure; - private static ArangoDriver driver; - - @BeforeClass - public static void beforeClass() { - configure = new ArangoConfigure(); - configure.init(); - driver = new ArangoDriver(configure); - } - - @AfterClass - public static void afterClass() { - configure.shutdown(); - } - - @Before - public void before() throws ArangoException { - - try { - driver.deleteCollection("unit_test_arango_001"); - } catch (final ArangoException e) { - } - try { - driver.createCollection("unit_test_arango_001"); - } catch (final ArangoException e) { - } - - } - - private static class DocumentKeyTestEntity1 { - @DocumentKey - public String S1; - public String S2; - public Integer X; - } - - private static class DocumentKeyTestEntity2 { - @SuppressWarnings("unused") - public String S1; - @SuppressWarnings("unused") - public String S2; - @DocumentKey - public Integer X; - } - - @SuppressWarnings("rawtypes") - @Test - public void test_document_key_string() throws ArangoException { - - final DocumentKeyTestEntity1 obj = new DocumentKeyTestEntity1(); - obj.S1 = "s1"; - obj.S2 = "s2"; - obj.X = 123; - - // create - DocumentEntity doc = driver.createDocument("unit_test_arango_001", obj, null); - assertThat(doc.getDocumentKey(), is("s1")); - assertThat(doc.getDocumentHandle(), is("unit_test_arango_001/s1")); - assertThat(doc.getEntity(), is(notNullValue())); - assertThat(doc.getEntity(), is(obj)); - - // get - doc = driver.getDocument(doc.getDocumentHandle(), DocumentKeyTestEntity1.class); - assertThat(doc.getDocumentKey(), is("s1")); - assertThat(doc.getDocumentHandle(), is("unit_test_arango_001/s1")); - assertThat(doc.getEntity(), is(notNullValue())); - assertThat(doc.getEntity().S1, is("s1")); - assertThat(doc.getEntity().S2, is("s2")); - assertThat(doc.getEntity().X, is(123)); - - // get as map - final DocumentEntity doc2 = driver.getDocument(doc.getDocumentHandle(), Map.class); - assertThat(doc2.getEntity().get("s1"), is(nullValue())); // s1 is not - // contains. - assertThat((String) doc2.getEntity().get("_key"), is("s1")); - } - - @Test - public void test_document_key_integer() throws ArangoException { - - final DocumentKeyTestEntity2 obj = new DocumentKeyTestEntity2(); - obj.S1 = "s1"; - obj.S2 = "s2"; - obj.X = 123; - - // create - try { - driver.createDocument("unit_test_arango_001", obj, null); - fail(); - } catch (final ArangoException e) { - assertThat(e.getCode(), is(400)); - assertThat(e.getErrorNumber(), is(1221)); - assertThat(e.getErrorMessage(), is("invalid document key")); - } - - } - - @Test - public void test_document_create() throws ArangoException { - - final DocumentKeyTestEntity1 obj = new DocumentKeyTestEntity1(); - obj.S1 = "s1"; - obj.S2 = "s2"; - obj.X = 123; - - final DocumentEntity doc1 = driver.createDocument("unit_test_arango_001", "mykey1", obj, null); - assertThat(doc1.getStatusCode(), is(202)); - assertThat(doc1.getDocumentKey(), is("mykey1")); - - } - - @Test - public void test_document_replace() throws ArangoException { - - final DocumentKeyTestEntity1 obj = new DocumentKeyTestEntity1(); - obj.S1 = "s1"; - obj.S2 = "s2"; - obj.X = 123; - - final DocumentEntity doc1 = driver.createDocument("unit_test_arango_001", "mykey1", obj, null); - assertThat(doc1.getStatusCode(), is(202)); - assertThat(doc1.getDocumentKey(), is("mykey1")); - - // replace - obj.S1 = "s3"; - obj.X = 456; - final DocumentEntity doc2 = driver.replaceDocument("unit_test_arango_001", "mykey1", obj); - assertThat(doc1.getStatusCode(), is(202)); - assertThat(doc1.getDocumentKey(), is("mykey1")); - - final DocumentEntity doc3 = driver.getDocument(doc2.getDocumentHandle(), - DocumentKeyTestEntity1.class); - assertThat(doc3.getEntity().S1, is("mykey1")); - assertThat(doc3.getEntity().S2, is("s2")); - assertThat(doc3.getEntity().X, is(456)); - - } - - @Test - public void test_document_update() throws ArangoException { - - final DocumentKeyTestEntity1 obj = new DocumentKeyTestEntity1(); - obj.S1 = "s1"; - obj.S2 = "s2"; - obj.X = 123; - - final DocumentEntity doc1 = driver.createDocument("unit_test_arango_001", "mykey1", obj, null); - assertThat(doc1.getStatusCode(), is(202)); - assertThat(doc1.getDocumentKey(), is("mykey1")); - - // update - obj.S1 = "s3"; - obj.X = 456; - obj.S2 = null; - final DocumentEntity doc2 = driver.updateDocument("unit_test_arango_001", "mykey1", obj, false); - assertThat(doc1.getStatusCode(), is(202)); - assertThat(doc1.getDocumentKey(), is("mykey1")); - - final DocumentEntity doc3 = driver.getDocument(doc2.getDocumentHandle(), - DocumentKeyTestEntity1.class); - assertThat(doc3.getEntity().S1, is("mykey1")); - assertThat(doc3.getEntity().S2, is(nullValue())); - assertThat(doc3.getEntity().X, is(456)); - - } - - @Test - public void test_document_delete() throws ArangoException { - - final DocumentKeyTestEntity1 obj = new DocumentKeyTestEntity1(); - obj.S1 = "s1"; - obj.S2 = "s2"; - obj.X = 123; - - final DocumentEntity doc1 = driver.createDocument("unit_test_arango_001", "mykey1", obj, null); - assertThat(doc1.getStatusCode(), is(202)); - assertThat(doc1.getDocumentKey(), is("mykey1")); - - // delete - obj.S1 = "s3"; - obj.X = 456; - obj.S2 = null; - final DocumentEntity doc2 = driver.deleteDocument("unit_test_arango_001", "mykey1"); - assertThat(doc1.getStatusCode(), is(202)); - assertThat(doc1.getDocumentKey(), is("mykey1")); - - try { - driver.getDocument(doc2.getDocumentHandle(), DocumentKeyTestEntity1.class); - fail(); - } catch (final ArangoException e) { - assertThat(e.getCode(), is(404)); - assertThat(e.getErrorNumber(), is(1202)); - // assertThat(e.isNotFound(), is(true)); - } - - } - - @Test - public void test_document_check() throws ArangoException { - - final DocumentKeyTestEntity1 obj = new DocumentKeyTestEntity1(); - obj.S1 = "s1"; - obj.S2 = "s2"; - obj.X = 123; - - final DocumentEntity doc1 = driver.createDocument("unit_test_arango_001", "mykey1", obj, null); - assertThat(doc1.getStatusCode(), is(202)); - assertThat(doc1.getDocumentKey(), is("mykey1")); - - // check - final String rev = driver.checkDocument(doc1.getDocumentHandle()); - assertThat(rev, is(doc1.getDocumentRevision())); - - } - -} diff --git a/src/test/java/com/arangodb/ArangoDriverDocumentTest.java b/src/test/java/com/arangodb/ArangoDriverDocumentTest.java deleted file mode 100644 index 14a6cb237..000000000 --- a/src/test/java/com/arangodb/ArangoDriverDocumentTest.java +++ /dev/null @@ -1,702 +0,0 @@ -/* - * Copyright (C) 2012 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb; - -import static org.hamcrest.CoreMatchers.instanceOf; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.not; -import static org.hamcrest.CoreMatchers.notNullValue; -import static org.hamcrest.CoreMatchers.nullValue; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.util.Arrays; -import java.util.List; - -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.arangodb.entity.BaseDocument; -import com.arangodb.entity.CollectionEntity; -import com.arangodb.entity.DocumentEntity; -import com.arangodb.entity.EntityFactory; - -/** - * @author tamtam180 - kirscheless at gmail.com - */ -public class ArangoDriverDocumentTest extends BaseTest { - - private static Logger logger = LoggerFactory.getLogger(ArangoDriverCollectionTest.class); - - private final String collectionName = "unit_test_arango_001"; // 通常ケースで使うコレクション名 - private final String collectionName2 = "unit_test_arango_002"; - private final String collectionName404 = "unit_test_arango_404"; // 存在しないコレクション名 - - private TestInterfaceInstanceCreator testInstanceCreator; - - @Before - public void before() throws ArangoException { - - logger.debug("----------"); - - // 事前に消しておく - for (final String col : new String[] { collectionName, collectionName2, collectionName404 }) { - try { - driver.deleteCollection(col); - } catch (final ArangoException e) { - } - } - - // 1と2は作る - driver.createCollection(collectionName); - driver.createCollection(collectionName2); - - // configure Gson to use our instance creator whenever documents of - // TestInterface are requested - testInstanceCreator = new TestInterfaceInstanceCreator(); - EntityFactory.configure( - EntityFactory.getGsonBuilder().registerTypeAdapter(TestInterface.class, testInstanceCreator)); - - logger.debug("--"); - - } - - @After - public void after() { - // revert to default configuration - EntityFactory.configure(EntityFactory.getGsonBuilder()); - logger.debug("----------"); - } - - @Test - public void test_create_normal() throws ArangoException { - - // 適当にドキュメントを作る - final TestComplexEntity01 value = new TestComplexEntity01("user-" + 9999, "説明:" + 9999, 9999); - final DocumentEntity doc = driver.createDocument(collectionName, value, false); - - assertThat(doc.getDocumentKey(), is(notNullValue())); - assertThat(doc.getDocumentHandle(), is(collectionName + "/" + doc.getDocumentKey())); - assertThat(doc.getDocumentRevision(), is(notNullValue())); - assertThat(doc.getEntity(), is(notNullValue())); - - } - - @Test - public void test_create_normal_with_document_attributes() throws ArangoException { - - // 適当にドキュメントを作る - final TestComplexEntity03 value = new TestComplexEntity03("user-" + 9999, "説明:" + 9999, 9999); - final DocumentEntity doc = driver.createDocument(collectionName, value, false); - - assertThat(doc.getDocumentKey(), is(notNullValue())); - assertThat(doc.getDocumentHandle(), is(collectionName + "/" + doc.getDocumentKey())); - assertThat(doc.getDocumentRevision(), is(notNullValue())); - assertThat(doc.getEntity(), is(notNullValue())); - assertThat(doc.getEntity().getDocumentHandle(), is(notNullValue())); - assertThat(doc.getEntity().getDocumentKey(), is(notNullValue())); - assertThat(doc.getEntity().getDocumentRevision(), is(notNullValue())); - - } - - @Test - public void test_create_normal100() throws ArangoException { - - // 適当にドキュメントを作る - for (int i = 0; i < 100; i++) { - final TestComplexEntity01 value = new TestComplexEntity01("user-" + i, "説明:" + i, i); - driver.createDocument(collectionName, value, false); - } - - // 100個格納できていることを確認する - assertThat(driver.getCollectionCount(collectionName).getCount(), is(100L)); - - } - - @Test - public void test_create_sameobject() throws ArangoException { - // 適当にドキュメントを作る - for (int i = 0; i < 100; i++) { - final TestComplexEntity01 value = new TestComplexEntity01("user", "説明:", 10); - driver.createDocument(collectionName, value, true); - } - // 100個格納できていることを確認する - assertThat(driver.getCollectionCount(collectionName).getCount(), is(100L)); - } - - /** - * 存在しないコレクションに追加しようとするテスト - * - * @throws ArangoException - */ - @Test - public void test_create_404() throws ArangoException { - final TestComplexEntity01 value = new TestComplexEntity01("test-user", "test user", 22); - try { - driver.createDocument(collectionName404, value, true); - fail("no exception was thrown"); - } catch (final ArangoException e) { - assertThat(e.getCode(), is(404)); - assertThat(e.getErrorNumber(), is(1203)); - } - - } - - /** - * コレクションがない場合、コレクションを勝手に作ってくれることを確認。 - * - * @throws ArangoException - */ - @Test - public void test_create_404_insert() throws ArangoException { - - try { - driver.createCollection(collectionName404); - } catch (final ArangoException e) { - } - - final TestComplexEntity01 value = new TestComplexEntity01("test-user", "test user", 22); - // 存在しないコレクションに追加しようとする - final DocumentEntity res = driver.createDocument(collectionName404, value, true); - assertThat(res, is(notNullValue())); - final CollectionEntity col3 = driver.getCollection(collectionName404); - assertThat(col3, is(notNullValue())); - - assertThat(res.getDocumentHandle().startsWith(collectionName404 + "/"), is(true)); - assertThat(res.getDocumentRevision(), is(notNullValue())); - assertThat(res.getDocumentKey(), is(notNullValue())); - - } - - @Test - public void test_replace() throws ArangoException { - - final TestComplexEntity01 value = new TestComplexEntity01("test-user", "test user", 22); - - // Create Document - final DocumentEntity doc = driver.createDocument(collectionName, value, false); - assertThat(doc, is(notNullValue())); - value.setUser(null); - value.setDesc("UpdatedDescription"); - value.setAge(15); - - final String id = doc.getDocumentHandle(); - final String key = doc.getDocumentKey(); - final String rev = doc.getDocumentRevision(); - - final DocumentEntity doc2 = driver.replaceDocument(doc.getDocumentHandle(), value, null, - null); - - assertThat(doc2.getDocumentHandle(), is(id)); - assertThat(doc2.getDocumentKey(), is(key)); - assertThat(doc2.getDocumentRevision(), is(not(rev))); - final String rev2 = doc2.getDocumentRevision(); - - assertThat(doc2.getStatusCode(), is(202)); - // Get - final DocumentEntity doc3 = driver.getDocument(doc2.getDocumentHandle(), - TestComplexEntity01.class); - assertThat(doc3.getStatusCode(), is(200)); - assertThat(doc3.getEntity(), is(notNullValue())); - assertThat(doc3.getEntity().getUser(), is(nullValue())); - assertThat(doc3.getEntity().getDesc(), is("UpdatedDescription")); - assertThat(doc3.getEntity().getAge(), is(15)); - - assertThat(doc3.getDocumentHandle(), is(id)); - assertThat(doc3.getDocumentKey(), is(key)); - assertThat(doc3.getDocumentRevision(), is(not(rev))); - assertThat(doc3.getDocumentRevision(), is(rev2)); - } - - @Test - public void test_replace_with_document_attributes() throws ArangoException { - - final TestComplexEntity03 value = new TestComplexEntity03("test-user", "test user", 22); - - // Create Document - final DocumentEntity doc = driver.createDocument(collectionName, value, false); - assertThat(doc, is(notNullValue())); - value.setUser(null); - value.setDesc("UpdatedDescription"); - value.setAge(15); - - final String id = doc.getDocumentHandle(); - final String key = doc.getDocumentKey(); - final String rev = doc.getDocumentRevision(); - - final DocumentEntity doc2 = driver.replaceDocument(doc.getDocumentHandle(), value, null, - null); - TestComplexEntity03 ent = doc2.getEntity(); - - assertThat(ent.getDocumentHandle(), is(id)); - assertThat(ent.getDocumentKey(), is(key)); - assertThat(ent.getDocumentRevision(), is(not(rev))); - final String rev2 = ent.getDocumentRevision(); - - assertThat(doc2.getStatusCode(), is(202)); - // Get - final DocumentEntity doc3 = driver.getDocument(doc2.getDocumentHandle(), - TestComplexEntity03.class); - - ent = doc3.getEntity(); - - assertThat(ent.getDocumentHandle(), is(id)); - assertThat(ent.getDocumentKey(), is(key)); - assertThat(ent.getDocumentRevision(), is(not(rev))); - assertThat(ent.getDocumentRevision(), is(rev2)); - - assertThat(doc3.getStatusCode(), is(200)); - assertThat(doc3.getEntity(), is(notNullValue())); - assertThat(doc3.getEntity().getUser(), is(nullValue())); - assertThat(doc3.getEntity().getDesc(), is("UpdatedDescription")); - assertThat(doc3.getEntity().getAge(), is(15)); - } - - @Test - public void test_replace_404() throws ArangoException { - - final TestComplexEntity01 value = new TestComplexEntity01("test-user", "test user", 22); - // 存在しないコレクションに追加しようとする - try { - driver.replaceDocument(collectionName404, "1", value, null, null); - fail("no exception was thrown"); - } catch (final ArangoException e) { - assertThat(e.getCode(), is(404)); - assertThat(e.getErrorNumber(), is(1203)); - } - } - - @Test - public void test_replace_404_2() throws ArangoException { - final TestComplexEntity01 value = new TestComplexEntity01("test-user", "test user", 22); - // 存在するコレクションだが、ドキュメントが存在しない - try { - driver.replaceDocument(collectionName, "1", value, null, null); - fail("no exception was thrown"); - } catch (final ArangoException e) { - assertThat(e.getCode(), is(404)); - assertThat(e.getErrorNumber(), is(1202)); - } - } - - @Test - public void test_partial_update() throws ArangoException { - final TestComplexEntity01 value = new TestComplexEntity01("test-user", "test user", 22); - - // Create Document - final DocumentEntity doc = driver.createDocument(collectionName, value, false); - assertThat(doc, is(notNullValue())); - - // PartialUpdate - value.setUser(null); - value.setDesc("UpdatedDescription"); - value.setAge(15); - final DocumentEntity doc2 = driver.updateDocument(doc.getDocumentHandle(), value, null, - null, null); - assertThat(doc2.getStatusCode(), is(202)); - // Get - final DocumentEntity doc3 = driver.getDocument(doc2.getDocumentHandle(), - TestComplexEntity01.class); - assertThat(doc3.getStatusCode(), is(200)); - assertThat(doc3.getEntity(), is(notNullValue())); - assertThat(doc3.getEntity().getUser(), is("test-user")); // not update - assertThat(doc3.getEntity().getDesc(), is("UpdatedDescription")); - assertThat(doc3.getEntity().getAge(), is(15)); - final DocumentEntity doc4 = driver.updateDocument(doc.getDocumentHandle(), value, null, - null, false); - assertThat(doc4.getStatusCode(), is(202)); - final DocumentEntity doc5 = driver.getDocument(doc2.getDocumentHandle(), - TestComplexEntity01.class); - assertThat(doc5.getStatusCode(), is(200)); - assertThat(doc5.getEntity(), is(notNullValue())); - assertThat(doc5.getEntity().getUser(), is(nullValue())); // update - assertThat(doc5.getEntity().getDesc(), is("UpdatedDescription")); - assertThat(doc5.getEntity().getAge(), is(15)); - } - - @Test - public void test_partial_update_with_document_attributes() throws ArangoException { - final TestComplexEntity03 value = new TestComplexEntity03("test-user", "test user", 22); - - // Create Document - final DocumentEntity doc = driver.createDocument(collectionName, value, false); - assertThat(doc, is(notNullValue())); - - // PartialUpdate - value.setUser(null); - value.setDesc("UpdatedDescription"); - value.setAge(15); - final DocumentEntity doc2 = driver.updateDocument(doc.getDocumentHandle(), value, null, - null, null); - assertThat(doc2.getStatusCode(), is(202)); - - final TestComplexEntity03 en1 = doc2.getEntity(); - assertThat(en1.getDocumentHandle(), is(notNullValue())); - assertThat(en1.getDocumentKey(), is(notNullValue())); - final String rev1 = en1.getDocumentRevision(); - assertThat(rev1, is(notNullValue())); - - // Get - final DocumentEntity doc3 = driver.getDocument(doc2.getDocumentHandle(), - TestComplexEntity03.class); - assertThat(doc3.getStatusCode(), is(200)); - assertThat(doc3.getEntity(), is(notNullValue())); - assertThat(doc3.getEntity().getUser(), is("test-user")); // not update - assertThat(doc3.getEntity().getDesc(), is("UpdatedDescription")); - assertThat(doc3.getEntity().getAge(), is(15)); - assertThat(doc3.getDocumentRevision(), is(rev1)); - - final DocumentEntity doc4 = driver.updateDocument(doc.getDocumentHandle(), value, null, - null, false); - assertThat(doc4.getStatusCode(), is(202)); - final DocumentEntity doc5 = driver.getDocument(doc2.getDocumentHandle(), - TestComplexEntity03.class); - assertThat(doc5.getStatusCode(), is(200)); - assertThat(doc5.getEntity(), is(notNullValue())); - assertThat(doc5.getEntity().getUser(), is(nullValue())); // update - assertThat(doc5.getEntity().getDesc(), is("UpdatedDescription")); - assertThat(doc5.getEntity().getAge(), is(15)); - } - - @Test - public void test_getDocuments() throws ArangoException { - // create document - final DocumentEntity doc1 = driver.createDocument(collectionName, - new TestComplexEntity01("test-user1", "test-user1-desc", 21), false); - final DocumentEntity doc2 = driver.createDocument(collectionName, - new TestComplexEntity01("test-user2", "test-user2-desc", 22), false); - final DocumentEntity doc3 = driver.createDocument(collectionName, - new TestComplexEntity01("test-user3", "test-user3-desc", 23), false); - assertThat(doc1, is(notNullValue())); - assertThat(doc2, is(notNullValue())); - assertThat(doc3, is(notNullValue())); - - // get documents - final List documents = driver.getDocuments(collectionName); - assertEquals(3, documents.size()); - - final List list = Arrays.asList(doc1.getDocumentHandle(), doc2.getDocumentHandle(), - doc3.getDocumentHandle()); - - assertTrue(documents.containsAll(list)); - } - - @Test - public void test_getDocuments_handle() throws ArangoException { - - // create document - final DocumentEntity doc1 = driver.createDocument(collectionName, - new TestComplexEntity01("test-user1", "test-user1-desc", 21), false); - final DocumentEntity doc2 = driver.createDocument(collectionName, - new TestComplexEntity01("test-user2", "test-user2-desc", 22), false); - final DocumentEntity doc3 = driver.createDocument(collectionName, - new TestComplexEntity01("test-user3", "test-user3-desc", 23), false); - assertThat(doc1, is(notNullValue())); - assertThat(doc2, is(notNullValue())); - assertThat(doc3, is(notNullValue())); - - // get documents - final List documents = driver.getDocuments(collectionName); - assertEquals(3, documents.size()); - - final List list = Arrays.asList(doc1.getDocumentHandle(), doc2.getDocumentHandle(), - doc3.getDocumentHandle()); - - assertTrue(documents.containsAll(list)); - } - - @Test - public void test_get_document() throws ArangoException { - final TestComplexEntity01 value = new TestComplexEntity01("user-" + 9999, "説明:" + 9999, 9999); - final DocumentEntity doc = driver.createDocument(collectionName, value, false); - - assertThat(doc.getDocumentKey(), is(notNullValue())); - assertThat(doc.getDocumentHandle(), is(collectionName + "/" + doc.getDocumentKey())); - assertThat(doc.getDocumentRevision(), is(notNullValue())); - final DocumentEntity retVal = driver.getDocument(doc.getDocumentHandle(), - TestComplexEntity01.class); - assertThat(retVal.getDocumentHandle(), is(doc.getDocumentHandle())); - assertThat(retVal.getDocumentRevision(), is(doc.getDocumentRevision())); - assertThat(retVal.getDocumentKey(), is(doc.getDocumentKey())); - assertThat(retVal.getEntity(), instanceOf(TestComplexEntity01.class)); - assertThat(retVal.getEntity().getUser(), is("user-9999")); - assertThat(retVal.getEntity().getDesc(), is("説明:9999")); - assertThat(retVal.getEntity().getAge(), is(9999)); - } - - @Test - public void test_get_document_with_instance_creator() throws ArangoException { - // save an instance of TestInterfaceImpl with null as "name" - final DocumentEntity doc = driver.createDocument(collectionName, new TestInterfaceImpl(null), - false); - - assertThat(doc.getDocumentKey(), is(notNullValue())); - assertThat(doc.getDocumentHandle(), is(collectionName + "/" + doc.getDocumentKey())); - assertThat(doc.getDocumentRevision(), is(notNullValue())); - - // now we should get back an instance created with our configured - // InstanceCreator (with "name" already set) - final DocumentEntity retVal = driver.getDocument(doc.getDocumentHandle(), TestInterface.class); - assertThat(retVal.getDocumentHandle(), is(doc.getDocumentHandle())); - assertThat(retVal.getDocumentRevision(), is(doc.getDocumentRevision())); - assertThat(retVal.getDocumentKey(), is(doc.getDocumentKey())); - assertThat(retVal.getEntity(), instanceOf(TestInterface.class)); - assertThat(retVal.getEntity(), instanceOf(TestInterfaceImpl.class)); - assertThat(testInstanceCreator.getCounter(), is(1)); - assertThat(retVal.getEntity().getName(), is("name 0")); - } - - @Test - public void test_get_document_collection_not_found() throws ArangoException { - // Get - try { - driver.getDocument(collectionName404, "1", TestComplexEntity01.class); - fail(""); - } catch (final ArangoException e) { - assertThat(e.getCode(), is(404)); - assertThat(e.getErrorNumber(), is(1203)); - // collection not found - } - } - - @Test - public void test_get_document_doc_not_found() throws ArangoException { - // Get - try { - driver.getDocument(collectionName, "1", TestComplexEntity01.class); - fail(""); - } catch (final ArangoException e) { - assertThat(e.getCode(), is(404)); - assertThat(e.getErrorNumber(), is(1202)); - // document not found - } - } - - // TODO: If-None-Match, If-Matchヘッダを付けても挙動が変わらない。arango-1.4.0 - - // @Test - // public void test_get_document_none_match_eq() throws ArangoException { - // - // // create document - // TestComplexEntity01 value = new TestComplexEntity01("user-" + 9999, "説明:" - // + - // 9999, 9999); - // DocumentEntity doc = - // driver.createDocument(collectionName, value, null, false); - // - // assertThat(doc.getDocumentKey(), is(notNullValue())); - // assertThat(doc.getDocumentHandle(), is(collectionName + "/" + - // doc.getDocumentKey())); - // assertThat(doc.getDocumentRevision(), is(not(0L))); - // - // // Get - // DocumentEntity retVal = - // driver.getDocument(doc.getDocumentHandle(), TestComplexEntity01.class, - // doc.getDocumentRevision(), null); - // assertThat(retVal.getDocumentHandle(), is(doc.getDocumentHandle())); - // assertThat(retVal.getDocumentRevision(), is(doc.getDocumentRevision())); - // assertThat(retVal.getDocumentKey(), is(doc.getDocumentKey())); - // - // assertThat(retVal.getEntity(), instanceOf(TestComplexEntity01.class)); - // assertThat(retVal.getEntity().getUser(), is("user-9999")); - // assertThat(retVal.getEntity().getDesc(), is("説明:9999")); - // assertThat(retVal.getEntity().getAge(), is(9999)); - // - // } - // - // @Test - // public void test_get_document_none_match_ne() throws ArangoException { - // - // // create document - // TestComplexEntity01 value = new TestComplexEntity01("user-" + 9999, "説明:" - // + - // 9999, 9999); - // DocumentEntity doc = - // driver.createDocument(collectionName, value, null, false); - // - // assertThat(doc.getDocumentKey(), is(notNullValue())); - // assertThat(doc.getDocumentHandle(), is(collectionName + "/" + - // doc.getDocumentKey())); - // assertThat(doc.getDocumentRevision(), is(not(0L))); - // - // // Get - // DocumentEntity retVal = - // driver.getDocument(doc.getDocumentHandle(), TestComplexEntity01.class, - // doc.getDocumentRevision() + 1, null); - // assertThat(retVal.getDocumentHandle(), is(doc.getDocumentHandle())); - // assertThat(retVal.getDocumentRevision(), is(doc.getDocumentRevision())); - // assertThat(retVal.getDocumentKey(), is(doc.getDocumentKey())); - // - // assertThat(retVal.getEntity(), instanceOf(TestComplexEntity01.class)); - // assertThat(retVal.getEntity().getUser(), is("user-9999")); - // assertThat(retVal.getEntity().getDesc(), is("説明:9999")); - // assertThat(retVal.getEntity().getAge(), is(9999)); - // - // } - - /** - * Mapで取得した時に特別なキー(_id, _rev, _key)はEntityに入ってこないこと TODO: - * アノテーションで設定できるようにしようかな。。 - * - * @throws ArangoException - */ - @Test - public void test_get_as_map() throws ArangoException { - } - - @Test - public void test_checkDocument() throws ArangoException { - - final DocumentEntity doc = driver.createDocument(collectionName, - new TestComplexEntity02(1, 2, 3), null); - - final String etag = driver.checkDocument(doc.getDocumentHandle()); - assertThat(etag, is(doc.getDocumentRevision())); - } - - @Test - public void test_check_document_doc_not_found() throws ArangoException { - - driver.createDocument(collectionName, new TestComplexEntity02(1, 2, 3), null); - - try { - driver.checkDocument(collectionName, "1"); - fail(); - } catch (final ArangoException e) { - assertThat(e.getCode(), is(404)); - assertThat(e.getErrorNumber(), is(0)); - } - } - - @Test - public void test_check_document_doc_not_exists() throws ArangoException { - - driver.createDocument(collectionName, new TestComplexEntity02(1, 2, 3), null); - - final boolean b = driver.exists(collectionName, "1"); - - assertThat(b, is(false)); - } - - @Test - public void test_delete() throws ArangoException { - final DocumentEntity doc = driver.createDocument(collectionName, - new TestComplexEntity02(1, 2, 3)); - driver.deleteDocument(doc.getDocumentHandle()); - } - - @Test - public void test_delete_doc_not_found() throws ArangoException { - try { - driver.deleteDocument(collectionName, "1"); - fail(); - } catch (final ArangoException e) { - assertThat(e.getCode(), is(ErrorNums.ERROR_HTTP_NOT_FOUND)); - } - } - - @Test - public void test_BaseDocumentProperties() throws ArangoException { - // create a document - final BaseDocument myObject = new BaseDocument(); - myObject.setDocumentKey("myKey"); - myObject.addAttribute("a", "Foo"); - myObject.addAttribute("b", 42); - driver.createDocument(collectionName, myObject); - - // read a document - DocumentEntity myDocument = null; - BaseDocument myObject2 = null; - myDocument = driver.getDocument(collectionName, "myKey", BaseDocument.class); - myObject2 = myDocument.getEntity(); - - assertThat(myObject2.getProperties().get("a"), is(notNullValue())); - assertThat((String) myObject2.getProperties().get("a"), is("Foo")); - assertThat(myObject2.getProperties().get("b"), is(notNullValue())); - assertThat((Double) myObject2.getProperties().get("b"), is(42.0)); - assertThat(myObject2.getProperties().get("c"), is(nullValue())); - } - - @Test - public void createRawDocument() throws ArangoException { - final String jsonString = "{\"test\":123}"; - logger.debug("jsonString before: " + jsonString); - final DocumentEntity entity = driver.createDocumentRaw(collectionName, jsonString, false); - Assert.assertNotNull(entity); - Assert.assertNotNull(entity.getDocumentHandle()); - Assert.assertNotNull(entity.getDocumentKey()); - Assert.assertNotNull(entity.getDocumentRevision()); - final String documentHandle = entity.getDocumentHandle(); - - final String str = driver.getDocumentRaw(documentHandle, null, null); - Assert.assertNotNull(str); - Assert.assertTrue(str.contains("\"test\":123")); - // this string has "_id", "_key" and "_rev" attributes: - logger.debug("jsonString after: " + str); - } - - @Test - public void createRawDocumentWithKey() throws ArangoException { - final String key = "key1"; - final String jsonString = "{\"_key\":\"" + key + "\",\"test\":123}"; - logger.debug("jsonString before: " + jsonString); - final DocumentEntity entity = driver.createDocumentRaw(collectionName, jsonString, false); - Assert.assertNotNull(entity); - Assert.assertNotNull(entity.getDocumentHandle()); - Assert.assertNotNull(entity.getDocumentKey()); - Assert.assertNotNull(entity.getDocumentRevision()); - Assert.assertEquals(collectionName + "/" + key, entity.getDocumentHandle()); - Assert.assertEquals(key, entity.getDocumentKey()); - final String documentHandle = entity.getDocumentHandle(); - - final String str = driver.getDocumentRaw(documentHandle, null, null); - Assert.assertNotNull(str); - Assert.assertTrue(str.contains("\"test\":123")); - Assert.assertTrue(str.contains("\"_key\":\"" + key + "\"")); - Assert.assertTrue(str.contains("\"_id\":\"" + collectionName + "/" + key + "\"")); - logger.debug("jsonString after: " + str); - } - - @Test - public void createRawDocumentFails() throws ArangoException { - try { - final String jsonString = "no JSON"; - driver.createDocumentRaw(collectionName, jsonString, false); - fail(); - } catch (final ArangoException e) { - Assert.assertEquals(ErrorNums.ERROR_HTTP_BAD_PARAMETER, e.getCode()); - Assert.assertEquals(ErrorNums.ERROR_HTTP_CORRUPTED_JSON, e.getErrorNumber()); - } - } - - @Test - public void getRawDocumentFails() throws ArangoException { - try { - driver.getDocumentRaw(collectionName + "/notfound", null, null); - fail(); - } catch (final ArangoException e) { - Assert.assertEquals(ErrorNums.ERROR_HTTP_NOT_FOUND, e.getCode()); - Assert.assertEquals(ErrorNums.ERROR_HTTP_NOT_FOUND, e.getErrorNumber()); - } - } -} diff --git a/src/test/java/com/arangodb/ArangoDriverEdgeTest.java b/src/test/java/com/arangodb/ArangoDriverEdgeTest.java deleted file mode 100644 index 1c232049c..000000000 --- a/src/test/java/com/arangodb/ArangoDriverEdgeTest.java +++ /dev/null @@ -1,113 +0,0 @@ -package com.arangodb; - -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import com.arangodb.entity.BaseDocument; -import com.arangodb.entity.CollectionOptions; -import com.arangodb.entity.CollectionType; -import com.arangodb.entity.DocumentEntity; -import com.arangodb.entity.EdgeEntity; - -/** - * @author Mark - mark@arangodb.com - * - */ -public class ArangoDriverEdgeTest extends BaseTest { - - final String collectionName = "unit_test_edge_collection_EdgeTest"; - final String collectionName2 = "unit_test_normal_collection_EdgeTest"; - - @Before - public void before() throws ArangoException { - try { - driver.deleteCollection(collectionName); - } catch (final ArangoException e) { - } - try { - final CollectionOptions collectionOptions = new CollectionOptions(); - collectionOptions.setType(CollectionType.EDGE); - driver.createCollection(collectionName, collectionOptions); - } catch (final ArangoException e) { - } - try { - driver.deleteCollection(collectionName2); - } catch (final ArangoException e) { - } - try { - driver.createCollection(collectionName2); - } catch (final ArangoException e) { - } - } - - @After - public void after() throws ArangoException { - try { - driver.deleteCollection(collectionName); - } catch (final ArangoException e) { - } - try { - driver.deleteCollection(collectionName2); - } catch (final ArangoException e) { - } - } - - @Test - public void test_createDocument() throws ArangoException { - - final TestComplexEntity01 value = new TestComplexEntity01("user", "desc", 42); - final DocumentEntity fromDoc = driver.createDocument(collectionName2, value, true); - final DocumentEntity toDoc = driver.createDocument(collectionName2, value, true); - - final BaseDocument baseDocument = new BaseDocument(); - baseDocument.addAttribute(BaseDocument.FROM, fromDoc.getDocumentHandle()); - baseDocument.addAttribute(BaseDocument.TO, toDoc.getDocumentHandle()); - - final DocumentEntity doc = driver.createDocument(collectionName, baseDocument, true); - - Assert.assertNotNull(doc.getDocumentKey()); - Assert.assertEquals(collectionName + "/" + doc.getDocumentKey(), doc.getDocumentHandle()); - Assert.assertNotEquals(0L, doc.getDocumentRevision()); - Assert.assertEquals(fromDoc.getDocumentHandle(), doc.getEntity().getAttribute(BaseDocument.FROM)); - Assert.assertEquals(toDoc.getDocumentHandle(), doc.getEntity().getAttribute(BaseDocument.TO)); - - } - - @Test - public void test_createEdge() throws ArangoException { - - TestComplexEntity01 value = new TestComplexEntity01("user", "desc", 42); - DocumentEntity fromDoc = driver.createDocument(collectionName2, value, true); - DocumentEntity toDoc = driver.createDocument(collectionName2, value, true); - - EdgeEntity doc = driver.createEdge(collectionName, value, fromDoc.getDocumentHandle(), - toDoc.getDocumentHandle(), true); - - Assert.assertNotNull(doc.getDocumentKey()); - Assert.assertEquals(collectionName + "/" + doc.getDocumentKey(), doc.getDocumentHandle()); - Assert.assertNotEquals(0L, doc.getDocumentRevision()); - Assert.assertEquals(fromDoc.getDocumentHandle(), doc.getFromVertexHandle()); - Assert.assertEquals(toDoc.getDocumentHandle(), doc.getToVertexHandle()); - } - - @Test - public void test_createEdgeWithKey() throws ArangoException { - - final TestComplexEntity01 value = new TestComplexEntity01("user", "desc", 42); - final DocumentEntity fromDoc = driver.createDocument(collectionName2, value, true); - final DocumentEntity toDoc = driver.createDocument(collectionName2, value, true); - - final String documentKey = ArangoDriverEdgeTest.class.getSimpleName() + "_test_createEdgeWithKey"; - EdgeEntity doc = driver.createEdge(collectionName, documentKey, value, - fromDoc.getDocumentHandle(), toDoc.getDocumentHandle(), true); - - Assert.assertNotNull(doc.getDocumentKey()); - Assert.assertEquals(collectionName + "/" + documentKey, doc.getDocumentHandle()); - Assert.assertNotEquals(0L, doc.getDocumentRevision()); - Assert.assertEquals(fromDoc.getDocumentHandle(), doc.getFromVertexHandle()); - Assert.assertEquals(toDoc.getDocumentHandle(), doc.getToVertexHandle()); - } - -} \ No newline at end of file diff --git a/src/test/java/com/arangodb/ArangoDriverEndpointTest.java b/src/test/java/com/arangodb/ArangoDriverEndpointTest.java deleted file mode 100644 index ca312bc0c..000000000 --- a/src/test/java/com/arangodb/ArangoDriverEndpointTest.java +++ /dev/null @@ -1,155 +0,0 @@ -/* - * Copyright (C) 2012,2013 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb; - -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; - -import java.util.Arrays; -import java.util.List; -import java.util.TreeMap; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import com.arangodb.entity.BooleanResultEntity; -import com.arangodb.entity.Endpoint; - -/** - * @author tamtam180 - kirscheless at gmail.com - * - */ -public class ArangoDriverEndpointTest extends BaseTest { - - private static final String DB = "db"; - private static final String MYDB = "mydb"; - private static final String MYDB1 = "mydb1"; - private static final String MYDB2 = "mydb2"; - private static final String[] DB_S = new String[] { DB, MYDB, MYDB1, MYDB2 }; - - @Before - public void _before() { - for (final String db : DB_S) { - try { - driver.deleteDatabase(db); - } catch (final ArangoException e) { - } - try { - driver.createDatabase(db); - } catch (final ArangoException e) { - } - } - } - - @After - public void _after() { - for (final String db : DB_S) { - try { - driver.deleteDatabase(db); - } catch (final ArangoException e) { - } - } - } - - @Test - public void test_create_endpoint() throws ArangoException { - final BooleanResultEntity result = driver.createEndpoint("tcp://0.0.0.0:18529", DB); - assertThat(result.getResult(), is(true)); - } - - @Test - public void test_create_endpoint_dup() throws ArangoException { - - final BooleanResultEntity result1 = driver.createEndpoint("tcp://0.0.0.0:18529", DB); - assertThat(result1.getResult(), is(true)); - - final BooleanResultEntity result2 = driver.createEndpoint("tcp://0.0.0.0:18529", DB); - assertThat(result2.getResult(), is(true)); - - } - - @Test - public void test_get_endpoints() throws ArangoException { - - final BooleanResultEntity result1 = driver.createEndpoint("tcp://0.0.0.0:18530", DB); - assertThat(result1.getResult(), is(true)); - - final BooleanResultEntity result2 = driver.createEndpoint("tcp://0.0.0.0:18531", MYDB1, MYDB2, MYDB); - assertThat(result2.getResult(), is(true)); - - final List endpoints = driver.getEndpoints(); - // convert to Map - final TreeMap> endpointMap = new TreeMap>(); - for (final Endpoint ep : endpoints) { - endpointMap.put(ep.getEndpoint(), ep.getDatabases()); - } - - assertThat(endpointMap.get("tcp://0.0.0.0:18530"), is(Arrays.asList(DB))); - assertThat(endpointMap.get("tcp://0.0.0.0:18531"), is(Arrays.asList(MYDB1, MYDB2, MYDB))); - - } - - @Test - public void test_connect_new_endpoint() throws ArangoException { - - try { - driver.createDatabase(MYDB2); - } catch (final ArangoException e) { - } - - final BooleanResultEntity result2 = driver.createEndpoint("tcp://0.0.0.0:18531", MYDB1, MYDB2, MYDB); - assertThat(result2.getResult(), is(true)); - - final ArangoConfigure configure = new ArangoConfigure(); - configure.getArangoHost().setPort(18531); // change port - configure.init(); - try { - final ArangoDriver driver = new ArangoDriver(configure, MYDB2); - driver.getCollections(); - } finally { - configure.shutdown(); - } - - } - - @Test - public void test_delete() throws ArangoException { - - try { - driver.createDatabase(MYDB2); - } catch (final ArangoException e) { - } - - final BooleanResultEntity result2 = driver.createEndpoint("tcp://0.0.0.0:18531", MYDB1, MYDB2, MYDB); - assertThat(result2.getResult(), is(true)); - - final BooleanResultEntity result3 = driver.deleteEndpoint("tcp://0.0.0.0:18531"); - assertThat(result3.getResult(), is(true)); - - try { - driver.deleteEndpoint("tcp://0.0.0.0:18531"); - fail(); - } catch (final ArangoException e) { - assertThat(e.getCode(), is(404)); - assertThat(e.getErrorNumber(), is(1231)); - } - - } - -} diff --git a/src/test/java/com/arangodb/ArangoDriverGraphEdgeCreateTest.java b/src/test/java/com/arangodb/ArangoDriverGraphEdgeCreateTest.java deleted file mode 100644 index 2cd421c42..000000000 --- a/src/test/java/com/arangodb/ArangoDriverGraphEdgeCreateTest.java +++ /dev/null @@ -1,211 +0,0 @@ -/* - * Copyright (C) 2012,2013 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb; - -import static org.hamcrest.CoreMatchers.instanceOf; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.notNullValue; -import static org.hamcrest.CoreMatchers.startsWith; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; - -import org.junit.Test; - -import com.arangodb.entity.DocumentEntity; -import com.arangodb.entity.EdgeEntity; - -/** - * @author tamtam180 - kirscheless at gmail.com - * @author gschwab - * - */ -public class ArangoDriverGraphEdgeCreateTest extends BaseGraphTest { - - private final String graphName = "UnitTestGraph"; - private final String edgeCollectionName = "edge-1"; - - @Test - public void test_create_edge_no_key() throws ArangoException { - - final String edgeCollectionName = "edge-1"; - - driver.createGraph(this.graphName, this.createEdgeDefinitions(2, 0), this.createOrphanCollections(2), true); - final DocumentEntity v1 = driver.graphCreateVertex(this.graphName, "from1-1", - new TestComplexEntity01("v1-user", "desc1", 10), null); - final DocumentEntity v2 = driver.graphCreateVertex(this.graphName, "to1-1", - new TestComplexEntity01("v2-user", "desc2", 12), null); - - EdgeEntity edge = driver.graphCreateEdge(this.graphName, edgeCollectionName, null, v1.getDocumentHandle(), - v2.getDocumentHandle(), null, null); - - assertThat(edge.getCode(), is(202)); - assertThat(edge.isError(), is(false)); - - assertThat(edge.getDocumentHandle(), is(notNullValue())); - assertThat(edge.getDocumentRevision(), is(notNullValue())); - assertThat(edge.getDocumentKey(), is(notNullValue())); - edge = driver.graphGetEdge(this.graphName, this.edgeCollectionName, edge.getDocumentKey(), null); - assertThat(edge.getFromVertexHandle(), is(v1.getDocumentHandle())); - assertThat(edge.getToVertexHandle(), is(v2.getDocumentHandle())); - - } - - @Test - public void test_create_edge_key() throws ArangoException { - - driver.createGraph(this.graphName, this.createEdgeDefinitions(2, 0), this.createOrphanCollections(2), true); - final DocumentEntity v1 = driver.graphCreateVertex(this.graphName, "from1-1", - new TestComplexEntity01("v1-user", "desc1", 10), null); - final DocumentEntity v2 = driver.graphCreateVertex(this.graphName, "to1-1", - new TestComplexEntity01("v2-user", "desc2", 12), null); - - EdgeEntity edge = driver.graphCreateEdge(this.graphName, edgeCollectionName, "e1", v1.getDocumentHandle(), - v2.getDocumentHandle(), null, null); - - assertThat(edge.getCode(), is(202)); - assertThat(edge.isError(), is(false)); - - assertThat(edge.getDocumentHandle(), is(notNullValue())); - assertThat(edge.getDocumentRevision(), is(notNullValue())); - assertThat(edge.getDocumentKey(), is("e1")); - edge = driver.graphGetEdge(this.graphName, this.edgeCollectionName, edge.getDocumentKey(), null); - assertThat(edge.getFromVertexHandle(), is(v1.getDocumentHandle())); - assertThat(edge.getToVertexHandle(), is(v2.getDocumentHandle())); - - } - - @Test - public void test_create_edge_optional_value() throws ArangoException { - - final String edgeCollectionName = "edge-1"; - driver.createGraph(this.graphName, this.createEdgeDefinitions(2, 0), this.createOrphanCollections(2), true); - final DocumentEntity v1 = driver.graphCreateVertex(this.graphName, "from1-1", - new TestComplexEntity01("v1-user", "desc1", 10), null); - final DocumentEntity v2 = driver.graphCreateVertex(this.graphName, "to1-1", - new TestComplexEntity01("v2-user", "desc2", 12), null); - - EdgeEntity edge = driver.graphCreateEdge(this.graphName, edgeCollectionName, "e1", - v1.getDocumentHandle(), v2.getDocumentHandle(), new TestComplexEntity02(1, 2, 3), null); - - assertThat(edge.getCode(), is(202)); - assertThat(edge.isError(), is(false)); - - assertThat(edge.getDocumentHandle(), is(notNullValue())); - assertThat(edge.getDocumentRevision(), is(notNullValue())); - assertThat(edge.getDocumentKey(), is("e1")); - edge = driver.graphGetEdge(this.graphName, this.edgeCollectionName, edge.getDocumentKey(), - TestComplexEntity02.class); - assertThat(edge.getFromVertexHandle(), is(v1.getDocumentHandle())); - assertThat(edge.getToVertexHandle(), is(v2.getDocumentHandle())); - - assertThat(edge.getEntity(), instanceOf(TestComplexEntity02.class)); - assertThat(edge.getEntity().getX(), is(1)); - assertThat(edge.getEntity().getY(), is(2)); - assertThat(edge.getEntity().getZ(), is(3)); - - } - - @Test - public void test_create_edge_label() throws ArangoException { - - final String edgeCollectionName = "edge-1"; - driver.createGraph(this.graphName, this.createEdgeDefinitions(2, 0), this.createOrphanCollections(2), true); - - final DocumentEntity v1 = driver.graphCreateVertex(this.graphName, "from1-1", - new TestComplexEntity01("v1-user", "desc1", 10), null); - final DocumentEntity v2 = driver.graphCreateVertex(this.graphName, "to1-1", - new TestComplexEntity01("v2-user", "desc2", 12), null); - - EdgeEntity edge = driver.graphCreateEdge(this.graphName, edgeCollectionName, "e1", - v1.getDocumentHandle(), v2.getDocumentHandle(), new TestComplexEntity02(1, 2, 3), null); - - assertThat(edge.getCode(), is(202)); - assertThat(edge.isError(), is(false)); - - assertThat(edge.getDocumentHandle(), is(notNullValue())); - assertThat(edge.getDocumentRevision(), is(notNullValue())); - assertThat(edge.getDocumentKey(), is("e1")); - edge = driver.graphGetEdge(this.graphName, this.edgeCollectionName, edge.getDocumentKey(), - TestComplexEntity02.class); - assertThat(edge.getFromVertexHandle(), is(v1.getDocumentHandle())); - assertThat(edge.getToVertexHandle(), is(v2.getDocumentHandle())); - - assertThat(edge.getEntity(), instanceOf(TestComplexEntity02.class)); - assertThat(edge.getEntity().getX(), is(1)); - assertThat(edge.getEntity().getY(), is(2)); - assertThat(edge.getEntity().getZ(), is(3)); - - } - - @Test - public void test_create_edge_no_graph() throws ArangoException { - try { - driver.graphCreateEdge(this.graphName, "edge-1", null, "1", "2", null, null); - fail(); - } catch (final ArangoException e) { - assertThat(e.getCode(), is(404)); - assertThat(e.getErrorMessage(), startsWith("graph not found")); - } - - } - - @Test - public void test_create_edge_no_edge() throws ArangoException { - - final String edgeCollectionName = "edge-1"; - driver.createGraph(this.graphName, this.createEdgeDefinitions(2, 0), this.createOrphanCollections(2), true); - final DocumentEntity v1 = driver.graphCreateVertex(this.graphName, "from1-1", - new TestComplexEntity01("v1-user", "desc1", 10), null); - driver.graphCreateVertex(this.graphName, "to1-1", new TestComplexEntity01("v2-user", "desc2", 12), null); - - try { - driver.graphCreateEdge(this.graphName, edgeCollectionName, null, v1.getDocumentHandle(), "vol1/1", null, - null); - fail(); - } catch (final ArangoException e) { - assertThat(e.getCode(), is(400)); - assertThat(e.getErrorMessage(), startsWith("invalid edge")); - } - - } - - @Test - public void test_create_edge_waitForSync() throws ArangoException { - - final String edgeCollectionName = "edge-1"; - driver.createGraph(this.graphName, this.createEdgeDefinitions(2, 0), this.createOrphanCollections(2), true); - final DocumentEntity v1 = driver.graphCreateVertex(this.graphName, "from1-1", - new TestComplexEntity01("v1-user", "desc1", 10), null); - final DocumentEntity v2 = driver.graphCreateVertex(this.graphName, "to1-1", - new TestComplexEntity01("v2-user", "desc2", 12), null); - - EdgeEntity edge = driver.graphCreateEdge(this.graphName, edgeCollectionName, null, v1.getDocumentHandle(), - v2.getDocumentHandle(), null, false); - - assertThat(edge.getCode(), is(202)); - assertThat(edge.isError(), is(false)); - - assertThat(edge.getDocumentHandle(), is(notNullValue())); - assertThat(edge.getDocumentRevision(), is(notNullValue())); - assertThat(edge.getDocumentKey(), is(notNullValue())); - edge = driver.graphGetEdge(this.graphName, this.edgeCollectionName, edge.getDocumentKey(), null); - assertThat(edge.getFromVertexHandle(), is(v1.getDocumentHandle())); - assertThat(edge.getToVertexHandle(), is(v2.getDocumentHandle())); - - } - -} diff --git a/src/test/java/com/arangodb/ArangoDriverGraphEdgeDeleteTest.java b/src/test/java/com/arangodb/ArangoDriverGraphEdgeDeleteTest.java deleted file mode 100644 index 40b9e1ab1..000000000 --- a/src/test/java/com/arangodb/ArangoDriverGraphEdgeDeleteTest.java +++ /dev/null @@ -1,207 +0,0 @@ -/* - * Copyright (C) 2012,2013 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb; - -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.startsWith; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; - -import org.junit.Test; - -import com.arangodb.entity.DeletedEntity; -import com.arangodb.entity.DocumentEntity; -import com.arangodb.entity.EdgeEntity; - -/** - * @author tamtam180 - kirscheless at gmail.com - * @author gschwab - * - */ -public class ArangoDriverGraphEdgeDeleteTest extends BaseGraphTest { - - private final String graphName = "UnitTestGraph"; - private final String edgeCollectionName = "edge-1"; - - @Test - public void test_delete_edge() throws ArangoException { - - driver.createGraph(this.graphName, this.createEdgeDefinitions(2, 0), this.createOrphanCollections(2), true); - final DocumentEntity v1 = driver.graphCreateVertex(this.graphName, "from1-1", - new TestComplexEntity01("v1-user", "desc1", 10), null); - final DocumentEntity v2 = driver.graphCreateVertex(this.graphName, "to1-1", - new TestComplexEntity01("v2-user", "desc2", 12), null); - - final EdgeEntity edge = driver.graphCreateEdge(this.graphName, this.edgeCollectionName, null, - v1.getDocumentHandle(), v2.getDocumentHandle(), null, null); - assertThat(edge.getCode(), is(202)); - - final DeletedEntity deleted = driver.graphDeleteEdge(this.graphName, this.edgeCollectionName, - edge.getDocumentKey()); - assertThat(deleted.getCode(), is(202)); - assertThat(deleted.isError(), is(false)); - assertThat(deleted.getDeleted(), is(true)); - - } - - @Test - public void test_delete_edge_no_graph() throws ArangoException { - try { - driver.graphDeleteEdge("foo", "bar", null); - fail(); - } catch (final ArangoException e) { - assertThat(e.getCode(), is(404)); - assertThat(e.getErrorNumber(), is(1924)); - assertThat(e.getErrorMessage(), startsWith("graph not found")); - } - - } - - @Test - public void test_delete_edge_no_edge_collection() throws ArangoException { - - driver.createGraph(this.graphName, this.createEdgeDefinitions(2, 0), this.createOrphanCollections(2), true); - driver.graphCreateVertex(this.graphName, "from1-1", new TestComplexEntity01("v1-user", "desc1", 10), null); - driver.graphCreateVertex(this.graphName, "to1-1", new TestComplexEntity01("v2-user", "desc2", 12), null); - - try { - driver.graphDeleteEdge(this.graphName, "1", "2"); - fail(); - } catch (final ArangoException e) { - assertThat(e.getCode(), is(404)); - assertThat(e.getErrorNumber(), is(1203)); - assertThat(e.getErrorMessage(), startsWith("collection not found")); - } - - } - - @Test - public void test_delete_edge_waitForSync() throws ArangoException { - - driver.createGraph(this.graphName, this.createEdgeDefinitions(2, 0), this.createOrphanCollections(2), true); - final DocumentEntity v1 = driver.graphCreateVertex(this.graphName, "from1-1", - new TestComplexEntity01("v1-user", "desc1", 10), null); - final DocumentEntity v2 = driver.graphCreateVertex(this.graphName, "to1-1", - new TestComplexEntity01("v2-user", "desc2", 12), null); - - final EdgeEntity edge = driver.graphCreateEdge(this.graphName, this.edgeCollectionName, null, - v1.getDocumentHandle(), v2.getDocumentHandle(), null, false); - assertThat(edge.getCode(), is(202)); - assertThat(edge.isError(), is(false)); - - final DeletedEntity deleted = driver.graphDeleteEdge(this.graphName, this.edgeCollectionName, - edge.getDocumentKey(), false); - assertThat(deleted.getCode(), is(202)); - assertThat(deleted.getDeleted(), is(true)); - - } - - @Test - public void test_delete_edge_rev_eq() throws ArangoException { - - driver.createGraph(this.graphName, this.createEdgeDefinitions(2, 0), this.createOrphanCollections(2), true); - final DocumentEntity v1 = driver.graphCreateVertex(this.graphName, "from1-1", - new TestComplexEntity01("v1-user", "desc1", 10), null); - final DocumentEntity v2 = driver.graphCreateVertex(this.graphName, "to1-1", - new TestComplexEntity01("v2-user", "desc2", 12), null); - - final EdgeEntity edge = driver.graphCreateEdge(this.graphName, this.edgeCollectionName, null, - v1.getDocumentHandle(), v2.getDocumentHandle(), null, null); - assertThat(edge.getCode(), is(202)); - - final String rev = edge.getDocumentRevision(); - final DeletedEntity deleted = driver.graphDeleteEdge(this.graphName, this.edgeCollectionName, - edge.getDocumentKey(), null, rev, null); - assertThat(deleted.getCode(), is(202)); - assertThat(deleted.isError(), is(false)); - assertThat(deleted.getDeleted(), is(true)); - - } - - @Test - public void test_delete_edge_rev_ne() throws ArangoException { - - driver.createGraph(this.graphName, this.createEdgeDefinitions(2, 0), this.createOrphanCollections(2), true); - final DocumentEntity v1 = driver.graphCreateVertex(this.graphName, "from1-1", - new TestComplexEntity01("v1-user", "desc1", 10), null); - final DocumentEntity v2 = driver.graphCreateVertex(this.graphName, "to1-1", - new TestComplexEntity01("v2-user", "desc2", 12), null); - - final EdgeEntity edge = driver.graphCreateEdge(this.graphName, this.edgeCollectionName, null, - v1.getDocumentHandle(), v2.getDocumentHandle(), null, null); - assertThat(edge.getCode(), is(202)); - - try { - final String rev = edge.getDocumentRevision() + 1; - driver.graphDeleteEdge(this.graphName, this.edgeCollectionName, edge.getDocumentKey(), null, rev, null); - fail(); - } catch (final ArangoException e) { - assertThat(e.getCode(), is(412)); - assertThat(e.getErrorNumber(), is(1903)); - assertThat(e.getErrorMessage(), is("wrong revision")); - } - - } - - @Test - public void test_delete_edge_match_eq() throws ArangoException { - - driver.createGraph(this.graphName, this.createEdgeDefinitions(2, 0), this.createOrphanCollections(2), true); - final DocumentEntity v1 = driver.graphCreateVertex(this.graphName, "from1-1", - new TestComplexEntity01("v1-user", "desc1", 10), null); - final DocumentEntity v2 = driver.graphCreateVertex(this.graphName, "to1-1", - new TestComplexEntity01("v2-user", "desc2", 12), null); - - final EdgeEntity edge = driver.graphCreateEdge(this.graphName, this.edgeCollectionName, null, - v1.getDocumentHandle(), v2.getDocumentHandle(), null, null); - assertThat(edge.getCode(), is(202)); - - final String rev = edge.getDocumentRevision(); - final DeletedEntity deleted = driver.graphDeleteEdge(this.graphName, this.edgeCollectionName, - edge.getDocumentKey(), null, rev, null); - assertThat(deleted.getCode(), is(202)); - assertThat(deleted.isError(), is(false)); - assertThat(deleted.getDeleted(), is(true)); - - } - - @Test - public void test_delete_edge_match_ne() throws ArangoException { - - driver.createGraph(this.graphName, this.createEdgeDefinitions(2, 0), this.createOrphanCollections(2), true); - final DocumentEntity v1 = driver.graphCreateVertex(this.graphName, "from1-1", - new TestComplexEntity01("v1-user", "desc1", 10), null); - final DocumentEntity v2 = driver.graphCreateVertex(this.graphName, "to1-1", - new TestComplexEntity01("v2-user", "desc2", 12), null); - - final EdgeEntity edge = driver.graphCreateEdge(this.graphName, this.edgeCollectionName, null, - v1.getDocumentHandle(), v2.getDocumentHandle(), null, null); - assertThat(edge.getCode(), is(202)); - - try { - final String rev = edge.getDocumentRevision() + 1; - driver.graphDeleteEdge(this.graphName, this.edgeCollectionName, edge.getDocumentKey(), null, rev, null); - fail(); - } catch (final ArangoException e) { - assertThat(e.getCode(), is(412)); - assertThat(e.getErrorNumber(), is(1903)); - assertThat(e.getErrorMessage(), is("wrong revision")); - } - - } - -} diff --git a/src/test/java/com/arangodb/ArangoDriverGraphEdgeGetTest.java b/src/test/java/com/arangodb/ArangoDriverGraphEdgeGetTest.java deleted file mode 100644 index 0c8c2df51..000000000 --- a/src/test/java/com/arangodb/ArangoDriverGraphEdgeGetTest.java +++ /dev/null @@ -1,291 +0,0 @@ -/* - * Copyright (C) 2012,2013 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb; - -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.startsWith; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; - -import org.junit.Test; - -import com.arangodb.entity.EdgeEntity; -import com.arangodb.entity.marker.VertexEntity; - -/** - * @author tamtam180 - kirscheless at gmail.com - * - */ -public class ArangoDriverGraphEdgeGetTest extends BaseGraphTest { - - private final String graphName = "UnitTestGraph"; - private final String edgeCollectionName = "edge-1"; - - @Test - public void test_get_edge() throws ArangoException { - - driver.createGraph(this.graphName, this.createEdgeDefinitions(2, 0), this.createOrphanCollections(2), true); - final VertexEntity v1 = driver.graphCreateVertex(this.graphName, "from1-1", - new TestComplexEntity01("v1-user", "desc1", 10), null); - final VertexEntity v2 = driver.graphCreateVertex(this.graphName, "to1-1", - new TestComplexEntity01("v2-user", "desc2", 12), null); - - final EdgeEntity edge1 = driver.graphCreateEdge(this.graphName, this.edgeCollectionName, null, - v1.getDocumentHandle(), v2.getDocumentHandle(), null, null); - - final EdgeEntity edge2 = driver.graphGetEdge(this.graphName, this.edgeCollectionName, edge1.getDocumentKey(), - null); - assertThat(edge2.getCode(), is(200)); - assertThat(edge2.isError(), is(false)); - - assertThat(edge2.getDocumentHandle(), is(edge1.getDocumentHandle())); - assertThat(edge2.getDocumentRevision(), is(edge1.getDocumentRevision())); - assertThat(edge2.getDocumentKey(), is(edge1.getDocumentKey())); - assertThat(edge2.getFromVertexHandle(), is(v1.getDocumentHandle())); - assertThat(edge2.getToVertexHandle(), is(v2.getDocumentHandle())); - - } - - @Test - public void test_get_edge2() throws ArangoException { - - driver.createGraph(this.graphName, this.createEdgeDefinitions(2, 0), this.createOrphanCollections(2), true); - final VertexEntity v1 = driver.graphCreateVertex(this.graphName, "from1-1", - new TestComplexEntity01("v1-user", "desc1", 10), null); - final VertexEntity v2 = driver.graphCreateVertex(this.graphName, "to1-1", - new TestComplexEntity01("v2-user", "desc2", 12), null); - - final EdgeEntity edge1 = driver.graphCreateEdge(this.graphName, this.edgeCollectionName, null, - v1.getDocumentHandle(), v2.getDocumentHandle(), new TestComplexEntity02(1, 2, 3), null); - - final EdgeEntity edge2 = driver.graphGetEdge(this.graphName, this.edgeCollectionName, - edge1.getDocumentKey(), TestComplexEntity02.class); - assertThat(edge2.getCode(), is(200)); - assertThat(edge2.isError(), is(false)); - - assertThat(edge2.getDocumentHandle(), is(edge1.getDocumentHandle())); - assertThat(edge2.getDocumentRevision(), is(edge1.getDocumentRevision())); - assertThat(edge2.getDocumentKey(), is(edge1.getDocumentKey())); - assertThat(edge2.getFromVertexHandle(), is(v1.getDocumentHandle())); - assertThat(edge2.getToVertexHandle(), is(v2.getDocumentHandle())); - - assertThat(edge2.getEntity().getX(), is(1)); - assertThat(edge2.getEntity().getY(), is(2)); - assertThat(edge2.getEntity().getZ(), is(3)); - - } - - @Test - public void test_get_edge_graph_not_found() throws ArangoException { - - try { - driver.graphGetEdge("foo", "bar", "v1", null); - fail(); - } catch (final ArangoException e) { - assertThat(e.getCode(), is(404)); - assertThat(e.getErrorNumber(), is(1924)); - assertThat(e.getErrorMessage(), startsWith("graph not found")); - } - - } - - @Test - public void test_get_edge_edge_not_found() throws ArangoException { - - driver.createGraph(this.graphName, this.createEdgeDefinitions(2, 0), this.createOrphanCollections(2), true); - final VertexEntity v1 = driver.graphCreateVertex(this.graphName, "from1-1", - new TestComplexEntity01("v1-user", "desc1", 10), null); - final VertexEntity v2 = driver.graphCreateVertex(this.graphName, "to1-1", - new TestComplexEntity01("v2-user", "desc2", 12), null); - - driver.graphCreateEdge(this.graphName, this.edgeCollectionName, null, v1.getDocumentHandle(), - v2.getDocumentHandle(), null, null); - - try { - driver.graphGetEdge(this.graphName, this.edgeCollectionName, "xx", null); - fail(); - } catch (final ArangoException e) { - assertThat(e.getCode(), is(404)); - assertThat(e.getErrorNumber(), is(1202)); - assertThat(e.getErrorMessage(), startsWith("document not found")); - } - - } - - @Test - public void test_get_edge_rev_eq() throws ArangoException { - - driver.createGraph(this.graphName, this.createEdgeDefinitions(2, 0), this.createOrphanCollections(2), true); - final VertexEntity v1 = driver.graphCreateVertex(this.graphName, "from1-1", - new TestComplexEntity01("v1-user", "desc1", 10), null); - final VertexEntity v2 = driver.graphCreateVertex(this.graphName, "to1-1", - new TestComplexEntity01("v2-user", "desc2", 12), null); - - final EdgeEntity edge1 = driver.graphCreateEdge(this.graphName, this.edgeCollectionName, null, - v1.getDocumentHandle(), v2.getDocumentHandle(), new TestComplexEntity02(1, 2, 3), null); - - final String rev = edge1.getDocumentRevision(); - final EdgeEntity edge2 = driver.graphGetEdge(this.graphName, this.edgeCollectionName, - edge1.getDocumentKey(), TestComplexEntity02.class, rev, null); - assertThat(edge2.getCode(), is(200)); - assertThat(edge2.isError(), is(false)); - - assertThat(edge2.getDocumentHandle(), is(edge1.getDocumentHandle())); - assertThat(edge2.getDocumentRevision(), is(edge1.getDocumentRevision())); - assertThat(edge2.getDocumentKey(), is(edge1.getDocumentKey())); - assertThat(edge2.getFromVertexHandle(), is(v1.getDocumentHandle())); - assertThat(edge2.getToVertexHandle(), is(v2.getDocumentHandle())); - - assertThat(edge2.getEntity().getX(), is(1)); - assertThat(edge2.getEntity().getY(), is(2)); - assertThat(edge2.getEntity().getZ(), is(3)); - - } - - @Test - public void test_get_edge_rev_ne() throws ArangoException { - - driver.createGraph(this.graphName, this.createEdgeDefinitions(2, 0), this.createOrphanCollections(2), true); - final VertexEntity v1 = driver.graphCreateVertex(this.graphName, "from1-1", - new TestComplexEntity01("v1-user", "desc1", 10), null); - final VertexEntity v2 = driver.graphCreateVertex(this.graphName, "to1-1", - new TestComplexEntity01("v2-user", "desc2", 12), null); - - final EdgeEntity edge1 = driver.graphCreateEdge(this.graphName, this.edgeCollectionName, null, - v1.getDocumentHandle(), v2.getDocumentHandle(), new TestComplexEntity02(1, 2, 3), null); - - try { - final String rev = edge1.getDocumentRevision() + 1; - driver.graphGetEdge(this.graphName, this.edgeCollectionName, edge1.getDocumentKey(), - TestComplexEntity02.class, rev, null); - fail(); - } catch (final ArangoException e) { - assertThat(e.getCode(), is(412)); - assertThat(e.getErrorNumber(), is(1903)); - assertThat(e.getErrorMessage(), is("wrong revision")); - } - - } - - @Test - public void test_get_edge_nomatch_eq() throws ArangoException { - - driver.createGraph(this.graphName, this.createEdgeDefinitions(2, 0), this.createOrphanCollections(2), true); - final VertexEntity v1 = driver.graphCreateVertex(this.graphName, "from1-1", - new TestComplexEntity01("v1-user", "desc1", 10), null); - final VertexEntity v2 = driver.graphCreateVertex(this.graphName, "to1-1", - new TestComplexEntity01("v2-user", "desc2", 12), null); - - final EdgeEntity edge1 = driver.graphCreateEdge(this.graphName, this.edgeCollectionName, null, - v1.getDocumentHandle(), v2.getDocumentHandle(), new TestComplexEntity02(1, 2, 3), null); - - final String rev = edge1.getDocumentRevision(); - final EdgeEntity edge2 = driver.graphGetEdge(this.graphName, this.edgeCollectionName, - edge1.getDocumentKey(), TestComplexEntity02.class, null, rev); - assertThat(edge2.getStatusCode(), is(304)); - assertThat(edge2.isNotModified(), is(true)); - assertThat(edge2.isError(), is(false)); - - } - - @Test - public void test_get_edge_nomatch_ne() throws ArangoException { - - driver.createGraph(this.graphName, this.createEdgeDefinitions(2, 0), this.createOrphanCollections(2), true); - final VertexEntity v1 = driver.graphCreateVertex(this.graphName, "from1-1", - new TestComplexEntity01("v1-user", "desc1", 10), null); - final VertexEntity v2 = driver.graphCreateVertex(this.graphName, "to1-1", - new TestComplexEntity01("v2-user", "desc2", 12), null); - - final EdgeEntity edge1 = driver.graphCreateEdge(this.graphName, this.edgeCollectionName, null, - v1.getDocumentHandle(), v2.getDocumentHandle(), new TestComplexEntity02(1, 2, 3), null); - - final String rev = edge1.getDocumentRevision() + 1; - final EdgeEntity edge2 = driver.graphGetEdge(this.graphName, this.edgeCollectionName, - edge1.getDocumentKey(), TestComplexEntity02.class, null, rev); - - assertThat(edge2.getCode(), is(200)); - assertThat(edge2.isError(), is(false)); - - assertThat(edge2.getDocumentHandle(), is(edge1.getDocumentHandle())); - assertThat(edge2.getDocumentRevision(), is(edge1.getDocumentRevision())); - assertThat(edge2.getDocumentKey(), is(edge1.getDocumentKey())); - assertThat(edge2.getFromVertexHandle(), is(v1.getDocumentHandle())); - assertThat(edge2.getToVertexHandle(), is(v2.getDocumentHandle())); - - assertThat(edge2.getEntity().getX(), is(1)); - assertThat(edge2.getEntity().getY(), is(2)); - assertThat(edge2.getEntity().getZ(), is(3)); - - } - - @Test - public void test_get_edge_match_eq() throws ArangoException { - - driver.createGraph(this.graphName, this.createEdgeDefinitions(2, 0), this.createOrphanCollections(2), true); - final VertexEntity v1 = driver.graphCreateVertex(this.graphName, "from1-1", - new TestComplexEntity01("v1-user", "desc1", 10), null); - final VertexEntity v2 = driver.graphCreateVertex(this.graphName, "to1-1", - new TestComplexEntity01("v2-user", "desc2", 12), null); - - final EdgeEntity edge1 = driver.graphCreateEdge(this.graphName, this.edgeCollectionName, null, - v1.getDocumentHandle(), v2.getDocumentHandle(), new TestComplexEntity02(1, 2, 3), null); - - final String rev = edge1.getDocumentRevision(); - final EdgeEntity edge2 = driver.graphGetEdge(this.graphName, this.edgeCollectionName, - edge1.getDocumentKey(), TestComplexEntity02.class, rev, null); - assertThat(edge2.getCode(), is(200)); - assertThat(edge2.isError(), is(false)); - - assertThat(edge2.getDocumentHandle(), is(edge1.getDocumentHandle())); - assertThat(edge2.getDocumentRevision(), is(edge1.getDocumentRevision())); - assertThat(edge2.getDocumentKey(), is(edge1.getDocumentKey())); - assertThat(edge2.getFromVertexHandle(), is(v1.getDocumentHandle())); - assertThat(edge2.getToVertexHandle(), is(v2.getDocumentHandle())); - - assertThat(edge2.getEntity().getX(), is(1)); - assertThat(edge2.getEntity().getY(), is(2)); - assertThat(edge2.getEntity().getZ(), is(3)); - - } - - @Test - public void test_get_edge_match_ne() throws ArangoException { - - driver.createGraph(this.graphName, this.createEdgeDefinitions(2, 0), this.createOrphanCollections(2), true); - final VertexEntity v1 = driver.graphCreateVertex(this.graphName, "from1-1", - new TestComplexEntity01("v1-user", "desc1", 10), null); - final VertexEntity v2 = driver.graphCreateVertex(this.graphName, "to1-1", - new TestComplexEntity01("v2-user", "desc2", 12), null); - - final EdgeEntity edge1 = driver.graphCreateEdge(this.graphName, this.edgeCollectionName, null, - v1.getDocumentHandle(), v2.getDocumentHandle(), new TestComplexEntity02(1, 2, 3), null); - - try { - final String rev = edge1.getDocumentRevision() + 1; - driver.graphGetEdge(this.graphName, this.edgeCollectionName, edge1.getDocumentKey(), - TestComplexEntity02.class, rev, null); - fail(); - } catch (final ArangoException e) { - assertThat(e.getCode(), is(412)); - assertThat(e.getErrorNumber(), is(1903)); - assertThat(e.getErrorMessage(), is("wrong revision")); - } - - } - -} diff --git a/src/test/java/com/arangodb/ArangoDriverGraphEdgeReplaceTest.java b/src/test/java/com/arangodb/ArangoDriverGraphEdgeReplaceTest.java deleted file mode 100644 index 4c4ee39c0..000000000 --- a/src/test/java/com/arangodb/ArangoDriverGraphEdgeReplaceTest.java +++ /dev/null @@ -1,305 +0,0 @@ -/* - * Copyright (C) 2012,2013 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb; - -import static org.hamcrest.CoreMatchers.instanceOf; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.not; -import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; - -import org.junit.Test; - -import com.arangodb.entity.DocumentEntity; -import com.arangodb.entity.EdgeEntity; -import com.arangodb.entity.marker.VertexEntity; - -/** - * @author tamtam180 - kirscheless at gmail.com - * - */ -public class ArangoDriverGraphEdgeReplaceTest extends BaseGraphTest { - - private final String graphName = "UnitTestGraph"; - private final String edgeCollectionName = "edge-1"; - - @Test - public void test_replace_edge() throws ArangoException { - - driver.createGraph(this.graphName, this.createEdgeDefinitions(2, 0), this.createOrphanCollections(2), true); - final VertexEntity v1 = driver.graphCreateVertex(this.graphName, "from1-1", - new TestComplexEntity01("v1-user", "desc1", 10), null); - final VertexEntity v2 = driver.graphCreateVertex(this.graphName, "to1-1", - new TestComplexEntity01("v2-user", "desc2", 12), null); - driver.graphCreateVertex(this.graphName, "from1-1", new TestComplexEntity01("v3-user", "desc3", 14), null); - driver.graphCreateVertex(this.graphName, "to1-1", new TestComplexEntity01("v4-user", "desc4", 20), null); - - final EdgeEntity edge = driver.graphCreateEdge(this.graphName, this.edgeCollectionName, null, - v1.getDocumentHandle(), v2.getDocumentHandle(), new TestComplexEntity02(1, 2, 3), null); - assertThat(edge.getCode(), is(202)); - - EdgeEntity replacedEdge = driver.graphReplaceEdge(this.graphName, this.edgeCollectionName, - edge.getDocumentKey(), v1.getDocumentHandle(), v2.getDocumentHandle(), - new TestComplexEntity01("xx", "yy", 20)); - assertThat(replacedEdge.getCode(), is(202)); - assertThat(replacedEdge.isError(), is(false)); - assertThat(replacedEdge.getDocumentKey(), is(edge.getDocumentKey())); - assertThat(replacedEdge.getDocumentRevision(), is(not(edge.getDocumentRevision()))); - assertThat(replacedEdge.getDocumentHandle(), is(edge.getDocumentHandle())); - replacedEdge = driver.graphGetEdge(this.graphName, this.edgeCollectionName, replacedEdge.getDocumentKey(), - TestComplexEntity01.class); - assertThat(replacedEdge.getFromVertexHandle(), is(v1.getDocumentHandle())); - assertThat(replacedEdge.getToVertexHandle(), is(v2.getDocumentHandle())); - - assertThat(replacedEdge.getEntity(), instanceOf(TestComplexEntity01.class)); - assertThat(replacedEdge.getEntity().getUser(), is("xx")); - assertThat(replacedEdge.getEntity().getDesc(), is("yy")); - assertThat(replacedEdge.getEntity().getAge(), is(20)); - - } - - @Test - public void test_replace_edge_null() throws ArangoException { - - driver.createGraph(this.graphName, this.createEdgeDefinitions(2, 0), this.createOrphanCollections(2), true); - final DocumentEntity v1 = driver.graphCreateVertex(this.graphName, "from1-1", - new TestComplexEntity01("v1-user", "desc1", 10), null); - final VertexEntity v2 = driver.graphCreateVertex(this.graphName, "to1-1", - new TestComplexEntity01("v2-user", "desc2", 12), null); - driver.graphCreateVertex(this.graphName, "from1-1", new TestComplexEntity01("v3-user", "desc3", 14), null); - driver.graphCreateVertex(this.graphName, "to1-1", new TestComplexEntity01("v4-user", "desc4", 20), null); - - final EdgeEntity edge = driver.graphCreateEdge(this.graphName, this.edgeCollectionName, null, - v1.getDocumentHandle(), v2.getDocumentHandle(), new TestComplexEntity02(1, 2, 3), null); - assertThat(edge.getCode(), is(202)); - - EdgeEntity replacedEdge = driver.graphReplaceEdge(this.graphName, this.edgeCollectionName, - edge.getDocumentKey(), v1.getDocumentHandle(), v2.getDocumentHandle(), null); - assertThat(replacedEdge.getCode(), is(202)); - assertThat(replacedEdge.isError(), is(false)); - assertThat(replacedEdge.getDocumentKey(), is(edge.getDocumentKey())); - assertThat(replacedEdge.getDocumentRevision(), is(not(edge.getDocumentRevision()))); - assertThat(replacedEdge.getDocumentHandle(), is(edge.getDocumentHandle())); - - replacedEdge = driver.graphGetEdge(this.graphName, this.edgeCollectionName, replacedEdge.getDocumentKey(), - null); - - assertThat(replacedEdge.getFromVertexHandle(), is(v1.getDocumentHandle())); - assertThat(replacedEdge.getToVertexHandle(), is(v2.getDocumentHandle())); - assertThat(replacedEdge.getEntity(), is(nullValue())); - - } - - @Test - public void test_replace_edge_waitForSync() throws ArangoException { - - driver.createGraph(this.graphName, this.createEdgeDefinitions(2, 0), this.createOrphanCollections(2), true); - final VertexEntity v1 = driver.graphCreateVertex(this.graphName, "from1-1", - new TestComplexEntity01("v1-user", "desc1", 10), null); - final VertexEntity v2 = driver.graphCreateVertex(this.graphName, "to1-1", - new TestComplexEntity01("v2-user", "desc2", 12), null); - driver.graphCreateVertex(this.graphName, "from1-1", new TestComplexEntity01("v3-user", "desc3", 14), null); - driver.graphCreateVertex(this.graphName, "to1-1", new TestComplexEntity01("v4-user", "desc4", 20), null); - - final EdgeEntity edge = driver.graphCreateEdge(this.graphName, this.edgeCollectionName, null, - v1.getDocumentHandle(), v2.getDocumentHandle(), new TestComplexEntity02(1, 2, 3), null); - assertThat(edge.getCode(), is(202)); - - EdgeEntity replacedEdge = driver.graphReplaceEdge(this.graphName, this.edgeCollectionName, - edge.getDocumentKey(), v1.getDocumentHandle(), v2.getDocumentHandle(), null, false, null, null); - assertThat(replacedEdge.getCode(), is(202)); - assertThat(replacedEdge.isError(), is(false)); - assertThat(replacedEdge.getDocumentKey(), is(edge.getDocumentKey())); - assertThat(replacedEdge.getDocumentRevision(), is(not(edge.getDocumentRevision()))); - assertThat(replacedEdge.getDocumentHandle(), is(edge.getDocumentHandle())); - replacedEdge = driver.graphGetEdge(this.graphName, this.edgeCollectionName, edge.getDocumentKey(), null); - assertThat(replacedEdge.getFromVertexHandle(), is(v1.getDocumentHandle())); - assertThat(replacedEdge.getToVertexHandle(), is(v2.getDocumentHandle())); - assertThat(replacedEdge.getEntity(), is(nullValue())); - - } - - @Test - public void test_replace_edge_rev_eq() throws ArangoException { - - driver.createGraph(this.graphName, this.createEdgeDefinitions(2, 0), this.createOrphanCollections(2), true); - final DocumentEntity v1 = driver.graphCreateVertex(this.graphName, "from1-1", - new TestComplexEntity01("v1-user", "desc1", 10), null); - final VertexEntity v2 = driver.graphCreateVertex(this.graphName, "to1-1", - new TestComplexEntity01("v2-user", "desc2", 12), null); - driver.graphCreateVertex(this.graphName, "from1-1", new TestComplexEntity01("v3-user", "desc3", 14), null); - driver.graphCreateVertex(this.graphName, "to1-1", new TestComplexEntity01("v4-user", "desc4", 20), null); - - final EdgeEntity edge = driver.graphCreateEdge(this.graphName, this.edgeCollectionName, null, - v1.getDocumentHandle(), v2.getDocumentHandle(), new TestComplexEntity02(1, 2, 3), null); - assertThat(edge.getCode(), is(202)); - - final String rev = edge.getDocumentRevision(); - EdgeEntity replacedEdge = driver.graphReplaceEdge(this.graphName, this.edgeCollectionName, - edge.getDocumentKey(), v1.getDocumentHandle(), v2.getDocumentHandle(), - new TestComplexEntity01("xx", "yy", 20), null, rev, null); - assertThat(replacedEdge.getCode(), is(202)); - assertThat(replacedEdge.isError(), is(false)); - assertThat(replacedEdge.getDocumentKey(), is(edge.getDocumentKey())); - assertThat(replacedEdge.getDocumentRevision(), is(not(edge.getDocumentRevision()))); - assertThat(replacedEdge.getDocumentHandle(), is(edge.getDocumentHandle())); - replacedEdge = driver.graphGetEdge(this.graphName, this.edgeCollectionName, edge.getDocumentKey(), - TestComplexEntity01.class); - assertThat(replacedEdge.getFromVertexHandle(), is(v1.getDocumentHandle())); - assertThat(replacedEdge.getToVertexHandle(), is(v2.getDocumentHandle())); - assertThat(replacedEdge.getEntity(), instanceOf(TestComplexEntity01.class)); - assertThat(replacedEdge.getEntity().getUser(), is("xx")); - assertThat(replacedEdge.getEntity().getDesc(), is("yy")); - assertThat(replacedEdge.getEntity().getAge(), is(20)); - - } - - @Test - public void test_replace_edge_rev_ne() throws ArangoException { - - driver.createGraph(this.graphName, this.createEdgeDefinitions(2, 0), this.createOrphanCollections(2), true); - final VertexEntity v1 = driver.graphCreateVertex(this.graphName, "from1-1", - new TestComplexEntity01("v1-user", "desc1", 10), null); - final VertexEntity v2 = driver.graphCreateVertex(this.graphName, "to1-1", - new TestComplexEntity01("v2-user", "desc2", 12), null); - driver.graphCreateVertex(this.graphName, "from1-1", new TestComplexEntity01("v3-user", "desc3", 14), null); - driver.graphCreateVertex(this.graphName, "to1-1", new TestComplexEntity01("v4-user", "desc4", 20), null); - - final EdgeEntity edge = driver.graphCreateEdge(this.graphName, this.edgeCollectionName, null, - v1.getDocumentHandle(), v2.getDocumentHandle(), new TestComplexEntity02(1, 2, 3), null); - assertThat(edge.getCode(), is(202)); - - try { - final String rev = edge.getDocumentRevision() + 1; - driver.graphReplaceEdge(this.graphName, this.edgeCollectionName, edge.getDocumentKey(), - v1.getDocumentHandle(), v2.getDocumentHandle(), new TestComplexEntity01("xx", "yy", 20), null, rev, - null); - fail(); - } catch (final ArangoException e) { - assertThat(e.getCode(), is(412)); - assertThat(e.getErrorNumber(), is(1903)); - assertThat(e.getErrorMessage(), is("wrong revision")); - } - - } - - @Test - public void test_replace_edge_match_eq() throws ArangoException { - - driver.createGraph(this.graphName, this.createEdgeDefinitions(2, 0), this.createOrphanCollections(2), true); - final VertexEntity v1 = driver.graphCreateVertex(this.graphName, "from1-1", - new TestComplexEntity01("v1-user", "desc1", 10), null); - final VertexEntity v2 = driver.graphCreateVertex(this.graphName, "to1-1", - new TestComplexEntity01("v2-user", "desc2", 12), null); - driver.graphCreateVertex(this.graphName, "from1-1", new TestComplexEntity01("v3-user", "desc3", 14), null); - driver.graphCreateVertex(this.graphName, "to1-1", new TestComplexEntity01("v4-user", "desc4", 20), null); - - final EdgeEntity edge = driver.graphCreateEdge(this.graphName, this.edgeCollectionName, null, - v1.getDocumentHandle(), v2.getDocumentHandle(), new TestComplexEntity02(1, 2, 3), null); - assertThat(edge.getCode(), is(202)); - - final String rev = edge.getDocumentRevision(); - EdgeEntity replacedEdge = driver.graphReplaceEdge(this.graphName, this.edgeCollectionName, - edge.getDocumentKey(), v1.getDocumentHandle(), v2.getDocumentHandle(), - new TestComplexEntity01("xx", "yy", 20), null, rev, null); - assertThat(replacedEdge.getCode(), is(202)); - assertThat(replacedEdge.isError(), is(false)); - assertThat(replacedEdge.getDocumentKey(), is(edge.getDocumentKey())); - assertThat(replacedEdge.getDocumentRevision(), is(not(edge.getDocumentRevision()))); - replacedEdge = driver.graphGetEdge(this.graphName, this.edgeCollectionName, edge.getDocumentKey(), - TestComplexEntity01.class); - assertThat(replacedEdge.getDocumentHandle(), is(edge.getDocumentHandle())); - assertThat(replacedEdge.getFromVertexHandle(), is(v1.getDocumentHandle())); - assertThat(replacedEdge.getToVertexHandle(), is(v2.getDocumentHandle())); - - assertThat(replacedEdge.getEntity(), instanceOf(TestComplexEntity01.class)); - assertThat(replacedEdge.getEntity().getUser(), is("xx")); - assertThat(replacedEdge.getEntity().getDesc(), is("yy")); - assertThat(replacedEdge.getEntity().getAge(), is(20)); - - } - - @Test - public void test_replace_edge_match_ne() throws ArangoException { - - driver.createGraph(this.graphName, this.createEdgeDefinitions(2, 0), this.createOrphanCollections(2), true); - final VertexEntity v1 = driver.graphCreateVertex(this.graphName, "from1-1", - new TestComplexEntity01("v1-user", "desc1", 10), null); - final VertexEntity v2 = driver.graphCreateVertex(this.graphName, "to1-1", - new TestComplexEntity01("v2-user", "desc2", 12), null); - driver.graphCreateVertex(this.graphName, "from1-1", new TestComplexEntity01("v3-user", "desc3", 14), null); - driver.graphCreateVertex(this.graphName, "to1-1", new TestComplexEntity01("v4-user", "desc4", 20), null); - - final EdgeEntity edge = driver.graphCreateEdge(this.graphName, this.edgeCollectionName, null, - v1.getDocumentHandle(), v2.getDocumentHandle(), new TestComplexEntity02(1, 2, 3), null); - assertThat(edge.getCode(), is(202)); - - try { - final String rev = edge.getDocumentRevision() + 1; - driver.graphReplaceEdge(this.graphName, this.edgeCollectionName, edge.getDocumentKey(), - v1.getDocumentHandle(), v2.getDocumentHandle(), new TestComplexEntity01("xx", "yy", 20), null, rev, - null); - fail(); - } catch (final ArangoException e) { - assertThat(e.getCode(), is(412)); - assertThat(e.getErrorNumber(), is(1903)); - assertThat(e.getErrorMessage(), is("wrong revision")); - } - - } - - @Test - public void test_replace_from_to() throws ArangoException { - - driver.createGraph(this.graphName, this.createEdgeDefinitions(2, 0), this.createOrphanCollections(2), true); - final VertexEntity v1 = driver.graphCreateVertex(this.graphName, "from1-1", - new TestComplexEntity01("v1-user", "desc1", 10), null); - final VertexEntity v2 = driver.graphCreateVertex(this.graphName, "to1-1", - new TestComplexEntity01("v2-user", "desc2", 12), null); - driver.graphCreateVertex(this.graphName, "from1-1", new TestComplexEntity01("v3-user", "desc3", 14), null); - driver.graphCreateVertex(this.graphName, "to1-1", new TestComplexEntity01("v4-user", "desc4", 20), null); - - final EdgeEntity edge = driver.graphCreateEdge(this.graphName, this.edgeCollectionName, - null, v1.getDocumentHandle(), v2.getDocumentHandle(), new TestComplexEntity02(1, 2, 3), null); - assertThat(edge.getCode(), is(202)); - - final String rev = edge.getDocumentRevision(); - EdgeEntity replacedEdge = driver.graphReplaceEdge(this.graphName, this.edgeCollectionName, - edge.getDocumentKey(), v2.getDocumentHandle(), v1.getDocumentHandle(), edge.getEntity(), null, rev, null); - - assertThat(replacedEdge.getCode(), is(202)); - assertThat(replacedEdge.isError(), is(false)); - assertThat(replacedEdge.getDocumentKey(), is(edge.getDocumentKey())); - assertThat(replacedEdge.getDocumentRevision(), is(not(edge.getDocumentRevision()))); - assertThat(replacedEdge.getFromVertexHandle(), is(v2.getDocumentHandle())); - assertThat(replacedEdge.getToVertexHandle(), is(v1.getDocumentHandle())); - - replacedEdge = driver.graphGetEdge(this.graphName, this.edgeCollectionName, edge.getDocumentKey(), - TestComplexEntity02.class); - - assertThat(replacedEdge.getDocumentHandle(), is(edge.getDocumentHandle())); - assertThat(replacedEdge.getFromVertexHandle(), is(v2.getDocumentHandle())); - assertThat(replacedEdge.getToVertexHandle(), is(v1.getDocumentHandle())); - assertThat(replacedEdge.getEntity(), instanceOf(TestComplexEntity02.class)); - assertThat(replacedEdge.getEntity().getX(), is(1)); - assertThat(replacedEdge.getEntity().getY(), is(2)); - assertThat(replacedEdge.getEntity().getZ(), is(3)); - - } - -} diff --git a/src/test/java/com/arangodb/ArangoDriverGraphEdgeUpdateTest.java b/src/test/java/com/arangodb/ArangoDriverGraphEdgeUpdateTest.java deleted file mode 100644 index f012d0c1a..000000000 --- a/src/test/java/com/arangodb/ArangoDriverGraphEdgeUpdateTest.java +++ /dev/null @@ -1,263 +0,0 @@ -/** - * Copyright 2004-2014 triAGENS GmbH, Cologne, Germany - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Copyright holder is triAGENS GmbH, Cologne, Germany - * - * @author gschwab - * @author Copyright 2014, triAGENS GmbH, Cologne, Germany - */ -package com.arangodb; - -import static org.hamcrest.CoreMatchers.instanceOf; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.not; -import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; - -import org.junit.Test; - -import com.arangodb.entity.DocumentEntity; -import com.arangodb.entity.EdgeEntity; - -public class ArangoDriverGraphEdgeUpdateTest extends BaseGraphTest { - - private final String graphName = "UnitTestGraph"; - private final String edgeCollectionName = "edge-1"; - - @Test - public void test_graphUpdateEdge() throws ArangoException { - - driver.createGraph(this.graphName, this.createEdgeDefinitions(2, 0), this.createOrphanCollections(2), true); - final DocumentEntity v1 = driver.graphCreateVertex(this.graphName, "from1-1", - new TestComplexEntity01("v1-user", "desc1", 10), null); - final DocumentEntity v2 = driver.graphCreateVertex(this.graphName, "to1-1", - new TestComplexEntity01("v2-user", "desc2", 12), null); - driver.graphCreateVertex(this.graphName, "from1-1", new TestComplexEntity01("v3-user", "desc3", 14), null); - driver.graphCreateVertex(this.graphName, "to1-1", new TestComplexEntity01("v4-user", "desc4", 20), null); - - final EdgeEntity edge = driver.graphCreateEdge(this.graphName, this.edgeCollectionName, null, - v1.getDocumentHandle(), v2.getDocumentHandle(), new TestComplexEntity02(1, 2, 3), null); - assertThat(edge.getCode(), is(202)); - - EdgeEntity updatedEdge = driver.graphUpdateEdge(this.graphName, this.edgeCollectionName, - edge.getDocumentKey(), v1.getDocumentHandle(), v2.getDocumentHandle(), - new TestComplexEntity01("xx", "yy", 20), true); - assertThat(updatedEdge.getCode(), is(202)); - assertThat(updatedEdge.isError(), is(false)); - assertThat(updatedEdge.getDocumentKey(), is(edge.getDocumentKey())); - assertThat(updatedEdge.getDocumentRevision(), is(not(edge.getDocumentRevision()))); - assertThat(updatedEdge.getDocumentHandle(), is(edge.getDocumentHandle())); - updatedEdge = driver.graphGetEdge(this.graphName, this.edgeCollectionName, updatedEdge.getDocumentKey(), - TestComplexEntity01.class); - assertThat(updatedEdge.getFromVertexHandle(), is(v1.getDocumentHandle())); - assertThat(updatedEdge.getToVertexHandle(), is(v2.getDocumentHandle())); - - assertThat(updatedEdge.getEntity(), instanceOf(TestComplexEntity01.class)); - assertThat(updatedEdge.getEntity().getUser(), is("xx")); - assertThat(updatedEdge.getEntity().getDesc(), is("yy")); - assertThat(updatedEdge.getEntity().getAge(), is(20)); - - } - - @Test - public void test_updateEdge_null() throws ArangoException { - - driver.createGraph(this.graphName, this.createEdgeDefinitions(2, 0), this.createOrphanCollections(2), true); - final DocumentEntity v1 = driver.graphCreateVertex(this.graphName, "from1-1", - new TestComplexEntity01("v1-user", "desc1", 10), null); - final DocumentEntity v2 = driver.graphCreateVertex(this.graphName, "to1-1", - new TestComplexEntity01("v2-user", "desc2", 12), null); - driver.graphCreateVertex(this.graphName, "from1-1", new TestComplexEntity01("v3-user", "desc3", 14), null); - driver.graphCreateVertex(this.graphName, "to1-1", new TestComplexEntity01("v4-user", "desc4", 20), null); - - final EdgeEntity edge = driver.graphCreateEdge(this.graphName, this.edgeCollectionName, null, - v1.getDocumentHandle(), v2.getDocumentHandle(), new TestComplexEntity02(1, 2, 3), null); - assertThat(edge.getCode(), is(202)); - - EdgeEntity updatedEdge = driver.graphUpdateEdge(this.graphName, this.edgeCollectionName, - edge.getDocumentKey(), v1.getDocumentHandle(), v2.getDocumentHandle(), null, null); - assertThat(updatedEdge.getCode(), is(202)); - assertThat(updatedEdge.isError(), is(false)); - assertThat(updatedEdge.getDocumentKey(), is(edge.getDocumentKey())); - assertThat(updatedEdge.getDocumentRevision(), is(not(edge.getDocumentRevision()))); - assertThat(updatedEdge.getDocumentHandle(), is(edge.getDocumentHandle())); - - updatedEdge = driver.graphGetEdge(this.graphName, this.edgeCollectionName, updatedEdge.getDocumentKey(), null); - - assertThat(updatedEdge.getFromVertexHandle(), is(v1.getDocumentHandle())); - assertThat(updatedEdge.getToVertexHandle(), is(v2.getDocumentHandle())); - assertThat(updatedEdge.getEntity(), is(nullValue())); - - } - - @Test - public void test_updateEdge_waitForSync() throws ArangoException { - - driver.createGraph(this.graphName, this.createEdgeDefinitions(2, 0), this.createOrphanCollections(2), true); - final DocumentEntity v1 = driver.graphCreateVertex(this.graphName, "from1-1", - new TestComplexEntity01("v1-user", "desc1", 10), null); - final DocumentEntity v2 = driver.graphCreateVertex(this.graphName, "to1-1", - new TestComplexEntity01("v2-user", "desc2", 12), null); - driver.graphCreateVertex(this.graphName, "from1-1", new TestComplexEntity01("v3-user", "desc3", 14), null); - driver.graphCreateVertex(this.graphName, "to1-1", new TestComplexEntity01("v4-user", "desc4", 20), null); - - final EdgeEntity edge = driver.graphCreateEdge(this.graphName, this.edgeCollectionName, null, - v1.getDocumentHandle(), v2.getDocumentHandle(), new TestComplexEntity02(1, 2, 3), null); - assertThat(edge.getCode(), is(202)); - - EdgeEntity updatedEdge = driver.graphUpdateEdge(this.graphName, this.edgeCollectionName, - edge.getDocumentKey(), v1.getDocumentHandle(), v2.getDocumentHandle(), null, false, true, null, null); - assertThat(updatedEdge.getCode(), is(202)); - assertThat(updatedEdge.isError(), is(false)); - assertThat(updatedEdge.getDocumentKey(), is(edge.getDocumentKey())); - assertThat(updatedEdge.getDocumentRevision(), is(not(edge.getDocumentRevision()))); - assertThat(updatedEdge.getDocumentHandle(), is(edge.getDocumentHandle())); - updatedEdge = driver.graphGetEdge(this.graphName, this.edgeCollectionName, edge.getDocumentKey(), null); - assertThat(updatedEdge.getFromVertexHandle(), is(v1.getDocumentHandle())); - assertThat(updatedEdge.getToVertexHandle(), is(v2.getDocumentHandle())); - assertThat(updatedEdge.getEntity(), is(nullValue())); - - } - - @Test - public void test_updateEdge_rev_eq() throws ArangoException { - - driver.createGraph(this.graphName, this.createEdgeDefinitions(2, 0), this.createOrphanCollections(2), true); - final DocumentEntity v1 = driver.graphCreateVertex(this.graphName, "from1-1", - new TestComplexEntity01("v1-user", "desc1", 10), null); - final DocumentEntity v2 = driver.graphCreateVertex(this.graphName, "to1-1", - new TestComplexEntity01("v2-user", "desc2", 12), null); - driver.graphCreateVertex(this.graphName, "from1-1", new TestComplexEntity01("v3-user", "desc3", 14), null); - driver.graphCreateVertex(this.graphName, "to1-1", new TestComplexEntity01("v4-user", "desc4", 20), null); - - final EdgeEntity edge = driver.graphCreateEdge(this.graphName, this.edgeCollectionName, null, - v1.getDocumentHandle(), v2.getDocumentHandle(), new TestComplexEntity02(1, 2, 3), null); - assertThat(edge.getCode(), is(202)); - - final String rev = edge.getDocumentRevision(); - EdgeEntity updatedEdge = driver.graphUpdateEdge(this.graphName, this.edgeCollectionName, - edge.getDocumentKey(), v1.getDocumentHandle(), v2.getDocumentHandle(), - new TestComplexEntity01("xx", "yy", 20), null, null, rev, null); - assertThat(updatedEdge.getCode(), is(202)); - assertThat(updatedEdge.isError(), is(false)); - assertThat(updatedEdge.getDocumentKey(), is(edge.getDocumentKey())); - assertThat(updatedEdge.getDocumentRevision(), is(not(edge.getDocumentRevision()))); - assertThat(updatedEdge.getDocumentHandle(), is(edge.getDocumentHandle())); - updatedEdge = driver.graphGetEdge(this.graphName, this.edgeCollectionName, edge.getDocumentKey(), - TestComplexEntity01.class); - assertThat(updatedEdge.getFromVertexHandle(), is(v1.getDocumentHandle())); - assertThat(updatedEdge.getToVertexHandle(), is(v2.getDocumentHandle())); - assertThat(updatedEdge.getEntity(), instanceOf(TestComplexEntity01.class)); - assertThat(updatedEdge.getEntity().getUser(), is("xx")); - assertThat(updatedEdge.getEntity().getDesc(), is("yy")); - assertThat(updatedEdge.getEntity().getAge(), is(20)); - - } - - @Test - public void test_updateEdge_rev_ne() throws ArangoException { - - driver.createGraph(this.graphName, this.createEdgeDefinitions(2, 0), this.createOrphanCollections(2), true); - final DocumentEntity v1 = driver.graphCreateVertex(this.graphName, "from1-1", - new TestComplexEntity01("v1-user", "desc1", 10), null); - final DocumentEntity v2 = driver.graphCreateVertex(this.graphName, "to1-1", - new TestComplexEntity01("v2-user", "desc2", 12), null); - driver.graphCreateVertex(this.graphName, "from1-1", new TestComplexEntity01("v3-user", "desc3", 14), null); - driver.graphCreateVertex(this.graphName, "to1-1", new TestComplexEntity01("v4-user", "desc4", 20), null); - - final EdgeEntity edge = driver.graphCreateEdge(this.graphName, this.edgeCollectionName, null, - v1.getDocumentHandle(), v2.getDocumentHandle(), new TestComplexEntity02(1, 2, 3), null); - assertThat(edge.getCode(), is(202)); - - try { - final String rev = edge.getDocumentRevision() + 1; - driver.graphUpdateEdge(this.graphName, this.edgeCollectionName, edge.getDocumentKey(), - v1.getDocumentHandle(), v2.getDocumentHandle(), new TestComplexEntity01("xx", "yy", 20), null, null, - rev, null); - fail(); - } catch (final ArangoException e) { - assertThat(e.getCode(), is(412)); - assertThat(e.getErrorNumber(), is(1903)); - assertThat(e.getErrorMessage(), is("wrong revision")); - } - - } - - @Test - public void test_updateEdge_match_eq() throws ArangoException { - - driver.createGraph(this.graphName, this.createEdgeDefinitions(2, 0), this.createOrphanCollections(2), true); - final DocumentEntity v1 = driver.graphCreateVertex(this.graphName, "from1-1", - new TestComplexEntity01("v1-user", "desc1", 10), null); - final DocumentEntity v2 = driver.graphCreateVertex(this.graphName, "to1-1", - new TestComplexEntity01("v2-user", "desc2", 12), null); - driver.graphCreateVertex(this.graphName, "from1-1", new TestComplexEntity01("v3-user", "desc3", 14), null); - driver.graphCreateVertex(this.graphName, "to1-1", new TestComplexEntity01("v4-user", "desc4", 20), null); - - final EdgeEntity edge = driver.graphCreateEdge(this.graphName, this.edgeCollectionName, null, - v1.getDocumentHandle(), v2.getDocumentHandle(), new TestComplexEntity02(1, 2, 3), null); - assertThat(edge.getCode(), is(202)); - - final String rev = edge.getDocumentRevision(); - EdgeEntity updatedEdge = driver.graphUpdateEdge(this.graphName, this.edgeCollectionName, - edge.getDocumentKey(), v1.getDocumentHandle(), v2.getDocumentHandle(), - new TestComplexEntity01("xx", "yy", 20), null, null, rev, null); - - assertThat(updatedEdge.getCode(), is(202)); - assertThat(updatedEdge.isError(), is(false)); - assertThat(updatedEdge.getDocumentKey(), is(edge.getDocumentKey())); - assertThat(updatedEdge.getDocumentRevision(), is(not(edge.getDocumentRevision()))); - updatedEdge = driver.graphGetEdge(this.graphName, this.edgeCollectionName, edge.getDocumentKey(), - TestComplexEntity01.class); - assertThat(updatedEdge.getDocumentHandle(), is(edge.getDocumentHandle())); - assertThat(updatedEdge.getFromVertexHandle(), is(v1.getDocumentHandle())); - assertThat(updatedEdge.getToVertexHandle(), is(v2.getDocumentHandle())); - - assertThat(updatedEdge.getEntity(), instanceOf(TestComplexEntity01.class)); - assertThat(updatedEdge.getEntity().getUser(), is("xx")); - assertThat(updatedEdge.getEntity().getDesc(), is("yy")); - assertThat(updatedEdge.getEntity().getAge(), is(20)); - - } - - @Test - public void test_updateEdge_match_ne() throws ArangoException { - - driver.createGraph(this.graphName, this.createEdgeDefinitions(2, 0), this.createOrphanCollections(2), true); - final DocumentEntity v1 = driver.graphCreateVertex(this.graphName, "from1-1", - new TestComplexEntity01("v1-user", "desc1", 10), null); - final DocumentEntity v2 = driver.graphCreateVertex(this.graphName, "to1-1", - new TestComplexEntity01("v2-user", "desc2", 12), null); - driver.graphCreateVertex(this.graphName, "from1-1", new TestComplexEntity01("v3-user", "desc3", 14), null); - driver.graphCreateVertex(this.graphName, "to1-1", new TestComplexEntity01("v4-user", "desc4", 20), null); - - final EdgeEntity edge = driver.graphCreateEdge(this.graphName, this.edgeCollectionName, null, - v1.getDocumentHandle(), v2.getDocumentHandle(), new TestComplexEntity02(1, 2, 3), null); - assertThat(edge.getCode(), is(202)); - - try { - final String rev = edge.getDocumentRevision() + 1; - driver.graphUpdateEdge(this.graphName, this.edgeCollectionName, edge.getDocumentKey(), - v1.getDocumentHandle(), v2.getDocumentHandle(), new TestComplexEntity01("xx", "yy", 20), null, null, - rev, null); - fail(); - } catch (final ArangoException e) { - assertThat(e.getCode(), is(412)); - assertThat(e.getErrorNumber(), is(1903)); - assertThat(e.getErrorMessage(), is("wrong revision")); - } - - } -} diff --git a/src/test/java/com/arangodb/ArangoDriverGraphEdgesGetCursorTest.java b/src/test/java/com/arangodb/ArangoDriverGraphEdgesGetCursorTest.java deleted file mode 100644 index 7a97fd887..000000000 --- a/src/test/java/com/arangodb/ArangoDriverGraphEdgesGetCursorTest.java +++ /dev/null @@ -1,473 +0,0 @@ -/* - * Copyright (C) 2012,2013 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb; - -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.Matchers.startsWith; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import org.junit.Before; -import org.junit.Test; - -import com.arangodb.entity.EdgeEntity; -import com.arangodb.entity.GraphEntity; -import com.arangodb.entity.PlainEdgeEntity; -import com.arangodb.entity.ShortestPathEntity; -import com.arangodb.entity.marker.VertexEntity; -import com.arangodb.util.AqlQueryOptions; -import com.arangodb.util.GraphEdgesOptions; -import com.arangodb.util.ShortestPathOptions; - -/** - * @author tamtam180 - kirscheless at gmail.com - * - */ -public class ArangoDriverGraphEdgesGetCursorTest extends BaseGraphTest { - - private static final String GRAPH_NAME = "UnitTestGraph"; - - @Before - public void setup() throws ArangoException { - try { - driver.createGraph(GRAPH_NAME, this.createEdgeDefinitions(1, 0), this.createOrphanCollections(0), true); - } catch (final ArangoException e) { - } - } - - @Test - public void graphGetEdgeCursorTest() throws ArangoException { - final GraphEntity graph = this.createTestGraph(); - final EdgeCursor cursor = driver.graphGetEdgeCursor(graph.getName()); - assertThat(cursor.getCount(), is(8)); - assertThat(cursor.getCode(), is(201)); - assertThat(cursor.hasMore(), is(false)); - assertThat(cursor.getCursorId(), is(-1L)); - - final List results = cursor.asEntityList(); - assertThat(results.size(), is(8)); - assertThat(results.get(0).getFromCollection(), startsWith("Country/")); - assertThat(results.get(0).getToCollection(), startsWith("Country/")); - } - - @Test - public void graphGetEdgeCursorIteratorTest() throws ArangoException { - final GraphEntity graph = this.createTestGraph(); - final EdgeCursor cursor = driver.graphGetEdgeCursor(graph.getName()); - assertThat(cursor.getCount(), is(8)); - assertThat(cursor.getCode(), is(201)); - assertThat(cursor.hasMore(), is(false)); - assertThat(cursor.getCursorId(), is(-1L)); - - int count = 0; - - final Iterator> iterator = cursor.iterator(); - while (iterator.hasNext()) { - final EdgeEntity edgeEntity = iterator.next(); - ++count; - assertThat(edgeEntity.getEntity().getFromCollection(), startsWith("Country/")); - assertThat(edgeEntity.getEntity().getToCollection(), startsWith("Country/")); - } - - assertThat(count, is(8)); - } - - @Test - public void graphGetEdgeCursorByExampleVertexHandle() throws ArangoException { - - final TestComplexEntity01 v1 = new TestComplexEntity01("Homer", "A Simpson", 38); - final TestComplexEntity01 v2 = new TestComplexEntity01("Marge", "A Simpson", 36); - final TestComplexEntity01 v3 = new TestComplexEntity01("Bart", "A Simpson", 10); - - final VertexEntity vertex1 = driver.graphCreateVertex(GRAPH_NAME, "from1-1", v1, true); - final VertexEntity vertex2 = driver.graphCreateVertex(GRAPH_NAME, "to1-1", v2, true); - final VertexEntity vertex3 = driver.graphCreateVertex(GRAPH_NAME, "to1-1", v3, true); - - driver.graphCreateEdge(GRAPH_NAME, "edge-1", null, vertex1.getDocumentHandle(), vertex2.getDocumentHandle(), - new TestComplexEntity02(1, 2, 3), null); - - driver.graphCreateEdge(GRAPH_NAME, "edge-1", null, vertex1.getDocumentHandle(), vertex3.getDocumentHandle(), - new TestComplexEntity02(4, 5, 6), null); - - EdgeCursor cursor = driver.graphGetEdgeCursorByExample(GRAPH_NAME, - TestComplexEntity02.class, vertex1.getDocumentHandle()); - assertThat(cursor.getCount(), is(2)); - - cursor = driver.graphGetEdgeCursorByExample(GRAPH_NAME, TestComplexEntity02.class, vertex2.getDocumentHandle()); - assertThat(cursor.getCount(), is(1)); - } - - @Test - public void graphGetEdgeCursorByExampleObjectTest() throws ArangoException { - final TestComplexEntity01 v1 = new TestComplexEntity01("Homer", "A Simpson", 38); - final TestComplexEntity01 v2 = new TestComplexEntity01("Marge", "A Simpson", 36); - final TestComplexEntity01 v3 = new TestComplexEntity01("Bart", "A Simpson", 10); - final TestComplexEntity01 v4 = new TestComplexEntity01("Remoh", "Homer's twin", 38); - - final VertexEntity vertex1 = driver.graphCreateVertex(GRAPH_NAME, "from1-1", v1, true); - - final VertexEntity vertex2 = driver.graphCreateVertex(GRAPH_NAME, "to1-1", v2, true); - - final VertexEntity vertex3 = driver.graphCreateVertex(GRAPH_NAME, "to1-1", v3, true); - - final VertexEntity vertex4 = driver.graphCreateVertex(GRAPH_NAME, "from1-1", v4, true); - - driver.graphCreateEdge(GRAPH_NAME, "edge-1", null, vertex1.getDocumentHandle(), vertex2.getDocumentHandle(), - new TestComplexEntity02(1, 2, 3), null); - - driver.graphCreateEdge(GRAPH_NAME, "edge-1", null, vertex1.getDocumentHandle(), vertex3.getDocumentHandle(), - new TestComplexEntity02(4, 5, 6), null); - - driver.graphCreateEdge(GRAPH_NAME, "edge-1", null, vertex4.getDocumentHandle(), vertex2.getDocumentHandle(), - new TestComplexEntity02(7, 8, 9), null); - - EdgeCursor cursor = driver.graphGetEdgeCursorByExample(GRAPH_NAME, - TestComplexEntity02.class, new TestComplexEntity01(null, null, 38)); - assertThat(cursor.getCount(), is(3)); - - cursor = driver.graphGetEdgeCursorByExample(GRAPH_NAME, TestComplexEntity02.class, v3); - assertThat(cursor.getCount(), is(1)); - - final List results = cursor.asEntityList(); - - assertThat(results.get(0).getClass().getName(), is(TestComplexEntity02.class.getName())); - assertThat(results.get(0).getX(), is(4)); - - } - - @Test - public void graphGetEdgeCursorByExampleMapTest() throws ArangoException { - final TestComplexEntity01 v1 = new TestComplexEntity01("Homer", "A Simpson", 38); - final TestComplexEntity01 v2 = new TestComplexEntity01("Marge", "A Simpson", 36); - final TestComplexEntity01 v3 = new TestComplexEntity01("Bart", "A Simpson", 10); - final TestComplexEntity01 v4 = new TestComplexEntity01("Remoh", "Homer's twin", 38); - - final VertexEntity vertex1 = driver.graphCreateVertex(GRAPH_NAME, "from1-1", v1, true); - final VertexEntity vertex2 = driver.graphCreateVertex(GRAPH_NAME, "to1-1", v2, true); - final VertexEntity vertex3 = driver.graphCreateVertex(GRAPH_NAME, "to1-1", v3, true); - final VertexEntity vertex4 = driver.graphCreateVertex(GRAPH_NAME, "from1-1", v4, true); - - driver.graphCreateEdge(GRAPH_NAME, "edge-1", null, vertex1.getDocumentHandle(), vertex2.getDocumentHandle(), - new TestComplexEntity02(1, 2, 3), null); - - driver.graphCreateEdge(GRAPH_NAME, "edge-1", null, vertex1.getDocumentHandle(), vertex3.getDocumentHandle(), - new TestComplexEntity02(4, 5, 6), null); - - driver.graphCreateEdge(GRAPH_NAME, "edge-1", null, vertex4.getDocumentHandle(), vertex2.getDocumentHandle(), - new TestComplexEntity02(7, 8, 9), null); - - final Map exampleVertex = new HashMap(); - exampleVertex.put("user", "Homer"); - - EdgeCursor cursor = driver.graphGetEdgeCursorByExample(GRAPH_NAME, - TestComplexEntity02.class, exampleVertex); - assertThat(cursor.getCount(), is(2)); - - exampleVertex.put("user", "Bart"); - cursor = driver.graphGetEdgeCursorByExample(GRAPH_NAME, TestComplexEntity02.class, exampleVertex); - assertThat(cursor.getCount(), is(1)); - - final List results = cursor.asEntityList(); - - assertThat(results.get(0).getClass().getName(), is(TestComplexEntity02.class.getName())); - assertThat(results.get(0).getX(), is(4)); - - } - - private AqlQueryOptions getAqlQueryOptions(final Boolean count, final Integer batchSize, final Boolean fullCount) { - return new AqlQueryOptions().setCount(count).setBatchSize(batchSize).setFullCount(fullCount); - } - - @Test - public void batchSizeAndLimitTest() throws ArangoException { - - final TestComplexEntity01 v1 = new TestComplexEntity01("Homer", "A Simpson", 38); - final TestComplexEntity01 v2 = new TestComplexEntity01("Marge", "A Simpson", 36); - final TestComplexEntity01 v3 = new TestComplexEntity01("Bart", "A Simpson", 10); - final TestComplexEntity01 v4 = new TestComplexEntity01("Remoh", "Homer's twin", 38); - - final VertexEntity vertex1 = driver.graphCreateVertex(GRAPH_NAME, "from1-1", v1, true); - final VertexEntity vertex2 = driver.graphCreateVertex(GRAPH_NAME, "to1-1", v2, true); - final VertexEntity vertex3 = driver.graphCreateVertex(GRAPH_NAME, "to1-1", v3, true); - final VertexEntity vertex4 = driver.graphCreateVertex(GRAPH_NAME, "from1-1", v4, true); - - driver.graphCreateEdge(GRAPH_NAME, "edge-1", null, vertex1.getDocumentHandle(), vertex2.getDocumentHandle(), - new TestComplexEntity02(1, 2, 3), null); - - driver.graphCreateEdge(GRAPH_NAME, "edge-1", null, vertex1.getDocumentHandle(), vertex3.getDocumentHandle(), - new TestComplexEntity02(4, 5, 6), null); - - driver.graphCreateEdge(GRAPH_NAME, "edge-1", null, vertex4.getDocumentHandle(), vertex2.getDocumentHandle(), - new TestComplexEntity02(7, 8, 9), null); - - driver.graphCreateEdge(GRAPH_NAME, "edge-1", null, vertex4.getDocumentHandle(), vertex3.getDocumentHandle(), - new TestComplexEntity02(10, 11, 12), null); - - final Integer batchSize = 2; - final Boolean count = true; - final Boolean fullCount = true; - - GraphEdgesOptions graphEdgesOptions = new GraphEdgesOptions(); - graphEdgesOptions.setLimit(3); - - final EdgeCursor cursor = driver.graphGetEdgeCursor(GRAPH_NAME, TestComplexEntity02.class, - null, graphEdgesOptions, getAqlQueryOptions(count, batchSize, fullCount)); - - assertEquals(3, cursor.getCount()); - assertEquals(201, cursor.getCode()); - assertTrue(cursor.hasMore()); - assertEquals(8, cursor.getFullCount()); - assertTrue(cursor.getCursorId() > -1L); - } - - @Test - public void edgesAqlTest() throws ArangoException { - - final TestComplexEntity01 v1 = new TestComplexEntity01("Homer", "A Simpson", 38); - final TestComplexEntity01 v2 = new TestComplexEntity01("Marge", "A Simpson", 36); - final TestComplexEntity01 v3 = new TestComplexEntity01("Bart", "A Simpson", 10); - final TestComplexEntity01 v4 = new TestComplexEntity01("Remoh", "Homer's twin", 38); - - final VertexEntity vertex1 = driver.graphCreateVertex(GRAPH_NAME, "from1-1", v1, true); - final VertexEntity vertex2 = driver.graphCreateVertex(GRAPH_NAME, "to1-1", v2, true); - final VertexEntity vertex3 = driver.graphCreateVertex(GRAPH_NAME, "to1-1", v3, true); - final VertexEntity vertex4 = driver.graphCreateVertex(GRAPH_NAME, "from1-1", v4, true); - - driver.graphCreateEdge(GRAPH_NAME, "edge-1", null, vertex1.getDocumentHandle(), vertex2.getDocumentHandle(), - new TestComplexEntity02(1, 2, 3), null); - - driver.graphCreateEdge(GRAPH_NAME, "edge-1", null, vertex1.getDocumentHandle(), vertex3.getDocumentHandle(), - new TestComplexEntity02(4, 5, 6), null); - - driver.graphCreateEdge(GRAPH_NAME, "edge-1", null, vertex4.getDocumentHandle(), vertex2.getDocumentHandle(), - new TestComplexEntity02(7, 8, 9), null); - - driver.graphCreateEdge(GRAPH_NAME, "edge-1", null, vertex4.getDocumentHandle(), vertex3.getDocumentHandle(), - new TestComplexEntity02(10, 11, 12), null); - - final Integer batchSize = 10; - final Boolean count = true; - final Boolean fullCount = true; - - GraphEdgesOptions graphEdgesOptions = new GraphEdgesOptions(); - graphEdgesOptions.setDirection(Direction.OUTBOUND); - graphEdgesOptions.setIncludeData(true); - { - EdgeCursor cursor = driver.graphGetEdgeCursor(GRAPH_NAME, TestComplexEntity02.class, - vertex1.getDocumentHandle(), graphEdgesOptions, getAqlQueryOptions(count, batchSize, fullCount)); - - assertEquals(2, cursor.getCount()); - assertEquals(201, cursor.getCode()); - assertFalse(cursor.hasMore()); - assertEquals(new Long(-1L), cursor.getCursorId()); - } - { - // get outbound vertices of vertex2 (the should be no) - EdgeCursor cursor = driver.graphGetEdgeCursor(GRAPH_NAME, TestComplexEntity02.class, - vertex2.getDocumentHandle(), graphEdgesOptions, getAqlQueryOptions(count, batchSize, fullCount)); - - assertEquals(0, cursor.getCount()); - assertEquals(201, cursor.getCode()); - assertFalse(cursor.hasMore()); - assertEquals(new Long(-1L), cursor.getCursorId()); - } - - } - - @Test - public void graphGetEdgeCursorWithEdgeExample() throws ArangoException { - - final TestComplexEntity01 v1 = new TestComplexEntity01("Homer", "A Simpson", 38); - final TestComplexEntity01 v2 = new TestComplexEntity01("Marge", "A Simpson", 36); - final TestComplexEntity01 v3 = new TestComplexEntity01("Bart", "A Simpson", 10); - final TestComplexEntity01 v4 = new TestComplexEntity01("Remoh", "Homer's twin", 38); - - final VertexEntity vertex1 = driver.graphCreateVertex(GRAPH_NAME, "from1-1", v1, true); - final VertexEntity vertex2 = driver.graphCreateVertex(GRAPH_NAME, "to1-1", v2, true); - final VertexEntity vertex3 = driver.graphCreateVertex(GRAPH_NAME, "to1-1", v3, true); - final VertexEntity vertex4 = driver.graphCreateVertex(GRAPH_NAME, "from1-1", v4, true); - - final TestComplexEntity02 e1 = new TestComplexEntity02(1, 2, 3); - driver.graphCreateEdge(GRAPH_NAME, "edge-1", null, vertex1.getDocumentHandle(), vertex2.getDocumentHandle(), e1, - null); - - final TestComplexEntity02 e2 = new TestComplexEntity02(4, 5, 6); - EdgeEntity edge2 = driver.graphCreateEdge(GRAPH_NAME, "edge-1", null, - vertex1.getDocumentHandle(), vertex3.getDocumentHandle(), e2, null); - - final TestComplexEntity02 e3 = new TestComplexEntity02(7, 8, 9); - driver.graphCreateEdge(GRAPH_NAME, "edge-1", null, vertex4.getDocumentHandle(), vertex2.getDocumentHandle(), e3, - null); - - final TestComplexEntity02 e4 = new TestComplexEntity02(10, 11, 12); - driver.graphCreateEdge(GRAPH_NAME, "edge-1", null, vertex4.getDocumentHandle(), vertex3.getDocumentHandle(), e4, - null); - - GraphEdgesOptions graphEdgesOptions = new GraphEdgesOptions(); - graphEdgesOptions.setEdgeExamples(e2); - - EdgeCursor cursor = driver.graphGetEdgeCursor(GRAPH_NAME, TestComplexEntity02.class, - vertex1.getDocumentHandle(), graphEdgesOptions, getAqlQueryOptions(true, 10, true)); - - assertEquals(201, cursor.getCode()); - assertEquals(1, cursor.getCount()); - assertEquals(edge2.getDocumentHandle(), cursor.getUniqueResult().getDocumentHandle()); - } - - @Test - public void graphGetEdgeCursorWithNeighborExample() throws ArangoException { - - final TestComplexEntity01 v1 = new TestComplexEntity01("Homer", "A Simpson", 38); - final TestComplexEntity01 v2 = new TestComplexEntity01("Marge", "A Simpson", 36); - final TestComplexEntity01 v3 = new TestComplexEntity01("Bart", "A Simpson", 10); - final TestComplexEntity01 v4 = new TestComplexEntity01("Remoh", "Homer's twin", 38); - - final VertexEntity vertex1 = driver.graphCreateVertex(GRAPH_NAME, "from1-1", v1, true); - final VertexEntity vertex2 = driver.graphCreateVertex(GRAPH_NAME, "to1-1", v2, true); - final VertexEntity vertex3 = driver.graphCreateVertex(GRAPH_NAME, "to1-1", v3, true); - final VertexEntity vertex4 = driver.graphCreateVertex(GRAPH_NAME, "from1-1", v4, true); - - final TestComplexEntity02 e1 = new TestComplexEntity02(1, 2, 3); - EdgeEntity edge1 = driver.graphCreateEdge(GRAPH_NAME, "edge-1", null, - vertex1.getDocumentHandle(), vertex2.getDocumentHandle(), e1, null); - - final TestComplexEntity02 e2 = new TestComplexEntity02(4, 5, 6); - driver.graphCreateEdge(GRAPH_NAME, "edge-1", null, vertex1.getDocumentHandle(), vertex3.getDocumentHandle(), e2, - null); - - final TestComplexEntity02 e3 = new TestComplexEntity02(7, 8, 9); - driver.graphCreateEdge(GRAPH_NAME, "edge-1", null, vertex4.getDocumentHandle(), vertex2.getDocumentHandle(), e3, - null); - - final TestComplexEntity02 e4 = new TestComplexEntity02(10, 11, 12); - driver.graphCreateEdge(GRAPH_NAME, "edge-1", null, vertex4.getDocumentHandle(), vertex3.getDocumentHandle(), e4, - null); - - GraphEdgesOptions graphEdgesOptions = new GraphEdgesOptions(); - graphEdgesOptions.setNeighborExamples(new TestComplexEntity01(null, null, 36)); - - EdgeCursor cursor = driver.graphGetEdgeCursor(GRAPH_NAME, TestComplexEntity02.class, - vertex1.getDocumentHandle(), graphEdgesOptions, getAqlQueryOptions(true, 10, true)); - - assertEquals(201, cursor.getCode()); - assertEquals(1, cursor.getCount()); - assertEquals(edge1.getDocumentHandle(), cursor.getUniqueResult().getDocumentHandle()); - } - - @Test - public void graphGetEdgeCursorByExampleStartVertexRestriction() throws ArangoException { - final TestComplexEntity01 v1 = new TestComplexEntity01("Homer", "A Simpson", 38); - final TestComplexEntity01 v2 = new TestComplexEntity01("Marge", "A Simpson", 36); - final TestComplexEntity01 v3 = new TestComplexEntity01("Bart", "A Simpson", 10); - final TestComplexEntity01 v4 = new TestComplexEntity01("Remoh", "Homer's twin", 38); - - final VertexEntity vertex1 = driver.graphCreateVertex(GRAPH_NAME, "from1-1", v1, true); - - final VertexEntity vertex2 = driver.graphCreateVertex(GRAPH_NAME, "to1-1", v2, true); - - final VertexEntity vertex3 = driver.graphCreateVertex(GRAPH_NAME, "to1-1", v3, true); - - final VertexEntity vertex4 = driver.graphCreateVertex(GRAPH_NAME, "from1-1", v4, true); - - driver.graphCreateEdge(GRAPH_NAME, "edge-1", null, vertex1.getDocumentHandle(), vertex2.getDocumentHandle(), - new TestComplexEntity02(1, 2, 3), null); - - driver.graphCreateEdge(GRAPH_NAME, "edge-1", null, vertex1.getDocumentHandle(), vertex3.getDocumentHandle(), - new TestComplexEntity02(4, 5, 6), null); - - driver.graphCreateEdge(GRAPH_NAME, "edge-1", null, vertex4.getDocumentHandle(), vertex2.getDocumentHandle(), - new TestComplexEntity02(7, 8, 9), null); - - GraphEdgesOptions graphEdgesOptions = new GraphEdgesOptions(); - List startVertexCollectionRestriction = new ArrayList(); - startVertexCollectionRestriction.add("from1-1"); - graphEdgesOptions.setStartVertexCollectionRestriction(startVertexCollectionRestriction); - - EdgeCursor cursor = driver.graphGetEdgeCursor(GRAPH_NAME, TestComplexEntity02.class, - new TestComplexEntity01(null, "A Simpson", null), graphEdgesOptions, getAqlQueryOptions(true, 10, true)); - assertThat(cursor.getCount(), is(2)); - } - - @Test - public void graphGetEdgeCursorByExampleEndVertexRestriction() throws ArangoException { - final TestComplexEntity01 v1 = new TestComplexEntity01("Homer", "A Simpson", 38); - final TestComplexEntity01 v2 = new TestComplexEntity01("Marge", "A Simpson", 36); - final TestComplexEntity01 v3 = new TestComplexEntity01("Bart", "A Simpson", 10); - final TestComplexEntity01 v4 = new TestComplexEntity01("Remoh", "Homer's twin", 38); - - final VertexEntity vertex1 = driver.graphCreateVertex(GRAPH_NAME, "from1-1", v1, true); - - final VertexEntity vertex2 = driver.graphCreateVertex(GRAPH_NAME, "to1-1", v2, true); - - final VertexEntity vertex3 = driver.graphCreateVertex(GRAPH_NAME, "to1-1", v3, true); - - final VertexEntity vertex4 = driver.graphCreateVertex(GRAPH_NAME, "from1-1", v4, true); - - driver.graphCreateEdge(GRAPH_NAME, "edge-1", null, vertex1.getDocumentHandle(), vertex2.getDocumentHandle(), - new TestComplexEntity02(1, 2, 3), null); - - driver.graphCreateEdge(GRAPH_NAME, "edge-1", null, vertex1.getDocumentHandle(), vertex3.getDocumentHandle(), - new TestComplexEntity02(4, 5, 6), null); - - driver.graphCreateEdge(GRAPH_NAME, "edge-1", null, vertex4.getDocumentHandle(), vertex2.getDocumentHandle(), - new TestComplexEntity02(7, 8, 9), null); - - GraphEdgesOptions graphEdgesOptions = new GraphEdgesOptions(); - List endVertexCollectionRestriction = new ArrayList(); - endVertexCollectionRestriction.add("to1-1"); - graphEdgesOptions.setEndVertexCollectionRestriction(endVertexCollectionRestriction); - - EdgeCursor cursor = driver.graphGetEdgeCursor(GRAPH_NAME, TestComplexEntity02.class, - new TestComplexEntity01(null, "A Simpson", null), graphEdgesOptions, getAqlQueryOptions(true, 10, true)); - assertThat(cursor.getCount(), is(2)); - } - - @Test - public void shortestPathTest() throws ArangoException { - - final TestComplexEntity01 v1 = new TestComplexEntity01("Homer", "A Simpson", 38); - final TestComplexEntity01 v2 = new TestComplexEntity01("Marge", "A Simpson", 36); - - final VertexEntity vertex1 = driver.graphCreateVertex(GRAPH_NAME, "from1-1", v1, true); - final VertexEntity vertex2 = driver.graphCreateVertex(GRAPH_NAME, "to1-1", v2, true); - - driver.graphCreateEdge(GRAPH_NAME, "edge-1", null, vertex1.getDocumentHandle(), vertex2.getDocumentHandle(), - new TestComplexEntity02(1, 2, 3), null); - - final ShortestPathOptions shortestPathOptions = new ShortestPathOptions(); - shortestPathOptions.setDirection(Direction.OUTBOUND); - - // - final ShortestPathEntity entity = driver.graphGetShortestPath( - GRAPH_NAME, vertex1.getDocumentHandle(), vertex2.getDocumentHandle(), shortestPathOptions, - TestComplexEntity01.class, TestComplexEntity02.class); - - assertEquals(201, entity.getCode()); - - assertEquals(1L, entity.getDistance().longValue()); - assertEquals(1, entity.getEdges().size()); - assertEquals(2, entity.getVertices().size()); - } -} diff --git a/src/test/java/com/arangodb/ArangoDriverGraphEdgesGetTest.java b/src/test/java/com/arangodb/ArangoDriverGraphEdgesGetTest.java deleted file mode 100644 index cf2c5fb91..000000000 --- a/src/test/java/com/arangodb/ArangoDriverGraphEdgesGetTest.java +++ /dev/null @@ -1,956 +0,0 @@ -/* - * Copyright (C) 2012,2013 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb; - -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.Matchers.startsWith; -import static org.junit.Assert.assertThat; - -import java.util.HashMap; -import java.util.Map; - -import org.junit.Before; -import org.junit.Test; - -import com.arangodb.entity.GraphEntity; -import com.arangodb.entity.PlainEdgeEntity; -import com.arangodb.entity.marker.VertexEntity; - -/** - * @author tamtam180 - kirscheless at gmail.com - * - */ -public class ArangoDriverGraphEdgesGetTest extends BaseGraphTest { - - private static final String GRAPH_NAME = "UnitTestGraph"; - - @Before - public void setup() throws ArangoException { - try { - driver.createGraph(GRAPH_NAME, this.createEdgeDefinitions(1, 0), this.createOrphanCollections(0), true); - } catch (final ArangoException e) { - } - } - - @Test - public void test_getEdges_All() throws ArangoException { - final GraphEntity graph = this.createTestGraph(); - final EdgeCursor cursor = driver.graphGetEdgeCursor(graph.getName()); - assertThat(cursor.getCount(), is(8)); - assertThat(cursor.getCode(), is(201)); - assertThat(cursor.hasMore(), is(false)); - assertThat(cursor.getCursorId(), is(-1L)); - assertThat(cursor.asEntityList().size(), is(8)); - assertThat(cursor.asEntityList().get(0).getFromCollection(), startsWith("Country/")); - assertThat(cursor.asEntityList().get(0).getToCollection(), startsWith("Country/")); - - } - - @Test - public void test_getEdges_Vertex() throws ArangoException { - final VertexEntity vertex1 = driver.graphCreateVertex(GRAPH_NAME, "from1-1", - new TestComplexEntity01("Homer", "A Simpson", 38), true); - - final VertexEntity vertex2 = driver.graphCreateVertex(GRAPH_NAME, "to1-1", - new TestComplexEntity01("Marge", "A Simpson", 36), true); - - final VertexEntity vertex3 = driver.graphCreateVertex(GRAPH_NAME, "to1-1", - new TestComplexEntity01("Bart", "A Simpson", 10), true); - - driver.graphCreateEdge(GRAPH_NAME, "edge-1", null, vertex1.getDocumentHandle(), vertex2.getDocumentHandle(), - new TestComplexEntity02(1, 2, 3), null); - - driver.graphCreateEdge(GRAPH_NAME, "edge-1", null, vertex1.getDocumentHandle(), vertex3.getDocumentHandle(), - new TestComplexEntity02(4, 5, 6), null); - - EdgeCursor cursor = driver.graphGetEdgeCursor(GRAPH_NAME, TestComplexEntity02.class, - vertex1.getDocumentHandle(), null, null); - assertThat(cursor.getCount(), is(2)); - - cursor = driver.graphGetEdgeCursor(GRAPH_NAME, TestComplexEntity02.class, vertex2.getDocumentHandle(), null, - null); - assertThat(cursor.getCount(), is(1)); - } - - @Test - public void test_GetEdgesByExampleObject() throws ArangoException { - final TestComplexEntity01 v1 = new TestComplexEntity01("Homer", "A Simpson", 38); - final TestComplexEntity01 v2 = new TestComplexEntity01("Marge", "A Simpson", 36); - final TestComplexEntity01 v3 = new TestComplexEntity01("Bart", "A Simpson", 10); - final TestComplexEntity01 v4 = new TestComplexEntity01("Remoh", "Homer's twin", 38); - - final VertexEntity vertex1 = driver.graphCreateVertex(GRAPH_NAME, "from1-1", v1, true); - - final VertexEntity vertex2 = driver.graphCreateVertex(GRAPH_NAME, "to1-1", v2, true); - - final VertexEntity vertex3 = driver.graphCreateVertex(GRAPH_NAME, "to1-1", v3, true); - - final VertexEntity vertex4 = driver.graphCreateVertex(GRAPH_NAME, "from1-1", v4, true); - - driver.graphCreateEdge(GRAPH_NAME, "edge-1", null, vertex1.getDocumentHandle(), vertex2.getDocumentHandle(), - new TestComplexEntity02(1, 2, 3), null); - - driver.graphCreateEdge(GRAPH_NAME, "edge-1", null, vertex1.getDocumentHandle(), vertex3.getDocumentHandle(), - new TestComplexEntity02(4, 5, 6), null); - - driver.graphCreateEdge(GRAPH_NAME, "edge-1", null, vertex4.getDocumentHandle(), vertex2.getDocumentHandle(), - new TestComplexEntity02(7, 8, 9), null); - - EdgeCursor cursor = driver.graphGetEdgeCursorByExample(GRAPH_NAME, - TestComplexEntity02.class, new TestComplexEntity01(null, null, 38)); - assertThat(cursor.getCount(), is(3)); - - cursor = driver.graphGetEdgeCursorByExample(GRAPH_NAME, TestComplexEntity02.class, v3); - assertThat(cursor.getCount(), is(1)); - assertThat(cursor.asEntityList().get(0).getClass().getName(), is(TestComplexEntity02.class.getName())); - assertThat(cursor.asEntityList().get(0).getX(), is(4)); - - } - - @Test - public void test_GetEdgesByExampleMap() throws ArangoException { - final TestComplexEntity01 v1 = new TestComplexEntity01("Homer", "A Simpson", 38); - final TestComplexEntity01 v2 = new TestComplexEntity01("Marge", "A Simpson", 36); - final TestComplexEntity01 v3 = new TestComplexEntity01("Bart", "A Simpson", 10); - final TestComplexEntity01 v4 = new TestComplexEntity01("Remoh", "Homer's twin", 38); - - final VertexEntity vertex1 = driver.graphCreateVertex(GRAPH_NAME, "from1-1", v1, true); - - final VertexEntity vertex2 = driver.graphCreateVertex(GRAPH_NAME, "to1-1", v2, true); - - final VertexEntity vertex3 = driver.graphCreateVertex(GRAPH_NAME, "to1-1", v3, true); - - final VertexEntity vertex4 = driver.graphCreateVertex(GRAPH_NAME, "from1-1", v4, true); - - driver.graphCreateEdge(GRAPH_NAME, "edge-1", null, vertex1.getDocumentHandle(), vertex2.getDocumentHandle(), - new TestComplexEntity02(1, 2, 3), null); - - driver.graphCreateEdge(GRAPH_NAME, "edge-1", null, vertex1.getDocumentHandle(), vertex3.getDocumentHandle(), - new TestComplexEntity02(4, 5, 6), null); - - driver.graphCreateEdge(GRAPH_NAME, "edge-1", null, vertex4.getDocumentHandle(), vertex2.getDocumentHandle(), - new TestComplexEntity02(7, 8, 9), null); - - final Map exampleVertex = new HashMap(); - exampleVertex.put("user", "Homer"); - - EdgeCursor cursor = driver.graphGetEdgeCursorByExample(GRAPH_NAME, - TestComplexEntity02.class, exampleVertex); - assertThat(cursor.getCount(), is(2)); - - exampleVertex.put("user", "Bart"); - cursor = driver.graphGetEdgeCursorByExample(GRAPH_NAME, TestComplexEntity02.class, exampleVertex); - assertThat(cursor.getCount(), is(1)); - assertThat(cursor.asEntityList().get(0).getClass().getName(), is(TestComplexEntity02.class.getName())); - assertThat(cursor.asEntityList().get(0).getX(), is(4)); - - } - // - // @Test - // public void test_get_edges() throws ArangoException { - // - // GraphEntity g1 = driver.createGraph("g1", "vcol1", "ecol1", true); - // DocumentEntity v1 = driver.createVertex("g1", new - // TestComplexEntity01("v1-user", "desc1", 10), null); - // DocumentEntity v2 = driver.createVertex("g1", new - // TestComplexEntity01("v2-user", "desc2", 12), null); - // DocumentEntity v3 = driver.createVertex("g1", new - // TestComplexEntity01("v2-user", "desc3", 12), null); - // DocumentEntity v4 = driver.createVertex("g1", new - // TestComplexEntity01("v2-user", "desc4", 12), null); - // - // EdgeEntity e1 = driver.createEdge("g1", null, - // v1.getDocumentHandle(), v2.getDocumentHandle(), new - // TestComplexEntity02(1,20,100), "e1", null); - // EdgeEntity e2 = driver.createEdge("g1", null, - // v1.getDocumentHandle(), v2.getDocumentHandle(), new - // TestComplexEntity02(1,20,200), "e2", null); - // EdgeEntity e3 = driver.createEdge("g1", null, - // v2.getDocumentHandle(), v3.getDocumentHandle(), new - // TestComplexEntity02(1,30,300), "e3", null); - // EdgeEntity e4 = driver.createEdge("g1", null, - // v4.getDocumentHandle(), v3.getDocumentHandle(), new - // TestComplexEntity02(1,30,400), "e4", null); - // - // HashMap> map = new - // HashMap>(); - // map.put(e1.getDocumentKey(), e1); - // map.put(e2.getDocumentKey(), e2); - // map.put(e3.getDocumentKey(), e3); - // map.put(e4.getDocumentKey(), e4); - // - // - // - // CursorEntity> cursor = - // driver.getEdges("g1", TestComplexEntity02.class); - // assertThat(cursor.getCount(), is(-1)); - // assertThat(cursor.getCode(), is(201)); - // assertThat(cursor.isError(), is(false)); - // assertThat(cursor.hasMore(), is(false)); - // assertThat(cursor.getCursorId(), is(-1L)); - // - // assertThat(cursor.getResults().size(), is(4)); - // - // EdgeEntity e0 = - // map.get(cursor.getResults().get(0).getDocumentKey()); - // assertThat(cursor.getResults().get(0).getDocumentHandle(), - // is(e0.getDocumentHandle())); - // assertThat(cursor.getResults().get(0).getDocumentRevision(), - // is(e0.getDocumentRevision())); - // assertThat(cursor.getResults().get(0).getDocumentKey(), - // is(e0.getDocumentKey())); - // assertThat(cursor.getResults().get(0).getFromVertexHandle(), - // is(e0.getFromVertexHandle())); - // assertThat(cursor.getResults().get(0).getToVertexHandle(), - // is(e0.getToVertexHandle())); - // assertThat(cursor.getResults().get(0).getEdgeLabel(), - // is(e0.getEdgeLabel())); - // assertThat(cursor.getResults().get(0).getEntity().getX(), - // is(e0.getEntity().getX())); - // assertThat(cursor.getResults().get(0).getEntity().getY(), - // is(e0.getEntity().getY())); - // assertThat(cursor.getResults().get(0).getEntity().getZ(), - // is(e0.getEntity().getZ())); - // - // } - // - // @Test - // public void test_get_edges_batchszie_limit_count() throws ArangoException - // { - // - // GraphEntity g1 = driver.createGraph("g1", "vcol1", "ecol1", true); - // DocumentEntity v1 = driver.createVertex("g1", new - // TestComplexEntity01("v1-user", "desc1", 10), null); - // DocumentEntity v2 = driver.createVertex("g1", new - // TestComplexEntity01("v2-user", "desc2", 12), null); - // DocumentEntity v3 = driver.createVertex("g1", new - // TestComplexEntity01("v2-user", "desc3", 12), null); - // DocumentEntity v4 = driver.createVertex("g1", new - // TestComplexEntity01("v2-user", "desc4", 12), null); - // - // EdgeEntity e1 = driver.createEdge("g1", null, v1.getDocumentHandle(), - // v2.getDocumentHandle(), new TestComplexEntity02(1,20,100), "e1", null); - // EdgeEntity e2 = driver.createEdge("g1", null, v1.getDocumentHandle(), - // v2.getDocumentHandle(), new TestComplexEntity02(1,20,200), "e2", null); - // EdgeEntity e3 = driver.createEdge("g1", null, v2.getDocumentHandle(), - // v3.getDocumentHandle(), new TestComplexEntity02(1,30,300), "e3", null); - // EdgeEntity e4 = driver.createEdge("g1", null, v4.getDocumentHandle(), - // v3.getDocumentHandle(), new TestComplexEntity02(1,30,400), "e4", null); - // - // Integer batchSize = 2; - // Integer limit = 3; - // Boolean count = true; - // CursorEntity> cursor = driver.getEdges( - // "g1", TestComplexEntity02.class, - // batchSize, limit, count); - // - // assertThat(cursor.getCount(), is(3)); - // assertThat(cursor.getCode(), is(201)); - // assertThat(cursor.isError(), is(false)); - // assertThat(cursor.hasMore(), is(true)); - // assertThat(cursor.getCursorId(), is(not(-1L))); - // - // assertThat(cursor.getResults().size(), is(2)); - // - // } - // - // - // @Test - // public void test_get_edges_filter_label() throws ArangoException { - // - // GraphEntity g1 = driver.createGraph("g1", "vcol1", "ecol1", true); - // DocumentEntity v1 = driver.createVertex("g1", new - // TestComplexEntity01("v1-user", "desc1", 10), null); - // DocumentEntity v2 = driver.createVertex("g1", new - // TestComplexEntity01("v2-user", "desc2", 12), null); - // DocumentEntity v3 = driver.createVertex("g1", new - // TestComplexEntity01("v2-user", "desc3", 12), null); - // DocumentEntity v4 = driver.createVertex("g1", new - // TestComplexEntity01("v2-user", "desc4", 12), null); - // - // EdgeEntity e1 = driver.createEdge("g1", null, v1.getDocumentHandle(), - // v2.getDocumentHandle(), new TestComplexEntity02(1,20,100), "e1", null); - // EdgeEntity e2 = driver.createEdge("g1", null, v1.getDocumentHandle(), - // v2.getDocumentHandle(), new TestComplexEntity02(1,20,200), "e2", null); - // EdgeEntity e3 = driver.createEdge("g1", null, v2.getDocumentHandle(), - // v3.getDocumentHandle(), new TestComplexEntity02(1,30,300), "e3", null); - // EdgeEntity e4 = driver.createEdge("g1", null, v4.getDocumentHandle(), - // v3.getDocumentHandle(), new TestComplexEntity02(1,30,400), "e4", null); - // - // CursorEntity> cursor = driver.getEdges( - // "g1", TestComplexEntity02.class, - // null, null, true, - // Arrays.asList("e1", "e2", "e3")); - // - // assertThat(cursor.getCount(), is(3)); - // assertThat(cursor.getCode(), is(201)); - // assertThat(cursor.isError(), is(false)); - // assertThat(cursor.hasMore(), is(false)); - // assertThat(cursor.getCursorId(), is(-1L)); - // - // assertThat(cursor.getResults().size(), is(3)); - // - // } - // - // - // @Test - // public void test_get_edges_filter_by_condition() throws ArangoException { - // - // GraphEntity g1 = driver.createGraph("g1", "vcol1", "ecol1", true); - // DocumentEntity v1 = driver.createVertex("g1", new - // TestComplexEntity01("v1-user", "desc1", 10), null); - // DocumentEntity v2 = driver.createVertex("g1", new - // TestComplexEntity01("v2-user", "desc2", 12), null); - // DocumentEntity v3 = driver.createVertex("g1", new - // TestComplexEntity01("v2-user", "desc3", 12), null); - // DocumentEntity v4 = driver.createVertex("g1", new - // TestComplexEntity01("v2-user", "desc4", 12), null); - // - // EdgeEntity e1 = driver.createEdge("g1", null, v1.getDocumentHandle(), - // v2.getDocumentHandle(), new TestComplexEntity02(1,20,100), "e1", null); - // EdgeEntity e2 = driver.createEdge("g1", null, v1.getDocumentHandle(), - // v2.getDocumentHandle(), new TestComplexEntity02(1,20,200), "e2", null); - // EdgeEntity e3 = driver.createEdge("g1", null, v2.getDocumentHandle(), - // v3.getDocumentHandle(), new TestComplexEntity02(1,30,300), "e3", null); - // EdgeEntity e4 = driver.createEdge("g1", null, v4.getDocumentHandle(), - // v3.getDocumentHandle(), new TestComplexEntity02(1,30,400), "e4", null); - // - // CursorEntity> cursor = driver.getEdges( - // "g1", TestComplexEntity02.class, - // null, null, true, - // null, new FilterCondition("y", 20, "=="), new FilterCondition("z", 200, - // "==")); - // // FilterCondition is AND condition. - // - // assertThat(cursor.getCount(), is(1)); - // assertThat(cursor.getCode(), is(201)); - // assertThat(cursor.isError(), is(false)); - // assertThat(cursor.hasMore(), is(false)); - // assertThat(cursor.getCursorId(), is(-1L)); - // - // assertThat(cursor.getResults().size(), is(1)); - // - // } - // - // @Test - // public void test_get_edges_filter_by_label_condition() throws - // ArangoException { - // - // GraphEntity g1 = driver.createGraph("g1", "vcol1", "ecol1", true); - // DocumentEntity v1 = driver.createVertex("g1", new - // TestComplexEntity01("v1-user", "desc1", 10), null); - // DocumentEntity v2 = driver.createVertex("g1", new - // TestComplexEntity01("v2-user", "desc2", 12), null); - // DocumentEntity v3 = driver.createVertex("g1", new - // TestComplexEntity01("v2-user", "desc3", 12), null); - // DocumentEntity v4 = driver.createVertex("g1", new - // TestComplexEntity01("v2-user", "desc4", 12), null); - // - // EdgeEntity e1 = driver.createEdge("g1", null, v1.getDocumentHandle(), - // v2.getDocumentHandle(), new TestComplexEntity02(1,20,100), "e1", null); - // EdgeEntity e2 = driver.createEdge("g1", null, v1.getDocumentHandle(), - // v2.getDocumentHandle(), new TestComplexEntity02(1,20,200), "e2", null); - // EdgeEntity e3 = driver.createEdge("g1", null, v2.getDocumentHandle(), - // v3.getDocumentHandle(), new TestComplexEntity02(1,30,300), "e3", null); - // EdgeEntity e4 = driver.createEdge("g1", null, v4.getDocumentHandle(), - // v3.getDocumentHandle(), new TestComplexEntity02(1,30,400), "e4", null); - // - // CursorEntity> cursor = driver.getEdges( - // "g1", TestComplexEntity02.class, - // null, null, true, - // Arrays.asList("e1", "e2", "e4", "e99"), new FilterCondition("y", 20, - // "=="), - // new FilterCondition("z", 200, "==")); - // // And condition: labels and filterCondition - // // (e1 OR e2 OR e4 OR e99) AND (y == 20) AND (z == 200) - // - // assertThat(cursor.getCount(), is(1)); - // assertThat(cursor.getCode(), is(201)); - // assertThat(cursor.isError(), is(false)); - // assertThat(cursor.hasMore(), is(false)); - // assertThat(cursor.getCursorId(), is(-1L)); - // - // assertThat(cursor.getResults().size(), is(1)); - // - // } - // - // - // @Test - // public void test_get_edges_filter_by_label_condition2() throws - // ArangoException { - // - // GraphEntity g1 = driver.createGraph("g1", "vcol1", "ecol1", true); - // DocumentEntity v1 = driver.createVertex("g1", new - // TestComplexEntity01("v1-user", "desc1", 10), null); - // DocumentEntity v2 = driver.createVertex("g1", new - // TestComplexEntity01("v2-user", "desc2", 12), null); - // DocumentEntity v3 = driver.createVertex("g1", new - // TestComplexEntity01("v2-user", "desc3", 12), null); - // DocumentEntity v4 = driver.createVertex("g1", new - // TestComplexEntity01("v2-user", "desc4", 12), null); - // - // EdgeEntity e1 = driver.createEdge("g1", null, v1.getDocumentHandle(), - // v2.getDocumentHandle(), new TestComplexEntity02(1,20,100), "e1", null); - // EdgeEntity e2 = driver.createEdge("g1", null, v1.getDocumentHandle(), - // v2.getDocumentHandle(), new TestComplexEntity02(1,20,200), "e2", null); - // EdgeEntity e3 = driver.createEdge("g1", null, v2.getDocumentHandle(), - // v3.getDocumentHandle(), new TestComplexEntity02(1,30,300), "e3", null); - // EdgeEntity e4 = driver.createEdge("g1", null, v4.getDocumentHandle(), - // v3.getDocumentHandle(), new TestComplexEntity02(1,30,400), "e4", null); - // - // CursorEntity> cursor = driver.getEdges( - // "g1", TestComplexEntity02.class, - // null, null, true, - // Arrays.asList("e1", "e4"), new FilterCondition("y", 20, "=="), new - // FilterCondition("z", 200, "==")); - // // And condition: labels and filterCondition - // // (e1 OR e4) AND (y == 20) AND (z == 200) - // - // assertThat(cursor.getCount(), is(0)); - // assertThat(cursor.getCode(), is(201)); - // assertThat(cursor.isError(), is(false)); - // assertThat(cursor.hasMore(), is(false)); - // assertThat(cursor.getCursorId(), is(-1L)); - // - // assertThat(cursor.getResults().size(), is(0)); - // - // } - // - // @Test - // public void test_get_edges_batchSize_server_limit_1000() throws - // ArangoException { - // - // GraphEntity g1 = driver.createGraph("g1", "vcol1", "ecol1", true); - // DocumentEntity v1 = driver.createVertex("g1", new - // TestComplexEntity01("v1-user", "desc1", 10), null); - // DocumentEntity v2 = driver.createVertex("g1", new - // TestComplexEntity01("v2-user", "desc2", 12), null); - // - // for (int i = 0; i < 1010; i++) { - // EdgeEntity e1 = driver.createEdge("g1", null, v1.getDocumentHandle(), - // v2.getDocumentHandle(), new TestComplexEntity02(1,20,100), "e1", null); - // } - // - // Integer batchSize = null; - // Integer limit = null; - // Boolean count = true; - // CursorEntity> cursor = driver.getEdges( - // "g1", TestComplexEntity02.class, - // batchSize, limit, count); - // - // assertThat(cursor.getCount(), is(1010)); - // assertThat(cursor.getCode(), is(201)); - // assertThat(cursor.isError(), is(false)); - // assertThat(cursor.hasMore(), is(true)); - // assertThat(cursor.getCursorId(), is(not(-1L))); - // - // assertThat(cursor.getResults().size(), is(1000)); - // - // } - // - // @Test - // public void test_get_edges_graph_not_found() throws ArangoException { - // - // try { - // CursorEntity> cursor = - // driver.getEdges("g1", TestComplexEntity02.class); - // fail(); - // } catch (ArangoException e) { - // assertThat(e.getCode(), is(404)); - // assertThat(e.getErrorNumber(), is(1901)); - // assertThat(e.getErrorMessage(), startsWith("no graph named")); - // } - // - // } - // - // - // @Test - // public void test_get_edges_result_set() throws ArangoException { - // - // GraphEntity g1 = driver.createGraph("g1", "vcol1", "ecol1", true); - // DocumentEntity v1 = driver.createVertex("g1", new - // TestComplexEntity01("v1-user", "desc1", 10), null); - // DocumentEntity v2 = driver.createVertex("g1", new - // TestComplexEntity01("v2-user", "desc2", 12), null); - // DocumentEntity v3 = driver.createVertex("g1", new - // TestComplexEntity01("v2-user", "desc3", 12), null); - // DocumentEntity v4 = driver.createVertex("g1", new - // TestComplexEntity01("v2-user", "desc4", 12), null); - // - // EdgeEntity e1 = driver.createEdge("g1", null, - // v1.getDocumentHandle(), v2.getDocumentHandle(), new - // TestComplexEntity02(1,20,100), "e1", null); - // EdgeEntity e2 = driver.createEdge("g1", null, - // v1.getDocumentHandle(), v2.getDocumentHandle(), new - // TestComplexEntity02(1,20,200), "e2", null); - // EdgeEntity e3 = driver.createEdge("g1", null, - // v2.getDocumentHandle(), v3.getDocumentHandle(), new - // TestComplexEntity02(1,30,300), "e3", null); - // EdgeEntity e4 = driver.createEdge("g1", null, - // v4.getDocumentHandle(), v3.getDocumentHandle(), new - // TestComplexEntity02(1,30,400), "e4", null); - // - // HashMap> map = new - // HashMap>(); - // map.put(e1.getDocumentKey(), e1); - // map.put(e2.getDocumentKey(), e2); - // map.put(e3.getDocumentKey(), e3); - // map.put(e4.getDocumentKey(), e4); - // - // CursorResultSet> rs = - // driver.getEdgesWithResultSet("g1", TestComplexEntity02.class, - // 2, 10, true); - // assertThat(rs.getTotalCount(), is(4)); // count = true - // - // while (rs.hasNext()) { - // - // EdgeEntity e = rs.next(); - // EdgeEntity e0 = map.get(e.getDocumentKey()); - // - // assertThat(e.getDocumentHandle(), is(e0.getDocumentHandle())); - // assertThat(e.getDocumentRevision(), is(e0.getDocumentRevision())); - // assertThat(e.getDocumentKey(), is(e0.getDocumentKey())); - // assertThat(e.getFromVertexHandle(), is(e0.getFromVertexHandle())); - // assertThat(e.getToVertexHandle(), is(e0.getToVertexHandle())); - // assertThat(e.getEdgeLabel(), is(e0.getEdgeLabel())); - // assertThat(e.getEntity().getX(), is(e0.getEntity().getX())); - // assertThat(e.getEntity().getY(), is(e0.getEntity().getY())); - // assertThat(e.getEntity().getZ(), is(e0.getEntity().getZ())); - // - // } - // - // } - // - // // ----- with vertex - // - // @Test - // public void test_get_edges_v() throws ArangoException { - // - // GraphEntity g1 = driver.createGraph("g1", "vcol1", "ecol1", true); - // DocumentEntity v1 = driver.createVertex("g1", new - // TestComplexEntity01("v1-user", "desc1", 10), null); - // DocumentEntity v2 = driver.createVertex("g1", new - // TestComplexEntity01("v2-user", "desc2", 12), null); - // DocumentEntity v3 = driver.createVertex("g1", new - // TestComplexEntity01("v2-user", "desc3", 12), null); - // DocumentEntity v4 = driver.createVertex("g1", new - // TestComplexEntity01("v2-user", "desc4", 12), null); - // - // EdgeEntity e1 = driver.createEdge("g1", null, - // v1.getDocumentHandle(), v2.getDocumentHandle(), new - // TestComplexEntity02(1,20,100), "e1", null); - // EdgeEntity e2 = driver.createEdge("g1", null, - // v1.getDocumentHandle(), v2.getDocumentHandle(), new - // TestComplexEntity02(1,20,200), "e2", null); - // EdgeEntity e3 = driver.createEdge("g1", null, - // v2.getDocumentHandle(), v3.getDocumentHandle(), new - // TestComplexEntity02(1,30,300), "e3", null); - // EdgeEntity e4 = driver.createEdge("g1", null, - // v4.getDocumentHandle(), v3.getDocumentHandle(), new - // TestComplexEntity02(1,30,400), "e4", null); - // - // HashMap> map = new - // HashMap>(); - // map.put(e1.getDocumentKey(), e1); - // map.put(e2.getDocumentKey(), e2); - // map.put(e3.getDocumentKey(), e3); - // map.put(e4.getDocumentKey(), e4); - // - // - // - // CursorEntity> cursor = - // driver.getEdges("g1", v2.getDocumentKey(), TestComplexEntity02.class); - // assertThat(cursor.getCount(), is(-1)); - // assertThat(cursor.getCode(), is(201)); - // assertThat(cursor.isError(), is(false)); - // assertThat(cursor.hasMore(), is(false)); - // assertThat(cursor.getCursorId(), is(-1L)); - // - // assertThat(cursor.getResults().size(), is(3)); - // - // EdgeEntity e0 = - // map.get(cursor.getResults().get(0).getDocumentKey()); - // assertThat(cursor.getResults().get(0).getDocumentHandle(), - // is(e0.getDocumentHandle())); - // assertThat(cursor.getResults().get(0).getDocumentRevision(), - // is(e0.getDocumentRevision())); - // assertThat(cursor.getResults().get(0).getDocumentKey(), - // is(e0.getDocumentKey())); - // assertThat(cursor.getResults().get(0).getFromVertexHandle(), - // is(e0.getFromVertexHandle())); - // assertThat(cursor.getResults().get(0).getToVertexHandle(), - // is(e0.getToVertexHandle())); - // assertThat(cursor.getResults().get(0).getEdgeLabel(), - // is(e0.getEdgeLabel())); - // assertThat(cursor.getResults().get(0).getEntity().getX(), - // is(e0.getEntity().getX())); - // assertThat(cursor.getResults().get(0).getEntity().getY(), - // is(e0.getEntity().getY())); - // assertThat(cursor.getResults().get(0).getEntity().getZ(), - // is(e0.getEntity().getZ())); - // - // Set act = new - // HashSet(Arrays.asList(cursor.getResults().get(0).getEdgeLabel(), - // cursor.getResults().get(1).getEdgeLabel(), - // cursor.getResults().get(2).getEdgeLabel())); - // Set ans = new HashSet(Arrays.asList("e1", "e2", "e3")); - // assertThat(act, is(ans)); - // - // } - // - // - // @Test - // public void test_get_edges_v_batchSize_limit_count() throws - // ArangoException - // { - // - // GraphEntity g1 = driver.createGraph("g1", "vcol1", "ecol1", true); - // DocumentEntity v1 = driver.createVertex("g1", new - // TestComplexEntity01("v1-user", "desc1", 10), null); - // DocumentEntity v2 = driver.createVertex("g1", new - // TestComplexEntity01("v2-user", "desc2", 12), null); - // DocumentEntity v3 = driver.createVertex("g1", new - // TestComplexEntity01("v2-user", "desc3", 12), null); - // DocumentEntity v4 = driver.createVertex("g1", new - // TestComplexEntity01("v2-user", "desc4", 12), null); - // - // EdgeEntity e1 = driver.createEdge("g1", null, - // v1.getDocumentHandle(), v2.getDocumentHandle(), new - // TestComplexEntity02(1,20,100), "e1", null); - // EdgeEntity e2 = driver.createEdge("g1", null, - // v1.getDocumentHandle(), v2.getDocumentHandle(), new - // TestComplexEntity02(1,20,200), "e2", null); - // EdgeEntity e3 = driver.createEdge("g1", null, - // v2.getDocumentHandle(), v3.getDocumentHandle(), new - // TestComplexEntity02(1,30,300), "e3", null); - // EdgeEntity e4 = driver.createEdge("g1", null, - // v4.getDocumentHandle(), v3.getDocumentHandle(), new - // TestComplexEntity02(1,30,400), "e4", null); - // - // HashMap> map = new - // HashMap>(); - // map.put(e1.getDocumentKey(), e1); - // map.put(e2.getDocumentKey(), e2); - // map.put(e3.getDocumentKey(), e3); - // map.put(e4.getDocumentKey(), e4); - // - // - // - // CursorEntity> cursor = - // driver.getEdges("g1", v2.getDocumentKey(), TestComplexEntity02.class, - // 1, 2, true); - // assertThat(cursor.getCount(), is(2)); - // assertThat(cursor.getCode(), is(201)); - // assertThat(cursor.isError(), is(false)); - // assertThat(cursor.hasMore(), is(true)); - // assertThat(cursor.getCursorId(), is(not(-1L))); - // - // assertThat(cursor.getResults().size(), is(1)); - // - // EdgeEntity e0 = - // map.get(cursor.getResults().get(0).getDocumentKey()); - // assertThat(cursor.getResults().get(0).getDocumentHandle(), - // is(e0.getDocumentHandle())); - // assertThat(cursor.getResults().get(0).getDocumentRevision(), - // is(e0.getDocumentRevision())); - // assertThat(cursor.getResults().get(0).getDocumentKey(), - // is(e0.getDocumentKey())); - // assertThat(cursor.getResults().get(0).getFromVertexHandle(), - // is(e0.getFromVertexHandle())); - // assertThat(cursor.getResults().get(0).getToVertexHandle(), - // is(e0.getToVertexHandle())); - // assertThat(cursor.getResults().get(0).getEdgeLabel(), - // is(e0.getEdgeLabel())); - // assertThat(cursor.getResults().get(0).getEntity().getX(), - // is(e0.getEntity().getX())); - // assertThat(cursor.getResults().get(0).getEntity().getY(), - // is(e0.getEntity().getY())); - // assertThat(cursor.getResults().get(0).getEntity().getZ(), - // is(e0.getEntity().getZ())); - // - // } - // - // - // @Test - // public void test_get_edges_v_direction_in() throws ArangoException { - // - // GraphEntity g1 = driver.createGraph("g1", "vcol1", "ecol1", true); - // DocumentEntity v1 = driver.createVertex("g1", new - // TestComplexEntity01("v1-user", "desc1", 10), null); - // DocumentEntity v2 = driver.createVertex("g1", new - // TestComplexEntity01("v2-user", "desc2", 12), null); - // DocumentEntity v3 = driver.createVertex("g1", new - // TestComplexEntity01("v2-user", "desc3", 12), null); - // DocumentEntity v4 = driver.createVertex("g1", new - // TestComplexEntity01("v2-user", "desc4", 12), null); - // - // EdgeEntity e1 = driver.createEdge("g1", null, - // v1.getDocumentHandle(), v2.getDocumentHandle(), new - // TestComplexEntity02(1,20,100), "e1", null); - // EdgeEntity e2 = driver.createEdge("g1", null, - // v1.getDocumentHandle(), v2.getDocumentHandle(), new - // TestComplexEntity02(1,20,200), "e2", null); - // EdgeEntity e3 = driver.createEdge("g1", null, - // v2.getDocumentHandle(), v3.getDocumentHandle(), new - // TestComplexEntity02(1,30,300), "e3", null); - // EdgeEntity e4 = driver.createEdge("g1", null, - // v4.getDocumentHandle(), v3.getDocumentHandle(), new - // TestComplexEntity02(1,30,400), "e4", null); - // - // // V2[IN] - // CursorEntity> cursor = driver.getEdges( - // "g1", v2.getDocumentKey(), TestComplexEntity02.class, - // null, null, true, - // Direction.IN, null); - // assertThat(cursor.getCount(), is(2)); - // assertThat(cursor.getCode(), is(201)); - // assertThat(cursor.isError(), is(false)); - // assertThat(cursor.hasMore(), is(false)); - // assertThat(cursor.getCursorId(), is(-1L)); - // - // - // assertThat(cursor.getResults().size(), is(2)); - // assertThat(asSet(cursor.getResults()), is(asSet(e1.getDocumentKey(), - // e2.getDocumentKey()))); - // - // } - // - // @Test - // public void test_get_edges_v_direction_out() throws ArangoException { - // - // GraphEntity g1 = driver.createGraph("g1", "vcol1", "ecol1", true); - // DocumentEntity v1 = driver.createVertex("g1", new - // TestComplexEntity01("v1-user", "desc1", 10), null); - // DocumentEntity v2 = driver.createVertex("g1", new - // TestComplexEntity01("v2-user", "desc2", 12), null); - // DocumentEntity v3 = driver.createVertex("g1", new - // TestComplexEntity01("v2-user", "desc3", 12), null); - // DocumentEntity v4 = driver.createVertex("g1", new - // TestComplexEntity01("v2-user", "desc4", 12), null); - // - // EdgeEntity e1 = driver.createEdge("g1", null, - // v1.getDocumentHandle(), v2.getDocumentHandle(), new - // TestComplexEntity02(1,20,100), "e1", null); - // EdgeEntity e2 = driver.createEdge("g1", null, - // v1.getDocumentHandle(), v2.getDocumentHandle(), new - // TestComplexEntity02(1,20,200), "e2", null); - // EdgeEntity e3 = driver.createEdge("g1", null, - // v2.getDocumentHandle(), v3.getDocumentHandle(), new - // TestComplexEntity02(1,30,300), "e3", null); - // EdgeEntity e4 = driver.createEdge("g1", null, - // v4.getDocumentHandle(), v3.getDocumentHandle(), new - // TestComplexEntity02(1,30,400), "e4", null); - // - // // V2[OUT] - // CursorEntity> cursor = driver.getEdges( - // "g1", v2.getDocumentKey(), TestComplexEntity02.class, - // null, null, true, - // Direction.OUT, null); - // - // assertThat(cursor.getCount(), is(1)); - // assertThat(cursor.getCode(), is(201)); - // assertThat(cursor.isError(), is(false)); - // assertThat(cursor.hasMore(), is(false)); - // assertThat(cursor.getCursorId(), is(-1L)); - // - // assertThat(cursor.getResults().size(), is(1)); - // assertThat(asSet(cursor.getResults()), is(asSet(e3.getDocumentKey()))); - // - // } - // - // @Test - // public void test_get_edges_v_direction_any() throws ArangoException { - // - // GraphEntity g1 = driver.createGraph("g1", "vcol1", "ecol1", true); - // DocumentEntity v1 = driver.createVertex("g1", new - // TestComplexEntity01("v1-user", "desc1", 10), null); - // DocumentEntity v2 = driver.createVertex("g1", new - // TestComplexEntity01("v2-user", "desc2", 12), null); - // DocumentEntity v3 = driver.createVertex("g1", new - // TestComplexEntity01("v2-user", "desc3", 12), null); - // DocumentEntity v4 = driver.createVertex("g1", new - // TestComplexEntity01("v2-user", "desc4", 12), null); - // - // EdgeEntity e1 = driver.createEdge("g1", null, - // v1.getDocumentHandle(), v2.getDocumentHandle(), new - // TestComplexEntity02(1,20,100), "e1", null); - // EdgeEntity e2 = driver.createEdge("g1", null, - // v1.getDocumentHandle(), v2.getDocumentHandle(), new - // TestComplexEntity02(1,20,200), "e2", null); - // EdgeEntity e3 = driver.createEdge("g1", null, - // v2.getDocumentHandle(), v3.getDocumentHandle(), new - // TestComplexEntity02(1,30,300), "e3", null); - // EdgeEntity e4 = driver.createEdge("g1", null, - // v4.getDocumentHandle(), v3.getDocumentHandle(), new - // TestComplexEntity02(1,30,400), "e4", null); - // - // // V2[ANY] - // CursorEntity> cursor = driver.getEdges( - // "g1", v2.getDocumentKey(), TestComplexEntity02.class, - // null, null, true, - // Direction.ANY, null); - // - // assertThat(cursor.getCount(), is(3)); - // assertThat(cursor.getCode(), is(201)); - // assertThat(cursor.isError(), is(false)); - // assertThat(cursor.hasMore(), is(false)); - // assertThat(cursor.getCursorId(), is(-1L)); - // - // assertThat(cursor.getResults().size(), is(3)); - // assertThat(asSet(cursor.getResults()), is(asSet(e1.getDocumentKey(), - // e2.getDocumentKey(), e3.getDocumentKey()))); - // - // } - // - // @Test - // public void test_get_edges_v_direction_in_filter() throws ArangoException - // { - // - // GraphEntity g1 = driver.createGraph("g1", "vcol1", "ecol1", true); - // DocumentEntity v1 = driver.createVertex("g1", new - // TestComplexEntity01("v1-user", "desc1", 10), null); - // DocumentEntity v2 = driver.createVertex("g1", new - // TestComplexEntity01("v2-user", "desc2", 12), null); - // DocumentEntity v3 = driver.createVertex("g1", new - // TestComplexEntity01("v2-user", "desc3", 12), null); - // DocumentEntity v4 = driver.createVertex("g1", new - // TestComplexEntity01("v2-user", "desc4", 12), null); - // - // EdgeEntity e1 = driver.createEdge("g1", null, - // v1.getDocumentHandle(), v2.getDocumentHandle(), new - // TestComplexEntity02(1,20,100), "e1", null); - // EdgeEntity e2 = driver.createEdge("g1", null, - // v1.getDocumentHandle(), v2.getDocumentHandle(), new - // TestComplexEntity02(1,20,200), "e2", null); - // EdgeEntity e3 = driver.createEdge("g1", null, - // v2.getDocumentHandle(), v3.getDocumentHandle(), new - // TestComplexEntity02(1,30,300), "e3", null); - // EdgeEntity e4 = driver.createEdge("g1", null, - // v4.getDocumentHandle(), v3.getDocumentHandle(), new - // TestComplexEntity02(1,30,400), "e4", null); - // EdgeEntity e5 = driver.createEdge("g1", null, - // v1.getDocumentHandle(), v2.getDocumentHandle(), new - // TestComplexEntity02(1,40,500), "e5", null); - // EdgeEntity e6 = driver.createEdge("g1", null, - // v1.getDocumentHandle(), v2.getDocumentHandle(), new - // TestComplexEntity02(1,40,600), "e6", null); - // EdgeEntity e7 = driver.createEdge("g1", null, - // v1.getDocumentHandle(), v2.getDocumentHandle(), new - // TestComplexEntity02(1,40,700), "e7", null); - // EdgeEntity e8 = driver.createEdge("g1", null, - // v1.getDocumentHandle(), v2.getDocumentHandle(), new - // TestComplexEntity02(1,40,800), "e8", null); - // - // // V2[IN] - // CursorEntity> cursor = driver.getEdges( - // "g1", v2.getDocumentKey(), TestComplexEntity02.class, - // null, null, true, - // Direction.IN, Arrays.asList("e1", "e5", "e6", "e8"), new - // FilterCondition("z", 600, ">="), new FilterCondition("z", 800, "<")); - // // IN: e[1,2,5,6,7,8] - // // LABEL: e[1,5,6,8] - // // FILTER: z>=600 ->e[6,7,8] - // // FILTER: z<800 ->e[6,7] - // // -> e6 - // - // assertThat(cursor.getCount(), is(1)); - // assertThat(cursor.getCode(), is(201)); - // assertThat(cursor.isError(), is(false)); - // assertThat(cursor.hasMore(), is(false)); - // assertThat(cursor.getCursorId(), is(-1L)); - // - // assertThat(cursor.getResults().size(), is(1)); - // assertThat(asSet(cursor.getResults()), is(asSet(e6.getDocumentKey()))); - // - // } - // - // - // @Test - // public void test_get_edges_v_direction_in_filter_rs() throws - // ArangoException { - // - // GraphEntity g1 = driver.createGraph("g1", "vcol1", "ecol1", true); - // DocumentEntity v1 = driver.createVertex("g1", new - // TestComplexEntity01("v1-user", "desc1", 10), null); - // DocumentEntity v2 = driver.createVertex("g1", new - // TestComplexEntity01("v2-user", "desc2", 12), null); - // DocumentEntity v3 = driver.createVertex("g1", new - // TestComplexEntity01("v2-user", "desc3", 12), null); - // DocumentEntity v4 = driver.createVertex("g1", new - // TestComplexEntity01("v2-user", "desc4", 12), null); - // - // EdgeEntity e1 = driver.createEdge("g1", null, - // v1.getDocumentHandle(), v2.getDocumentHandle(), new - // TestComplexEntity02(1,20,100), "e1", null); - // EdgeEntity e2 = driver.createEdge("g1", null, - // v1.getDocumentHandle(), v2.getDocumentHandle(), new - // TestComplexEntity02(1,20,200), "e2", null); - // EdgeEntity e3 = driver.createEdge("g1", null, - // v2.getDocumentHandle(), v3.getDocumentHandle(), new - // TestComplexEntity02(1,30,300), "e3", null); - // EdgeEntity e4 = driver.createEdge("g1", null, - // v4.getDocumentHandle(), v3.getDocumentHandle(), new - // TestComplexEntity02(1,30,400), "e4", null); - // EdgeEntity e5 = driver.createEdge("g1", null, - // v1.getDocumentHandle(), v2.getDocumentHandle(), new - // TestComplexEntity02(1,40,500), "e5", null); - // EdgeEntity e6 = driver.createEdge("g1", null, - // v1.getDocumentHandle(), v2.getDocumentHandle(), new - // TestComplexEntity02(1,40,600), "e6", null); - // EdgeEntity e7 = driver.createEdge("g1", null, - // v1.getDocumentHandle(), v2.getDocumentHandle(), new - // TestComplexEntity02(1,40,700), "e7", null); - // EdgeEntity e8 = driver.createEdge("g1", null, - // v1.getDocumentHandle(), v2.getDocumentHandle(), new - // TestComplexEntity02(1,40,800), "e8", null); - // - // // V2[IN] - // CursorResultSet> rs = - // driver.getEdgesWithResultSet( - // "g1", v2.getDocumentKey(), TestComplexEntity02.class, - // null, null, true, - // Direction.IN, Arrays.asList("e1", "e5", "e6", "e8"), new - // FilterCondition("z", 600, ">="), new FilterCondition("z", 800, "<")); - // // IN: e[1,2,5,6,7,8] - // // LABEL: e[1,5,6,8] - // // FILTER: z>=600 ->e[6,7,8] - // // FILTER: z<800 ->e[6,7] - // // -> e6 - // - // assertThat(rs.getTotalCount(), is(1)); - // - // EdgeEntity edge = rs.next(); - // - // assertThat(edge.getDocumentHandle(), is(e6.getDocumentHandle())); - // assertThat(edge.getDocumentRevision(), is(e6.getDocumentRevision())); - // assertThat(edge.getDocumentKey(), is(e6.getDocumentKey())); - // assertThat(edge.getFromVertexHandle(), is(e6.getFromVertexHandle())); - // assertThat(edge.getToVertexHandle(), is(e6.getToVertexHandle())); - // assertThat(edge.getEdgeLabel(), is(e6.getEdgeLabel())); - // assertThat(edge.getEntity().getX(), is(e6.getEntity().getX())); - // assertThat(edge.getEntity().getY(), is(e6.getEntity().getY())); - // assertThat(edge.getEntity().getZ(), is(e6.getEntity().getZ())); - // - // - // } - // - // -} diff --git a/src/test/java/com/arangodb/ArangoDriverGraphShortestPathTest.java b/src/test/java/com/arangodb/ArangoDriverGraphShortestPathTest.java deleted file mode 100644 index 3b1f61b49..000000000 --- a/src/test/java/com/arangodb/ArangoDriverGraphShortestPathTest.java +++ /dev/null @@ -1,225 +0,0 @@ -package com.arangodb; - -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import com.arangodb.entity.EdgeEntity; -import com.arangodb.entity.ShortestPathEntity; -import com.arangodb.entity.marker.VertexEntity; -import com.arangodb.util.ShortestPathOptions; - -/** - * @author Mark - mark@arangodb.com - * - */ -public class ArangoDriverGraphShortestPathTest extends BaseGraphTest { - - private static final String GRAPH_NAME = "UnitTestGraph"; - - @Before - public void setup() { - try { - driver.deleteGraph(GRAPH_NAME); - } catch (ArangoException e1) { - } - try { - driver.createGraph(GRAPH_NAME, this.createEdgeDefinitions(1, 0), this.createOrphanCollections(0), true); - } catch (final ArangoException e) { - } - } - - @After - public void cleanup() { - try { - driver.deleteGraph(GRAPH_NAME); - } catch (ArangoException e1) { - } - } - - @Test - public void shortestPath() throws ArangoException { - final TestComplexEntity01 v1 = new TestComplexEntity01("Homer", "A Simpson", 38); - final TestComplexEntity01 v2 = new TestComplexEntity01("Marge", "A Simpson", 36); - final TestComplexEntity01 v3 = new TestComplexEntity01("Bart", "A Simpson", 10); - final TestComplexEntity01 v4 = new TestComplexEntity01("Remoh", "Homer's twin", 38); - - final VertexEntity vertex1 = driver.graphCreateVertex(GRAPH_NAME, "from1-1", v1, true); - final VertexEntity vertex2 = driver.graphCreateVertex(GRAPH_NAME, "to1-1", v2, true); - final VertexEntity vertex3 = driver.graphCreateVertex(GRAPH_NAME, "to1-1", v3, true); - final VertexEntity vertex4 = driver.graphCreateVertex(GRAPH_NAME, "from1-1", v4, true); - - final TestComplexEntity02 e1 = new TestComplexEntity02(1, 2, 3); - driver.graphCreateEdge(GRAPH_NAME, "edge-1", null, vertex1.getDocumentHandle(), vertex2.getDocumentHandle(), e1, - null); - - final TestComplexEntity02 e2 = new TestComplexEntity02(4, 5, 6); - driver.graphCreateEdge(GRAPH_NAME, "edge-1", null, vertex1.getDocumentHandle(), vertex3.getDocumentHandle(), e2, - null); - - final TestComplexEntity02 e3 = new TestComplexEntity02(7, 8, 9); - driver.graphCreateEdge(GRAPH_NAME, "edge-1", null, vertex4.getDocumentHandle(), vertex2.getDocumentHandle(), e3, - null); - - final TestComplexEntity02 e4 = new TestComplexEntity02(10, 11, 12); - driver.graphCreateEdge(GRAPH_NAME, "edge-1", null, vertex4.getDocumentHandle(), vertex3.getDocumentHandle(), e4, - null); - - final ShortestPathOptions shortestPathOptions = new ShortestPathOptions(); - { - final ShortestPathEntity entity = driver.graphGetShortestPath( - GRAPH_NAME, v1, v2, shortestPathOptions, TestComplexEntity01.class, TestComplexEntity02.class); - Assert.assertEquals(201, entity.getCode()); - Assert.assertEquals(1, entity.getEdges().size()); - Assert.assertEquals(2, entity.getVertices().size()); - Assert.assertEquals(1L, entity.getDistance().longValue()); - } - { - final ShortestPathEntity entity = driver.graphGetShortestPath( - GRAPH_NAME, v1, v4, shortestPathOptions, TestComplexEntity01.class, TestComplexEntity02.class); - Assert.assertEquals(201, entity.getCode()); - Assert.assertEquals(2, entity.getEdges().size()); - Assert.assertEquals(3, entity.getVertices().size()); - Assert.assertEquals(2L, entity.getDistance().longValue()); - } - } - - @Test - public void shortestPathDirectionOut() throws ArangoException { - final TestComplexEntity01 v1 = new TestComplexEntity01("Homer", "A Simpson", 38); - final TestComplexEntity01 v2 = new TestComplexEntity01("Marge", "A Simpson", 36); - final TestComplexEntity01 v3 = new TestComplexEntity01("Bart", "A Simpson", 10); - final TestComplexEntity01 v4 = new TestComplexEntity01("Remoh", "Homer's twin", 38); - - final VertexEntity vertex1 = driver.graphCreateVertex(GRAPH_NAME, "from1-1", v1, true); - final VertexEntity vertex2 = driver.graphCreateVertex(GRAPH_NAME, "to1-1", v2, true); - final VertexEntity vertex3 = driver.graphCreateVertex(GRAPH_NAME, "to1-1", v3, true); - final VertexEntity vertex4 = driver.graphCreateVertex(GRAPH_NAME, "from1-1", v4, true); - - final TestComplexEntity02 e1 = new TestComplexEntity02(1, 2, 3); - driver.graphCreateEdge(GRAPH_NAME, "edge-1", null, vertex1.getDocumentHandle(), vertex2.getDocumentHandle(), e1, - null); - - final TestComplexEntity02 e2 = new TestComplexEntity02(4, 5, 6); - driver.graphCreateEdge(GRAPH_NAME, "edge-1", null, vertex1.getDocumentHandle(), vertex3.getDocumentHandle(), e2, - null); - - final TestComplexEntity02 e3 = new TestComplexEntity02(7, 8, 9); - driver.graphCreateEdge(GRAPH_NAME, "edge-1", null, vertex4.getDocumentHandle(), vertex2.getDocumentHandle(), e3, - null); - - final TestComplexEntity02 e4 = new TestComplexEntity02(10, 11, 12); - driver.graphCreateEdge(GRAPH_NAME, "edge-1", null, vertex4.getDocumentHandle(), vertex3.getDocumentHandle(), e4, - null); - - final ShortestPathOptions shortestPathOptions = new ShortestPathOptions(); - shortestPathOptions.setDirection(Direction.OUTBOUND); - { - final ShortestPathEntity entity = driver.graphGetShortestPath( - GRAPH_NAME, v1, v2, shortestPathOptions, TestComplexEntity01.class, TestComplexEntity02.class); - Assert.assertEquals(201, entity.getCode()); - Assert.assertEquals(1, entity.getEdges().size()); - Assert.assertEquals(2, entity.getVertices().size()); - } - { - final ShortestPathEntity entity = driver.graphGetShortestPath( - GRAPH_NAME, v1, v4, shortestPathOptions, TestComplexEntity01.class, TestComplexEntity02.class); - Assert.assertEquals(201, entity.getCode()); - Assert.assertNull(entity.getEdges()); - Assert.assertNull(entity.getVertices()); - } - } - - @Test - public void shortestPathDirectionIn() throws ArangoException { - final TestComplexEntity01 v1 = new TestComplexEntity01("Homer", "A Simpson", 38); - final TestComplexEntity01 v2 = new TestComplexEntity01("Marge", "A Simpson", 36); - final TestComplexEntity01 v3 = new TestComplexEntity01("Bart", "A Simpson", 10); - final TestComplexEntity01 v4 = new TestComplexEntity01("Remoh", "Homer's twin", 38); - - final VertexEntity vertex1 = driver.graphCreateVertex(GRAPH_NAME, "from1-1", v1, true); - final VertexEntity vertex2 = driver.graphCreateVertex(GRAPH_NAME, "to1-1", v2, true); - final VertexEntity vertex3 = driver.graphCreateVertex(GRAPH_NAME, "to1-1", v3, true); - final VertexEntity vertex4 = driver.graphCreateVertex(GRAPH_NAME, "from1-1", v4, true); - - final TestComplexEntity02 e1 = new TestComplexEntity02(1, 2, 3); - driver.graphCreateEdge(GRAPH_NAME, "edge-1", null, vertex1.getDocumentHandle(), vertex2.getDocumentHandle(), e1, - null); - - final TestComplexEntity02 e2 = new TestComplexEntity02(4, 5, 6); - driver.graphCreateEdge(GRAPH_NAME, "edge-1", null, vertex1.getDocumentHandle(), vertex3.getDocumentHandle(), e2, - null); - - final TestComplexEntity02 e3 = new TestComplexEntity02(7, 8, 9); - driver.graphCreateEdge(GRAPH_NAME, "edge-1", null, vertex4.getDocumentHandle(), vertex2.getDocumentHandle(), e3, - null); - - final TestComplexEntity02 e4 = new TestComplexEntity02(10, 11, 12); - driver.graphCreateEdge(GRAPH_NAME, "edge-1", null, vertex4.getDocumentHandle(), vertex3.getDocumentHandle(), e4, - null); - - final ShortestPathOptions shortestPathOptions = new ShortestPathOptions(); - shortestPathOptions.setDirection(Direction.INBOUND); - { - final ShortestPathEntity entity = driver.graphGetShortestPath( - GRAPH_NAME, v1, v2, shortestPathOptions, TestComplexEntity01.class, TestComplexEntity02.class); - Assert.assertEquals(201, entity.getCode()); - Assert.assertNull(entity.getEdges()); - Assert.assertNull(entity.getVertices()); - } - { - final ShortestPathEntity entity = driver.graphGetShortestPath( - GRAPH_NAME, v1, v4, shortestPathOptions, TestComplexEntity01.class, TestComplexEntity02.class); - Assert.assertEquals(201, entity.getCode()); - Assert.assertNull(entity.getEdges()); - Assert.assertNull(entity.getVertices()); - } - } - - @Test - public void shortestPathWeigth() throws ArangoException { - final TestComplexEntity01 v1 = new TestComplexEntity01("Homer", "A Simpson", 38); - final TestComplexEntity01 v2 = new TestComplexEntity01("Marge", "A Simpson", 36); - final TestComplexEntity01 v3 = new TestComplexEntity01("Bart", "A Simpson", 10); - final TestComplexEntity01 v4 = new TestComplexEntity01("Remoh", "Homer's twin", 38); - - final VertexEntity vertex1 = driver.graphCreateVertex(GRAPH_NAME, "from1-1", v1, true); - final VertexEntity vertex2 = driver.graphCreateVertex(GRAPH_NAME, "to1-1", v2, true); - final VertexEntity vertex3 = driver.graphCreateVertex(GRAPH_NAME, "to1-1", v3, true); - final VertexEntity vertex4 = driver.graphCreateVertex(GRAPH_NAME, "from1-1", v4, true); - - int x1 = 1; - final TestComplexEntity02 e1 = new TestComplexEntity02(x1, 2, 3); - EdgeEntity edge1 = driver.graphCreateEdge(GRAPH_NAME, "edge-1", null, - vertex1.getDocumentHandle(), vertex2.getDocumentHandle(), e1, null); - - final TestComplexEntity02 e2 = new TestComplexEntity02(4, 5, 6); - driver.graphCreateEdge(GRAPH_NAME, "edge-1", null, vertex1.getDocumentHandle(), vertex3.getDocumentHandle(), e2, - null); - - int x3 = 7; - final TestComplexEntity02 e3 = new TestComplexEntity02(x3, 8, 9); - EdgeEntity edge3 = driver.graphCreateEdge(GRAPH_NAME, "edge-1", null, - vertex4.getDocumentHandle(), vertex2.getDocumentHandle(), e3, null); - - final TestComplexEntity02 e4 = new TestComplexEntity02(10, 11, 12); - driver.graphCreateEdge(GRAPH_NAME, "edge-1", null, vertex4.getDocumentHandle(), vertex3.getDocumentHandle(), e4, - null); - - final ShortestPathOptions shortestPathOptions = new ShortestPathOptions(); - shortestPathOptions.setWeight("x"); - { - final ShortestPathEntity entity = driver.graphGetShortestPath( - GRAPH_NAME, v1, v4, shortestPathOptions, TestComplexEntity01.class, TestComplexEntity02.class); - Assert.assertEquals(201, entity.getCode()); - Assert.assertEquals(2, entity.getEdges().size()); - Assert.assertEquals(3, entity.getVertices().size()); - Assert.assertEquals(x1 + x3, entity.getDistance().longValue()); - for (EdgeEntity edge : entity.getEdges()) { - Assert.assertTrue(edge.getDocumentHandle().equals(edge1.getDocumentHandle()) - || edge.getDocumentHandle().equals(edge3.getDocumentHandle())); - } - } - } -} diff --git a/src/test/java/com/arangodb/ArangoDriverGraphTest.java b/src/test/java/com/arangodb/ArangoDriverGraphTest.java deleted file mode 100644 index f6f3ebaf3..000000000 --- a/src/test/java/com/arangodb/ArangoDriverGraphTest.java +++ /dev/null @@ -1,454 +0,0 @@ -/* - * Copyright (C) 2012,2013 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb; - -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.Matchers.greaterThan; -import static org.hamcrest.Matchers.notNullValue; -import static org.hamcrest.Matchers.startsWith; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; - -import java.util.ArrayList; -import java.util.List; - -import org.junit.Test; - -import com.arangodb.entity.CollectionEntity; -import com.arangodb.entity.EdgeDefinitionEntity; -import com.arangodb.entity.GraphEntity; -import com.arangodb.entity.GraphsEntity; - -/** - * @author tamtam180 - kirscheless at gmail.com - * @author gschwab - * - */ -public class ArangoDriverGraphTest extends BaseGraphTest { - - private final String graphName = "UnitTestGraph"; - private final String collectionName = "UnitTestCollection"; - - @Test - public void test_getGraphs() throws ArangoException { - GraphsEntity graphs = driver.getGraphs(); - assertThat(graphs.getGraphs().size(), is(0)); - driver.createGraph("UnitTestGraph1", true); - driver.createGraph("UnitTestGraph2", true); - driver.createGraph("UnitTestGraph3", true); - graphs = driver.getGraphs(); - assertThat(graphs.getGraphs().size(), is(3)); - assertThat(graphs.getGraphs().get(0).getName(), startsWith("UnitTestGraph")); - assertThat(graphs.getGraphs().get(1).getName(), startsWith("UnitTestGraph")); - assertThat(graphs.getGraphs().get(2).getName(), startsWith("UnitTestGraph")); - } - - @Test - public void test_getGraphList() throws ArangoException { - List graphs = driver.getGraphList(); - assertThat(graphs.size(), is(0)); - final String graphName1 = "UnitTestGraph1"; - final String graphName2 = "UnitTestGraph2"; - final String graphName3 = "UnitTestGraph3"; - driver.createGraph(graphName1, true); - driver.createGraph(graphName2, true); - driver.createGraph(graphName3, true); - graphs = driver.getGraphList(); - assertThat(graphs.size(), is(3)); - assertThat(graphs.contains(graphName1), is(true)); - assertThat(graphs.contains(graphName2), is(true)); - assertThat(graphs.contains(graphName3), is(true)); - assertThat(graphs.contains("foo"), is(false)); - } - - @Test - public void test_createGraph() throws ArangoException { - - final List edgeDefinitions = new ArrayList(); - final List orphanCollections = new ArrayList(); - - // create - final GraphEntity graph = driver.createGraph(this.graphName, edgeDefinitions, orphanCollections, true); - - assertThat(graph.getCode(), is(201)); - assertThat(graph.getDocumentRevision(), is(notNullValue())); - assertThat(graph.getDocumentHandle(), is("_graphs/" + this.graphName)); - assertThat(graph.getName(), is(this.graphName)); - assertThat(graph.getOrphanCollections(), is(orphanCollections)); - - } - - @Test - public void test_createGraph_2() throws ArangoException { - - final List edgeDefinitions = this.createEdgeDefinitions(2, 0); - - final List orphanCollections = this.createOrphanCollections(2); - - // create - final GraphEntity graph = driver.createGraph(this.graphName, edgeDefinitions, orphanCollections, true); - assertThat(graph.getCode(), is(201)); - assertThat(graph.getDocumentRevision(), is(notNullValue())); - assertThat(graph.getDocumentHandle(), is("_graphs/" + this.graphName)); - assertThat(graph.getName(), is(this.graphName)); - assertThat(graph.getOrphanCollections(), is(orphanCollections)); - } - - @Test - public void test_getGraph() throws ArangoException { - driver.createGraph(this.graphName, this.createEdgeDefinitions(2, 0), this.createOrphanCollections(2), true); - final GraphEntity graph = driver.getGraph(this.graphName); - assertThat(graph.getEdgeDefinitionsEntity().getEdgeDefinitions().get(0).getClass().getName(), - is(EdgeDefinitionEntity.class.getName())); - assertThat(graph.getEdgeDefinitionsEntity().getEdgeDefinitions().get(0).getFrom().size(), is(3)); - assertThat(graph.getOrphanCollections().size(), is(2)); - assertThat(graph.getName(), is(this.graphName)); - assertThat(graph.getEdgeDefinitionsEntity().getSize(), is(2)); - assertThat(graph.getEdgeDefinitionsEntity().getEdgeDefinitions().get(0).getCollection().startsWith("edge"), - is(true)); - - } - - @Test - public void test_deleteGraph_keep_collections() throws ArangoException { - GraphsEntity graphs = driver.getGraphs(); - assertThat(graphs.getGraphs().size(), is(0)); - driver.createGraph(this.graphName, this.createEdgeDefinitions(2, 0), this.createOrphanCollections(2), true); - graphs = driver.getGraphs(); - assertThat(graphs.getGraphs().size(), is(1)); - assertThat(driver.getGraph(this.graphName).getName(), is(this.graphName)); - driver.deleteGraph(this.graphName); - graphs = driver.getGraphs(); - assertThat(graphs.getGraphs().size(), is(0)); - assertThat("number of collections", driver.getCollections(true).getCollections().size(), greaterThan(0)); - } - - @Test - public void test_deleteGraph_delete_collections() throws ArangoException { - GraphsEntity graphs = driver.getGraphs(); - assertThat(graphs.getGraphs().size(), is(0)); - driver.createGraph(this.graphName, this.createEdgeDefinitions(2, 0), this.createOrphanCollections(2), true); - graphs = driver.getGraphs(); - assertThat(graphs.getGraphs().size(), is(1)); - assertThat(driver.getGraph(this.graphName).getName(), is(this.graphName)); - driver.deleteGraph(this.graphName, true); - graphs = driver.getGraphs(); - assertThat(graphs.getGraphs().size(), is(0)); - assertThat("number of collections", driver.getCollections(true).getCollections().size(), is(0)); - } - - @Test - public void test_deleteGraph_not_found() throws ArangoException { - try { - driver.deleteGraph("foo"); - - } catch (final ArangoException e) { - assertThat(e.getErrorMessage(), is("graph not found")); - } - } - - @Test - public void test_getVertexCollections() throws ArangoException { - driver.createGraph(this.graphName, this.createEdgeDefinitions(2, 0), this.createOrphanCollections(2), true); - final List collections = driver.graphGetVertexCollections(this.graphName); - assertThat(collections.size(), is(14)); - } - - @Test - public void test_getVertexCollections_not_found() throws ArangoException { - try { - driver.graphGetVertexCollections("foo"); - fail(); - } catch (final ArangoException e) { - assertThat(e.getCode(), is(404)); - assertThat(e.getErrorMessage(), is("graph not found")); - } - } - - @Test - public void test_createVertexCollection() throws ArangoException { - driver.createGraph(this.graphName, this.createEdgeDefinitions(2, 0), this.createOrphanCollections(2), true); - final GraphEntity graph = driver.graphCreateVertexCollection(this.graphName, collectionName); - assertThat(driver.graphGetVertexCollections(this.graphName).contains(collectionName), is(true)); - assertThat(graph.getName(), is(this.graphName)); - } - - @Test - public void test_create_newVertexCollection_error() throws ArangoException { - try { - driver.graphCreateVertexCollection("foo", "UnitTestCollection"); - } catch (final ArangoException e) { - assertThat(e.getCode(), is(404)); - } - } - - @Test - public void test_deleteVertexCollection_keep_collection() throws ArangoException { - - driver.createGraph(this.graphName, this.createEdgeDefinitions(2, 0), this.createOrphanCollections(2), true); - driver.graphCreateVertexCollection(this.graphName, collectionName); - assertThat(driver.graphGetVertexCollections(this.graphName).contains(collectionName), is(true)); - driver.graphDeleteVertexCollection(this.graphName, collectionName, false); - assertThat(driver.graphGetVertexCollections(this.graphName).contains(collectionName), is(false)); - assertThat(driver.getCollection(collectionName).getClass().getName(), is(CollectionEntity.class.getName())); - - } - - @Test - public void test_deleteVertexCollection_drop_collection() throws ArangoException { - driver.createGraph(this.graphName, this.createEdgeDefinitions(2, 0), this.createOrphanCollections(2), true); - driver.graphCreateVertexCollection(this.graphName, collectionName); - assertThat(driver.graphGetVertexCollections(this.graphName).contains(collectionName), is(true)); - driver.graphDeleteVertexCollection(this.graphName, collectionName, true); - assertThat(driver.graphGetVertexCollections(this.graphName).contains(collectionName), is(false)); - try { - driver.getCollection(collectionName); - fail(); - } catch (final ArangoException e) { - assertThat(e.getCode(), greaterThan(300)); - } - - } - - @Test - public void test_deleteVertexCollection_drop_collection_fail() throws ArangoException { - final String graphName1 = "UnitTestGraph1"; - final String graphName2 = "UnitTestGraph2"; - driver.createGraph(graphName1, this.createEdgeDefinitions(2, 0), this.createOrphanCollections(2), true); - driver.createGraph(graphName2, this.createEdgeDefinitions(2, 2), this.createOrphanCollections(2), true); - driver.graphCreateVertexCollection(graphName1, collectionName); - assertThat(driver.graphGetVertexCollections(graphName1).contains(collectionName), is(true)); - driver.graphCreateVertexCollection(graphName2, collectionName); - assertThat(driver.graphGetVertexCollections(graphName2).contains(collectionName), is(true)); - driver.graphDeleteVertexCollection(graphName1, collectionName, true); - assertThat(driver.graphGetVertexCollections(graphName1).contains(collectionName), is(false)); - assertThat(driver.graphGetVertexCollections(graphName2).contains(collectionName), is(true)); - assertThat(driver.getCollection(collectionName).getClass().getName(), is(CollectionEntity.class.getName())); - } - - @Test - public void test_delete_vertex_collection_error1() throws ArangoException { - try { - driver.graphDeleteVertexCollection("foo", "bar", true); - fail(); - } catch (final ArangoException e) { - assertThat(e.getCode(), is(404)); - } - } - - @Test - public void test_delete_vertex_collection_error2() throws ArangoException { - driver.createGraph(this.graphName, this.createEdgeDefinitions(2, 0), this.createOrphanCollections(2), true); - try { - driver.graphDeleteVertexCollection(this.graphName, "bar", true); - fail(); - } catch (final ArangoException e) { - assertThat(e.getCode(), is(404)); - } - } - - @Test - public void test_get_edge_Collections() throws ArangoException { - driver.createGraph(this.graphName, this.createEdgeDefinitions(2, 0), this.createOrphanCollections(2), true); - final List collections = driver.graphGetEdgeCollections(this.graphName); - assertThat(collections.size(), is(2)); - } - - @Test - public void test_get_edge_Collections_not_found() throws ArangoException { - try { - driver.graphGetEdgeCollections("foo"); - fail(); - } catch (final ArangoException e) { - assertThat(e.getCode(), is(404)); - assertThat(e.getErrorMessage(), is("graph not found")); - } - } - - @Test - public void test_create_edge_definition() throws ArangoException { - final String edgeCollectionName = "UnitTestEdgeCollection"; - final String fromCollectionName = "UnitTestFromCollection"; - final String toCollectionName = "UnitTestToCollection"; - driver.createGraph(this.graphName, this.createEdgeDefinitions(2, 0), this.createOrphanCollections(2), true); - final EdgeDefinitionEntity edgeDefinition = new EdgeDefinitionEntity(); - edgeDefinition.setCollection(edgeCollectionName); - final List from = new ArrayList(); - from.add(fromCollectionName); - edgeDefinition.setFrom(from); - final List to = new ArrayList(); - to.add(toCollectionName); - edgeDefinition.setTo(to); - driver.graphCreateEdgeDefinition(this.graphName, edgeDefinition); - assertThat(driver.graphGetEdgeCollections(this.graphName).contains(edgeCollectionName), is(true)); - } - - @Test - public void test_create_edge_definition_2_graphs() throws ArangoException { - final String graphName1 = "UnitTestGraph1"; - final String graphName2 = "UnitTestGraph2"; - final String edgeCollectionName = "UnitTestEdgeCollection"; - final String fromCollectionName = "UnitTestFromCollection"; - final String toCollectionName = "UnitTestToCollection"; - driver.createGraph(graphName1, this.createEdgeDefinitions(2, 0), this.createOrphanCollections(2), true); - driver.createGraph(graphName2, this.createEdgeDefinitions(2, 2), this.createOrphanCollections(2), true); - final EdgeDefinitionEntity edgeDefinition = new EdgeDefinitionEntity(); - edgeDefinition.setCollection(edgeCollectionName); - final List from = new ArrayList(); - from.add(fromCollectionName); - edgeDefinition.setFrom(from); - final List to = new ArrayList(); - to.add(toCollectionName); - edgeDefinition.setTo(to); - driver.graphCreateEdgeDefinition(graphName1, edgeDefinition); - driver.graphCreateEdgeDefinition(graphName2, edgeDefinition); - assertThat(driver.graphGetEdgeCollections(graphName1).contains(edgeCollectionName), is(true)); - assertThat(driver.graphGetEdgeCollections(graphName2).contains(edgeCollectionName), is(true)); - } - - @Test - public void test_replace_edge_definition() throws ArangoException { - final String edgeCollectionName = "UnitTestEdgeCollection"; - final String fromCollectionName1 = "UnitTestFromCollection1"; - final String fromCollectionName2 = "UnitTestFromCollection2"; - final String toCollectionName1 = "UnitTestToCollection1"; - final String toCollectionName2 = "UnitTestToCollection2"; - driver.createGraph(this.graphName, this.createEdgeDefinitions(2, 0), this.createOrphanCollections(2), true); - final EdgeDefinitionEntity edgeDefinition1 = new EdgeDefinitionEntity(); - edgeDefinition1.setCollection(edgeCollectionName); - final List from1 = new ArrayList(); - from1.add(fromCollectionName1); - edgeDefinition1.setFrom(from1); - final List to1 = new ArrayList(); - to1.add(toCollectionName1); - edgeDefinition1.setTo(to1); - driver.graphCreateEdgeDefinition(this.graphName, edgeDefinition1); - assertThat(driver.graphGetEdgeCollections(this.graphName).contains(edgeCollectionName), is(true)); - assertThat(driver.graphGetVertexCollections(this.graphName).contains(fromCollectionName1), is(true)); - assertThat(driver.graphGetVertexCollections(this.graphName).contains(toCollectionName1), is(true)); - final EdgeDefinitionEntity edgeDefinition2 = new EdgeDefinitionEntity(); - edgeDefinition2.setCollection(edgeCollectionName); - final List from2 = new ArrayList(); - from2.add(fromCollectionName2); - edgeDefinition2.setFrom(from2); - final List to2 = new ArrayList(); - to2.add(toCollectionName2); - edgeDefinition2.setTo(to2); - final GraphEntity graph = driver.graphReplaceEdgeDefinition(this.graphName, edgeCollectionName, - edgeDefinition2); - final List edgeDefinitions = graph.getEdgeDefinitionsEntity().getEdgeDefinitions(); - for (final EdgeDefinitionEntity edgeDef : edgeDefinitions) { - final List f = edgeDef.getFrom(); - assertThat(f.contains(from1), is(false)); - final List t = edgeDef.getTo(); - assertThat(t.contains(to1), is(false)); - } - assertThat(driver.graphGetEdgeCollections(this.graphName).contains(edgeCollectionName), is(true)); - assertThat(driver.graphGetVertexCollections(this.graphName).contains(fromCollectionName1), is(true)); - assertThat(driver.graphGetVertexCollections(this.graphName).contains(toCollectionName1), is(true)); - assertThat(driver.graphGetVertexCollections(this.graphName).contains(fromCollectionName2), is(true)); - assertThat(driver.graphGetVertexCollections(this.graphName).contains(toCollectionName2), is(true)); - } - - @Test - public void test_replace_edge_definition_2_graphs() throws ArangoException { - final String graphName1 = "UnitTestGraph1"; - final String graphName2 = "UnitTestGraph2"; - final String edgeCollectionName = "UnitTestEdgeCollection"; - final String fromCollectionName1 = "UnitTestFromCollection1"; - final String fromCollectionName2 = "UnitTestFromCollection2"; - final String toCollectionName1 = "UnitTestToCollection1"; - final String toCollectionName2 = "UnitTestToCollection2"; - driver.createGraph(graphName1, this.createEdgeDefinitions(2, 0), this.createOrphanCollections(2), true); - driver.createGraph(graphName2, this.createEdgeDefinitions(2, 2), this.createOrphanCollections(2), true); - final EdgeDefinitionEntity edgeDefinition1 = new EdgeDefinitionEntity(); - edgeDefinition1.setCollection(edgeCollectionName); - final List from1 = new ArrayList(); - from1.add(fromCollectionName1); - edgeDefinition1.setFrom(from1); - final List to1 = new ArrayList(); - to1.add(toCollectionName1); - edgeDefinition1.setTo(to1); - driver.graphCreateEdgeDefinition(graphName1, edgeDefinition1); - driver.graphCreateEdgeDefinition(graphName2, edgeDefinition1); - assertThat(driver.graphGetEdgeCollections(graphName1).contains(edgeCollectionName), is(true)); - assertThat(driver.graphGetVertexCollections(graphName1).contains(fromCollectionName1), is(true)); - assertThat(driver.graphGetVertexCollections(graphName1).contains(toCollectionName1), is(true)); - assertThat(driver.graphGetEdgeCollections(graphName2).contains(edgeCollectionName), is(true)); - assertThat(driver.graphGetVertexCollections(graphName2).contains(fromCollectionName1), is(true)); - assertThat(driver.graphGetVertexCollections(graphName2).contains(toCollectionName1), is(true)); - final EdgeDefinitionEntity edgeDefinition2 = new EdgeDefinitionEntity(); - edgeDefinition2.setCollection(edgeCollectionName); - final List from2 = new ArrayList(); - from2.add(fromCollectionName2); - edgeDefinition2.setFrom(from2); - final List to2 = new ArrayList(); - to2.add(toCollectionName2); - edgeDefinition2.setTo(to2); - final GraphEntity graph1 = driver.graphReplaceEdgeDefinition(graphName1, edgeCollectionName, edgeDefinition2); - final List edgeDefinitions1 = graph1.getEdgeDefinitionsEntity().getEdgeDefinitions(); - for (final EdgeDefinitionEntity edgeDef : edgeDefinitions1) { - final List f = edgeDef.getFrom(); - assertThat(f.contains(from1), is(false)); - final List t = edgeDef.getTo(); - assertThat(t.contains(to1), is(false)); - } - final GraphEntity graph2 = driver.graphReplaceEdgeDefinition(graphName1, edgeCollectionName, edgeDefinition2); - final List edgeDefinitions2 = graph2.getEdgeDefinitionsEntity().getEdgeDefinitions(); - for (final EdgeDefinitionEntity edgeDef : edgeDefinitions2) { - final List f = edgeDef.getFrom(); - assertThat(f.contains(from1), is(false)); - final List t = edgeDef.getTo(); - assertThat(t.contains(to1), is(false)); - } - assertThat(driver.graphGetEdgeCollections(graphName1).contains(edgeCollectionName), is(true)); - assertThat(driver.graphGetVertexCollections(graphName1).contains(fromCollectionName1), is(true)); - assertThat(driver.graphGetVertexCollections(graphName1).contains(toCollectionName1), is(true)); - assertThat(driver.graphGetVertexCollections(graphName1).contains(fromCollectionName2), is(true)); - assertThat(driver.graphGetVertexCollections(graphName1).contains(toCollectionName2), is(true)); - assertThat(driver.graphGetEdgeCollections(graphName2).contains(edgeCollectionName), is(true)); - assertThat(driver.graphGetVertexCollections(graphName2).contains(fromCollectionName1), is(true)); - assertThat(driver.graphGetVertexCollections(graphName2).contains(toCollectionName1), is(true)); - assertThat(driver.graphGetVertexCollections(graphName2).contains(fromCollectionName2), is(true)); - assertThat(driver.graphGetVertexCollections(graphName2).contains(toCollectionName2), is(true)); - } - - @Test - public void test_delete_edge_definition_keep_collections() throws ArangoException { - driver.createGraph(this.graphName, this.createEdgeDefinitions(2, 0), this.createOrphanCollections(2), true); - driver.graphDeleteEdgeDefinition(this.graphName, "edge-1", false); - assertThat(driver.graphGetEdgeCollections(this.graphName).contains("edge-1"), is(false)); - assertThat(driver.graphGetEdgeCollections(this.graphName).contains("edge-2"), is(true)); - - } - - @Test - public void test_delete_edge_definition_drop_collections() throws ArangoException { - driver.createGraph(this.graphName, this.createEdgeDefinitions(2, 0), this.createOrphanCollections(2), true); - driver.graphDeleteEdgeDefinition(this.graphName, "edge-1", true); - assertThat(driver.graphGetEdgeCollections(this.graphName).contains("edge-1"), is(false)); - assertThat(driver.graphGetEdgeCollections(this.graphName).contains("edge-2"), is(true)); - try { - driver.getCollection("edge-1"); - fail(); - } catch (final ArangoException e) { - assertThat(e.getCode(), greaterThan(300)); - } - - } - -} diff --git a/src/test/java/com/arangodb/ArangoDriverGraphVertexReplaceTest.java b/src/test/java/com/arangodb/ArangoDriverGraphVertexReplaceTest.java deleted file mode 100644 index 8fe1fcaa8..000000000 --- a/src/test/java/com/arangodb/ArangoDriverGraphVertexReplaceTest.java +++ /dev/null @@ -1,239 +0,0 @@ -/* - * Copyright (C) 2012,2013 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb; - -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.not; -import static org.hamcrest.Matchers.notNullValue; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; - -import org.junit.Test; - -import com.arangodb.entity.DocumentEntity; -import com.arangodb.entity.marker.VertexEntity; - -/** - * @author tamtam180 - kirscheless at gmail.com - * @author gschwab - * - */ -public class ArangoDriverGraphVertexReplaceTest extends BaseGraphTest { - - private final String graphName = "UnitTestGraph"; - private final String collectionName = "UnitTestCollection"; - - @Test - public void test_vertex_replace() throws ArangoException { - - // create graph - driver.createGraph(this.graphName, this.createEdgeDefinitions(2, 0), this.createOrphanCollections(2), true); - // create vertex collection - driver.graphCreateVertexCollection(this.graphName, this.collectionName); - // create vertex - final VertexEntity v1 = driver.graphCreateVertex(this.graphName, this.collectionName, - new TestComplexEntity01("Homer", "Simpson", 38), null); - // check exists vertex - final VertexEntity vertex = driver.graphGetVertex(this.graphName, this.collectionName, - v1.getDocumentKey(), TestComplexEntity01.class, null, null); - assertThat(vertex.getCode(), is(200)); - - // replace - final DocumentEntity updatedVertex = driver.graphReplaceVertex(this.graphName, - this.collectionName, v1.getDocumentKey(), new TestComplexEntity02(1, 2, 3)); - assertThat(updatedVertex.getCode(), is(202)); - assertThat(updatedVertex.isError(), is(false)); - - assertThat(updatedVertex.getDocumentHandle(), is(v1.getDocumentHandle())); - assertThat(updatedVertex.getDocumentRevision(), is(not(v1.getDocumentRevision()))); - assertThat(updatedVertex.getDocumentRevision(), is(notNullValue())); - assertThat(updatedVertex.getDocumentKey(), is(v1.getDocumentKey())); - - final DocumentEntity updatedVertex2 = driver.graphGetVertex(this.graphName, - this.collectionName, v1.getDocumentKey(), TestComplexEntity02.class); - assertThat(updatedVertex2.getEntity().getX(), is(1)); - assertThat(updatedVertex2.getEntity().getY(), is(2)); - assertThat(updatedVertex2.getEntity().getZ(), is(3)); - - // check count - assertThat(driver.getCollectionCount(this.collectionName).getCount(), is(1L)); - - } - - @Test - public void test_vertex_replace_graph_not_found() throws ArangoException { - - try { - driver.graphReplaceVertex(this.graphName, this.collectionName, "key1", new TestComplexEntity02(1, 2, 3)); - fail(); - } catch (final ArangoException e) { - assertThat(e.getCode(), is(404)); - assertThat(e.getErrorMessage(), is("graph not found")); - } - - } - - @Test - public void test_vertex_replace_vertex_not_found() throws ArangoException { - - // create graph - driver.createGraph(this.graphName, this.createEdgeDefinitions(2, 0), this.createOrphanCollections(2), true); - // create vertex collection - driver.graphCreateVertexCollection(this.graphName, this.collectionName); - // replace - try { - driver.graphReplaceVertex(this.graphName, this.collectionName, "key1", new TestComplexEntity02(1, 2, 3)); - fail(); - } catch (final ArangoException e) { - assertThat(e.getCode(), is(404)); - } - - } - - @Test - public void test_vertex_replace_rev_eq() throws ArangoException { - - // create graph - driver.createGraph(this.graphName, this.createEdgeDefinitions(2, 0), this.createOrphanCollections(2), true); - // create vertex collection - driver.graphCreateVertexCollection(this.graphName, this.collectionName); - // create vertex - final VertexEntity v1 = driver.graphCreateVertex(this.graphName, this.collectionName, - new TestComplexEntity01("Homer", "Simpson", 38), null); - // check exists vertex - final VertexEntity vertex = driver.graphGetVertex(this.graphName, this.collectionName, - v1.getDocumentKey(), TestComplexEntity01.class, null, null); - assertThat(vertex.getCode(), is(200)); - - // replace - final VertexEntity updatedVertex = driver.graphReplaceVertex(this.graphName, - this.collectionName, v1.getDocumentKey(), new TestComplexEntity02(1, 2, 3)); - assertThat(updatedVertex.getCode(), is(202)); - assertThat(updatedVertex.isError(), is(false)); - - assertThat(updatedVertex.getDocumentHandle(), is(v1.getDocumentHandle())); - assertThat(updatedVertex.getDocumentRevision(), is(not(v1.getDocumentRevision()))); - assertThat(updatedVertex.getDocumentRevision(), is(notNullValue())); - assertThat(updatedVertex.getDocumentKey(), is(v1.getDocumentKey())); - - final VertexEntity updatedVertex2 = driver.graphGetVertex(this.graphName, - this.collectionName, v1.getDocumentKey(), TestComplexEntity02.class); - assertThat(updatedVertex2.getEntity().getX(), is(1)); - assertThat(updatedVertex2.getEntity().getY(), is(2)); - assertThat(updatedVertex2.getEntity().getZ(), is(3)); - - // check count - assertThat(driver.getCollectionCount(this.collectionName).getCount(), is(1L)); - - } - - @Test - public void test_vertex_replace_rev_ne() throws ArangoException { - - // create graph - driver.createGraph(this.graphName, this.createEdgeDefinitions(2, 0), this.createOrphanCollections(2), true); - // create vertex collection - driver.graphCreateVertexCollection(this.graphName, this.collectionName); - // create vertex - final VertexEntity v1 = driver.graphCreateVertex(this.graphName, this.collectionName, - new TestComplexEntity01("Homer", "Simpson", 38), null); - // check exists vertex - final VertexEntity vertex = driver.graphGetVertex(this.graphName, this.collectionName, - v1.getDocumentKey(), TestComplexEntity01.class, null, null); - assertThat(vertex.getCode(), is(200)); - - // replace - try { - final String rev = "1"; - driver.graphReplaceVertex(this.graphName, this.collectionName, v1.getDocumentKey(), - new TestComplexEntity02(1, 2, 3), true, rev, null); - fail(); - } catch (final ArangoException e) { - assertThat(e.getCode(), is(412)); - assertThat(e.getErrorNumber(), is(1903)); - assertThat(e.getErrorMessage(), is("wrong revision")); - } - - } - - @Test - public void test_vertex_replace_ifmatch_eq() throws ArangoException { - - // create graph - driver.createGraph(this.graphName, this.createEdgeDefinitions(2, 0), this.createOrphanCollections(2), true); - // create vertex collection - driver.graphCreateVertexCollection(this.graphName, this.collectionName); - // create vertex - final VertexEntity v1 = driver.graphCreateVertex(this.graphName, this.collectionName, - new TestComplexEntity01("Homer", "Simpson", 38), null); - // check exists vertex - final VertexEntity vertex = driver.graphGetVertex(this.graphName, this.collectionName, - v1.getDocumentKey(), TestComplexEntity01.class, null, null); - assertThat(vertex.getCode(), is(200)); - - // replace - final String rev = vertex.getDocumentRevision(); - final VertexEntity updatedVertex = driver.graphReplaceVertex(this.graphName, - this.collectionName, v1.getDocumentKey(), new TestComplexEntity02(1, 2, 3), true, rev, null); - assertThat(updatedVertex.getCode(), is(200)); - assertThat(updatedVertex.isError(), is(false)); - - assertThat(updatedVertex.getDocumentHandle(), is(v1.getDocumentHandle())); - assertThat(updatedVertex.getDocumentRevision(), is(not(v1.getDocumentRevision()))); - assertThat(updatedVertex.getDocumentRevision(), is(notNullValue())); - assertThat(updatedVertex.getDocumentKey(), is(v1.getDocumentKey())); - - final DocumentEntity updatedVertex2 = driver.graphGetVertex(this.graphName, - this.collectionName, v1.getDocumentKey(), TestComplexEntity02.class); - assertThat(updatedVertex2.getEntity().getX(), is(1)); - assertThat(updatedVertex2.getEntity().getY(), is(2)); - assertThat(updatedVertex2.getEntity().getZ(), is(3)); - - // check count - assertThat(driver.getCollectionCount(this.collectionName).getCount(), is(1L)); - - } - - @Test - public void test_vertex_replace_ifmatch_ne() throws ArangoException { - - // create graph - driver.createGraph(this.graphName, this.createEdgeDefinitions(2, 0), this.createOrphanCollections(2), true); - // create vertex collection - driver.graphCreateVertexCollection(this.graphName, this.collectionName); - // create vertex - final VertexEntity v1 = driver.graphCreateVertex(this.graphName, this.collectionName, - new TestComplexEntity01("xxx", "yyy", 10), null); - // check exists vertex - final VertexEntity vertex = driver.graphGetVertex(this.graphName, this.collectionName, - v1.getDocumentKey(), TestComplexEntity01.class, null, null); - assertThat(vertex.getCode(), is(200)); - - // replace - try { - final String rev = "1"; - driver.graphReplaceVertex(this.graphName, this.collectionName, v1.getDocumentKey(), - new TestComplexEntity02(1, 2, 3), true, rev, null); - fail(); - } catch (final ArangoException e) { - assertThat(e.getCode(), is(412)); - assertThat(e.getErrorNumber(), is(1903)); - assertThat(e.getErrorMessage(), is("wrong revision")); - } - - } -} diff --git a/src/test/java/com/arangodb/ArangoDriverGraphVertexTest.java b/src/test/java/com/arangodb/ArangoDriverGraphVertexTest.java deleted file mode 100644 index 37d868e03..000000000 --- a/src/test/java/com/arangodb/ArangoDriverGraphVertexTest.java +++ /dev/null @@ -1,391 +0,0 @@ -/* - * Copyright (C) 2012,2013 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb; - -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.isA; -import static org.hamcrest.CoreMatchers.not; -import static org.hamcrest.CoreMatchers.notNullValue; -import static org.hamcrest.Matchers.greaterThan; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; - -import java.util.ArrayList; -import java.util.List; - -import org.junit.Before; -import org.junit.Test; - -import com.arangodb.entity.DeletedEntity; -import com.arangodb.entity.DocumentEntity; -import com.arangodb.entity.marker.VertexEntity; -import com.arangodb.util.AqlQueryOptions; -import com.arangodb.util.GraphVerticesOptions; - -/** - * @author tamtam180 - kirscheless at gmail.com - * @author gschwab - * - */ -public class ArangoDriverGraphVertexTest extends BaseGraphTest { - - private final static String GRAPH_NAME = "UnitTestGraph"; - private final static String COLLECTION_NAME = "UnitTestCollection"; - - @Before - public void setup() throws ArangoException { - try { - driver.createGraph(GRAPH_NAME, this.createEdgeDefinitions(2, 0), this.createOrphanCollections(2), true); - } catch (final ArangoException e) { - } - } - - @Test - public void test_create_vertex() throws ArangoException { - - final VertexEntity vertex = driver.graphCreateVertex(GRAPH_NAME, "from1-1", - new TestComplexEntity01("Homer", "Simpson", 38), true); - - assertThat(vertex.getDocumentHandle(), is(notNullValue())); - assertThat(vertex.getDocumentRevision(), is(notNullValue())); - assertThat(vertex.getDocumentKey(), is(notNullValue())); - assertThat(vertex.getEntity(), isA(TestComplexEntity01.class)); - final DocumentEntity document = driver.getDocument(vertex.getDocumentHandle(), - TestComplexEntity01.class); - assertThat(document.getEntity().getUser(), is("Homer")); - assertThat(document.getEntity().getDesc(), is("Simpson")); - assertThat(document.getEntity().getAge(), is(38)); - } - - @Test - public void test_create_vertex_with_document_attributes() throws ArangoException { - - final VertexEntity vertex = driver.graphCreateVertex(GRAPH_NAME, "from1-1", - new TestComplexEntity03("Homer", "Simpson", 38), true); - - assertThat(vertex.getDocumentHandle(), is(notNullValue())); - assertThat(vertex.getDocumentRevision(), is(notNullValue())); - assertThat(vertex.getDocumentKey(), is(notNullValue())); - assertThat(vertex.getEntity(), isA(TestComplexEntity03.class)); - - assertThat(vertex.getEntity().getDocumentHandle(), is(notNullValue())); - assertThat(vertex.getEntity().getDocumentKey(), is(notNullValue())); - assertThat(vertex.getEntity().getDocumentRevision(), is(notNullValue())); - - final DocumentEntity document = driver.getDocument(vertex.getDocumentHandle(), - TestComplexEntity03.class); - assertThat(document.getEntity().getUser(), is("Homer")); - assertThat(document.getEntity().getDesc(), is("Simpson")); - assertThat(document.getEntity().getAge(), is(38)); - - } - - @Test - public void test_create_vertex_error_graph() throws ArangoException { - - try { - driver.graphCreateVertex("foo", "bar", new TestComplexEntity01("Homer", "Simpson", 38), true); - fail(); - } catch (final ArangoException e) { - assertThat(e.getCode(), greaterThan(300)); - } - - } - - @Test - public void test_create_vertex_error_collection() throws ArangoException { - - try { - driver.graphCreateVertex(GRAPH_NAME, "foo", new TestComplexEntity01("Homer", "Simpson", 38), true); - fail(); - } catch (final ArangoException e) { - assertThat(e.getCode(), greaterThan(300)); - } - - } - - @Test - public void test_graphGetVertex() throws ArangoException { - VertexEntity vertex = driver.graphCreateVertex(GRAPH_NAME, "from1-1", - new TestComplexEntity01("Homer", "Simpson", 38), true); - try { - vertex = driver.graphGetVertex(GRAPH_NAME, COLLECTION_NAME, vertex.getDocumentKey(), - TestComplexEntity01.class, vertex.getDocumentRevision(), null); - } catch (final ArangoException e) { - assertThat(e.getCode(), greaterThan(300)); - } - - } - - // *********************** - // *** Delete Vertex Tests - // *********************** - - @Test - public void test_delete_vertex() throws ArangoException { - // create collection - driver.graphCreateVertexCollection(GRAPH_NAME, COLLECTION_NAME); - // create vertex - final VertexEntity v1 = driver.graphCreateVertex(GRAPH_NAME, COLLECTION_NAME, - new TestComplexEntity01("Homer", "Simpson", 38), true); - - // check exists vertex - final VertexEntity vertex = driver.graphGetVertex(GRAPH_NAME, COLLECTION_NAME, - v1.getDocumentKey(), TestComplexEntity01.class); - assertThat(vertex.getCode(), is(200)); - - // delete - final DeletedEntity deleted = driver.graphDeleteVertex(GRAPH_NAME, COLLECTION_NAME, v1.getDocumentKey(), true, - null, null); - assertThat(deleted.getCode(), is(200)); - assertThat(deleted.getDeleted(), is(true)); - - } - - @Test - public void test_delete_vertex_graph_not_found() throws ArangoException { - - try { - driver.graphDeleteVertex("foo", "bar", "foobar", true, null, null); - fail(); - } catch (final ArangoException e) { - assertThat(e.getCode(), is(404)); - assertThat(e.getErrorNumber(), is(1924)); - } - - } - - @Test - public void test_delete_vertex_not_found() throws ArangoException { - - driver.graphCreateVertexCollection(GRAPH_NAME, COLLECTION_NAME); - - try { - driver.graphDeleteVertex(GRAPH_NAME, COLLECTION_NAME, "foo", true, null, null); - } catch (final ArangoException e) { - assertThat(e.getCode(), is(404)); - } - - } - - @Test - public void test_delete_vertex_rev_eq() throws ArangoException { - - driver.graphCreateVertexCollection(GRAPH_NAME, COLLECTION_NAME); - - final VertexEntity v1 = driver.graphCreateVertex(GRAPH_NAME, COLLECTION_NAME, - new TestComplexEntity01("Hoemr", "Simpson", 38), null); - final VertexEntity vertex = driver.graphGetVertex(GRAPH_NAME, COLLECTION_NAME, - v1.getDocumentKey(), TestComplexEntity01.class, null, null); - assertThat(vertex.getCode(), is(200)); - - // delete - final DeletedEntity deleted = driver.graphDeleteVertex(GRAPH_NAME, COLLECTION_NAME, v1.getDocumentKey(), null, - v1.getDocumentRevision(), null); - assertThat(deleted.getCode(), is(202)); - assertThat(deleted.getDeleted(), is(true)); - - } - - @Test - public void test_delete_vertex_rev_ng() throws ArangoException { - - driver.graphCreateVertexCollection(GRAPH_NAME, COLLECTION_NAME); - - final VertexEntity v1 = driver.graphCreateVertex(GRAPH_NAME, COLLECTION_NAME, - new TestComplexEntity01("Homer", "Simspin", 38), null); - final VertexEntity vertex = driver.graphGetVertex(GRAPH_NAME, COLLECTION_NAME, - v1.getDocumentKey(), TestComplexEntity01.class, null, null); - assertThat(vertex.getCode(), is(200)); - - // delete - try { - driver.graphDeleteVertex(GRAPH_NAME, COLLECTION_NAME, v1.getDocumentKey(), null, - v1.getDocumentRevision() + 1, null); - } catch (final ArangoException e) { - assertThat(e.getCode(), is(412)); - assertThat(e.getErrorNumber(), is(1903)); - assertThat(e.getErrorMessage(), is("wrong revision")); - } - - } - - @Test - public void test_delete_vertex_match_eq() throws ArangoException { - driver.graphCreateVertexCollection(GRAPH_NAME, COLLECTION_NAME); - - final VertexEntity v1 = driver.graphCreateVertex(GRAPH_NAME, COLLECTION_NAME, - new TestComplexEntity01("Homer", "Simpson", 38), null); - final VertexEntity vertex = driver.graphGetVertex(GRAPH_NAME, COLLECTION_NAME, - v1.getDocumentKey(), TestComplexEntity01.class, null, null); - assertThat(vertex.getCode(), is(200)); - - // delete - final DeletedEntity deleted = driver.graphDeleteVertex(GRAPH_NAME, COLLECTION_NAME, v1.getDocumentKey(), null, - v1.getDocumentRevision(), null); - assertThat(deleted.getCode(), is(202)); - assertThat(deleted.getDeleted(), is(true)); - - } - - @Test - public void test_delete_vertex_match_ng() throws ArangoException { - driver.graphCreateVertexCollection(GRAPH_NAME, COLLECTION_NAME); - - final VertexEntity v1 = driver.graphCreateVertex(GRAPH_NAME, COLLECTION_NAME, - new TestComplexEntity01("Homer", "Simpson", 38), null); - final VertexEntity vertex = driver.graphGetVertex(GRAPH_NAME, COLLECTION_NAME, - v1.getDocumentKey(), TestComplexEntity01.class, null, null); - assertThat(vertex.getCode(), is(200)); - - // delete - try { - driver.graphDeleteVertex(GRAPH_NAME, COLLECTION_NAME, v1.getDocumentKey(), null, null, - v1.getDocumentRevision() + 1); - } catch (final ArangoException e) { - assertThat(e.getCode(), is(412)); - assertThat(e.getErrorNumber(), is(1903)); - assertThat(e.getErrorMessage(), is("wrong revision")); - } - } - - @Test - public void graphGetVertexCursorTest() throws ArangoException { - - final TestComplexEntity01 v1 = new TestComplexEntity01("Homer", "A Simpson", 38); - final TestComplexEntity01 v2 = new TestComplexEntity01("Marge", "A Simpson", 36); - final TestComplexEntity01 v3 = new TestComplexEntity01("Bart", "A Simpson", 10); - final TestComplexEntity01 v4 = new TestComplexEntity01("Remoh", "Homer's twin", 38); - - final VertexEntity vertex1 = driver.graphCreateVertex(GRAPH_NAME, "from1-1", v1, true); - final VertexEntity vertex2 = driver.graphCreateVertex(GRAPH_NAME, "to1-1", v2, true); - final VertexEntity vertex3 = driver.graphCreateVertex(GRAPH_NAME, "to1-1", v3, true); - final VertexEntity vertex4 = driver.graphCreateVertex(GRAPH_NAME, "from1-1", v4, true); - - driver.graphCreateEdge(GRAPH_NAME, "edge-1", null, vertex1.getDocumentHandle(), vertex2.getDocumentHandle(), - new TestComplexEntity02(1, 2, 3), null); - - driver.graphCreateEdge(GRAPH_NAME, "edge-1", null, vertex1.getDocumentHandle(), vertex3.getDocumentHandle(), - new TestComplexEntity02(4, 5, 6), null); - - driver.graphCreateEdge(GRAPH_NAME, "edge-1", null, vertex4.getDocumentHandle(), vertex2.getDocumentHandle(), - new TestComplexEntity02(7, 8, 9), null); - - driver.graphCreateEdge(GRAPH_NAME, "edge-1", null, vertex4.getDocumentHandle(), vertex3.getDocumentHandle(), - new TestComplexEntity02(10, 11, 12), null); - - // setCount = true - final AqlQueryOptions aqlQueryOptions = driver.getDefaultAqlQueryOptions().setCount(true); - - VertexCursor vertexCursor = driver.graphGetVertexCursor(GRAPH_NAME, - TestComplexEntity01.class, null, null, aqlQueryOptions); - assertEquals(4, vertexCursor.getCount()); - assertEquals(201, vertexCursor.getCode()); - - vertexCursor = driver.graphGetVertexCursor(GRAPH_NAME, TestComplexEntity01.class, - new TestComplexEntity01("Homer", null, null), null, aqlQueryOptions); - assertEquals(1, vertexCursor.getCount()); - assertEquals(201, vertexCursor.getCode()); - - final GraphVerticesOptions graphVerticesOptions = new GraphVerticesOptions(); - final List vertexCollectionRestriction = new ArrayList(); - vertexCollectionRestriction.add("from1-1"); - graphVerticesOptions.setVertexCollectionRestriction(vertexCollectionRestriction); - - vertexCursor = driver.graphGetVertexCursor(GRAPH_NAME, TestComplexEntity01.class, null, graphVerticesOptions, - aqlQueryOptions); - assertEquals(2, vertexCursor.getCount()); - assertEquals(201, vertexCursor.getCode()); - - vertexCursor = driver.graphGetVertexCursor(GRAPH_NAME, TestComplexEntity01.class, vertex1.getDocumentHandle(), - null, aqlQueryOptions); - assertEquals(201, vertexCursor.getCode()); - assertEquals(1, vertexCursor.getCount()); - assertEquals(vertex1.getDocumentHandle(), vertexCursor.getUniqueResult().getDocumentHandle()); - } - - @Test - public void test_replace_vertex_with_document_attributes() throws ArangoException { - - final VertexEntity vertex = driver.graphCreateVertex(GRAPH_NAME, "from1-1", - new TestComplexEntity03("Homer", "Simpson", 38), true); - - assertThat(vertex.getDocumentHandle(), is(notNullValue())); - assertThat(vertex.getDocumentRevision(), is(notNullValue())); - assertThat(vertex.getDocumentKey(), is(notNullValue())); - final TestComplexEntity03 en1 = vertex.getEntity(); - assertThat(en1, isA(TestComplexEntity03.class)); - - assertThat(en1.getDocumentHandle(), is(notNullValue())); - assertThat(en1.getDocumentKey(), is(notNullValue())); - assertThat(en1.getDocumentRevision(), is(notNullValue())); - final String rev = en1.getDocumentRevision(); - - en1.setUser("Tim"); - - final DocumentEntity document2 = driver.graphReplaceVertex(GRAPH_NAME, "from1-1", - en1.getDocumentKey(), en1); - assertThat(document2.getEntity().getUser(), is("Tim")); - assertThat(document2.getEntity().getDesc(), is("Simpson")); - assertThat(document2.getEntity().getAge(), is(38)); - final TestComplexEntity03 en2 = document2.getEntity(); - assertThat(en2.getDocumentHandle(), is(notNullValue())); - assertThat(en2.getDocumentKey(), is(notNullValue())); - assertThat(en2.getDocumentRevision(), is(notNullValue())); - assertThat(en2.getDocumentRevision(), is(not(rev))); - final String rev2 = en2.getDocumentRevision(); - - final DocumentEntity document = driver.getDocument(vertex.getDocumentHandle(), - TestComplexEntity03.class); - assertThat(document.getEntity().getUser(), is("Tim")); - assertThat(document.getEntity().getDesc(), is("Simpson")); - assertThat(document.getEntity().getAge(), is(38)); - assertThat(document.getDocumentRevision(), is(rev2)); - } - - @Test - public void test_update_vertex_with_document_attributes() throws ArangoException { - - final VertexEntity vertex = driver.graphCreateVertex(GRAPH_NAME, "from1-1", - new TestComplexEntity03("Homer", "Simpson", 38), true); - - assertThat(vertex.getDocumentHandle(), is(notNullValue())); - assertThat(vertex.getDocumentRevision(), is(notNullValue())); - assertThat(vertex.getDocumentKey(), is(notNullValue())); - final String rev = vertex.getDocumentRevision(); - - final TestComplexEntity03 en1 = new TestComplexEntity03("Tim", null, null); - - final DocumentEntity document2 = driver.graphUpdateVertex(GRAPH_NAME, "from1-1", - vertex.getDocumentKey(), en1, true); - assertThat(document2.getEntity().getUser(), is("Tim")); - final TestComplexEntity03 en2 = document2.getEntity(); - assertThat(en2.getDocumentHandle(), is(notNullValue())); - assertThat(en2.getDocumentKey(), is(notNullValue())); - assertThat(en2.getDocumentRevision(), is(notNullValue())); - assertThat(en2.getDocumentRevision(), is(not(rev))); - final String rev2 = en2.getDocumentRevision(); - - final DocumentEntity document = driver.getDocument(vertex.getDocumentHandle(), - TestComplexEntity03.class); - assertThat(document.getEntity().getUser(), is("Tim")); - assertThat(document.getEntity().getDesc(), is("Simpson")); - assertThat(document.getEntity().getAge(), is(38)); - assertThat(document.getDocumentRevision(), is(rev2)); - } -} diff --git a/src/test/java/com/arangodb/ArangoDriverGraphVertexUpdateTest.java b/src/test/java/com/arangodb/ArangoDriverGraphVertexUpdateTest.java deleted file mode 100644 index 6cc20c9c3..000000000 --- a/src/test/java/com/arangodb/ArangoDriverGraphVertexUpdateTest.java +++ /dev/null @@ -1,287 +0,0 @@ -/* - * Copyright (C) 2012,2013 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb; - -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.not; -import static org.hamcrest.CoreMatchers.nullValue; -import static org.hamcrest.CoreMatchers.startsWith; -import static org.hamcrest.Matchers.notNullValue; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; - -import org.junit.Test; - -import com.arangodb.entity.DocumentEntity; -import com.arangodb.entity.marker.VertexEntity; - -/** - * @author tamtam180 - kirscheless at gmail.com - * @author gschwab - */ -public class ArangoDriverGraphVertexUpdateTest extends BaseGraphTest { - - private final String graphName = "UnitTestGraph"; - private final String collectionName = "UnitTestCollection"; - - @Test - public void test_vertex_update_keep_null() throws ArangoException { - - // create graph - driver.createGraph(this.graphName, this.createEdgeDefinitions(2, 0), this.createOrphanCollections(2), true); - // create vertex collection - driver.graphCreateVertexCollection(this.graphName, this.collectionName); - // create vertex - final VertexEntity v1 = driver.graphCreateVertex(this.graphName, this.collectionName, - new TestComplexEntity01("Homa", "Simpson", 83), null); - // check exists vertex - final VertexEntity vertex = driver.graphGetVertex(this.graphName, this.collectionName, - v1.getDocumentKey(), TestComplexEntity01.class, null, null); - assertThat(vertex.getCode(), is(200)); - - // update - VertexEntity updatedVertex = driver.graphUpdateVertex(this.graphName, this.collectionName, - vertex.getDocumentKey(), new TestComplexEntity01("Homer", null, 38), true); - assertThat(updatedVertex.getCode(), is(202)); - assertThat(updatedVertex.isError(), is(false)); - - assertThat(updatedVertex.getDocumentHandle(), is(v1.getDocumentHandle())); - assertThat(updatedVertex.getDocumentRevision(), is(not(v1.getDocumentRevision()))); - assertThat(updatedVertex.getDocumentRevision(), is(notNullValue())); - assertThat(updatedVertex.getDocumentKey(), is(v1.getDocumentKey())); - - updatedVertex = driver.graphGetVertex(this.graphName, this.collectionName, vertex.getDocumentKey(), - TestComplexEntity01.class); - - assertThat(updatedVertex.getEntity().getUser(), is("Homer")); - assertThat(updatedVertex.getEntity().getDesc(), is("Simpson")); - assertThat(updatedVertex.getEntity().getAge(), is(38)); - - // check count - assertThat(driver.getCollectionCount(this.collectionName).getCount(), is(1L)); - - } - - @Test - public void test_vertex_update_keep_null_false() throws ArangoException { - - // create graph - driver.createGraph(this.graphName, this.createEdgeDefinitions(2, 0), this.createOrphanCollections(2), true); - // create vertex collection - driver.graphCreateVertexCollection(this.graphName, this.collectionName); - // create vertex - final VertexEntity v1 = driver.graphCreateVertex(this.graphName, this.collectionName, - new TestComplexEntity01("Homer", "A Sompsin", 83), null); - // check exists vertex - final VertexEntity vertex = driver.graphGetVertex(this.graphName, this.collectionName, - v1.getDocumentKey(), TestComplexEntity01.class, null, null); - assertThat(vertex.getCode(), is(200)); - - // update - VertexEntity updatedVertex = driver.graphUpdateVertex(this.graphName, this.collectionName, - vertex.getDocumentKey(), new TestComplexEntity01("Homer", null, 38), false); - assertThat(updatedVertex.getCode(), is(202)); - assertThat(updatedVertex.isError(), is(false)); - - assertThat(updatedVertex.getDocumentHandle(), is(v1.getDocumentHandle())); - assertThat(updatedVertex.getDocumentRevision(), is(not(v1.getDocumentRevision()))); - assertThat(updatedVertex.getDocumentRevision(), is(notNullValue())); - assertThat(updatedVertex.getDocumentKey(), is(v1.getDocumentKey())); - - updatedVertex = driver.graphGetVertex(this.graphName, this.collectionName, vertex.getDocumentKey(), - TestComplexEntity01.class); - - assertThat(updatedVertex.getEntity().getUser(), is("Homer")); - assertThat(updatedVertex.getEntity().getDesc(), is(nullValue())); - assertThat(updatedVertex.getEntity().getAge(), is(38)); - - // check count - assertThat(driver.getCollectionCount(this.collectionName).getCount(), is(1L)); - - } - - @Test - public void test_vertex_update_graph_not_found() throws ArangoException { - - // update - try { - driver.graphUpdateVertex(this.graphName, this.collectionName, "xx", - new TestComplexEntity01("zzz", null, 99), true); - fail(); - } catch (final ArangoException e) { - assertThat(e.getCode(), is(404)); - assertThat(e.getErrorMessage(), startsWith("graph not found")); - } - - } - - @Test - public void test_vertex_update_collection_not_found() throws ArangoException { - - // create graph - driver.createGraph(this.graphName, this.createEdgeDefinitions(2, 0), this.createOrphanCollections(2), true); - - // update - try { - driver.graphUpdateVertex(this.graphName, this.collectionName, "xx", - new TestComplexEntity01("zzz", null, 99), true); - fail(); - } catch (final ArangoException e) { - assertThat(e.getCode(), is(404)); - assertThat(e.getErrorMessage(), startsWith("collection not found")); - } - - } - - @Test - public void test_vertex_update_rev_eq() throws ArangoException { - - // create graph - driver.createGraph(this.graphName, this.createEdgeDefinitions(2, 0), this.createOrphanCollections(2), true); - // create vertex collection - driver.graphCreateVertexCollection(this.graphName, this.collectionName); - // create vertex - final VertexEntity v1 = driver.graphCreateVertex(this.graphName, this.collectionName, - new TestComplexEntity01("xxx", "yyy", 83), null); - // check exists vertex - final VertexEntity vertex = driver.graphGetVertex(this.graphName, this.collectionName, - v1.getDocumentKey(), TestComplexEntity01.class, null, null); - assertThat(vertex.getCode(), is(200)); - - // update - final String rev = vertex.getDocumentRevision(); - DocumentEntity updatedVertex = driver.graphUpdateVertex(this.graphName, - this.collectionName, vertex.getDocumentKey(), new TestComplexEntity01("zzz", null, 99), null, true, rev, - null); - assertThat(updatedVertex.getCode(), is(200)); - assertThat(updatedVertex.isError(), is(false)); - - assertThat(updatedVertex.getDocumentHandle(), is(v1.getDocumentHandle())); - assertThat(updatedVertex.getDocumentRevision(), is(not(v1.getDocumentRevision()))); - assertThat(updatedVertex.getDocumentRevision(), is(notNullValue())); - assertThat(updatedVertex.getDocumentKey(), is(v1.getDocumentKey())); - - updatedVertex = driver.graphGetVertex(this.graphName, this.collectionName, vertex.getDocumentKey(), - TestComplexEntity01.class); - - assertThat(updatedVertex.getEntity().getUser(), is("zzz")); - assertThat(updatedVertex.getEntity().getDesc(), is("yyy")); - assertThat(updatedVertex.getEntity().getAge(), is(99)); - - // check count - assertThat(driver.getCollectionCount(this.collectionName).getCount(), is(1L)); - - } - - @Test - public void test_vertex_update_rev_ne() throws ArangoException { - - // create graph - driver.createGraph(this.graphName, this.createEdgeDefinitions(2, 0), this.createOrphanCollections(2), true); - // create vertex collection - driver.graphCreateVertexCollection(this.graphName, this.collectionName); - // create vertex - final VertexEntity v1 = driver.graphCreateVertex(this.graphName, this.collectionName, - new TestComplexEntity01("xxx", "yyy", 83), null); - // check exists vertex - final VertexEntity vertex = driver.graphGetVertex(this.graphName, this.collectionName, - v1.getDocumentKey(), TestComplexEntity01.class, null, null); - assertThat(vertex.getCode(), is(200)); - - // update - try { - final String rev = vertex.getDocumentRevision() + 1; - driver.graphUpdateVertex(this.graphName, this.collectionName, vertex.getDocumentKey(), - new TestComplexEntity01("zzz", null, 99), null, true, rev, null); - fail(); - } catch (final ArangoException e) { - assertThat(e.getCode(), is(412)); - assertThat(e.getErrorNumber(), is(1903)); - assertThat(e.getErrorMessage(), is("wrong revision")); - } - - } - - @Test - public void test_vertex_update_ifmatch_eq() throws ArangoException { - - // create graph - driver.createGraph(this.graphName, this.createEdgeDefinitions(2, 0), this.createOrphanCollections(2), true); - // create vertex collection - driver.graphCreateVertexCollection(this.graphName, this.collectionName); - // create vertex - final VertexEntity v1 = driver.graphCreateVertex(this.graphName, this.collectionName, - new TestComplexEntity01("xxx", "yyy", 83), null); - // check exists vertex - final VertexEntity vertex = driver.graphGetVertex(this.graphName, this.collectionName, - v1.getDocumentKey(), TestComplexEntity01.class, null, null); - assertThat(vertex.getCode(), is(200)); - - // update - final String rev = vertex.getDocumentRevision(); - VertexEntity updatedVertex = driver.graphUpdateVertex(this.graphName, this.collectionName, - vertex.getDocumentKey(), new TestComplexEntity01("zzz", null, 99), null, true, rev, null); - assertThat(updatedVertex.getCode(), is(200)); - assertThat(updatedVertex.isError(), is(false)); - - assertThat(updatedVertex.getDocumentHandle(), is(v1.getDocumentHandle())); - assertThat(updatedVertex.getDocumentRevision(), is(not(v1.getDocumentRevision()))); - assertThat(updatedVertex.getDocumentRevision(), is(notNullValue())); - assertThat(updatedVertex.getDocumentKey(), is(v1.getDocumentKey())); - - updatedVertex = driver.graphGetVertex(this.graphName, this.collectionName, vertex.getDocumentKey(), - TestComplexEntity01.class); - - assertThat(updatedVertex.getEntity().getUser(), is("zzz")); - assertThat(updatedVertex.getEntity().getDesc(), is("yyy")); - assertThat(updatedVertex.getEntity().getAge(), is(99)); - - // check count - assertThat(driver.getCollectionCount(this.collectionName).getCount(), is(1L)); - - } - - @Test - public void test_vertex_update_ifmatch_ne() throws ArangoException { - - // create graph - driver.createGraph(this.graphName, this.createEdgeDefinitions(2, 0), this.createOrphanCollections(2), true); - // create vertex collection - driver.graphCreateVertexCollection(this.graphName, this.collectionName); - // create vertex - final VertexEntity v1 = driver.graphCreateVertex(this.graphName, this.collectionName, - new TestComplexEntity01("Homer", "A Sompsin", 83), null); - // check exists vertex - final VertexEntity vertex = driver.graphGetVertex(this.graphName, this.collectionName, - v1.getDocumentKey(), TestComplexEntity01.class, null, null); - assertThat(vertex.getCode(), is(200)); - - // update - try { - final String rev = vertex.getDocumentRevision() + 1; - driver.graphUpdateVertex(this.graphName, this.collectionName, vertex.getDocumentKey(), - new TestComplexEntity01("zzz", null, 99), null, true, rev, null); - fail(); - } catch (final ArangoException e) { - assertThat(e.getCode(), is(412)); - assertThat(e.getErrorNumber(), is(1903)); - assertThat(e.getErrorMessage(), is("wrong revision")); - } - - } - -} diff --git a/src/test/java/com/arangodb/ArangoDriverImportTest.java b/src/test/java/com/arangodb/ArangoDriverImportTest.java deleted file mode 100644 index f16fae9d2..000000000 --- a/src/test/java/com/arangodb/ArangoDriverImportTest.java +++ /dev/null @@ -1,438 +0,0 @@ -/* - * Copyright (C) 2012,2013 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb; - -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.junit.Before; -import org.junit.Test; - -import com.arangodb.entity.BaseDocument; -import com.arangodb.entity.CollectionOptions; -import com.arangodb.entity.CollectionType; -import com.arangodb.entity.ImportResultEntity; -import com.arangodb.util.ImportOptions; -import com.arangodb.util.ImportOptions.OnDuplicate; -import com.arangodb.util.ImportOptionsJson; -import com.arangodb.util.ImportOptionsRaw; -import com.arangodb.util.ImportOptionsRaw.ImportType; -import com.arangodb.util.TestUtils; - -/** - * @author tamtam180 - kirscheless at gmail.com - * - */ -@SuppressWarnings("unchecked") -public class ArangoDriverImportTest extends BaseTest { - - private static final String UT_IMPORT_TEST = "ut-import-test"; - private static final String UT_IMPORT_TEST_EDGE = "ut-import-test-edge"; - - @Before - public void setUp() { - try { - driver.deleteCollection(UT_IMPORT_TEST); - } catch (final ArangoException e) { - } - try { - driver.createCollection(UT_IMPORT_TEST); - } catch (final ArangoException e) { - } - try { - driver.deleteCollection(UT_IMPORT_TEST_EDGE); - } catch (final ArangoException e) { - } - try { - CollectionOptions options = new CollectionOptions(); - options.setType(CollectionType.EDGE); - driver.createCollection(UT_IMPORT_TEST_EDGE, options); - } catch (final ArangoException e) { - } - } - - @Test - public void test_import_documents() throws ArangoException, IOException { - - final List stations = TestUtils.readStations(); - final ImportResultEntity result = driver.importDocuments(UT_IMPORT_TEST, stations); - - assertThat(result.getStatusCode(), is(201)); - assertThat(result.isError(), is(false)); - assertThat(result.getCreated(), is(632)); - assertThat(result.getErrors(), is(0)); - assertThat(result.getEmpty(), is(0)); - - } - - @Test - public void test_import_documents_404() throws ArangoException, IOException { - - try { - driver.deleteCollection(UT_IMPORT_TEST); - } catch (final ArangoException e) { - } - - final List stations = TestUtils.readStations(); - try { - driver.importDocuments(UT_IMPORT_TEST, stations); - fail(); - } catch (final ArangoException e) { - assertThat(e.getCode(), is(404)); - assertThat(e.getErrorNumber(), is(1203)); - } - - } - - @Test - public void test_import_xsv_404() throws ArangoException, IOException { - - try { - driver.deleteCollection(UT_IMPORT_TEST); - } catch (final ArangoException e) { - } - - final List> values = new ArrayList>(); - values.add(Arrays.asList("firstName", "lastName", "age", "gender")); - values.add(Arrays.asList("Joe", "Public", 42, "male", 10)); // error - values.add(Arrays.asList("Jane", "Doe", 31, "female")); - - try { - driver.importDocuments(UT_IMPORT_TEST, values); - fail(); - } catch (final ArangoException e) { - assertThat(e.getCode(), is(404)); - assertThat(e.getErrorNumber(), is(1203)); - } - - } - - @Test - public void test_import_updateOnDuplicate() throws ArangoException, IOException { - - Collection docs = new ArrayList(); - for (int i = 0; i < 100; i++) { - BaseDocument doc = new BaseDocument(); - doc.setDocumentKey(String.valueOf(i)); - docs.add(doc); - } - ImportOptionsJson options = new ImportOptionsJson(); - { - final ImportResultEntity result = driver.importDocuments(UT_IMPORT_TEST, docs, options); - assertThat(result.getStatusCode(), is(201)); - assertThat(result.isError(), is(false)); - assertThat(result.getCreated(), is(docs.size())); - } - options.setOnDuplicate(OnDuplicate.UPDATE); - { - final ImportResultEntity result = driver.importDocuments(UT_IMPORT_TEST, docs, options); - assertThat(result.getStatusCode(), is(201)); - assertThat(result.isError(), is(false)); - assertThat(result.getCreated(), is(0)); - assertThat(result.getUpdated(), is(docs.size())); - } - } - - @Test - public void test_import_ignoreOnDuplicate() throws ArangoException, IOException { - - Collection docs = new ArrayList(); - for (int i = 0; i < 100; i++) { - BaseDocument doc = new BaseDocument(); - doc.setDocumentKey(String.valueOf(i)); - docs.add(doc); - } - ImportOptionsJson options = new ImportOptionsJson(); - { - final ImportResultEntity result = driver.importDocuments(UT_IMPORT_TEST, docs, options); - assertThat(result.getStatusCode(), is(201)); - assertThat(result.isError(), is(false)); - assertThat(result.getCreated(), is(docs.size())); - } - options.setOnDuplicate(OnDuplicate.IGNORE); - { - final ImportResultEntity result = driver.importDocuments(UT_IMPORT_TEST, docs, options); - assertThat(result.getStatusCode(), is(201)); - assertThat(result.isError(), is(false)); - assertThat(result.getCreated(), is(0)); - assertThat(result.getIgnored(), is(docs.size())); - } - } - - @Test - public void test_import_replaceOnDuplicate() throws ArangoException, IOException { - - Collection docs = new ArrayList(); - for (int i = 0; i < 100; i++) { - BaseDocument doc = new BaseDocument(); - doc.setDocumentKey(String.valueOf(i)); - docs.add(doc); - } - ImportOptionsJson options = new ImportOptionsJson(); - { - final ImportResultEntity result = driver.importDocuments(UT_IMPORT_TEST, docs, options); - assertThat(result.getStatusCode(), is(201)); - assertThat(result.isError(), is(false)); - assertThat(result.getCreated(), is(docs.size())); - } - options.setOnDuplicate(OnDuplicate.REPLACE); - { - final ImportResultEntity result = driver.importDocuments(UT_IMPORT_TEST, docs, options); - assertThat(result.getStatusCode(), is(201)); - assertThat(result.isError(), is(false)); - assertThat(result.getCreated(), is(0)); - assertThat(result.getUpdated(), is(docs.size())); - } - } - - @Test - public void test_import_errorOnDuplicate() throws ArangoException, IOException { - - Collection docs = new ArrayList(); - for (int i = 0; i < 100; i++) { - BaseDocument doc = new BaseDocument(); - doc.setDocumentKey(String.valueOf(i)); - docs.add(doc); - } - ImportOptionsJson options = new ImportOptionsJson(); - { - final ImportResultEntity result = driver.importDocuments(UT_IMPORT_TEST, docs, options); - assertThat(result.getStatusCode(), is(201)); - assertThat(result.isError(), is(false)); - assertThat(result.getCreated(), is(docs.size())); - } - options.setOnDuplicate(OnDuplicate.ERROR); - { - final ImportResultEntity result = driver.importDocuments(UT_IMPORT_TEST, docs, options); - assertThat(result.getStatusCode(), is(201)); - assertThat(result.isError(), is(false)); - assertThat(result.getCreated(), is(0)); - assertThat(result.getErrors(), is(docs.size())); - } - } - - @Test - public void test_import_overwrite() throws ArangoException, IOException { - ImportOptionsJson options = new ImportOptionsJson(); - { - Collection docs = new ArrayList(); - for (int i = 0; i < 100; i++) { - BaseDocument doc = new BaseDocument(); - doc.setDocumentKey(String.valueOf(i)); - docs.add(doc); - } - { - final ImportResultEntity result = driver.importDocuments(UT_IMPORT_TEST, docs, options); - assertThat(result.getStatusCode(), is(201)); - assertThat(result.isError(), is(false)); - assertThat(result.getCreated(), is(docs.size())); - assertThat(docs.size(), is(driver.getDocuments(UT_IMPORT_TEST).size())); - } - } - { - Collection docs2 = new ArrayList(); - for (int i = 0; i < 50; i++) { - BaseDocument doc = new BaseDocument(); - doc.setDocumentKey(String.valueOf(-i)); - docs2.add(doc); - } - options.setOverwrite(true); - { - final ImportResultEntity result = driver.importDocuments(UT_IMPORT_TEST, docs2, options); - assertThat(result.getStatusCode(), is(201)); - assertThat(result.isError(), is(false)); - assertThat(result.getCreated(), is(docs2.size())); - assertThat(docs2.size(), is(driver.getDocuments(UT_IMPORT_TEST).size())); - } - } - } - - @Test - public void test_import_from_to_Prefix() throws ArangoException, IOException { - ImportOptionsJson options = new ImportOptionsJson(); - { - Collection docs = new ArrayList(); - for (int i = 0; i < 100; i++) { - BaseDocument doc = new BaseDocument(); - doc.setDocumentKey(String.valueOf(i)); - docs.add(doc); - } - { - final ImportResultEntity result = driver.importDocuments(UT_IMPORT_TEST, docs, options); - assertThat(result.getStatusCode(), is(201)); - assertThat(result.isError(), is(false)); - assertThat(result.getCreated(), is(docs.size())); - } - } - { - Collection> edgeDocs = new ArrayList>(); - for (int i = 0; i < 100; i++) { - final HashMap doc = new HashMap(); - doc.put(BaseDocument.KEY, String.valueOf(i)); - doc.put(BaseDocument.FROM, String.valueOf(i)); - doc.put(BaseDocument.TO, String.valueOf(i)); - edgeDocs.add(doc); - } - options.setFromPrefix(UT_IMPORT_TEST); - options.setToPrefix(UT_IMPORT_TEST); - final ImportResultEntity result = driver.importDocuments(UT_IMPORT_TEST_EDGE, edgeDocs, options); - assertThat(result.getStatusCode(), is(201)); - assertThat(result.isError(), is(false)); - assertThat(result.getCreated(), is(edgeDocs.size())); - } - } - - @Test - public void test_import_from_to_Prefix_with_errors_details() throws ArangoException, IOException { - ImportOptionsJson options = new ImportOptionsJson(); - { - Collection docs = new ArrayList(); - for (int i = 0; i < 100; i++) { - BaseDocument doc = new BaseDocument(); - doc.setDocumentKey(String.valueOf(i)); - docs.add(doc); - } - { - final ImportResultEntity result = driver.importDocuments(UT_IMPORT_TEST, docs, options); - assertThat(result.getStatusCode(), is(201)); - assertThat(result.isError(), is(false)); - assertThat(result.getCreated(), is(docs.size())); - } - } - { - Collection> edgeDocs = new ArrayList>(); - for (int i = 0; i < 100; i++) { - final HashMap doc = new HashMap(); - doc.put(BaseDocument.KEY, String.valueOf(i)); - // doc.put(BaseDocument.FROM, String.valueOf(i)); - doc.put(BaseDocument.TO, String.valueOf(i)); - edgeDocs.add(doc); - } - options.setFromPrefix(UT_IMPORT_TEST); - options.setToPrefix(UT_IMPORT_TEST); - options.setDetails(true); - final ImportResultEntity result = driver.importDocuments(UT_IMPORT_TEST_EDGE, edgeDocs, options); - assertThat(result.getStatusCode(), is(201)); - assertThat(result.isError(), is(false)); - assertThat(result.getErrors(), is(edgeDocs.size())); - assertThat(result.getDetails().size(), is(edgeDocs.size())); - } - } - - @Test - public void test_import_rawList() throws ArangoException { - String values = "[{\"_key\":\"a\"},{\"_key\":\"b\"}]"; - ImportOptionsRaw importOptionsRaw = new ImportOptionsRaw(ImportType.LIST); - final ImportResultEntity result = driver.importDocumentsRaw(UT_IMPORT_TEST, values, importOptionsRaw); - assertThat(result.getStatusCode(), is(201)); - assertThat(result.isError(), is(false)); - assertThat(result.getCreated(), is(2)); - } - - @Test - public void test_import_rawDocuments() throws ArangoException { - String values = "{\"_key\":\"a\"}\n{\"_key\":\"b\"}"; - ImportOptionsRaw importOptionsRaw = new ImportOptionsRaw(ImportType.DOCUMENTS); - final ImportResultEntity result = driver.importDocumentsRaw(UT_IMPORT_TEST, values, importOptionsRaw); - assertThat(result.getStatusCode(), is(201)); - assertThat(result.isError(), is(false)); - assertThat(result.getCreated(), is(2)); - } - - @Test - public void test_import_rawAutoList() throws ArangoException { - String values = "[{\"_key\":\"a\"},{\"_key\":\"b\"}]"; - ImportOptionsRaw importOptionsRaw = new ImportOptionsRaw(ImportType.LIST); - final ImportResultEntity result = driver.importDocumentsRaw(UT_IMPORT_TEST, values, importOptionsRaw); - assertThat(result.getStatusCode(), is(201)); - assertThat(result.isError(), is(false)); - assertThat(result.getCreated(), is(2)); - } - - @Test - public void test_import_rawAutoDocuments() throws ArangoException { - String values = "{\"_key\":\"a\"}\n{\"_key\":\"b\"}"; - ImportOptionsRaw importOptionsRaw = new ImportOptionsRaw(ImportType.AUTO); - final ImportResultEntity result = driver.importDocumentsRaw(UT_IMPORT_TEST, values, importOptionsRaw); - assertThat(result.getStatusCode(), is(201)); - assertThat(result.isError(), is(false)); - assertThat(result.getCreated(), is(2)); - } - - @Test - public void test_import_xsv() throws ArangoException, IOException { - - final List> values = new ArrayList>(); - values.add(Arrays.asList("firstName", "lastName", "age", "gender")); - values.add(Arrays.asList("Joe", "Public", 42, "male")); - values.add(Arrays.asList("Jane", "Doe", 31, "female")); - - final ImportResultEntity result = driver.importDocumentsByHeaderValues(UT_IMPORT_TEST, values); - - assertThat(result.getStatusCode(), is(201)); - assertThat(result.isError(), is(false)); - assertThat(result.getCreated(), is(2)); - assertThat(result.getErrors(), is(0)); - assertThat(result.getEmpty(), is(0)); - assertThat(result.getUpdated(), is(0)); - assertThat(result.getIgnored(), is(0)); - assertThat(result.getDetails().size(), is(0)); - } - - @Test - public void test_import_xsv_errors() throws ArangoException, IOException { - - final List> values = new ArrayList>(); - values.add(Arrays.asList("firstName", "lastName", "age", "gender")); - values.add(Arrays.asList("Joe", "Public", 42, "male", 10)); // error - values.add(Arrays.asList("Jane", "Doe", 31, "female")); - - final ImportResultEntity result = driver.importDocumentsByHeaderValues(UT_IMPORT_TEST, values); - - assertThat(result.getStatusCode(), is(201)); - assertThat(result.isError(), is(false)); - assertThat(result.getCreated(), is(1)); - assertThat(result.getErrors(), is(1)); - assertThat(result.getEmpty(), is(0)); - assertThat(result.getUpdated(), is(0)); - assertThat(result.getIgnored(), is(0)); - assertThat(result.getDetails().size(), is(0)); - } - - @Test - public void test_import_xsv_raw() throws ArangoException, IOException { - - final String values = "[\"firstName\",\"lastName\",\"age\",\"gender\"]\n[\"Joe\",\"Public\",42,\"male\"]\n[\"Jane\",\"Doe\",31,\"female\"]"; - - final ImportResultEntity result = driver.importDocumentsByHeaderValuesRaw(UT_IMPORT_TEST, values, - new ImportOptions()); - - assertThat(result.getStatusCode(), is(201)); - assertThat(result.isError(), is(false)); - assertThat(result.getCreated(), is(2)); - } - -} diff --git a/src/test/java/com/arangodb/ArangoDriverIndexTest.java b/src/test/java/com/arangodb/ArangoDriverIndexTest.java deleted file mode 100644 index d81a7eabd..000000000 --- a/src/test/java/com/arangodb/ArangoDriverIndexTest.java +++ /dev/null @@ -1,420 +0,0 @@ -/* - * Copyright (C) 2012 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb; - -import static org.hamcrest.CoreMatchers.hasItems; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.not; -import static org.hamcrest.CoreMatchers.notNullValue; -import static org.hamcrest.CoreMatchers.nullValue; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; - -import java.util.Arrays; - -import org.junit.After; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.arangodb.entity.CollectionEntity; -import com.arangodb.entity.IndexEntity; -import com.arangodb.entity.IndexType; -import com.arangodb.entity.IndexesEntity; - -/** - * @author tamtam180 - kirscheless at gmail.com - * - */ -public class ArangoDriverIndexTest extends BaseTest { - - private static Logger logger = LoggerFactory.getLogger(ArangoDriverCollectionTest.class); - - private final String collectionName = "unit_test_arango_index"; // - private final String collectionName404 = "unit_test_arango_404"; // 存在しないコレクション名 - - CollectionEntity col1; - - @Before - public void before() throws ArangoException { - - logger.debug("----------"); - - // 事前に消しておく - try { - driver.deleteCollection(collectionName); - } catch (final ArangoException e) { - } - try { - driver.deleteCollection(collectionName404); - } catch (final ArangoException e) { - } - - // 1は作る - col1 = driver.createCollection(collectionName); - - logger.debug("--"); - - } - - @After - public void after() { - logger.debug("----------"); - } - - @Test - public void test_create_index() throws ArangoException { - - { - final IndexEntity entity = driver.createIndex(collectionName, IndexType.GEO, false, "a"); - - assertThat(entity, is(notNullValue())); - assertThat(entity.getCode(), is(201)); - assertThat(entity.isError(), is(false)); - assertThat(entity.isNewlyCreated(), is(true)); - assertThat(entity.isGeoJson(), is(false)); - assertThat(entity.getId(), is(notNullValue())); - assertThat(entity.getType(), is(IndexType.GEO)); - } - - // 重複して作成する - { - final IndexEntity entity = driver.createIndex(collectionName, IndexType.GEO, false, "a"); - - assertThat(entity, is(notNullValue())); - assertThat(entity.getCode(), is(200)); - assertThat(entity.isError(), is(false)); - assertThat(entity.isNewlyCreated(), is(false)); - assertThat(entity.isGeoJson(), is(false)); - assertThat(entity.getId(), is(notNullValue())); - assertThat(entity.getType(), is(IndexType.GEO)); - } - - } - - @Test - public void test_create_index_404() throws ArangoException { - - try { - driver.createIndex(collectionName404, IndexType.GEO, false, "a"); - fail("We expect an Exception here"); - } catch (final ArangoException e) { - assertThat(e.getErrorNumber(), is(1203)); // FIXME MagicNumber - } - - } - - @Test - public void test_create_geo_index_unique() throws ArangoException { - - final IndexEntity entity = driver.createIndex(collectionName, IndexType.GEO, true, "a", "b"); - - assertThat(entity, is(notNullValue())); - assertThat(entity.getCode(), is(201)); - assertThat(entity.isError(), is(false)); - assertThat(entity.isNewlyCreated(), is(true)); - assertThat(entity.isGeoJson(), is(false)); - assertThat(entity.getId(), is(notNullValue())); - assertThat(entity.getType(), is(IndexType.GEO)); - - } - - @Test - public void test_create_geo_index_over_columnnum() throws ArangoException { - - // GeoIndexは2つまで。だけど3つを指定した場合のエラー確認 - - try { - driver.createIndex(collectionName, IndexType.GEO, true, "a", "b", "c"); - fail("We expect an Exception here"); - } catch (final ArangoException e) { - assertThat(e.getErrorNumber(), is(ErrorNums.ERROR_BAD_PARAMETER)); - } - - } - - @Test - public void test_create_hash_index() throws ArangoException { - - final IndexEntity entity = driver.createIndex(collectionName, IndexType.HASH, false, "a", "b", "c", "d", "e", - "f", "g"); - - assertThat(entity, is(notNullValue())); - assertThat(entity.getCode(), is(201)); - assertThat(entity.isError(), is(false)); - assertThat(entity.isNewlyCreated(), is(true)); - assertThat(entity.isGeoJson(), is(false)); - assertThat(entity.getId(), is(notNullValue())); - assertThat(entity.getType(), is(IndexType.HASH)); - - } - - @Test - public void test_create_hash_index_404() throws ArangoException { - - try { - driver.createIndex(collectionName404, IndexType.HASH, false, "a", "b", "c", "d", "e", "f", "g"); - fail("We expect an Exception here"); - } catch (final ArangoException e) { - assertThat(e.getErrorNumber(), is(ErrorNums.ERROR_ARANGO_COLLECTION_NOT_FOUND)); - } - - } - - @Test - public void test_create_hash_index_unique() throws ArangoException { - - final IndexEntity entity = driver.createIndex(collectionName, IndexType.HASH, true, "a", "b", "c", "d", "e", - "f", "g"); - - assertThat(entity, is(notNullValue())); - assertThat(entity.getCode(), is(201)); - assertThat(entity.isError(), is(false)); - assertThat(entity.isNewlyCreated(), is(true)); - assertThat(entity.isGeoJson(), is(false)); - assertThat(entity.getId(), is(notNullValue())); - assertThat(entity.getType(), is(IndexType.HASH)); - - } - - @Test - public void test_create_skiplist_index() throws ArangoException { - - final IndexEntity entity = driver.createIndex(collectionName, IndexType.SKIPLIST, false, "a", "b", "c", "d", - "e", "f", "g"); - - assertThat(entity, is(notNullValue())); - assertThat(entity.getCode(), is(201)); - assertThat(entity.isError(), is(false)); - assertThat(entity.isNewlyCreated(), is(true)); - assertThat(entity.isGeoJson(), is(false)); - assertThat(entity.getId(), is(notNullValue())); - assertThat(entity.getType(), is(IndexType.SKIPLIST)); - assertThat(entity.getFields().get(0), is("a")); - assertThat(entity.getFields().get(1), is("b")); - assertThat(entity.getFields().get(2), is("c")); - assertThat(entity.getFields().get(3), is("d")); - assertThat(entity.getFields().get(4), is("e")); - assertThat(entity.getFields().get(5), is("f")); - assertThat(entity.getFields().get(6), is("g")); - } - - @Test - public void test_create_skiplist_index_unique() throws ArangoException { - - final IndexEntity entity = driver.createIndex(collectionName, IndexType.SKIPLIST, true, "a", "b", "c", "d", "e", - "f", "g"); - - assertThat(entity, is(notNullValue())); - assertThat(entity.getCode(), is(201)); - assertThat(entity.isError(), is(false)); - assertThat(entity.isNewlyCreated(), is(true)); - assertThat(entity.isGeoJson(), is(false)); - assertThat(entity.getId(), is(notNullValue())); - assertThat(entity.getType(), is(IndexType.SKIPLIST)); - assertThat(entity.getFields().get(0), is("a")); - assertThat(entity.getFields().get(1), is("b")); - assertThat(entity.getFields().get(2), is("c")); - assertThat(entity.getFields().get(3), is("d")); - assertThat(entity.getFields().get(4), is("e")); - assertThat(entity.getFields().get(5), is("f")); - assertThat(entity.getFields().get(6), is("g")); - } - - @Test - public void test_create_hash_index_with_document() throws ArangoException { - - for (int i = 0; i < 100; i++) { - final TestComplexEntity01 value = new TestComplexEntity01("user_" + i, "", i); - - assertThat(driver.createDocument(collectionName, value, false), is(notNullValue())); - } - - final IndexEntity entity = driver.createIndex(collectionName, IndexType.HASH, true, "name", "age"); - - assertThat(entity, is(notNullValue())); - assertThat(entity.getCode(), is(201)); - assertThat(entity.isError(), is(false)); - assertThat(entity.isNewlyCreated(), is(true)); - assertThat(entity.isGeoJson(), is(false)); - assertThat(entity.getId(), is(notNullValue())); - assertThat(entity.getType(), is(IndexType.HASH)); - - } - - @Test - public void test_create_fulltext_index() throws ArangoException { - - // create test data 100 count. - for (int i = 0; i < 100; i++) { - final String desc = i % 2 == 0 ? "寿司" : "天ぷら"; - final TestComplexEntity01 value = new TestComplexEntity01("user_" + i, desc, i); - assertThat(driver.createDocument(collectionName, value, false), is(notNullValue())); - } - - // create fulltext index - final IndexEntity index = driver.createFulltextIndex(collectionName, 1, "desc"); - - // {"id":"unit_test_arango_index/6420761720","unique":false,"type":"fulltext","minLength":1,"fields":["desc"],"isNewlyCreated":true,"error":false,"code":201} - assertThat(index.getCode(), is(201)); - assertThat(index.isError(), is(false)); - assertThat(index.getId(), is(not(nullValue()))); - assertThat(index.isUnique(), is(false)); - assertThat(index.getType(), is(IndexType.FULLTEXT)); - assertThat(index.getMinLength(), is(1)); - assertThat(index.getFields(), is(Arrays.asList("desc"))); - assertThat(index.isNewlyCreated(), is(true)); - - } - - @Test - public void test_create_persistent_index() throws ArangoException { - - final IndexEntity entity = driver.createIndex(collectionName, IndexType.PERSISTENT, false, "a", "b", "c", "d", - "e", "f", "g"); - - assertThat(entity, is(notNullValue())); - assertThat(entity.getCode(), is(201)); - assertThat(entity.isError(), is(false)); - assertThat(entity.isNewlyCreated(), is(true)); - assertThat(entity.isGeoJson(), is(false)); - assertThat(entity.getId(), is(notNullValue())); - assertThat(entity.getType(), is(IndexType.PERSISTENT)); - - } - - @Test - public void test_create_persistent_index2() throws ArangoException { - - final IndexEntity entity = driver.createPersistentIndex(collectionName, true, false, "a", "b", "c", "d", "e", - "f", "g"); - - assertThat(entity, is(notNullValue())); - assertThat(entity.getCode(), is(201)); - assertThat(entity.isError(), is(false)); - assertThat(entity.isNewlyCreated(), is(true)); - assertThat(entity.isGeoJson(), is(false)); - assertThat(entity.getId(), is(notNullValue())); - assertThat(entity.getType(), is(IndexType.PERSISTENT)); - - } - - @Test - public void test_delete_index() throws ArangoException { - - final IndexEntity entity = driver.createIndex(collectionName, IndexType.HASH, true, "name", "age"); - assertThat(entity, is(notNullValue())); - assertThat(entity.getId(), is(notNullValue())); - - final String id = entity.getId(); - - final IndexEntity entity2 = driver.deleteIndex(id); - - assertThat(entity2, is(notNullValue())); - assertThat(entity2.getCode(), is(200)); - assertThat(entity2.isError(), is(false)); - assertThat(entity2.getId(), is(id)); - - } - - @Test - public void test_delete_index_pk() throws ArangoException { - - // PKは削除できない - try { - driver.deleteIndex(collectionName + "/0"); - fail("例外が飛ばないといけない"); - } catch (final ArangoException e) { - assertThat(e.getErrorNumber(), is(1212)); - } - - } - - @Test - public void test_delete_index_404_1() throws ArangoException { - - // コレクションは存在するが、存在しないインデックスを削除しようとした - - try { - driver.deleteIndex(collectionName + "/1"); - fail("例外が飛ばないといけない"); - } catch (final ArangoException e) { - assertThat(e.getErrorNumber(), is(1212)); - } - - } - - /** - * ユニークインデックスの列が重複した場合。 TODO: あとで - * - * @throws ArangoException - */ - @Test - @Ignore - public void test_create_hash_index_dup_unique() throws ArangoException { - - final IndexEntity entity = driver.createIndex(collectionName, IndexType.HASH, true, "user", "age"); - - assertThat(driver.createDocument(collectionName, new TestComplexEntity01("寿司天ぷら", "", 18), false), - is(notNullValue())); - assertThat(driver.createDocument(collectionName, new TestComplexEntity01("寿司天ぷら", "", 18), false), - is(notNullValue())); - - assertThat(entity, is(notNullValue())); - assertThat(entity.getCode(), is(201)); - assertThat(entity.isError(), is(false)); - assertThat(entity.isNewlyCreated(), is(true)); - assertThat(entity.isGeoJson(), is(false)); - assertThat(entity.getId(), is(notNullValue())); - assertThat(entity.getType(), is(IndexType.HASH)); - - } - - @Test - public void test_getIndexes() throws ArangoException { - - final IndexEntity entity = driver.createIndex(collectionName, IndexType.HASH, true, "name", "age"); - assertThat(entity, is(notNullValue())); - - final IndexesEntity indexes = driver.getIndexes(collectionName); - - assertThat(indexes, is(notNullValue())); - - assertThat(indexes.getIndexes().size(), is(2)); - assertThat(indexes.getIndexes().get(0).getType(), is(IndexType.PRIMARY)); - assertThat(indexes.getIndexes().get(0).getFields().size(), is(1)); - assertThat(indexes.getIndexes().get(0).getFields().get(0), is("_key")); - assertThat(indexes.getIndexes().get(1).getType(), is(IndexType.HASH)); - assertThat(indexes.getIndexes().get(1).getFields().size(), is(2)); - assertThat(indexes.getIndexes().get(1).getFields(), hasItems("name", "age")); - - final String id1 = indexes.getIndexes().get(0).getId(); - final String id2 = indexes.getIndexes().get(1).getId(); - - assertThat(indexes.getIdentifiers().size(), is(2)); - assertThat(indexes.getIdentifiers().get(id1).getType(), is(IndexType.PRIMARY)); - assertThat(indexes.getIdentifiers().get(id1).getFields().size(), is(1)); - assertThat(indexes.getIdentifiers().get(id1).getFields().get(0), is("_key")); - assertThat(indexes.getIdentifiers().get(id2).getType(), is(IndexType.HASH)); - assertThat(indexes.getIdentifiers().get(id2).getFields().size(), is(2)); - assertThat(indexes.getIdentifiers().get(id2).getFields(), hasItems("name", "age")); - - } - -} diff --git a/src/test/java/com/arangodb/ArangoDriverQueryCacheTest.java b/src/test/java/com/arangodb/ArangoDriverQueryCacheTest.java deleted file mode 100644 index 54de07958..000000000 --- a/src/test/java/com/arangodb/ArangoDriverQueryCacheTest.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright (C) 2012,2013 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -import org.junit.Test; - -import com.arangodb.entity.DefaultEntity; -import com.arangodb.entity.QueryCachePropertiesEntity; -import com.arangodb.entity.QueryCachePropertiesEntity.CacheMode; -import com.arangodb.util.TestUtils; - -/** - * @author tamtam180 - kirscheless at gmail.com - * - */ -public class ArangoDriverQueryCacheTest extends BaseTest { - - @Test - public void test_deleteQueryCache() throws ArangoException { - if (isMinimumVersion(TestUtils.VERSION_2_7)) { - final DefaultEntity ret = driver.deleteQueryCache(); - assertEquals(200, ret.getStatusCode()); - assertEquals(200, ret.getCode()); - assertEquals(false, ret.isError()); - } - } - - @Test - public void test_getQueryCacheProperties() throws ArangoException { - if (isMinimumVersion(TestUtils.VERSION_2_7)) { - final QueryCachePropertiesEntity ret = driver.getQueryCacheProperties(); - assertEquals(200, ret.getStatusCode()); - assertNotNull(ret.getMode()); - assertNotNull(ret.getMaxResults()); - } - } - - @Test - public void test_setQueryCacheProperties() throws ArangoException { - - if (isMinimumVersion(TestUtils.VERSION_2_7)) { - final QueryCachePropertiesEntity properties = new QueryCachePropertiesEntity(); - properties.setMode(CacheMode.on); - properties.setMaxResults(100L); - - QueryCachePropertiesEntity ret = driver.setQueryCacheProperties(properties); - assertEquals(200, ret.getStatusCode()); - assertEquals(CacheMode.on, ret.getMode()); - assertEquals(new Long(100L), ret.getMaxResults()); - - properties.setMode(CacheMode.off); - properties.setMaxResults(200L); - - ret = driver.setQueryCacheProperties(properties); - assertEquals(200, ret.getStatusCode()); - assertEquals(CacheMode.off, ret.getMode()); - assertEquals(new Long(200L), ret.getMaxResults()); - } - } -} diff --git a/src/test/java/com/arangodb/ArangoDriverQueryTest.java b/src/test/java/com/arangodb/ArangoDriverQueryTest.java deleted file mode 100644 index 4ef1ccb18..000000000 --- a/src/test/java/com/arangodb/ArangoDriverQueryTest.java +++ /dev/null @@ -1,248 +0,0 @@ -/* - * Copyright (C) 2012,2013 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.junit.Test; - -import com.arangodb.entity.DefaultEntity; -import com.arangodb.entity.QueriesResultEntity; -import com.arangodb.entity.QueryEntity; -import com.arangodb.entity.QueryTrackingPropertiesEntity; - -/** - * @author a-brandt - * - */ -public class ArangoDriverQueryTest extends BaseTest { - - @Test - public void test_getQueryTrackingProperties() throws ArangoException { - final QueryTrackingPropertiesEntity queryTrackingProperties = driver.getQueryTrackingProperties(); - assertEquals(200, queryTrackingProperties.getStatusCode()); - assertNotNull(queryTrackingProperties.getEnabled()); - assertNotNull(queryTrackingProperties.getTrackSlowQueries()); - assertNotNull(queryTrackingProperties.getSlowQueryThreshold()); - assertNotNull(queryTrackingProperties.getMaxSlowQueries()); - assertNotNull(queryTrackingProperties.getMaxQueryStringLength()); - } - - @Test - public void test_setQueryTrackingProperties() throws ArangoException { - final QueryTrackingPropertiesEntity properties1 = driver.getQueryTrackingProperties(); - - final Long maxQueryStringLength = properties1.getMaxQueryStringLength() + 10; - - properties1.setMaxQueryStringLength(maxQueryStringLength); - - final QueryTrackingPropertiesEntity properties2 = driver.setQueryTrackingProperties(properties1); - - assertEquals(200, properties2.getStatusCode()); - assertNotNull(properties2.getEnabled()); - assertNotNull(properties2.getTrackSlowQueries()); - assertNotNull(properties2.getSlowQueryThreshold()); - assertNotNull(properties2.getMaxSlowQueries()); - assertNotNull(properties2.getMaxQueryStringLength()); - assertEquals(maxQueryStringLength, properties2.getMaxQueryStringLength()); - } - - @Test - public void test_getCurrentlyRunningQueries() throws ArangoException, InterruptedException { - - final String queryString = "return sleep(3)"; - - final Thread thread1 = new Thread(new RunnableThread(driver.getDefaultDatabase(), configure, queryString), - "thread1"); - thread1.start(); - - Thread.sleep(1000); - - final QueriesResultEntity currentlyRunningQueries = driver.getCurrentlyRunningQueries(); - - // wait for thread - thread1.join(); - - // check result - assertEquals(200, currentlyRunningQueries.getStatusCode()); - final List queries = currentlyRunningQueries.getQueries(); - assertEquals(1, queries.size()); - } - - @Test - public void test_getCurrentlyRunningQueriesWithoutDatabase() throws ArangoException, InterruptedException { - - final String queryString = "return sleep(3)"; - - // create job in _system database - final Thread thread1 = new Thread(new RunnableThread(null, configure, queryString), "thread1"); - thread1.start(); - - Thread.sleep(1000); - - // search in default database - final QueriesResultEntity currentlyRunningQueries = driver.getCurrentlyRunningQueries(); - - // wait for thread - thread1.join(); - - // check result - assertEquals(200, currentlyRunningQueries.getStatusCode()); - final List queries = currentlyRunningQueries.getQueries(); - assertEquals(0, queries.size()); - } - - @Test - public void test_getCurrentlyRunningQueriesWithoutDatabase2() throws ArangoException, InterruptedException { - - final String queryString = "return sleep(3)"; - - // create job in _system database - final Thread thread1 = new Thread(new RunnableThread(null, configure, queryString), "thread1"); - thread1.start(); - - Thread.sleep(1000); - - // search in _system database - final QueriesResultEntity currentlyRunningQueries = driver.getCurrentlyRunningQueries(null); - - // wait for thread - thread1.join(); - - // check result - assertEquals(200, currentlyRunningQueries.getStatusCode()); - final List queries = currentlyRunningQueries.getQueries(); - assertEquals(1, queries.size()); - } - - @Test - public void test_getSlowQueries() throws ArangoException, InterruptedException { - // set SlowQueryThreshold to 2 - final QueryTrackingPropertiesEntity properties1 = driver.getQueryTrackingProperties(); - properties1.setSlowQueryThreshold(2L); - driver.setQueryTrackingProperties(properties1); - - // create a slow query - driver.executeDocumentQuery("return sleep(3)", new HashMap(), null, Map.class); - - final QueriesResultEntity currentlyRunningQueries = driver.getSlowQueries(); - - // check result - assertEquals(200, currentlyRunningQueries.getStatusCode()); - final List queries = currentlyRunningQueries.getQueries(); - assertTrue(queries.size() > 0); - } - - @Test - public void test_deleteSlowQueries() throws ArangoException, InterruptedException { - driver.deleteSlowQueries(); - QueriesResultEntity currentlyRunningQueries = driver.getSlowQueries(); - - // check result - assertEquals(200, currentlyRunningQueries.getStatusCode()); - List queries = currentlyRunningQueries.getQueries(); - assertEquals(0, queries.size()); - - // set SlowQueryThreshold to 2 - final QueryTrackingPropertiesEntity properties1 = driver.getQueryTrackingProperties(); - properties1.setSlowQueryThreshold(2L); - driver.setQueryTrackingProperties(properties1); - - // create a slow query - driver.executeDocumentQuery("return sleep(3)", new HashMap(), null, Map.class); - - currentlyRunningQueries = driver.getSlowQueries(); - - // check result - assertEquals(200, currentlyRunningQueries.getStatusCode()); - queries = currentlyRunningQueries.getQueries(); - assertEquals(1, queries.size()); - } - - @Test - public void test_killQuery() throws ArangoException, InterruptedException { - - final String queryString = "return sleep(3)"; - - // create job in _system database - final Thread thread1 = new Thread(new RunnableThread(driver.getDefaultDatabase(), configure, queryString), - "thread1"); - thread1.start(); - - Thread.sleep(1000); - - int numKilled = 0; - - // search in default database - final QueriesResultEntity currentlyRunningQueries = driver.getCurrentlyRunningQueries(); - // check result - assertEquals(200, currentlyRunningQueries.getStatusCode()); - final List queries = currentlyRunningQueries.getQueries(); - if (queries.size() > 0) { - for (final QueryEntity qe : queries) { - try { - final DefaultEntity killQuery = driver.killQuery(qe.getId()); - assertEquals(200, killQuery.getStatusCode()); - numKilled++; - } catch (final ArangoException e) { - - } - } - } - - // wait for thread - thread1.join(); - assertTrue(queries.size() > 0); - assertEquals(numKilled, queries.size()); - } - - class RunnableThread implements Runnable { - - Thread runner; - ArangoDriver driver; - String queryString; - - public RunnableThread(final String database, final ArangoConfigure configure, final String queryString) { - this.driver = new ArangoDriver(configure); - this.driver.setDefaultDatabase(database); - this.queryString = queryString; - } - - public RunnableThread(final String threadName) { - runner = new Thread(this, threadName); - runner.start(); - } - - @Override - public void run() { - try { - driver.executeDocumentQuery(queryString, new HashMap(), null, Map.class); - } catch (final ArangoException e) { - if (e.getErrorNumber() != ErrorNums.ERROR_QUERY_KILLED) { - e.printStackTrace(); - } - } - - } - } -} diff --git a/src/test/java/com/arangodb/ArangoDriverReplicationTest.java b/src/test/java/com/arangodb/ArangoDriverReplicationTest.java deleted file mode 100644 index a3a179c6b..000000000 --- a/src/test/java/com/arangodb/ArangoDriverReplicationTest.java +++ /dev/null @@ -1,563 +0,0 @@ -/* - * Copyright (C) 2012,2013 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb; - -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.not; -import static org.hamcrest.CoreMatchers.notNullValue; -import static org.hamcrest.CoreMatchers.nullValue; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; - -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicInteger; - -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.arangodb.entity.ReplicationApplierConfigEntity; -import com.arangodb.entity.ReplicationApplierStateEntity; -import com.arangodb.entity.ReplicationDumpHeader; -import com.arangodb.entity.ReplicationDumpRecord; -import com.arangodb.entity.ReplicationInventoryEntity; -import com.arangodb.entity.ReplicationInventoryEntity.Collection; -import com.arangodb.entity.ReplicationLoggerConfigEntity; -import com.arangodb.entity.ReplicationLoggerStateEntity; -import com.arangodb.util.DumpHandler; -import com.arangodb.util.DumpHandlerAdapter; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; - -/** - * @author tamtam180 - kirscheless at gmail.com - * - */ -@Ignore -public class ArangoDriverReplicationTest extends BaseTest { - - private static Logger logger = LoggerFactory.getLogger(ArangoConfigure.class); - - @Before - public void before() { - driver.setDefaultDatabase(null); - } - - @Test - public void test_get_inventory() throws ArangoException { - - try { - driver.stopReplicationLogger(); - } catch (final Exception e) { - } - - final ReplicationInventoryEntity entity = driver.getReplicationInventory(); - assertThat(entity.getCode(), is(0)); - assertThat(entity.getStatusCode(), is(200)); - - assertThat(entity.getTick(), is(not(0L))); - assertThat(entity.getState().isRunning(), is(false)); - assertThat(entity.getCollections().size(), is(not(0))); - - } - - @Test - public void test_get_inventory_includeSystem() throws ArangoException { - - final ReplicationInventoryEntity entity = driver.getReplicationInventory(true); - assertThat(entity.getCode(), is(0)); - assertThat(entity.getStatusCode(), is(200)); - - final Gson gson = new GsonBuilder().setPrettyPrinting().create(); - for (final Collection col : entity.getCollections()) { - logger.debug(gson.toJson(col.getParameter())); - logger.debug(gson.toJson(col.getIndexes())); - } - - } - - @Test - public void test_get_inventory_404() throws ArangoException { - - driver.setDefaultDatabase("database-404"); - try { - driver.getReplicationInventory(); - fail(); - } catch (final ArangoException e) { - assertThat(e.getCode(), is(404)); - assertThat(e.getErrorNumber(), is(1228)); // database not found - } - - } - - @Test - public void test_get_dump() throws ArangoException { - - final String collectionName = "rep_dump_test"; - - try { - driver.deleteCollection(collectionName); - } catch (final ArangoException e) { - } - try { - driver.createCollection(collectionName); - } catch (final ArangoException e) { - } - - // create 10 document - for (int i = 0; i < 10; i++) { - final TestComplexEntity01 entity = new TestComplexEntity01("user-" + i, "desc-" + i, 20 + i); - driver.createDocument(collectionName, entity, null); - } - // truncate - try { - driver.truncateCollection(collectionName); - } catch (final ArangoException e) { - } - // create 1 document - final TestComplexEntity01 entity = new TestComplexEntity01("user-99", "desc-99", 99); - driver.createDocument(collectionName, entity, null); - - final AtomicInteger upsertCount = new AtomicInteger(0); - final AtomicInteger deleteCount = new AtomicInteger(0); - final AtomicBoolean headCall = new AtomicBoolean(false); - driver.getReplicationDump(collectionName, null, null, null, null, TestComplexEntity01.class, - new DumpHandler() { - @Override - public boolean head(final ReplicationDumpHeader header) { - headCall.set(true); - assertThat(header.getCheckmore(), is(not(nullValue()))); - assertThat(header.getLastincluded(), is(not(nullValue()))); - assertThat(header.getLasttick(), is((nullValue()))); - assertThat(header.getActive(), is((nullValue()))); - return true; - } - - @Override - public boolean handle(final ReplicationDumpRecord entity) { - switch (entity.getType()) { - case DOCUMENT_UPSERT: - case EDGE_UPSERT: - upsertCount.getAndIncrement(); - assertThat(entity.getTick(), is(not(0L))); - assertThat(entity.getKey(), is(not(nullValue()))); - assertThat(entity.getRev(), is(notNullValue())); - assertThat(entity.getData(), is(notNullValue())); - assertThat(entity.getData().getDocumentKey(), is(notNullValue())); - assertThat(entity.getData().getDocumentRevision(), is(notNullValue())); - assertThat(entity.getData().getDocumentHandle(), is(nullValue())); - assertThat(entity.getData().getEntity().getAge(), is(not(0))); - break; - case DELETION: - deleteCount.incrementAndGet(); - assertThat(entity.getTick(), is(not(0L))); - assertThat(entity.getKey(), is(not(nullValue()))); - assertThat(entity.getRev(), is(notNullValue())); - assertThat(entity.getData(), is(nullValue())); - break; - default: - break; - } - return true; - } - - }); - - assertThat(headCall.get(), is(true)); - assertThat(upsertCount.get(), is(11)); - assertThat(deleteCount.get(), is(10)); - - } - - @Test - public void test_get_dump_noticks() throws ArangoException { - - final String collectionName = "rep_dump_test"; - - try { - driver.deleteCollection(collectionName); - } catch (final ArangoException e) { - } - try { - driver.createCollection(collectionName); - } catch (final ArangoException e) { - } - - // create 10 document - for (int i = 0; i < 10; i++) { - final TestComplexEntity01 entity = new TestComplexEntity01("user-" + i, "desc-" + i, 20 + i); - driver.createDocument(collectionName, entity, null); - } - // truncate - try { - driver.truncateCollection(collectionName); - } catch (final ArangoException e) { - } - // create 1 document - final TestComplexEntity01 entity = new TestComplexEntity01("user-99", "desc-99", 99); - driver.createDocument(collectionName, entity, null); - - final AtomicInteger upsertCount = new AtomicInteger(0); - final AtomicInteger deleteCount = new AtomicInteger(0); - driver.getReplicationDump(collectionName, null, null, null, false, TestComplexEntity01.class, - new DumpHandlerAdapter() { - @Override - public boolean handle(final ReplicationDumpRecord entity) { - switch (entity.getType()) { - case DOCUMENT_UPSERT: - case EDGE_UPSERT: - upsertCount.getAndIncrement(); - assertThat(entity.getTick(), is((0L))); - assertThat(entity.getKey(), is(not(nullValue()))); - assertThat(entity.getRev(), is(notNullValue())); - assertThat(entity.getData(), is(notNullValue())); - assertThat(entity.getData().getDocumentKey(), is(notNullValue())); - assertThat(entity.getData().getDocumentRevision(), is(notNullValue())); - assertThat(entity.getData().getDocumentHandle(), is(nullValue())); - assertThat(entity.getData().getEntity().getAge(), is(not(0))); - break; - case DELETION: - deleteCount.incrementAndGet(); - assertThat(entity.getTick(), is((0L))); - assertThat(entity.getKey(), is(not(nullValue()))); - assertThat(entity.getRev(), is(notNullValue())); - assertThat(entity.getData(), is(nullValue())); - break; - default: - break; - } - return true; - } - - }); - - assertThat(upsertCount.get(), is(11)); - assertThat(deleteCount.get(), is(10)); - - } - - @Test - public void test_get_dump_handler_control_1() throws ArangoException { - - final String collectionName = "rep_dump_test"; - - try { - driver.deleteCollection(collectionName); - } catch (final ArangoException e) { - } - try { - driver.createCollection(collectionName); - } catch (final ArangoException e) { - } - - // create 10 document - for (int i = 0; i < 10; i++) { - final TestComplexEntity01 entity = new TestComplexEntity01("user-" + i, "desc-" + i, 20 + i); - driver.createDocument(collectionName, entity, null); - } - // truncate - try { - driver.truncateCollection(collectionName); - } catch (final ArangoException e) { - } - // create 1 document - final TestComplexEntity01 entity = new TestComplexEntity01("user-99", "desc-99", 99); - driver.createDocument(collectionName, entity, null); - - final AtomicBoolean headCall = new AtomicBoolean(false); - driver.getReplicationDump(collectionName, null, null, null, null, TestComplexEntity01.class, - new DumpHandler() { - @Override - public boolean head(final ReplicationDumpHeader header) { - headCall.set(true); - return false; - } - - @Override - public boolean handle(final ReplicationDumpRecord entity) { - fail(""); - return true; - } - }); - - assertThat(headCall.get(), is(true)); - - } - - @Test - public void test_get_dump_handler_control_2() throws ArangoException { - - final String collectionName = "rep_dump_test"; - - try { - driver.deleteCollection(collectionName); - } catch (final ArangoException e) { - } - try { - driver.createCollection(collectionName); - } catch (final ArangoException e) { - } - - // create 10 document - for (int i = 0; i < 10; i++) { - final TestComplexEntity01 entity = new TestComplexEntity01("user-" + i, "desc-" + i, 20 + i); - driver.createDocument(collectionName, entity, null); - } - // truncate - try { - driver.truncateCollection(collectionName); - } catch (final ArangoException e) { - } - // create 1 document - final TestComplexEntity01 entity = new TestComplexEntity01("user-99", "desc-99", 99); - driver.createDocument(collectionName, entity, null); - - final AtomicInteger handleCount = new AtomicInteger(0); - final AtomicBoolean headCall = new AtomicBoolean(false); - driver.getReplicationDump(collectionName, null, null, null, null, TestComplexEntity01.class, - new DumpHandler() { - @Override - public boolean head(final ReplicationDumpHeader header) { - headCall.set(true); - return true; - } - - @Override - public boolean handle(final ReplicationDumpRecord entity) { - final int cnt = handleCount.incrementAndGet(); - if (cnt == 5) { - return false; - } - return true; - } - - }); - - assertThat(headCall.get(), is(true)); - assertThat(handleCount.get(), is(5)); - - } - - // TODO: Dump from-to - - // public void test_sync() throws ArangoException { - // - // driver.syncReplication(endpoint, database, username, password, - // restrictType, restrictCollections); - // - // } - - @Test - public void test_server_id() throws ArangoException { - - final String serverId = driver.getReplicationServerId(); - assertThat(serverId, is(notNullValue())); - - } - - @Test - public void test_start_logger() throws ArangoException { - - final boolean running = driver.startReplicationLogger(); - assertThat(running, is(true)); - - final boolean running2 = driver.startReplicationLogger(); - assertThat(running2, is(true)); - - } - - @Test - public void test_stop_logger() throws ArangoException { - - final boolean running = driver.stopReplicationLogger(); - assertThat(running, is(false)); - - final boolean running2 = driver.stopReplicationLogger(); - assertThat(running2, is(false)); - - } - - @Test - public void test_logger_config() throws ArangoException { - - // set - final ReplicationLoggerConfigEntity config1 = driver.setReplicationLoggerConfig(true, true, 0L, 0L); - assertThat(config1.isAutoStart(), is(true)); - assertThat(config1.isLogRemoteChanges(), is(true)); - assertThat(config1.getMaxEvents(), is(0L)); - assertThat(config1.getMaxEventsSize(), is(0L)); - - // get - final ReplicationLoggerConfigEntity config2 = driver.getReplicationLoggerConfig(); - assertThat(config2.isAutoStart(), is(true)); - assertThat(config2.isLogRemoteChanges(), is(true)); - assertThat(config2.getMaxEvents(), is(0L)); - assertThat(config2.getMaxEventsSize(), is(0L)); - - // set - final ReplicationLoggerConfigEntity config3 = driver.setReplicationLoggerConfig(false, false, 1048576L, - 134217728L); - assertThat(config3.isAutoStart(), is(false)); - assertThat(config3.isLogRemoteChanges(), is(false)); - assertThat(config3.getMaxEvents(), is(1048576L)); - assertThat(config3.getMaxEventsSize(), is(134217728L)); - - // get - final ReplicationLoggerConfigEntity config4 = driver.getReplicationLoggerConfig(); - assertThat(config4.isAutoStart(), is(false)); - assertThat(config4.isLogRemoteChanges(), is(false)); - assertThat(config4.getMaxEvents(), is(1048576L)); - assertThat(config4.getMaxEventsSize(), is(134217728L)); - - // fail (500 error) - try { - driver.setReplicationLoggerConfig(false, false, 0L, 32768L); - fail(); - } catch (final ArangoException e) { - assertThat(e.getCode(), is(500)); - assertThat(e.getErrorNumber(), is(1409)); - } - - } - - @Ignore("理由は以下のコメントを見てね") - @Test - public void test_set_applier_config_endpoint_null() { - - // endpointはmust指定のはずなのに、1.4.0時点ではエラーにならない。 - // 一度endpointを設定してしまうと、REPLICATION-APPLIER-CONFIG ファイルに保存されてしまい、 - // 以降、修正はできてもリセットはできない。 - // インストール直後のみ再現するケースである。 - - try { - driver.setReplicationApplierConfig(null, // endpoint is null - null, null, null, 99, 98, 97, 1024, true, true); - fail(""); - } catch (final ArangoException e) { - assertThat(e.getCode(), is(400)); - assertThat(e.getErrorNumber(), is(1410)); - } - } - - @Test - public void test_set_get_applier_config() throws ArangoException { - - // master - ReplicationApplierConfigEntity config = driver.setReplicationApplierConfig(configure.getEndpoint(), null, - "root", "", 99, 98, 97, 1024, true, true); - - assertThat(config.getEndpoint(), is(configure.getEndpoint())); - assertThat(config.getDatabase(), is("_system")); - assertThat(config.getMaxConnectRetries(), is(99)); - assertThat(config.getConnectTimeout(), is(98)); - assertThat(config.getRequestTimeout(), is(97)); - assertThat(config.getChunkSize(), is(1024)); - assertThat(config.getAutoStart(), is(true)); - assertThat(config.getAdaptivePolling(), is(true)); - assertThat(config.getUsername(), is("root")); - assertThat(config.getPassword(), is(nullValue())); - - config = driver.getReplicationApplierConfig(); - assertThat(config.getEndpoint(), is(configure.getEndpoint())); - assertThat(config.getDatabase(), is("_system")); - assertThat(config.getMaxConnectRetries(), is(99)); - assertThat(config.getConnectTimeout(), is(98)); - assertThat(config.getRequestTimeout(), is(97)); - assertThat(config.getChunkSize(), is(1024)); - assertThat(config.getAutoStart(), is(true)); - assertThat(config.getAdaptivePolling(), is(true)); - assertThat(config.getUsername(), is("root")); - assertThat(config.getPassword(), is(nullValue())); - - } - - @Test - public void test_start_stop_applier() throws ArangoException { - - final ReplicationApplierStateEntity state1 = driver.startReplicationApplier(null); - assertThat(state1.getStatusCode(), is(200)); - assertThat(state1.getServerVersion(), is(notNullValue())); - assertThat(state1.getServerId(), is(notNullValue())); - assertThat(state1.getEndpoint(), is(notNullValue())); - assertThat(state1.getDatabase(), is("_system")); - assertThat(state1.getState().getRunning(), is(true)); - assertThat(state1.getState().getLastAppliedContinuousTick(), is(nullValue())); - assertThat(state1.getState().getLastProcessedContinuousTick(), is(nullValue())); - assertThat(state1.getState().getLastAvailableContinuousTick(), is(nullValue())); - assertThat(state1.getState().getTime(), is(notNullValue())); - assertThat(state1.getState().getTotalRequests().longValue(), is(not(0L))); - assertThat(state1.getState().getTotalFailedConnects().longValue(), is(not(0L))); - assertThat(state1.getState().getTotalEvents(), is(notNullValue())); - // LastError, Progress -> see Sceinario Test - - final ReplicationApplierStateEntity state2 = driver.stopReplicationApplier(); - assertThat(state2.getStatusCode(), is(200)); - assertThat(state2.getServerVersion(), is(notNullValue())); - assertThat(state2.getServerId(), is(notNullValue())); - assertThat(state2.getEndpoint(), is(notNullValue())); - assertThat(state2.getDatabase(), is("_system")); - assertThat(state2.getState().getRunning(), is(false)); - assertThat(state2.getState().getLastAppliedContinuousTick(), is(nullValue())); - assertThat(state2.getState().getLastProcessedContinuousTick(), is(nullValue())); - assertThat(state2.getState().getLastAvailableContinuousTick(), is(nullValue())); - assertThat(state2.getState().getTime(), is(notNullValue())); - assertThat(state2.getState().getTotalRequests().longValue(), is(not(0L))); - assertThat(state2.getState().getTotalFailedConnects().longValue(), is(not(0L))); - assertThat(state2.getState().getTotalEvents(), is(notNullValue())); - - } - - @Test - public void test_logger_state() throws ArangoException { - - final ReplicationLoggerStateEntity entity = driver.getReplicationLoggerState(); - - assertThat(entity.getState().isRunning(), is(false)); - assertThat(entity.getState().getLastLogTick(), is(not(0L))); - assertThat(entity.getState().getTotalEvents(), is(not(0L))); - assertThat(entity.getState().getTime(), is(notNullValue())); - - assertThat(entity.getServerId(), is(notNullValue())); - assertThat(entity.getServerVersion(), is(notNullValue())); - assertThat(entity.getClients().size(), is(0)); // see another - // test-class(scenario1) - - } - - @Test - public void test_applier_state() throws ArangoException { - - final ReplicationApplierStateEntity state = driver.getReplicationApplierState(); - assertThat(state.getStatusCode(), is(200)); - assertThat(state.getServerVersion(), is(notNullValue())); - assertThat(state.getServerId(), is(notNullValue())); - assertThat(state.getEndpoint(), is(notNullValue())); - assertThat(state.getDatabase(), is("_system")); - assertThat(state.getState().getRunning(), is(false)); - assertThat(state.getState().getLastAppliedContinuousTick(), is(nullValue())); - assertThat(state.getState().getLastProcessedContinuousTick(), is(nullValue())); - assertThat(state.getState().getLastAvailableContinuousTick(), is(nullValue())); - assertThat(state.getState().getTime(), is(notNullValue())); - assertThat(state.getState().getTotalRequests().longValue(), is(not(0L))); - assertThat(state.getState().getTotalFailedConnects().longValue(), is(not(0L))); - assertThat(state.getState().getTotalEvents(), is(notNullValue())); - - } - -} diff --git a/src/test/java/com/arangodb/ArangoDriverReplicationTestScenario1.java b/src/test/java/com/arangodb/ArangoDriverReplicationTestScenario1.java deleted file mode 100644 index 405c01bb7..000000000 --- a/src/test/java/com/arangodb/ArangoDriverReplicationTestScenario1.java +++ /dev/null @@ -1,291 +0,0 @@ -/* - * Copyright (C) 2012,2013 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb; - -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.not; -import static org.hamcrest.CoreMatchers.notNullValue; -import static org.hamcrest.CoreMatchers.nullValue; -import static org.hamcrest.CoreMatchers.startsWith; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; - -import java.util.LinkedList; -import java.util.Map; -import java.util.concurrent.TimeUnit; - -import org.junit.After; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; - -import com.arangodb.entity.BooleanResultEntity; -import com.arangodb.entity.CollectionEntity; -import com.arangodb.entity.DocumentEntity; -import com.arangodb.entity.ImportResultEntity; -import com.arangodb.entity.ReplicationApplierStateEntity; -import com.arangodb.entity.ReplicationLoggerStateEntity; -import com.arangodb.entity.ReplicationSyncEntity; -import com.arangodb.util.MapBuilder; - -/** - * @author tamtam180 - kirscheless at gmail.com - * - */ -public class ArangoDriverReplicationTestScenario1 { - - ArangoConfigure masterConfigure; - ArangoConfigure slaveConfigure; - ArangoDriver masterDriver; - ArangoDriver slaveDriver; - - String database = "repl_scenario_test1"; - String collectionName1 = "col1"; - String collectionName2 = "col2"; - - @Before - public void before() throws ArangoException { - - masterConfigure = new ArangoConfigure("/arangodb.properties"); - masterConfigure.init(); - masterDriver = new ArangoDriver(masterConfigure); - - slaveConfigure = new ArangoConfigure("/arangodb-slave.properties"); - slaveConfigure.init(); - slaveDriver = new ArangoDriver(slaveConfigure); - - // turn off replication logger at master - masterDriver.stopReplicationLogger(); - masterDriver.stopReplicationApplier(); - - // turn off replication applier at slave - slaveDriver.stopReplicationLogger(); - slaveDriver.stopReplicationApplier(); - - } - - @After - public void after() throws ArangoException { - try { - masterDriver.deleteDatabase(database); - } catch (final ArangoException e) { - } - masterConfigure.shutdown(); - slaveConfigure.shutdown(); - } - - @SuppressWarnings("rawtypes") - @Test - @Ignore - public void test_scienario() throws ArangoException, InterruptedException { - - // replication: master[db=repl_scenario_test1] -> slave[db=_system] - - // create database in master - try { - masterDriver.deleteDatabase(database); - } catch (final ArangoException e) { - } - { - final BooleanResultEntity result = masterDriver.createDatabase(database); - assertThat(result.getResult(), is(true)); - } - // configure database - masterDriver.setDefaultDatabase(database); - slaveDriver.setDefaultDatabase(null); - - try { - slaveDriver.deleteCollection(collectionName1); - } catch (final ArangoException e) { - } - - // [Master] add document - masterDriver.createCollection(collectionName1); - final DocumentEntity> doc1 = masterDriver.createDocument(collectionName1, - new MapBuilder().put("my-key1", "100").get(), false); - final DocumentEntity> doc2 = masterDriver.createDocument(collectionName1, - new MapBuilder().put("my-key2", "255").get(), false); - masterDriver.createDocument(collectionName1, new MapBuilder().put("my-key3", 1234567).get(), false); - - // [Master] logger property - masterDriver.setReplicationLoggerConfig(true, null, 1048576L, 0L); - - // [Master] turn on replication logger - masterDriver.startReplicationLogger(); - - // [Slave] turn off replication applier - slaveDriver.stopReplicationApplier(); - - // [Master] get logger state - final ReplicationLoggerStateEntity state1 = masterDriver.getReplicationLoggerState(); - assertThat(state1.getClients().size(), is(0)); - - // [Slave] sync - final ReplicationSyncEntity syncResult = slaveDriver.syncReplication(masterConfigure.getEndpoint(), database, - "root", null, null); - - Thread.sleep(3000L); - - slaveDriver.setReplicationApplierConfig(masterConfigure.getEndpoint(), database, "root", null, null, null, null, - null, true, true); - - // [Slave] turn on replication applier - slaveDriver.startReplicationApplier(syncResult.getLastLogTick()); - - // [Master] create 10 document - for (int i = 0; i < 10; i++) { - masterDriver.createDocument(collectionName1, new MapBuilder().put("my-key" + i, 1234567).get(), false); - } - - // [Master] import 290 document - final LinkedList> values = new LinkedList>(); - for (int i = 10; i < 300; i++) { - values.add(new MapBuilder().put("my-key" + i, 1234567).get()); - } - final ImportResultEntity importResult = masterDriver.importDocuments(collectionName1, values); - assertThat(importResult.getCreated(), is(290)); - - // wait - TimeUnit.SECONDS.sleep(2); - - // [Slave] check a replication data - final CollectionEntity entity1 = slaveDriver.getCollectionCount(collectionName1); - assertThat(entity1.getCount(), is(303L)); - - // ------------------------------------------------------------ - // Delete - // ------------------------------------------------------------ - - // [Master] delete document - final DocumentEntity delEntity = masterDriver.deleteDocument(doc1.getDocumentHandle(), null, null); - assertThat(delEntity.isError(), is(false)); - assertThat(delEntity.getDocumentKey(), is(doc1.getDocumentKey())); - - // wait - TimeUnit.SECONDS.sleep(2); - - // [Slave] check a replication data - final CollectionEntity entity2 = slaveDriver.getCollectionCount(collectionName1); - assertThat(entity2.getCount(), is(302L)); - - try { - slaveDriver.getDocument(doc1.getDocumentHandle(), Map.class); - fail(); - } catch (final ArangoException e) { - assertThat(e.getCode(), is(404)); - } - - // ------------------------------------------------------------ - // Replace - // ------------------------------------------------------------ - // [Master] replace document - masterDriver.replaceDocument(doc2.getDocumentHandle(), new MapBuilder().put("updatedKey", "あいうえお").get(), null, - null); - - // wait - TimeUnit.SECONDS.sleep(2); - - // [Slave] check a replication data - final CollectionEntity entity3 = slaveDriver.getCollectionCount(collectionName1); - assertThat(entity3.getCount(), is(302L)); - - final DocumentEntity doc2a = slaveDriver.getDocument(doc2.getDocumentHandle(), Map.class); - assertThat(doc2a.getDocumentHandle(), is(doc2a.getDocumentHandle())); - assertThat(doc2a.getEntity().size(), is(4)); // _id, _rev, _key - assertThat((String) doc2a.getEntity().get("updatedKey"), is("あいうえお")); - - // ------------------------------------------------------------ - // Partial Update - // ------------------------------------------------------------ - // [Master] update document - masterDriver.updateDocument(doc2.getDocumentHandle(), new MapBuilder().put("updatedKey2", "ABCDE").get(), null, - null, null); - - // wait - TimeUnit.SECONDS.sleep(2); - - // [Slave] check a replication data - final CollectionEntity entity4 = slaveDriver.getCollectionCount(collectionName1); - assertThat(entity4.getCount(), is(302L)); - - final DocumentEntity doc2b = slaveDriver.getDocument(doc2.getDocumentHandle(), Map.class); - assertThat(doc2b.getDocumentHandle(), is(doc2a.getDocumentHandle())); - assertThat(doc2b.getEntity().size(), is(5)); // _id, _rev, _key - assertThat((String) doc2b.getEntity().get("updatedKey"), is("あいうえお")); - assertThat((String) doc2b.getEntity().get("updatedKey2"), is("ABCDE")); - - // ------------------------------------------------------------ - // Delete Collection - // ------------------------------------------------------------ - // [Master] delete collection - masterDriver.deleteCollection(collectionName1); - - // wait - TimeUnit.SECONDS.sleep(2); - - // [Slave] check a replication data - try { - masterDriver.getCollection(collectionName1); - fail(); - } catch (final ArangoException e) { - assertThat(e.getCode(), is(404)); - } - - // ------------------------------------------------------------ - // State - // ------------------------------------------------------------ - - // [Master] logger state - final ReplicationLoggerStateEntity state2 = masterDriver.getReplicationLoggerState(); - assertThat(state2.getState().isRunning(), is(true)); - assertThat(state2.getState().getLastLogTick(), is(not(0L))); - assertThat(state2.getState().getTotalEvents(), is(307L)); - assertThat(state2.getState().getTime(), is(notNullValue())); - - assertThat(state2.getServerVersion(), is(notNullValue())); - assertThat(state2.getServerId(), is(masterDriver.getReplicationServerId())); - - assertThat(state2.getClients().size(), is(1)); - assertThat(state2.getClients().get(0).getServerId(), is(slaveDriver.getReplicationServerId())); - assertThat(state2.getClients().get(0).getLastServedTick(), is(0L)); - assertThat(state2.getClients().get(0).getTime(), is(notNullValue())); - - // [Slave] applier state - final ReplicationApplierStateEntity state3 = slaveDriver.getReplicationApplierState(); - assertThat(state3.getStatusCode(), is(200)); - assertThat(state3.getServerVersion(), is(notNullValue())); - assertThat(state3.getServerId(), is(slaveDriver.getReplicationServerId())); - assertThat(state3.getEndpoint(), is(masterConfigure.getEndpoint())); - assertThat(state3.getDatabase(), is(database)); - assertThat(state3.getState().getRunning(), is(true)); - assertThat(state3.getState().getLastAppliedContinuousTick(), is(notNullValue())); - assertThat(state3.getState().getLastProcessedContinuousTick(), is(notNullValue())); - assertThat(state3.getState().getLastAvailableContinuousTick(), is(notNullValue())); - assertThat(state3.getState().getProgress().getTime(), is(notNullValue())); - assertThat(state3.getState().getProgress().getMessage(), startsWith("fetching master log from offset")); - assertThat(state3.getState().getProgress().getFailedConnects(), is(0L)); - assertThat(state3.getState().getTotalRequests().longValue(), is(not(0L))); - assertThat(state3.getState().getTotalFailedConnects().longValue(), is(0L)); - assertThat(state3.getState().getTotalEvents(), is(306L)); - assertThat(state3.getState().getLastError().getErrorNum(), is(0)); - assertThat(state3.getState().getLastError().getErrorMessage(), is(nullValue())); - assertThat(state3.getState().getLastError().getTime(), is(nullValue())); - assertThat(state3.getState().getTime(), is(notNullValue())); - - } - -} diff --git a/src/test/java/com/arangodb/ArangoDriverSimpleTest.java b/src/test/java/com/arangodb/ArangoDriverSimpleTest.java deleted file mode 100644 index f5946974d..000000000 --- a/src/test/java/com/arangodb/ArangoDriverSimpleTest.java +++ /dev/null @@ -1,439 +0,0 @@ -/* - * Copyright (C) 2012,2013 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb; - -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.notNullValue; -import static org.hamcrest.Matchers.nullValue; -import static org.hamcrest.Matchers.startsWith; -import static org.junit.Assert.assertThat; - -import java.io.IOException; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import org.junit.Before; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.arangodb.entity.DocumentEntity; -import com.arangodb.entity.IndexType; -import com.arangodb.entity.ScalarExampleEntity; -import com.arangodb.entity.SimpleByResultEntity; -import com.arangodb.util.MapBuilder; -import com.arangodb.util.TestUtils; - -/** - * @author tamtam180 - kirscheless at gmail.com - * @author a-brandt - */ -public class ArangoDriverSimpleTest extends BaseTest { - - // TODO: 404 test each example. - - private static Logger logger = LoggerFactory.getLogger(ArangoDriverSimpleTest.class); - - private static final String COLLECTION_NAME = "unit_test_simple_test"; - private static final String COLLECTION_NAME_400 = "unit_test_simple_test_400"; - - @Before - public void setup() throws ArangoException { - - // create test collection - try { - driver.deleteCollection(COLLECTION_NAME); - } catch (final ArangoException e) { - } - try { - driver.createCollection(COLLECTION_NAME); - } catch (final ArangoException e) { - } - - // add some test data - for (int i = 0; i < 100; i++) { - final TestComplexEntity01 value = new TestComplexEntity01("user_" + (i % 10), "desc" + (i % 10), i); - driver.createDocument(COLLECTION_NAME, value, null); - } - - // delete second test collection - try { - driver.deleteCollection(COLLECTION_NAME_400); - } catch (final ArangoException e) { - } - - } - - @Test - public void test_simple_all() throws ArangoException { - - final DocumentCursor documentCursor = driver.executeSimpleAllDocuments(COLLECTION_NAME, 0, - 0, TestComplexEntity01.class); - - final Iterator> iterator = documentCursor.iterator(); - - int count = 0; - while (iterator.hasNext()) { - final TestComplexEntity01 entity = iterator.next().getEntity(); - count++; - assertThat(entity, is(notNullValue())); - } - - assertThat(count, is(100)); - } - - @Test - public void test_example_by() throws ArangoException { - - final DocumentCursor documentCursor = driver.executeSimpleByExampleDocuments( - COLLECTION_NAME, new MapBuilder().put("user", "user_6").get(), 0, 0, TestComplexEntity01.class); - - final Iterator> iterator = documentCursor.iterator(); - - int count = 0; - while (iterator.hasNext()) { - final TestComplexEntity01 entity = iterator.next().getEntity(); - count++; - assertThat(entity.getUser(), is("user_6")); - } - assertThat(count, is(10)); - } - - @Test - public void test_first_example() throws ArangoException { - - final ScalarExampleEntity entity = driver.executeSimpleFirstExample(COLLECTION_NAME, - new MapBuilder().put("user", "user_5").put("desc", "desc5").get(), TestComplexEntity01.class); - - final DocumentEntity doc = entity.getDocument(); - - assertThat(entity.getStatusCode(), is(200)); - assertThat(doc.getDocumentRevision(), is(notNullValue())); - assertThat(doc.getDocumentHandle(), is(COLLECTION_NAME + "/" + doc.getDocumentKey())); - assertThat(doc.getDocumentKey(), is(notNullValue())); - assertThat(doc.getEntity(), is(notNullValue())); - assertThat(doc.getEntity().getUser(), is("user_5")); - assertThat(doc.getEntity().getDesc(), is("desc5")); - - } - - @Test - public void test_any() throws ArangoException { - - final ScalarExampleEntity entity = driver.executeSimpleAny(COLLECTION_NAME, - TestComplexEntity01.class); - - for (int i = 0; i < 30; i++) { - final DocumentEntity doc = entity.getDocument(); - - assertThat(entity.getStatusCode(), is(200)); - assertThat(doc.getDocumentRevision(), is(notNullValue())); - assertThat(doc.getDocumentHandle(), is(COLLECTION_NAME + "/" + doc.getDocumentKey())); - assertThat(doc.getDocumentKey(), is(notNullValue())); - assertThat(doc.getEntity(), is(notNullValue())); - assertThat(doc.getEntity().getUser(), is(notNullValue())); - assertThat(doc.getEntity().getDesc(), is(notNullValue())); - assertThat(doc.getEntity().getAge(), is(notNullValue())); - } - } - - @Test - public void test_range() throws ArangoException { - - // create skip-list - driver.createIndex(COLLECTION_NAME, IndexType.SKIPLIST, false, "age"); - - { - final DocumentCursor documentCursor = driver.executeSimpleRangeWithDocuments( - COLLECTION_NAME, "age", 5, 30, null, 0, 0, TestComplexEntity01.class); - final Iterator> iterator = documentCursor.iterator(); - - int count = 0; - while (iterator.hasNext()) { - final TestComplexEntity01 entity = iterator.next().getEntity(); - count++; - assertThat(entity, is(notNullValue())); - } - - assertThat(count, is(25)); - } - - { - final DocumentCursor documentCursor = driver.executeSimpleRangeWithDocuments( - COLLECTION_NAME, "age", 5, 30, true, 0, 0, TestComplexEntity01.class); - final Iterator> iterator = documentCursor.iterator(); - - int count = 0; - while (iterator.hasNext()) { - final TestComplexEntity01 entity = iterator.next().getEntity(); - count++; - assertThat(entity, is(notNullValue())); - } - - assertThat(count, is(26)); - } - - } - - @Test - public void test_remove_by_example() throws ArangoException { - - final SimpleByResultEntity entity = driver.executeSimpleRemoveByExample(COLLECTION_NAME, - new MapBuilder().put("user", "user_3").get(), null, null); - - assertThat(entity.getCode(), is(200)); - assertThat(entity.getCount(), is(10)); - assertThat(entity.getDeleted(), is(10)); - assertThat(entity.getReplaced(), is(0)); - assertThat(entity.getUpdated(), is(0)); - - } - - @Test - public void test_remove_by_example_with_limit() throws ArangoException { - - final SimpleByResultEntity entity = driver.executeSimpleRemoveByExample(COLLECTION_NAME, - new MapBuilder().put("user", "user_3").get(), null, 5); - - assertThat(entity.getCode(), is(200)); - assertThat(entity.getCount(), is(5)); - assertThat(entity.getDeleted(), is(5)); - assertThat(entity.getReplaced(), is(0)); - assertThat(entity.getUpdated(), is(0)); - - } - - @SuppressWarnings("rawtypes") - @Test - public void test_replace_by_example() throws ArangoException { - - final SimpleByResultEntity entity = driver.executeSimpleReplaceByExample(COLLECTION_NAME, - new MapBuilder().put("user", "user_3").get(), new MapBuilder().put("abc", "xxx").get(), null, null); - - assertThat(entity.getCode(), is(200)); - assertThat(entity.getCount(), is(10)); - assertThat(entity.getDeleted(), is(0)); - assertThat(entity.getReplaced(), is(10)); - assertThat(entity.getUpdated(), is(0)); - - // Get Replaced Document - final DocumentCursor documentCursor = driver.executeSimpleByExampleDocuments(COLLECTION_NAME, - new MapBuilder().put("abc", "xxx").get(), 0, 0, Map.class); - - final List> list = documentCursor.asList(); - - assertThat(list.size(), is(10)); - for (final DocumentEntity docuemntEntity : list) { - final Map map = docuemntEntity.getEntity(); - assertThat(map.size(), is(4)); // _id, _rev, _key and "abc" - assertThat((String) map.get("abc"), is("xxx")); - } - - } - - @SuppressWarnings({ "rawtypes", "unchecked" }) - @Test - public void test_replace_by_example_with_limit() throws ArangoException { - - final SimpleByResultEntity entity = driver.executeSimpleReplaceByExample(COLLECTION_NAME, - new MapBuilder().put("user", "user_3").get(), new MapBuilder().put("abc", "xxx").get(), null, 3); - - assertThat(entity.getCode(), is(200)); - assertThat(entity.getCount(), is(3)); - assertThat(entity.getDeleted(), is(0)); - assertThat(entity.getReplaced(), is(3)); - assertThat(entity.getUpdated(), is(0)); - - // Get Replaced Document - final DocumentCursor rs = driver.executeSimpleByExampleDocuments(COLLECTION_NAME, - new MapBuilder().put("abc", "xxx").get(), 0, 0, Map.class); - final List list = rs.asEntityList(); - - assertThat(list.size(), is(3)); - for (final Map map : list) { - assertThat(map.size(), is(4)); // _id, _rev, _key and "abc" - assertThat((String) map.get("abc"), is("xxx")); - } - - } - - @SuppressWarnings({ "rawtypes", "unchecked" }) - @Test - public void test_update_by_example() throws ArangoException { - - final SimpleByResultEntity entity = driver.executeSimpleUpdateByExample(COLLECTION_NAME, - new MapBuilder().put("user", "user_3").get(), new MapBuilder().put("abc", "xxx").put("age", 999).get(), - null, null, null); - - assertThat(entity.getCode(), is(200)); - assertThat(entity.getCount(), is(10)); - assertThat(entity.getDeleted(), is(0)); - assertThat(entity.getReplaced(), is(0)); - assertThat(entity.getUpdated(), is(10)); - - // Get Replaced Document - final DocumentCursor rs = driver.executeSimpleByExampleDocuments(COLLECTION_NAME, - new MapBuilder().put("abc", "xxx").get(), 0, 0, Map.class); - final List list = rs.asEntityList(); - - assertThat(list.size(), is(10)); - for (final Map map : list) { - assertThat(map.size(), is(7)); // _id, _rev, _key and "user", - // "desc", "age", "abc" - assertThat((String) map.get("user"), is("user_3")); - assertThat((String) map.get("desc"), is("desc3")); - assertThat(((Number) map.get("age")).intValue(), is(999)); - assertThat((String) map.get("abc"), is("xxx")); - } - - } - - @SuppressWarnings({ "rawtypes", "unchecked" }) - @Test - public void test_update_by_example_with_limit() throws ArangoException { - - final SimpleByResultEntity entity = driver.executeSimpleUpdateByExample(COLLECTION_NAME, - new MapBuilder().put("user", "user_3").get(), new MapBuilder().put("abc", "xxx").put("age", 999).get(), - null, null, 3); - - assertThat(entity.getCode(), is(200)); - assertThat(entity.getCount(), is(3)); - assertThat(entity.getDeleted(), is(0)); - assertThat(entity.getReplaced(), is(0)); - assertThat(entity.getUpdated(), is(3)); - - // Get Replaced Document - final DocumentCursor rs = driver.executeSimpleByExampleDocuments(COLLECTION_NAME, - new MapBuilder().put("age", 999).get(), 0, 0, Map.class); - final List list = rs.asEntityList(); - - assertThat(list.size(), is(3)); - for (final Map map : list) { - assertThat(map.size(), is(7)); // _id, _rev, _key and "user", - // "desc", "age", "abc" - assertThat((String) map.get("user"), is("user_3")); - assertThat((String) map.get("desc"), is("desc3")); - assertThat(((Number) map.get("age")).intValue(), is(999)); - assertThat((String) map.get("abc"), is("xxx")); - } - - } - - @SuppressWarnings({ "rawtypes", "unchecked" }) - @Test - public void test_update_by_example_with_keepnull() throws ArangoException { - - final SimpleByResultEntity entity = driver.executeSimpleUpdateByExample(COLLECTION_NAME, - new MapBuilder().put("user", "user_3").get(), - new MapBuilder(false).put("abc", "xxx").put("age", 999).put("user", null).get(), false, null, null); - - assertThat(entity.getCode(), is(200)); - assertThat(entity.getCount(), is(10)); - assertThat(entity.getDeleted(), is(0)); - assertThat(entity.getReplaced(), is(0)); - assertThat(entity.getUpdated(), is(10)); - - // Get Replaced Document - final DocumentCursor rs = driver.executeSimpleByExampleDocuments(COLLECTION_NAME, - new MapBuilder().put("abc", "xxx").get(), 0, 0, Map.class); - final List list = rs.asEntityList(); - - assertThat(list.size(), is(10)); - for (final Map map : list) { - assertThat(map.size(), is(6)); // _id, _rev, _key and "desc", "age", - // "abc" - assertThat(map.get("user"), is(nullValue())); - assertThat((String) map.get("desc"), is("desc3")); - assertThat(((Number) map.get("age")).intValue(), is(999)); - assertThat((String) map.get("abc"), is("xxx")); - } - - } - - // TODO fulltext Japanese Text - - @Test - public void test_fulltext() throws ArangoException { - - // MEMO: INDEX作成前のドキュメントはヒットしない・・。仕様? - - // create fulltext index - driver.createFulltextIndex(COLLECTION_NAME, 2, "desc"); - - driver.createDocument(COLLECTION_NAME, new TestComplexEntity01("xxx1", "this text contains a word", 10), null); - driver.createDocument(COLLECTION_NAME, new TestComplexEntity01("xxx2", "this text also contains a word", 10), - null); - - final DocumentCursor documentCursor = driver.executeSimpleFulltextWithDocuments( - COLLECTION_NAME, "desc", "word", 0, 0, null, TestComplexEntity01.class); - final List> list = documentCursor.asList(); - - assertThat(list.size(), is(2)); - assertThat(list.get(0).getEntity().getUser(), is("xxx1")); - assertThat(list.get(0).getEntity().getDesc(), is("this text contains a word")); - assertThat(list.get(0).getEntity().getAge(), is(10)); - - assertThat(list.get(1).getEntity().getUser(), is("xxx2")); - assertThat(list.get(1).getEntity().getDesc(), is("this text also contains a word")); - assertThat(list.get(1).getEntity().getAge(), is(10)); - - } - - @Test - public void test_fulltext_with_doc() throws ArangoException { - - // MEMO: INDEX作成前のドキュメントはヒットしない・・。仕様? - - // create fulltext index - driver.createFulltextIndex(COLLECTION_NAME, 2, "desc"); - - driver.createDocument(COLLECTION_NAME, new TestComplexEntity01("xxx1", "this text contains a word", 10), null); - driver.createDocument(COLLECTION_NAME, new TestComplexEntity01("xxx2", "this text also contains a word", 10), - null); - - final DocumentCursor documentCursor = driver.executeSimpleFulltextWithDocuments( - COLLECTION_NAME, "desc", "word", 0, 0, null, TestComplexEntity01.class); - final List> list = documentCursor.asList(); - - assertThat(list.size(), is(2)); - assertThat(list.get(0).getDocumentHandle(), startsWith(COLLECTION_NAME)); - assertThat(list.get(0).getDocumentKey(), is(notNullValue())); - assertThat(list.get(0).getDocumentRevision(), is(notNullValue())); - assertThat(list.get(0).getEntity().getUser(), is("xxx1")); - assertThat(list.get(0).getEntity().getDesc(), is("this text contains a word")); - assertThat(list.get(0).getEntity().getAge(), is(10)); - - assertThat(list.get(1).getDocumentHandle(), startsWith(COLLECTION_NAME)); - assertThat(list.get(1).getDocumentKey(), is(notNullValue())); - assertThat(list.get(1).getDocumentRevision(), is(notNullValue())); - assertThat(list.get(1).getEntity().getUser(), is("xxx2")); - assertThat(list.get(1).getEntity().getDesc(), is("this text also contains a word")); - assertThat(list.get(1).getEntity().getAge(), is(10)); - - } - - @Test - public void test_geo() throws ArangoException, IOException { - - // Load Station data - final List stations = TestUtils.readStations(); - logger.debug(stations.toString()); - - } - -} diff --git a/src/test/java/com/arangodb/ArangoDriverThreadSafeTest.java b/src/test/java/com/arangodb/ArangoDriverThreadSafeTest.java deleted file mode 100644 index 51a5ed6e0..000000000 --- a/src/test/java/com/arangodb/ArangoDriverThreadSafeTest.java +++ /dev/null @@ -1,112 +0,0 @@ -/* - * Copyright (C) 2012 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb; - -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; - -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; - -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.arangodb.entity.CollectionEntity; -import com.arangodb.entity.DocumentEntity; - -/** - * @author tamtam180 - kirscheless at gmail.com - * - */ -public class ArangoDriverThreadSafeTest { - - private static Logger logger = LoggerFactory.getLogger(ArangoDriverThreadSafeTest.class); - - @Test - public void story01() throws ArangoException, InterruptedException { - - // hostやport, connection-poolなどの設定 - final ArangoConfigure configure = new ArangoConfigure(); - configure.init(); - final ArangoDriver driver = new ArangoDriver(configure); - - // コレクションを作る - final String collectionName = "unit_test_story_01"; - try { - driver.deleteCollection(collectionName); - } catch (final ArangoException e) { - } - final CollectionEntity collection = driver.createCollection(collectionName); - logger.debug("collectionId={}", collection.getId()); - - // コレクションの中身を削除する - driver.truncateCollection(collectionName); - - // スレッドセーフです - try { - final ExecutorService svc = Executors.newFixedThreadPool(4); - for (int t = 0; t < 4; t++) { - final int threadNo = t; - svc.execute(new Runnable() { - @Override - public void run() { - try { - for (int i = 0; i < 100; i++) { - final TestComplexEntity01 value = new TestComplexEntity01("user" + threadNo + "_" + i, - "テスト☆ユーザー:" + threadNo + "_" + i, (int) (100d * Math.random())); - // ドキュメントを作る - final DocumentEntity ret1 = driver.createDocument(collectionName, - value, null); - - final String _id = ret1.getDocumentHandle(); // ドキュメントのID(_id) - final String _rev = ret1.getDocumentRevision(); // ドキュメントのリビジョン(_rev) - - // ドキュメントを取得する - final DocumentEntity ret2 = driver.getDocument(_id, - TestComplexEntity01.class); - // 取得したドキュメントの確認 - assertThat(ret2.getDocumentHandle(), is(_id)); - assertThat(ret2.getEntity().getUser(), is(value.getUser())); - assertThat(ret2.getEntity().getDesc(), is(value.getDesc())); - assertThat(ret2.getEntity().getAge(), is(value.getAge())); - - // ドキュメントを削除する - final DocumentEntity ret3 = driver.deleteDocument(_id); - assertThat(ret3.getDocumentHandle(), is(_id)); - assertThat(ret3.getDocumentRevision(), is(_rev)); - - } - - } catch (final ArangoException e) { - logger.error(e.getMessage(), e); - fail("だめぽ"); - } - } - }); - } - svc.shutdown(); - svc.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS); - } finally { - // 後始末 - configure.shutdown(); - } - } - -} diff --git a/src/test/java/com/arangodb/ArangoDriverTransactionTest.java b/src/test/java/com/arangodb/ArangoDriverTransactionTest.java deleted file mode 100644 index e4784981b..000000000 --- a/src/test/java/com/arangodb/ArangoDriverTransactionTest.java +++ /dev/null @@ -1,185 +0,0 @@ -/* - * Copyright (C) 2012,2013 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb; - -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; - -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import com.arangodb.entity.BaseEntity; -import com.arangodb.entity.TransactionEntity; -import com.arangodb.entity.TransactionResultEntity; - -/** - * @author tamtam180 - kirscheless at gmail.com - * - */ -public class ArangoDriverTransactionTest extends BaseTest { - - private static final String SOME_COLLECTION = "someCollection"; - private static final String SOME_OTHER_COLLECTION = "someOtherCollection"; - - public class ParamObject { - private String a = "a"; - - private String b = "b"; - - private int i = 3; - - public String getA() { - return a; - } - - public void setA(final String a) { - this.a = a; - } - - public String getB() { - return b; - } - - public void setB(final String b) { - this.b = b; - } - - public int getI() { - return i; - } - - public void setI(final int i) { - this.i = i; - } - } - - @Before - public void setup() throws ArangoException { - try { - driver.deleteCollection(SOME_COLLECTION); - } catch (final ArangoException e) { - - } - try { - driver.createCollection(SOME_COLLECTION); - } catch (final ArangoException e) { - - } - try { - driver.deleteCollection(SOME_OTHER_COLLECTION); - } catch (final ArangoException e) { - - } - try { - driver.createCollection(SOME_OTHER_COLLECTION); - } catch (final ArangoException e) { - - } - } - - @After - public void teardown() throws ArangoException { - try { - driver.deleteCollection(SOME_COLLECTION); - } catch (final ArangoException e) { - - } - try { - driver.deleteCollection(SOME_OTHER_COLLECTION); - } catch (final ArangoException e) { - - } - } - - @Test - public void test_Transaction() throws ArangoException { - - TransactionEntity transaction = driver.createTransaction("function (params) {return params;}"); - transaction.setParams(5); - TransactionResultEntity result = driver.executeTransaction(transaction); - - assertThat(result.getResultAsDouble(), is(5.0)); - assertThat(result.getStatusCode(), is(200)); - assertThat(result.getCode(), is(200)); - assertThat(result.isError(), is(false)); - - transaction = driver.createTransaction("function (params) {" + "var db = require('internal').db;" - + "return db.someCollection.all().toArray()[0];" + "}"); - transaction.addReadCollection(SOME_COLLECTION); - result = driver.executeTransaction(transaction); - - assertThat(result.getStatusCode(), is(200)); - assertThat(result.getCode(), is(200)); - assertThat(result.isError(), is(false)); - - transaction = driver.createTransaction("function (params) {return params;}"); - transaction.setParams(5); - result = driver.executeTransaction(transaction); - - assertThat(result.getResultAsInt(), is(5)); - assertThat(result.getStatusCode(), is(200)); - assertThat(result.getCode(), is(200)); - assertThat(result.isError(), is(false)); - - transaction.setParams(true); - result = driver.executeTransaction(transaction); - - assertThat(result.getResultAsBoolean(), is(true)); - assertThat(result.getStatusCode(), is(200)); - assertThat(result.getCode(), is(200)); - assertThat(result.isError(), is(false)); - - transaction.setParams("Hans"); - result = driver.executeTransaction(transaction); - - assertThat(result.getResultAsString(), is("Hans")); - assertThat(result.getStatusCode(), is(200)); - assertThat(result.getCode(), is(200)); - assertThat(result.isError(), is(false)); - - } - - @Test - public void allowImplicit() throws ArangoException { - final TransactionEntity transaction = driver - .createTransaction("function (params) {" + "var db = require('internal').db;" - + "return {'a':db.someCollection.all().toArray()[0], 'b':db.someOtherCollection.all().toArray()[0]};" - + "}"); - transaction.addReadCollection(SOME_COLLECTION); - { - final TransactionResultEntity result = driver.executeTransaction(transaction); - assertThat(result.getStatusCode(), is(200)); - assertThat(result.getCode(), is(200)); - assertThat(result.isError(), is(false)); - } - driver.deleteQueryCache(); - { - transaction.setAllowImplicit(false); - try { - driver.executeTransaction(transaction); - Assert.fail(); - } catch (final ArangoException e) { - final BaseEntity result = e.getEntity(); - assertThat(result.getStatusCode(), is(400)); - assertThat(result.getCode(), is(400)); - assertThat(result.isError(), is(true)); - } - } - } -} diff --git a/src/test/java/com/arangodb/ArangoDriverTraversalTest.java b/src/test/java/com/arangodb/ArangoDriverTraversalTest.java deleted file mode 100644 index 012876d14..000000000 --- a/src/test/java/com/arangodb/ArangoDriverTraversalTest.java +++ /dev/null @@ -1,194 +0,0 @@ -/** - * Copyright 2004-2015 triAGENS GmbH, Cologne, Germany - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Copyright holder is triAGENS GmbH, Cologne, Germany - * - * @author a-brandt - * @author Copyright 2015, triAGENS GmbH, Cologne, Germany - */ - -package com.arangodb; - -import static org.hamcrest.CoreMatchers.notNullValue; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import org.junit.Before; -import org.junit.Test; - -import com.arangodb.entity.BaseDocument; -import com.arangodb.entity.BaseEntity; -import com.arangodb.entity.EdgeDefinitionEntity; -import com.arangodb.entity.EdgeEntity; -import com.arangodb.entity.PathEntity; -import com.arangodb.entity.TraversalEntity; -import com.arangodb.entity.marker.VertexEntity; -import com.arangodb.util.TraversalQueryOptions; - -/** - * @author a-brandt - */ -public class ArangoDriverTraversalTest extends BaseGraphTest { - - private final String graphName = "TraversalTestGraph"; - private final String vertexCollectionName = "person"; - private final String edgeCollectionName = "knows"; - - @Override - @Before - public void _before() throws ArangoException { - super._before(); - - final List edgeDefinitions = new ArrayList(); - final EdgeDefinitionEntity edgeDefinition = new EdgeDefinitionEntity(); - edgeDefinition.setCollection(edgeCollectionName); - - final List from = new ArrayList(); - from.add(vertexCollectionName); - edgeDefinition.setFrom(from); - - final List to = new ArrayList(); - to.add(vertexCollectionName); - edgeDefinition.setTo(to); - - edgeDefinitions.add(edgeDefinition); - - driver.createGraph(graphName, edgeDefinitions, null, true); - - final VertexEntity alice = createPerson("Alice"); - final VertexEntity bob = createPerson("Bob"); - final VertexEntity charlie = createPerson("Charlie"); - final VertexEntity dave = createPerson("Dave"); - final VertexEntity eve = createPerson("Eve"); - - driver.graphCreateEdge(graphName, edgeCollectionName, "Alice_knows_Bob", alice.getDocumentHandle(), - bob.getDocumentHandle()); - driver.graphCreateEdge(graphName, edgeCollectionName, "Bob_knows_Charlie", bob.getDocumentHandle(), - charlie.getDocumentHandle()); - driver.graphCreateEdge(graphName, edgeCollectionName, "Bob_knows_Dave", bob.getDocumentHandle(), - dave.getDocumentHandle()); - driver.graphCreateEdge(graphName, edgeCollectionName, "Eve_knows_Alice", eve.getDocumentHandle(), - alice.getDocumentHandle()); - driver.graphCreateEdge(graphName, edgeCollectionName, "Eve_knows_Bob", eve.getDocumentHandle(), - bob.getDocumentHandle()); - } - - @SuppressWarnings("rawtypes") - @Test - public void test_getTraversal() throws ArangoException { - final TraversalQueryOptions traversalQueryOptions = new TraversalQueryOptions(); - - traversalQueryOptions.setGraphName(graphName); - traversalQueryOptions.setStartVertex("person/Alice"); - traversalQueryOptions.setDirection(Direction.OUTBOUND); - - final Class vertexClass = Person.class; - final Class edgeClass = Map.class; - - final TraversalEntity traversal = driver.getTraversal(traversalQueryOptions, vertexClass, - edgeClass); - - assertThat(traversal, is(notNullValue())); - - final List> vertices = traversal.getVertices(); - assertThat(vertices, is(notNullValue())); - assertThat(vertices.size(), is(4)); - assertThat(vertices.get(0).getEntity().getName(), is("Alice")); - assertThat(vertices.get(1).getEntity().getName(), is("Bob")); - assertThat(vertices.get(2).getEntity().getName(), is("Charlie")); - assertThat(vertices.get(3).getEntity().getName(), is("Dave")); - - final List> paths = traversal.getPaths(); - assertThat(paths, is(notNullValue())); - assertThat(paths.size(), is(4)); - - // start vertex! - assertThat(paths.get(0).getEdges().size(), is(0)); - assertThat(paths.get(0).getVertices().size(), is(1)); - assertThat(paths.get(0).getVertices().get(0).getEntity().getName(), is("Alice")); - - assertThat(paths.get(3).getEdges().size(), is(2)); - assertThat(paths.get(3).getVertices().size(), is(3)); - - } - - @Test - public void test_getTraversalWithBaseDocument() throws ArangoException { - final TraversalQueryOptions traversalQueryOptions = new TraversalQueryOptions(); - - traversalQueryOptions.setGraphName(graphName); - traversalQueryOptions.setStartVertex("person/Alice"); - traversalQueryOptions.setDirection(Direction.OUTBOUND); - - final TraversalEntity traversal = driver.getTraversal(traversalQueryOptions, - BaseDocument.class, BaseDocument.class); - - assertThat(traversal, is(notNullValue())); - - final List> vertices = traversal.getVertices(); - assertThat(vertices, is(notNullValue())); - assertThat(vertices.size(), is(4)); - assertThat(vertices.get(0).getEntity().getProperties().size(), is(1)); - assertThat((String) vertices.get(0).getEntity().getAttribute("name"), is("Alice")); - assertThat((String) vertices.get(1).getEntity().getAttribute("name"), is("Bob")); - assertThat((String) vertices.get(2).getEntity().getAttribute("name"), is("Charlie")); - assertThat((String) vertices.get(3).getEntity().getAttribute("name"), is("Dave")); - - final List> paths = traversal.getPaths(); - assertThat(paths, is(notNullValue())); - assertThat(paths.size(), is(4)); - - // start vertex! - assertThat(paths.get(0).getEdges().size(), is(0)); - assertThat(paths.get(0).getVertices().size(), is(1)); - assertThat((String) paths.get(0).getVertices().get(0).getEntity().getAttribute("name"), is("Alice")); - - assertThat(paths.get(3).getEdges().size(), is(2)); - assertThat(paths.get(3).getVertices().size(), is(3)); - - assertThat(paths.get(1).getEdges().size(), is(1)); - EdgeEntity edgeEntity = traversal.getPaths().get(1).getEdges().get(0); - assertThat(edgeEntity.getFromVertexHandle(), is("person/Alice")); - assertThat(edgeEntity.getToVertexHandle(), is("person/Bob")); - - } - - private VertexEntity createPerson(final String name) throws ArangoException { - return driver.graphCreateVertex(graphName, vertexCollectionName, name, new Person(name), true); - } - - public class Person extends BaseEntity { - - private static final long serialVersionUID = 1L; - - private String name; - - public Person(final String name) { - this.name = name; - } - - public String getName() { - return name; - } - - public void setName(final String name) { - this.name = name; - } - } - -} diff --git a/src/test/java/com/arangodb/ArangoDriverUsersTest.java b/src/test/java/com/arangodb/ArangoDriverUsersTest.java deleted file mode 100644 index 3590f225c..000000000 --- a/src/test/java/com/arangodb/ArangoDriverUsersTest.java +++ /dev/null @@ -1,353 +0,0 @@ -/* - * Copyright (C) 2012,2013 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb; - -import static org.hamcrest.CoreMatchers.notNullValue; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.greaterThan; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; - -import java.util.Collections; -import java.util.Comparator; -import java.util.List; -import java.util.Map; -import java.util.TreeMap; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import com.arangodb.entity.DefaultEntity; -import com.arangodb.entity.DocumentEntity; -import com.arangodb.entity.UserEntity; -import com.arangodb.util.MapBuilder; - -/** - * @author tamtam180 - kirscheless at gmail.com - * - */ -public class ArangoDriverUsersTest extends BaseTest { - - @Before - @After - public void setup() throws ArangoException { - // delete user - for (final String user : new String[] { "user1", "user2", "user3", "user4", "testuser", "テスト☆ユーザー", "user-A", - "userA", "userB", "ゆーざーA" }) { - // user-A, userA, userB, ゆーざーA is created another(auth) testcase. - try { - driver.deleteUser(user); - } catch (final ArangoException e) { - } - } - } - - private Map> toMap(final List> users) { - final TreeMap> map = new TreeMap>(); - for (final DocumentEntity user : users) { - map.put(user.getEntity().getUsername(), user); - } - return map; - } - - @Test - public void test_create_user() throws ArangoException { - final DefaultEntity ret = driver.createUser("testuser", "test-pass1", null, null); - - assertThat(ret.getStatusCode(), is(201)); - assertThat(ret.getCode(), is(201)); - assertThat(ret.isError(), is(false)); - } - - @Test - public void test_create_user_japanese() throws ArangoException { - - // create - final DefaultEntity ret = driver.createUser("テスト☆ユーザー", "パスワード", null, null); - // validate - assertThat(ret.getStatusCode(), is(201)); - assertThat(ret.getCode(), is(201)); - assertThat(ret.isError(), is(false)); - - // get - final UserEntity user = driver.getUser("テスト☆ユーザー"); - assertThat(user.getUsername(), is("テスト☆ユーザー")); - assertThat(user.getPassword(), is(nullValue())); - assertThat(user.isActive(), is(true)); - assertThat(user.getExtra().isEmpty(), is(true)); - - } - - @Test - public void test_create_user_inactive() throws ArangoException { - final DefaultEntity ret = driver.createUser("testuser", "test-pass1", false, null); - - assertThat(ret.getStatusCode(), is(201)); - assertThat(ret.getCode(), is(201)); - assertThat(ret.isError(), is(false)); - } - - @Test - public void test_create_user_extra() throws ArangoException { - - // create user - final DefaultEntity ret = driver.createUser("testuser", "test-pass1", false, - new MapBuilder().put("attr1", "寿司").put("日本語属性1", "日本語値").get()); - - // valdate - assertThat(ret.getStatusCode(), is(201)); - assertThat(ret.getCode(), is(201)); - assertThat(ret.isError(), is(false)); - - // get user - final UserEntity user = driver.getUser("testuser"); - assertThat(user.getUsername(), is("testuser")); - assertThat(user.getPassword(), is(nullValue())); - assertThat(user.isActive(), is(false)); - assertThat(user.getExtra().size(), is(2)); - assertThat((String) user.getExtra().get("attr1"), is("寿司")); - assertThat((String) user.getExtra().get("日本語属性1"), is("日本語値")); - - } - - @Test - public void test_create_user_duplicate() throws ArangoException { - - final DefaultEntity ret = driver.createUser("testuser", "test-pass1", null, null); - assertThat(ret.isError(), is(false)); - - try { - driver.createUser("testuser", "test-pass1", null, null); - fail("did not raise exception"); - } catch (final ArangoException e) { - assertThat(e.getErrorNumber(), is(1702)); - assertThat(e.getMessage(), containsString("duplicate user")); - } - - } - - @Test - public void test_create_user_empty() throws ArangoException { - - try { - driver.createUser("", "test-pass1", null, null); - fail("did not raise exception"); - } catch (final ArangoException e) { - assertThat(e.getErrorNumber(), is(1700)); - assertThat(e.getMessage(), containsString("invalid user name")); - } - - } - - @Test - public void test_delete_user_empty() throws ArangoException { - - try { - driver.deleteUser(""); - fail("did not raise exception"); - } catch (final ArangoException e) { - assertThat(e.getErrorNumber(), is(400)); - assertThat(e.getMessage(), containsString("bad parameter")); - } - - } - - public void test_delete_user_404() throws ArangoException { - - try { - driver.deleteUser("testuser"); - fail("did not raise exception"); - } catch (final ArangoException e) { - assertThat(e.getErrorNumber(), is(1703)); - assertThat(e.getMessage(), containsString("user not found")); - } - - } - - @Test - public void test_get_user_empty() throws ArangoException { - // returns a list of users - - // TODO check the list - driver.getUser(""); - - } - - @Test - public void test_get_user_404() throws ArangoException { - - try { - driver.getUser("testuser"); - fail("did not raise exception"); - } catch (final ArangoException e) { - assertThat(e.getErrorNumber(), is(1703)); - assertThat(e.getMessage(), containsString("user not found")); - } - - } - - @Test - public void test_replace_user() throws ArangoException { - - // create - driver.createUser("testuser", "pass1", true, null); - // get document - final DocumentEntity doc1 = toMap(driver.getUsersDocument()).get("testuser"); - - // replace - final DefaultEntity res = driver.replaceUser("testuser", "pass2", false, - new MapBuilder().put("aaa", "bbbb").get()); - assertThat(res.getCode(), is(200)); - assertThat(res.isError(), is(false)); - - // get replace user - final DocumentEntity doc2 = toMap(driver.getUsersDocument()).get("testuser"); - - assertThat(doc2.getEntity().getUsername(), is("testuser")); - // assertThat(doc2.getEntity().getPassword(), - // is(not(doc1.getEntity().getPassword()))); - assertThat(doc2.getEntity().isActive(), is(false)); - assertThat((String) doc2.getEntity().getExtra().get("aaa"), is("bbbb")); - - assertThat(doc2.getDocumentRevision(), greaterThan(doc1.getDocumentRevision())); - assertThat(doc2.getDocumentKey(), is(doc1.getDocumentKey())); - assertThat(doc2.getDocumentHandle(), is(doc1.getDocumentHandle())); - - } - - @Test - public void test_replace_user_empty() throws ArangoException { - - try { - driver.replaceUser("", "pass2", false, new MapBuilder().put("aaa", "bbbb").get()); - fail("did not raise exception"); - } catch (final ArangoException e) { - assertThat(e.getErrorNumber(), is(400)); - assertThat(e.getMessage(), containsString("bad parameter")); - } - - } - - @Test - public void test_replace_user_404() throws ArangoException { - - try { - driver.replaceUser("testuser", "pass2", false, new MapBuilder().put("aaa", "bbbb").get()); - fail("did not raise exception"); - } catch (final ArangoException e) { - assertThat(e.getErrorNumber(), is(1703)); - assertThat(e.getMessage(), containsString("user not found")); - } - - } - - @Test - public void test_update_user() throws ArangoException { - - // create - driver.createUser("testuser", "pass1", true, null); - // get document - final DocumentEntity doc1 = toMap(driver.getUsersDocument()).get("testuser"); - - // partial update - final DefaultEntity res = driver.updateUser("testuser", null, null, new MapBuilder().put("aaa", "bbbb").get()); - assertThat(res.getCode(), is(200)); - assertThat(res.isError(), is(false)); - - // get replace user - final DocumentEntity doc2 = toMap(driver.getUsersDocument()).get("testuser"); - - assertThat(doc2.getEntity().getUsername(), is("testuser")); - assertThat(doc2.getEntity().getPassword(), is(doc1.getEntity().getPassword())); - assertThat(doc2.getEntity().isActive(), is(true)); - assertThat((String) doc2.getEntity().getExtra().get("aaa"), is("bbbb")); - - assertThat(doc2.getDocumentRevision(), greaterThan(doc1.getDocumentRevision())); - assertThat(doc2.getDocumentKey(), is(doc1.getDocumentKey())); - assertThat(doc2.getDocumentHandle(), is(doc1.getDocumentHandle())); - - } - - @Test - public void test_update_user_empty() throws ArangoException { - - try { - driver.updateUser("", "pass2", false, new MapBuilder().put("aaa", "bbbb").get()); - fail("did not raise exception"); - } catch (final ArangoException e) { - assertThat(e.getErrorNumber(), is(400)); - assertThat(e.getMessage(), containsString("bad parameter")); - } - - } - - @Test - public void test_update_user_404() throws ArangoException { - - try { - driver.updateUser("testuser", "pass2", false, new MapBuilder().put("aaa", "bbbb").get()); - fail("did not raise exception"); - } catch (final ArangoException e) { - assertThat(e.getErrorNumber(), is(1703)); - assertThat(e.getMessage(), containsString("user not found")); - } - - } - - @Test - public void test_get_users() throws ArangoException { - - int expectedUserSize = driver.getUsers().size() + 3; - - driver.createUser("user1", "pass1", true, null); - driver.createUser("user2", "pass2", false, null); - driver.createUser("user3", "pass3", true, new MapBuilder().put("key", "value").get()); - - // get users - final List users = driver.getUsers(); - Collections.sort(users, new Comparator() { - @Override - public int compare(final UserEntity o1, final UserEntity o2) { - return o1.getUsername().compareTo(o2.getUsername()); - } - }); - - // validate - assertThat(users.size(), is(expectedUserSize)); // user1,2,3 and root - assertThat(users.get(0).getUsername(), is("root")); - - assertThat(users.get(1).getUsername(), is("user1")); - assertThat(users.get(1).isActive(), is(true)); - assertThat(users.get(1).getExtra(), is(notNullValue())); - assertThat(users.get(1).getExtra().size(), is(0)); - - assertThat(users.get(2).getUsername(), is("user2")); - assertThat(users.get(2).isActive(), is(false)); - assertThat(users.get(2).getExtra(), is(notNullValue())); - assertThat(users.get(2).getExtra().size(), is(0)); - - assertThat(users.get(3).getUsername(), is("user3")); - assertThat(users.get(3).isActive(), is(true)); - assertThat(users.get(3).getExtra().size(), is(1)); - assertThat((String) users.get(3).getExtra().get("key"), is("value")); - - } - -} diff --git a/src/test/java/com/arangodb/ArangoEdgeCollectionTest.java b/src/test/java/com/arangodb/ArangoEdgeCollectionTest.java new file mode 100644 index 000000000..79a9b4739 --- /dev/null +++ b/src/test/java/com/arangodb/ArangoEdgeCollectionTest.java @@ -0,0 +1,383 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb; + +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.junit.Assert.assertThat; +import static org.junit.Assert.fail; + +import java.util.ArrayList; +import java.util.Collection; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import com.arangodb.entity.BaseDocument; +import com.arangodb.entity.BaseEdgeDocument; +import com.arangodb.entity.CollectionType; +import com.arangodb.entity.EdgeDefinition; +import com.arangodb.entity.EdgeEntity; +import com.arangodb.entity.EdgeUpdateEntity; +import com.arangodb.entity.VertexEntity; +import com.arangodb.model.CollectionCreateOptions; +import com.arangodb.model.DocumentReadOptions; +import com.arangodb.model.EdgeDeleteOptions; +import com.arangodb.model.EdgeReplaceOptions; +import com.arangodb.model.EdgeUpdateOptions; + +/** + * @author Mark - mark at arangodb.com + * + */ +public class ArangoEdgeCollectionTest extends BaseTest { + + private static final String GRAPH_NAME = "db_collection_test"; + private static final String EDGE_COLLECTION_NAME = "db_edge_collection_test"; + private static final String VERTEX_COLLECTION_NAME = "db_vertex_collection_test"; + + @Before + public void setup() { + try { + db.createCollection(VERTEX_COLLECTION_NAME, null); + } catch (final ArangoDBException e) { + } + try { + db.createCollection(EDGE_COLLECTION_NAME, new CollectionCreateOptions().type(CollectionType.EDGES)); + } catch (final ArangoDBException e) { + } + final Collection edgeDefinitions = new ArrayList(); + edgeDefinitions.add(new EdgeDefinition().collection(EDGE_COLLECTION_NAME).from(VERTEX_COLLECTION_NAME) + .to(VERTEX_COLLECTION_NAME)); + db.createGraph(GRAPH_NAME, edgeDefinitions, null); + } + + @After + public void teardown() { + for (final String collection : new String[] { VERTEX_COLLECTION_NAME, EDGE_COLLECTION_NAME }) { + try { + db.collection(collection).drop(); + } catch (final ArangoDBException e) { + } + } + db.graph(GRAPH_NAME).drop(); + } + + private BaseEdgeDocument createEdgeValue() { + final VertexEntity v1 = db.graph(GRAPH_NAME).vertexCollection(VERTEX_COLLECTION_NAME) + .insertVertex(new BaseDocument(), null); + final VertexEntity v2 = db.graph(GRAPH_NAME).vertexCollection(VERTEX_COLLECTION_NAME) + .insertVertex(new BaseDocument(), null); + + final BaseEdgeDocument value = new BaseEdgeDocument(); + value.setFrom(v1.getId()); + value.setTo(v2.getId()); + return value; + } + + @Test + public void insertEdge() { + final BaseEdgeDocument value = createEdgeValue(); + final EdgeEntity edge = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).insertEdge(value, null); + assertThat(edge, is(notNullValue())); + final BaseEdgeDocument document = db.collection(EDGE_COLLECTION_NAME).getDocument(edge.getKey(), + BaseEdgeDocument.class, null); + assertThat(document, is(notNullValue())); + assertThat(document.getKey(), is(edge.getKey())); + } + + @Test + public void getEdge() { + final BaseEdgeDocument value = createEdgeValue(); + final EdgeEntity edge = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).insertEdge(value, null); + final BaseDocument document = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).getEdge(edge.getKey(), + BaseDocument.class, null); + assertThat(document, is(notNullValue())); + assertThat(document.getKey(), is(edge.getKey())); + } + + @Test + public void getEdgeIfMatch() { + final BaseEdgeDocument value = createEdgeValue(); + final EdgeEntity edge = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).insertEdge(value, null); + final DocumentReadOptions options = new DocumentReadOptions().ifMatch(edge.getRev()); + final BaseDocument document = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).getEdge(edge.getKey(), + BaseDocument.class, options); + assertThat(document, is(notNullValue())); + assertThat(document.getKey(), is(edge.getKey())); + } + + @Test + public void getEdgeIfMatchFail() { + final BaseEdgeDocument value = createEdgeValue(); + final EdgeEntity edge = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).insertEdge(value, null); + final DocumentReadOptions options = new DocumentReadOptions().ifMatch("no"); + try { + db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).getEdge(edge.getKey(), BaseEdgeDocument.class, + options); + fail(); + } catch (final ArangoDBException e) { + } + } + + @Test + public void getEdgeIfNoneMatch() { + final BaseEdgeDocument value = createEdgeValue(); + final EdgeEntity edge = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).insertEdge(value, null); + final DocumentReadOptions options = new DocumentReadOptions().ifNoneMatch("no"); + final BaseDocument document = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).getEdge(edge.getKey(), + BaseDocument.class, options); + assertThat(document, is(notNullValue())); + assertThat(document.getKey(), is(edge.getKey())); + } + + @Test + public void getEdgeIfNoneMatchFail() { + final BaseEdgeDocument value = createEdgeValue(); + final EdgeEntity edge = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).insertEdge(value, null); + final DocumentReadOptions options = new DocumentReadOptions().ifNoneMatch(edge.getRev()); + try { + db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).getEdge(edge.getKey(), BaseEdgeDocument.class, + options); + fail(); + } catch (final ArangoDBException e) { + } + } + + @Test + public void replaceEdge() { + final BaseEdgeDocument doc = createEdgeValue(); + doc.addAttribute("a", "test"); + final EdgeEntity createResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).insertEdge(doc, null); + doc.getProperties().clear(); + doc.addAttribute("b", "test"); + final EdgeUpdateEntity replaceResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME) + .replaceEdge(createResult.getKey(), doc, null); + assertThat(replaceResult, is(notNullValue())); + assertThat(replaceResult.getId(), is(createResult.getId())); + assertThat(replaceResult.getRev(), is(not(replaceResult.getOldRev()))); + assertThat(replaceResult.getOldRev(), is(createResult.getRev())); + + final BaseEdgeDocument readResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME) + .getEdge(createResult.getKey(), BaseEdgeDocument.class, null); + assertThat(readResult.getKey(), is(createResult.getKey())); + assertThat(readResult.getRevision(), is(replaceResult.getRev())); + assertThat(readResult.getProperties().keySet(), not(hasItem("a"))); + assertThat(readResult.getAttribute("b"), is(notNullValue())); + assertThat(String.valueOf(readResult.getAttribute("b")), is("test")); + } + + @Test + public void replaceEdgeIfMatch() { + final BaseEdgeDocument doc = createEdgeValue(); + doc.addAttribute("a", "test"); + final EdgeEntity createResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).insertEdge(doc, null); + doc.getProperties().clear(); + doc.addAttribute("b", "test"); + final EdgeReplaceOptions options = new EdgeReplaceOptions().ifMatch(createResult.getRev()); + final EdgeUpdateEntity replaceResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME) + .replaceEdge(createResult.getKey(), doc, options); + assertThat(replaceResult, is(notNullValue())); + assertThat(replaceResult.getId(), is(createResult.getId())); + assertThat(replaceResult.getRev(), is(not(replaceResult.getOldRev()))); + assertThat(replaceResult.getOldRev(), is(createResult.getRev())); + + final BaseEdgeDocument readResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME) + .getEdge(createResult.getKey(), BaseEdgeDocument.class, null); + assertThat(readResult.getKey(), is(createResult.getKey())); + assertThat(readResult.getRevision(), is(replaceResult.getRev())); + assertThat(readResult.getProperties().keySet(), not(hasItem("a"))); + assertThat(readResult.getAttribute("b"), is(notNullValue())); + assertThat(String.valueOf(readResult.getAttribute("b")), is("test")); + } + + @Test + public void replaceEdgeIfMatchFail() { + final BaseEdgeDocument doc = createEdgeValue(); + doc.addAttribute("a", "test"); + final EdgeEntity createResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).insertEdge(doc, null); + doc.getProperties().clear(); + doc.addAttribute("b", "test"); + try { + final EdgeReplaceOptions options = new EdgeReplaceOptions().ifMatch("no"); + db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).replaceEdge(createResult.getKey(), doc, options); + fail(); + } catch (final ArangoDBException e) { + } + } + + @Test + public void updateEdge() { + final BaseEdgeDocument doc = createEdgeValue(); + doc.addAttribute("a", "test"); + doc.addAttribute("c", "test"); + final EdgeEntity createResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).insertEdge(doc, null); + doc.updateAttribute("a", "test1"); + doc.addAttribute("b", "test"); + doc.updateAttribute("c", null); + final EdgeUpdateEntity updateResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME) + .updateEdge(createResult.getKey(), doc, null); + assertThat(updateResult, is(notNullValue())); + assertThat(updateResult.getId(), is(createResult.getId())); + assertThat(updateResult.getRev(), is(not(updateResult.getOldRev()))); + assertThat(updateResult.getOldRev(), is(createResult.getRev())); + + final BaseEdgeDocument readResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME) + .getEdge(createResult.getKey(), BaseEdgeDocument.class, null); + assertThat(readResult.getKey(), is(createResult.getKey())); + assertThat(readResult.getAttribute("a"), is(notNullValue())); + assertThat(String.valueOf(readResult.getAttribute("a")), is("test1")); + assertThat(readResult.getAttribute("b"), is(notNullValue())); + assertThat(String.valueOf(readResult.getAttribute("b")), is("test")); + assertThat(readResult.getRevision(), is(updateResult.getRev())); + assertThat(readResult.getProperties().keySet(), hasItem("c")); + } + + @Test + public void updateEdgeIfMatch() { + final BaseEdgeDocument doc = createEdgeValue(); + doc.addAttribute("a", "test"); + doc.addAttribute("c", "test"); + final EdgeEntity createResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).insertEdge(doc, null); + doc.updateAttribute("a", "test1"); + doc.addAttribute("b", "test"); + doc.updateAttribute("c", null); + final EdgeUpdateOptions options = new EdgeUpdateOptions().ifMatch(createResult.getRev()); + final EdgeUpdateEntity updateResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME) + .updateEdge(createResult.getKey(), doc, options); + assertThat(updateResult, is(notNullValue())); + assertThat(updateResult.getId(), is(createResult.getId())); + assertThat(updateResult.getRev(), is(not(updateResult.getOldRev()))); + assertThat(updateResult.getOldRev(), is(createResult.getRev())); + + final BaseEdgeDocument readResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME) + .getEdge(createResult.getKey(), BaseEdgeDocument.class, null); + assertThat(readResult.getKey(), is(createResult.getKey())); + assertThat(readResult.getAttribute("a"), is(notNullValue())); + assertThat(String.valueOf(readResult.getAttribute("a")), is("test1")); + assertThat(readResult.getAttribute("b"), is(notNullValue())); + assertThat(String.valueOf(readResult.getAttribute("b")), is("test")); + assertThat(readResult.getRevision(), is(updateResult.getRev())); + assertThat(readResult.getProperties().keySet(), hasItem("c")); + } + + @Test + public void updateEdgeIfMatchFail() { + final BaseEdgeDocument doc = createEdgeValue(); + doc.addAttribute("a", "test"); + doc.addAttribute("c", "test"); + final EdgeEntity createResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).insertEdge(doc, null); + doc.updateAttribute("a", "test1"); + doc.addAttribute("b", "test"); + doc.updateAttribute("c", null); + try { + final EdgeUpdateOptions options = new EdgeUpdateOptions().ifMatch("no"); + db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).updateEdge(createResult.getKey(), doc, options); + fail(); + } catch (final ArangoDBException e) { + } + } + + @Test + public void updateEdgeKeepNullTrue() { + final BaseEdgeDocument doc = createEdgeValue(); + doc.addAttribute("a", "test"); + final EdgeEntity createResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).insertEdge(doc, null); + doc.updateAttribute("a", null); + final EdgeUpdateOptions options = new EdgeUpdateOptions().keepNull(true); + final EdgeUpdateEntity updateResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME) + .updateEdge(createResult.getKey(), doc, options); + assertThat(updateResult, is(notNullValue())); + assertThat(updateResult.getId(), is(createResult.getId())); + assertThat(updateResult.getRev(), is(not(updateResult.getOldRev()))); + assertThat(updateResult.getOldRev(), is(createResult.getRev())); + + final BaseEdgeDocument readResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME) + .getEdge(createResult.getKey(), BaseEdgeDocument.class, null); + assertThat(readResult.getKey(), is(createResult.getKey())); + assertThat(readResult.getProperties().keySet().size(), is(1)); + assertThat(readResult.getProperties().keySet(), hasItem("a")); + } + + @Test + public void updateEdgeKeepNullFalse() { + final BaseEdgeDocument doc = createEdgeValue(); + doc.addAttribute("a", "test"); + final EdgeEntity createResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).insertEdge(doc, null); + doc.updateAttribute("a", null); + final EdgeUpdateOptions options = new EdgeUpdateOptions().keepNull(false); + final EdgeUpdateEntity updateResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME) + .updateEdge(createResult.getKey(), doc, options); + assertThat(updateResult, is(notNullValue())); + assertThat(updateResult.getId(), is(createResult.getId())); + assertThat(updateResult.getRev(), is(not(updateResult.getOldRev()))); + assertThat(updateResult.getOldRev(), is(createResult.getRev())); + + final BaseEdgeDocument readResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME) + .getEdge(createResult.getKey(), BaseEdgeDocument.class, null); + assertThat(readResult.getKey(), is(createResult.getKey())); + assertThat(readResult.getId(), is(createResult.getId())); + assertThat(readResult.getRevision(), is(notNullValue())); + assertThat(readResult.getProperties().keySet(), not(hasItem("a"))); + } + + @Test + public void deleteEdge() { + final BaseEdgeDocument doc = createEdgeValue(); + final EdgeEntity createResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).insertEdge(doc, null); + db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).deleteEdge(createResult.getKey(), null); + try { + db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).getEdge(createResult.getKey(), + BaseEdgeDocument.class, null); + fail(); + } catch (final ArangoDBException e) { + } + } + + @Test + public void deleteEdgeIfMatch() { + final BaseEdgeDocument doc = createEdgeValue(); + final EdgeEntity createResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).insertEdge(doc, null); + final EdgeDeleteOptions options = new EdgeDeleteOptions().ifMatch(createResult.getRev()); + db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).deleteEdge(createResult.getKey(), options); + try { + db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).getEdge(createResult.getKey(), + BaseEdgeDocument.class, null); + fail(); + } catch (final ArangoDBException e) { + } + } + + @Test + public void deleteEdgeIfMatchFail() { + final BaseEdgeDocument doc = createEdgeValue(); + final EdgeEntity createResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).insertEdge(doc, null); + final EdgeDeleteOptions options = new EdgeDeleteOptions().ifMatch("no"); + try { + db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).deleteEdge(createResult.getKey(), options); + fail(); + } catch (final ArangoDBException e) { + } + } +} diff --git a/src/test/java/com/arangodb/ArangoExecuteableTest.java b/src/test/java/com/arangodb/ArangoExecuteableTest.java new file mode 100644 index 000000000..62e6aa3c3 --- /dev/null +++ b/src/test/java/com/arangodb/ArangoExecuteableTest.java @@ -0,0 +1,84 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb; + +import org.junit.Test; + +import com.arangodb.internal.ArangoExecutor; + +/** + * @author Mark - mark at arangodb.com + * + */ +public class ArangoExecuteableTest { + + @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 validateDocumentKeyEmpty() { + checkDocumentKey(""); + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + private void checkDocumentKey(final String key) throws ArangoDBException { + final ArangoExecutor executeBase = new ArangoExecutor(null, null, null, null, null, null) { + }; + executeBase.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(expected = ArangoDBException.class) + public void validateDocumentIdInvalidWithoutSlash() { + checkDocumentId("test"); + } + + @Test(expected = ArangoDBException.class) + public void validateDocumentIdEmpty() { + checkDocumentId(""); + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + private void checkDocumentId(final String id) throws ArangoDBException { + final ArangoExecutor executeBase = new ArangoExecutor(null, null, null, null, null, null) { + }; + executeBase.validateDocumentId(id); + } +} diff --git a/src/test/java/com/arangodb/ArangoGraphTest.java b/src/test/java/com/arangodb/ArangoGraphTest.java new file mode 100644 index 000000000..04fd8c74f --- /dev/null +++ b/src/test/java/com/arangodb/ArangoGraphTest.java @@ -0,0 +1,192 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb; + +import static org.hamcrest.Matchers.empty; +import static org.hamcrest.Matchers.hasItem; +import static org.hamcrest.Matchers.hasItems; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.junit.Assert.assertThat; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Iterator; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import com.arangodb.entity.CollectionType; +import com.arangodb.entity.EdgeDefinition; +import com.arangodb.entity.GraphEntity; +import com.arangodb.model.CollectionCreateOptions; + +/** + * @author Mark - mark at arangodb.com + * + */ +public class ArangoGraphTest extends BaseTest { + + private static final String GRAPH_NAME = "db_collection_test"; + private static final String EDGE_COL_1 = "db_edge1_collection_test"; + private static final String EDGE_COL_2 = "db_edge2_collection_test"; + private static final String EDGE_COL_3 = "db_edge3_collection_test"; + private static final String VERTEX_COL_1 = "db_vertex1_collection_test"; + private static final String VERTEX_COL_2 = "db_vertex2_collection_test"; + private static final String VERTEX_COL_3 = "db_vertex3_collection_test"; + private static final String VERTEX_COL_4 = "db_vertex4_collection_test"; + + @Before + public void setup() { + for (final String collection : new String[] { VERTEX_COL_1, VERTEX_COL_2, VERTEX_COL_2, VERTEX_COL_3, + VERTEX_COL_4 }) { + try { + db.createCollection(collection, null); + } catch (final ArangoDBException e) { + } + } + for (final String collection : new String[] { EDGE_COL_1, EDGE_COL_2 }) { + try { + final CollectionCreateOptions options = new CollectionCreateOptions().type(CollectionType.EDGES); + db.createCollection(collection, options); + } catch (final ArangoDBException e) { + } + } + final Collection edgeDefinitions = new ArrayList(); + edgeDefinitions.add(new EdgeDefinition().collection(EDGE_COL_1).from(VERTEX_COL_1).to(VERTEX_COL_2)); + edgeDefinitions + .add(new EdgeDefinition().collection(EDGE_COL_2).from(VERTEX_COL_2).to(VERTEX_COL_1, VERTEX_COL_3)); + db.createGraph(GRAPH_NAME, edgeDefinitions, null); + } + + @After + public void teardown() { + for (final String collection : new String[] { EDGE_COL_1, EDGE_COL_2, VERTEX_COL_1, VERTEX_COL_2, VERTEX_COL_3, + VERTEX_COL_4 }) { + try { + db.collection(collection).drop(); + } catch (final ArangoDBException e) { + } + } + db.graph(GRAPH_NAME).drop(); + } + + @Test + public void getGraphs() { + final Collection graphs = db.getGraphs(); + assertThat(graphs, is(notNullValue())); + assertThat(graphs.size(), is(1)); + } + + @Test + public void getInfo() { + final GraphEntity info = db.graph(GRAPH_NAME).getInfo(); + assertThat(info, is(notNullValue())); + assertThat(info.getName(), is(GRAPH_NAME)); + assertThat(info.getEdgeDefinitions().size(), is(2)); + final Iterator iterator = info.getEdgeDefinitions().iterator(); + final EdgeDefinition e1 = iterator.next(); + assertThat(e1.getCollection(), is(EDGE_COL_1)); + assertThat(e1.getFrom(), hasItem(VERTEX_COL_1)); + assertThat(e1.getTo(), hasItem(VERTEX_COL_2)); + final EdgeDefinition e2 = iterator.next(); + assertThat(e2.getCollection(), is(EDGE_COL_2)); + assertThat(e2.getFrom(), hasItem(VERTEX_COL_2)); + assertThat(e2.getTo(), hasItems(VERTEX_COL_1, VERTEX_COL_3)); + assertThat(info.getOrphanCollections(), is(empty())); + } + + @Test + public void getVertexCollections() { + final Collection vertexCollections = db.graph(GRAPH_NAME).getVertexCollections(); + assertThat(vertexCollections, is(notNullValue())); + assertThat(vertexCollections.size(), is(3)); + assertThat(vertexCollections, hasItems(VERTEX_COL_1, VERTEX_COL_2, VERTEX_COL_3)); + } + + @Test + public void addVertexCollection() { + final GraphEntity graph = db.graph(GRAPH_NAME).addVertexCollection(VERTEX_COL_4); + assertThat(graph, is(notNullValue())); + final Collection vertexCollections = db.graph(GRAPH_NAME).getVertexCollections(); + assertThat(vertexCollections, hasItems(VERTEX_COL_1, VERTEX_COL_2, VERTEX_COL_3, VERTEX_COL_4)); + } + + @Test + public void getEdgeCollections() { + final Collection edgeCollections = db.graph(GRAPH_NAME).getEdgeDefinitions(); + assertThat(edgeCollections, is(notNullValue())); + assertThat(edgeCollections.size(), is(2)); + assertThat(edgeCollections, hasItems(EDGE_COL_1, EDGE_COL_2)); + } + + @Test + public void addEdgeDefinition() { + final GraphEntity graph = db.graph(GRAPH_NAME) + .addEdgeDefinition(new EdgeDefinition().collection(EDGE_COL_3).from(VERTEX_COL_1).to(VERTEX_COL_2)); + assertThat(graph, is(notNullValue())); + final Collection edgeDefinitions = graph.getEdgeDefinitions(); + assertThat(edgeDefinitions.size(), is(3)); + int count = 0; + for (final EdgeDefinition e : edgeDefinitions) { + if (e.getCollection().equals(EDGE_COL_3)) { + count++; + } + } + assertThat(count, is(1)); + for (final EdgeDefinition e : edgeDefinitions) { + if (e.getCollection().equals(EDGE_COL_3)) { + assertThat(e.getFrom(), hasItem(VERTEX_COL_1)); + assertThat(e.getTo(), hasItem(VERTEX_COL_2)); + } + } + } + + @Test + public void replaceEdgeDefinition() { + final GraphEntity graph = db.graph(GRAPH_NAME) + .replaceEdgeDefinition(new EdgeDefinition().collection(EDGE_COL_1).from(VERTEX_COL_3).to(VERTEX_COL_4)); + final Collection edgeDefinitions = graph.getEdgeDefinitions(); + assertThat(edgeDefinitions.size(), is(2)); + int count = 0; + for (final EdgeDefinition e : edgeDefinitions) { + if (e.getCollection().equals(EDGE_COL_1)) { + count++; + } + } + assertThat(count, is(1)); + for (final EdgeDefinition e : edgeDefinitions) { + if (e.getCollection().equals(EDGE_COL_1)) { + assertThat(e.getFrom(), hasItem(VERTEX_COL_3)); + assertThat(e.getTo(), hasItem(VERTEX_COL_4)); + } + } + } + + @Test + public void removeEdgeDefinition() { + final GraphEntity graph = db.graph(GRAPH_NAME).removeEdgeDefinition(EDGE_COL_1); + final Collection edgeDefinitions = graph.getEdgeDefinitions(); + assertThat(edgeDefinitions.size(), is(1)); + assertThat(edgeDefinitions.iterator().next().getCollection(), is(EDGE_COL_2)); + } +} diff --git a/src/test/java/com/arangodb/ArangoSslTest.java b/src/test/java/com/arangodb/ArangoSslTest.java new file mode 100644 index 000000000..1e2238276 --- /dev/null +++ b/src/test/java/com/arangodb/ArangoSslTest.java @@ -0,0 +1,90 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb; + +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 javax.net.ssl.KeyManagerFactory; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLHandshakeException; +import javax.net.ssl.TrustManagerFactory; + +import org.junit.Ignore; +import org.junit.Test; + +import com.arangodb.entity.ArangoDBVersion; + +/** + * @author Mark - mark at arangodb.com + * + */ +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"; + + @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 TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); + tmf.init(ks); + + final SSLContext sc = SSLContext.getInstance("TLS"); + sc.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); + + final ArangoDB arangoDB = new ArangoDB.Builder().port(8530).useSsl(true).sslContext(sc).build(); + final ArangoDBVersion version = arangoDB.getVersion(); + assertThat(version, is(notNullValue())); + } + + @Test + @Ignore + public void connectWithoutValidSslContext() throws Exception { + try { + final ArangoDB arangoDB = new ArangoDB.Builder().port(8530).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/ArangoTestSuite.java b/src/test/java/com/arangodb/ArangoTestSuite.java deleted file mode 100644 index 9afbaac74..000000000 --- a/src/test/java/com/arangodb/ArangoTestSuite.java +++ /dev/null @@ -1,143 +0,0 @@ -/* - * Copyright (C) 2012 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb; - -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.runner.RunWith; -import org.junit.runners.Suite; -import org.junit.runners.Suite.SuiteClasses; - -import com.arangodb.example.ExamplesTestSuite; -import com.arangodb.util.StringJoinTest; - -/** - * Starts all unit tests - * - * @author tamtam180 - kirscheless at gmail.com - * @author gschwab - * - */ -@RunWith(Suite.class) -@SuiteClasses({ - - // Utils Test - StringJoinTest.class, - - // Drivers Test - ArangoConfigureTest.class, - - ArangoDriverAuthTest.class, - - NegativeTest.class, - - PrimitiveDocumentTest.class, - - ArangoBaseParameterTest.class, - - ArangoDriverDatabaseTest.class, - - ArangoDriverDatabaseAndUserTest.class, - - ArangoDriverBatchTest.class, - - ArangoDriverAsyncTest.class, - - ArangoDriverDocumentTest.class, - - ArangoDriverAqlfunctionsTest.class, - - ArangoDriverDocumentKeyTest.class, - - ArangoDriverCollectionTest.class, - - ArangoDriverDocumentCursorEntityTest.class, - - ArangoDriverDocumentCursorTest.class, - - ArangoDriverCursorTest.class, - - ArangoDriverCursorResultSetTest.class, - - ArangoDriverIndexTest.class, - - ArangoDriverAdminTest.class, - - ArangoDriverSimpleTest.class, - - ArangoDriverImportTest.class, - // ArangoDriverSimpleGeoTest.class, - // ArangoDriverKeyValueTest.class, - - ArangoDriverGraphTest.class, - - ArangoDriverGraphVertexTest.class, - - ArangoDriverGraphVertexReplaceTest.class, - - ArangoDriverGraphVertexUpdateTest.class, - - ArangoDriverGraphEdgeCreateTest.class, - - ArangoDriverGraphEdgeGetTest.class, - - ArangoDriverGraphEdgeDeleteTest.class, - - ArangoDriverGraphEdgesGetCursorTest.class, - - ArangoDriverGraphEdgeReplaceTest.class, - - ArangoDriverGraphEdgeUpdateTest.class, - - ArangoDriverGraphShortestPathTest.class, - - ArangoDriverBatchGraphTest.class, - - ArangoDriverTransactionTest.class, - - ArangoDriverThreadSafeTest.class, - - ArangoDriverReplicationTest.class, - - ArangoDriverReplicationTestScenario1.class, - - ArangoDriverTraversalTest.class, - - ArangoDriverQueryTest.class, - - // since ArangoDB 2.7 - ArangoDriverQueryCacheTest.class, - - // examples - ExamplesTestSuite.class - -}) - -public class ArangoTestSuite { - - @BeforeClass - public static void setup() { - BaseTest.__setup(); - BaseTest.MANAGE_SETUP = false; - } - - @AfterClass - public static void shutdown() { - BaseTest.MANAGE_SETUP = true; - BaseTest.__shutdown(); - } -} diff --git a/src/test/java/com/arangodb/ArangoVertexCollectionTest.java b/src/test/java/com/arangodb/ArangoVertexCollectionTest.java new file mode 100644 index 000000000..e219b1ad3 --- /dev/null +++ b/src/test/java/com/arangodb/ArangoVertexCollectionTest.java @@ -0,0 +1,375 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb; + +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.junit.Assert.assertThat; +import static org.junit.Assert.fail; + +import java.util.Collection; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import com.arangodb.entity.BaseDocument; +import com.arangodb.entity.VertexEntity; +import com.arangodb.entity.VertexUpdateEntity; +import com.arangodb.model.DocumentReadOptions; +import com.arangodb.model.GraphCreateOptions; +import com.arangodb.model.VertexDeleteOptions; +import com.arangodb.model.VertexReplaceOptions; +import com.arangodb.model.VertexUpdateOptions; + +/** + * @author Mark - mark at arangodb.com + * + */ +public class ArangoVertexCollectionTest extends BaseTest { + + private static final String GRAPH_NAME = "db_collection_test"; + private static final String COLLECTION_NAME = "db_vertex_collection_test"; + + @Before + public void setup() { + try { + db.createCollection(COLLECTION_NAME, null); + } catch (final ArangoDBException e) { + } + final GraphCreateOptions options = new GraphCreateOptions().orphanCollections(COLLECTION_NAME); + db.createGraph(GRAPH_NAME, null, options); + } + + @After + public void teardown() { + try { + db.collection(COLLECTION_NAME).drop(); + } catch (final ArangoDBException e) { + } + db.graph(GRAPH_NAME).drop(); + } + + @Test + public void dropVertexCollection() { + db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME).drop(); + final Collection vertexCollections = db.graph(GRAPH_NAME).getVertexCollections(); + assertThat(vertexCollections, not(hasItem(COLLECTION_NAME))); + } + + @Test + public void insertVertex() { + final VertexEntity vertex = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) + .insertVertex(new BaseDocument(), null); + assertThat(vertex, is(notNullValue())); + final BaseDocument document = db.collection(COLLECTION_NAME).getDocument(vertex.getKey(), BaseDocument.class, + null); + assertThat(document, is(notNullValue())); + assertThat(document.getKey(), is(vertex.getKey())); + } + + @Test + public void getVertex() { + final VertexEntity vertex = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) + .insertVertex(new BaseDocument(), null); + final BaseDocument document = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME).getVertex(vertex.getKey(), + BaseDocument.class, null); + assertThat(document, is(notNullValue())); + assertThat(document.getKey(), is(vertex.getKey())); + } + + @Test + public void getVertexIfMatch() { + final VertexEntity vertex = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) + .insertVertex(new BaseDocument(), null); + final DocumentReadOptions options = new DocumentReadOptions().ifMatch(vertex.getRev()); + final BaseDocument document = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME).getVertex(vertex.getKey(), + BaseDocument.class, options); + assertThat(document, is(notNullValue())); + assertThat(document.getKey(), is(vertex.getKey())); + } + + @Test + public void getVertexIfMatchFail() { + final VertexEntity vertex = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) + .insertVertex(new BaseDocument(), null); + final DocumentReadOptions options = new DocumentReadOptions().ifMatch("no"); + try { + db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME).getVertex(vertex.getKey(), BaseDocument.class, + options); + fail(); + } catch (final ArangoDBException e) { + } + } + + @Test + public void getVertexIfNoneMatch() { + final VertexEntity vertex = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) + .insertVertex(new BaseDocument(), null); + final DocumentReadOptions options = new DocumentReadOptions().ifNoneMatch("no"); + final BaseDocument document = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME).getVertex(vertex.getKey(), + BaseDocument.class, options); + assertThat(document, is(notNullValue())); + assertThat(document.getKey(), is(vertex.getKey())); + } + + @Test + public void getVertexIfNoneMatchFail() { + final VertexEntity vertex = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) + .insertVertex(new BaseDocument(), null); + final DocumentReadOptions options = new DocumentReadOptions().ifNoneMatch(vertex.getRev()); + try { + db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME).getVertex(vertex.getKey(), BaseDocument.class, + options); + fail(); + } catch (final ArangoDBException e) { + } + } + + @Test + public void replaceVertex() { + final BaseDocument doc = new BaseDocument(); + doc.addAttribute("a", "test"); + final VertexEntity createResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME).insertVertex(doc, + null); + doc.getProperties().clear(); + doc.addAttribute("b", "test"); + final VertexUpdateEntity replaceResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) + .replaceVertex(createResult.getKey(), doc, null); + assertThat(replaceResult, is(notNullValue())); + assertThat(replaceResult.getId(), is(createResult.getId())); + assertThat(replaceResult.getRev(), is(not(replaceResult.getOldRev()))); + assertThat(replaceResult.getOldRev(), is(createResult.getRev())); + + final BaseDocument readResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) + .getVertex(createResult.getKey(), BaseDocument.class, null); + assertThat(readResult.getKey(), is(createResult.getKey())); + assertThat(readResult.getRevision(), is(replaceResult.getRev())); + assertThat(readResult.getProperties().keySet(), not(hasItem("a"))); + assertThat(readResult.getAttribute("b"), is(notNullValue())); + assertThat(String.valueOf(readResult.getAttribute("b")), is("test")); + } + + @Test + public void replaceVertexIfMatch() { + final BaseDocument doc = new BaseDocument(); + doc.addAttribute("a", "test"); + final VertexEntity createResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME).insertVertex(doc, + null); + doc.getProperties().clear(); + doc.addAttribute("b", "test"); + final VertexReplaceOptions options = new VertexReplaceOptions().ifMatch(createResult.getRev()); + final VertexUpdateEntity replaceResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) + .replaceVertex(createResult.getKey(), doc, options); + assertThat(replaceResult, is(notNullValue())); + assertThat(replaceResult.getId(), is(createResult.getId())); + assertThat(replaceResult.getRev(), is(not(replaceResult.getOldRev()))); + assertThat(replaceResult.getOldRev(), is(createResult.getRev())); + + final BaseDocument readResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) + .getVertex(createResult.getKey(), BaseDocument.class, null); + assertThat(readResult.getKey(), is(createResult.getKey())); + assertThat(readResult.getRevision(), is(replaceResult.getRev())); + assertThat(readResult.getProperties().keySet(), not(hasItem("a"))); + assertThat(readResult.getAttribute("b"), is(notNullValue())); + assertThat(String.valueOf(readResult.getAttribute("b")), is("test")); + } + + @Test + public void replaceVertexIfMatchFail() { + final BaseDocument doc = new BaseDocument(); + doc.addAttribute("a", "test"); + final VertexEntity createResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME).insertVertex(doc, + null); + doc.getProperties().clear(); + doc.addAttribute("b", "test"); + try { + final VertexReplaceOptions options = new VertexReplaceOptions().ifMatch("no"); + db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME).replaceVertex(createResult.getKey(), doc, options); + fail(); + } catch (final ArangoDBException e) { + } + } + + @Test + public void updateVertex() { + final BaseDocument doc = new BaseDocument(); + doc.addAttribute("a", "test"); + doc.addAttribute("c", "test"); + final VertexEntity createResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME).insertVertex(doc, + null); + doc.updateAttribute("a", "test1"); + doc.addAttribute("b", "test"); + doc.updateAttribute("c", null); + final VertexUpdateEntity updateResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) + .updateVertex(createResult.getKey(), doc, null); + assertThat(updateResult, is(notNullValue())); + assertThat(updateResult.getId(), is(createResult.getId())); + assertThat(updateResult.getRev(), is(not(updateResult.getOldRev()))); + assertThat(updateResult.getOldRev(), is(createResult.getRev())); + + final BaseDocument readResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) + .getVertex(createResult.getKey(), BaseDocument.class, null); + assertThat(readResult.getKey(), is(createResult.getKey())); + assertThat(readResult.getAttribute("a"), is(notNullValue())); + assertThat(String.valueOf(readResult.getAttribute("a")), is("test1")); + assertThat(readResult.getAttribute("b"), is(notNullValue())); + assertThat(String.valueOf(readResult.getAttribute("b")), is("test")); + assertThat(readResult.getRevision(), is(updateResult.getRev())); + assertThat(readResult.getProperties().keySet(), hasItem("c")); + } + + @Test + public void updateVertexIfMatch() { + final BaseDocument doc = new BaseDocument(); + doc.addAttribute("a", "test"); + doc.addAttribute("c", "test"); + final VertexEntity createResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME).insertVertex(doc, + null); + doc.updateAttribute("a", "test1"); + doc.addAttribute("b", "test"); + doc.updateAttribute("c", null); + final VertexUpdateOptions options = new VertexUpdateOptions().ifMatch(createResult.getRev()); + final VertexUpdateEntity updateResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) + .updateVertex(createResult.getKey(), doc, options); + assertThat(updateResult, is(notNullValue())); + assertThat(updateResult.getId(), is(createResult.getId())); + assertThat(updateResult.getRev(), is(not(updateResult.getOldRev()))); + assertThat(updateResult.getOldRev(), is(createResult.getRev())); + + final BaseDocument readResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) + .getVertex(createResult.getKey(), BaseDocument.class, null); + assertThat(readResult.getKey(), is(createResult.getKey())); + assertThat(readResult.getAttribute("a"), is(notNullValue())); + assertThat(String.valueOf(readResult.getAttribute("a")), is("test1")); + assertThat(readResult.getAttribute("b"), is(notNullValue())); + assertThat(String.valueOf(readResult.getAttribute("b")), is("test")); + assertThat(readResult.getRevision(), is(updateResult.getRev())); + assertThat(readResult.getProperties().keySet(), hasItem("c")); + } + + @Test + public void updateVertexIfMatchFail() { + final BaseDocument doc = new BaseDocument(); + doc.addAttribute("a", "test"); + doc.addAttribute("c", "test"); + final VertexEntity createResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME).insertVertex(doc, + null); + doc.updateAttribute("a", "test1"); + doc.addAttribute("b", "test"); + doc.updateAttribute("c", null); + try { + final VertexUpdateOptions options = new VertexUpdateOptions().ifMatch("no"); + db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME).updateVertex(createResult.getKey(), doc, options); + fail(); + } catch (final ArangoDBException e) { + } + } + + @Test + public void updateVertexKeepNullTrue() { + final BaseDocument doc = new BaseDocument(); + doc.addAttribute("a", "test"); + final VertexEntity createResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME).insertVertex(doc, + null); + doc.updateAttribute("a", null); + final VertexUpdateOptions options = new VertexUpdateOptions().keepNull(true); + final VertexUpdateEntity updateResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) + .updateVertex(createResult.getKey(), doc, options); + assertThat(updateResult, is(notNullValue())); + assertThat(updateResult.getId(), is(createResult.getId())); + assertThat(updateResult.getRev(), is(not(updateResult.getOldRev()))); + assertThat(updateResult.getOldRev(), is(createResult.getRev())); + + final BaseDocument readResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) + .getVertex(createResult.getKey(), BaseDocument.class, null); + assertThat(readResult.getKey(), is(createResult.getKey())); + assertThat(readResult.getProperties().keySet().size(), is(1)); + assertThat(readResult.getProperties().keySet(), hasItem("a")); + } + + @Test + public void updateVertexKeepNullFalse() { + final BaseDocument doc = new BaseDocument(); + doc.addAttribute("a", "test"); + final VertexEntity createResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME).insertVertex(doc, + null); + doc.updateAttribute("a", null); + final VertexUpdateOptions options = new VertexUpdateOptions().keepNull(false); + final VertexUpdateEntity updateResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) + .updateVertex(createResult.getKey(), doc, options); + assertThat(updateResult, is(notNullValue())); + assertThat(updateResult.getId(), is(createResult.getId())); + assertThat(updateResult.getRev(), is(not(updateResult.getOldRev()))); + assertThat(updateResult.getOldRev(), is(createResult.getRev())); + + final BaseDocument readResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) + .getVertex(createResult.getKey(), BaseDocument.class, null); + assertThat(readResult.getKey(), is(createResult.getKey())); + assertThat(readResult.getId(), is(createResult.getId())); + assertThat(readResult.getRevision(), is(notNullValue())); + assertThat(readResult.getProperties().keySet(), not(hasItem("a"))); + } + + @Test + public void deleteVertex() { + final BaseDocument doc = new BaseDocument(); + final VertexEntity createResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME).insertVertex(doc, + null); + db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME).deleteVertex(createResult.getKey(), null); + try { + db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME).getVertex(createResult.getKey(), BaseDocument.class, + null); + fail(); + } catch (final ArangoDBException e) { + } + } + + @Test + public void deleteVertexIfMatch() { + final BaseDocument doc = new BaseDocument(); + final VertexEntity createResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME).insertVertex(doc, + null); + final VertexDeleteOptions options = new VertexDeleteOptions().ifMatch(createResult.getRev()); + db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME).deleteVertex(createResult.getKey(), options); + try { + db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME).getVertex(createResult.getKey(), BaseDocument.class, + null); + fail(); + } catch (final ArangoDBException e) { + } + } + + @Test + public void deleteVertexIfMatchFail() { + final BaseDocument doc = new BaseDocument(); + final VertexEntity createResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME).insertVertex(doc, + null); + final VertexDeleteOptions options = new VertexDeleteOptions().ifMatch("no"); + try { + db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME).deleteVertex(createResult.getKey(), options); + fail(); + } catch (final ArangoDBException e) { + } + } +} diff --git a/src/test/java/com/arangodb/BaseDocumentTest.java b/src/test/java/com/arangodb/BaseDocumentTest.java deleted file mode 100644 index 2ddc4c97c..000000000 --- a/src/test/java/com/arangodb/BaseDocumentTest.java +++ /dev/null @@ -1,182 +0,0 @@ -package com.arangodb; - -import static org.hamcrest.CoreMatchers.instanceOf; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.not; -import static org.hamcrest.CoreMatchers.notNullValue; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.junit.Test; - -import com.arangodb.entity.BaseDocument; -import com.arangodb.entity.DocumentEntity; -import com.arangodb.entity.EdgeDefinitionEntity; - -/** - * Created by gschwab on 1/14/15. - */ -public class BaseDocumentTest extends BaseGraphTest { - - private final String graphName = "UnitTestGraph"; - // private final String edgeCollectionName = "edge"; - - class Blub { - public String getBlubStr() { - return blubStr; - } - - public void setBlubStr(final String blubStr) { - this.blubStr = blubStr; - } - - public Object getBlubObj() { - return blubObj; - } - - public void setBlubObj(final Object blubObj) { - this.blubObj = blubObj; - } - - private String blubStr; - private Object blubObj; - - public Blub(final String blubStr, final Object blubObj) { - this.blubStr = blubStr; - this.blubObj = blubObj; - } - } - - @Test - public void constructor() { - final String myKey = "myKey"; - final Map myEmptyMap = new HashMap(); - - BaseDocument doc = new BaseDocument(); - assertThat(doc, instanceOf(BaseDocument.class)); - assertEquals(doc.getProperties(), myEmptyMap); - - doc = new BaseDocument(myKey); - assertThat(doc, instanceOf(BaseDocument.class)); - assertEquals(doc.getProperties(), myEmptyMap); - assertThat(doc.getDocumentKey(), is(myKey)); - - final String key1 = "key1"; - final String key2 = "key2"; - final String key3 = "key3"; - final String val1 = "val1"; - final int val2 = 2; - - final Blub val3 = new Blub("pappnase", 4711); - - final Map myMap = new HashMap(); - myMap.put(key1, val1); - myMap.put(key2, val2); - myMap.put(key3, val3); - - doc = new BaseDocument(myMap); - assertThat(doc, instanceOf(BaseDocument.class)); - assertThat(doc.getProperties().size(), is(3)); - assertThat(doc.getProperties().get(key1), instanceOf(String.class)); - assertThat((String) doc.getProperties().get(key1), is(val1)); - assertThat(doc.getProperties().get(key2), instanceOf(Integer.class)); - assertThat((Integer) doc.getProperties().get(key2), is(val2)); - assertThat(doc.getProperties().get(key3), instanceOf(Blub.class)); - assertThat((Blub) doc.getProperties().get(key3), is(val3)); - - doc = new BaseDocument(myKey, myMap); - assertThat(doc, instanceOf(BaseDocument.class)); - assertThat(doc.getDocumentKey(), is(myKey)); - assertThat(doc.getProperties().size(), is(3)); - assertThat(doc.getProperties().get(key1), instanceOf(String.class)); - assertThat((String) doc.getProperties().get(key1), is(val1)); - assertThat(doc.getProperties().get(key2), instanceOf(Integer.class)); - assertThat((Integer) doc.getProperties().get(key2), is(val2)); - assertThat(doc.getProperties().get(key3), instanceOf(Blub.class)); - assertThat((Blub) doc.getProperties().get(key3), is(val3)); - - } - - @Test - public void save_document() throws ArangoException { - final String key1 = "key1"; - final String key2 = "key2"; - final String key3 = "key3"; - final String key4 = "key4"; - final String key5 = "key5"; - final String key6 = "key6"; - final String key7 = "key7"; - - final String val1 = "val1"; - final double val2 = -20; - final Blub val3 = new Blub("pappnase", 4711); - final Object[] val4 = new Object[4]; - val4[0] = 1; - val4[1] = 2; - val4[2] = "Hallo"; - val4[3] = new Blub("Hallo", 42); - final Boolean val5 = true; - final Object val6 = null; - final Object val7 = 0; - - final Map myMap = new HashMap(); - myMap.put(key1, val1); - myMap.put(key2, val2); - myMap.put(key3, val3); - myMap.put(key4, val4); - myMap.put(key5, val5); - myMap.put(key6, val6); - myMap.put(key7, val7); - - final BaseDocument baseDocument = new BaseDocument(myMap); - - driver.createCollection("myCollection"); - driver.createDocument("myCollection", baseDocument); - - driver.createGraph(this.graphName, this.createEdgeDefinitions(), null, true); - final BaseDocument myDoc1 = new BaseDocument("myKeyFROM", myMap); - final Blub myDoc2 = new Blub("myKeyTO", new Blub("blub2", new Blub("blub3", 42))); - final DocumentEntity v1 = driver.graphCreateVertex(this.graphName, "from", myDoc1, null); - driver.graphCreateVertex(this.graphName, "to", myDoc2, null); - - final DocumentEntity v1DB = driver.getDocument(v1.getDocumentHandle(), BaseDocument.class); - // DocumentEntity v2DB = - // driver.getDocument(v2.getDocumentHandle(), Blub.class); - - assertThat(v1DB.getStatusCode(), is(200)); - assertThat(v1DB.isError(), is(false)); - assertThat(v1DB.getDocumentHandle(), is(notNullValue())); - assertThat(v1DB.getDocumentRevision(), is(not(notNullValue()))); - assertThat(v1DB.getDocumentKey(), is(notNullValue())); - // final Map dbProperties = - // v1DB.getEntity().getProperties(); - // final Object x = dbProperties.get(key1); - - assertThat((String) v1DB.getEntity().getProperties().get(key1), is(val1)); - assertThat((Double) v1DB.getEntity().getProperties().get(key2), is(val2)); - assertThat((Boolean) v1DB.getEntity().getProperties().get(key5), is(val5)); - - assertThat(v1DB.getDocumentKey(), is(notNullValue())); - - } - - protected List createEdgeDefinitions() { - final List edgeDefinitions = new ArrayList(); - final EdgeDefinitionEntity edgeDefinition = new EdgeDefinitionEntity(); - edgeDefinition.setCollection("edge"); - final List from = new ArrayList(); - from.add("from"); - edgeDefinition.setFrom(from); - final List to = new ArrayList(); - to.add("to"); - edgeDefinition.setTo(to); - edgeDefinitions.add(edgeDefinition); - return edgeDefinitions; - } - -} diff --git a/src/test/java/com/arangodb/BaseGraphTest.java b/src/test/java/com/arangodb/BaseGraphTest.java deleted file mode 100644 index a2c434175..000000000 --- a/src/test/java/com/arangodb/BaseGraphTest.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Copyright (C) 2012,2013 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb; - -import java.util.ArrayList; -import java.util.List; - -import org.junit.After; -import org.junit.Before; - -import com.arangodb.entity.EdgeDefinitionEntity; -import com.arangodb.entity.GraphEntity; - -/** - * @author tamtam180 - kirscheless at gmail.com - * @author a-brandt - * - */ -public abstract class BaseGraphTest extends BaseTest { - - @Before - public void _before() throws ArangoException { - - final String deleteAllGraphsAndTheirCollections = "var db = require('internal').db;\n" - + "var graph = require('org/arangodb/general-graph');\n" + "graph._list().forEach(function(g){\n" - + " graph._drop(g, true)\n" + "});"; - driver.executeScript(deleteAllGraphsAndTheirCollections); - final String deleteAllCollections = "var db = require('internal').db;\n" - + "var cols = db._collections().filter(function(c) { return c.name()[0] !== \"_\" });\n" - + "cols.forEach(function(col){db._drop(col.name())});"; - driver.executeScript(deleteAllCollections); - } - - @After - public void after() throws ArangoException { - final String deleteAllGraphsAndTheirCollections = "var db = require('internal').db;\n" - + "var graph = require('org/arangodb/general-graph');\n" + "graph._list().forEach(function(g){\n" - + " graph._drop(g, true)\n" + "});"; - driver.executeScript(deleteAllGraphsAndTheirCollections); - } - - protected List createEdgeDefinitions(final int count, final int offset) { - final List edgeDefinitions = new ArrayList(); - for (int i = 1 + offset; i <= count + offset; i++) { - final EdgeDefinitionEntity edgeDefinition = new EdgeDefinitionEntity(); - edgeDefinition.setCollection("edge-" + i); - final List from = new ArrayList(); - from.add("from" + i + "-1"); - from.add("from" + i + "-2"); - from.add("from" + i + "-3"); - edgeDefinition.setFrom(from); - final List to = new ArrayList(); - to.add("to" + i + "-1"); - to.add("to" + i + "-2"); - to.add("to" + i + "-3"); - edgeDefinition.setTo(to); - edgeDefinitions.add(edgeDefinition); - } - return edgeDefinitions; - } - - protected List createOrphanCollections(final int count) { - final List orphanCollections = new ArrayList(); - for (int i = 1; i <= count; i++) { - orphanCollections.add("orphan" + i); - } - return orphanCollections; - } - - protected GraphEntity createTestGraph() throws ArangoException { - final String createGraph = "var db = require('internal').db;\n" - + "var graphModule = require('org/arangodb/general-graph');\n" - + "graphModule._create('CountryGraph', [graphModule._relation('hasBorderWith', ['Country'], ['Country'])]);\n" - + "db.Country.save({'_key' : 'Germany'});\n" + "db.Country.save({'_key' : 'Austria'});\n" - + "db.Country.save({'_key' : 'Switzerland'});\n" + "db.Country.save({'_key' : 'Marocco'});\n" - + "db.Country.save({'_key' : 'Algeria'});\n" + "db.Country.save({'_key' : 'Tunesia'});\n" - + "db.Country.save({'_key' : 'Brasil'});\n" + "db.Country.save({'_key' : 'Argentina'});\n" - + "db.Country.save({'_key' : 'Uruguay'});\n" + "db.Country.save({'_key' : 'Australia'});\n" - + "db.hasBorderWith.save('Country/Germany', 'Country/Austria', {});\n" - + "db.hasBorderWith.save('Country/Germany', 'Country/Switzerland', {});\n" - + "db.hasBorderWith.save('Country/Switzerland', 'Country/Austria', {});\n" - + "db.hasBorderWith.save('Country/Marocco', 'Country/Algeria', {});\n" - + "db.hasBorderWith.save('Country/Algeria', 'Country/Tunesia', {});\n" - + "db.hasBorderWith.save('Country/Brasil', 'Country/Argentina', {});\n" - + "db.hasBorderWith.save('Country/Brasil', 'Country/Uruguay', {});\n" - + "db.hasBorderWith.save('Country/Argentina', 'Country/Uruguay', {});"; - - driver.executeScript(createGraph); - - return driver.getGraph("CountryGraph"); - } - -} diff --git a/src/test/java/com/arangodb/BaseTest.java b/src/test/java/com/arangodb/BaseTest.java index a3abe9c50..1fa45fd47 100644 --- a/src/test/java/com/arangodb/BaseTest.java +++ b/src/test/java/com/arangodb/BaseTest.java @@ -1,72 +1,56 @@ -/* - * Copyright (C) 2012 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb; - -import org.junit.AfterClass; -import org.junit.BeforeClass; - -import com.arangodb.entity.ArangoVersion; -import com.arangodb.util.TestUtils; - -/** - * @author tamtam180 - kirscheless at gmail.com - * - */ -public abstract class BaseTest { - - protected static final String DATABASE_NAME = "unitTestDatabase"; - - protected static boolean MANAGE_SETUP = true; - protected static ArangoConfigure configure; - protected static ArangoDriver driver; - - @BeforeClass - public static void __setup() { - if (MANAGE_SETUP) { - final ArangoConfigure configure = new ArangoConfigure(); - configure.setConnectRetryCount(2); - configure.init(); - final ArangoDriver driver = new ArangoDriver(configure); - - BaseTest.driver = driver; - BaseTest.configure = configure; - } - try { - driver.createDatabase(DATABASE_NAME); - } catch (final ArangoException e) { - } - driver.setDefaultDatabase(DATABASE_NAME); - } - - @AfterClass - public static void __shutdown() { - if (MANAGE_SETUP) { - try { - driver.deleteDatabase(DATABASE_NAME); - } catch (final ArangoException e) { - } - configure.shutdown(); - } - } - - protected boolean isMinimumVersion(final String version) throws ArangoException { - final ArangoVersion ver = driver.getVersion(); - final int b = TestUtils.compareVersion(ver.getVersion(), version); - return b > -1; - } - -} +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb; + +import org.junit.AfterClass; +import org.junit.BeforeClass; + +/** + * @author Mark - mark at arangodb.com + * + */ +public abstract class BaseTest { + + protected static final String TEST_DB = "java_driver_test_db"; + protected static ArangoDB arangoDB; + protected static ArangoDatabase db; + + @BeforeClass + public static void init() { + if (arangoDB == null) { + arangoDB = new ArangoDB.Builder().build(); + } + try { + arangoDB.db(TEST_DB).drop(); + } catch (final ArangoDBException e) { + } + arangoDB.createDatabase(TEST_DB); + BaseTest.db = arangoDB.db(TEST_DB); + } + + @AfterClass + public static void shutdown() { + arangoDB.db(TEST_DB).drop(); + arangoDB.shutdown(); + arangoDB = null; + } + +} diff --git a/src/test/java/com/arangodb/NegativeTest.java b/src/test/java/com/arangodb/NegativeTest.java deleted file mode 100644 index 6b102dbb7..000000000 --- a/src/test/java/com/arangodb/NegativeTest.java +++ /dev/null @@ -1,128 +0,0 @@ -/* - * Copyright (C) 2012 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb; - -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; - -import org.junit.Ignore; -import org.junit.Test; - -import com.arangodb.entity.DefaultEntity; -import com.arangodb.entity.DocumentEntity; -import com.arangodb.entity.EntityFactory; -import com.arangodb.http.HttpManager; -import com.arangodb.http.HttpResponseEntity; - -/** - * @author tamtam180 - kirscheless at gmail.com - * - */ -public class NegativeTest extends BaseTest { - - /** - * 開発途中にあった命令だけど、今は存在しない。 きとんとエラーになること。 - * - * @throws ArangoException - */ - @Ignore - @Test - public void test_collections() throws ArangoException { - - final ArangoConfigure configure = new ArangoConfigure(); - - final HttpManager httpManager = new HttpManager(configure); - httpManager.init(); - - // TODO Create configure of common test. - final HttpResponseEntity res = httpManager.doGet("http://" + configure.getArangoHost().getHost() + ":" - + configure.getArangoHost().getPort() + "/_api/collections", - null); - - final DefaultEntity entity = EntityFactory.createEntity(res.getText(), DefaultEntity.class); - assertThat(entity.isError(), is(true)); - assertThat(entity.getCode(), is(501)); - assertThat(entity.getErrorNumber(), is(9)); - - httpManager.destroy(); - - } - - public static class TestComplex { - private String name; - - public String getName() { - return name; - } - - public void setName(final String name) { - this.name = name; - } - } - - @Test - public void test_issue_35_and_41() throws Exception { - - final ArangoConfigure configure = new ArangoConfigure(); - configure.init(); - final ArangoDriver driver = new ArangoDriver(configure); - - try { - driver.createCollection("unit_test_issue35"); - } catch (final ArangoException e) { - } - - final TestComplex value = new TestComplex(); - value.setName("A\"A'@:///A"); - - // String value = "AAA"; - final DocumentEntity doc = driver.createDocument("unit_test_issue35", value, true); - final String documentHandle = doc.getDocumentHandle(); - driver.getDocument(documentHandle, TestComplex.class); - - configure.shutdown(); - - } - - @Test - public void test_primitive() throws Exception { - - final ArangoConfigure configure = new ArangoConfigure(); - configure.init(); - final ArangoDriver driver = new ArangoDriver(configure); - - try { - driver.createCollection("unit_test_issue35"); - } catch (final ArangoException e) { - } - - try { - final String value = "AAA"; - final DocumentEntity doc = driver.createDocument("unit_test_issue35", value, true, true); - final String documentHandle = doc.getDocumentHandle(); - driver.getDocument(documentHandle, String.class); - fail(); - } catch (final ArangoException e) { - assertThat(e.getErrorNumber(), is(ErrorNums.ERROR_ARANGO_DOCUMENT_TYPE_INVALID)); - } - - configure.shutdown(); - - } - -} diff --git a/src/test/java/com/arangodb/PrimitiveDocumentTest.java b/src/test/java/com/arangodb/PrimitiveDocumentTest.java deleted file mode 100644 index c42d254fb..000000000 --- a/src/test/java/com/arangodb/PrimitiveDocumentTest.java +++ /dev/null @@ -1,209 +0,0 @@ -/* - * Copyright (C) 2012 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb; - -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; - -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.arangodb.entity.DocumentEntity; -import com.google.gson.Gson; - -/** - * @author tamtam180 - kirscheless at gmail.com - * - */ -public class PrimitiveDocumentTest extends BaseTest { - - private static Logger logger = LoggerFactory.getLogger(PrimitiveDocumentTest.class); - - @Before - public void setUp() { - try { - driver.createCollection("unit_test_primitive"); - } catch (final ArangoException e) { - } - - } - - @Test - public void test_string() throws ArangoException { - - final String value = "AAA"; - try { - driver.createDocument("unit_test_primitive", value, true, true); - fail(); - } catch (final ArangoException e) { - assertThat(e.getErrorNumber(), is(ErrorNums.ERROR_ARANGO_DOCUMENT_TYPE_INVALID)); - } - } - - @Test - public void test_string_quote() throws ArangoException { - - final String value = "AA\"A"; - - try { - driver.createDocument("unit_test_primitive", value, true, true); - fail(); - } catch (final ArangoException e) { - assertThat(e.getErrorNumber(), is(ErrorNums.ERROR_ARANGO_DOCUMENT_TYPE_INVALID)); - } - } - - @Test - public void test_string_multibyte1() throws ArangoException { - - final String value = "AA☆A"; - - try { - driver.createDocument("unit_test_primitive", value, true, true); - fail(); - } catch (final ArangoException e) { - assertThat(e.getErrorNumber(), is(ErrorNums.ERROR_ARANGO_DOCUMENT_TYPE_INVALID)); - } - } - - @Test - public void test_string_multibyte2() throws ArangoException { - - final TestComplexEntity01 value = new TestComplexEntity01("寿司", "", 10); - logger.debug(new Gson().toJson(value)); - - final DocumentEntity res = driver.createDocument("unit_test_primitive", value, true); - final String documentHandle = res.getDocumentHandle(); - - final DocumentEntity doc = driver.getDocument(documentHandle, TestComplexEntity01.class); - logger.debug(doc.getEntity().getUser()); - logger.debug(doc.getEntity().getDesc()); - logger.debug(doc.getEntity().getAge().toString()); - } - - @Test - public void test_string_escape() throws ArangoException { - - final String value = "\\\\"; - try { - driver.createDocument("unit_test_primitive", value, true, true); - fail(); - } catch (final ArangoException e) { - assertThat(e.getErrorNumber(), is(ErrorNums.ERROR_ARANGO_DOCUMENT_TYPE_INVALID)); - } - } - - @Test - public void test_string_spchar() throws ArangoException { - - final String value = "AA\t\nA;/@*:='&%$#!~\\"; - - try { - driver.createDocument("unit_test_primitive", value, true, true); - fail(); - } catch (final ArangoException e) { - assertThat(e.getErrorNumber(), is(ErrorNums.ERROR_ARANGO_DOCUMENT_TYPE_INVALID)); - } - } - - @Test - public void test_null() throws ArangoException { - - final String value = null; - try { - driver.createDocument("unit_test_primitive", value, true, true); - fail(); - } catch (final ArangoException e) { - assertThat(e.getErrorNumber(), is(ErrorNums.ERROR_ARANGO_DOCUMENT_TYPE_INVALID)); - } - } - - @Test - public void test_boolean_true() throws ArangoException { - - final boolean value = true; - - try { - driver.createDocument("unit_test_primitive", value, true); - fail(); - } catch (final ArangoException e) { - assertThat(e.getErrorNumber(), is(ErrorNums.ERROR_ARANGO_DOCUMENT_TYPE_INVALID)); - } - - } - - @Test - public void test_boolean_false() throws ArangoException { - - final boolean value = false; - try { - driver.createDocument("unit_test_primitive", value, true); - fail(); - } catch (final ArangoException e) { - assertThat(e.getErrorNumber(), is(ErrorNums.ERROR_ARANGO_DOCUMENT_TYPE_INVALID)); - } - - } - - @Test - public void test_number_int() throws ArangoException { - - final int value = 1000000; - - try { - driver.createDocument("unit_test_primitive", value, true); - fail(); - } catch (final ArangoException e) { - assertThat(e.getErrorNumber(), is(ErrorNums.ERROR_ARANGO_DOCUMENT_TYPE_INVALID)); - } - - } - - @Test - public void test_number_long() throws ArangoException { - - final long value = Long.MAX_VALUE; - - try { - driver.createDocument("unit_test_primitive", value, true); - fail(); - } catch (final ArangoException e) { - assertThat(e.getErrorNumber(), is(ErrorNums.ERROR_ARANGO_DOCUMENT_TYPE_INVALID)); - } - - } - - @Test - @Ignore - public void test_number_double() throws ArangoException { - - final double value = Double.MAX_VALUE; - - try { - driver.createDocument("unit_test_primitive", value, true); - fail(); - } catch (final ArangoException e) { - assertThat(e.getErrorNumber(), is(ErrorNums.ERROR_ARANGO_DOCUMENT_TYPE_INVALID)); - } - - } - -} diff --git a/src/test/java/com/arangodb/Station.java b/src/test/java/com/arangodb/Station.java deleted file mode 100644 index e32ced73d..000000000 --- a/src/test/java/com/arangodb/Station.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Copyright (C) 2012,2013 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb; - -/** - * Test POJO. - * Station Information in Tokyo, Japan. - * @author tamtam180 - kirscheless at gmail.com - * - */ -public class Station { - - private int companyCode; - private String company; - private int lineCode; - private String line; - private int stationCode; - private String station; - private String address; - private double lon; - private double lat; - - public Station() { - - } - - public Station(String[] items) { - this.companyCode = Integer.parseInt(items[0]); - this.company = items[1]; - this.lineCode = Integer.parseInt(items[2]); - this.line = items[3]; - this.stationCode = Integer.parseInt(items[4]); - this.station = items[5]; - this.address = items[6]; - this.lon = Double.parseDouble(items[7]); - this.lat = Double.parseDouble(items[8]); - } - - public int getCompanyCode() { - return companyCode; - } - public String getCompany() { - return company; - } - public int getLineCode() { - return lineCode; - } - public String getLine() { - return line; - } - public int getStationCode() { - return stationCode; - } - public String getStation() { - return station; - } - public String getAddress() { - return address; - } - public double getLon() { - return lon; - } - public double getLat() { - return lat; - } - public void setCompanyCode(int companyCode) { - this.companyCode = companyCode; - } - public void setCompany(String company) { - this.company = company; - } - public void setLineCode(int lineCode) { - this.lineCode = lineCode; - } - public void setLine(String line) { - this.line = line; - } - public void setStationCode(int stationCode) { - this.stationCode = stationCode; - } - public void setStation(String station) { - this.station = station; - } - public void setAddress(String address) { - this.address = address; - } - public void setLon(double lon) { - this.lon = lon; - } - public void setLat(double lat) { - this.lat = lat; - } - -} diff --git a/src/test/java/com/arangodb/TestBaseParameters.java b/src/test/java/com/arangodb/TestBaseParameters.java deleted file mode 100644 index 17534d98a..000000000 --- a/src/test/java/com/arangodb/TestBaseParameters.java +++ /dev/null @@ -1,55 +0,0 @@ -package com.arangodb; - -public class TestBaseParameters { - - private boolean error; - private int code; - private int errorNum; - private String errorMessage; - private int etag; - - public TestBaseParameters( - boolean error, - int code, - int errorNum, - String errorMessage, - int etag) { - this.error = error; - this.code = code; - this.errorNum = errorNum; - this.errorMessage = errorMessage; - this.etag = etag; - } - - public boolean isError() { - return error; - } - public void setError(boolean error) { - this.error = error; - } - public int getCode() { - return code; - } - public void setCode(int code) { - this.code = code; - } - public int getErrorNum() { - return errorNum; - } - public void setErrorNum(int errorNum) { - this.errorNum = errorNum; - } - public String getErrorMessage() { - return errorMessage; - } - public void setErrorMessage(String errorMessage) { - this.errorMessage = errorMessage; - } - public int getEtag() { - return etag; - } - public void setEtag(int etag) { - this.etag = etag; - } - -} diff --git a/src/test/java/com/arangodb/TestComplexEntity01.java b/src/test/java/com/arangodb/TestComplexEntity01.java deleted file mode 100644 index 4c157b5fc..000000000 --- a/src/test/java/com/arangodb/TestComplexEntity01.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright (C) 2012 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb; - -/** - * @author tamtam180 - kirscheless at gmail.com - * @author gschwab - * - */ -public class TestComplexEntity01 { - - private String user;// = "testUser01"; - private String desc;// = "This is a test user"; - private Integer age;// = 18; - - public TestComplexEntity01() { - } - - public TestComplexEntity01(String user, String desc, Integer age) { - this.user = user; - this.desc = desc; - this.age = age; - } - - public String getUser() { - return user; - } - - public String getDesc() { - return desc; - } - - public Integer getAge() { - return age; - } - - public void setUser(String user) { - this.user = user; - } - - public void setDesc(String desc) { - this.desc = desc; - } - - public void setAge(Integer age) { - this.age = age; - } - -} diff --git a/src/test/java/com/arangodb/TestComplexEntity02.java b/src/test/java/com/arangodb/TestComplexEntity02.java deleted file mode 100644 index 4ab0bda1d..000000000 --- a/src/test/java/com/arangodb/TestComplexEntity02.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright (C) 2012,2013 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb; - -/** - * @author tamtam180 - kirscheless at gmail.com - * - */ -public class TestComplexEntity02 { - - private Integer x; - private Integer y; - private Integer z; - - public TestComplexEntity02() { - } - - public TestComplexEntity02(Integer x, Integer y, Integer z) { - this.x = x; - this.y = y; - this.z = z; - } - - public Integer getX() { - return x; - } - public Integer getY() { - return y; - } - public Integer getZ() { - return z; - } - public void setX(Integer x) { - this.x = x; - } - public void setY(Integer y) { - this.y = y; - } - public void setZ(Integer z) { - this.z = z; - } - -} diff --git a/src/test/java/com/arangodb/TestComplexEntity03.java b/src/test/java/com/arangodb/TestComplexEntity03.java deleted file mode 100644 index b4f7e32de..000000000 --- a/src/test/java/com/arangodb/TestComplexEntity03.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Copyright (C) 2012 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb; - -import com.arangodb.entity.BaseDocument; -import com.google.gson.annotations.SerializedName; - -/** - * @author tamtam180 - kirscheless at gmail.com - * @author gschwab - * - */ -public class TestComplexEntity03 { - - @SerializedName(BaseDocument.KEY) - private String documentKey; - @SerializedName(BaseDocument.REV) - private String documentRevision; - @SerializedName(BaseDocument.ID) - private String documentHandle; - - private String user;// = "testUser01"; - private String desc;// = "This is a test user"; - private Integer age;// = 18; - - public TestComplexEntity03() { - } - - public TestComplexEntity03(final String user, final String desc, final Integer age) { - this.user = user; - this.desc = desc; - this.age = age; - } - - public String getUser() { - return user; - } - - public String getDesc() { - return desc; - } - - public Integer getAge() { - return age; - } - - public void setUser(final String user) { - this.user = user; - } - - public void setDesc(final String desc) { - this.desc = desc; - } - - public void setAge(final Integer age) { - this.age = age; - } - - public String getDocumentKey() { - return documentKey; - } - - public void setDocumentKey(final String documentKey) { - this.documentKey = documentKey; - } - - public String getDocumentHandle() { - return documentHandle; - } - - public void setDocumentHandle(final String documentHandle) { - this.documentHandle = documentHandle; - } - - public String getDocumentRevision() { - return documentRevision; - } - - public void setDocumentRevision(final String documentRevision) { - this.documentRevision = documentRevision; - } - -} diff --git a/src/test/java/com/arangodb/TestInterface.java b/src/test/java/com/arangodb/TestInterface.java deleted file mode 100644 index 12e919013..000000000 --- a/src/test/java/com/arangodb/TestInterface.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright (C) 2015 tporadowski - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb; - -/** - * @author tporadowski - tomasz at poradowski.com - */ -public interface TestInterface { - String getName(); -} diff --git a/src/test/java/com/arangodb/bench/AbstractBenchmarkImporter.java b/src/test/java/com/arangodb/bench/AbstractBenchmarkImporter.java deleted file mode 100644 index a9f991e56..000000000 --- a/src/test/java/com/arangodb/bench/AbstractBenchmarkImporter.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.arangodb.bench; - -import java.util.List; - -import com.arangodb.ArangoDriver; - -public abstract class AbstractBenchmarkImporter { - - protected final ArangoDriver driver; - - protected final String collectionName; - - public AbstractBenchmarkImporter(ArangoDriver driver, String collectionName) { - this.driver = driver; - this.collectionName = collectionName; - } - - abstract protected void execute(List values) throws Exception; - - public long bench(List values) throws Exception { - long t = System.currentTimeMillis(); - execute(values); - return System.currentTimeMillis() - t; - } - -} diff --git a/src/test/java/com/arangodb/bench/BenchmarkImport.java b/src/test/java/com/arangodb/bench/BenchmarkImport.java deleted file mode 100644 index cd7f036a8..000000000 --- a/src/test/java/com/arangodb/bench/BenchmarkImport.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Copyright (C) 2012,2013 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.bench; - -import java.util.List; - -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import com.arangodb.ArangoException; -import com.arangodb.Station; -import com.arangodb.example.document.BaseExample; -import com.arangodb.util.TestUtils; - -/** - * Import a list of objects - * - * 1. Import the data with importDocuments() - * - * 2. Import the data with createDocument() - * - * @author tamtam180 - kirscheless at gmail.com - * @author a-brandt - * - */ -public class BenchmarkImport extends BaseExample { - - private static final String DATABASE_NAME = "BenchmarkImport"; - private static final String COLLECTION_NAME = "BenchmarkImportCollection"; - - @Before - public void _before() { - removeTestDatabase(DATABASE_NAME); - - createDatabase(driver, DATABASE_NAME); - } - - @After - public void _after() { - removeTestDatabase(DATABASE_NAME); - } - - @Test - public void BenchmarkImportTest() throws Exception { - - final int max = 10; - - // - printHeadline("read example data"); - // - - final List stations = TestUtils.readStations(); - - // truncate collection - try { - driver.truncateCollection(COLLECTION_NAME); - } catch (final ArangoException e) { - } - - // create importer - final AbstractBenchmarkImporter logic1 = new ImportDocumentBenchmarkImporter(driver, COLLECTION_NAME); - final AbstractBenchmarkImporter logic2 = new SingleDocumentBenchmarkImporter(driver, COLLECTION_NAME); - - // - printHeadline("import data"); - // - - // Bench import and create document - long time1 = 0, time2 = 0; - for (int i = 0; i < max; i++) { - time1 += logic1.bench(stations); - time2 += logic2.bench(stations); - } - - // - printHeadline("results"); - // - System.out.println("importDocuments(): " + time1 + " ms"); - System.out.println("createDocument(): " + time2 + " ms"); - - Assert.assertTrue(time1 < time2); - } - -} diff --git a/src/test/java/com/arangodb/bench/ImportDocumentBenchmarkImporter.java b/src/test/java/com/arangodb/bench/ImportDocumentBenchmarkImporter.java deleted file mode 100644 index a7abed823..000000000 --- a/src/test/java/com/arangodb/bench/ImportDocumentBenchmarkImporter.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.arangodb.bench; - -import java.util.List; - -import com.arangodb.ArangoDriver; - -/** - * Import all values with importDocuments() - * - * @author a-brandt - * - */ -public class ImportDocumentBenchmarkImporter extends AbstractBenchmarkImporter { - - public ImportDocumentBenchmarkImporter(ArangoDriver driver, String collectionName) { - super(driver, collectionName); - } - - @Override - protected void execute(List values) throws Exception { - try { - driver.createCollection(collectionName); - } catch (Exception ex) { - } - - driver.importDocuments(collectionName, values); - } - -} diff --git a/src/test/java/com/arangodb/bench/SingleDocumentBenchmarkImporter.java b/src/test/java/com/arangodb/bench/SingleDocumentBenchmarkImporter.java deleted file mode 100644 index 43d7409c7..000000000 --- a/src/test/java/com/arangodb/bench/SingleDocumentBenchmarkImporter.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.arangodb.bench; - -import java.util.List; - -import com.arangodb.ArangoDriver; - -/** - * Import all values with createDocument() - * - * @author a-brandt - * - */ -public class SingleDocumentBenchmarkImporter extends AbstractBenchmarkImporter { - - public SingleDocumentBenchmarkImporter(final ArangoDriver driver, final String collectionName) { - super(driver, collectionName); - } - - @Override - protected void execute(final List values) throws Exception { - for (final Object value : values) { - driver.createDocument(collectionName, value, false); - } - } - -} diff --git a/src/test/java/com/arangodb/entity/BaseDocumentTest.java b/src/test/java/com/arangodb/entity/BaseDocumentTest.java new file mode 100644 index 000000000..40f770781 --- /dev/null +++ b/src/test/java/com/arangodb/entity/BaseDocumentTest.java @@ -0,0 +1,98 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.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.VPackConfigure; +import com.arangodb.velocypack.VPack; +import com.arangodb.velocypack.VPack.Builder; +import com.arangodb.velocypack.VPackBuilder; +import com.arangodb.velocypack.VPackParser; +import com.arangodb.velocypack.VPackSlice; +import com.arangodb.velocypack.ValueType; +import com.arangodb.velocypack.exception.VPackException; + +/** + * @author Mark - mark at arangodb.com + * + */ +public class BaseDocumentTest { + + @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(); + VPackConfigure.configure(builder, new VPackParser(), null); + 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 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 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(); + + final VPack.Builder vbuilder = new VPack.Builder(); + VPackConfigure.configure(vbuilder, new VPackParser(), null); + 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")); + } + +} diff --git a/src/test/java/com/arangodb/example/ExampleBase.java b/src/test/java/com/arangodb/example/ExampleBase.java new file mode 100644 index 000000000..d89a7c439 --- /dev/null +++ b/src/test/java/com/arangodb/example/ExampleBase.java @@ -0,0 +1,63 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.example; + +import org.junit.AfterClass; +import org.junit.BeforeClass; + +import com.arangodb.ArangoCollection; +import com.arangodb.ArangoDB; +import com.arangodb.ArangoDBException; +import com.arangodb.ArangoDatabase; + +/** + * @author Mark - mark at arangodb.com + * + */ +public class ExampleBase { + + protected static final String DB_NAME = "json_example_db"; + protected static final String COLLECTION_NAME = "json_example_collection"; + + protected static ArangoDB arangoDB; + protected static ArangoDatabase db; + protected static ArangoCollection collection; + + @BeforeClass + public static void setUp() { + arangoDB = new ArangoDB.Builder().build(); + try { + arangoDB.db(DB_NAME).drop(); + } catch (final ArangoDBException e) { + } + arangoDB.createDatabase(DB_NAME); + db = arangoDB.db(DB_NAME); + db.createCollection(COLLECTION_NAME); + collection = db.collection(COLLECTION_NAME); + } + + @AfterClass + public static void tearDown() { + db.drop(); + arangoDB.shutdown(); + } + +} diff --git a/src/test/java/com/arangodb/example/ExamplesTestSuite.java b/src/test/java/com/arangodb/example/ExamplesTestSuite.java deleted file mode 100644 index c698ecebd..000000000 --- a/src/test/java/com/arangodb/example/ExamplesTestSuite.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (C) 2015 ArangoDB GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.example; - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; -import org.junit.runners.Suite.SuiteClasses; - -import com.arangodb.bench.BenchmarkImport; -import com.arangodb.example.document.DocumentExamplesTestSuite; -import com.arangodb.example.graph.GraphExamplesTestSuite; -import com.arangodb.example.ssl.SslExample; - -/** - * Start all examples (unit tests) in example directory - * - * @author a-brandt - * - */ -@RunWith(Suite.class) -@SuiteClasses({ - - DocumentExamplesTestSuite.class, - - GraphExamplesTestSuite.class, - - BenchmarkImport.class, - - TransactionExample.class, - - SslExample.class - -}) - -public class ExamplesTestSuite { - -} diff --git a/src/test/java/com/arangodb/example/FirstProject.java b/src/test/java/com/arangodb/example/FirstProject.java index df3f2b790..c7d3a4c42 100644 --- a/src/test/java/com/arangodb/example/FirstProject.java +++ b/src/test/java/com/arangodb/example/FirstProject.java @@ -1,170 +1,136 @@ -/* - * Copyright (C) 2015 ArangoDB GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.example; - -import java.util.Iterator; -import java.util.Map; - -import com.arangodb.ArangoConfigure; -import com.arangodb.ArangoDriver; -import com.arangodb.ArangoException; -import com.arangodb.DocumentCursor; -import com.arangodb.entity.BaseDocument; -import com.arangodb.entity.CollectionEntity; -import com.arangodb.entity.DocumentEntity; -import com.arangodb.util.MapBuilder; - -/** - * My first ArangoDB project - */ -public class FirstProject { - - public static void main(String[] args) { - - // - // You can find the ArangoDB Web interface here: - // http://127.0.0.1:8529/_db/mydb/ - // - - // Lets configure and open a connection to start ArangoDB. - ArangoConfigure configure = new ArangoConfigure(); - configure.init(); - ArangoDriver arangoDriver = new ArangoDriver(configure); - // The default connection is to http://127.0.0.1:8529. - - // Lets configure and open a connection to start ArangoDB. - String dbName = "mydb"; - try { - arangoDriver.createDatabase(dbName); - System.out.println("Database created: " + dbName); - } catch (Exception e) { - System.out.println("Failed to create database " + dbName + "; " + e.getMessage()); - } - - // You can set the new database as default database for the driver: - arangoDriver.setDefaultDatabase(dbName); - - String collectionName = "firstCollection"; - try { - CollectionEntity myArangoCollection = arangoDriver.createCollection(collectionName); - System.out.println("Collection created: " + myArangoCollection.getName()); - } catch (Exception e) { - System.out.println("Failed to create colleciton " + collectionName + "; " + e.getMessage()); - } - - // create a document - BaseDocument myObject = new BaseDocument(); - myObject.setDocumentKey("myKey"); - myObject.addAttribute("a", "Foo"); - myObject.addAttribute("b", 42); - try { - arangoDriver.createDocument(collectionName, myObject); - System.out.println("Document created"); - } catch (ArangoException e) { - System.out.println("Failed to create document. " + e.getMessage()); - } - - // read a document - DocumentEntity myDocument = null; - BaseDocument myObject2 = null; - try { - myDocument = arangoDriver.getDocument(collectionName, "myKey", BaseDocument.class); - myObject2 = myDocument.getEntity(); - System.out.println("Key: " + myObject2.getDocumentKey()); - System.out.println("Attribute 'a': " + myObject2.getProperties().get("a")); - System.out.println("Attribute 'b': " + myObject2.getProperties().get("b")); - System.out.println("Attribute 'c': " + myObject2.getProperties().get("c")); - } catch (ArangoException e) { - System.out.println("Failed to get document. " + e.getMessage()); - } - - // update a document - try { - myObject2.addAttribute("c", "Bar"); - arangoDriver.updateDocument(myDocument.getDocumentHandle(), myObject2); - } catch (ArangoException e) { - System.out.println("Failed to update document. " + e.getMessage()); - } - - // read document again - try { - myDocument = arangoDriver.getDocument(collectionName, "myKey", BaseDocument.class); - System.out.println("Key: " + myObject2.getDocumentKey()); - System.out.println("Attribute 'a': " + myObject2.getProperties().get("a")); - System.out.println("Attribute 'b': " + myObject2.getProperties().get("b")); - System.out.println("Attribute 'c': " + myObject2.getProperties().get("c")); - } catch (ArangoException e) { - System.out.println("Failed to get document. " + e.getMessage()); - } - - // delete document - try { - arangoDriver.deleteDocument(myDocument.getDocumentHandle()); - } catch (ArangoException e) { - System.out.println("Failed to delete document. " + e.getMessage()); - } - - // create some example entries - try { - for (Integer i = 0; i < 10; i++) { - BaseDocument baseDocument = new BaseDocument(); - baseDocument.setDocumentKey(i.toString()); - baseDocument.addAttribute("name", "Homer"); - baseDocument.addAttribute("b", i + 42); - arangoDriver.createDocument(collectionName, baseDocument); - } - } catch (ArangoException e) { - System.out.println("Failed to create document. " + e.getMessage()); - } - - // Get all documents with the name "Homer" from collection - // "firstCollection" and iterate over the result: - try { - String query = "FOR t IN firstCollection FILTER t.name == @name RETURN t"; - Map bindVars = new MapBuilder().put("name", "Homer").get(); - DocumentCursor cursor = arangoDriver.executeDocumentQuery(query, bindVars, null, - BaseDocument.class); - - Iterator iterator = cursor.entityIterator(); - while (iterator.hasNext()) { - BaseDocument aDocument = iterator.next(); - System.out.println("Key: " + aDocument.getDocumentKey()); - } - } catch (ArangoException e) { - System.out.println("Failed to execute query. " + e.getMessage()); - } - - // Now we will delete the document created before: - try { - String query = "FOR t IN firstCollection FILTER t.name == @name " - + "REMOVE t IN firstCollection LET removed = OLD RETURN removed"; - Map bindVars = new MapBuilder().put("name", "Homer").get(); - DocumentCursor cursor = arangoDriver.executeDocumentQuery(query, bindVars, null, - BaseDocument.class); - - Iterator iterator = cursor.entityIterator(); - while (iterator.hasNext()) { - BaseDocument aDocument = iterator.next(); - System.out.println("Removed document: " + aDocument.getDocumentKey()); - } - - } catch (ArangoException e) { - System.out.println("Failed to execute query. " + e.getMessage()); - } - } - -} +package com.arangodb.example; + +import java.util.Map; + +import com.arangodb.ArangoCollection; +import com.arangodb.ArangoCursor; +import com.arangodb.ArangoDB; +import com.arangodb.ArangoDBException; +import com.arangodb.entity.BaseDocument; +import com.arangodb.entity.CollectionEntity; +import com.arangodb.util.MapBuilder; +import com.arangodb.velocypack.VPackSlice; + +public class FirstProject { + + public static void main(final String[] args) { + final ArangoDB arangoDB = new ArangoDB.Builder().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/TransactionExample.java b/src/test/java/com/arangodb/example/TransactionExample.java deleted file mode 100644 index 8aa64b2a4..000000000 --- a/src/test/java/com/arangodb/example/TransactionExample.java +++ /dev/null @@ -1,252 +0,0 @@ -/* - * Copyright (C) 2012,2013 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.example; - -import java.util.ArrayList; -import java.util.List; - -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import com.arangodb.ArangoDriver; -import com.arangodb.ArangoException; -import com.arangodb.entity.DocumentEntity; -import com.arangodb.entity.TransactionEntity; -import com.arangodb.example.document.BaseExample; - -/** - * Using a server-side transaction function. - * - * see https://docs.arangodb.com/Transactions/TransactionInvocation.html - * - * @author a-brandt - */ -public class TransactionExample extends BaseExample { - - private static final String DATABASE_NAME = "TransactionExample"; - - private static final String COLLECTION_NAME = "transactionCollection"; - - // start 10 threads - private static final int NUMBER_THREADS = 10; - - // increment counter 10 times - private static final int NUMBER_UPDATES = 10; - - @Before - public void _before() { - removeTestDatabase(DATABASE_NAME); - - createDatabase(driver, DATABASE_NAME); - - try { - driver.createCollection(COLLECTION_NAME); - } catch (final Exception ex) { - } - } - - @After - public void _after() { - removeTestDatabase(DATABASE_NAME); - } - - @Test - public void transactionExample() throws ArangoException { - final List noTransactionThreadslist = new ArrayList(); - final List transactionThreadslist = new ArrayList(); - - final myCounter entity = new myCounter(); - entity.setCount(0L); - DocumentEntity documentEntity1 = driver.createDocument(COLLECTION_NAME, entity, null); - DocumentEntity documentEntity2 = driver.createDocument(COLLECTION_NAME, entity, null); - - // start threads without transaction - for (int i = 0; i < NUMBER_THREADS; i++) { - final NoTransactionThread s = new NoTransactionThread(documentEntity1.getDocumentHandle()); - noTransactionThreadslist.add(s); - s.start(); - } - joinThreads(noTransactionThreadslist); - - documentEntity1 = driver.getDocument(documentEntity1.getDocumentHandle(), myCounter.class); - - // result should be NUMBER_THREADS * NUMBER_UPDATES = 100 but has random - // values - System.out.println("no transaction result: count = " + documentEntity1.getEntity().getCount() + " != " - + NUMBER_THREADS * NUMBER_UPDATES); - Assert.assertTrue(documentEntity1.getEntity().getCount() != NUMBER_THREADS * NUMBER_UPDATES); - - // start threads with ArangoDB transaction - for (int i = 0; i < NUMBER_THREADS; i++) { - final TransactionThread s = new TransactionThread(documentEntity2.getDocumentHandle()); - transactionThreadslist.add(s); - s.start(); - } - joinThreads(transactionThreadslist); - - documentEntity2 = driver.getDocument(documentEntity2.getDocumentHandle(), myCounter.class); - - // result should be NUMBER_THREADS * NUMBER_UPDATES = 100 - System.out.println("with transaction result: count = " + documentEntity2.getEntity().getCount()); - Assert.assertEquals(NUMBER_THREADS * NUMBER_UPDATES, documentEntity2.getEntity().getCount().intValue()); - } - - /** - * Example without transaction function - * - */ - public static class NoTransactionThread extends Thread { - - private final String documentHandle; - - public NoTransactionThread(final String documentHandle) { - this.documentHandle = documentHandle; - } - - @Override - public void run() { - final ArangoDriver driver2 = new ArangoDriver(configure, DATABASE_NAME); - - try { - ; - for (int i = 0; i < NUMBER_UPDATES; i++) { - sleepRandom(); - // read counter - final DocumentEntity documentEntity = driver2.getDocument(documentHandle, - myCounter.class); - final myCounter entity = documentEntity.getEntity(); - // update counter - entity.setCount(entity.getCount() + 1); - sleepRandom(); - // save counter - driver2.replaceDocument(documentHandle, entity); - } - } catch (final ArangoException e) { - e.printStackTrace(); - } - } - } - - /** - * Example with transaction function - * - */ - public static class TransactionThread extends Thread { - - private final String documentHandle; - - public TransactionThread(final String documentHandle) { - this.documentHandle = documentHandle; - - } - - @Override - public void run() { - final ArangoDriver driver = new ArangoDriver(configure, DATABASE_NAME); - - final TransactionEntity transaction = buildTransaction(driver); - try { - ; - for (int i = 0; i < NUMBER_UPDATES; i++) { - sleepRandom(); - transaction.setParams(documentHandle); - // call transaction function - driver.executeTransaction(transaction); - } - } catch (final ArangoException e) { - e.printStackTrace(); - } - } - } - - /** - * A simple counter class - */ - public static class myCounter { - private Long count; - - public Long getCount() { - return count; - } - - public void setCount(final Long count) { - this.count = count; - } - } - - public static void joinThreads(final List threads) { - for (final T st : threads) { - try { - st.join(); - } catch (final Exception ex) { - } - } - } - - private static void sleepRandom() { - try { - Thread.sleep((long) (Math.random() * 1000L)); - } catch (final Exception ex) { - } - - } - - /** - * Build the server side function to update a value transactional. - * - * @param driver - * the ArangoDB driver - * @return a transaction entity - */ - private static TransactionEntity buildTransaction(final ArangoDriver driver) { - - // create action function - final String action = "function (id) {" - // use internal database functions - + " var db = require('internal').db;" - // get the document - + "a = db._document(id); " - // update the counter - + "a.count = a.count + 1; " - // store the new value - + "db._replace(id, a);}"; - - final TransactionEntity transaction = driver.createTransaction(action); - - transaction.addWriteCollection(COLLECTION_NAME); - - return transaction; - } - - /** - * Get the counter value - * - * @param driver - * the database driver - * @param documentHandle - * the document identifier of the counter - * @return the current value - * @throws ArangoException - */ - public static Long getCount(final ArangoDriver driver, final String documentHandle) throws ArangoException { - final DocumentEntity documentEntity = driver.getDocument(documentHandle, myCounter.class); - return documentEntity.getEntity().getCount(); - } - -} diff --git a/src/test/java/com/arangodb/example/document/AqlQueryWithSpecialReturnTypesExample.java b/src/test/java/com/arangodb/example/document/AqlQueryWithSpecialReturnTypesExample.java index 74768d826..8826580df 100644 --- a/src/test/java/com/arangodb/example/document/AqlQueryWithSpecialReturnTypesExample.java +++ b/src/test/java/com/arangodb/example/document/AqlQueryWithSpecialReturnTypesExample.java @@ -1,147 +1,140 @@ -/* - * Copyright (C) 2015 ArangoDB GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.example.document; - -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import com.arangodb.ArangoException; -import com.arangodb.CursorResult; -import com.arangodb.util.AqlQueryOptions; - -public class AqlQueryWithSpecialReturnTypesExample extends BaseExample { - - private static final String DATABASE_NAME = "SimplePersonAqlQueryWithLimitExample"; - private static final String COLLECTION_NAME = "SimplePersonAqlQueryWithLimitExample"; - - @Before - public void _before() { - removeTestDatabase(DATABASE_NAME); - - createDatabase(driver, DATABASE_NAME); - createCollection(driver, COLLECTION_NAME); - } - - @After - public void _after() { - removeTestDatabase(DATABASE_NAME); - } - - @Test - public void simplePersonAqlWithLimitQuery() { - // - // You can find the ArangoDB Web interface here: - // http://127.0.0.1:8529/ - // - // change the log level to "debug" in /src/test/resource/logback.xml to - // see the HTTP communication - - try { - // - printHeadline("create example documents"); - // - createExamples(); - - // - printHeadline("build query"); - // - - // bind @gender to WOMAN - final HashMap bindVars = new HashMap(); - bindVars.put("gender", FEMALE); - - // query (count = true, batchSize = 5) - final AqlQueryOptions aqlQueryOptions = new AqlQueryOptions().setCount(true).setBatchSize(5); - - // - printHeadline("get query results in a map"); - // - - String queryString = "FOR t IN " + COLLECTION_NAME - + " FILTER t.age >= 20 && t.age < 30 && t.gender == @gender RETURN t"; - System.out.println(queryString); - - @SuppressWarnings("rawtypes") - final CursorResult cursor = driver.executeAqlQuery(queryString, bindVars, aqlQueryOptions, Map.class); - Assert.assertNotNull(cursor); - - @SuppressWarnings("rawtypes") - final Iterator iterator = cursor.iterator(); - while (iterator.hasNext()) { - final Map map = iterator.next(); - - Assert.assertNotNull(map); - Assert.assertNotNull(map.get("name")); - Assert.assertNotNull(map.get("gender")); - Assert.assertNotNull(map.get("age")); - - System.out.printf("%15s (%5s): %s%n", map.get("name"), map.get("gender"), map.get("age").toString()); - } - - // - printHeadline("get query results in a list"); - // - - queryString = "FOR t IN " + COLLECTION_NAME - + " FILTER t.age >= 20 && t.age < 30 && t.gender == @gender RETURN [t.name, t.gender, t.age]"; - System.out.println(queryString); - - @SuppressWarnings("rawtypes") - final CursorResult cursor2 = driver.executeAqlQuery(queryString, bindVars, aqlQueryOptions, - List.class); - Assert.assertNotNull(cursor2); - - @SuppressWarnings("rawtypes") - final Iterator iterator2 = cursor2.iterator(); - while (iterator2.hasNext()) { - final List list = iterator2.next(); - - Assert.assertNotNull(list); - Assert.assertNotNull(list.get(0)); - Assert.assertNotNull(list.get(1)); - Assert.assertNotNull(list.get(2)); - - System.out.printf("%15s (%5s): %s%n", list.get(0), list.get(1), list.get(2).toString()); - } - - } catch (final ArangoException e) { - Assert.fail("Example failed. " + e.getMessage()); - } - - } - - private void createExamples() throws ArangoException { - // create some persons - for (int i = 0; i < 100; i++) { - final SimplePerson person = new SimplePerson(); - person.setName("TestUser" + i); - person.setGender((i % 2) == 0 ? MALE : FEMALE); - person.setAge((int) (Math.random() * 100) + 10); - - driver.createDocument(COLLECTION_NAME, person, null); - } - - } - -} +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.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 com.arangodb.velocypack.exception.VPackException; + +/** + * @author Mark - mark at arangodb.com + * + */ +public class AqlQueryWithSpecialReturnTypesExample extends ExampleBase { + + @BeforeClass + public static void before() { + createExamples(); + } + + public enum Gender { + MALE, FEMALE + } + + private static void createExamples() { + for (int i = 0; i < 100; i++) { + final BaseDocument value = new BaseDocument(); + value.addAttribute("name", "TestUser" + i); + value.addAttribute("gender", (i % 2) == 0 ? Gender.MALE : Gender.FEMALE); + value.addAttribute("age", i + 10); + db.collection(COLLECTION_NAME).insertDocument(value); + } + } + + @Test + public void aqlWithLimitQueryAsVPackObject() { + final String query = "FOR t IN " + COLLECTION_NAME + + " FILTER t.age >= 20 && t.age < 30 && t.gender == @gender RETURN t"; + final Map bindVars = new MapBuilder().put("gender", Gender.FEMALE).get(); + final ArangoCursor cursor = db.query(query, bindVars, null, VPackSlice.class); + assertThat(cursor, is(notNullValue())); + for (; cursor.hasNext();) { + final VPackSlice vpack = cursor.next(); + try { + assertThat(vpack.get("name").getAsString(), + isOneOf("TestUser11", "TestUser13", "TestUser15", "TestUser17", "TestUser19")); + assertThat(vpack.get("gender").getAsString(), is(Gender.FEMALE.name())); + assertThat(vpack.get("age").getAsInt(), isOneOf(21, 23, 25, 27, 29)); + } catch (final VPackException e) { + } + } + } + + @Test + public void aqlWithLimitQueryAsVPackArray() { + final String query = "FOR t IN " + COLLECTION_NAME + + " FILTER t.age >= 20 && t.age < 30 && t.gender == @gender RETURN [t.name, t.gender, t.age]"; + final Map bindVars = new MapBuilder().put("gender", Gender.FEMALE).get(); + final ArangoCursor cursor = db.query(query, bindVars, null, VPackSlice.class); + assertThat(cursor, is(notNullValue())); + for (; cursor.hasNext();) { + final VPackSlice vpack = cursor.next(); + assertThat(vpack.get(0).getAsString(), + isOneOf("TestUser11", "TestUser13", "TestUser15", "TestUser17", "TestUser19")); + assertThat(vpack.get(1).getAsString(), is(Gender.FEMALE.name())); + assertThat(vpack.get(2).getAsInt(), isOneOf(21, 23, 25, 27, 29)); + } + } + + @Test + @SuppressWarnings("rawtypes") + public void aqlWithLimitQueryAsMap() { + final String query = "FOR t IN " + COLLECTION_NAME + + " FILTER t.age >= 20 && t.age < 30 && t.gender == @gender RETURN t"; + final Map bindVars = new MapBuilder().put("gender", Gender.FEMALE).get(); + final ArangoCursor cursor = db.query(query, bindVars, null, Map.class); + assertThat(cursor, is(notNullValue())); + for (; cursor.hasNext();) { + final Map map = cursor.next(); + assertThat(map.get("name"), is(notNullValue())); + assertThat(String.valueOf(map.get("name")), + isOneOf("TestUser11", "TestUser13", "TestUser15", "TestUser17", "TestUser19")); + assertThat(map.get("gender"), is(notNullValue())); + assertThat(String.valueOf(map.get("gender")), is(Gender.FEMALE.name())); + assertThat(map.get("age"), is(notNullValue())); + assertThat(Long.valueOf(map.get("age").toString()), isOneOf(21L, 23L, 25L, 27L, 29L)); + } + } + + @Test + @SuppressWarnings("rawtypes") + public void aqlWithLimitQueryAsList() { + final String query = "FOR t IN " + COLLECTION_NAME + + " FILTER t.age >= 20 && t.age < 30 && t.gender == @gender RETURN [t.name, t.gender, t.age]"; + final Map bindVars = new MapBuilder().put("gender", Gender.FEMALE).get(); + final ArangoCursor cursor = db.query(query, bindVars, null, List.class); + assertThat(cursor, is(notNullValue())); + for (; cursor.hasNext();) { + final List list = cursor.next(); + assertThat(list.get(0), is(notNullValue())); + assertThat(String.valueOf(list.get(0)), + isOneOf("TestUser11", "TestUser13", "TestUser15", "TestUser17", "TestUser19")); + assertThat(list.get(1), is(notNullValue())); + assertThat(Gender.valueOf(String.valueOf(list.get(1))), is(Gender.FEMALE)); + assertThat(list.get(2), is(notNullValue())); + assertThat(Long.valueOf(String.valueOf(list.get(2))), isOneOf(21L, 23L, 25L, 27L, 29L)); + } + } +} diff --git a/src/test/java/com/arangodb/example/document/BaseExample.java b/src/test/java/com/arangodb/example/document/BaseExample.java deleted file mode 100644 index 94a288982..000000000 --- a/src/test/java/com/arangodb/example/document/BaseExample.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Copyright (C) 2015 ArangoDB GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.example.document; - -import org.junit.Assert; - -import com.arangodb.ArangoDriver; -import com.arangodb.ArangoException; -import com.arangodb.BaseTest; -import com.arangodb.entity.BooleanResultEntity; -import com.arangodb.entity.CollectionEntity; - -public class BaseExample extends BaseTest { - - protected static final String FEMALE = "female"; - protected static final String MALE = "male"; - - protected void removeTestDatabase(final String name) { - try { - driver.deleteDatabase(name); - } catch (final Exception e) { - } - } - - protected void createDatabase(final ArangoDriver arangoDriver, final String name) { - try { - final BooleanResultEntity createDatabase = arangoDriver.createDatabase(name); - Assert.assertNotNull(createDatabase); - Assert.assertNotNull(createDatabase.getResult()); - Assert.assertTrue(createDatabase.getResult()); - } catch (final Exception e) { - Assert.fail("Failed to create database " + name + "; " + e.getMessage()); - } - - arangoDriver.setDefaultDatabase(name); - } - - protected void deleteDatabase(final ArangoDriver arangoDriver, final String name) { - try { - arangoDriver.deleteDatabase(name); - } catch (final Exception e) { - } - } - - protected void createCollection(final ArangoDriver arangoDriver, final String name) { - try { - final CollectionEntity createCollection = arangoDriver.createCollection(name); - Assert.assertNotNull(createCollection); - Assert.assertNotNull(createCollection.getName()); - Assert.assertEquals(name, createCollection.getName()); - } catch (final ArangoException e) { - Assert.fail("create collection failed. " + e.getMessage()); - } - } - - protected void printEntity(final Object object) { - if (object == null) { - System.out.println("Document not found"); - } else { - System.out.println(object); - } - } - - protected void printHeadline(final String name) { - System.out.println("---------------------------------------------"); - System.out.println(name); - System.out.println("---------------------------------------------"); - } - -} diff --git a/src/test/java/com/arangodb/example/document/CollectionExample.java b/src/test/java/com/arangodb/example/document/CollectionExample.java deleted file mode 100644 index 6810bf1e4..000000000 --- a/src/test/java/com/arangodb/example/document/CollectionExample.java +++ /dev/null @@ -1,165 +0,0 @@ -/* - * Copyright (C) 2015 ArangoDB GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.example.document; - -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import com.arangodb.ArangoException; -import com.arangodb.entity.CollectionEntity; -import com.arangodb.entity.CollectionsEntity; - -public class CollectionExample extends BaseExample { - - private static final String DATABASE_NAME = "CreateCollectionExample"; - - @Before - public void _before() { - removeTestDatabase(DATABASE_NAME); - - createDatabase(driver, DATABASE_NAME); - } - - @After - public void _after() { - removeTestDatabase(DATABASE_NAME); - } - - @Test - public void createAndDeleteCollection() { - - String myFirstCollection = "collection1"; - long myFirstCollectionId = 0L; - - // - printHeadline("create a collection"); - // - try { - final CollectionEntity entity = driver.createCollection(myFirstCollection); - Assert.assertNotNull(entity); - Assert.assertNotNull(entity.getName()); - Assert.assertEquals(myFirstCollection, entity.getName()); - Assert.assertTrue(entity.getId() != 0L); - myFirstCollectionId = entity.getId(); - - printCollectionEntity(entity); - // System.out.println(entity); - } catch (final ArangoException e) { - Assert.fail("create collection failed. " + e.getMessage()); - } - - createCollection(driver, "collection2"); - createCollection(driver, "collection3"); - - // - printHeadline("get list of all collections"); - // - try { - final CollectionsEntity collectionsEntity = driver.getCollections(); - Assert.assertNotNull(collectionsEntity); - Assert.assertNotNull(collectionsEntity.getCollections()); - - for (final CollectionEntity entity : collectionsEntity.getCollections()) { - printCollectionEntity(entity); - // System.out.println(entity); - } - - } catch (final ArangoException e) { - Assert.fail("could not get collections. " + e.getMessage()); - } - - // - printHeadline("get one collection"); - // - try { - final CollectionEntity entity = driver.getCollection(myFirstCollection); - Assert.assertNotNull(entity); - Assert.assertNotNull(entity.getName()); - Assert.assertNotNull(entity.getId()); - - printCollectionEntity(entity); - // System.out.println(entity); - } catch (final ArangoException e) { - Assert.fail("could not get collection. " + e.getMessage()); - } - - // - printHeadline("rename collection"); - // - try { - final CollectionEntity entity = driver.renameCollection(myFirstCollection, "collection4"); - Assert.assertNotNull(entity); - Assert.assertNotNull(entity.getName()); - Assert.assertNotNull(entity.getId()); - Assert.assertEquals(myFirstCollectionId, entity.getId()); - myFirstCollection = entity.getName(); - - printCollectionEntity(entity); - // System.out.println(entity); - } catch (final ArangoException e) { - Assert.fail("could not rename collection. " + e.getMessage()); - } - - // - printHeadline("truncate collection"); - // - try { - final CollectionEntity truncateCollection = driver.truncateCollection(myFirstCollection); - Assert.assertNotNull(truncateCollection); - Assert.assertNotNull(truncateCollection.getName()); - Assert.assertNotNull(truncateCollection.getId()); - Assert.assertEquals(myFirstCollectionId, truncateCollection.getId()); - - } catch (final ArangoException e) { - Assert.fail("could not truncate collection. " + e.getMessage()); - } - - // - printHeadline("delete collection"); - // - try { - final CollectionEntity entity = driver.deleteCollection(myFirstCollection); - Assert.assertNotNull(entity); - // the name has to be null - Assert.assertNull(entity.getName()); - Assert.assertNotNull(entity.getId()); - Assert.assertEquals(myFirstCollectionId, entity.getId()); - - printCollectionEntity(entity); - // System.out.println(entity); - } catch (final ArangoException e) { - Assert.fail("could not delete collection. " + e.getMessage()); - } - - } - - private void printCollectionEntity(final CollectionEntity collection) { - if (collection == null) { - System.out.println("Collection not found"); - } else if (collection.getName() == null) { - // collection is deleted - System.out.println("Collection '" + collection.getName() + "' with id '" + collection.getId() + "'"); - } else { - System.out.println( - "Collection '" + collection.getName() + "' (" + (collection.getIsSystem() ? "system" : "normal") - + " collection) with id '" + collection.getId() + "'"); - } - } - -} diff --git a/src/test/java/com/arangodb/example/document/CreateAndDeleteDatabaseExample.java b/src/test/java/com/arangodb/example/document/CreateAndDeleteDatabaseExample.java deleted file mode 100644 index c28cab71c..000000000 --- a/src/test/java/com/arangodb/example/document/CreateAndDeleteDatabaseExample.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Copyright (C) 2015 ArangoDB GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.example.document; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import com.arangodb.ArangoConfigure; -import com.arangodb.ArangoDriver; -import com.arangodb.ArangoException; -import com.arangodb.entity.BooleanResultEntity; -import com.arangodb.entity.StringsResultEntity; - -public class CreateAndDeleteDatabaseExample extends BaseExample { - - private static final String DATABASE_NAME = "CreateDatabaseExample"; - - @Before - public void _before() { - removeTestDatabase(DATABASE_NAME); - } - - @Test - public void createAndDeleteDatabase() { - // - // You can find the ArangoDB Web interface here: - // http://127.0.0.1:8529/ - // - // change the log level to "debug" in /src/test/resource/logback.xml to - // see the HTTP communication - - // - printHeadline("create a driver"); - // - printHeadline("create a database"); - // - try { - final BooleanResultEntity createDatabase = driver.createDatabase(DATABASE_NAME); - Assert.assertNotNull(createDatabase); - Assert.assertNotNull(createDatabase.getResult()); - Assert.assertTrue(createDatabase.getResult()); - - System.out.println("Database created: " + DATABASE_NAME); - } catch (final ArangoException e) { - Assert.fail("Failed to create database " + DATABASE_NAME + "; " + e.getMessage()); - } - // set a default database for the connection - driver.setDefaultDatabase(DATABASE_NAME); - - // do something ... - - // - printHeadline("read names of all databases"); - // - try { - final StringsResultEntity databases = driver.getDatabases(); - Assert.assertNotNull(databases); - Assert.assertNotNull(databases.getResult()); - Assert.assertTrue(databases.getResult().size() > 0); - - for (final String str : databases.getResult()) { - System.out.println("Database: " + str); - } - - } catch (final ArangoException e) { - Assert.fail("Failed to read databases. " + e.getMessage()); - } - - // - printHeadline("create a driver with default database"); - // - final ArangoConfigure configure2 = new ArangoConfigure(); - configure2.init(); - final ArangoDriver arangoDriver2 = new ArangoDriver(configure2, DATABASE_NAME); - Assert.assertNotNull(arangoDriver2); - - // do something ... - - // - printHeadline("delete database"); - // - try { - final BooleanResultEntity deleteDatabase = driver.deleteDatabase(DATABASE_NAME); - Assert.assertNotNull(deleteDatabase); - Assert.assertNotNull(deleteDatabase.getResult()); - Assert.assertTrue(deleteDatabase.getResult()); - } catch (final ArangoException e) { - Assert.fail("Failed to delete database " + DATABASE_NAME + "; " + e.getMessage()); - } - - } -} diff --git a/src/test/java/com/arangodb/example/document/CreateDocumentExample.java b/src/test/java/com/arangodb/example/document/CreateDocumentExample.java deleted file mode 100644 index 1289760ac..000000000 --- a/src/test/java/com/arangodb/example/document/CreateDocumentExample.java +++ /dev/null @@ -1,210 +0,0 @@ -/* - * Copyright (C) 2015 ArangoDB GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.example.document; - -import java.util.HashMap; - -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import com.arangodb.ArangoException; -import com.arangodb.entity.BaseDocument; -import com.arangodb.entity.DocumentEntity; - -public class CreateDocumentExample extends BaseExample { - - private static final String DATABASE_NAME = "CreateDocument"; - - private static final String COLLECTION_NAME = "CreateDocument"; - - private static final String KEY1 = "key1"; - - private static final String KEY2 = "key2"; - - private static final String KEY3 = "key3"; - - private static final String KEY4 = "key4"; - - @Before - public void _before() { - removeTestDatabase(DATABASE_NAME); - - createDatabase(driver, DATABASE_NAME); - createCollection(driver, COLLECTION_NAME); - } - - @After - public void _after() { - removeTestDatabase(DATABASE_NAME); - } - - @Test - public void createAndDeleteDocuments() { - // - // You can find the ArangoDB Web interface here: - // http://127.0.0.1:8529/ - // - // change the log level to "debug" in /src/test/resource/logback.xml to - // see the HTTP communication - - // - printHeadline("create documents"); - // - - System.out.println("1. create a document by a BaseDocument object:"); - final BaseDocument myBaseDocument = new BaseDocument(); - myBaseDocument.setDocumentKey(KEY1); - // attributes are stored in a HashMap - myBaseDocument.addAttribute("name", "Alice"); - myBaseDocument.addAttribute("gender", "female"); - myBaseDocument.addAttribute("age", 18); - - try { - final DocumentEntity entity = driver.createDocument(COLLECTION_NAME, myBaseDocument); - // or DocumentEntity entity = - // arangoDriver.createDocument(COLLECTION_NAME, KEY1, - // myBaseDocument); - - Assert.assertNotNull(entity); - Assert.assertNotNull(entity.getDocumentKey()); - Assert.assertNotNull(entity.getDocumentHandle()); - Assert.assertNotNull(entity.getDocumentRevision()); - Assert.assertNotNull(entity.getEntity()); - - // the DocumentEntity contains the key, document handle and revision - System.out.println("Key: " + entity.getDocumentKey()); - System.out.println("Id: " + entity.getDocumentHandle()); - System.out.println("Revision: " + entity.getDocumentRevision()); - - final BaseDocument baseDocument = entity.getEntity(); - // the BaseDocument contains the key, document handle and revision - System.out.println("Key: " + baseDocument.getDocumentKey()); - System.out.println("Id: " + baseDocument.getDocumentHandle()); - System.out.println("Revision: " + baseDocument.getDocumentRevision()); - // get the attributes - System.out.println("Attribute 'name': " + baseDocument.getProperties().get("name")); - System.out.println("Attribute 'gender': " + baseDocument.getProperties().get("gender")); - System.out.println("Attribute 'age': " + baseDocument.getProperties().get("age")); - - // printEntity(entity); - } catch (final ArangoException e) { - Assert.fail("Failed to create document. " + e.getMessage()); - } - - System.out.println("2. create a document by a HashMap object:"); - final HashMap myHashMap = new HashMap(); - myHashMap.put("_key", KEY2); - // attributes are stored in a HashMap - myHashMap.put("name", "Alice"); - myHashMap.put("gender", "female"); - myHashMap.put("age", 18); - - try { - final DocumentEntity> entity = driver.createDocument(COLLECTION_NAME, myHashMap); - // or DocumentEntity> entity = - // arangoDriver.createDocument(COLLECTION_NAME, KEY2, myHashMap); - - Assert.assertNotNull(entity); - Assert.assertNotNull(entity.getDocumentKey()); - Assert.assertNotNull(entity.getDocumentHandle()); - Assert.assertNotNull(entity.getDocumentRevision()); - Assert.assertNotNull(entity.getEntity()); - - // the DocumentEntity contains the key, document handle and revision - System.out.println("Key: " + entity.getDocumentKey()); - System.out.println("Id: " + entity.getDocumentHandle()); - System.out.println("Revision: " + entity.getDocumentRevision()); - - final HashMap hashMap = entity.getEntity(); - // the HashMap contains the key, document handle and revision - System.out.println("Key: " + hashMap.get("_key")); - System.out.println("Id: " + hashMap.get("_id")); - System.out.println("Revision: " + hashMap.get("_rev")); - // get the attributes - System.out.println("Attribute 'name': " + hashMap.get("name")); - System.out.println("Attribute 'gender': " + hashMap.get("gender")); - System.out.println("Attribute 'age': " + hashMap.get("age")); - - // printEntity(entity); - } catch (final ArangoException e) { - Assert.fail("Failed to create document. " + e.getMessage()); - } - - System.out.println("3. create a document by an object:"); - final SimplePerson mySimplePerson = new SimplePerson("Angela", "female", 42); - try { - final DocumentEntity entity = driver.createDocument(COLLECTION_NAME, KEY3, mySimplePerson); - - Assert.assertNotNull(entity); - Assert.assertNotNull(entity.getDocumentKey()); - Assert.assertNotNull(entity.getDocumentHandle()); - Assert.assertNotNull(entity.getDocumentRevision()); - Assert.assertNotNull(entity.getEntity()); - - // the DocumentEntity contains the key, document handle and revision - System.out.println("Key: " + entity.getDocumentKey()); - System.out.println("Id: " + entity.getDocumentHandle()); - System.out.println("Revision: " + entity.getDocumentRevision()); - - final SimplePerson simplePerson = entity.getEntity(); - // get the attributes - System.out.println("Attribute 'name': " + simplePerson.getName()); - System.out.println("Attribute 'gender': " + simplePerson.getGender()); - System.out.println("Attribute 'age': " + simplePerson.getAge()); - - // printEntity(entity); - } catch (final ArangoException e) { - Assert.fail("Failed to create document. " + e.getMessage()); - } - - System.out.println("4. create a document by an object with document attributes:"); - final DocumentPerson myDocumentPerson = new DocumentPerson("Peter", "male", 24); - try { - final DocumentEntity entity = driver.createDocument(COLLECTION_NAME, KEY4, - myDocumentPerson); - - Assert.assertNotNull(entity); - Assert.assertNotNull(entity.getDocumentKey()); - Assert.assertNotNull(entity.getDocumentHandle()); - Assert.assertNotNull(entity.getDocumentRevision()); - Assert.assertNotNull(entity.getEntity()); - - // the DocumentEntity contains the key, document handle and revision - System.out.println("Key: " + entity.getDocumentKey()); - System.out.println("Id: " + entity.getDocumentHandle()); - System.out.println("Revision: " + entity.getDocumentRevision()); - - final DocumentPerson documentPerson = entity.getEntity(); - // the DocumentPerson contains the key, document handle and revision - System.out.println("Key: " + documentPerson.getDocumentKey()); - System.out.println("Id: " + documentPerson.getDocumentHandle()); - System.out.println("Revision: " + documentPerson.getDocumentRevision()); - // get the attributes - System.out.println("Attribute 'name': " + documentPerson.getName()); - System.out.println("Attribute 'gender': " + documentPerson.getGender()); - System.out.println("Attribute 'age': " + documentPerson.getAge()); - - // printEntity(entity); - } catch (final ArangoException e) { - Assert.fail("Failed to create document. " + e.getMessage()); - } - - } - -} diff --git a/src/test/java/com/arangodb/example/document/DocumentExamplesTestSuite.java b/src/test/java/com/arangodb/example/document/DocumentExamplesTestSuite.java deleted file mode 100644 index 3ba68efad..000000000 --- a/src/test/java/com/arangodb/example/document/DocumentExamplesTestSuite.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (C) 2015 ArangoDB GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.example.document; - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; -import org.junit.runners.Suite.SuiteClasses; - -/** - * Starts all unit tests - * - * @author a-brandt - * - */ -@RunWith(Suite.class) -@SuiteClasses({ - - CreateAndDeleteDatabaseExample.class, - - CollectionExample.class, - - CreateDocumentExample.class, - - ReadDocumentExample.class, - - ReplaceAndUpdateDocumentExample.class, - - SimplePersonAqlQueryExample.class, - - DocumentPersonAqlQueryExample.class, - - SimplePersonAqlQueryWithLimitExample.class, - - AqlQueryWithSpecialReturnTypesExample.class, - - RawDocumentExample.class }) - -public class DocumentExamplesTestSuite { - -} diff --git a/src/test/java/com/arangodb/example/document/DocumentPerson.java b/src/test/java/com/arangodb/example/document/DocumentPerson.java deleted file mode 100644 index 6850a0e50..000000000 --- a/src/test/java/com/arangodb/example/document/DocumentPerson.java +++ /dev/null @@ -1,106 +0,0 @@ -/* - * Copyright (C) 2015 ArangoDB GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.example.document; - -import com.arangodb.entity.BaseDocument; -import com.google.gson.annotations.SerializedName; - -/** - * A person class. - * - * The document person class has attributes to store the document key, id and - * revision. - * - * @author a-brandt - * - */ -public class DocumentPerson { - - @SerializedName(BaseDocument.ID) - private String documentHandle; - - @SerializedName(BaseDocument.KEY) - private String documentKey; - - @SerializedName(BaseDocument.REV) - private String documentRevision; - - private String name; - - private String gender; - - private Integer age; - - public DocumentPerson() { - - } - - public DocumentPerson(final String name, final String gender, final Integer age) { - this.name = name; - this.gender = gender; - this.age = age; - } - - public String getName() { - return name; - } - - public void setName(final String name) { - this.name = name; - } - - public String getGender() { - return gender; - } - - public void setGender(final String gender) { - this.gender = gender; - } - - public Integer getAge() { - return age; - } - - public void setAge(final Integer age) { - this.age = age; - } - - public String getDocumentHandle() { - return documentHandle; - } - - public void setDocumentHandle(final String documentHandle) { - this.documentHandle = documentHandle; - } - - public String getDocumentKey() { - return documentKey; - } - - public void setDocumentKey(final String documentKey) { - this.documentKey = documentKey; - } - - public String getDocumentRevision() { - return documentRevision; - } - - public void setDocumentRevision(final String documentRevision) { - this.documentRevision = documentRevision; - } - -} diff --git a/src/test/java/com/arangodb/example/document/DocumentPersonAqlQueryExample.java b/src/test/java/com/arangodb/example/document/DocumentPersonAqlQueryExample.java deleted file mode 100644 index 97d3d8d62..000000000 --- a/src/test/java/com/arangodb/example/document/DocumentPersonAqlQueryExample.java +++ /dev/null @@ -1,132 +0,0 @@ -/* - * Copyright (C) 2015 ArangoDB GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.example.document; - -import java.util.HashMap; -import java.util.Iterator; - -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import com.arangodb.ArangoException; -import com.arangodb.DocumentCursor; -import com.arangodb.util.AqlQueryOptions; - -public class DocumentPersonAqlQueryExample extends BaseExample { - - private static final String DATABASE_NAME = "DocumentPersonAqlQueryExample"; - private static final String COLLECTION_NAME = "DocumentPersonAqlQueryExample"; - - @Before - public void _before() { - removeTestDatabase(DATABASE_NAME); - - createDatabase(driver, DATABASE_NAME); - createCollection(driver, COLLECTION_NAME); - } - - @After - public void _after() { - removeTestDatabase(DATABASE_NAME); - } - - @Test - public void documentPersonAqlQuery() { - // - // You can find the ArangoDB Web interface here: - // http://127.0.0.1:8529/ - // - // change the log level to "debug" in /src/test/resource/logback.xml to - // see the HTTP communication - - try { - // - printHeadline("create example documents"); - // - createExamples(); - - // - printHeadline("build query"); - // - - // build an AQL query string - final String queryString = "FOR t IN " + COLLECTION_NAME - + " FILTER t.age >= 20 && t.age < 30 && t.gender == @gender RETURN t"; - System.out.println(queryString); - - // bind @gender to female - final HashMap bindVars = new HashMap(); - bindVars.put("gender", FEMALE); - - // query (count = true, batchSize = 5) - final AqlQueryOptions aqlQueryOptions = new AqlQueryOptions().setCount(true).setBatchSize(5); - - // - printHeadline("execute query"); - // - - final DocumentCursor rs = driver.executeDocumentQuery(queryString, bindVars, - aqlQueryOptions, DocumentPerson.class); - Assert.assertNotNull(rs); - - // - printHeadline("get number of results"); - // - - // get total number of results - System.out.println(rs.getCount()); - - // - printHeadline("print results"); - // - - // using the entity iterator - final Iterator iterator = rs.entityIterator(); - while (iterator.hasNext()) { - final DocumentPerson person = iterator.next(); - - Assert.assertNotNull(person); - Assert.assertNotNull(person.getDocumentKey()); - Assert.assertNotNull(person.getDocumentHandle()); - Assert.assertNotNull(person.getDocumentRevision()); - - System.out.printf("%20s %15s(%5s): %d%n", person.getDocumentKey(), person.getName(), - person.getGender(), person.getAge()); - } - - } catch (final ArangoException e) { - Assert.fail("Example failed. " + e.getMessage()); - } - - } - - private void createExamples() throws ArangoException { - // create some persons - for (int i = 0; i < 1000; i++) { - final DocumentPerson person = new DocumentPerson(); - person.setName("TestUser" + i); - person.setGender((i % 2) == 0 ? MALE : FEMALE); - person.setAge((int) (Math.random() * 100) + 10); - - driver.createDocument(COLLECTION_NAME, person, null); - } - - } - -} diff --git a/src/test/java/com/arangodb/example/document/GetDocumentExample.java b/src/test/java/com/arangodb/example/document/GetDocumentExample.java new file mode 100644 index 000000000..4be732a4c --- /dev/null +++ b/src/test/java/com/arangodb/example/document/GetDocumentExample.java @@ -0,0 +1,83 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.example.document; + +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.junit.Assert.assertThat; + +import org.json.simple.parser.ParseException; +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; + +/** + * @author Mark - mark at arangodb.com + * + */ +public class GetDocumentExample extends ExampleBase { + + 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(); + } + + @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 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() throws ParseException { + 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 new file mode 100644 index 000000000..7f8291e98 --- /dev/null +++ b/src/test/java/com/arangodb/example/document/InsertDocumentExample.java @@ -0,0 +1,70 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.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; + +/** + * @author Mark - mark at arangodb.com + * + */ +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 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 insertJson() { + final DocumentCreateEntity doc = collection.insertDocument("{\"foo\":\"bar\"}"); + assertThat(doc.getKey(), is(notNullValue())); + } + +} diff --git a/src/test/java/com/arangodb/example/document/RawDocumentExample.java b/src/test/java/com/arangodb/example/document/RawDocumentExample.java deleted file mode 100644 index f7491f1b5..000000000 --- a/src/test/java/com/arangodb/example/document/RawDocumentExample.java +++ /dev/null @@ -1,217 +0,0 @@ -/* - * Copyright (C) 2015 ArangoDB GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.example.document; - -import java.util.HashMap; -import java.util.Iterator; - -import org.json.JSONML; -import org.json.JSONObject; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import com.arangodb.ArangoException; -import com.arangodb.CursorRawResult; -import com.arangodb.ErrorNums; -import com.arangodb.entity.DocumentEntity; - -public class RawDocumentExample extends BaseExample { - - private static final String DATABASE_NAME = "RawDocument"; - private static final String COLLECTION_NAME = "RawDocument"; - - @Before - public void _before() { - removeTestDatabase(DATABASE_NAME); - - createDatabase(driver, DATABASE_NAME); - createCollection(driver, COLLECTION_NAME); - } - - @After - public void _after() { - removeTestDatabase(DATABASE_NAME); - } - - @Test - public void ReadDocuments() { - // - // You can find the ArangoDB Web interface here: - // http://127.0.0.1:8529/ - // - // change the log level to "debug" in /src/test/resource/logback.xml to - // see the HTTP communication - - // - printHeadline("create example document 1"); - // - - String documentHandle1 = null; - String documentHandle2 = null; - String documentHandle3 = null; - - String x = "{\"test\":123}"; - try { - final DocumentEntity entity = driver.createDocumentRaw(COLLECTION_NAME, x, false); - // the DocumentEntity contains the key, document handle and revision - System.out.println("Key: " + entity.getDocumentKey()); - System.out.println("Id: " + entity.getDocumentHandle()); - System.out.println("Revision: " + entity.getDocumentRevision()); - documentHandle1 = entity.getDocumentHandle(); - } catch (final ArangoException e) { - Assert.fail("Failed to create document. " + e.getMessage()); - } - - // - printHeadline("read example document 1"); - // - - try { - final String str = driver.getDocumentRaw(documentHandle1, null, null); - System.out.println("value: " + str); - } catch (final ArangoException e) { - Assert.fail("Failed to read document. " + e.getMessage()); - } - - // - printHeadline("create example document 2 with key"); - // - - x = "{\"_key\":\"key2\",\"test\":123}"; - try { - final DocumentEntity entity = driver.createDocumentRaw(COLLECTION_NAME, x, false); - // the DocumentEntity contains the key, document handle and revision - System.out.println("Key: " + entity.getDocumentKey()); - System.out.println("Id: " + entity.getDocumentHandle()); - System.out.println("Revision: " + entity.getDocumentRevision()); - documentHandle2 = entity.getDocumentHandle(); - } catch (final ArangoException e) { - Assert.fail("Failed to create document. " + e.getMessage()); - } - - // - printHeadline("read example document 2"); - // - - try { - final String str = driver.getDocumentRaw(documentHandle2, null, null); - System.out.println("value: " + str); - } catch (final ArangoException e) { - Assert.fail("Failed to read document. " + e.getMessage()); - } - - // - printHeadline("read wrong document"); - // - - try { - driver.getDocumentRaw(COLLECTION_NAME + "/unknown", null, null); - Assert.fail("This should fail"); - } catch (final ArangoException e) { - Assert.assertEquals(ErrorNums.ERROR_HTTP_NOT_FOUND, e.getCode()); - } - - // - printHeadline("update attributes of a document"); - // - - x = "{\"test\":1234}"; - try { - final DocumentEntity updateDocumentRaw = driver.updateDocumentRaw(documentHandle2, x, null, false, - true); - // print new document revision - System.out.println("rev: " + updateDocumentRaw.getDocumentRevision()); - // show request result (you have to use getDocumentRaw to get - // all attributes of the changed object): - System.out.println("value: " + updateDocumentRaw.getEntity()); - } catch (final ArangoException e) { - Assert.assertEquals(ErrorNums.ERROR_HTTP_NOT_FOUND, e.getCode()); - } - - // - printHeadline("replace a document"); - // - - x = "{\"hund\":321,\"katze\":321,\"maus\":777}"; - try { - final DocumentEntity replaceDocumentRaw = driver.replaceDocumentRaw(documentHandle2, x, null, - false); - // print new document revision - System.out.println("rev: " + replaceDocumentRaw.getDocumentRevision()); - // show request result (you have to use getDocumentRaw to get - // all attributes of the replaced object): - System.out.println("value: " + replaceDocumentRaw.getEntity()); - } catch (final ArangoException e) { - Assert.assertEquals(ErrorNums.ERROR_HTTP_NOT_FOUND, e.getCode()); - } - - // - printHeadline("using org.json.JSONML to save a xml file"); - // - final String string = " Basic bread Flour Yeast Water Salt Mix all ingredients together. Knead thoroughly. Cover with a cloth, and leave for one hour in warm room. Knead again. Place in a bread baking tin. Cover with a cloth, and leave for one hour in warm room. Bake in the oven at 180(degrees)C for 30 minutes. "; - System.out.println("Orig XML value: " + string); - final JSONObject jsonObject = JSONML.toJSONObject(string); - try { - final DocumentEntity entity = driver.createDocumentRaw(COLLECTION_NAME, jsonObject.toString(), - false); - // the DocumentEntity contains the key, document handle and revision - System.out.println("Key: " + entity.getDocumentKey()); - System.out.println("Id: " + entity.getDocumentHandle()); - System.out.println("Revision: " + entity.getDocumentRevision()); - documentHandle3 = entity.getDocumentHandle(); - } catch (final ArangoException e) { - Assert.fail("Failed to create document. " + e.getMessage()); - } - - // - printHeadline("read example and convert it back to XML"); - // - - try { - final String str = driver.getDocumentRaw(documentHandle3, null, null); - System.out.println("JSON value: " + str); - final JSONObject jsonObject2 = new JSONObject(str); - System.out.println("XML value: " + JSONML.toString(jsonObject2)); - } catch (final ArangoException e) { - Assert.fail("Failed to read document. " + e.getMessage()); - } - - // - printHeadline("get query results"); - // - - final String queryString = "FOR t IN " + COLLECTION_NAME + " FILTER t.cook_time == \"3 hours\" RETURN t"; - System.out.println(queryString); - final HashMap bindVars = new HashMap(); - - try { - final CursorRawResult cursor = driver.executeAqlQueryRaw(queryString, bindVars, null); - Assert.assertNotNull(cursor); - final Iterator iter = cursor.iterator(); - while (iter.hasNext()) { - final JSONObject jsonObject2 = new JSONObject(iter.next()); - System.out.println("XML value: " + JSONML.toString(jsonObject2)); - } - } catch (final ArangoException e) { - Assert.fail("Failed to query documents. " + e.getMessage()); - } - - } - -} diff --git a/src/test/java/com/arangodb/example/document/ReadDocumentExample.java b/src/test/java/com/arangodb/example/document/ReadDocumentExample.java deleted file mode 100644 index 25810b6e6..000000000 --- a/src/test/java/com/arangodb/example/document/ReadDocumentExample.java +++ /dev/null @@ -1,265 +0,0 @@ -/* - * Copyright (C) 2015 ArangoDB GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.example.document; - -import java.util.HashMap; -import java.util.List; - -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import com.arangodb.ArangoException; -import com.arangodb.entity.BaseDocument; -import com.arangodb.entity.CollectionEntity; -import com.arangodb.entity.DocumentEntity; - -public class ReadDocumentExample extends BaseExample { - - private static final String DATABASE_NAME = "ReadDocument"; - - private static final String COLLECTION_NAME = "ReadDocument"; - - private static final String KEY1 = "key1"; - - @Before - public void _before() { - removeTestDatabase(DATABASE_NAME); - - createDatabase(driver, DATABASE_NAME); - createCollection(driver, COLLECTION_NAME); - } - - @After - public void _after() { - removeTestDatabase(DATABASE_NAME); - } - - @Test - public void ReadDocuments() { - // - // You can find the ArangoDB Web interface here: - // http://127.0.0.1:8529/ - // - // change the log level to "debug" in /src/test/resource/logback.xml to - // see the HTTP communication - - // - printHeadline("create example document"); - // - - final HashMap myHashMap = new HashMap(); - myHashMap.put("_key", KEY1); - // attributes are stored in a HashMap - myHashMap.put("name", "Alice"); - myHashMap.put("gender", "female"); - myHashMap.put("age", 18); - String documentHandleExample = null; - - try { - final DocumentEntity> entity = driver.createDocument(COLLECTION_NAME, myHashMap); - Assert.assertNotNull(entity); - Assert.assertNotNull(entity.getDocumentHandle()); - Assert.assertNotNull(entity.getDocumentKey()); - Assert.assertNotNull(entity.getDocumentRevision()); - - documentHandleExample = entity.getDocumentHandle(); - } catch (final ArangoException e) { - Assert.fail("Failed to create document. " + e.getMessage()); - } - - // - printHeadline("read documents"); - // - - System.out.println("1. read document as BaseDocument object:"); - try { - final DocumentEntity entity = driver.getDocument(COLLECTION_NAME, KEY1, BaseDocument.class); - - Assert.assertNotNull(entity); - Assert.assertNotNull(entity.getDocumentHandle()); - Assert.assertNotNull(entity.getDocumentKey()); - Assert.assertNotNull(entity.getDocumentRevision()); - Assert.assertEquals(KEY1, entity.getDocumentKey()); - - // the DocumentEntity contains the key, document handle and revision - System.out.println("Key: " + entity.getDocumentKey()); - System.out.println("Id: " + entity.getDocumentHandle()); - System.out.println("Revision: " + entity.getDocumentRevision()); - - final BaseDocument baseDocument2 = entity.getEntity(); - Assert.assertNotNull(baseDocument2); - - // the BaseDocument contains the key, document handle and revision - System.out.println("Key: " + baseDocument2.getDocumentKey()); - System.out.println("Id: " + baseDocument2.getDocumentHandle()); - System.out.println("Revision: " + baseDocument2.getDocumentRevision()); - // get the attributes - System.out.println("Attribute 'name': " + baseDocument2.getProperties().get("name")); - System.out.println("Attribute 'gender': " + baseDocument2.getProperties().get("gender")); - - Assert.assertTrue(baseDocument2.getProperties().get("age") instanceof Double); - - // ArangoDb stores numeric values as double values - System.out.println( - "Attribute 'age': " + baseDocument2.getProperties().get("age") + " <- Data type changed to double"); - - // printEntity(entity); - } catch (final ArangoException e) { - Assert.fail("Failed to read document. " + e.getMessage()); - } - - System.out.println("2. read document as HashMap object:"); - try { - @SuppressWarnings("rawtypes") - final DocumentEntity entity = driver.getDocument(COLLECTION_NAME, KEY1, HashMap.class); - - Assert.assertNotNull(entity); - Assert.assertNotNull(entity.getDocumentHandle()); - Assert.assertNotNull(entity.getDocumentKey()); - Assert.assertNotNull(entity.getDocumentRevision()); - Assert.assertEquals(KEY1, entity.getDocumentKey()); - - final HashMap map = entity.getEntity(); - Assert.assertNotNull(map); - - // get the attributes - System.out.println("Key: " + map.get("_key")); - System.out.println("Id: " + map.get("_id")); - System.out.println("Revision: " + map.get("_rev")); - System.out.println("Attribute 'name': " + map.get("name")); - System.out.println("Attribute 'gender': " + map.get("gender")); - - Assert.assertTrue(map.get("age") instanceof Double); - - System.out.println("Attribute 'age': " + map.get("age") + " <- Data type changed to double"); - - // printEntity(entity); - } catch (final ArangoException e) { - Assert.fail("Failed to read document. " + e.getMessage()); - } - - System.out.println("3. read document as SimplePerson object:"); - try { - final DocumentEntity entity = driver.getDocument(COLLECTION_NAME, KEY1, SimplePerson.class); - - Assert.assertNotNull(entity); - Assert.assertNotNull(entity.getDocumentHandle()); - Assert.assertNotNull(entity.getDocumentKey()); - Assert.assertNotNull(entity.getDocumentRevision()); - Assert.assertEquals(KEY1, entity.getDocumentKey()); - - final SimplePerson sp = entity.getEntity(); - Assert.assertNotNull(sp); - - // get the attributes - System.out.println("Attribute 'name': " + sp.getName()); - System.out.println("Attribute 'gender': " + sp.getGender()); - // ArangoDb stores numeric values as double values but the value is - // converted back to integer - System.out.println("Attribute 'age': " + sp.getAge()); - - // printEntity(entity); - } catch (final ArangoException e) { - Assert.fail("Failed to read document. " + e.getMessage()); - } - - System.out.println("4. read document as DocumentPerson object:"); - try { - final DocumentEntity entity = driver.getDocument(COLLECTION_NAME, KEY1, - DocumentPerson.class); - - Assert.assertNotNull(entity); - Assert.assertNotNull(entity.getDocumentHandle()); - Assert.assertNotNull(entity.getDocumentKey()); - Assert.assertNotNull(entity.getDocumentRevision()); - Assert.assertEquals(KEY1, entity.getDocumentKey()); - - final DocumentPerson dp = entity.getEntity(); - Assert.assertNotNull(dp); - - System.out.println("Key: " + dp.getDocumentKey()); - System.out.println("Id: " + dp.getDocumentHandle()); - System.out.println("Revision: " + dp.getDocumentRevision()); - // get the attributes - System.out.println("Attribute 'name': " + dp.getName()); - System.out.println("Attribute 'gender': " + dp.getGender()); - // ArangoDb stores numeric values as double values but the value is - // converted back to integer - System.out.println("Attribute 'age': " + dp.getAge()); - - // printEntity(entity); - } catch (final ArangoException e) { - Assert.fail("Failed to read document. " + e.getMessage()); - } - - // - printHeadline("read document by document handle"); - // - try { - final DocumentEntity entity = driver.getDocument(documentHandleExample, - DocumentPerson.class); - - Assert.assertNotNull(entity); - Assert.assertNotNull(entity.getDocumentHandle()); - Assert.assertNotNull(entity.getDocumentKey()); - Assert.assertNotNull(entity.getDocumentRevision()); - Assert.assertEquals(KEY1, entity.getDocumentKey()); - - final DocumentPerson dp = entity.getEntity(); - Assert.assertNotNull(dp); - - System.out.println("Key: " + dp.getDocumentKey()); - System.out.println("Attribute 'name': " + dp.getName()); - } catch (final ArangoException e) { - Assert.fail("Failed to read document. " + e.getMessage()); - } - - // - printHeadline("read collection count"); - // - try { - final CollectionEntity collectionCount = driver.getCollectionCount(COLLECTION_NAME); - - Assert.assertNotNull(collectionCount); - Assert.assertEquals(1, collectionCount.getCount()); - - System.out.println("Collection count: " + collectionCount.getCount()); - } catch (final ArangoException e) { - Assert.fail("Failed to read collection count. " + e.getMessage()); - } - - // - printHeadline("read all document handles of a collection"); - // - try { - final List documentHandles = driver.getDocuments(COLLECTION_NAME); - - Assert.assertNotNull(documentHandles); - Assert.assertEquals(1, documentHandles.size()); - - for (final String documentHandle : documentHandles) { - System.out.println("document handle: " + documentHandle); - } - - } catch (final ArangoException e) { - Assert.fail("Failed to read all documents. " + e.getMessage()); - } - } - -} diff --git a/src/test/java/com/arangodb/example/document/ReplaceAndUpdateDocumentExample.java b/src/test/java/com/arangodb/example/document/ReplaceAndUpdateDocumentExample.java deleted file mode 100644 index 752a13252..000000000 --- a/src/test/java/com/arangodb/example/document/ReplaceAndUpdateDocumentExample.java +++ /dev/null @@ -1,166 +0,0 @@ -/* - * Copyright (C) 2015 ArangoDB GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.example.document; - -import java.util.HashMap; - -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import com.arangodb.ArangoException; -import com.arangodb.ErrorNums; -import com.arangodb.entity.DocumentEntity; - -public class ReplaceAndUpdateDocumentExample extends BaseExample { - - private static final String DATABASE_NAME = "ReplaceDocument"; - - private static final String COLLECTION_NAME = "ReplaceDocument"; - - private static final String KEY1 = "key1"; - - @Before - public void _before() { - removeTestDatabase(DATABASE_NAME); - - createDatabase(driver, DATABASE_NAME); - createCollection(driver, COLLECTION_NAME); - } - - @After - public void _after() { - removeTestDatabase(DATABASE_NAME); - } - - @Test - public void replaceAndUpdateDocument() { - // - // You can find the ArangoDB Web interface here: - // http://127.0.0.1:8529/ - // - // change the log level to "debug" in /src/test/resource/logback.xml to - // see the HTTP communication - - // - printHeadline("create example document"); - // - - final HashMap myHashMap = new HashMap(); - myHashMap.put("_key", KEY1); - // attributes are stored in a HashMap - myHashMap.put("name", "Alice"); - myHashMap.put("gender", "female"); - myHashMap.put("age", 18); - String documentHandleExample = null; - String revision = "0"; - - try { - final DocumentEntity> entity = driver.createDocument(COLLECTION_NAME, myHashMap); - - Assert.assertNotNull(entity); - Assert.assertNotNull(entity.getDocumentHandle()); - Assert.assertNotNull(entity.getDocumentKey()); - Assert.assertNotNull(entity.getDocumentRevision()); - revision = entity.getDocumentRevision(); - - System.out.println("Key: " + entity.getDocumentKey()); - System.out.println("Id: " + entity.getDocumentHandle()); - System.out.println("Revision: " + entity.getDocumentRevision()); - documentHandleExample = entity.getDocumentHandle(); - } catch (final ArangoException e) { - Assert.fail("Failed to create document. " + e.getMessage()); - } - - // - printHeadline("replace document"); - // - - try { - final DocumentPerson dp = new DocumentPerson("Moritz", "male", 6); - driver.replaceDocument(documentHandleExample, dp); - - System.out.println("Key: " + dp.getDocumentKey()); - System.out.println("Revision: " + dp.getDocumentRevision() + " <- revision changed"); - System.out.println("Attribute 'name': " + dp.getName()); - - Assert.assertTrue(dp.getDocumentRevision() != revision); - - revision = dp.getDocumentRevision(); - - } catch (final ArangoException e) { - Assert.fail("Failed to replace document. " + e.getMessage()); - } - - // - printHeadline("update document"); - // - - // update one attribute - final HashMap newHashMap = new HashMap(); - newHashMap.put("name", "Fritz"); - try { - driver.updateDocument(documentHandleExample, newHashMap); - - final DocumentEntity entity = driver.getDocument(documentHandleExample, - DocumentPerson.class); - - Assert.assertNotNull(entity); - Assert.assertNotNull(entity.getDocumentHandle()); - Assert.assertNotNull(entity.getDocumentKey()); - Assert.assertNotNull(entity.getDocumentRevision()); - Assert.assertNotNull(entity.getEntity()); - - final DocumentPerson dp = entity.getEntity(); - - System.out.println("Key: " + dp.getDocumentKey()); - System.out.println("Revision: " + dp.getDocumentRevision() + " <- revision changed"); - System.out.println("Attribute 'name': " + dp.getName()); - System.out.println("Attribute 'gender': " + dp.getGender()); - System.out.println("Attribute 'age': " + dp.getAge()); - - Assert.assertTrue(dp.getDocumentRevision() != revision); - - revision = dp.getDocumentRevision(); - - } catch (final ArangoException e) { - Assert.fail("Failed to update document. " + e.getMessage()); - } - - // - printHeadline("replace document with given revision"); - // - try { - final DocumentPerson dp = new DocumentPerson("Nina", "female", 9); - // wrong revision - driver.replaceDocument(documentHandleExample, dp, "22", true); - Assert.fail("replaceDocument should fail here!"); - } catch (final ArangoException e) { - Assert.assertEquals(ErrorNums.ERROR_ARANGO_CONFLICT, e.getErrorNumber()); - } - - try { - final DocumentPerson dp = new DocumentPerson("Nina", "female", 9); - // current revision - driver.replaceDocument(documentHandleExample, dp, revision, true); - } catch (final ArangoException e) { - Assert.fail("Failed to replace document. " + e.getMessage()); - } - } - -} diff --git a/src/test/java/com/arangodb/example/document/SimplePerson.java b/src/test/java/com/arangodb/example/document/SimplePerson.java deleted file mode 100644 index b41aa601f..000000000 --- a/src/test/java/com/arangodb/example/document/SimplePerson.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright (C) 2015 ArangoDB GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.example.document; - -/** - * A simple person class. - * - * The simple person class has no attributes to store the document key or - * revision. - * - * @author a-brandt - * - */ -public class SimplePerson { - - private String name; - - private String gender; - - private Integer age; - - public SimplePerson() { - - } - - public SimplePerson(String name, String gender, Integer age) { - this.name = name; - this.gender = gender; - this.age = age; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getGender() { - return gender; - } - - public void setGender(String gender) { - this.gender = gender; - } - - public Integer getAge() { - return age; - } - - public void setAge(Integer age) { - this.age = age; - } - -} diff --git a/src/test/java/com/arangodb/example/document/SimplePersonAqlQueryExample.java b/src/test/java/com/arangodb/example/document/SimplePersonAqlQueryExample.java deleted file mode 100644 index 39faa87b4..000000000 --- a/src/test/java/com/arangodb/example/document/SimplePersonAqlQueryExample.java +++ /dev/null @@ -1,156 +0,0 @@ -/* - * Copyright (C) 2015 ArangoDB GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.example.document; - -import java.util.HashMap; -import java.util.Iterator; - -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import com.arangodb.ArangoException; -import com.arangodb.DocumentCursor; -import com.arangodb.entity.DocumentEntity; -import com.arangodb.util.AqlQueryOptions; - -public class SimplePersonAqlQueryExample extends BaseExample { - - private static final String DATABASE_NAME = "SimplePersonAqlQueryExample"; - - private static final String COLLECTION_NAME = "SimplePersonAqlQueryExample"; - - @Before - public void _before() { - removeTestDatabase(DATABASE_NAME); - - createDatabase(driver, DATABASE_NAME); - createCollection(driver, COLLECTION_NAME); - } - - @After - public void _after() { - removeTestDatabase(DATABASE_NAME); - } - - @Test - public void simplePersonAqlQuery() { - // - // You can find the ArangoDB Web interface here: - // http://127.0.0.1:8529/ - // - // change the log level to "debug" in /src/test/resource/logback.xml to - // see the HTTP communication - - try { - // - printHeadline("create example documents"); - // - createExamples(); - - // - printHeadline("build query"); - // - - // build an AQL query string - final String queryString = "FOR t IN " + COLLECTION_NAME - + " FILTER t.age >= 20 && t.age < 30 && t.gender == @gender RETURN t"; - System.out.println(queryString); - - // bind @gender to female - final HashMap bindVars = new HashMap(); - bindVars.put("gender", FEMALE); - - // query (count = true, batchSize = 5) - final AqlQueryOptions aqlQueryOptions = new AqlQueryOptions().setCount(true).setBatchSize(5); - - // - printHeadline("execute query"); - // - - DocumentCursor rs = driver.executeDocumentQuery(queryString, bindVars, aqlQueryOptions, - SimplePerson.class); - Assert.assertNotNull(rs); - - // - printHeadline("get number of results"); - // - - // get total number of results - System.out.println(rs.getCount()); - - // - printHeadline("print results"); - // - - // using the DocumentEntity iterator - final Iterator> iterator = rs.iterator(); - while (iterator.hasNext()) { - final DocumentEntity documentEntity = iterator.next(); - - Assert.assertNotNull(documentEntity); - Assert.assertNotNull(documentEntity.getDocumentKey()); - Assert.assertNotNull(documentEntity.getDocumentHandle()); - Assert.assertNotNull(documentEntity.getDocumentRevision()); - Assert.assertNotNull(documentEntity.getEntity()); - - final SimplePerson person = documentEntity.getEntity(); - System.out.printf("%20s %15s(%5s): %d%n", documentEntity.getDocumentKey(), person.getName(), - person.getGender(), person.getAge()); - } - - // - printHeadline("execute query again"); - // - - rs = driver.executeDocumentQuery(queryString, bindVars, aqlQueryOptions, SimplePerson.class); - Assert.assertNotNull(rs); - - // get total number of results - System.out.println(rs.getCount()); - - // using the entity iterator - final Iterator iterator2 = rs.entityIterator(); - while (iterator2.hasNext()) { - final SimplePerson person = iterator2.next(); - - Assert.assertNotNull(person); - - System.out.printf(" %15s(%5s): %d%n", person.getName(), person.getGender(), person.getAge()); - } - - } catch (final ArangoException e) { - Assert.fail("Example failed. " + e.getMessage()); - } - - } - - private void createExamples() throws ArangoException { - // create some persons - for (int i = 0; i < 1000; i++) { - final SimplePerson person = new SimplePerson(); - person.setName("TestUser" + i); - person.setGender((i % 2) == 0 ? MALE : FEMALE); - person.setAge((int) (Math.random() * 100) + 10); - - driver.createDocument(COLLECTION_NAME, person, null); - } - - } - -} diff --git a/src/test/java/com/arangodb/example/document/SimplePersonAqlQueryWithLimitExample.java b/src/test/java/com/arangodb/example/document/SimplePersonAqlQueryWithLimitExample.java deleted file mode 100644 index 9029cfd2b..000000000 --- a/src/test/java/com/arangodb/example/document/SimplePersonAqlQueryWithLimitExample.java +++ /dev/null @@ -1,140 +0,0 @@ -/* - * Copyright (C) 2015 ArangoDB GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.example.document; - -import java.util.HashMap; -import java.util.Iterator; - -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import com.arangodb.ArangoException; -import com.arangodb.DocumentCursor; -import com.arangodb.entity.DocumentEntity; -import com.arangodb.util.AqlQueryOptions; - -public class SimplePersonAqlQueryWithLimitExample extends BaseExample { - - private static final String DATABASE_NAME = "SimplePersonAqlQueryWithLimitExample"; - - private static final String COLLECTION_NAME = "SimplePersonAqlQueryWithLimitExample"; - - @Before - public void _before() { - removeTestDatabase(DATABASE_NAME); - - createDatabase(driver, DATABASE_NAME); - createCollection(driver, COLLECTION_NAME); - } - - @After - public void _after() { - removeTestDatabase(DATABASE_NAME); - } - - @Test - public void simplePersonAqlWithLimitQuery() { - // - // You can find the ArangoDB Web interface here: - // http://127.0.0.1:8529/ - // - // change the log level to "debug" in /src/test/resource/logback.xml to - // see the HTTP communication - - try { - // - printHeadline("create example documents"); - // - createExamples(); - - // - printHeadline("build query"); - // - - // build an AQL query string - final String queryString = "FOR t IN " + COLLECTION_NAME + " FILTER t.gender == @gender LIMIT 5 RETURN t"; - System.out.println(queryString); - - // bind @gender to female - final HashMap bindVars = new HashMap(); - bindVars.put("gender", FEMALE); - - // query (count = true, batchSize = 5) - final AqlQueryOptions aqlQueryOptions = new AqlQueryOptions().setCount(true).setFullCount(true); - - // - printHeadline("execute query"); - // - - final DocumentCursor rs = driver.executeDocumentQuery(queryString, bindVars, aqlQueryOptions, - SimplePerson.class); - Assert.assertNotNull(rs); - - // - printHeadline("get number of results"); - // - - // number of results with LIMIT = 5 - System.out.println("cursor count = " + rs.getCount()); - Assert.assertEquals(5, rs.getCount()); - - // number of results without LIMIT - System.out.println("cursor full count = " + rs.getFullCount()); - Assert.assertTrue(5 < rs.getFullCount()); - - // - printHeadline("print results"); - // - - // using the DocumentEntity iterator - final Iterator> iterator = rs.iterator(); - while (iterator.hasNext()) { - final DocumentEntity documentEntity = iterator.next(); - - Assert.assertNotNull(documentEntity); - Assert.assertNotNull(documentEntity.getDocumentKey()); - Assert.assertNotNull(documentEntity.getDocumentHandle()); - Assert.assertNotNull(documentEntity.getDocumentRevision()); - Assert.assertNotNull(documentEntity.getEntity()); - - final SimplePerson person = documentEntity.getEntity(); - System.out.printf("%20s %15s(%5s): %d%n", documentEntity.getDocumentKey(), person.getName(), - person.getGender(), person.getAge()); - } - - } catch (final ArangoException e) { - Assert.fail("Example failed. " + e.getMessage()); - } - - } - - private void createExamples() throws ArangoException { - // create some persons - for (int i = 0; i < 100; i++) { - final SimplePerson person = new SimplePerson(); - person.setName("TestUser" + i); - person.setGender((i % 2) == 0 ? MALE : FEMALE); - person.setAge((int) (Math.random() * 100) + 10); - - driver.createDocument(COLLECTION_NAME, person, null); - } - - } - -} diff --git a/src/test/java/com/arangodb/example/document/TestEntity.java b/src/test/java/com/arangodb/example/document/TestEntity.java new file mode 100644 index 000000000..95a16d110 --- /dev/null +++ b/src/test/java/com/arangodb/example/document/TestEntity.java @@ -0,0 +1,48 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.example.document; + +/** + * @author Mark - mark at arangodb.com + * + */ +public class TestEntity { + + private String foo; + + public TestEntity() { + super(); + } + + public TestEntity(final String foo) { + super(); + this.foo = foo; + } + + public String getFoo() { + return 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 new file mode 100644 index 000000000..f247607ba --- /dev/null +++ b/src/test/java/com/arangodb/example/graph/AQLActorsAndMoviesExample.java @@ -0,0 +1,573 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.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; +import com.arangodb.ArangoDBException; +import com.arangodb.ArangoDatabase; +import com.arangodb.entity.BaseDocument; +import com.arangodb.entity.BaseEdgeDocument; +import com.arangodb.entity.CollectionType; +import com.arangodb.entity.DocumentCreateEntity; +import com.arangodb.model.CollectionCreateOptions; + +/** + * @author Mark - mark at arangodb.com + * + * @see AQL Example Queries on an + * Actors and Movies Database + * + */ +public class AQLActorsAndMoviesExample { + + private static final String TEST_DB = "actors_movies_test_db"; + private static ArangoDB arangoDB; + private static ArangoDatabase db; + + @BeforeClass + public static void setUp() { + arangoDB = new ArangoDB.Builder().build(); + try { + arangoDB.db(TEST_DB).drop(); + } catch (final ArangoDBException e) { + } + arangoDB.createDatabase(TEST_DB); + db = arangoDB.db(TEST_DB); + createData(); + } + + @AfterClass + public static void tearDown() { + db.drop(); + arangoDB.shutdown(); + } + + /** + * @see AQL + * Example Queries on an Actors and Movies Database + */ + @Test + public void allActorsActsInMovie1or2() { + final ArangoCursor cursor = db.query( + "FOR x IN ANY 'movies/TheMatrix' actsIn OPTIONS {bfs: true, uniqueVertices: 'global'} RETURN x._id", null, + null, String.class); + assertThat(cursor.asListRemaining(), + hasItems("actors/Keanu", "actors/Hugo", "actors/Emil", "actors/Carrie", "actors/Laurence")); + } + + /** + * @see AQL + * Example Queries on an Actors and Movies Database + */ + @Test + public void allActorsActsInMovie1or2UnionDistinct() { + final ArangoCursor cursor = db.query( + "FOR x IN UNION_DISTINCT ((FOR y IN ANY 'movies/TheMatrix' actsIn OPTIONS {bfs: true, uniqueVertices: 'global'} RETURN y._id), (FOR y IN ANY 'movies/TheDevilsAdvocate' actsIn OPTIONS {bfs: true, uniqueVertices: 'global'} RETURN y._id)) RETURN x", + null, null, String.class); + assertThat(cursor.asListRemaining(), hasItems("actors/Emil", "actors/Hugo", "actors/Carrie", "actors/Laurence", + "actors/Keanu", "actors/Al", "actors/Charlize")); + } + + /** + * @see AQL + * Example Queries on an Actors and Movies Database + */ + @Test + public void allActorsActsInMovie1and2() { + final ArangoCursor cursor = db.query( + "FOR x IN INTERSECTION ((FOR y IN ANY 'movies/TheMatrix' actsIn OPTIONS {bfs: true, uniqueVertices: 'global'} RETURN y._id), (FOR y IN ANY 'movies/TheDevilsAdvocate' actsIn OPTIONS {bfs: true, uniqueVertices: 'global'} RETURN y._id)) RETURN x", + null, null, String.class); + assertThat(cursor.asListRemaining(), hasItems("actors/Keanu")); + } + + /** + * @see AQL + * Example Queries on an Actors and Movies Database + */ + @Test + public void allMoviesBetweenActor1andActor2() { + final ArangoCursor cursor = db.query( + "FOR x IN INTERSECTION ((FOR y IN ANY 'actors/Hugo' actsIn OPTIONS {bfs: true, uniqueVertices: 'global'} RETURN y._id), (FOR y IN ANY 'actors/Keanu' actsIn OPTIONS {bfs: true, uniqueVertices: 'global'} RETURN y._id)) RETURN x", + null, null, String.class); + assertThat(cursor.asListRemaining(), + hasItems("movies/TheMatrixRevolutions", "movies/TheMatrixReloaded", "movies/TheMatrix")); + } + + /** + * @see AQL + * Example Queries on an Actors and Movies Database + */ + @Test + public void allActorsWhoActedIn3orMoreMovies() { + final ArangoCursor cursor = db.query( + "FOR x IN actsIn COLLECT actor = x._from WITH COUNT INTO counter FILTER counter >= 3 RETURN {actor: actor, movies: counter}", + null, null, Actor.class); + assertThat(cursor.asListRemaining(), + hasItems(new Actor("actors/Carrie", 3), new Actor("actors/CubaG", 4), new Actor("actors/Hugo", 3), + new Actor("actors/Keanu", 4), new Actor("actors/Laurence", 3), new Actor("actors/MegR", 5), + new Actor("actors/TomC", 3), new Actor("actors/TomH", 3))); + } + + /** + * @see AQL + * Example Queries on an Actors and Movies Database + */ + @Test + public void allMoviesWhereExactly6ActorsActedIn() { + final ArangoCursor cursor = db.query( + "FOR x IN actsIn COLLECT movie = x._to WITH COUNT INTO counter FILTER counter == 6 RETURN movie", null, + null, String.class); + assertThat(cursor.asListRemaining(), + hasItems("movies/SleeplessInSeattle", "movies/TopGun", "movies/YouveGotMail")); + } + + /** + * @see AQL + * Example Queries on an Actors and Movies Database + */ + @Test + public void theNumberOfActorsByMovie() { + final ArangoCursor cursor = db.query( + "FOR x IN actsIn COLLECT movie = x._to WITH COUNT INTO counter RETURN {movie: movie, actors: counter}", + null, null, Movie.class); + assertThat(cursor.asListRemaining(), + hasItems(new Movie("movies/AFewGoodMen", 11), new Movie("movies/AsGoodAsItGets", 4), + new Movie("movies/JerryMaguire", 9), new Movie("movies/JoeVersustheVolcano", 3), + new Movie("movies/SleeplessInSeattle", 6), new Movie("movies/SnowFallingonCedars", 4), + new Movie("movies/StandByMe", 7), new Movie("movies/TheDevilsAdvocate", 3), + new Movie("movies/TheMatrix", 5), new Movie("movies/TheMatrixReloaded", 4), + new Movie("movies/TheMatrixRevolutions", 4), new Movie("movies/TopGun", 6), + new Movie("movies/WhatDreamsMayCome", 5), new Movie("movies/WhenHarryMetSally", 4), + new Movie("movies/YouveGotMail", 6))); + } + + /** + * @see AQL + * Example Queries on an Actors and Movies Database + */ + @Test + public void theNumberOfMoviesByActor() { + final ArangoCursor cursor = db.query( + "FOR x IN actsIn COLLECT actor = x._from WITH COUNT INTO counter RETURN {actor: actor, movies: counter}", + null, null, Actor.class); + assertThat(cursor.asListRemaining(), + hasItems(new Actor("actors/Al", 1), new Actor("actors/AnnabellaS", 1), new Actor("actors/AnthonyE", 1), + new Actor("actors/BillPull", 1), new Actor("actors/BillyC", 1), new Actor("actors/BonnieH", 1), + new Actor("actors/BrunoK", 1), new Actor("actors/Carrie", 3), new Actor("actors/CarrieF", 1), + new Actor("actors/Charlize", 1), new Actor("actors/ChristopherG", 1), new Actor("actors/CoreyF", 1), + new Actor("actors/CubaG", 4), new Actor("actors/DaveC", 1), new Actor("actors/DemiM", 1), + new Actor("actors/Emil", 1), new Actor("actors/EthanH", 1), new Actor("actors/GregK", 2), + new Actor("actors/HelenH", 1), new Actor("actors/Hugo", 3), new Actor("actors/JackN", 2), + new Actor("actors/JamesC", 1), new Actor("actors/JamesM", 1), new Actor("actors/JayM", 1), + new Actor("actors/JerryO", 2), new Actor("actors/JohnC", 1), new Actor("actors/JonathanL", 1), + new Actor("actors/JTW", 1), new Actor("actors/Keanu", 4), new Actor("actors/KellyM", 1), + new Actor("actors/KellyP", 1), new Actor("actors/KevinB", 1), new Actor("actors/KevinP", 1), + new Actor("actors/KieferS", 2), new Actor("actors/Laurence", 3), new Actor("actors/MarshallB", 1), + new Actor("actors/MaxS", 2), new Actor("actors/MegR", 5), new Actor("actors/Nathan", 1), + new Actor("actors/NoahW", 1), new Actor("actors/ParkerP", 1), new Actor("actors/ReginaK", 1), + new Actor("actors/ReneeZ", 1), new Actor("actors/RickY", 1), new Actor("actors/RitaW", 1), + new Actor("actors/RiverP", 1), new Actor("actors/Robin", 1), new Actor("actors/RosieO", 1), + new Actor("actors/SteveZ", 1), new Actor("actors/TomC", 3), new Actor("actors/TomH", 3), + new Actor("actors/TomS", 1), new Actor("actors/ValK", 1), new Actor("actors/VictorG", 1), + new Actor("actors/WernerH", 1), new Actor("actors/WilW", 1))); + } + + /** + * @see AQL + * Example Queries on an Actors and Movies Database + */ + @Test + public void theNumberOfMoviesActedInBetween2005and2010byActor() { + final ArangoCursor cursor = db.query( + "FOR x IN actsIn FILTER x.year >= 1990 && x.year <= 1995 COLLECT actor = x._from WITH COUNT INTO counter RETURN {actor: actor, movies: counter}", + null, null, Actor.class); + assertThat(cursor.asListRemaining(), + hasItems(new Actor("actors/BillPull", 1), new Actor("actors/ChristopherG", 1), new Actor("actors/CubaG", 1), + new Actor("actors/DemiM", 1), new Actor("actors/JackN", 1), new Actor("actors/JamesM", 1), + new Actor("actors/JTW", 1), new Actor("actors/KevinB", 1), new Actor("actors/KieferS", 1), + new Actor("actors/MegR", 2), new Actor("actors/Nathan", 1), new Actor("actors/NoahW", 1), + new Actor("actors/RitaW", 1), new Actor("actors/RosieO", 1), new Actor("actors/TomC", 1), + new Actor("actors/TomH", 2), new Actor("actors/VictorG", 1))); + } + + public static class Actor { + private String actor; + private Integer movies; + + public Actor() { + super(); + } + + public Actor(final String actor, final Integer movies) { + super(); + this.actor = actor; + this.movies = movies; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((actor == null) ? 0 : actor.hashCode()); + result = prime * result + ((movies == null) ? 0 : movies.hashCode()); + return result; + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final Actor other = (Actor) obj; + if (actor == null) { + if (other.actor != null) { + return false; + } + } else if (!actor.equals(other.actor)) { + return false; + } + if (movies == null) { + if (other.movies != null) { + return false; + } + } else if (!movies.equals(other.movies)) { + return false; + } + return true; + } + + } + + public static class Movie { + private String movie; + private Integer actors; + + public Movie() { + super(); + } + + public Movie(final String movie, final Integer actors) { + super(); + this.movie = movie; + this.actors = actors; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((actors == null) ? 0 : actors.hashCode()); + result = prime * result + ((movie == null) ? 0 : movie.hashCode()); + return result; + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final Movie other = (Movie) obj; + if (actors == null) { + if (other.actors != null) { + return false; + } + } else if (!actors.equals(other.actors)) { + return false; + } + if (movie == null) { + if (other.movie != null) { + return false; + } + } else if (!movie.equals(other.movie)) { + return false; + } + return true; + } + + } + + private static DocumentCreateEntity saveMovie( + final ArangoCollection movies, + final String key, + final String title, + final int released, + final String tagline) { + final BaseDocument value = new BaseDocument(); + value.setKey(key); + value.addAttribute("title", title); + value.addAttribute("released", released); + value.addAttribute("tagline", tagline); + return movies.insertDocument(value); + } + + private static DocumentCreateEntity saveActor( + final ArangoCollection actors, + final String key, + final String name, + final int born) { + final BaseDocument value = new BaseDocument(); + value.setKey(key); + value.addAttribute("name", name); + value.addAttribute("born", born); + return actors.insertDocument(value); + } + + private static DocumentCreateEntity saveActsIn( + final ArangoCollection actsIn, + final String actor, + final String movie, + final String[] roles, + final int year) { + final BaseEdgeDocument value = new BaseEdgeDocument(); + value.setFrom(actor); + value.setTo(movie); + value.addAttribute("roles", roles); + value.addAttribute("year", year); + return actsIn.insertDocument(value); + } + + private static void createData() { + db.createCollection("actors"); + final ArangoCollection actors = db.collection("actors"); + db.createCollection("movies"); + final ArangoCollection movies = db.collection("movies"); + db.createCollection("actsIn", new CollectionCreateOptions().type(CollectionType.EDGES)); + final ArangoCollection actsIn = db.collection("actsIn"); + + final String theMatrix = saveMovie(movies, "TheMatrix", "The Matrix", 1999, "Welcome to the Real World") + .getId(); + final String keanu = saveActor(actors, "Keanu", "Keanu Reeves", 1964).getId(); + final String carrie = saveActor(actors, "Carrie", "Carrie-Anne Moss", 1967).getId(); + final String laurence = saveActor(actors, "Laurence", "Laurence Fishburne", 1961).getId(); + final String hugo = saveActor(actors, "Hugo", "Hugo Weaving", 1960).getId(); + final String emil = saveActor(actors, "Emil", "Emil Eifrem", 1978).getId(); + + saveActsIn(actsIn, keanu, theMatrix, new String[] { "Neo" }, 1999); + saveActsIn(actsIn, carrie, theMatrix, new String[] { "Trinity" }, 1999); + saveActsIn(actsIn, laurence, theMatrix, new String[] { "Morpheus" }, 1999); + saveActsIn(actsIn, hugo, theMatrix, new String[] { "Agent Smith" }, 1999); + saveActsIn(actsIn, emil, theMatrix, new String[] { "Emil" }, 1999); + + final String theMatrixReloaded = saveMovie(movies, "TheMatrixReloaded", "The Matrix Reloaded", 2003, + "Free your mind").getId(); + saveActsIn(actsIn, keanu, theMatrixReloaded, new String[] { "Neo" }, 2003); + saveActsIn(actsIn, carrie, theMatrixReloaded, new String[] { "Trinity" }, 2003); + saveActsIn(actsIn, laurence, theMatrixReloaded, new String[] { "Morpheus" }, 2003); + saveActsIn(actsIn, hugo, theMatrixReloaded, new String[] { "Agent Smith" }, 2003); + + final String theMatrixRevolutions = saveMovie(movies, "TheMatrixRevolutions", "The Matrix Revolutions", 2003, + "Everything that has a beginning has an end").getId(); + saveActsIn(actsIn, keanu, theMatrixRevolutions, new String[] { "Neo" }, 2003); + saveActsIn(actsIn, carrie, theMatrixRevolutions, new String[] { "Trinity" }, 2003); + saveActsIn(actsIn, laurence, theMatrixRevolutions, new String[] { "Morpheus" }, 2003); + saveActsIn(actsIn, hugo, theMatrixRevolutions, new String[] { "Agent Smith" }, 2003); + + final String theDevilsAdvocate = saveMovie(movies, "TheDevilsAdvocate", "The Devil's Advocate", 1997, + "Evil has its winning ways").getId(); + final String charlize = saveActor(actors, "Charlize", "Charlize Theron", 1975).getId(); + final String al = saveActor(actors, "Al", "Al Pacino", 1940).getId(); + saveActsIn(actsIn, keanu, theDevilsAdvocate, new String[] { "Kevin Lomax" }, 1997); + saveActsIn(actsIn, charlize, theDevilsAdvocate, new String[] { "Mary Ann Lomax" }, 1997); + saveActsIn(actsIn, al, theDevilsAdvocate, new String[] { "John Milton" }, 1997); + + final String AFewGoodMen = saveMovie(movies, "AFewGoodMen", "A Few Good Men", 1992, + "In the heart of the nation's capital, in a courthouse of the U.S. government, one man will stop at nothing to keep his honor, and one will stop at nothing to find the truth.") + .getId(); + final String tomC = saveActor(actors, "TomC", "Tom Cruise", 1962).getId(); + final String jackN = saveActor(actors, "JackN", "Jack Nicholson", 1937).getId(); + final String demiM = saveActor(actors, "DemiM", "Demi Moore", 1962).getId(); + final String kevinB = saveActor(actors, "KevinB", "Kevin Bacon", 1958).getId(); + final String kieferS = saveActor(actors, "KieferS", "Kiefer Sutherland", 1966).getId(); + final String noahW = saveActor(actors, "NoahW", "Noah Wyle", 1971).getId(); + final String cubaG = saveActor(actors, "CubaG", "Cuba Gooding Jr.", 1968).getId(); + final String kevinP = saveActor(actors, "KevinP", "Kevin Pollak", 1957).getId(); + final String jTW = saveActor(actors, "JTW", "J.T. Walsh", 1943).getId(); + final String jamesM = saveActor(actors, "JamesM", "James Marshall", 1967).getId(); + final String christopherG = saveActor(actors, "ChristopherG", "Christopher Guest", 1948).getId(); + saveActsIn(actsIn, tomC, AFewGoodMen, new String[] { "Lt. Daniel Kaffee" }, 1992); + saveActsIn(actsIn, jackN, AFewGoodMen, new String[] { "Col. Nathan R. Jessup" }, 1992); + saveActsIn(actsIn, demiM, AFewGoodMen, new String[] { "Lt. Cdr. JoAnne Galloway" }, 1992); + saveActsIn(actsIn, kevinB, AFewGoodMen, new String[] { "Capt. Jack Ross" }, 1992); + saveActsIn(actsIn, kieferS, AFewGoodMen, new String[] { "Lt. Jonathan Kendrick" }, 1992); + saveActsIn(actsIn, noahW, AFewGoodMen, new String[] { "Cpl. Jeffrey Barnes" }, 1992); + saveActsIn(actsIn, cubaG, AFewGoodMen, new String[] { "Cpl. Carl Hammaker" }, 1992); + saveActsIn(actsIn, kevinP, AFewGoodMen, new String[] { "Lt. Sam Weinberg" }, 1992); + saveActsIn(actsIn, jTW, AFewGoodMen, new String[] { "Lt. Col. Matthew Andrew Markinson" }, 1992); + saveActsIn(actsIn, jamesM, AFewGoodMen, new String[] { "Pfc. Louden Downey" }, 1992); + saveActsIn(actsIn, christopherG, AFewGoodMen, new String[] { "Dr. Stone" }, 1992); + + final String topGun = saveMovie(movies, "TopGun", "Top Gun", 1986, "I feel the need, the need for speed.") + .getId(); + final String kellyM = saveActor(actors, "KellyM", "Kelly McGillis", 1957).getId(); + final String valK = saveActor(actors, "ValK", "Val Kilmer", 1959).getId(); + final String anthonyE = saveActor(actors, "AnthonyE", "Anthony Edwards", 1962).getId(); + final String tomS = saveActor(actors, "TomS", "Tom Skerritt", 1933).getId(); + final String megR = saveActor(actors, "MegR", "Meg Ryan", 1961).getId(); + saveActsIn(actsIn, tomC, topGun, new String[] { "Maverick" }, 1986); + saveActsIn(actsIn, kellyM, topGun, new String[] { "Charlie" }, 1986); + saveActsIn(actsIn, valK, topGun, new String[] { "Iceman" }, 1986); + saveActsIn(actsIn, anthonyE, topGun, new String[] { "Goose" }, 1986); + saveActsIn(actsIn, tomS, topGun, new String[] { "Viper" }, 1986); + saveActsIn(actsIn, megR, topGun, new String[] { "Carole" }, 1986); + + final String jerryMaguire = saveMovie(movies, "JerryMaguire", "Jerry Maguire", 2000, + "The rest of his life begins now.").getId(); + final String reneeZ = saveActor(actors, "ReneeZ", "Renee Zellweger", 1969).getId(); + final String kellyP = saveActor(actors, "KellyP", "Kelly Preston", 1962).getId(); + final String jerryO = saveActor(actors, "JerryO", "Jerry O'Connell", 1974).getId(); + final String jayM = saveActor(actors, "JayM", "Jay Mohr", 1970).getId(); + final String bonnieH = saveActor(actors, "BonnieH", "Bonnie Hunt", 1961).getId(); + final String reginaK = saveActor(actors, "ReginaK", "Regina King", 1971).getId(); + final String jonathanL = saveActor(actors, "JonathanL", "Jonathan Lipnicki", 1996).getId(); + saveActsIn(actsIn, tomC, jerryMaguire, new String[] { "Jerry Maguire" }, 2000); + saveActsIn(actsIn, cubaG, jerryMaguire, new String[] { "Rod Tidwell" }, 2000); + saveActsIn(actsIn, reneeZ, jerryMaguire, new String[] { "Dorothy Boyd" }, 2000); + saveActsIn(actsIn, kellyP, jerryMaguire, new String[] { "Avery Bishop" }, 2000); + saveActsIn(actsIn, jerryO, jerryMaguire, new String[] { "Frank Cushman" }, 2000); + saveActsIn(actsIn, jayM, jerryMaguire, new String[] { "Bob Sugar" }, 2000); + saveActsIn(actsIn, bonnieH, jerryMaguire, new String[] { "Laurel Boyd" }, 2000); + saveActsIn(actsIn, reginaK, jerryMaguire, new String[] { "Marcee Tidwell" }, 2000); + saveActsIn(actsIn, jonathanL, jerryMaguire, new String[] { "Ray Boyd" }, 2000); + + final String standByMe = saveMovie(movies, "StandByMe", "Stand By Me", 1986, + "For some, it's the last real taste of innocence, and the first real taste of life. But for everyone, it's the time that memories are made of.") + .getId(); + final String riverP = saveActor(actors, "RiverP", "River Phoenix", 1970).getId(); + final String coreyF = saveActor(actors, "CoreyF", "Corey Feldman", 1971).getId(); + final String wilW = saveActor(actors, "WilW", "Wil Wheaton", 1972).getId(); + final String johnC = saveActor(actors, "JohnC", "John Cusack", 1966).getId(); + final String marshallB = saveActor(actors, "MarshallB", "Marshall Bell", 1942).getId(); + saveActsIn(actsIn, wilW, standByMe, new String[] { "Gordie Lachance" }, 1986); + saveActsIn(actsIn, riverP, standByMe, new String[] { "Chris Chambers" }, 1986); + saveActsIn(actsIn, jerryO, standByMe, new String[] { "Vern Tessio" }, 1986); + saveActsIn(actsIn, coreyF, standByMe, new String[] { "Teddy Duchamp" }, 1986); + saveActsIn(actsIn, johnC, standByMe, new String[] { "Denny Lachance" }, 1986); + saveActsIn(actsIn, kieferS, standByMe, new String[] { "Ace Merrill" }, 1986); + saveActsIn(actsIn, marshallB, standByMe, new String[] { "Mr. Lachance" }, 1986); + + final String asGoodAsItGets = saveMovie(movies, "AsGoodAsItGets", "As Good as It Gets", 1997, + "A comedy from the heart that goes for the throat.").getId(); + final String helenH = saveActor(actors, "HelenH", "Helen Hunt", 1963).getId(); + final String gregK = saveActor(actors, "GregK", "Greg Kinnear", 1963).getId(); + saveActsIn(actsIn, jackN, asGoodAsItGets, new String[] { "Melvin Udall" }, 1997); + saveActsIn(actsIn, helenH, asGoodAsItGets, new String[] { "Carol Connelly" }, 1997); + saveActsIn(actsIn, gregK, asGoodAsItGets, new String[] { "Simon Bishop" }, 1997); + saveActsIn(actsIn, cubaG, asGoodAsItGets, new String[] { "Frank Sachs" }, 1997); + + final String whatDreamsMayCome = saveMovie(movies, "WhatDreamsMayCome", "What Dreams May Come", 1998, + "After life there is more. The end is just the beginning.").getId(); + final String annabellaS = saveActor(actors, "AnnabellaS", "Annabella Sciorra", 1960).getId(); + final String maxS = saveActor(actors, "MaxS", "Max von Sydow", 1929).getId(); + final String wernerH = saveActor(actors, "WernerH", "Werner Herzog", 1942).getId(); + final String robin = saveActor(actors, "Robin", "Robin Williams", 1951).getId(); + saveActsIn(actsIn, robin, whatDreamsMayCome, new String[] { "Chris Nielsen" }, 1998); + saveActsIn(actsIn, cubaG, whatDreamsMayCome, new String[] { "Albert Lewis" }, 1998); + saveActsIn(actsIn, annabellaS, whatDreamsMayCome, new String[] { "Annie Collins-Nielsen" }, 1998); + saveActsIn(actsIn, maxS, whatDreamsMayCome, new String[] { "The Tracker" }, 1998); + saveActsIn(actsIn, wernerH, whatDreamsMayCome, new String[] { "The Face" }, 1998); + + final String snowFallingonCedars = saveMovie(movies, "SnowFallingonCedars", "Snow Falling on Cedars", 1999, + "First loves last. Forever.").getId(); + final String ethanH = saveActor(actors, "EthanH", "Ethan Hawke", 1970).getId(); + final String rickY = saveActor(actors, "RickY", "Rick Yune", 1971).getId(); + final String jamesC = saveActor(actors, "JamesC", "James Cromwell", 1940).getId(); + saveActsIn(actsIn, ethanH, snowFallingonCedars, new String[] { "Ishmael Chambers" }, 1999); + saveActsIn(actsIn, rickY, snowFallingonCedars, new String[] { "Kazuo Miyamoto" }, 1999); + saveActsIn(actsIn, maxS, snowFallingonCedars, new String[] { "Nels Gudmundsson" }, 1999); + saveActsIn(actsIn, jamesC, snowFallingonCedars, new String[] { "Judge Fielding" }, 1999); + + final String youveGotMail = saveMovie(movies, "YouveGotMail", "You've Got Mail", 1998, + "At odds in life... in love on-line.").getId(); + final String parkerP = saveActor(actors, "ParkerP", "Parker Posey", 1968).getId(); + final String daveC = saveActor(actors, "DaveC", "Dave Chappelle", 1973).getId(); + final String steveZ = saveActor(actors, "SteveZ", "Steve Zahn", 1967).getId(); + final String tomH = saveActor(actors, "TomH", "Tom Hanks", 1956).getId(); + saveActsIn(actsIn, tomH, youveGotMail, new String[] { "Joe Fox" }, 1998); + saveActsIn(actsIn, megR, youveGotMail, new String[] { "Kathleen Kelly" }, 1998); + saveActsIn(actsIn, gregK, youveGotMail, new String[] { "Frank Navasky" }, 1998); + saveActsIn(actsIn, parkerP, youveGotMail, new String[] { "Patricia Eden" }, 1998); + saveActsIn(actsIn, daveC, youveGotMail, new String[] { "Kevin Jackson" }, 1998); + saveActsIn(actsIn, steveZ, youveGotMail, new String[] { "George Pappas" }, 1998); + + final String sleeplessInSeattle = saveMovie(movies, "SleeplessInSeattle", "Sleepless in Seattle", 1993, + "What if someone you never met, someone you never saw, someone you never knew was the only someone for you?") + .getId(); + final String ritaW = saveActor(actors, "RitaW", "Rita Wilson", 1956).getId(); + final String billPull = saveActor(actors, "BillPull", "Bill Pullman", 1953).getId(); + final String victorG = saveActor(actors, "VictorG", "Victor Garber", 1949).getId(); + final String rosieO = saveActor(actors, "RosieO", "Rosie O'Donnell", 1962).getId(); + saveActsIn(actsIn, tomH, sleeplessInSeattle, new String[] { "Sam Baldwin" }, 1993); + saveActsIn(actsIn, megR, sleeplessInSeattle, new String[] { "Annie Reed" }, 1993); + saveActsIn(actsIn, ritaW, sleeplessInSeattle, new String[] { "Suzy" }, 1993); + saveActsIn(actsIn, billPull, sleeplessInSeattle, new String[] { "Walter" }, 1993); + saveActsIn(actsIn, victorG, sleeplessInSeattle, new String[] { "Greg" }, 1993); + saveActsIn(actsIn, rosieO, sleeplessInSeattle, new String[] { "Becky" }, 1993); + + final String joeVersustheVolcano = saveMovie(movies, "JoeVersustheVolcano", "Joe Versus the Volcano", 1990, + "A story of love, lava and burning desire.").getId(); + final String nathan = saveActor(actors, "Nathan", "Nathan Lane", 1956).getId(); + saveActsIn(actsIn, tomH, joeVersustheVolcano, new String[] { "Joe Banks" }, 1990); + saveActsIn(actsIn, megR, joeVersustheVolcano, + new String[] { "DeDe', 'Angelica Graynamore', 'Patricia Graynamore" }, 1990); + saveActsIn(actsIn, nathan, joeVersustheVolcano, new String[] { "Baw" }, 1990); + + final String whenHarryMetSally = saveMovie(movies, "WhenHarryMetSally", "When Harry Met Sally", 1998, + "At odds in life... in love on-line.").getId(); + final String billyC = saveActor(actors, "BillyC", "Billy Crystal", 1948).getId(); + final String carrieF = saveActor(actors, "CarrieF", "Carrie Fisher", 1956).getId(); + final String brunoK = saveActor(actors, "BrunoK", "Bruno Kirby", 1949).getId(); + saveActsIn(actsIn, billyC, whenHarryMetSally, new String[] { "Harry Burns" }, 1998); + saveActsIn(actsIn, megR, whenHarryMetSally, new String[] { "Sally Albright" }, 1998); + saveActsIn(actsIn, carrieF, whenHarryMetSally, new String[] { "Marie" }, 1998); + saveActsIn(actsIn, brunoK, whenHarryMetSally, new String[] { "Jess" }, 1998); + } + +} diff --git a/src/test/java/com/arangodb/example/graph/BaseExample.java b/src/test/java/com/arangodb/example/graph/BaseExample.java deleted file mode 100644 index d637673be..000000000 --- a/src/test/java/com/arangodb/example/graph/BaseExample.java +++ /dev/null @@ -1,150 +0,0 @@ -/* - * Copyright (C) 2015 ArangoDB GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.example.graph; - -import java.util.ArrayList; -import java.util.List; - -import org.junit.Assert; - -import com.arangodb.ArangoDriver; -import com.arangodb.ArangoException; -import com.arangodb.BaseTest; -import com.arangodb.entity.ArangoVersion; -import com.arangodb.entity.BooleanResultEntity; -import com.arangodb.entity.CollectionEntity; -import com.arangodb.entity.CollectionOptions; -import com.arangodb.entity.CollectionType; -import com.arangodb.entity.EdgeDefinitionEntity; -import com.arangodb.entity.GraphEntity; -import com.arangodb.util.TestUtils; - -public class BaseExample extends BaseTest { - - protected void removeTestDatabase(final String name) { - try { - driver.deleteDatabase(name); - } catch (final Exception e) { - } - } - - protected void createDatabase(final ArangoDriver arangoDriver, final String name) { - try { - final BooleanResultEntity createDatabase = arangoDriver.createDatabase(name); - Assert.assertNotNull(createDatabase); - Assert.assertNotNull(createDatabase.getResult()); - Assert.assertTrue(createDatabase.getResult()); - } catch (final Exception e) { - Assert.fail("Failed to create database " + name + "; " + e.getMessage()); - } - - arangoDriver.setDefaultDatabase(name); - } - - protected void deleteDatabase(final ArangoDriver arangoDriver, final String name) { - try { - arangoDriver.deleteDatabase(name); - } catch (final Exception e) { - } - } - - protected void createCollection(final ArangoDriver arangoDriver, final String name) { - try { - final CollectionEntity createCollection = arangoDriver.createCollection(name); - Assert.assertNotNull(createCollection); - Assert.assertNotNull(createCollection.getName()); - Assert.assertEquals(name, createCollection.getName()); - } catch (final ArangoException e) { - Assert.fail("create collection failed. " + e.getMessage()); - } - } - - protected void printEntity(final Object object) { - if (object == null) { - System.out.println("Document not found"); - } else { - System.out.println(object); - } - } - - protected void printHeadline(final String name) { - System.out.println("---------------------------------------------"); - System.out.println(name); - System.out.println("---------------------------------------------"); - } - - public void createGraph( - final ArangoDriver arangoDriver, - final String grapName, - final String nameEdgeCollection, - final String nameVertexCollection) throws ArangoException { - - // - printHeadline("create edge collection"); - // - - CollectionEntity createCollection = arangoDriver.createCollection(nameEdgeCollection, - new CollectionOptions().setType(CollectionType.EDGE)); - Assert.assertNotNull(createCollection); - Assert.assertNotNull(createCollection.getId()); - Assert.assertTrue(createCollection.getId() > 0L); - - // - printHeadline("create vertex collection"); - // - - createCollection = arangoDriver.createCollection(nameVertexCollection, - new CollectionOptions().setType(CollectionType.DOCUMENT)); - Assert.assertNotNull(createCollection); - Assert.assertNotNull(createCollection.getId()); - Assert.assertTrue(createCollection.getId() > 0L); - - // - printHeadline("create edge definition"); - // - - final EdgeDefinitionEntity ed = new EdgeDefinitionEntity(); - // add edge collection name - ed.setCollection(nameEdgeCollection); - - // add vertex collection names - ed.getFrom().add(nameVertexCollection); - - // add vertex collection names - ed.getTo().add(nameVertexCollection); - - // - printHeadline("create edge definition list"); - // - final List edgeDefinitions = new ArrayList(); - edgeDefinitions.add(ed); - - // - printHeadline("create graph"); - // - final GraphEntity createGraph = arangoDriver.createGraph(grapName, edgeDefinitions, null, true); - Assert.assertNotNull(createGraph); - Assert.assertEquals(grapName, createGraph.getName()); - } - - public boolean isMinimumVersion(final ArangoDriver arangoDriver, final String version) throws ArangoException { - final ArangoVersion ver = arangoDriver.getVersion(); - final int b = TestUtils.compareVersion(ver.getVersion(), version); - return b > -1; - } - -} diff --git a/src/test/java/com/arangodb/example/graph/BaseGraphTest.java b/src/test/java/com/arangodb/example/graph/BaseGraphTest.java new file mode 100644 index 000000000..19be066ad --- /dev/null +++ b/src/test/java/com/arangodb/example/graph/BaseGraphTest.java @@ -0,0 +1,118 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.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.EdgeEntity; +import com.arangodb.entity.VertexEntity; + +/** + * @author Mark - mark at arangodb.com + * + */ +public abstract class BaseGraphTest { + + protected static final String TEST_DB = "java_driver_graph_test_db"; + protected static ArangoDB arangoDB; + protected static ArangoDatabase db; + protected static final String GRAPH_NAME = "traversalGraph"; + protected static final String EDGE_COLLECTION_NAME = "edges"; + protected static final String VERTEXT_COLLECTION_NAME = "circles"; + + @BeforeClass + public static void init() { + if (arangoDB == null) { + arangoDB = new ArangoDB.Builder().build(); + } + try { + arangoDB.db(TEST_DB).drop(); + } catch (final ArangoDBException e) { + } + arangoDB.createDatabase(TEST_DB); + BaseGraphTest.db = arangoDB.db(TEST_DB); + + final Collection edgeDefinitions = new ArrayList(); + final EdgeDefinition edgeDefinition = new EdgeDefinition().collection(EDGE_COLLECTION_NAME) + .from(VERTEXT_COLLECTION_NAME).to(VERTEXT_COLLECTION_NAME); + edgeDefinitions.add(edgeDefinition); + try { + db.createGraph(GRAPH_NAME, edgeDefinitions, null); + addExampleElements(); + } catch (final ArangoDBException ex) { + + } + } + + @AfterClass + public static void shutdown() { + arangoDB.db(TEST_DB).drop(); + arangoDB.shutdown(); + arangoDB = null; + } + + private static void addExampleElements() throws ArangoDBException { + + // Add circle circles + final VertexEntity vA = createVertex(new Circle("A", "1")); + final VertexEntity vB = createVertex(new Circle("B", "2")); + final VertexEntity vC = createVertex(new Circle("C", "3")); + final VertexEntity vD = createVertex(new Circle("D", "4")); + final VertexEntity vE = createVertex(new Circle("E", "5")); + final VertexEntity vF = createVertex(new Circle("F", "6")); + final VertexEntity vG = createVertex(new Circle("G", "7")); + final VertexEntity vH = createVertex(new Circle("H", "8")); + final VertexEntity vI = createVertex(new Circle("I", "9")); + final VertexEntity vJ = createVertex(new Circle("J", "10")); + final VertexEntity vK = createVertex(new Circle("K", "11")); + + // Add relevant edges - left branch: + saveEdge(new CircleEdge(vA.getId(), vB.getId(), false, true, "left_bar")); + saveEdge(new CircleEdge(vB.getId(), vC.getId(), false, true, "left_blarg")); + saveEdge(new CircleEdge(vC.getId(), vD.getId(), false, true, "left_blorg")); + saveEdge(new CircleEdge(vB.getId(), vE.getId(), false, true, "left_blub")); + saveEdge(new CircleEdge(vE.getId(), vF.getId(), false, true, "left_schubi")); + + // Add relevant edges - right branch: + saveEdge(new CircleEdge(vA.getId(), vG.getId(), false, true, "right_foo")); + saveEdge(new CircleEdge(vG.getId(), vH.getId(), false, true, "right_blob")); + saveEdge(new CircleEdge(vH.getId(), vI.getId(), false, true, "right_blub")); + saveEdge(new CircleEdge(vG.getId(), vJ.getId(), false, true, "right_zip")); + saveEdge(new CircleEdge(vJ.getId(), vK.getId(), false, true, "right_zup")); + } + + private static EdgeEntity saveEdge(final CircleEdge edge) throws ArangoDBException { + return db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).insertEdge(edge); + } + + private static VertexEntity createVertex(final Circle vertex) throws ArangoDBException { + return db.graph(GRAPH_NAME).vertexCollection(VERTEXT_COLLECTION_NAME).insertVertex(vertex); + } + +} diff --git a/src/test/java/com/arangodb/example/graph/Circle.java b/src/test/java/com/arangodb/example/graph/Circle.java index bd98e8443..3c2e48ff7 100644 --- a/src/test/java/com/arangodb/example/graph/Circle.java +++ b/src/test/java/com/arangodb/example/graph/Circle.java @@ -1,85 +1,80 @@ /* - * Copyright (C) 2015 ArangoDB GmbH + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany */ package com.arangodb.example.graph; -import com.arangodb.entity.BaseDocument; -import com.google.gson.annotations.SerializedName; +import com.arangodb.entity.DocumentField; +import com.arangodb.entity.DocumentField.Type; /** - * A person class. - * - * The document person class has attributes to store the document key, id and - * revision. - * * @author a-brandt * */ public class Circle { - @SerializedName(BaseDocument.ID) - private String documentHandle; + @DocumentField(Type.ID) + private String id; - @SerializedName(BaseDocument.KEY) - private String documentKey; + @DocumentField(Type.KEY) + private String key; - @SerializedName(BaseDocument.REV) - private String documentRevision; + @DocumentField(Type.REV) + private String revision; private String label; - public Circle() { - - } - - public Circle(final String documentKey, final String label) { - this.documentKey = documentKey; + public Circle(String key, String label) { + this.key = key; this.label = label; } - public String getLabel() { - return label; + public String getId() { + return id; } - public void setLabel(final String label) { - this.label = label; + public void setId(String id) { + this.id = id; } - public String getDocumentHandle() { - return documentHandle; + public String getKey() { + return key; } - public void setDocumentHandle(final String documentHandle) { - this.documentHandle = documentHandle; + public void setKey(String key) { + this.key = key; } - public String getDocumentKey() { - return documentKey; + public String getRevision() { + return revision; } - public void setDocumentKey(final String documentKey) { - this.documentKey = documentKey; + public void setRevision(String revision) { + this.revision = revision; } - public String getDocumentRevision() { - return documentRevision; + public String getLabel() { + return label; } - public void setDocumentRevision(final String documentRevision) { - this.documentRevision = documentRevision; + 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 7854b47eb..dfcc0dc54 100644 --- a/src/test/java/com/arangodb/example/graph/CircleEdge.java +++ b/src/test/java/com/arangodb/example/graph/CircleEdge.java @@ -1,116 +1,124 @@ /* - * Copyright (C) 2015 ArangoDB GmbH + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany */ package com.arangodb.example.graph; -import com.arangodb.entity.BaseDocument; -import com.google.gson.annotations.SerializedName; +import com.arangodb.entity.DocumentField; +import com.arangodb.entity.DocumentField.Type; +/** + * @author a-brandt + * + */ public class CircleEdge { - @SerializedName(BaseDocument.ID) - private String documentHandle; + @DocumentField(Type.ID) + private String id; - @SerializedName(BaseDocument.KEY) - private String documentKey; + @DocumentField(Type.KEY) + private String key; - @SerializedName(BaseDocument.REV) - private String documentRevision; + @DocumentField(Type.REV) + private String revision; - @SerializedName(BaseDocument.FROM) - String fromVertexHandle; + @DocumentField(Type.FROM) + private String from; - @SerializedName(BaseDocument.TO) - String toVertexHandle; + @DocumentField(Type.TO) + private String to; private Boolean theFalse; private Boolean theTruth; private String label; - public CircleEdge() { - } - - public CircleEdge(final Boolean theFalse, final Boolean theTruth, final 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 Boolean getTheFalse() { - return theFalse; + public String getId() { + return id; } - public void setTheFalse(final Boolean theFalse) { - this.theFalse = theFalse; + public void setId(String id) { + this.id = id; } - public Boolean getTheTruth() { - return theTruth; + public String getKey() { + return key; } - public void setTheTruth(final Boolean theTruth) { - this.theTruth = theTruth; + public void setKey(String key) { + this.key = key; } - public String getLabel() { - return label; + public String getRevision() { + return revision; } - public void setLabel(final String label) { - this.label = label; + public void setRevision(String revision) { + this.revision = revision; } - public String getDocumentHandle() { - return documentHandle; + public String getFrom() { + return from; } - public void setDocumentHandle(final String documentHandle) { - this.documentHandle = documentHandle; + public void setFrom(String from) { + this.from = from; } - public String getDocumentKey() { - return documentKey; + public String getTo() { + return to; } - public void setDocumentKey(final String documentKey) { - this.documentKey = documentKey; + public void setTo(String to) { + this.to = to; } - public String getDocumentRevision() { - return documentRevision; + public Boolean getTheFalse() { + return theFalse; } - public void setDocumentRevision(final String documentRevision) { - this.documentRevision = documentRevision; + public void setTheFalse(Boolean theFalse) { + this.theFalse = theFalse; } - public String getFromVertexHandle() { - return fromVertexHandle; + public Boolean getTheTruth() { + return theTruth; } - public String getToVertexHandle() { - return toVertexHandle; + public void setTheTruth(Boolean theTruth) { + this.theTruth = theTruth; } - public void setFromVertexHandle(final String fromVertexHandle) { - this.fromVertexHandle = fromVertexHandle; + public String getLabel() { + return label; } - public void setToVertexHandle(final String toVertexHandle) { - this.toVertexHandle = toVertexHandle; + public void setLabel(String label) { + this.label = label; } } diff --git a/src/test/java/com/arangodb/example/graph/CreateGraphExample.java b/src/test/java/com/arangodb/example/graph/CreateGraphExample.java deleted file mode 100644 index d07eb8e72..000000000 --- a/src/test/java/com/arangodb/example/graph/CreateGraphExample.java +++ /dev/null @@ -1,111 +0,0 @@ -/* - * Copyright (C) 2015 ArangoDB GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.example.graph; - -import java.util.ArrayList; -import java.util.List; - -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import com.arangodb.ArangoException; -import com.arangodb.entity.CollectionEntity; -import com.arangodb.entity.CollectionOptions; -import com.arangodb.entity.CollectionType; -import com.arangodb.entity.EdgeDefinitionEntity; -import com.arangodb.entity.GraphEntity; - -/** - * Create graph example - * - * @author a-brandt - * - */ -public class CreateGraphExample extends BaseExample { - - private static final String DATABASE_NAME = "CreateGraphExample"; - - private static final String GRAPH_NAME = "example_graph1"; - private static final String EDGE_COLLECTION_NAME = "edgeColl1"; - private static final String VERTEXT_COLLECTION_NAME = "vertexColl1"; - - @Before - public void _before() { - removeTestDatabase(DATABASE_NAME); - - createDatabase(driver, DATABASE_NAME); - } - - @After - public void _after() { - removeTestDatabase(DATABASE_NAME); - } - - @Test - public void createGraph() throws ArangoException { - - // - printHeadline("create edge collection"); - // - - CollectionEntity createCollection = driver.createCollection(EDGE_COLLECTION_NAME, - new CollectionOptions().setType(CollectionType.EDGE)); - Assert.assertNotNull(createCollection); - Assert.assertNotNull(createCollection.getId()); - Assert.assertTrue(createCollection.getId() > 0L); - - // - printHeadline("create vertex collection"); - // - - createCollection = driver.createCollection(VERTEXT_COLLECTION_NAME, - new CollectionOptions().setType(CollectionType.DOCUMENT)); - Assert.assertNotNull(createCollection); - Assert.assertNotNull(createCollection.getId()); - Assert.assertTrue(createCollection.getId() > 0L); - - // - printHeadline("create edge definition"); - // - - final EdgeDefinitionEntity ed = new EdgeDefinitionEntity(); - // add edge collection name - ed.setCollection(EDGE_COLLECTION_NAME); - - // add vertex collection names - ed.getFrom().add(VERTEXT_COLLECTION_NAME); - - // add vertex collection names - ed.getTo().add(VERTEXT_COLLECTION_NAME); - - // - printHeadline("create edge definition list"); - // - final List edgeDefinitions = new ArrayList(); - edgeDefinitions.add(ed); - - // - printHeadline("create graph"); - // - final GraphEntity createGraph = driver.createGraph(GRAPH_NAME, edgeDefinitions, null, true); - Assert.assertNotNull(createGraph); - Assert.assertEquals(GRAPH_NAME, createGraph.getName()); - } - -} diff --git a/src/test/java/com/arangodb/example/graph/CreateVerticesAndEdgesExample.java b/src/test/java/com/arangodb/example/graph/CreateVerticesAndEdgesExample.java deleted file mode 100644 index af6570b21..000000000 --- a/src/test/java/com/arangodb/example/graph/CreateVerticesAndEdgesExample.java +++ /dev/null @@ -1,106 +0,0 @@ -/* - * Copyright (C) 2015 ArangoDB GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.example.graph; - -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import com.arangodb.ArangoException; -import com.arangodb.entity.EdgeEntity; -import com.arangodb.entity.marker.VertexEntity; - -/** - * AQL example creating vertices and edges - * - * @author a-brandt - * - */ -public class CreateVerticesAndEdgesExample extends BaseExample { - - private static final String DATABASE_NAME = "CreateVerticesAndEdgesExample"; - - private static final String GRAPH_NAME = "example_graph1"; - private static final String EDGE_COLLECTION_NAME = "edgeColl1"; - private static final String VERTEXT_COLLECTION_NAME = "vertexColl1"; - - @Before - public void _before() throws ArangoException { - removeTestDatabase(DATABASE_NAME); - - createDatabase(driver, DATABASE_NAME); - createGraph(driver, GRAPH_NAME, EDGE_COLLECTION_NAME, VERTEXT_COLLECTION_NAME); - } - - @After - public void _after() { - removeTestDatabase(DATABASE_NAME); - } - - @Test - public void verticesAndEdges() throws ArangoException { - - // - printHeadline("create two vertices"); - // - - // create some persons - final Person personA = new Person("A", Person.MALE); - final VertexEntity v1 = driver.graphCreateVertex(GRAPH_NAME, VERTEXT_COLLECTION_NAME, personA, true); - Assert.assertNotNull(v1); - Assert.assertNotNull(v1.getEntity()); - Person p = v1.getEntity(); - Assert.assertEquals(personA.getName(), p.getName()); - Assert.assertNotNull(p.getDocumentHandle()); - Assert.assertNotNull(p.getDocumentKey()); - Assert.assertNotNull(p.getDocumentRevision()); - - final Person personB = new Person("B", Person.MALE); - final VertexEntity v2 = driver.graphCreateVertex(GRAPH_NAME, VERTEXT_COLLECTION_NAME, personB, false); - Assert.assertNotNull(v2); - Assert.assertNotNull(v2.getEntity()); - p = v2.getEntity(); - Assert.assertEquals(personB.getName(), p.getName()); - Assert.assertNotNull(p.getDocumentHandle()); - Assert.assertNotNull(p.getDocumentKey()); - Assert.assertNotNull(p.getDocumentRevision()); - - // - printHeadline("create edge"); - // - - final Knows knows = new Knows(1984); - final EdgeEntity graphCreateEdge = driver.graphCreateEdge(GRAPH_NAME, EDGE_COLLECTION_NAME, - v1.getDocumentHandle(), v2.getDocumentHandle(), knows, false); - - Assert.assertNotNull(graphCreateEdge); - final Knows entity = graphCreateEdge.getEntity(); - Assert.assertNotNull(entity); - Assert.assertNotNull(entity.getDocumentHandle()); - Assert.assertNotNull(entity.getDocumentKey()); - Assert.assertNotNull(entity.getDocumentRevision()); - Assert.assertNotNull(entity.getFromVertexHandle()); - Assert.assertNotNull(entity.getToVertexHandle()); - Assert.assertNotNull(entity.getSince()); - Assert.assertEquals(v1.getDocumentHandle(), entity.getFromVertexHandle()); - Assert.assertEquals(v2.getDocumentHandle(), entity.getToVertexHandle()); - Assert.assertEquals(knows.getSince(), entity.getSince()); - - } - -} diff --git a/src/test/java/com/arangodb/example/graph/DeleteVerticesAndEdgesExample.java b/src/test/java/com/arangodb/example/graph/DeleteVerticesAndEdgesExample.java deleted file mode 100644 index 161570632..000000000 --- a/src/test/java/com/arangodb/example/graph/DeleteVerticesAndEdgesExample.java +++ /dev/null @@ -1,103 +0,0 @@ -package com.arangodb.example.graph; - -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import com.arangodb.ArangoException; -import com.arangodb.ErrorNums; -import com.arangodb.entity.DeletedEntity; -import com.arangodb.entity.EdgeEntity; -import com.arangodb.entity.marker.VertexEntity; - -/** - * Delete vertices and edges example - * - * @author a-brandt - * - */ -public class DeleteVerticesAndEdgesExample extends BaseExample { - - private static final String DATABASE_NAME = "DeleteVerticesAndEdgesExample"; - - private static final String GRAPH_NAME = "example_graph1"; - private static final String EDGE_COLLECTION_NAME = "edgeColl1"; - private static final String VERTEXT_COLLECTION_NAME = "vertexColl1"; - - @Before - public void _before() throws ArangoException { - removeTestDatabase(DATABASE_NAME); - - createDatabase(driver, DATABASE_NAME); - createGraph(driver, GRAPH_NAME, EDGE_COLLECTION_NAME, VERTEXT_COLLECTION_NAME); - } - - @After - public void _after() { - removeTestDatabase(DATABASE_NAME); - } - - @Test - public void deleteVertex() throws ArangoException { - - // - printHeadline("delete vertex"); - // - - final VertexEntity v1 = createVertex(new Person("A", Person.MALE)); - - final DeletedEntity deletedEntity = driver.graphDeleteVertex(GRAPH_NAME, VERTEXT_COLLECTION_NAME, - v1.getDocumentKey()); - Assert.assertNotNull(deletedEntity); - Assert.assertTrue(deletedEntity.getDeleted()); - - try { - driver.graphGetVertex(GRAPH_NAME, VERTEXT_COLLECTION_NAME, v1.getDocumentKey(), Person.class); - Assert.fail("graphGetVertex should fail"); - } catch (final ArangoException ex) { - Assert.assertEquals(ErrorNums.ERROR_ARANGO_DOCUMENT_NOT_FOUND, ex.getErrorNumber()); - } - } - - @Test - public void getEdge() throws ArangoException { - - // - printHeadline("delete edge"); - // - - final VertexEntity v1 = createVertex(new Person("A", Person.MALE)); - final VertexEntity v2 = createVertex(new Person("B", Person.FEMALE)); - final EdgeEntity e1 = createEdge(v1, v2, new Knows(1984)); - - final DeletedEntity deletedEntity = driver.graphDeleteEdge(GRAPH_NAME, EDGE_COLLECTION_NAME, - e1.getDocumentKey()); - Assert.assertNotNull(deletedEntity); - Assert.assertTrue(deletedEntity.getDeleted()); - - try { - driver.graphGetEdge(GRAPH_NAME, EDGE_COLLECTION_NAME, e1.getDocumentKey(), Knows.class); - Assert.fail("graphGetEdge should fail"); - } catch (final ArangoException ex) { - Assert.assertEquals(ErrorNums.ERROR_ARANGO_DOCUMENT_NOT_FOUND, ex.getErrorNumber()); - } - } - - private VertexEntity createVertex(final Person person) throws ArangoException { - final VertexEntity v = driver.graphCreateVertex(GRAPH_NAME, VERTEXT_COLLECTION_NAME, person, true); - Assert.assertNotNull(v); - return v; - } - - private EdgeEntity createEdge( - final VertexEntity personFrom, - final VertexEntity personTo, - final Knows knows) throws ArangoException { - final EdgeEntity e = driver.graphCreateEdge(GRAPH_NAME, EDGE_COLLECTION_NAME, - personFrom.getDocumentHandle(), personTo.getDocumentHandle(), knows, false); - Assert.assertNotNull(e); - return e; - } - -} diff --git a/src/test/java/com/arangodb/example/graph/GetVerticesAndEdgesExample.java b/src/test/java/com/arangodb/example/graph/GetVerticesAndEdgesExample.java deleted file mode 100644 index 41b1156e4..000000000 --- a/src/test/java/com/arangodb/example/graph/GetVerticesAndEdgesExample.java +++ /dev/null @@ -1,286 +0,0 @@ -package com.arangodb.example.graph; - -import java.util.Iterator; -import java.util.List; - -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import com.arangodb.ArangoException; -import com.arangodb.Direction; -import com.arangodb.EdgeCursor; -import com.arangodb.VertexCursor; -import com.arangodb.entity.EdgeEntity; -import com.arangodb.entity.marker.VertexEntity; -import com.arangodb.util.GraphEdgesOptions; - -/** - * Get vertices and edges example - * - * @author a-brandt - * - */ -public class GetVerticesAndEdgesExample extends BaseExample { - - private static final String DATABASE_NAME = "GetVerticesAndEdgesExample"; - - private static final String GRAPH_NAME = "example_graph1"; - private static final String EDGE_COLLECTION_NAME = "edgeColl1"; - private static final String VERTEXT_COLLECTION_NAME = "vertexColl1"; - - @Before - public void _before() throws ArangoException { - removeTestDatabase(DATABASE_NAME); - - createDatabase(driver, DATABASE_NAME); - createGraph(driver, GRAPH_NAME, EDGE_COLLECTION_NAME, VERTEXT_COLLECTION_NAME); - } - - @After - public void _after() { - removeTestDatabase(DATABASE_NAME); - } - - @Test - public void getVertex() throws ArangoException { - - // - printHeadline("get vertex"); - // - - final Person personA = new Person("A", Person.MALE); - final VertexEntity v1 = createVertex(personA); - - final VertexEntity vertexEntity = driver.graphGetVertex(GRAPH_NAME, VERTEXT_COLLECTION_NAME, - v1.getDocumentKey(), Person.class); - - Assert.assertNotNull(vertexEntity); - Assert.assertNotNull(vertexEntity.getEntity()); - final Person p = vertexEntity.getEntity(); - Assert.assertEquals(personA.getName(), p.getName()); - Assert.assertNotNull(p.getDocumentHandle()); - Assert.assertNotNull(p.getDocumentKey()); - Assert.assertNotNull(p.getDocumentRevision()); - } - - @Test - public void getVertices() throws ArangoException { - - // - printHeadline("get all vertices"); - // - - createVertex(new Person("A", Person.MALE)); - createVertex(new Person("B", Person.FEMALE)); - - // - printHeadline("using the cursor iterator"); - // - - VertexCursor vertexCursor = driver.graphGetVertexCursor(GRAPH_NAME, Person.class, null, null, null); - Assert.assertNotNull(vertexCursor); - - final Iterator> iterator = vertexCursor.iterator(); - while (iterator.hasNext()) { - final VertexEntity next = iterator.next(); - Assert.assertNotNull(next); - printPerson(next.getEntity()); - } - - // - printHeadline("using the cursor entity iterator"); - // - - vertexCursor = driver.graphGetVertexCursor(GRAPH_NAME, Person.class, null, null, null); - Assert.assertNotNull(vertexCursor); - - final Iterator entityIterator = vertexCursor.entityIterator(); - while (entityIterator.hasNext()) { - final Person next = entityIterator.next(); - Assert.assertNotNull(next); - printPerson(next); - } - - // - printHeadline("using cursor as list"); - // - - vertexCursor = driver.graphGetVertexCursor(GRAPH_NAME, Person.class, null, null, null); - Assert.assertNotNull(vertexCursor); - - final List> entityList = vertexCursor.asList(); - - for (final VertexEntity next : entityList) { - Assert.assertNotNull(next); - printPerson(next.getEntity()); - } - - // - printHeadline("using cursor as entity list"); - // - - vertexCursor = driver.graphGetVertexCursor(GRAPH_NAME, Person.class, null, null, null); - Assert.assertNotNull(vertexCursor); - - final List personList = vertexCursor.asEntityList(); - - for (final Person next : personList) { - Assert.assertNotNull(next); - printPerson(next); - } - - } - - @Test - public void getVerticesByExample() throws ArangoException { - - // - printHeadline("get vertices by example"); - // - - createVertex(new Person("A", Person.MALE)); - createVertex(new Person("B", Person.FEMALE)); - createVertex(new Person("C", Person.MALE)); - - // get all male persons - final Person example = new Person(null, Person.MALE); - - final VertexCursor vertexCursor = driver.graphGetVertexCursor(GRAPH_NAME, Person.class, example, null, - null); - Assert.assertNotNull(vertexCursor); - - final List personList = vertexCursor.asEntityList(); - Assert.assertEquals(2, personList.size()); - - for (final Person next : personList) { - Assert.assertNotNull(next); - printPerson(next); - } - - } - - @Test - public void getEdge() throws ArangoException { - - // - printHeadline("get edge"); - // - - final VertexEntity v1 = createVertex(new Person("A", Person.MALE)); - final VertexEntity v2 = createVertex(new Person("B", Person.FEMALE)); - final Knows knows = new Knows(1984); - final EdgeEntity e1 = createEdge(v1, v2, knows); - - final EdgeEntity edgeEntity = driver.graphGetEdge(GRAPH_NAME, EDGE_COLLECTION_NAME, e1.getDocumentKey(), - Knows.class); - Assert.assertNotNull(edgeEntity); - final Knows entity = edgeEntity.getEntity(); - Assert.assertNotNull(entity); - Assert.assertNotNull(entity.getDocumentHandle()); - Assert.assertNotNull(entity.getDocumentKey()); - Assert.assertNotNull(entity.getDocumentRevision()); - Assert.assertNotNull(entity.getFromVertexHandle()); - Assert.assertNotNull(entity.getToVertexHandle()); - Assert.assertNotNull(entity.getSince()); - Assert.assertEquals(v1.getDocumentHandle(), entity.getFromVertexHandle()); - Assert.assertEquals(v2.getDocumentHandle(), entity.getToVertexHandle()); - Assert.assertEquals(knows.getSince(), entity.getSince()); - } - - @Test - public void getEdges() throws ArangoException { - - // - printHeadline("get all edges"); - // - - final VertexEntity v1 = createVertex(new Person("A", Person.MALE)); - final VertexEntity v2 = createVertex(new Person("B", Person.FEMALE)); - createEdge(v1, v2, new Knows(1984)); - final VertexEntity v3 = createVertex(new Person("C", Person.MALE)); - createEdge(v1, v3, new Knows(1995)); - createEdge(v2, v3, new Knows(2005)); - - final EdgeCursor cursor = driver.graphGetEdgeCursor(GRAPH_NAME, Knows.class, null, null, null); - final List list = cursor.asEntityList(); - Assert.assertEquals(3, list.size()); - - for (final Knows knows : list) { - printKnows(knows); - } - } - - @Test - public void getEdgesByVertexExample() throws ArangoException { - - // - printHeadline("get edges by vertex example"); - // - - final VertexEntity v1 = createVertex(new Person("A", Person.MALE)); - final VertexEntity v2 = createVertex(new Person("B", Person.FEMALE)); - createEdge(v1, v2, new Knows(1984)); - final VertexEntity v3 = createVertex(new Person("C", Person.MALE)); - createEdge(v1, v3, new Knows(1995)); - createEdge(v2, v3, new Knows(2005)); - - // get all edges of female persons (inbound and outbound) - final Person example = new Person(null, Person.FEMALE); - - EdgeCursor cursor = driver.graphGetEdgeCursor(GRAPH_NAME, Knows.class, example, null, null); - List list = cursor.asEntityList(); - Assert.assertEquals(2, list.size()); - - for (final Knows knows : list) { - printKnows(knows); - } - - // get all edges of female persons (outbound) - final GraphEdgesOptions graphEdgesOptions = new GraphEdgesOptions().setDirection(Direction.OUTBOUND); - - cursor = driver.graphGetEdgeCursor(GRAPH_NAME, Knows.class, example, graphEdgesOptions, null); - list = cursor.asEntityList(); - Assert.assertEquals(1, list.size()); - - for (final Knows knows : list) { - printKnows(knows); - } - - } - - private VertexEntity createVertex(final Person person) throws ArangoException { - final VertexEntity v = driver.graphCreateVertex(GRAPH_NAME, VERTEXT_COLLECTION_NAME, person, true); - Assert.assertNotNull(v); - return v; - } - - private EdgeEntity createEdge( - final VertexEntity personFrom, - final VertexEntity personTo, - final Knows knows) throws ArangoException { - final EdgeEntity e = driver.graphCreateEdge(GRAPH_NAME, EDGE_COLLECTION_NAME, - personFrom.getDocumentHandle(), personTo.getDocumentHandle(), knows, false); - Assert.assertNotNull(e); - return e; - } - - private void printPerson(final Person person) { - if (person == null) { - System.out.println("Person is null"); - } else { - System.out - .println("Person " + person.getDocumentKey() + ", " + person.getName() + ", " + person.getGender()); - } - } - - private void printKnows(final Knows knows) { - if (knows == null) { - System.out.println("Knows is null"); - } else { - System.out.println("Knows " + knows.getDocumentKey() + ", " + knows.fromVertexHandle + " -> " - + knows.toVertexHandle + " = " + knows.getSince()); - } - } -} diff --git a/src/test/java/com/arangodb/example/graph/GraphAqlQueryExample.java b/src/test/java/com/arangodb/example/graph/GraphAqlQueryExample.java deleted file mode 100644 index eb8b1289e..000000000 --- a/src/test/java/com/arangodb/example/graph/GraphAqlQueryExample.java +++ /dev/null @@ -1,220 +0,0 @@ -/* - * Copyright (C) 2015 ArangoDB GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.example.graph; - -import java.util.Iterator; - -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import com.arangodb.ArangoException; -import com.arangodb.Direction; -import com.arangodb.EdgeCursor; -import com.arangodb.VertexCursor; -import com.arangodb.entity.EdgeEntity; -import com.arangodb.entity.ShortestPathEntity; -import com.arangodb.entity.marker.VertexEntity; -import com.arangodb.util.GraphEdgesOptions; -import com.arangodb.util.ShortestPathOptions; - -/** - * AQL example with new cursor implementation - * - * @author a-brandt - * - */ -public class GraphAqlQueryExample extends BaseExample { - - private static final String DATABASE_NAME = "GraphAqlQueryExample"; - - private static final String GRAPH_NAME = "example_graph1"; - private static final String EDGE_COLLECTION_NAME = "edgeColl1"; - private static final String VERTEXT_COLLECTION_NAME = "vertexColl1"; - - @Before - public void _before() throws ArangoException { - removeTestDatabase(DATABASE_NAME); - - createDatabase(driver, DATABASE_NAME); - createGraph(driver, GRAPH_NAME, EDGE_COLLECTION_NAME, VERTEXT_COLLECTION_NAME); - addExampleElements(); - } - - @After - public void _after() { - removeTestDatabase(DATABASE_NAME); - } - - @Test - public void graphAqlQuery() throws ArangoException { - - // - printHeadline("get all vertices"); - // - - int count = 0; - VertexCursor vertexCursor = driver.graphGetVertexCursor(GRAPH_NAME, Person.class, null, null, null); - Assert.assertNotNull(vertexCursor); - - Iterator> vertexIterator = vertexCursor.iterator(); - while (vertexIterator.hasNext()) { - final VertexEntity entity = vertexIterator.next(); - Assert.assertNotNull(entity); - - final Person person = entity.getEntity(); - Assert.assertNotNull(person); - - System.out.printf("%d\t%20s %15s%n", ++count, entity.getDocumentHandle(), person.getName()); - } - Assert.assertEquals(6, count); - - // - printHeadline("get vertices by example"); - // - - count = 0; - vertexCursor = driver.graphGetVertexCursor(GRAPH_NAME, Person.class, new Person("Christoph", null), null, null); - Assert.assertNotNull(vertexCursor); - - vertexIterator = vertexCursor.iterator(); - while (vertexIterator.hasNext()) { - final VertexEntity entity = vertexIterator.next(); - Assert.assertNotNull(entity); - - final Person person = entity.getEntity(); - - Assert.assertNotNull(person); - System.out.printf("%d\t%20s %15s%n", ++count, entity.getDocumentHandle(), person.getName()); - } - Assert.assertEquals(1, count); - - // - printHeadline("get all edges"); - // - - count = 0; - EdgeCursor edgeCursor = driver.graphGetEdgeCursor(GRAPH_NAME, Knows.class, null, null, null); - Assert.assertNotNull(edgeCursor); - - Iterator> edgeIterator = edgeCursor.iterator(); - while (edgeIterator.hasNext()) { - final EdgeEntity entity = edgeIterator.next(); - Assert.assertNotNull(entity); - - final Knows knows = entity.getEntity(); - Assert.assertNotNull(knows); - - System.out.printf("%d\t%20s %20s->%20s %d%n", ++count, entity.getDocumentHandle(), - entity.getFromVertexHandle(), entity.getToVertexHandle(), knows.getSince()); - } - Assert.assertEquals(7, count); - - // - printHeadline("get all outbound edges of a vertex"); - // - - count = 0; - edgeCursor = driver.graphGetEdgeCursor(GRAPH_NAME, Knows.class, new Person("Christoph", Person.MALE), - new GraphEdgesOptions().setDirection(Direction.OUTBOUND), null); - Assert.assertNotNull(edgeCursor); - - edgeIterator = edgeCursor.iterator(); - while (edgeIterator.hasNext()) { - final EdgeEntity entity = edgeIterator.next(); - Assert.assertNotNull(entity); - - final Knows knows = entity.getEntity(); - Assert.assertNotNull(knows); - System.out.printf("%d\t%20s %20s->%20s %d%n", ++count, entity.getDocumentHandle(), - entity.getFromVertexHandle(), entity.getToVertexHandle(), knows.getSince()); - } - Assert.assertEquals(2, count); - - // - printHeadline("get shortest path"); - // - - // path Anton -> Frauke - ShortestPathEntity shortestPath = driver.graphGetShortestPath(GRAPH_NAME, - new Person("Anton", Person.MALE), new Person("Frauke", Person.FEMALE), - new ShortestPathOptions().setDirection(Direction.OUTBOUND), Person.class, Knows.class); - Assert.assertNotNull(shortestPath); - - printShortestPath(shortestPath); - Assert.assertEquals(new Long(2L), shortestPath.getDistance()); - - // - printHeadline("get shortest path (empty)"); - // - - // path Frauke -> Anton (empty result) - shortestPath = driver.graphGetShortestPath(GRAPH_NAME, new Person("Frauke", Person.FEMALE), - new Person("Anton", Person.MALE), new ShortestPathOptions().setDirection(Direction.OUTBOUND), Person.class, - Knows.class); - Assert.assertNotNull(shortestPath); - - printShortestPath(shortestPath); - // no path found (distance = -1) - Assert.assertEquals(new Long(-1), shortestPath.getDistance()); - - } - - private void printShortestPath(final ShortestPathEntity shortestPath) { - if (shortestPath.getDistance() > -1) { - System.out.printf("%s -> %s : distance = %d, getVertices().size() = %d, edges.size() = %d%n", - shortestPath.getVertices().get(0).getDocumentHandle(), - shortestPath.getVertices().get(shortestPath.getVertices().size() - 1).getDocumentHandle(), - shortestPath.getDistance(), shortestPath.getVertices().size(), shortestPath.getEdges().size()); - } else { - System.out.println("no path"); - } - } - - private void addExampleElements() throws ArangoException { - // create some persons - final VertexEntity v1 = driver.graphCreateVertex(GRAPH_NAME, VERTEXT_COLLECTION_NAME, - new Person("Anton", Person.MALE), true); - final VertexEntity v2 = driver.graphCreateVertex(GRAPH_NAME, VERTEXT_COLLECTION_NAME, - new Person("Boris", Person.MALE), false); - final VertexEntity v3 = driver.graphCreateVertex(GRAPH_NAME, VERTEXT_COLLECTION_NAME, - new Person("Christoph", Person.MALE), false); - final VertexEntity v4 = driver.graphCreateVertex(GRAPH_NAME, VERTEXT_COLLECTION_NAME, - new Person("Doris", Person.FEMALE), false); - final VertexEntity v5 = driver.graphCreateVertex(GRAPH_NAME, VERTEXT_COLLECTION_NAME, - new Person("Else", Person.FEMALE), false); - final VertexEntity v6 = driver.graphCreateVertex(GRAPH_NAME, VERTEXT_COLLECTION_NAME, - new Person("Frauke", Person.FEMALE), false); - - driver.graphCreateEdge(GRAPH_NAME, EDGE_COLLECTION_NAME, v1.getDocumentHandle(), v2.getDocumentHandle(), - new Knows(1984), false); - driver.graphCreateEdge(GRAPH_NAME, EDGE_COLLECTION_NAME, v2.getDocumentHandle(), v6.getDocumentHandle(), - new Knows(1990), false); - driver.graphCreateEdge(GRAPH_NAME, EDGE_COLLECTION_NAME, v1.getDocumentHandle(), v3.getDocumentHandle(), - new Knows(1992), false); - driver.graphCreateEdge(GRAPH_NAME, EDGE_COLLECTION_NAME, v3.getDocumentHandle(), v4.getDocumentHandle(), - new Knows(1996), false); - driver.graphCreateEdge(GRAPH_NAME, EDGE_COLLECTION_NAME, v4.getDocumentHandle(), v6.getDocumentHandle(), - new Knows(2003), false); - driver.graphCreateEdge(GRAPH_NAME, EDGE_COLLECTION_NAME, v4.getDocumentHandle(), v5.getDocumentHandle(), - new Knows(2013), false); - driver.graphCreateEdge(GRAPH_NAME, EDGE_COLLECTION_NAME, v3.getDocumentHandle(), v5.getDocumentHandle(), - new Knows(2003), false); - } - -} diff --git a/src/test/java/com/arangodb/example/graph/GraphAqlTraversalQueryExample.java b/src/test/java/com/arangodb/example/graph/GraphAqlTraversalQueryExample.java deleted file mode 100644 index 5e8e36769..000000000 --- a/src/test/java/com/arangodb/example/graph/GraphAqlTraversalQueryExample.java +++ /dev/null @@ -1,194 +0,0 @@ -/* - * Copyright (C) 2015 ArangoDB GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.example.graph; - -import java.util.HashMap; -import java.util.Iterator; - -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import com.arangodb.ArangoException; -import com.arangodb.CursorResult; -import com.arangodb.entity.EdgeEntity; -import com.arangodb.entity.marker.VertexEntity; -import com.arangodb.util.AqlQueryOptions; -import com.arangodb.util.TestUtils; - -/** - * traversal example (since ArangoDB 2.8) - * - * @author a-brandt - * - */ -public class GraphAqlTraversalQueryExample extends BaseExample { - - private static final String DATABASE_NAME = "GraphAqlTraversalQueryExample"; - - private static final String GRAPH_NAME = "traversalGraph"; - private static final String EDGE_COLLECTION_NAME = "edges"; - private static final String VERTEXT_COLLECTION_NAME = "circles"; - - @Before - public void _before() throws ArangoException { - removeTestDatabase(DATABASE_NAME); - - createDatabase(driver, DATABASE_NAME); - createGraph(driver, GRAPH_NAME, EDGE_COLLECTION_NAME, VERTEXT_COLLECTION_NAME); - addExampleElements(); - } - - @After - public void _after() { - removeTestDatabase(DATABASE_NAME); - } - - @Test - public void graphAqlQuery() throws ArangoException { - - if (isMinimumVersion(driver, TestUtils.VERSION_2_8)) { - // - printHeadline( - "To get started we select the full graph; for better overview we only return the vertex ids:"); - // - - String queryString = "FOR v IN 1..3 OUTBOUND 'circles/A' GRAPH 'traversalGraph' RETURN v._key"; - CursorResult cursor = executeAndPrintResultKeys(queryString); - Assert.assertEquals(10, cursor.getCount()); - - queryString = "FOR v IN 1..3 OUTBOUND 'circles/A' edges RETURN v._key"; - cursor = executeAndPrintResultKeys(queryString); - Assert.assertEquals(10, cursor.getCount()); - - // - printHeadline( - "Now we only want the elements of a specific depth - 2 - the ones that are right behind the fork:"); - // - - queryString = "FOR v IN 2..2 OUTBOUND 'circles/A' GRAPH 'traversalGraph' return v._key"; - cursor = executeAndPrintResultKeys(queryString); - Assert.assertEquals(4, cursor.getCount()); - - queryString = "FOR v IN 2 OUTBOUND 'circles/A' GRAPH 'traversalGraph' return v._key"; - cursor = executeAndPrintResultKeys(queryString); - Assert.assertEquals(4, cursor.getCount()); - - // - printHeadline("Now lets start to add some filters:"); - // - - queryString = "FOR v, e, p IN 1..3 OUTBOUND 'circles/A' GRAPH 'traversalGraph' FILTER p.vertices[1]._key != 'G' RETURN v._key"; - cursor = executeAndPrintResultKeys(queryString); - Assert.assertEquals(5, cursor.getCount()); - - queryString = "FOR v, e, p IN 1..3 OUTBOUND 'circles/A' GRAPH 'traversalGraph' FILTER p.edges[0].label != 'right_foo' RETURN v._key"; - cursor = executeAndPrintResultKeys(queryString); - Assert.assertEquals(5, cursor.getCount()); - - 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 = executeAndPrintResultKeys(queryString); - Assert.assertEquals(3, cursor.getCount()); - - 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 = executeAndPrintResultKeys(queryString); - Assert.assertEquals(3, cursor.getCount()); - - // - printHeadline("Comparing OUTBOUND / INBOUND / ANY:"); - // - - queryString = "FOR v IN 1..3 OUTBOUND 'circles/E' GRAPH 'traversalGraph' return v._key"; - cursor = executeAndPrintResultKeys(queryString); - Assert.assertEquals(1, cursor.getCount()); - - queryString = "FOR v IN 1..3 INBOUND 'circles/E' GRAPH 'traversalGraph' return v._key"; - cursor = executeAndPrintResultKeys(queryString); - Assert.assertEquals(2, cursor.getCount()); - - queryString = "FOR v IN 1..3 ANY 'circles/E' GRAPH 'traversalGraph' return v._key"; - cursor = executeAndPrintResultKeys(queryString); - Assert.assertEquals(6, cursor.getCount()); - } - } - - private CursorResult executeAndPrintResultKeys(final String queryString) throws ArangoException { - final HashMap bindVars = new HashMap(); - final AqlQueryOptions aqlQueryOptions = new AqlQueryOptions().setCount(true); - - System.out.println("Query: " + queryString); - - final CursorResult cursor = driver.executeAqlQuery(queryString, bindVars, aqlQueryOptions, - String.class); - Assert.assertNotNull(cursor); - - final Iterator iterator = cursor.iterator(); - while (iterator.hasNext()) { - final String key = iterator.next(); - - Assert.assertNotNull(key); - - System.out.println("_key = " + key); - } - - return cursor; - } - - private void addExampleElements() throws ArangoException { - - // Add circle circles - final VertexEntity vA = createVertex(new Circle("A", "1")); - final VertexEntity vB = createVertex(new Circle("B", "2")); - final VertexEntity vC = createVertex(new Circle("C", "3")); - final VertexEntity vD = createVertex(new Circle("D", "4")); - final VertexEntity vE = createVertex(new Circle("E", "5")); - final VertexEntity vF = createVertex(new Circle("F", "6")); - final VertexEntity vG = createVertex(new Circle("G", "7")); - final VertexEntity vH = createVertex(new Circle("H", "8")); - final VertexEntity vI = createVertex(new Circle("I", "9")); - final VertexEntity vJ = createVertex(new Circle("J", "10")); - final VertexEntity vK = createVertex(new Circle("K", "11")); - - // Add relevant edges - left branch: - saveEdge(vA, vB, new CircleEdge(false, true, "left_bar")); - saveEdge(vB, vC, new CircleEdge(false, true, "left_blarg")); - saveEdge(vC, vD, new CircleEdge(false, true, "left_blorg")); - saveEdge(vB, vE, new CircleEdge(false, true, "left_blub")); - saveEdge(vE, vF, new CircleEdge(false, true, "left_schubi")); - - // Add relevant edges - right branch: - saveEdge(vA, vG, new CircleEdge(false, true, "right_foo")); - saveEdge(vG, vH, new CircleEdge(false, true, "right_blob")); - saveEdge(vH, vI, new CircleEdge(false, true, "right_blub")); - saveEdge(vG, vJ, new CircleEdge(false, true, "right_zip")); - saveEdge(vJ, vK, new CircleEdge(false, true, "right_zup")); - } - - private EdgeEntity saveEdge( - final VertexEntity from, - final VertexEntity to, - final CircleEdge edge) throws ArangoException { - return driver.graphCreateEdge(GRAPH_NAME, EDGE_COLLECTION_NAME, from.getDocumentHandle(), - to.getDocumentHandle(), edge, false); - } - - private VertexEntity createVertex(final Circle vertex) throws ArangoException { - return driver.graphCreateVertex(GRAPH_NAME, VERTEXT_COLLECTION_NAME, vertex, true); - } - -} diff --git a/src/test/java/com/arangodb/example/graph/GraphExamplesTestSuite.java b/src/test/java/com/arangodb/example/graph/GraphExamplesTestSuite.java deleted file mode 100644 index fbf745027..000000000 --- a/src/test/java/com/arangodb/example/graph/GraphExamplesTestSuite.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright (C) 2015 ArangoDB GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.example.graph; - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; -import org.junit.runners.Suite.SuiteClasses; - -/** - * Starts all unit tests - * - * @author a-brandt - * - */ -@RunWith(Suite.class) -@SuiteClasses({ - - CreateGraphExample.class, - - CreateVerticesAndEdgesExample.class, - - GraphAqlQueryExample.class, - - GraphAqlTraversalQueryExample.class, - - GetVerticesAndEdgesExample.class, - - DeleteVerticesAndEdgesExample.class, - - UpdateAndReplaceVertexExample.class - -}) - -public class GraphExamplesTestSuite { - -} diff --git a/src/test/java/com/arangodb/example/graph/GraphTraversalsInAQLExample.java b/src/test/java/com/arangodb/example/graph/GraphTraversalsInAQLExample.java new file mode 100644 index 000000000..eb1339cc6 --- /dev/null +++ b/src/test/java/com/arangodb/example/graph/GraphTraversalsInAQLExample.java @@ -0,0 +1,122 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.example.graph; + +import static org.hamcrest.Matchers.hasItems; +import static org.hamcrest.Matchers.is; +import static org.junit.Assert.assertThat; + +import java.util.Collection; + +import org.junit.Test; + +import com.arangodb.ArangoCursor; +import com.arangodb.ArangoDBException; + +/** + * Graph traversals in AQL + * + * @see Graph traversals in AQL + * + * @author a-brandt + * + */ +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 = "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/Knows.java b/src/test/java/com/arangodb/example/graph/Knows.java deleted file mode 100644 index cc9f15f8a..000000000 --- a/src/test/java/com/arangodb/example/graph/Knows.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Copyright (C) 2015 ArangoDB GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.example.graph; - -import com.arangodb.entity.BaseDocument; -import com.google.gson.annotations.SerializedName; - -public class Knows { - - @SerializedName(BaseDocument.ID) - private String documentHandle; - - @SerializedName(BaseDocument.KEY) - private String documentKey; - - @SerializedName(BaseDocument.REV) - private String documentRevision; - - @SerializedName(BaseDocument.FROM) - String fromVertexHandle; - - @SerializedName(BaseDocument.TO) - String toVertexHandle; - - private Integer since; - - public Knows() { - } - - public Knows(final Integer since) { - this.since = since; - } - - public Integer getSince() { - return since; - } - - public void setSince(final Integer since) { - this.since = since; - } - - public String getDocumentHandle() { - return documentHandle; - } - - public void setDocumentHandle(final String documentHandle) { - this.documentHandle = documentHandle; - } - - public String getDocumentKey() { - return documentKey; - } - - public void setDocumentKey(final String documentKey) { - this.documentKey = documentKey; - } - - public String getDocumentRevision() { - return documentRevision; - } - - public void setDocumentRevision(final String documentRevision) { - this.documentRevision = documentRevision; - } - - public String getFromVertexHandle() { - return fromVertexHandle; - } - - public String getToVertexHandle() { - return toVertexHandle; - } - - public void setFromVertexHandle(final String fromVertexHandle) { - this.fromVertexHandle = fromVertexHandle; - } - - public void setToVertexHandle(final String toVertexHandle) { - this.toVertexHandle = toVertexHandle; - } - -} diff --git a/src/test/java/com/arangodb/example/graph/Person.java b/src/test/java/com/arangodb/example/graph/Person.java deleted file mode 100644 index 14e82f1a6..000000000 --- a/src/test/java/com/arangodb/example/graph/Person.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Copyright (C) 2015 ArangoDB GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.example.graph; - -import com.arangodb.entity.BaseDocument; -import com.google.gson.annotations.SerializedName; - -/** - * A person class. - * - * The document person class has attributes to store the document key, id and - * revision. - * - * @author a-brandt - * - */ -public class Person { - - public static final String FEMALE = "female"; - - public static final String MALE = "male"; - - @SerializedName(BaseDocument.ID) - private String documentHandle; - - @SerializedName(BaseDocument.KEY) - private String documentKey; - - @SerializedName(BaseDocument.REV) - private String documentRevision; - - private String name; - - private String gender; - - public Person() { - - } - - public Person(final String name, final String gender) { - this.name = name; - this.gender = gender; - } - - public String getName() { - return name; - } - - public void setName(final String name) { - this.name = name; - } - - public String getGender() { - return gender; - } - - public void setGender(final String gender) { - this.gender = gender; - } - - public String getDocumentHandle() { - return documentHandle; - } - - public void setDocumentHandle(final String documentHandle) { - this.documentHandle = documentHandle; - } - - public String getDocumentKey() { - return documentKey; - } - - public void setDocumentKey(final String documentKey) { - this.documentKey = documentKey; - } - - public String getDocumentRevision() { - return documentRevision; - } - - public void setDocumentRevision(final String documentRevision) { - this.documentRevision = documentRevision; - } - -} diff --git a/src/test/java/com/arangodb/example/graph/ShortestPathInAQLExample.java b/src/test/java/com/arangodb/example/graph/ShortestPathInAQLExample.java new file mode 100644 index 000000000..07cfc4493 --- /dev/null +++ b/src/test/java/com/arangodb/example/graph/ShortestPathInAQLExample.java @@ -0,0 +1,106 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.example.graph; + +import static org.hamcrest.Matchers.hasItems; +import static org.hamcrest.Matchers.is; +import static org.junit.Assert.assertThat; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +import org.junit.Test; + +import com.arangodb.ArangoCursor; +import com.arangodb.ArangoDBException; + +/** + * Shortest Path in AQL + * + * @see Shortest Path in AQL + * + * @author a-brandt + * + */ +public class ShortestPathInAQLExample extends BaseGraphTest { + + 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 = "FOR v, e IN OUTBOUND SHORTEST_PATH 'circles/A' TO 'circles/D' edges RETURN {'vertex': v._key, 'edge': e._key}"; + cursor = db.query(queryString, null, null, Pair.class); + 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}"; + cursor = db.query(queryString, null, null, Pair.class); + assertThat(collection.size(), is(4)); + assertThat(collection, hasItems("A", "B", "C", "D")); + } + + protected Collection toVertexCollection(final ArangoCursor cursor) { + final List result = new ArrayList(); + for (; cursor.hasNext();) { + final Pair pair = cursor.next(); + result.add(pair.getVertex()); + } + return result; + } + +} diff --git a/src/test/java/com/arangodb/example/graph/UpdateAndReplaceVertexExample.java b/src/test/java/com/arangodb/example/graph/UpdateAndReplaceVertexExample.java deleted file mode 100644 index c8ea67bdf..000000000 --- a/src/test/java/com/arangodb/example/graph/UpdateAndReplaceVertexExample.java +++ /dev/null @@ -1,125 +0,0 @@ -package com.arangodb.example.graph; - -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import com.arangodb.ArangoException; -import com.arangodb.entity.marker.VertexEntity; - -/** - * Update and replace example - * - * @author a-brandt - * - */ -public class UpdateAndReplaceVertexExample extends BaseExample { - - private static final String DATABASE_NAME = "UpdateAndReplaceVertexExample"; - - private static final String GRAPH_NAME = "example_graph1"; - private static final String EDGE_COLLECTION_NAME = "edgeColl1"; - private static final String VERTEXT_COLLECTION_NAME = "vertexColl1"; - - @Before - public void _before() throws ArangoException { - removeTestDatabase(DATABASE_NAME); - - createDatabase(driver, DATABASE_NAME); - createGraph(driver, GRAPH_NAME, EDGE_COLLECTION_NAME, VERTEXT_COLLECTION_NAME); - } - - @After - public void _after() { - removeTestDatabase(DATABASE_NAME); - } - - @Test - public void replaceVertex() throws ArangoException { - - // - printHeadline("replace vertex"); - // - - final Person personA = new Person("A", Person.MALE); - final VertexEntity v1 = createVertex(personA); - - final Person personB = new Person("B", Person.FEMALE); - - final VertexEntity replaceVertex = driver.graphReplaceVertex(GRAPH_NAME, VERTEXT_COLLECTION_NAME, - v1.getDocumentKey(), personB); - // document handle is unchanged - Assert.assertNotNull(replaceVertex); - Assert.assertEquals(v1.getDocumentHandle(), replaceVertex.getDocumentHandle()); - // document revision has changed - Assert.assertNotEquals(v1.getDocumentRevision(), replaceVertex.getDocumentRevision()); - // name changed to "B" - Assert.assertNotNull(replaceVertex.getEntity()); - Assert.assertEquals(personB.getName(), replaceVertex.getEntity().getName()); - } - - @Test - public void updateVertex() throws ArangoException { - - // - printHeadline("update vertex"); - // - - final Person personA = new Person("A", Person.MALE); - final VertexEntity v1 = createVertex(personA); - - // update one attribute (gender) - personA.setGender(Person.FEMALE); - - final VertexEntity updateVertex = driver.graphUpdateVertex(GRAPH_NAME, VERTEXT_COLLECTION_NAME, - v1.getDocumentKey(), personA, true); - - // document handle is unchanged - Assert.assertNotNull(updateVertex); - Assert.assertEquals(v1.getDocumentHandle(), updateVertex.getDocumentHandle()); - // document revision has changed - Assert.assertNotEquals(v1.getDocumentRevision(), updateVertex.getDocumentRevision()); - // gender changed to Person.FEMALE - Assert.assertNotNull(updateVertex.getEntity()); - Assert.assertEquals(Person.FEMALE, updateVertex.getEntity().getGender()); - Assert.assertEquals(personA.getName(), updateVertex.getEntity().getName()); - } - - @Test - public void updateOneAttribute() throws ArangoException { - - // - printHeadline("update one vertex attribute"); - // - - final Person personA = new Person("A", Person.MALE); - final VertexEntity v1 = createVertex(personA); - - // update one attribute (gender) - final Person update = new Person(null, Person.FEMALE); - - driver.graphUpdateVertex(GRAPH_NAME, VERTEXT_COLLECTION_NAME, v1.getDocumentKey(), update, true); - - // reload vertex - final VertexEntity updateVertex = driver.graphGetVertex(GRAPH_NAME, VERTEXT_COLLECTION_NAME, - v1.getDocumentKey(), Person.class); - - // document handle is unchanged - Assert.assertNotNull(updateVertex); - Assert.assertEquals(v1.getDocumentHandle(), updateVertex.getDocumentHandle()); - // document revision has changed - Assert.assertNotEquals(v1.getDocumentRevision(), updateVertex.getDocumentRevision()); - // gender changed to Person.FEMALE - Assert.assertNotNull(updateVertex.getEntity()); - Assert.assertEquals(update.getGender(), updateVertex.getEntity().getGender()); - Assert.assertEquals(personA.getName(), updateVertex.getEntity().getName()); - } - - private VertexEntity createVertex(final Person person) throws ArangoException { - final VertexEntity v = driver.graphCreateVertex(GRAPH_NAME, VERTEXT_COLLECTION_NAME, person, true); - Assert.assertNotNull(v); - return v; - } - -} diff --git a/src/test/java/com/arangodb/example/ssl/SslExample.java b/src/test/java/com/arangodb/example/ssl/SslExample.java index 47a1de8fb..294cc9006 100644 --- a/src/test/java/com/arangodb/example/ssl/SslExample.java +++ b/src/test/java/com/arangodb/example/ssl/SslExample.java @@ -1,206 +1,77 @@ -/* - * Copyright (C) 2015 ArangoDB GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.example.ssl; - -import java.io.File; -import java.io.IOException; -import java.net.URISyntaxException; -import java.net.URL; -import java.security.KeyManagementException; -import java.security.KeyStoreException; -import java.security.NoSuchAlgorithmException; -import java.security.cert.CertificateException; - -import javax.net.ssl.SSLContext; - -import org.apache.http.ssl.SSLContexts; -import org.junit.Assert; -import org.junit.Test; - -import com.arangodb.ArangoConfigure; -import com.arangodb.ArangoDriver; -import com.arangodb.ArangoException; -import com.arangodb.ArangoHost; -import com.arangodb.entity.ArangoVersion; -import com.arangodb.http.HttpResponseEntity; -import com.arangodb.util.TestUtils; - -/*- - * Example for using a HTTPS connection - * - * Create a self signed certificate for arangod (or use the test certificate of the unit tests) - * https://docs.arangodb.com/ConfigureArango/Arangod.html - * - * Start arangod with HTTP (port 8529) and HTTPS (port 8530): - * - * bin/arangod - * --server.disable-authentication=false - * --configuration ./etc/relative/arangod.conf - * --server.endpoint ssl://localhost:8530 - * --server.keyfile UnitTests/server.pem - * --server.endpoint tcp://localhost:8529 - * ../database/ - * - * @author a-brandt - * - */ -public class SslExample { - - 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"; - - @Test - public void httpTest() throws ArangoException { - - ArangoConfigure configuration = null; - try { - configuration = new ArangoConfigure(); - // get host and port from arangodb.properties - // configuration.setArangoHost(new ArangoHost("localhost", 8529)); - configuration.init(); - - final ArangoDriver arangoDriver = new ArangoDriver(configuration); - - final ArangoVersion version = arangoDriver.getVersion(); - Assert.assertNotNull(version); - } finally { - if (configuration != null) { - configuration.shutdown(); - } - } - } - - @Test - public void sslConnectionTest() throws ArangoException { - final String javaVersion = System.getProperty("java.version"); - if (TestUtils.compareVersion(javaVersion, "1.7") > -1) { - // use HTTPS with java default trust store - ArangoConfigure configuration = null; - try { - configuration = new ArangoConfigure(); - configuration.setArangoHost(new ArangoHost("www.arangodb.com", 443)); - configuration.setUseSsl(true); - configuration.init(); - - final ArangoDriver arangoDriver = new ArangoDriver(configuration); - - final HttpResponseEntity response = arangoDriver.getHttpManager().doGet("/"); - Assert.assertEquals(200, response.getStatusCode()); - } finally { - if (configuration != null) { - configuration.shutdown(); - } - } - } - } - - @Test - public void sslWithSelfSignedCertificateTest() throws ArangoException, KeyManagementException, - NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException, URISyntaxException { - - ArangoConfigure configuration = null; - try { - // create a sslContext for the self signed certificate - final URL resource = this.getClass().getResource(SSL_TRUSTSTORE); - final SSLContext sslContext = SSLContexts.custom() - .loadTrustMaterial(new File(resource.toURI()), SSL_TRUSTSTORE_PASSWORD.toCharArray()).build(); - - configuration = new ArangoConfigure("/ssl-arangodb.properties"); - configuration.setSslContext(sslContext); - configuration.init(); - - final ArangoDriver arangoDriver = new ArangoDriver(configuration); - - final ArangoVersion version = arangoDriver.getVersion(); - Assert.assertNotNull(version); - } finally { - if (configuration != null) { - configuration.shutdown(); - } - } - } - - @Test - public void sslHandshakeExceptionTest() { - ArangoConfigure configuration = null; - try { - configuration = new ArangoConfigure("/ssl-arangodb.properties"); - configuration.init(); - - final ArangoDriver arangoDriver = new ArangoDriver(configuration); - - try { - // java do not trust self signed certificates - - arangoDriver.getVersion(); - Assert.fail("this should fail"); - - } catch (final ArangoException e) { - final Throwable cause = e.getCause(); - Assert.assertTrue(cause instanceof javax.net.ssl.SSLHandshakeException); - } - } finally { - if (configuration != null) { - configuration.shutdown(); - } - } - } - - @Test - public void sslPeerUnverifiedExceptionTest() throws ArangoException, KeyManagementException, - NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException, URISyntaxException { - - ArangoConfigure configuration = null; - try { - // create a sslContext for the self signed certificate - final URL resource = this.getClass().getResource(SSL_TRUSTSTORE); - final SSLContext sslContext = SSLContexts.custom() - .loadTrustMaterial(new File(resource.toURI()), SSL_TRUSTSTORE_PASSWORD.toCharArray()).build(); - - configuration = new ArangoConfigure("/ssl-arangodb.properties"); - // 127.0.0.1 is the wrong name - configuration.getArangoHost().setHost("127.0.0.1"); - configuration.setSslContext(sslContext); - configuration.init(); - - final ArangoDriver arangoDriver = new ArangoDriver(configuration); - - try { - arangoDriver.getVersion(); - Assert.fail("this should fail"); - } catch (final ArangoException e) { - final Throwable cause = e.getCause(); - Assert.assertTrue(cause instanceof javax.net.ssl.SSLPeerUnverifiedException); - } - } finally { - if (configuration != null) { - configuration.shutdown(); - } - } - } - -} +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.example.ssl; + +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.junit.Assert.assertThat; + +import java.security.KeyStore; + +import javax.net.ssl.KeyManagerFactory; +import javax.net.ssl.SSLContext; +import javax.net.ssl.TrustManagerFactory; + +import org.junit.Ignore; +import org.junit.Test; + +import com.arangodb.ArangoDB; +import com.arangodb.entity.ArangoDBVersion; + +/** + * @author Mark - mark at arangodb.com + * + */ +public class SslExample { + + /*- + * 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()); + + final KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); + kmf.init(ks, SSL_TRUSTSTORE_PASSWORD.toCharArray()); + + final TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); + tmf.init(ks); + + final SSLContext sc = SSLContext.getInstance("TLS"); + sc.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); + + final ArangoDB arangoDB = new ArangoDB.Builder().port(8530).useSsl(true).sslContext(sc).build(); + final ArangoDBVersion version = arangoDB.getVersion(); + assertThat(version, is(notNullValue())); + } + +} diff --git a/src/test/java/com/arangodb/example/velocypack/VPackExample.java b/src/test/java/com/arangodb/example/velocypack/VPackExample.java new file mode 100644 index 000000000..659b37b9b --- /dev/null +++ b/src/test/java/com/arangodb/example/velocypack/VPackExample.java @@ -0,0 +1,115 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.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; + +/** + * @author Mark - mark at arangodb.com + * + */ +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)); + } + +} diff --git a/src/test/java/com/arangodb/internal/DocumentCacheTest.java b/src/test/java/com/arangodb/internal/DocumentCacheTest.java new file mode 100644 index 000000000..6a9c265b5 --- /dev/null +++ b/src/test/java/com/arangodb/internal/DocumentCacheTest.java @@ -0,0 +1,75 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.internal; + +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.nullValue; +import static org.junit.Assert.assertThat; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Test; + +import com.arangodb.entity.BaseDocument; +import com.arangodb.entity.DocumentField; +import com.arangodb.entity.DocumentField.Type; + +/** + * @author Mark - mark at arangodb.com + * + */ +public class DocumentCacheTest { + + @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())); + + 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")); + } + + @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); + + assertThat(map.isEmpty(), is(true)); + } +} diff --git a/src/test/java/com/arangodb/internal/net/CommunicationTest.java b/src/test/java/com/arangodb/internal/net/CommunicationTest.java new file mode 100644 index 000000000..93346753f --- /dev/null +++ b/src/test/java/com/arangodb/internal/net/CommunicationTest.java @@ -0,0 +1,45 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.internal.net; + +import static org.hamcrest.CoreMatchers.notNullValue; +import static org.hamcrest.Matchers.is; +import static org.junit.Assert.assertThat; + +import org.junit.Test; + +import com.arangodb.ArangoDB; +import com.arangodb.entity.ArangoDBVersion; + +/** + * @author Mark - mark at arangodb.com + * + */ +public class CommunicationTest { + + @Test + public void chunkSizeSmall() { + final ArangoDB arangoDB = new ArangoDB.Builder().chunksize(20).build(); + final ArangoDBVersion version = arangoDB.getVersion(); + assertThat(version, is(notNullValue())); + } + +} diff --git a/src/test/java/com/arangodb/sandbox/ImportNico2Video.java b/src/test/java/com/arangodb/sandbox/ImportNico2Video.java deleted file mode 100644 index d42e37031..000000000 --- a/src/test/java/com/arangodb/sandbox/ImportNico2Video.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright (C) 2012,2013 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.sandbox; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStreamReader; -import java.util.zip.GZIPInputStream; - -import com.arangodb.ArangoClient; -import com.arangodb.ArangoConfigure; -import com.arangodb.ArangoException; -import com.arangodb.util.LineIterator; - -/** - * @author tamtam180 - kirscheless at gmail.com - * - */ -public class ImportNico2Video { - - public static void main(String[] args) throws ArangoException, IllegalArgumentException, IOException { - - ArangoConfigure configure = new ArangoConfigure(); - configure.init(); - - ArangoClient client = new ArangoClient(configure); - - File file = new File("0000.dat.gz"); - LineIterator itr = new LineIterator( - new BufferedReader(new InputStreamReader(new GZIPInputStream(new FileInputStream(file)), "utf-8"))); - client.importRawJsonDocuments("nico", itr, 10); - LineIterator.closeQuietly(itr); - configure.shutdown(); - - } - -} diff --git a/src/test/java/com/arangodb/sandbox/PostChunkTest.java b/src/test/java/com/arangodb/sandbox/PostChunkTest.java deleted file mode 100644 index 414bca1f0..000000000 --- a/src/test/java/com/arangodb/sandbox/PostChunkTest.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright (C) 2012,2013 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.sandbox; - -import java.io.ByteArrayInputStream; - -import org.apache.http.HttpResponse; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.entity.InputStreamEntity; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClientBuilder; - -/** - * @author tamtam180 - kirscheless at gmail.com - * - */ -public class PostChunkTest { - - /** - * @param args - */ - public static void main(String[] args) throws Exception { - - HttpClientBuilder builder = HttpClientBuilder.create(); - CloseableHttpClient client = builder.build(); - - HttpPost post = new HttpPost( - "http://localhost:8529/_api/import?collection=test1&createCollection=true&type=documents"); - // post.setEntity(new StringEntity("{\"xx\": \"123\"}{\"xx\": - // \"456\"}")); - InputStreamEntity entity = new InputStreamEntity( - new ByteArrayInputStream("{\"xx\": \"123\"}{\"xx\": \"456\"}".getBytes()), 26); - entity.setChunked(true); - post.setEntity(entity); - - HttpResponse res = client.execute(post); - - System.out.println(res.getStatusLine()); - - post.releaseConnection(); - } - -} diff --git a/src/test/java/com/arangodb/sandbox/SerializeNameTest.java b/src/test/java/com/arangodb/sandbox/SerializeNameTest.java deleted file mode 100644 index 96c61af70..000000000 --- a/src/test/java/com/arangodb/sandbox/SerializeNameTest.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright (C) 2012,2013 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.sandbox; - -import com.arangodb.annotations.DocumentKey; -import com.arangodb.entity.EntityFactory; -import com.google.gson.annotations.SerializedName; - -/** - * @author tamtam180 - kirscheless at gmail.com - * - */ -public class SerializeNameTest { - - private static class Hoge { - public String S; - public Boolean B; - @SerializedName("ZZZ") public Integer I; - } - - private static class Hoge2 { - public String S; - public Boolean B; - @DocumentKey public Integer I; - } - - public static void main(String[] args) throws Exception { - - do { - Hoge hoge = new Hoge(); - hoge.S = "ABC"; - hoge.B = true; - hoge.I = 123; - - String jsonText = EntityFactory.toJsonString(hoge); - System.out.println(jsonText); - // {"S":"ABC","B":true,"ZZZ":123} - - Hoge hoge2 = EntityFactory.createEntity(jsonText, Hoge.class); - System.out.println(hoge2.S); // ABC - System.out.println(hoge2.B); // true - System.out.println(hoge2.I); // 123 - } while (false); - - // ------------------------------------------------------------ - System.out.println("----------------------------------------"); - // ------------------------------------------------------------ - - do { - Hoge2 hoge = new Hoge2(); - hoge.S = "ABC"; - hoge.B = true; - hoge.I = 123; - - String jsonText = EntityFactory.toJsonString(hoge); - System.out.println(jsonText); - // {"S":"ABC","B":true,"ZZZ":123} - - Hoge2 hoge2 = EntityFactory.createEntity(jsonText, Hoge2.class); - System.out.println(hoge2.S); // ABC - System.out.println(hoge2.B); // true - System.out.println(hoge2.I); // 123 - - } while (false); - - - } - -} diff --git a/src/test/java/com/arangodb/util/CreateErrorNums.java b/src/test/java/com/arangodb/util/CreateErrorNums.java deleted file mode 100644 index 7fbb9e731..000000000 --- a/src/test/java/com/arangodb/util/CreateErrorNums.java +++ /dev/null @@ -1,119 +0,0 @@ -package com.arangodb.util; - -import java.io.BufferedReader; -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileReader; -import java.io.FileWriter; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -/** - * Converts the arangodb errors.dat file into a java file - * - * @author abrandt - * - */ -public class CreateErrorNums { - - public static class ErrorNum { - private String name; - private Integer num; - - public ErrorNum(String name, Integer num) { - this.name = name; - this.num = num; - } - - public String getName() { - return name; - } - - public Integer getNum() { - return num; - } - - @Override - public String toString() { - return "\tpublic static final int " + name + " = " + num + ";"; - } - - } - - public static void main(String[] args) { - - if (args.length < 1) { - System.out.println("Usage:"); - System.out.println(""); - System.out.println("CreateErrorNums "); - System.out.println(""); - System.out.println("Example"); - System.out.println("CreateErrorNums ~/arangodb/lib/BasicsC/errors.dat"); - System.exit(0); - } - - String filename = args[0]; - - BufferedReader br = null; - try { - br = new BufferedReader(new FileReader(filename)); - } catch (FileNotFoundException e) { - System.out.println("File '" + filename + "' not found"); - System.exit(0); - } - - List errorNums = new ArrayList(); - - String line; - try { - while ((line = br.readLine()) != null) { - // process the line. - - String[] part = line.split(","); - if (part.length > 2) { - Integer num = new Integer(part[1]); - ErrorNum en = new ErrorNum(part[0], num); - errorNums.add(en); - } - - } - } catch (IOException e1) { - } - - try { - br.close(); - } catch (IOException e) { - } - - try { - String current = new java.io.File(".").getCanonicalPath(); - System.out.println("Current dir: " + current); - - File file = new File("src/main/java/com/arangodb/ErrorNums.java"); - BufferedWriter output = new BufferedWriter(new FileWriter(file)); - - output.write("package com.arangodb;\r\n"); - output.write("\r\n"); - output.write("public class ErrorNums {\r\n"); - output.write("\r\n"); - - for (ErrorNum en : errorNums) { - output.write(en.toString()); - output.write("\n"); - } - - output.write("\r\n"); - output.write("}\r\n"); - output.write("\r\n"); - - output.close(); - } catch (IOException e) { - e.printStackTrace(); - } - - System.out.println("OK."); - } - -} diff --git a/src/test/java/com/arangodb/util/LineIterator.java b/src/test/java/com/arangodb/util/LineIterator.java deleted file mode 100644 index 5d588459c..000000000 --- a/src/test/java/com/arangodb/util/LineIterator.java +++ /dev/null @@ -1,183 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.arangodb.util; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.Reader; -import java.util.Iterator; -import java.util.NoSuchElementException; - -import com.arangodb.util.IOUtils; - -/** - * An Iterator over the lines in a Reader. - *

- * LineIterator holds a reference to an open Reader. - * When you have finished with the iterator you should close the reader - * to free internal resources. This can be done by closing the reader directly, - * or by calling the {@link #close()} or {@link #closeQuietly(LineIterator)} - * method on the iterator. - *

- * The recommended usage pattern is: - *

- * LineIterator it = FileUtils.lineIterator(file, "UTF-8");
- * try {
- *   while (it.hasNext()) {
- *     String line = it.nextLine();
- *     /// do something with line
- *   }
- * } finally {
- *   LineIterator.closeQuietly(iterator);
- * }
- * 
- * - * @author Niall Pemberton - * @author Stephen Colebourne - * @author Sandy McArthur - * @version $Id: LineIterator.java 437567 2006-08-28 06:39:07Z bayard $ - * @since Commons IO 1.2 - */ -public class LineIterator implements Iterator { - - /** The reader that is being read. */ - private final BufferedReader bufferedReader; - /** The current line. */ - private String cachedLine; - /** A flag indicating if the iterator has been fully read. */ - private boolean finished = false; - - /** - * Constructs an iterator of the lines for a Reader. - * - * @param reader the Reader to read from, not null - * @throws IllegalArgumentException if the reader is null - */ - public LineIterator(final Reader reader) throws IllegalArgumentException { - if (reader == null) { - throw new IllegalArgumentException("Reader must not be null"); - } - if (reader instanceof BufferedReader) { - bufferedReader = (BufferedReader) reader; - } else { - bufferedReader = new BufferedReader(reader); - } - } - - //----------------------------------------------------------------------- - /** - * Indicates whether the Reader has more lines. - * If there is an IOException then {@link #close()} will - * be called on this instance. - * - * @return true if the Reader has more lines - * @throws IllegalStateException if an IO exception occurs - */ - public boolean hasNext() { - if (cachedLine != null) { - return true; - } else if (finished) { - return false; - } else { - try { - while (true) { - String line = bufferedReader.readLine(); - if (line == null) { - finished = true; - return false; - } else if (isValidLine(line)) { - cachedLine = line; - return true; - } - } - } catch(IOException ioe) { - close(); - throw new IllegalStateException(ioe.toString()); - } - } - } - - /** - * Overridable method to validate each line that is returned. - * - * @param line the line that is to be validated - * @return true if valid, false to remove from the iterator - */ - protected boolean isValidLine(String line) { - return true; - } - - /** - * Returns the next line in the wrapped Reader. - * - * @return the next line from the input - * @throws NoSuchElementException if there is no line to return - */ - public String next() { - return nextLine(); - } - - /** - * Returns the next line in the wrapped Reader. - * - * @return the next line from the input - * @throws NoSuchElementException if there is no line to return - */ - public String nextLine() { - if (!hasNext()) { - throw new NoSuchElementException("No more lines"); - } - String currentLine = cachedLine; - cachedLine = null; - return currentLine; - } - - /** - * Closes the underlying Reader quietly. - * This method is useful if you only want to process the first few - * lines of a larger file. If you do not close the iterator - * then the Reader remains open. - * This method can safely be called multiple times. - */ - public void close() { - finished = true; - IOUtils.close(bufferedReader); - cachedLine = null; - } - - /** - * Unsupported. - * - * @throws UnsupportedOperationException always - */ - public void remove() { - throw new UnsupportedOperationException("Remove unsupported on LineIterator"); - } - - //----------------------------------------------------------------------- - /** - * Closes the iterator, handling null and ignoring exceptions. - * - * @param iterator the iterator to close - */ - public static void closeQuietly(LineIterator iterator) { - if (iterator != null) { - iterator.close(); - } - } - -} \ No newline at end of file diff --git a/src/test/java/com/arangodb/util/StringJoinTest.java b/src/test/java/com/arangodb/util/StringJoinTest.java deleted file mode 100644 index 381e6ac5d..000000000 --- a/src/test/java/com/arangodb/util/StringJoinTest.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.arangodb.util; - -import static org.hamcrest.CoreMatchers.*; -import static org.junit.Assert.*; - -import org.junit.Test; - -import com.arangodb.util.StringUtils; - - -public class StringJoinTest { - - @Test - public void test() { - - assertThat(StringUtils.join((String[])null), is(nullValue())); - assertThat(StringUtils.join(""), is("/")); - - assertThat(StringUtils.join("base", "p1"), is("/base/p1")); - assertThat(StringUtils.join("base", "/p1"), is("/base/p1")); - assertThat(StringUtils.join("base/", "p1"), is("/base/p1")); - assertThat(StringUtils.join("/base/", "/p1"), is("/base/p1")); - - assertThat(StringUtils.join("/base", "/p1", "abc"), is("/base/p1/abc")); - - assertThat(StringUtils.join("/base", "p1", "p2", "abc"), is("/base/p1/p2/abc")); - - assertThat(StringUtils.join("/base", null, "p2", "abc"), is("/base/p2/abc")); - assertThat(StringUtils.join("/base", null, null, "abc"), is("/base/abc")); - assertThat(StringUtils.join(null, null, "abc"), is("/abc")); - - } - -} diff --git a/src/test/java/com/arangodb/util/TestUtils.java b/src/test/java/com/arangodb/util/TestUtils.java deleted file mode 100644 index 736ffa093..000000000 --- a/src/test/java/com/arangodb/util/TestUtils.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Copyright (C) 2012,2013 tamtam180 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.arangodb.util; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.util.ArrayList; -import java.util.List; - -import com.arangodb.Station; - -/** - * @author tamtam180 - kirscheless at gmail.com - * - */ -public class TestUtils { - - public static final String VERSION_2_7 = "2.7"; - - public static final String VERSION_2_8 = "2.8"; - - public static List readStations() throws IOException { - - ArrayList stations = new ArrayList(1000); - BufferedReader br = new BufferedReader( - new InputStreamReader(TestUtils.class.getResourceAsStream("/test-data/jp-tokyo-station.tsv"), "utf-8")); - String line = null; - while ((line = br.readLine()) != null) { - line = line.trim(); - if (line.length() == 0) { - continue; - } - Station station = new Station(line.split(" ", -1)); - stations.add(station); - } - br.close(); - - return stations; - - } - - public static int compareVersion(String version1, String version2) { - String[] v1s = version1.split("\\."); - String[] v2s = version2.split("\\."); - - int minLength = Math.min(v1s.length, v2s.length); - int i = 0; - for (; i < minLength; i++) { - int i1 = getIntegerValueOfString(v1s[i]); - int i2 = getIntegerValueOfString(v2s[i]); - if (i1 > i2) - return 1; - else if (i1 < i2) - return -1; - } - int sum1 = 0; - for (int j = 0; j < v1s.length; j++) { - sum1 += getIntegerValueOfString(v1s[j]); - } - int sum2 = 0; - for (int j = 0; j < v2s.length; j++) { - sum2 += getIntegerValueOfString(v2s[j]); - } - if (sum1 == sum2) - return 0; - return v1s.length > v2s.length ? 1 : -1; - } - - private static int getIntegerValueOfString(String str) { - try { - return Integer.valueOf(str); - } catch (NumberFormatException e) { - if (str.contains("-")) { - str = str.substring(0, str.indexOf('-')); - return Integer.valueOf(str); - } - } - return 0; - } - -} diff --git a/src/test/java/com/arangodb/velocypack/VPackBuilderTest.java b/src/test/java/com/arangodb/velocypack/VPackBuilderTest.java new file mode 100644 index 000000000..6dd529408 --- /dev/null +++ b/src/test/java/com/arangodb/velocypack/VPackBuilderTest.java @@ -0,0 +1,890 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.velocypack; + +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.math.BigInteger; +import java.util.Date; + +import org.junit.Test; + +import com.arangodb.velocypack.exception.VPackBuilderNeedOpenCompoundException; +import com.arangodb.velocypack.exception.VPackBuilderNumberOutOfRangeException; +import com.arangodb.velocypack.exception.VPackBuilderUnexpectedValueException; +import com.arangodb.velocypack.exception.VPackException; + +/** + * @author Mark - mark at arangodb.com + * + */ +public class VPackBuilderTest { + + @Test + public void empty() { + final VPackSlice slice = new VPackBuilder().slice(); + assertThat(slice.isNone(), is(true)); + } + + @Test + public void addNull() throws VPackException { + final VPackBuilder builder = new VPackBuilder(); + builder.add(ValueType.NULL); + + final VPackSlice slice = builder.slice(); + assertThat(slice.isNull(), is(true)); + } + + @Test + public void addBooleanTrue() throws VPackException { + final VPackBuilder builder = new VPackBuilder(); + builder.add(true); + + final VPackSlice slice = builder.slice(); + assertThat(slice.isBoolean(), is(true)); + assertThat(slice.getAsBoolean(), is(true)); + } + + @Test + public void addBooleanFalse() throws VPackException { + final VPackBuilder builder = new VPackBuilder(); + builder.add(false); + + final VPackSlice slice = builder.slice(); + assertThat(slice.isBoolean(), is(true)); + assertThat(slice.getAsBoolean(), is(false)); + } + + @Test + public void addBooleanNull() throws VPackException { + final VPackBuilder builder = new VPackBuilder(); + final Boolean b = null; + builder.add(b); + + final VPackSlice slice = builder.slice(); + assertThat(slice.isNull(), is(true)); + } + + @Test + public void addDouble() throws VPackException { + final VPackBuilder builder = new VPackBuilder(); + final double value = Double.MAX_VALUE; + builder.add(value); + + final VPackSlice slice = builder.slice(); + assertThat(slice.isDouble(), is(true)); + assertThat(slice.getAsDouble(), is(value)); + } + + @Test + public void addIntegerAsSmallIntMin() throws VPackException { + final VPackBuilder builder = new VPackBuilder(); + final int value = -6; + builder.add(value); + + final VPackSlice slice = builder.slice(); + assertThat(slice.isSmallInt(), is(true)); + assertThat(slice.getAsInt(), is(value)); + } + + @Test + public void addIntegerAsSmallIntMax() throws VPackException { + final VPackBuilder builder = new VPackBuilder(); + final int value = 9; + builder.add(value); + + final VPackSlice slice = builder.slice(); + assertThat(slice.isSmallInt(), is(true)); + assertThat(slice.getAsInt(), is(value)); + } + + @Test + public void addLongAsSmallIntMin() throws VPackException { + final VPackBuilder builder = new VPackBuilder(); + final long value = -6; + builder.add(value, ValueType.SMALLINT); + + final VPackSlice slice = builder.slice(); + assertThat(slice.isSmallInt(), is(true)); + assertThat(slice.getAsLong(), is(value)); + } + + @Test + public void addLongAsSmallIntMax() throws VPackException { + final VPackBuilder builder = new VPackBuilder(); + final long value = 9; + builder.add(value, ValueType.SMALLINT); + + final VPackSlice slice = builder.slice(); + assertThat(slice.isSmallInt(), is(true)); + assertThat(slice.getAsLong(), is(value)); + } + + @Test(expected = VPackBuilderNumberOutOfRangeException.class) + public void addLongAsSmallIntOutofRange() throws VPackException { + final VPackBuilder builder = new VPackBuilder(); + final long value = Long.MAX_VALUE; + builder.add(value, ValueType.SMALLINT); + } + + @Test + public void addBigIntegerAsSmallIntMin() throws VPackException { + final VPackBuilder builder = new VPackBuilder(); + final BigInteger value = BigInteger.valueOf(-6); + builder.add(value, ValueType.SMALLINT); + + final VPackSlice slice = builder.slice(); + assertThat(slice.isSmallInt(), is(true)); + assertThat(slice.getAsBigInteger(), is(value)); + } + + @Test + public void addBigIntegerAsSmallIntMax() throws VPackException { + final VPackBuilder builder = new VPackBuilder(); + final BigInteger value = BigInteger.valueOf(9); + builder.add(value, ValueType.SMALLINT); + + final VPackSlice slice = builder.slice(); + assertThat(slice.isSmallInt(), is(true)); + assertThat(slice.getAsBigInteger(), is(value)); + } + + @Test(expected = VPackBuilderNumberOutOfRangeException.class) + public void addBigIntegerAsSmallIntOutofRange() throws VPackException { + final VPackBuilder builder = new VPackBuilder(); + final BigInteger value = BigInteger.valueOf(Long.MAX_VALUE); + builder.add(value, ValueType.SMALLINT); + } + + @Test + public void addIntegerAsInt() throws VPackException { + final VPackBuilder builder = new VPackBuilder(); + final int value = Integer.MAX_VALUE; + builder.add(value); + + final VPackSlice slice = builder.slice(); + assertThat(slice.isInt(), is(true)); + assertThat(slice.getAsInt(), is(value)); + } + + @Test + public void addLongAsInt() throws VPackException { + final VPackBuilder builder = new VPackBuilder(); + final long value = Long.MAX_VALUE; + builder.add(value, ValueType.INT); + + final VPackSlice slice = builder.slice(); + assertThat(slice.isInt(), is(true)); + assertThat(slice.getAsLong(), is(value)); + } + + @Test + public void addBigIntegerAsInt() throws VPackException { + final VPackBuilder builder = new VPackBuilder(); + final BigInteger value = BigInteger.valueOf(Long.MAX_VALUE); + builder.add(value, ValueType.INT); + + final VPackSlice slice = builder.slice(); + assertThat(slice.isInt(), is(true)); + assertThat(slice.getAsBigInteger(), is(value)); + } + + @Test + public void addLongAsUInt() throws VPackException { + final VPackBuilder builder = new VPackBuilder(); + final long value = Long.MAX_VALUE; + builder.add(value, ValueType.UINT); + + final VPackSlice slice = builder.slice(); + assertThat(slice.isUInt(), is(true)); + assertThat(slice.getAsLong(), is(value)); + } + + @Test + public void addBigIntegerAsUInt() throws VPackException { + final VPackBuilder builder = new VPackBuilder(); + final BigInteger value = BigInteger.valueOf(Long.MAX_VALUE); + builder.add(value, ValueType.UINT); + + final VPackSlice slice = builder.slice(); + assertThat(slice.isUInt(), is(true)); + assertThat(slice.getAsBigInteger(), is(value)); + } + + @Test(expected = VPackBuilderUnexpectedValueException.class) + public void addLongAsUIntNegative() throws VPackException { + final VPackBuilder builder = new VPackBuilder(); + final long value = -10; + builder.add(value, ValueType.UINT); + } + + @Test(expected = VPackBuilderUnexpectedValueException.class) + public void addBigIntegerAsUIntNegative() throws VPackException { + final VPackBuilder builder = new VPackBuilder(); + final BigInteger value = BigInteger.valueOf(-10); + builder.add(value, ValueType.UINT); + } + + @Test + public void addDate() throws VPackException { + final VPackBuilder builder = new VPackBuilder(); + final Date date = new Date(); + builder.add(date); + + final VPackSlice slice = builder.slice(); + assertThat(slice.isDate(), is(true)); + assertThat(slice.getAsDate(), is(date)); + } + + @Test + public void addSqlDate() throws VPackException { + final VPackBuilder builder = new VPackBuilder(); + final java.sql.Date date = new java.sql.Date(new Date().getTime()); + builder.add(date); + + final VPackSlice slice = builder.slice(); + assertThat(slice.isDate(), is(true)); + assertThat(slice.getAsSQLDate(), is(date)); + } + + @Test + public void addSqlTimestamp() throws VPackException { + final VPackBuilder builder = new VPackBuilder(); + final java.sql.Timestamp timestamp = new java.sql.Timestamp(new Date().getTime()); + builder.add(timestamp); + + final VPackSlice slice = builder.slice(); + assertThat(slice.isDate(), is(true)); + assertThat(slice.getAsSQLTimestamp(), is(timestamp)); + } + + @Test + public void addStringShort() throws VPackException { + final VPackBuilder builder = new VPackBuilder(); + final String s = "Hallo Welt!"; + builder.add(s); + + final VPackSlice slice = builder.slice(); + assertThat(slice.isString(), is(true)); + assertThat(slice.getAsString(), is(s)); + } + + @Test + public void addStringLong() throws VPackException { + final VPackBuilder builder = new VPackBuilder(); + final String s = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus."; + builder.add(s); + + final VPackSlice slice = builder.slice(); + assertThat(slice.isString(), is(true)); + assertThat(slice.getAsString(), is(s)); + } + + @Test + public void emptyArray() throws VPackException { + final VPackBuilder builder = new VPackBuilder(); + builder.add(ValueType.ARRAY); + builder.close(); + + final VPackSlice slice = builder.slice(); + assertThat(slice.isArray(), is(true)); + assertThat(slice.getLength(), is(0)); + try { + slice.get(0); + fail(); + } catch (final IndexOutOfBoundsException e) { + + } + } + + @Test + public void compactArray() throws VPackException { + final long[] expected = { 1, 16 }; + final VPackBuilder builder = new VPackBuilder(); + builder.add(ValueType.ARRAY, true); + for (final long l : expected) { + builder.add(l); + } + builder.close(); + + final VPackSlice slice = builder.slice(); + assertThat(slice.isArray(), is(true)); + assertThat(slice.getLength(), is(2)); + for (int i = 0; i < expected.length; i++) { + final VPackSlice at = slice.get(i); + assertThat(at.isInteger(), is(true)); + assertThat(at.getAsLong(), is(expected[i])); + } + } + + @Test + public void arrayItemsSameLength() throws VPackException { + VPackSlice sliceNotSame; + { + final VPackBuilder builder = new VPackBuilder(); + builder.add(ValueType.ARRAY); + builder.add("aa"); + builder.add("a"); + builder.close(); + sliceNotSame = builder.slice(); + } + VPackSlice sliceSame; + { + final VPackBuilder builder = new VPackBuilder(); + builder.add(ValueType.ARRAY); + builder.add("aa"); + builder.add("aa"); + builder.close(); + sliceSame = builder.slice(); + } + assertThat(sliceSame.getByteSize() < sliceNotSame.getByteSize(), is(true)); + } + + @Test + public void unindexedArray() throws VPackException { + final long[] expected = { 1, 16 }; + final VPackBuilder builder = new VPackBuilder(); + builder.getOptions().setBuildUnindexedArrays(true); + builder.add(ValueType.ARRAY, false); + for (final long l : expected) { + builder.add(l); + } + builder.close(); + + final VPackSlice slice = builder.slice(); + assertThat(slice.isArray(), is(true)); + assertThat(slice.getLength(), is(2)); + for (int i = 0; i < expected.length; i++) { + final VPackSlice at = slice.get(i); + assertThat(at.isInteger(), is(true)); + assertThat(at.getAsLong(), is(expected[i])); + } + } + + @Test + public void indexedArray() throws VPackException { + final long[] values = { 1, 2, 3 }; + final VPackBuilder builder = new VPackBuilder(); + builder.add(ValueType.ARRAY); + for (final long l : values) { + builder.add(l); + } + builder.close(); + + final VPackSlice slice = builder.slice(); + assertThat(slice.isArray(), is(true)); + assertThat(slice.getLength(), is(3)); + } + + @Test + public void indexedArray2ByteLength() throws VPackException { + final int valueCount = 100; + final VPackBuilder builder = new VPackBuilder(); + builder.add(ValueType.ARRAY); + for (long i = 0; i < valueCount; i++) { + builder.add( + i + "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus."); + } + builder.close(); + + final VPackSlice slice = builder.slice(); + assertThat(slice.head(), is((byte) 0x07)); + assertThat(slice.isArray(), is(true)); + assertThat(slice.getLength(), is(valueCount)); + } + + @Test + public void indexedArray2ByteLengthNoIndexTable() throws VPackException { + final int valueCount = 100; + final VPackBuilder builder = new VPackBuilder(); + builder.add(ValueType.ARRAY); + for (long i = 0; i < valueCount; i++) { + builder.add( + "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus."); + } + builder.close(); + + final VPackSlice slice = builder.slice(); + assertThat(slice.head(), is((byte) 0x03)); + assertThat(slice.isArray(), is(true)); + assertThat(slice.getLength(), is(valueCount)); + } + + @Test + public void indexedArray4ByteLength() throws VPackException { + final int valueCount = 200; + final VPackBuilder builder = new VPackBuilder(); + builder.add(ValueType.ARRAY); + for (long i = 0; i < valueCount; i++) { + builder.add( + "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus."); + } + builder.close(); + + final VPackSlice slice = builder.slice(); + assertThat(slice.head(), is((byte) 0x04)); + assertThat(slice.isArray(), is(true)); + assertThat(slice.getLength(), is(valueCount)); + } + + @Test + public void indexedArray4ByteLengthNoIndexTable() throws VPackException { + final int valueCount = 200; + final VPackBuilder builder = new VPackBuilder(); + builder.add(ValueType.ARRAY); + for (long i = 0; i < valueCount; i++) { + builder.add( + i + "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus."); + } + builder.close(); + + final VPackSlice slice = builder.slice(); + assertThat(slice.head(), is((byte) 0x08)); + assertThat(slice.isArray(), is(true)); + assertThat(slice.getLength(), is(valueCount)); + } + + @Test + public void arrayInArray() throws VPackException { + final long[][] values = { { 1, 2, 3 }, { 1, 2, 3 } }; + final VPackBuilder builder = new VPackBuilder(); + builder.add(ValueType.ARRAY); + for (final long[] ls : values) { + builder.add(ValueType.ARRAY); + for (final long l : ls) { + builder.add(l); + } + builder.close(); + } + builder.close(); + + final VPackSlice slice = builder.slice(); + assertThat(slice.isArray(), is(true)); + assertThat(slice.getLength(), is(values.length)); + for (int i = 0; i < values.length; i++) { + final VPackSlice ls = slice.get(i); + assertThat(ls.isArray(), is(true)); + assertThat(ls.getLength(), is(values[i].length)); + for (int j = 0; j < values[i].length; j++) { + final VPackSlice l = ls.get(j); + assertThat(l.isInteger(), is(true)); + assertThat(l.getAsLong(), is(values[i][j])); + } + } + } + + @Test + public void arrayInArrayInArray() throws VPackException { + final long[][][] values = { { { 1, 2, 3 } } }; + final VPackBuilder builder = new VPackBuilder(); + builder.add(ValueType.ARRAY); + for (final long[][] lss : values) { + builder.add(ValueType.ARRAY); + for (final long[] ls : lss) { + builder.add(ValueType.ARRAY); + for (final long l : ls) { + builder.add(l); + } + builder.close(); + } + builder.close(); + } + builder.close(); + + final VPackSlice slice = builder.slice(); + assertThat(slice.isArray(), is(true)); + assertThat(slice.getLength(), is(values.length)); + for (int i = 0; i < values.length; i++) { + final VPackSlice lls = slice.get(i); + assertThat(lls.isArray(), is(true)); + assertThat(lls.getLength(), is(values[i].length)); + for (int j = 0; j < values[i].length; j++) { + final VPackSlice ls = lls.get(i); + assertThat(ls.isArray(), is(true)); + assertThat(ls.getLength(), is(values[i][j].length)); + for (int k = 0; k < values[i][j].length; k++) { + final VPackSlice l = ls.get(k); + assertThat(l.isInteger(), is(true)); + assertThat(l.getAsLong(), is(values[i][j][k])); + } + } + + } + } + + @Test + public void emptyObject() throws VPackException { + final VPackBuilder builder = new VPackBuilder(); + builder.add(ValueType.OBJECT); + builder.close(); + + final VPackSlice slice = builder.slice(); + assertThat(slice.isObject(), is(true)); + assertThat(slice.getLength(), is(0)); + final VPackSlice a = slice.get("a"); + assertThat(a.isNone(), is(true)); + try { + slice.keyAt(0); + fail(); + } catch (final IndexOutOfBoundsException e) { + + } + try { + slice.valueAt(0); + fail(); + } catch (final IndexOutOfBoundsException e) { + + } + } + + @Test + public void compactObject() throws VPackException { + // {"a": 12, "b": true, "c": "xyz"} + final VPackBuilder builder = new VPackBuilder(); + builder.add(ValueType.OBJECT, true); + builder.add("a", 12); + builder.add("b", true); + builder.add("c", "xyz"); + builder.close(); + + final VPackSlice slice = builder.slice(); + assertThat(slice.isObject(), is(true)); + assertThat(slice.getLength(), is(3)); + assertThat(slice.get("a").getAsLong(), is(12L)); + assertThat(slice.get("b").getAsBoolean(), is(true)); + assertThat(slice.get("c").getAsString(), is("xyz")); + } + + @Test + public void unindexedObject() throws VPackException { + // {"a": 12, "b": true, "c": "xyz"} + final VPackBuilder builder = new VPackBuilder(); + builder.getOptions().setBuildUnindexedObjects(true); + builder.add(ValueType.OBJECT, false); + builder.add("a", 12); + builder.add("b", true); + builder.add("c", "xyz"); + builder.close(); + + final VPackSlice slice = builder.slice(); + assertThat(slice.isObject(), is(true)); + assertThat(slice.getLength(), is(3)); + assertThat(slice.get("a").getAsLong(), is(12L)); + assertThat(slice.get("b").getAsBoolean(), is(true)); + assertThat(slice.get("c").getAsString(), is("xyz")); + } + + @Test + public void indexedObject() throws VPackException { + // {"a": 12, "b": true, "c": "xyz"} + final VPackBuilder builder = new VPackBuilder(); + builder.add(ValueType.OBJECT); + builder.add("a", 12); + builder.add("b", true); + builder.add("c", "xyz"); + builder.close(); + + final VPackSlice slice = builder.slice(); + assertThat(slice.isObject(), is(true)); + assertThat(slice.getLength(), is(3)); + assertThat(slice.get("a").getAsLong(), is(12L)); + assertThat(slice.get("b").getAsBoolean(), is(true)); + assertThat(slice.get("c").getAsString(), is("xyz")); + } + + @Test + public void objectInObject() throws VPackException { + // {"a":{"a1":1,"a2":2},"b":{"b1":1,"b2":1}} + final VPackBuilder builder = new VPackBuilder(); + builder.add(ValueType.OBJECT); + { + builder.add("a", ValueType.OBJECT); + builder.add("a1", 1); + builder.add("a2", 2); + builder.close(); + } + { + builder.add("b", ValueType.OBJECT); + builder.add("b1", 1); + builder.add("b2", 2); + builder.close(); + } + builder.close(); + + final VPackSlice slice = builder.slice(); + assertThat(slice.isObject(), is(true)); + assertThat(slice.getLength(), is(2)); + { + final VPackSlice a = slice.get("a"); + assertThat(a.isObject(), is(true)); + assertThat(a.getLength(), is(2)); + assertThat(a.get("a1").getAsLong(), is(1L)); + assertThat(a.get("a2").getAsLong(), is(2L)); + } + { + final VPackSlice b = slice.get("b"); + assertThat(b.isObject(), is(true)); + assertThat(b.getLength(), is(2)); + assertThat(b.get("b1").getAsLong(), is(1L)); + assertThat(b.get("b2").getAsLong(), is(2L)); + } + } + + @Test + public void objectInObjectInObject() throws VPackException { + // {"a":{"b":{"c":{"d":true}}} + final VPackBuilder builder = new VPackBuilder(); + builder.add(ValueType.OBJECT); + builder.add("a", ValueType.OBJECT); + builder.add("b", ValueType.OBJECT); + builder.add("c", ValueType.OBJECT); + builder.add("d", true); + builder.close(); + builder.close(); + builder.close(); + builder.close(); + + final VPackSlice slice = builder.slice(); + assertThat(slice.isObject(), is(true)); + assertThat(slice.getLength(), is(1)); + final VPackSlice a = slice.get("a"); + assertThat(a.isObject(), is(true)); + assertThat(a.getLength(), is(1)); + final VPackSlice b = a.get("b"); + assertThat(b.isObject(), is(true)); + assertThat(b.getLength(), is(1)); + final VPackSlice c = b.get("c"); + assertThat(c.isObject(), is(true)); + assertThat(c.getLength(), is(1)); + final VPackSlice d = c.get("d"); + assertThat(d.isBoolean(), is(true)); + assertThat(d.isTrue(), is(true)); + } + + @Test + public void objectAttributeNotFound() throws VPackException { + final VPackBuilder builder = new VPackBuilder(); + builder.add(ValueType.OBJECT); + builder.add("a", "a"); + builder.close(); + final VPackSlice vpack = builder.slice(); + assertThat(vpack.isObject(), is(true)); + final VPackSlice b = vpack.get("b"); + assertThat(b.isNone(), is(true)); + } + + @Test + public void object1ByteOffset() throws VPackException { + final VPackBuilder builder = new VPackBuilder(); + builder.add(ValueType.OBJECT); + final int size = 5; + for (int i = 0; i < size; i++) { + builder.add(String.valueOf(i), ValueType.OBJECT); + for (int j = 0; j < size; j++) { + builder.add(String.valueOf(j), "test"); + } + builder.close(); + } + builder.close(); + final VPackSlice vpack = builder.slice(); + assertThat(vpack.isObject(), is(true)); + assertThat(vpack.getLength(), is(size)); + for (int i = 0; i < size; i++) { + final VPackSlice attr = vpack.get(String.valueOf(i)); + assertThat(attr.isObject(), is(true)); + for (int j = 0; j < size; j++) { + final VPackSlice childAttr = attr.get(String.valueOf(j)); + assertThat(childAttr.isString(), is(true)); + } + } + } + + @Test + public void object2ByteOffset() throws VPackException { + final VPackBuilder builder = new VPackBuilder(); + builder.add(ValueType.OBJECT); + final int size = 10; + for (int i = 0; i < size; i++) { + builder.add(String.valueOf(i), ValueType.OBJECT); + for (int j = 0; j < size; j++) { + builder.add(String.valueOf(j), "test"); + } + builder.close(); + } + builder.close(); + final VPackSlice vpack = builder.slice(); + assertThat(vpack.isObject(), is(true)); + assertThat(vpack.getLength(), is(size)); + for (int i = 0; i < size; i++) { + final VPackSlice attr = vpack.get(String.valueOf(i)); + assertThat(attr.isObject(), is(true)); + for (int j = 0; j < size; j++) { + final VPackSlice childAttr = attr.get(String.valueOf(j)); + assertThat(childAttr.isString(), is(true)); + } + } + } + + @Test + public void sortObjectAttr() throws VPackException { + final int min = 0; + final int max = 9; + final VPackBuilder builder = new VPackBuilder(); + builder.add(ValueType.OBJECT); + for (int i = max; i >= min; i--) { + builder.add(String.valueOf(i), "test"); + } + builder.close(); + final VPackSlice vpack = builder.slice(); + assertThat(vpack.isObject(), is(true)); + assertThat(vpack.getLength(), is(max - min + 1)); + for (int i = min, j = 0; i <= max; i++, j++) { + assertThat(vpack.keyAt(j).getAsString(), is(String.valueOf(i))); + } + } + + @Test + public void sortObjectAttr2() throws VPackException { + final String[] keys = { "a", "b", "c", "d", "e", "f", "g", "h" }; + final String[] keysUnsorted = { "b", "d", "c", "e", "g", "f", "h", "a" }; + assertThat(keysUnsorted.length, is(keys.length)); + final VPackBuilder builder = new VPackBuilder(); + builder.add(ValueType.OBJECT); + for (int i = 0; i < keysUnsorted.length; i++) { + builder.add(String.valueOf(keysUnsorted[i]), "test"); + } + builder.close(); + final VPackSlice vpack = builder.slice(); + assertThat(vpack.isObject(), is(true)); + assertThat(vpack.getLength(), is(keys.length)); + for (int i = 0; i < keys.length; i++) { + assertThat(vpack.keyAt(i).getAsString(), is(String.valueOf(keys[i]))); + } + } + + @Test + public void attributeAdapterDefaults() throws VPackException { + final VPackSlice vpackWithAttrAdapter; + { + final VPackBuilder builder = new VPackBuilder(); + builder.add(ValueType.OBJECT); + builder.add("_key", "a"); + builder.close(); + vpackWithAttrAdapter = builder.slice(); + assertThat(vpackWithAttrAdapter.isObject(), is(true)); + } + final VPackSlice vpackWithoutAttrAdapter; + { + final VPackBuilder builder = new VPackBuilder(); + builder.add(ValueType.OBJECT); + builder.add("_kay", "a"); + builder.close(); + vpackWithoutAttrAdapter = builder.slice(); + assertThat(vpackWithoutAttrAdapter.isObject(), is(true)); + } + assertThat(vpackWithAttrAdapter.getByteSize() < vpackWithoutAttrAdapter.getByteSize(), is(true)); + } + + @Test(expected = VPackBuilderNeedOpenCompoundException.class) + public void closeClosed() throws VPackException { + final VPackBuilder builder = new VPackBuilder(); + builder.add(ValueType.OBJECT); + builder.close(); + builder.close(); + } + + @Test + public void addBinary() throws VPackException { + final byte[] expected = new byte[] { 49, 50, 51, 52, 53, 54, 55, 56, 57 }; + final VPackBuilder builder = new VPackBuilder(); + builder.add(expected); + final VPackSlice slice = builder.slice(); + + assertThat(slice.isBinary(), is(true)); + assertThat(slice.getBinaryLength(), is(expected.length)); + assertThat(slice.getAsBinary(), is(expected)); + assertThat(slice.getByteSize(), is(1 + 4 + expected.length)); + } + + @Test + public void addVPack() throws VPackException { + final VPackBuilder builder = new VPackBuilder(); + builder.add(ValueType.OBJECT); + builder.add("s", new VPackBuilder().add("test").slice()); + builder.close(); + final VPackSlice slice = builder.slice(); + assertThat(slice, is(notNullValue())); + assertThat(slice.isObject(), is(true)); + assertThat(slice.get("s").isString(), is(true)); + assertThat(slice.get("s").getAsString(), is("test")); + assertThat(slice.size(), is(1)); + } + + @Test + public void addVPackObject() throws VPackException { + final VPackBuilder builder = new VPackBuilder(); + builder.add(ValueType.OBJECT); + { + final VPackBuilder builder2 = new VPackBuilder(); + builder2.add(ValueType.OBJECT); + builder2.add("s", "test"); + builder2.close(); + builder.add("o", builder2.slice()); + } + builder.close(); + final VPackSlice slice = builder.slice(); + assertThat(slice, is(notNullValue())); + assertThat(slice.isObject(), is(true)); + assertThat(slice.get("o").isObject(), is(true)); + assertThat(slice.get("o").get("s").isString(), is(true)); + assertThat(slice.get("o").get("s").getAsString(), is("test")); + assertThat(slice.size(), is(1)); + assertThat(slice.get("o").size(), is(1)); + } + + @Test + public void addVPackObjectInArray() throws VPackException { + final VPackBuilder builder = new VPackBuilder(); + builder.add(ValueType.ARRAY); + for (int i = 0; i < 10; i++) { + final VPackBuilder builder2 = new VPackBuilder(); + builder2.add(ValueType.OBJECT); + builder2.add("s", "test"); + builder2.close(); + builder.add(builder2.slice()); + } + builder.close(); + final VPackSlice slice = builder.slice(); + assertThat(slice, is(notNullValue())); + assertThat(slice.isArray(), is(true)); + assertThat(slice.size(), is(10)); + for (int i = 0; i < 10; i++) { + assertThat(slice.get(i).isObject(), is(true)); + assertThat(slice.get(i).get("s").isString(), is(true)); + assertThat(slice.get(i).get("s").getAsString(), is("test")); + assertThat(slice.get(i).size(), is(1)); + } + } + +} diff --git a/src/test/java/com/arangodb/velocypack/VPackParserTest.java b/src/test/java/com/arangodb/velocypack/VPackParserTest.java new file mode 100644 index 000000000..7defce3b2 --- /dev/null +++ b/src/test/java/com/arangodb/velocypack/VPackParserTest.java @@ -0,0 +1,448 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.velocypack; + +import static org.hamcrest.Matchers.is; +import static org.junit.Assert.assertThat; + +import org.json.simple.JSONValue; +import org.junit.Test; + +import com.arangodb.velocypack.exception.VPackException; + +/** + * @author Mark - mark at arangodb.com + * + */ +public class VPackParserTest { + + @Test + public void toJsonObject1Field() throws VPackException { + final VPackBuilder builder = new VPackBuilder(); + builder.add(ValueType.OBJECT); + builder.add("a", "test"); + builder.close(); + final String json = new VPackParser().toJson(builder.slice()); + assertThat(json, is("{\"a\":\"test\"}")); + } + + @Test + public void toJsonObject2Fields() throws VPackException { + final VPackBuilder builder = new VPackBuilder(); + builder.add(ValueType.OBJECT); + builder.add("a", "test"); + builder.add("b", true); + builder.close(); + final String json = new VPackParser().toJson(builder.slice()); + assertThat(json, is("{\"a\":\"test\",\"b\":true}")); + } + + @Test + public void toJsonObjectStringField() throws VPackException { + final VPackBuilder builder = new VPackBuilder(); + builder.add(ValueType.OBJECT); + builder.add("a", "test"); + builder.add("b", "test"); + builder.close(); + final String json = new VPackParser().toJson(builder.slice()); + assertThat(json, is("{\"a\":\"test\",\"b\":\"test\"}")); + } + + @Test + public void toJsonObjectBooleanField() throws VPackException { + final VPackBuilder builder = new VPackBuilder(); + builder.add(ValueType.OBJECT); + builder.add("a", true); + builder.add("b", false); + builder.close(); + final String json = new VPackParser().toJson(builder.slice()); + assertThat(json, is("{\"a\":true,\"b\":false}")); + } + + @Test + public void toJsonObjectNumberField() throws VPackException { + final VPackBuilder builder = new VPackBuilder(); + builder.add(ValueType.OBJECT); + builder.add("a", 5); + builder.add("b", 5.5); + builder.close(); + final String json = new VPackParser().toJson(builder.slice()); + assertThat(json, is("{\"a\":5,\"b\":5.5}")); + } + + @Test + public void toJsonArrayInObject() throws VPackException { + final VPackBuilder builder = new VPackBuilder(); + builder.add(ValueType.OBJECT); + builder.add("a", ValueType.ARRAY); + builder.add(1); + builder.add(2); + builder.add(3); + builder.close(); + builder.add("b", ValueType.ARRAY); + builder.add("a"); + builder.add("b"); + builder.add("c"); + builder.close(); + builder.close(); + final String json = new VPackParser().toJson(builder.slice()); + assertThat(json, is("{\"a\":[1,2,3],\"b\":[\"a\",\"b\",\"c\"]}")); + } + + @Test + public void toJsonObjectInObject() throws VPackException { + final VPackBuilder builder = new VPackBuilder(); + builder.add(ValueType.OBJECT); + builder.add("a", ValueType.OBJECT); + builder.add("aa", "test"); + builder.add("ab", true); + builder.close(); + builder.add("b", ValueType.OBJECT); + builder.add("ba", "test"); + builder.add("bb", 5.5); + builder.close(); + builder.close(); + final String json = new VPackParser().toJson(builder.slice()); + assertThat(json, is("{\"a\":{\"aa\":\"test\",\"ab\":true},\"b\":{\"ba\":\"test\",\"bb\":5.5}}")); + } + + @Test + public void toJsonObjectInArray() throws VPackException { + final VPackBuilder builder = new VPackBuilder(); + builder.add(ValueType.ARRAY); + builder.add(ValueType.OBJECT); + builder.add("a", "test"); + builder.close(); + builder.add(ValueType.OBJECT); + builder.add("a", "test"); + builder.close(); + builder.close(); + final String json = new VPackParser().toJson(builder.slice()); + assertThat(json, is("[{\"a\":\"test\"},{\"a\":\"test\"}]")); + } + + @Test + public void toJsonArrayInArray() throws VPackException { + final VPackBuilder builder = new VPackBuilder(); + builder.add(ValueType.ARRAY); + builder.add(ValueType.ARRAY); + builder.add(1); + builder.add(2); + builder.add(3); + builder.close(); + builder.add(ValueType.ARRAY); + builder.add("a"); + builder.add("b"); + builder.add("c"); + builder.close(); + builder.close(); + final String json = new VPackParser().toJson(builder.slice()); + assertThat(json, is("[[1,2,3],[\"a\",\"b\",\"c\"]]")); + } + + @Test + public void toJsonExcludeNullValueInObject() throws VPackException { + final VPackBuilder builder = new VPackBuilder(); + builder.add(ValueType.OBJECT); + builder.add("a", ValueType.NULL); + final String b = null; + builder.add("b", b); + builder.add("c", "test"); + builder.close(); + final String json = new VPackParser().toJson(builder.slice(), false); + assertThat(json, is("{\"c\":\"test\"}")); + } + + @Test + public void toJsonIncludeNullValueInObject() throws VPackException { + final VPackBuilder builder = new VPackBuilder(); + builder.add(ValueType.OBJECT); + builder.add("a", ValueType.NULL); + final String b = null; + builder.add("b", b); + builder.add("c", "test"); + builder.close(); + final String json = new VPackParser().toJson(builder.slice(), true); + assertThat(json, is("{\"a\":null,\"b\":null,\"c\":\"test\"}")); + } + + @Test + public void toJsonExcludeNullValueInArray() throws VPackException { + final VPackBuilder builder = new VPackBuilder(); + builder.add(ValueType.ARRAY); + builder.add(ValueType.NULL); + final String s = null; + builder.add(s); + builder.add("test"); + builder.close(); + final String json = new VPackParser().toJson(builder.slice(), false); + assertThat(json, is("[\"test\"]")); + } + + @Test + public void toJsonIncludeNullValueInArray() throws VPackException { + final VPackBuilder builder = new VPackBuilder(); + builder.add(ValueType.ARRAY); + builder.add(ValueType.NULL); + final String s = null; + builder.add(s); + builder.add("test"); + builder.close(); + final String json = new VPackParser().toJson(builder.slice(), true); + assertThat(json, is("[null,null,\"test\"]")); + } + + @Test + public void fromJsonObject1Field() throws VPackException { + final VPackSlice vpack = new VPackParser().fromJson("{\"a\":\"test\"}"); + assertThat(vpack.isObject(), is(true)); + final VPackSlice a = vpack.get("a"); + assertThat(a.isString(), is(true)); + assertThat(a.getAsString(), is("test")); + } + + @Test + public void fromJsonObject2Fields() throws VPackException { + final VPackSlice vpack = new VPackParser().fromJson("{\"a\":\"test\",\"b\":true}"); + assertThat(vpack.isObject(), is(true)); + final VPackSlice a = vpack.get("a"); + assertThat(a.isString(), is(true)); + assertThat(a.getAsString(), is("test")); + final VPackSlice b = vpack.get("b"); + assertThat(b.isBoolean(), is(true)); + assertThat(b.getAsBoolean(), is(true)); + } + + @Test + public void fromJsonObjectStringField() throws VPackException { + final VPackSlice vpack = new VPackParser().fromJson("{\"a\":\"test1\",\"b\":\"test2\"}"); + assertThat(vpack.isObject(), is(true)); + final VPackSlice a = vpack.get("a"); + assertThat(a.isString(), is(true)); + assertThat(a.getAsString(), is("test1")); + final VPackSlice b = vpack.get("b"); + assertThat(b.isString(), is(true)); + assertThat(b.getAsString(), is("test2")); + } + + @Test + public void fromJsonObjectBooleanField() throws VPackException { + final VPackSlice vpack = new VPackParser().fromJson("{\"a\":true,\"b\":false}"); + assertThat(vpack.isObject(), is(true)); + final VPackSlice a = vpack.get("a"); + assertThat(a.isBoolean(), is(true)); + assertThat(a.getAsBoolean(), is(true)); + final VPackSlice b = vpack.get("b"); + assertThat(b.isBoolean(), is(true)); + assertThat(b.getAsBoolean(), is(false)); + } + + @Test + public void fromJsonObjectNumberField() throws VPackException { + final VPackSlice vpack = new VPackParser().fromJson("{\"a\":5,\"b\":5.5}"); + assertThat(vpack.isObject(), is(true)); + final VPackSlice a = vpack.get("a"); + assertThat(a.isInteger(), is(true)); + assertThat(a.getAsInt(), is(5)); + final VPackSlice b = vpack.get("b"); + assertThat(b.isDouble(), is(true)); + assertThat(b.getAsDouble(), is(5.5)); + } + + @Test + public void fromJsonArrayInObject() throws VPackException { + final VPackSlice vpack = new VPackParser().fromJson("{\"a\":[1,2,3],\"b\":[\"a\",\"b\",\"c\"]}"); + assertThat(vpack.isObject(), is(true)); + final VPackSlice a = vpack.get("a"); + assertThat(a.isArray(), is(true)); + assertThat(a.size(), is(3)); + assertThat(a.get(0).isInteger(), is(true)); + assertThat(a.get(0).getAsInt(), is(1)); + assertThat(a.get(1).isInteger(), is(true)); + assertThat(a.get(1).getAsInt(), is(2)); + assertThat(a.get(2).isInteger(), is(true)); + assertThat(a.get(2).getAsInt(), is(3)); + final VPackSlice b = vpack.get("b"); + assertThat(b.isArray(), is(true)); + assertThat(b.size(), is(3)); + assertThat(b.get(0).isString(), is(true)); + assertThat(b.get(0).getAsString(), is("a")); + assertThat(b.get(1).isString(), is(true)); + assertThat(b.get(1).getAsString(), is("b")); + assertThat(b.get(2).isString(), is(true)); + assertThat(b.get(2).getAsString(), is("c")); + } + + @Test + public void fromJsonObjectInObject() throws VPackException { + final VPackSlice vpack = new VPackParser() + .fromJson("{\"a\":{\"aa\":\"test\",\"ab\":true},\"b\":{\"ba\":\"test\",\"bb\":5.5}}"); + assertThat(vpack.isObject(), is(true)); + assertThat(vpack.size(), is(2)); + final VPackSlice a = vpack.get("a"); + assertThat(a.isObject(), is(true)); + assertThat(a.size(), is(2)); + final VPackSlice aa = a.get("aa"); + assertThat(aa.isString(), is(true)); + assertThat(aa.getAsString(), is("test")); + final VPackSlice ab = a.get("ab"); + assertThat(ab.isBoolean(), is(true)); + assertThat(ab.getAsBoolean(), is(true)); + final VPackSlice b = vpack.get("b"); + assertThat(b.isObject(), is(true)); + assertThat(b.size(), is(2)); + final VPackSlice ba = b.get("ba"); + assertThat(ba.isString(), is(true)); + assertThat(ba.getAsString(), is("test")); + final VPackSlice bb = b.get("bb"); + assertThat(bb.isDouble(), is(true)); + assertThat(bb.getAsDouble(), is(5.5)); + } + + @Test + public void fromJsonObjectInArray() throws VPackException { + final VPackSlice vpack = new VPackParser().fromJson("[{\"a\":\"test\"},{\"a\":\"test\"}]"); + assertThat(vpack.isArray(), is(true)); + assertThat(vpack.size(), is(2)); + final VPackSlice z = vpack.get(0); + assertThat(z.isObject(), is(true)); + assertThat(z.size(), is(1)); + final VPackSlice za = z.get("a"); + assertThat(za.isString(), is(true)); + assertThat(za.getAsString(), is("test")); + final VPackSlice o = vpack.get(1); + assertThat(o.isObject(), is(true)); + assertThat(o.size(), is(1)); + final VPackSlice oa = o.get("a"); + assertThat(oa.isString(), is(true)); + assertThat(oa.getAsString(), is("test")); + } + + @Test + public void fromJsonArrayInArray() throws VPackException { + final VPackSlice vpack = new VPackParser().fromJson("[[1,2,3],[\"a\",\"b\",\"c\"]]"); + assertThat(vpack.isArray(), is(true)); + assertThat(vpack.size(), is(2)); + final VPackSlice z = vpack.get(0); + assertThat(z.isArray(), is(true)); + assertThat(z.size(), is(3)); + assertThat(z.get(0).isInteger(), is(true)); + assertThat(z.get(0).getAsInt(), is(1)); + assertThat(z.get(1).isInteger(), is(true)); + assertThat(z.get(1).getAsInt(), is(2)); + assertThat(z.get(2).isInteger(), is(true)); + assertThat(z.get(2).getAsInt(), is(3)); + final VPackSlice o = vpack.get(1); + assertThat(o.isArray(), is(true)); + assertThat(o.size(), is(3)); + assertThat(o.get(0).isString(), is(true)); + assertThat(o.get(0).getAsString(), is("a")); + assertThat(o.get(1).isString(), is(true)); + assertThat(o.get(1).getAsString(), is("b")); + assertThat(o.get(2).isString(), is(true)); + assertThat(o.get(2).getAsString(), is("c")); + } + + @Test + public void fromJsonExcludeNullValueInObject() throws VPackException { + final VPackSlice vpack = new VPackParser().fromJson("{\"a\":null,\"b\":null,\"c\":\"test\"}", false); + assertThat(vpack.isObject(), is(true)); + assertThat(vpack.size(), is(1)); + assertThat(vpack.get("a").isNone(), is(true)); + assertThat(vpack.get("b").isNone(), is(true)); + assertThat(vpack.get("c").isString(), is(true)); + assertThat(vpack.get("c").getAsString(), is("test")); + } + + @Test + public void fromJsonIncludeNullValueInObject() throws VPackException { + final VPackSlice vpack = new VPackParser().fromJson("{\"a\":null,\"b\":null,\"c\":\"test\"}", true); + assertThat(vpack.isObject(), is(true)); + assertThat(vpack.size(), is(3)); + assertThat(vpack.get("a").isNull(), is(true)); + assertThat(vpack.get("b").isNull(), is(true)); + assertThat(vpack.get("c").isString(), is(true)); + assertThat(vpack.get("c").getAsString(), is("test")); + } + + @Test + public void fromJsonExcludeNullValueInArray() throws VPackException { + final VPackSlice vpack = new VPackParser().fromJson("[null,null,\"test\"]", false); + assertThat(vpack.isArray(), is(true)); + assertThat(vpack.size(), is(1)); + assertThat(vpack.get(0).isString(), is(true)); + assertThat(vpack.get(0).getAsString(), is("test")); + } + + @Test + public void fromJsonIncludeNullValueInArray() throws VPackException { + final VPackSlice vpack = new VPackParser().fromJson("[null,null,\"test\"]", true); + assertThat(vpack.isArray(), is(true)); + assertThat(vpack.size(), is(3)); + assertThat(vpack.get(0).isNull(), is(true)); + assertThat(vpack.get(1).isNull(), is(true)); + assertThat(vpack.get(2).isString(), is(true)); + assertThat(vpack.get(2).getAsString(), is("test")); + } + + @Test + public void customDeserializer() throws VPackException { + final VPackBuilder builder = new VPackBuilder(); + builder.add(ValueType.OBJECT); + builder.add("a", "a"); + builder.add("b", "b"); + builder.close(); + final VPackJsonDeserializer deserializer = new VPackJsonDeserializer() { + @Override + public void deserialize( + final VPackSlice parent, + final String attribute, + final VPackSlice vpack, + final StringBuilder json) throws VPackException { + json.append(JSONValue.toJSONString(vpack.getAsString() + "1")); + } + }; + final String json = new VPackParser().registerDeserializer(ValueType.STRING, deserializer) + .toJson(builder.slice()); + assertThat(json, is("{\"a\":\"a1\",\"b\":\"b1\"}")); + } + + @Test + public void customDeserializerByName() throws VPackException { + final VPackBuilder builder = new VPackBuilder(); + builder.add(ValueType.OBJECT); + builder.add("a", "a"); + builder.add("b", "b"); + builder.close(); + final String json = new VPackParser().registerDeserializer("a", ValueType.STRING, new VPackJsonDeserializer() { + @Override + public void deserialize( + final VPackSlice parent, + final String attribute, + final VPackSlice vpack, + final StringBuilder json) throws VPackException { + json.append(JSONValue.toJSONString(vpack.getAsString() + "1")); + } + }).toJson(builder.slice()); + assertThat(json, is("{\"a\":\"a1\",\"b\":\"b\"}")); + } + +} diff --git a/src/test/java/com/arangodb/velocypack/VPackSerializeDeserializeTest.java b/src/test/java/com/arangodb/velocypack/VPackSerializeDeserializeTest.java new file mode 100644 index 000000000..eb121b8dd --- /dev/null +++ b/src/test/java/com/arangodb/velocypack/VPackSerializeDeserializeTest.java @@ -0,0 +1,3295 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.velocypack; + +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; +import static org.junit.Assert.assertThat; + +import java.lang.reflect.Field; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Date; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +import org.junit.Test; + +import com.arangodb.velocypack.annotations.Expose; +import com.arangodb.velocypack.annotations.SerializedName; +import com.arangodb.velocypack.exception.VPackException; + +/** + * @author Mark - mark at arangodb.com + * + */ +public class VPackSerializeDeserializeTest { + + protected static class TestEntityBoolean { + private boolean a = true; + private boolean b = false; + private Boolean c = Boolean.TRUE; + private Boolean d = Boolean.FALSE; + + public boolean isA() { + return a; + } + + public void setA(final boolean a) { + this.a = a; + } + + public boolean isB() { + return b; + } + + public void setB(final boolean b) { + this.b = b; + } + + public Boolean getC() { + return c; + } + + public void setC(final Boolean c) { + this.c = c; + } + + public Boolean getD() { + return d; + } + + public void setD(final Boolean d) { + this.d = d; + } + } + + @Test + public void fromBoolean() throws VPackException { + final VPackSlice vpack = new VPack.Builder().build().serialize(new TestEntityBoolean()); + assertThat(vpack, is(notNullValue())); + assertThat(vpack.isObject(), is(true)); + { + final VPackSlice a = vpack.get("a"); + assertThat(a.isBoolean(), is(true)); + assertThat(a.getAsBoolean(), is(true)); + } + { + final VPackSlice b = vpack.get("b"); + assertThat(b.isBoolean(), is(true)); + assertThat(b.getAsBoolean(), is(false)); + } + { + final VPackSlice c = vpack.get("c"); + assertThat(c.isBoolean(), is(true)); + assertThat(c.getAsBoolean(), is(true)); + } + { + final VPackSlice d = vpack.get("d"); + assertThat(d.isBoolean(), is(true)); + assertThat(d.getAsBoolean(), is(false)); + } + } + + @Test + public void toBoolean() throws VPackException { + final VPackBuilder builder = new VPackBuilder(); + { + builder.add(ValueType.OBJECT); + builder.add("a", false); + builder.add("b", true); + builder.add("c", Boolean.FALSE); + builder.add("d", Boolean.TRUE); + builder.close(); + } + final VPackSlice vpack = builder.slice(); + final TestEntityBoolean entity = new VPack.Builder().build().deserialize(vpack, TestEntityBoolean.class); + assertThat(entity, is(notNullValue())); + assertThat(entity.a, is(false)); + assertThat(entity.b, is(true)); + assertThat(entity.c, is(Boolean.FALSE)); + assertThat(entity.d, is(Boolean.TRUE)); + } + + protected static class TestEntityString { + private String s = "test"; + private Character c1 = 't'; + private char c2 = 't'; + + public String getS() { + return s; + } + + public void setS(final String s) { + this.s = s; + } + + public Character getC1() { + return c1; + } + + public void setC1(final Character c1) { + this.c1 = c1; + } + + public char getC2() { + return c2; + } + + public void setC2(final char c2) { + this.c2 = c2; + } + } + + @Test + public void fromStrings() throws VPackException { + final VPackSlice vpack = new VPack.Builder().build().serialize(new TestEntityString()); + assertThat(vpack, is(notNullValue())); + assertThat(vpack.isObject(), is(true)); + { + final VPackSlice s = vpack.get("s"); + assertThat(s.isString(), is(true)); + assertThat(s.getAsString(), is("test")); + } + { + final VPackSlice c1 = vpack.get("c1"); + assertThat(c1.isString(), is(true)); + assertThat(c1.getAsChar(), is('t')); + } + { + final VPackSlice c2 = vpack.get("c2"); + assertThat(c2.isString(), is(true)); + assertThat(c2.getAsChar(), is('t')); + } + } + + @Test + public void toStrings() throws VPackException { + final VPackBuilder builder = new VPackBuilder(); + { + builder.add(ValueType.OBJECT); + builder.add("s", "abc"); + builder.add("c1", 'd'); + builder.add("c2", 'd'); + builder.close(); + } + final VPackSlice vpack = builder.slice(); + final TestEntityString entity = new VPack.Builder().build().deserialize(vpack, TestEntityString.class); + assertThat(entity, is(notNullValue())); + assertThat(entity.s, is("abc")); + assertThat(entity.c1, is(new Character('d'))); + assertThat(entity.c1, is(new Character('d'))); + } + + protected static class TestEntityInteger { + private int i1 = 1; + private Integer i2 = 1; + + public int getI1() { + return i1; + } + + public void setI1(final int i1) { + this.i1 = i1; + } + + public Integer getI2() { + return i2; + } + + public void setI2(final Integer i2) { + this.i2 = i2; + } + } + + @Test + public void fromInteger() throws VPackException { + final VPackSlice vpack = new VPack.Builder().build().serialize(new TestEntityInteger()); + assertThat(vpack, is(notNullValue())); + assertThat(vpack.isObject(), is(true)); + { + final VPackSlice i1 = vpack.get("i1"); + assertThat(i1.isInteger(), is(true)); + assertThat(i1.getAsInt(), is(1)); + } + { + final VPackSlice i2 = vpack.get("i2"); + assertThat(i2.isInteger(), is(true)); + assertThat(i2.getAsInt(), is(1)); + } + } + + @Test + public void toInteger() throws VPackException { + final VPackBuilder builder = new VPackBuilder(); + { + builder.add(ValueType.OBJECT); + builder.add("i1", 2); + builder.add("i2", 3); + builder.close(); + } + final VPackSlice vpack = builder.slice(); + final TestEntityInteger entity = new VPack.Builder().build().deserialize(vpack, TestEntityInteger.class); + assertThat(entity, is(notNullValue())); + assertThat(entity.i1, is(2)); + assertThat(entity.i2, is(new Integer(3))); + } + + protected static class TestEntityLong { + private long l1 = 1; + private Long l2 = 1L; + + public long getL1() { + return l1; + } + + public void setL1(final long l1) { + this.l1 = l1; + } + + public Long getL2() { + return l2; + } + + public void setL2(final Long l2) { + this.l2 = l2; + } + } + + @Test + public void fromLong() throws VPackException { + final VPackSlice vpack = new VPack.Builder().build().serialize(new TestEntityLong()); + assertThat(vpack, is(notNullValue())); + assertThat(vpack.isObject(), is(true)); + { + final VPackSlice l1 = vpack.get("l1"); + assertThat(l1.isInteger(), is(true)); + assertThat(l1.getAsLong(), is(1L)); + } + { + final VPackSlice l2 = vpack.get("l2"); + assertThat(l2.isInteger(), is(true)); + assertThat(l2.getAsLong(), is(1L)); + } + } + + @Test + public void toLong() throws VPackException { + final VPackBuilder builder = new VPackBuilder(); + { + builder.add(ValueType.OBJECT); + builder.add("l1", 2); + builder.add("l2", 3); + builder.close(); + } + final VPackSlice vpack = builder.slice(); + final TestEntityLong entity = new VPack.Builder().build().deserialize(vpack, TestEntityLong.class); + assertThat(entity, is(notNullValue())); + assertThat(entity.l1, is(2L)); + assertThat(entity.l2, is(new Long(3))); + } + + protected static class TestEntityFloat { + private float f1 = 1; + private Float f2 = 1F; + + public float getF1() { + return f1; + } + + public void setF1(final float f1) { + this.f1 = f1; + } + + public Float getF2() { + return f2; + } + + public void setF2(final Float f2) { + this.f2 = f2; + } + } + + @Test + public void fromFloat() throws VPackException { + final VPackSlice vpack = new VPack.Builder().build().serialize(new TestEntityFloat()); + assertThat(vpack, is(notNullValue())); + assertThat(vpack.isObject(), is(true)); + { + final VPackSlice f1 = vpack.get("f1"); + assertThat(f1.isDouble(), is(true)); + assertThat(f1.getAsFloat(), is(1.0F)); + } + { + final VPackSlice f2 = vpack.get("f2"); + assertThat(f2.isDouble(), is(true)); + assertThat(f2.getAsFloat(), is(1.0F)); + } + } + + @Test + public void toFloat() throws VPackException { + final VPackBuilder builder = new VPackBuilder(); + { + builder.add(ValueType.OBJECT); + builder.add("f1", 2F); + builder.add("f2", 3F); + builder.close(); + } + final VPackSlice vpack = builder.slice(); + final TestEntityFloat entity = new VPack.Builder().build().deserialize(vpack, TestEntityFloat.class); + assertThat(entity, is(notNullValue())); + assertThat(entity.f1, is(2F)); + assertThat(entity.f2, is(new Float(3))); + } + + protected static class TestEntityShort { + private short s1 = 1; + private Short s2 = 1; + + public short getS1() { + return s1; + } + + public void setS1(final short s1) { + this.s1 = s1; + } + + public Short getS2() { + return s2; + } + + public void setS2(final Short s2) { + this.s2 = s2; + } + } + + @Test + public void fromShort() throws VPackException { + final VPackSlice vpack = new VPack.Builder().build().serialize(new TestEntityShort()); + assertThat(vpack, is(notNullValue())); + assertThat(vpack.isObject(), is(true)); + { + final VPackSlice s1 = vpack.get("s1"); + assertThat(s1.isInteger(), is(true)); + assertThat(s1.getAsShort(), is((short) 1)); + } + { + final VPackSlice s2 = vpack.get("s2"); + assertThat(s2.isInteger(), is(true)); + assertThat(s2.getAsShort(), is((short) 1)); + } + } + + @Test + public void toShort() throws VPackException { + final VPackBuilder builder = new VPackBuilder(); + { + builder.add(ValueType.OBJECT); + builder.add("s1", 2); + builder.add("s2", 3); + builder.close(); + } + final VPackSlice vpack = builder.slice(); + final TestEntityShort entity = new VPack.Builder().build().deserialize(vpack, TestEntityShort.class); + assertThat(entity, is(notNullValue())); + assertThat(entity.s1, is((short) 2)); + assertThat(entity.s2, is(new Short((short) 3))); + } + + protected static class TestEntityDouble { + private Double d1 = 1.5; + private double d2 = 1.5; + + public Double getD1() { + return d1; + } + + public void setD1(final Double d1) { + this.d1 = d1; + } + + public double getD2() { + return d2; + } + + public void setD2(final double d2) { + this.d2 = d2; + } + } + + @Test + public void fromDouble() throws VPackException { + final VPackSlice vpack = new VPack.Builder().build().serialize(new TestEntityDouble()); + assertThat(vpack, is(notNullValue())); + assertThat(vpack.isObject(), is(true)); + { + final VPackSlice d1 = vpack.get("d1"); + assertThat(d1.isDouble(), is(true)); + assertThat(d1.getAsDouble(), is(1.5)); + } + { + final VPackSlice d2 = vpack.get("d2"); + assertThat(d2.isDouble(), is(true)); + assertThat(d2.getAsDouble(), is(1.5)); + } + } + + @Test + public void toDouble() throws VPackException { + final VPackBuilder builder = new VPackBuilder(); + { + builder.add(ValueType.OBJECT); + builder.add("d1", 2.25); + builder.add("d2", 3.75); + builder.close(); + } + final VPackSlice vpack = builder.slice(); + final TestEntityDouble entity = new VPack.Builder().build().deserialize(vpack, TestEntityDouble.class); + assertThat(entity, is(notNullValue())); + assertThat(entity.d1, is(2.25)); + assertThat(entity.d2, is(3.75)); + } + + protected static class TestEntityBigNumber { + private BigInteger bi = BigInteger.valueOf(1L); + private BigDecimal bd = BigDecimal.valueOf(1.5); + + public BigInteger getBi() { + return bi; + } + + public void setBi(final BigInteger bi) { + this.bi = bi; + } + + public BigDecimal getBd() { + return bd; + } + + public void setBd(final BigDecimal bd) { + this.bd = bd; + } + } + + @Test + public void fromBigNumbers() throws VPackException { + final VPackSlice vpack = new VPack.Builder().build().serialize(new TestEntityBigNumber()); + assertThat(vpack, is(notNullValue())); + assertThat(vpack.isObject(), is(true)); + { + final VPackSlice bi = vpack.get("bi"); + assertThat(bi.isInteger(), is(true)); + assertThat(bi.getAsBigInteger(), is(BigInteger.valueOf(1L))); + } + { + final VPackSlice bd = vpack.get("bd"); + assertThat(bd.isDouble(), is(true)); + assertThat(bd.getAsBigDecimal(), is(BigDecimal.valueOf(1.5))); + } + } + + @Test + public void toBigNumbers() throws VPackException { + final VPackBuilder builder = new VPackBuilder(); + { + builder.add(ValueType.OBJECT); + builder.add("bi", BigInteger.valueOf(2)); + builder.add("bd", BigDecimal.valueOf(3.75)); + builder.close(); + } + final VPackSlice vpack = builder.slice(); + final TestEntityBigNumber entity = new VPack.Builder().build().deserialize(vpack, TestEntityBigNumber.class); + assertThat(entity, is(notNullValue())); + assertThat(entity.bi, is(BigInteger.valueOf(2))); + assertThat(entity.bd, is(BigDecimal.valueOf(3.75))); + } + + protected static class TestEntityArray { + private String[] a1 = { "a", "b", "cd" }; + private int[] a2 = { 1, 2, 3, 4, 5 }; + private boolean[] a3 = { true, true, false }; + private TestEnum[] a4 = TestEnum.values(); + + public String[] getA1() { + return a1; + } + + public void setA1(final String[] a1) { + this.a1 = a1; + } + + public int[] getA2() { + return a2; + } + + public void setA2(final int[] a2) { + this.a2 = a2; + } + + public boolean[] getA3() { + return a3; + } + + public void setA3(final boolean[] a3) { + this.a3 = a3; + } + + public TestEnum[] getA4() { + return a4; + } + + public void setA4(final TestEnum[] a4) { + this.a4 = a4; + } + + } + + @Test + public void fromArray() throws VPackException { + final TestEntityArray entity = new TestEntityArray(); + final VPackSlice vpack = new VPack.Builder().build().serialize(entity); + assertThat(vpack, is(notNullValue())); + assertThat(vpack.isObject(), is(true)); + { + final VPackSlice a1 = vpack.get("a1"); + assertThat(a1.isArray(), is(true)); + assertThat(a1.getLength(), is(entity.a1.length)); + for (int i = 0; i < a1.getLength(); i++) { + assertThat(a1.get(i).getAsString(), is(entity.a1[i])); + } + } + { + final VPackSlice a2 = vpack.get("a2"); + assertThat(a2.isArray(), is(true)); + assertThat(a2.getLength(), is(entity.a2.length)); + for (int i = 0; i < a2.getLength(); i++) { + assertThat(a2.get(i).getAsInt(), is(entity.a2[i])); + } + } + { + final VPackSlice a3 = vpack.get("a3"); + assertThat(a3.isArray(), is(true)); + assertThat(a3.getLength(), is(entity.a3.length)); + for (int i = 0; i < a3.getLength(); i++) { + assertThat(a3.get(i).getAsBoolean(), is(entity.a3[i])); + } + } + { + final VPackSlice a4 = vpack.get("a4"); + assertThat(a4.isArray(), is(true)); + assertThat(a4.getLength(), is(entity.a4.length)); + for (int i = 0; i < a4.getLength(); i++) { + assertThat(TestEnum.valueOf(a4.get(i).getAsString()), is(entity.a4[i])); + } + } + } + + @Test + public void toArray() throws VPackException { + final VPackBuilder builder = new VPackBuilder(); + { + builder.add(ValueType.OBJECT); + { + builder.add("a1", ValueType.ARRAY); + builder.add("a"); + builder.add("b"); + builder.add("c"); + builder.close(); + } + { + builder.add("a2", ValueType.ARRAY); + builder.add(1); + builder.add(2); + builder.add(3); + builder.add(4); + builder.close(); + } + { + builder.add("a3", ValueType.ARRAY); + builder.add(false); + builder.add(true); + builder.close(); + } + { + builder.add("a4", ValueType.ARRAY); + builder.add(TestEnum.A.name()); + builder.add(TestEnum.B.name()); + builder.close(); + } + builder.close(); + } + final VPackSlice vpack = builder.slice(); + final TestEntityArray entity = new VPack.Builder().build().deserialize(vpack, TestEntityArray.class); + assertThat(entity, is(notNullValue())); + { + assertThat(entity.a1.length, is(3)); + assertThat(entity.a1[0], is("a")); + assertThat(entity.a1[1], is("b")); + assertThat(entity.a1[2], is("c")); + } + { + assertThat(entity.a2.length, is(4)); + assertThat(entity.a2[0], is(1)); + assertThat(entity.a2[1], is(2)); + assertThat(entity.a2[2], is(3)); + assertThat(entity.a2[3], is(4)); + } + { + assertThat(entity.a3.length, is(2)); + assertThat(entity.a3[0], is(false)); + assertThat(entity.a3[1], is(true)); + } + { + assertThat(entity.a4.length, is(2)); + assertThat(entity.a4[0], is(TestEnum.A)); + assertThat(entity.a4[1], is(TestEnum.B)); + } + } + + protected enum TestEnum { + A, B, C + } + + protected static class TestEntityEnum { + private TestEnum e1 = TestEnum.A; + + public TestEnum getE1() { + return e1; + } + + public void setE1(final TestEnum e1) { + this.e1 = e1; + } + } + + @Test + public void fromEnum() throws VPackException { + final VPackSlice vpack = new VPack.Builder().build().serialize(new TestEntityEnum()); + assertThat(vpack, is(notNullValue())); + assertThat(vpack.isObject(), is(true)); + { + final VPackSlice e1 = vpack.get("e1"); + assertThat(e1.isString(), is(true)); + assertThat(TestEnum.valueOf(e1.getAsString()), is(TestEnum.A)); + } + } + + @Test + public void toEnum() throws VPackException { + final VPackBuilder builder = new VPackBuilder(); + { + builder.add(ValueType.OBJECT); + builder.add("e1", TestEnum.B.name()); + builder.close(); + } + final VPackSlice vpack = builder.slice(); + final TestEntityEnum entity = new VPack.Builder().build().deserialize(vpack, TestEntityEnum.class); + assertThat(entity, is(notNullValue())); + assertThat(entity.e1, is(TestEnum.B)); + } + + protected static class TestEntityObject { + private TestEntityLong o1 = new TestEntityLong(); + private TestEntityArray o2 = new TestEntityArray(); + + public TestEntityLong getO1() { + return o1; + } + + public void setO1(final TestEntityLong o1) { + this.o1 = o1; + } + + public TestEntityArray getO2() { + return o2; + } + + public void setO2(final TestEntityArray o2) { + this.o2 = o2; + } + } + + @Test + public void fromObject() throws VPackException { + final TestEntityObject entity = new TestEntityObject(); + final VPackSlice vpack = new VPack.Builder().build().serialize(entity); + assertThat(vpack, is(notNullValue())); + assertThat(vpack.isObject(), is(true)); + { + final VPackSlice o1 = vpack.get("o1"); + assertThat(o1.isObject(), is(true)); + { + final VPackSlice l1 = o1.get("l1"); + assertThat(l1.isInteger(), is(true)); + assertThat(l1.getAsLong(), is(1L)); + } + { + final VPackSlice l2 = o1.get("l2"); + assertThat(l2.isInteger(), is(true)); + assertThat(l2.getAsLong(), is(1L)); + } + } + { + final VPackSlice o2 = vpack.get("o2"); + assertThat(o2.isObject(), is(true)); + { + final VPackSlice a1 = o2.get("a1"); + assertThat(a1.isArray(), is(true)); + assertThat(a1.getLength(), is(entity.o2.a1.length)); + for (int i = 0; i < a1.getLength(); i++) { + assertThat(a1.get(i).getAsString(), is(entity.o2.a1[i])); + } + } + { + final VPackSlice a2 = o2.get("a2"); + assertThat(a2.isArray(), is(true)); + assertThat(a2.getLength(), is(entity.o2.a2.length)); + for (int i = 0; i < a2.getLength(); i++) { + assertThat(a2.get(i).getAsInt(), is(entity.o2.a2[i])); + } + } + { + final VPackSlice a3 = o2.get("a3"); + assertThat(a3.isArray(), is(true)); + assertThat(a3.getLength(), is(entity.o2.a3.length)); + for (int i = 0; i < a3.getLength(); i++) { + assertThat(a3.get(i).getAsBoolean(), is(entity.o2.a3[i])); + } + } + { + final VPackSlice a4 = o2.get("a4"); + assertThat(a4.isArray(), is(true)); + assertThat(a4.getLength(), is(entity.o2.a4.length)); + for (int i = 0; i < a4.getLength(); i++) { + assertThat(TestEnum.valueOf(a4.get(i).getAsString()), is(entity.o2.a4[i])); + } + } + } + } + + @Test + public void toObject() throws VPackException { + final VPackBuilder builder = new VPackBuilder(); + { + builder.add(ValueType.OBJECT); + { + builder.add("o1", ValueType.OBJECT); + builder.add("l1", 5L); + builder.add("l2", 5L); + builder.close(); + } + { + builder.add("o2", ValueType.OBJECT); + { + builder.add("a1", ValueType.ARRAY); + builder.add("a"); + builder.add("b"); + builder.add("c"); + builder.close(); + } + { + builder.add("a2", ValueType.ARRAY); + builder.add(1); + builder.add(2); + builder.add(3); + builder.add(4); + builder.close(); + } + { + builder.add("a3", ValueType.ARRAY); + builder.add(false); + builder.add(true); + builder.close(); + } + { + builder.add("a4", ValueType.ARRAY); + builder.add(TestEnum.A.name()); + builder.add(TestEnum.B.name()); + builder.close(); + } + builder.close(); + } + builder.close(); + } + final VPackSlice vpack = builder.slice(); + final TestEntityObject entity = new VPack.Builder().build().deserialize(vpack, TestEntityObject.class); + assertThat(entity, is(notNullValue())); + { + assertThat(entity.o1.l1, is(5L)); + assertThat(entity.o1.l2, is(new Long(5))); + } + { + assertThat(entity.o2.a1.length, is(3)); + assertThat(entity.o2.a1[0], is("a")); + assertThat(entity.o2.a1[1], is("b")); + assertThat(entity.o2.a1[2], is("c")); + } + { + assertThat(entity.o2.a2.length, is(4)); + assertThat(entity.o2.a2[0], is(1)); + assertThat(entity.o2.a2[1], is(2)); + assertThat(entity.o2.a2[2], is(3)); + assertThat(entity.o2.a2[3], is(4)); + } + { + assertThat(entity.o2.a3.length, is(2)); + assertThat(entity.o2.a3[0], is(false)); + assertThat(entity.o2.a3[1], is(true)); + } + { + assertThat(entity.o2.a4.length, is(2)); + assertThat(entity.o2.a4[0], is(TestEnum.A)); + assertThat(entity.o2.a4[1], is(TestEnum.B)); + } + } + + protected static class TestEntityArrayInArray { + private long[][] a1; + + public long[][] getA1() { + return a1; + } + + public void setA1(final long[][] a1) { + this.a1 = a1; + } + } + + @Test + public void fromArrayInArray() throws VPackException { + final TestEntityArrayInArray entity = new TestEntityArrayInArray(); + entity.a1 = new long[][] { { 1, 2, 3 }, { 4, 5, 6 } }; + final VPackSlice vpack = new VPack.Builder().build().serialize(entity); + assertThat(vpack, is(notNullValue())); + assertThat(vpack.isObject(), is(true)); + { + final VPackSlice a1 = vpack.get("a1"); + assertThat(a1.isArray(), is(true)); + assertThat(a1.getLength(), is(entity.a1.length)); + for (int i = 0; i < a1.getLength(); i++) { + final VPackSlice at = a1.get(i); + assertThat(at.isArray(), is(true)); + assertThat(at.getLength(), is(entity.a1[i].length)); + for (int j = 0; j < at.getLength(); j++) { + final VPackSlice atat = at.get(j); + assertThat(atat.isInteger(), is(true)); + assertThat(atat.getAsLong(), is(entity.a1[i][j])); + } + } + } + } + + @Test + public void toArrayInArray() throws VPackException { + final VPackBuilder builder = new VPackBuilder(); + { + builder.add(ValueType.OBJECT); + { + builder.add("a1", ValueType.ARRAY); + { + builder.add(ValueType.ARRAY); + builder.add(1); + builder.add(2); + builder.add(3); + builder.close(); + } + { + builder.add(ValueType.ARRAY); + builder.add(4); + builder.add(5); + builder.add(6); + builder.close(); + } + builder.close(); + } + builder.close(); + } + final VPackSlice vpack = builder.slice(); + final TestEntityArrayInArray entity = new VPack.Builder().build().deserialize(vpack, + TestEntityArrayInArray.class); + assertThat(entity, is(notNullValue())); + assertThat(entity.a1.length, is(2)); + { + assertThat(entity.a1[0].length, is(3)); + assertThat(entity.a1[0][0], is(1L)); + assertThat(entity.a1[0][1], is(2L)); + assertThat(entity.a1[0][2], is(3L)); + } + { + assertThat(entity.a1[1].length, is(3)); + assertThat(entity.a1[1][0], is(4L)); + assertThat(entity.a1[1][1], is(5L)); + assertThat(entity.a1[1][2], is(6L)); + } + } + + protected static class TestEntityArrayInArrayInArray { + private double[][][] a1; + + public double[][][] getA1() { + return a1; + } + + public void setA1(final double[][][] a1) { + this.a1 = a1; + } + + } + + @Test + public void fromArrayInArrayInArray() throws VPackException { + final TestEntityArrayInArrayInArray entity = new TestEntityArrayInArrayInArray(); + entity.setA1(new double[][][] { { { 1.5, 2.25 }, { 10.5, 20.25 } }, { { 100.5 }, { 200.25 } } }); + final VPackSlice vpack = new VPack.Builder().build().serialize(entity); + assertThat(vpack, is(notNullValue())); + assertThat(vpack.isObject(), is(true)); + { + final VPackSlice a1 = vpack.get("a1"); + assertThat(a1.isArray(), is(true)); + assertThat(a1.getLength(), is(entity.a1.length)); + for (int i = 0; i < a1.getLength(); i++) { + final VPackSlice at = a1.get(i); + assertThat(at.isArray(), is(true)); + assertThat(at.getLength(), is(entity.a1[i].length)); + for (int j = 0; j < at.getLength(); j++) { + final VPackSlice atat = at.get(j); + assertThat(atat.isArray(), is(true)); + assertThat(atat.getLength(), is(entity.a1[i][j].length)); + for (int k = 0; k < atat.getLength(); k++) { + final VPackSlice atatat = atat.get(k); + assertThat(atatat.isDouble(), is(true)); + assertThat(atatat.getAsDouble(), is(entity.a1[i][j][k])); + } + } + } + } + } + + @Test + public void toArrayInArrayInArray() throws VPackException { + final VPackBuilder builder = new VPackBuilder(); + { + builder.add(ValueType.OBJECT); + { + builder.add("a1", ValueType.ARRAY); + builder.add(ValueType.ARRAY); + { + builder.add(ValueType.ARRAY); + builder.add(1.5); + builder.add(2.5); + builder.add(3.5); + builder.close(); + } + { + builder.add(ValueType.ARRAY); + builder.add(4.5); + builder.add(5.5); + builder.add(6.5); + builder.close(); + } + { + builder.add(ValueType.ARRAY); + builder.add(7.5); + builder.add(8.5); + builder.add(9.5); + builder.close(); + } + builder.close(); + builder.add(ValueType.ARRAY); + { + builder.add(ValueType.ARRAY); + builder.add(1.5); + builder.add(2.5); + builder.add(3.5); + builder.close(); + } + { + builder.add(ValueType.ARRAY); + builder.add(4.5); + builder.add(5.5); + builder.add(6.5); + builder.close(); + } + { + builder.add(ValueType.ARRAY); + builder.add(7.5); + builder.add(8.5); + builder.add(9.5); + builder.close(); + } + builder.close(); + builder.close(); + } + builder.close(); + } + final VPackSlice vpack = builder.slice(); + final TestEntityArrayInArrayInArray entity = new VPack.Builder().build().deserialize(vpack, + TestEntityArrayInArrayInArray.class); + assertThat(entity, is(notNullValue())); + assertThat(entity.a1.length, is(2)); + { + assertThat(entity.a1[0].length, is(3)); + assertThat(entity.a1[0][0].length, is(3)); + assertThat(entity.a1[0][0][0], is(1.5)); + assertThat(entity.a1[0][0][1], is(2.5)); + assertThat(entity.a1[0][0][2], is(3.5)); + assertThat(entity.a1[0][1].length, is(3)); + assertThat(entity.a1[0][1][0], is(4.5)); + assertThat(entity.a1[0][1][1], is(5.5)); + assertThat(entity.a1[0][1][2], is(6.5)); + assertThat(entity.a1[0][2].length, is(3)); + assertThat(entity.a1[0][2][0], is(7.5)); + assertThat(entity.a1[0][2][1], is(8.5)); + assertThat(entity.a1[0][2][2], is(9.5)); + } + { + assertThat(entity.a1[1].length, is(3)); + assertThat(entity.a1[1][0].length, is(3)); + assertThat(entity.a1[1][0][0], is(1.5)); + assertThat(entity.a1[1][0][1], is(2.5)); + assertThat(entity.a1[1][0][2], is(3.5)); + assertThat(entity.a1[1][1].length, is(3)); + assertThat(entity.a1[1][1][0], is(4.5)); + assertThat(entity.a1[1][1][1], is(5.5)); + assertThat(entity.a1[1][1][2], is(6.5)); + assertThat(entity.a1[1][2].length, is(3)); + assertThat(entity.a1[1][2][0], is(7.5)); + assertThat(entity.a1[1][2][1], is(8.5)); + assertThat(entity.a1[1][2][2], is(9.5)); + } + } + + protected static class TestEntityObjectInArray { + private TestEntityString[] a1; + + public TestEntityString[] getA1() { + return a1; + } + + public void setA1(final TestEntityString[] a1) { + this.a1 = a1; + } + } + + @Test + public void fromObjectInArray() throws VPackException { + final TestEntityObjectInArray entity = new TestEntityObjectInArray(); + { + final TestEntityString[] a1 = new TestEntityString[2]; + final TestEntityString s = new TestEntityString(); + s.setS("abc"); + a1[0] = s; + a1[1] = s; + entity.setA1(a1); + } + final VPackSlice vpack = new VPack.Builder().build().serialize(entity); + assertThat(vpack, is(notNullValue())); + assertThat(vpack.isObject(), is(true)); + { + final VPackSlice a1 = vpack.get("a1"); + assertThat(a1.isArray(), is(true)); + assertThat(a1.getLength(), is(2)); + for (int i = 0; i < a1.getLength(); i++) { + final VPackSlice at = a1.get(i); + assertThat(at.isObject(), is(true)); + final VPackSlice s = at.get("s"); + assertThat(s.isString(), is(true)); + assertThat(s.getAsString(), is("abc")); + } + } + } + + @Test + public void toObjectInArray() throws VPackException { + final VPackBuilder builder = new VPackBuilder(); + { + builder.add(ValueType.OBJECT); + builder.add("a1", ValueType.ARRAY); + { + builder.add(ValueType.OBJECT); + builder.add("s", "abc"); + builder.close(); + } + builder.close(); + builder.close(); + } + final VPackSlice vpack = builder.slice(); + final TestEntityObjectInArray entity = new VPack.Builder().build().deserialize(vpack, + TestEntityObjectInArray.class); + assertThat(entity, is(notNullValue())); + assertThat(entity.a1, is(notNullValue())); + assertThat(entity.a1.length, is(1)); + final TestEntityString st = entity.a1[0]; + assertThat(st, is(notNullValue())); + assertThat(st.s, is("abc")); + } + + protected static class TestEntityA { + private String a = "a"; + + public String getA() { + return a; + } + + public void setA(final String a) { + this.a = a; + } + } + + protected static class TestEntityB extends TestEntityA { + private String b = "b"; + + public String getB() { + return b; + } + + public void setB(final String b) { + this.b = b; + } + } + + @Test + public void fromInheritance() throws VPackException { + final VPackSlice vpack = new VPack.Builder().build().serialize(new TestEntityB()); + assertThat(vpack, is(notNullValue())); + assertThat(vpack.isObject(), is(true)); + assertThat(vpack.getLength(), is(2)); + { + final VPackSlice a = vpack.get("a"); + assertThat(a.isString(), is(true)); + assertThat(a.getAsString(), is("a")); + } + { + final VPackSlice b = vpack.get("b"); + assertThat(b.isString(), is(true)); + assertThat(b.getAsString(), is("b")); + } + } + + @Test + public void toInheritance() throws VPackException { + final VPackBuilder builder = new VPackBuilder(); + { + builder.add(ValueType.OBJECT); + builder.add("a", "test"); + builder.add("b", "test"); + builder.close(); + } + final VPackSlice vpack = builder.slice(); + { + final TestEntityA entity = new VPack.Builder().build().deserialize(vpack, TestEntityA.class); + assertThat(entity, is(notNullValue())); + assertThat(entity.getA(), is("test")); + } + { + final TestEntityB entity = new VPack.Builder().build().deserialize(vpack, TestEntityB.class); + assertThat(entity, is(notNullValue())); + assertThat(entity.getA(), is("test")); + assertThat(entity.getB(), is("test")); + } + } + + protected static class TestEntityC { + private TestEntityD d; + + public TestEntityD getD() { + return d; + } + + public void setD(final TestEntityD d) { + this.d = d; + } + } + + protected static interface TestEntityD { + String getD(); + + void setD(String d); + } + + protected static class TestEntityDImpl implements TestEntityD { + private String d = "d"; + + @Override + public String getD() { + return d; + } + + @Override + public void setD(final String d) { + this.d = d; + } + } + + @Test + public void fromInterface() throws VPackException { + final TestEntityC entity = new TestEntityC(); + entity.setD(new TestEntityDImpl()); + final VPackSlice vpack = new VPack.Builder().build().serialize(entity); + assertThat(vpack, is(notNullValue())); + assertThat(vpack.isObject(), is(true)); + { + final VPackSlice d = vpack.get("d"); + assertThat(d.isObject(), is(true)); + final VPackSlice dd = d.get("d"); + assertThat(dd.isString(), is(true)); + assertThat(dd.getAsString(), is("d")); + } + } + + @Test + public void toInterface() throws VPackException { + final VPackBuilder builder = new VPackBuilder(); + { + builder.add(ValueType.OBJECT); + builder.add("d", ValueType.OBJECT); + builder.add("d", "test"); + builder.close(); + builder.close(); + } + final VPackSlice slice = builder.slice(); + final VPack vPack = new VPack.Builder() + .regitserInstanceCreator(TestEntityD.class, new VPackInstanceCreator() { + @Override + public TestEntityD createInstance() { + return new TestEntityDImpl(); + } + }).build(); + final TestEntityC entity = vPack.deserialize(slice, TestEntityC.class); + assertThat(entity, is(notNullValue())); + assertThat(entity.d, is(notNullValue())); + assertThat(entity.d.getD(), is("test")); + } + + protected static class TestEntityCollection { + private Collection c1 = new LinkedList(); + private List c2 = new ArrayList(); + private ArrayList c3 = new ArrayList(); + private Set c4 = new LinkedHashSet(); + private HashSet c5 = new HashSet(); + + public TestEntityCollection() { + super(); + } + + public Collection getC1() { + return c1; + } + + public void setC1(final Collection c1) { + this.c1 = c1; + } + + public List getC2() { + return c2; + } + + public void setC2(final List c2) { + this.c2 = c2; + } + + public ArrayList getC3() { + return c3; + } + + public void setC3(final ArrayList c3) { + this.c3 = c3; + } + + public Set getC4() { + return c4; + } + + public void setC4(final Set c4) { + this.c4 = c4; + } + + public HashSet getC5() { + return c5; + } + + public void setC5(final HashSet c5) { + this.c5 = c5; + } + } + + @Test + public void fromCollection() throws VPackException { + final TestEntityCollection entity = new TestEntityCollection(); + { + entity.c1.add("test"); + entity.c2.add("test"); + entity.c3.add("test"); + entity.c4.add("test"); + entity.c5.add("test"); + } + final VPackSlice vpack = new VPack.Builder().build().serialize(entity); + assertThat(vpack, is(notNullValue())); + assertThat(vpack.isObject(), is(true)); + { + final VPackSlice c1 = vpack.get("c1"); + assertThat(c1.isArray(), is(true)); + assertThat(c1.getLength(), is(1)); + assertThat(c1.get(0).getAsString(), is("test")); + } + { + final VPackSlice c2 = vpack.get("c2"); + assertThat(c2.isArray(), is(true)); + assertThat(c2.getLength(), is(1)); + assertThat(c2.get(0).getAsString(), is("test")); + } + { + final VPackSlice c3 = vpack.get("c3"); + assertThat(c3.isArray(), is(true)); + assertThat(c3.getLength(), is(1)); + assertThat(c3.get(0).getAsString(), is("test")); + } + { + final VPackSlice c4 = vpack.get("c4"); + assertThat(c4.isArray(), is(true)); + assertThat(c4.getLength(), is(1)); + assertThat(c4.get(0).getAsString(), is("test")); + } + { + final VPackSlice c5 = vpack.get("c5"); + assertThat(c5.isArray(), is(true)); + assertThat(c5.getLength(), is(1)); + assertThat(c5.get(0).getAsString(), is("test")); + } + } + + @Test + public void toCollection() throws VPackException { + final VPackBuilder builder = new VPackBuilder(); + { + builder.add(ValueType.OBJECT); + { + builder.add("c1", ValueType.ARRAY); + builder.add("test1"); + builder.add("test2"); + builder.close(); + } + { + builder.add("c2", ValueType.ARRAY); + builder.add("test1"); + builder.add("test2"); + builder.close(); + } + { + builder.add("c3", ValueType.ARRAY); + builder.add("test1"); + builder.add("test2"); + builder.close(); + } + { + builder.add("c4", ValueType.ARRAY); + builder.add("test1"); + builder.add("test2"); + builder.close(); + } + { + builder.add("c5", ValueType.ARRAY); + builder.add("test1"); + builder.add("test2"); + builder.close(); + } + builder.close(); + } + final VPackSlice vpack = builder.slice(); + final TestEntityCollection entity = new VPack.Builder().build().deserialize(vpack, TestEntityCollection.class); + assertThat(entity, is(notNullValue())); + { + checkCollection(entity.c1); + checkCollection(entity.c2); + checkCollection(entity.c3); + checkCollection(entity.c4); + checkCollection(entity.c5); + } + } + + private void checkCollection(final Collection col) { + assertThat(col, is(notNullValue())); + assertThat(col.size(), is(2)); + for (final Iterator iterator = col.iterator(); iterator.hasNext();) { + final String next = iterator.next(); + assertThat("test1".equals(next) || "test2".equals(next), is(true)); + } + } + + protected static class TestEntityCollectionWithObjects { + private Collection c1; + private Set c2; + + public Collection getC1() { + return c1; + } + + public void setC1(final Collection c1) { + this.c1 = c1; + } + + public Set getC2() { + return c2; + } + + public void setC2(final Set c2) { + this.c2 = c2; + } + } + + @Test + public void fromCollectionWithObjects() throws VPackException { + final TestEntityCollectionWithObjects entity = new TestEntityCollectionWithObjects(); + { + final Collection c1 = new ArrayList(); + c1.add(new TestEntityString()); + c1.add(new TestEntityString()); + entity.setC1(c1); + final Set c2 = new HashSet(); + c2.add(new TestEntityArray()); + entity.setC2(c2); + } + final VPackSlice vpack = new VPack.Builder().build().serialize(entity); + assertThat(vpack, is(notNullValue())); + assertThat(vpack.isObject(), is(true)); + { + final VPackSlice c1 = vpack.get("c1"); + assertThat(c1.isArray(), is(true)); + assertThat(c1.getLength(), is(2)); + assertThat(c1.get(0).isObject(), is(true)); + assertThat(c1.get(1).isObject(), is(true)); + { + final VPackSlice s = c1.get(0).get("s"); + assertThat(s.isString(), is(true)); + assertThat(s.getAsString(), is("test")); + } + } + { + final VPackSlice c2 = vpack.get("c2"); + assertThat(c2.isArray(), is(true)); + assertThat(c2.getLength(), is(1)); + assertThat(c2.get(0).isObject(), is(true)); + { + final VPackSlice a2 = c2.get(0).get("a2"); + assertThat(a2.isArray(), is(true)); + assertThat(a2.getLength(), is(5)); + for (int i = 0; i < a2.getLength(); i++) { + final VPackSlice at = a2.get(i); + assertThat(at.isInteger(), is(true)); + assertThat(at.getAsInt(), is(i + 1)); + } + } + } + } + + @Test + public void toCollectionWithObjects() throws VPackException { + final VPackBuilder builder = new VPackBuilder(); + { + builder.add(ValueType.OBJECT); + { + builder.add("c1", ValueType.ARRAY); + builder.add(ValueType.OBJECT); + builder.add("s", "abc"); + builder.close(); + builder.close(); + } + { + builder.add("c2", ValueType.ARRAY); + builder.add(ValueType.OBJECT); + builder.add("a2", ValueType.ARRAY); + for (int i = 0; i < 10; i++) { + builder.add(i); + } + builder.close(); + builder.close(); + builder.close(); + } + builder.close(); + } + final VPackSlice vpack = builder.slice(); + final TestEntityCollectionWithObjects entity = new VPack.Builder().build().deserialize(vpack, + TestEntityCollectionWithObjects.class); + assertThat(entity, is(notNullValue())); + { + assertThat(entity.c1, is(notNullValue())); + assertThat(entity.c1.size(), is(1)); + assertThat(entity.c1.iterator().next().s, is("abc")); + } + { + assertThat(entity.c2, is(notNullValue())); + assertThat(entity.c2.size(), is(1)); + final int[] array = entity.c2.iterator().next().a2; + for (int i = 0; i < array.length; i++) { + assertThat(array[i], is(i)); + } + } + } + + protected static class TestEntityMap { + private Map m1; + private HashMap m2; + private Map m3; + + public Map getM1() { + return m1; + } + + public void setM1(final Map m1) { + this.m1 = m1; + } + + public HashMap getM2() { + return m2; + } + + public void setM2(final HashMap m2) { + this.m2 = m2; + } + + public Map getM3() { + return m3; + } + + public void setM3(final Map m3) { + this.m3 = m3; + } + } + + @Test + public void fromMap() throws VPackException { + final TestEntityMap entity = new TestEntityMap(); + { + final Map m1 = new LinkedHashMap(); + m1.put("a", "b"); + m1.put("c", "d"); + entity.setM1(m1); + final HashMap m2 = new HashMap(); + m2.put(1, "a"); + m2.put(2, "b"); + entity.setM2(m2); + final Map m3 = new HashMap(); + final TestEntityString s = new TestEntityString(); + s.setS("abc"); + m3.put("a", s); + entity.setM3(m3); + } + final VPackSlice vpack = new VPack.Builder().build().serialize(entity); + assertThat(vpack, is(notNullValue())); + assertThat(vpack.isObject(), is(true)); + { + final VPackSlice m1 = vpack.get("m1"); + assertThat(m1.isObject(), is(true)); + assertThat(m1.getLength(), is(2)); + { + final VPackSlice a = m1.get("a"); + assertThat(a.isString(), is(true)); + assertThat(a.getAsString(), is("b")); + } + { + final VPackSlice c = m1.get("c"); + assertThat(c.isString(), is(true)); + assertThat(c.getAsString(), is("d")); + } + } + { + final VPackSlice m2 = vpack.get("m2"); + assertThat(m2.isObject(), is(true)); + assertThat(m2.getLength(), is(2)); + { + final VPackSlice one = m2.get("1"); + assertThat(one.isString(), is(true)); + assertThat(one.getAsString(), is("a")); + } + { + final VPackSlice two = m2.get("2"); + assertThat(two.isString(), is(true)); + assertThat(two.getAsString(), is("b")); + } + } + { + final VPackSlice m3 = vpack.get("m3"); + assertThat(m3.isObject(), is(true)); + assertThat(m3.getLength(), is(1)); + final VPackSlice a = m3.get("a"); + assertThat(a.isObject(), is(true)); + final VPackSlice s = a.get("s"); + assertThat(s.isString(), is(true)); + assertThat(s.getAsString(), is("abc")); + } + } + + @Test + public void toMap() throws VPackException { + final VPackBuilder builder = new VPackBuilder(); + { + builder.add(ValueType.OBJECT); + { + builder.add("m1", ValueType.OBJECT); + builder.add("a", "a"); + builder.add("b", "b"); + builder.close(); + } + { + builder.add("m2", ValueType.OBJECT); + builder.add("1", "a"); + builder.add("-1", "a"); + builder.close(); + } + { + builder.add("m3", ValueType.OBJECT); + builder.add("a", ValueType.OBJECT); + builder.add("s", "abc"); + builder.close(); + builder.close(); + } + builder.close(); + } + final VPackSlice vpack = builder.slice(); + final TestEntityMap entity = new VPack.Builder().build().deserialize(vpack, TestEntityMap.class); + assertThat(entity, is(notNullValue())); + { + assertThat(entity.m1, is(notNullValue())); + assertThat(entity.m1.size(), is(2)); + final String a = entity.m1.get("a"); + assertThat(a, is(notNullValue())); + assertThat(a, is("a")); + final String b = entity.m1.get("b"); + assertThat(b, is(notNullValue())); + assertThat(b, is("b")); + } + { + assertThat(entity.m2, is(notNullValue())); + assertThat(entity.m2.size(), is(2)); + final String one = entity.m2.get(1); + assertThat(one, is(notNullValue())); + assertThat(one, is("a")); + final String oneNegative = entity.m2.get(-1); + assertThat(oneNegative, is(notNullValue())); + assertThat(oneNegative, is("a")); + } + { + assertThat(entity.m3, is(notNullValue())); + assertThat(entity.m3.size(), is(1)); + final TestEntityString a = entity.m3.get("a"); + assertThat(a, is(notNullValue())); + assertThat(a.s, is("abc")); + } + } + + protected static class TestEntityMapStringableKey { + private Map m1; + private Map m2; + private Map m3; + private Map m4; + private Map m5; + private Map m6; + private Map m7; + private Map m8; + private Map m9; + private Map m10; + private Map m11; + + public Map getM1() { + return m1; + } + + public void setM1(final Map m1) { + this.m1 = m1; + } + + public Map getM2() { + return m2; + } + + public void setM2(final Map m2) { + this.m2 = m2; + } + + public Map getM3() { + return m3; + } + + public void setM3(final Map m3) { + this.m3 = m3; + } + + public Map getM4() { + return m4; + } + + public void setM4(final Map m4) { + this.m4 = m4; + } + + public Map getM5() { + return m5; + } + + public void setM5(final Map m5) { + this.m5 = m5; + } + + public Map getM6() { + return m6; + } + + public void setM6(final Map m6) { + this.m6 = m6; + } + + public Map getM7() { + return m7; + } + + public void setM7(final Map m7) { + this.m7 = m7; + } + + public Map getM8() { + return m8; + } + + public void setM8(final Map m8) { + this.m8 = m8; + } + + public Map getM9() { + return m9; + } + + public void setM9(final Map m9) { + this.m9 = m9; + } + + public Map getM10() { + return m10; + } + + public void setM10(final Map m10) { + this.m10 = m10; + } + + public Map getM11() { + return m11; + } + + public void setM11(final Map m11) { + this.m11 = m11; + } + + } + + @Test + public void fromMapStringableKey() throws VPackException { + final TestEntityMapStringableKey entity = new TestEntityMapStringableKey(); + final String value = "test"; + { + final Map m1 = new HashMap(); + m1.put(true, value); + m1.put(false, value); + entity.setM1(m1); + } + { + final Map m2 = new HashMap(); + m2.put(1, value); + m2.put(2, value); + entity.setM2(m2); + } + { + final Map m3 = new HashMap(); + m3.put(1L, value); + m3.put(2L, value); + entity.setM3(m3); + } + { + final Map m4 = new HashMap(); + m4.put(1.5F, value); + m4.put(2.25F, value); + entity.setM4(m4); + } + { + final Map m5 = new HashMap(); + m5.put(new Short("1"), value); + m5.put(new Short("2"), value); + entity.setM5(m5); + } + { + final Map m6 = new HashMap(); + m6.put(1.5, value); + m6.put(2.25, value); + entity.setM6(m6); + } + { + final Map m7 = new HashMap(); + m7.put(1.5, value); + m7.put(1L, value); + entity.setM7(m7); + } + { + final Map m8 = new HashMap(); + m8.put(new BigInteger("1"), value); + m8.put(new BigInteger("2"), value); + entity.setM8(m8); + } + { + final Map m9 = new HashMap(); + m9.put(new BigDecimal("1.5"), value); + m9.put(new BigDecimal("2.25"), value); + entity.setM9(m9); + } + { + final Map m10 = new HashMap(); + m10.put('1', value); + m10.put('a', value); + entity.setM10(m10); + } + { + final Map m11 = new HashMap(); + m11.put(TestEnum.A, value); + m11.put(TestEnum.B, value); + entity.setM11(m11); + } + final VPackSlice vpack = new VPack.Builder().build().serialize(entity); + assertThat(vpack, is(notNullValue())); + assertThat(vpack.isObject(), is(true)); + { + final VPackSlice m1 = vpack.get("m1"); + assertThat(m1.isObject(), is(true)); + assertThat(m1.getLength(), is(2)); + checkMapAttribute(m1.get("true")); + checkMapAttribute(m1.get("false")); + } + { + final VPackSlice m2 = vpack.get("m2"); + assertThat(m2.isObject(), is(true)); + assertThat(m2.getLength(), is(2)); + checkMapAttribute(m2.get("1")); + checkMapAttribute(m2.get("2")); + } + { + final VPackSlice m3 = vpack.get("m3"); + assertThat(m3.isObject(), is(true)); + assertThat(m3.getLength(), is(2)); + checkMapAttribute(m3.get("1")); + checkMapAttribute(m3.get("2")); + } + { + final VPackSlice m4 = vpack.get("m4"); + assertThat(m4.isObject(), is(true)); + assertThat(m4.getLength(), is(2)); + checkMapAttribute(m4.get("1.5")); + checkMapAttribute(m4.get("2.25")); + } + { + final VPackSlice m5 = vpack.get("m5"); + assertThat(m5.isObject(), is(true)); + assertThat(m5.getLength(), is(2)); + checkMapAttribute(m5.get("1")); + checkMapAttribute(m5.get("2")); + } + { + final VPackSlice m6 = vpack.get("m6"); + assertThat(m6.isObject(), is(true)); + assertThat(m6.getLength(), is(2)); + checkMapAttribute(m6.get("1.5")); + checkMapAttribute(m6.get("2.25")); + } + { + final VPackSlice m7 = vpack.get("m7"); + assertThat(m7.isObject(), is(true)); + assertThat(m7.getLength(), is(2)); + checkMapAttribute(m7.get("1.5")); + checkMapAttribute(m7.get("1")); + } + { + final VPackSlice m8 = vpack.get("m8"); + assertThat(m8.isObject(), is(true)); + assertThat(m8.getLength(), is(2)); + checkMapAttribute(m8.get("1")); + checkMapAttribute(m8.get("2")); + } + { + final VPackSlice m9 = vpack.get("m9"); + assertThat(m9.isObject(), is(true)); + assertThat(m9.getLength(), is(2)); + checkMapAttribute(m9.get("1.5")); + checkMapAttribute(m9.get("2.25")); + } + { + final VPackSlice m10 = vpack.get("m10"); + assertThat(m10.isObject(), is(true)); + assertThat(m10.getLength(), is(2)); + checkMapAttribute(m10.get("1")); + checkMapAttribute(m10.get("a")); + } + { + final VPackSlice m11 = vpack.get("m11"); + assertThat(m11.isObject(), is(true)); + assertThat(m11.getLength(), is(2)); + checkMapAttribute(m11.get(TestEnum.A.name())); + checkMapAttribute(m11.get(TestEnum.B.name())); + } + } + + @Test + public void toMapSringableKey() throws VPackException { + final VPackBuilder builder = new VPackBuilder(); + builder.add(ValueType.OBJECT); + { + builder.add("m1", ValueType.OBJECT); + builder.add("true", "test"); + builder.add("false", "test"); + builder.close(); + } + { + builder.add("m2", ValueType.OBJECT); + builder.add("1", "test"); + builder.add("2", "test"); + builder.close(); + } + { + builder.add("m3", ValueType.OBJECT); + builder.add("1", "test"); + builder.add("2", "test"); + builder.close(); + } + { + builder.add("m4", ValueType.OBJECT); + builder.add("1.5", "test"); + builder.add("2.25", "test"); + builder.close(); + } + { + builder.add("m5", ValueType.OBJECT); + builder.add("1", "test"); + builder.add("2", "test"); + builder.close(); + } + { + builder.add("m6", ValueType.OBJECT); + builder.add("1.5", "test"); + builder.add("2.25", "test"); + builder.close(); + } + { + builder.add("m7", ValueType.OBJECT); + builder.add("1.5", "test"); + builder.add("1", "test"); + builder.close(); + } + { + builder.add("m8", ValueType.OBJECT); + builder.add("1", "test"); + builder.add("2", "test"); + builder.close(); + } + { + builder.add("m9", ValueType.OBJECT); + builder.add("1.5", "test"); + builder.add("2.25", "test"); + builder.close(); + } + { + builder.add("m10", ValueType.OBJECT); + builder.add("1", "test"); + builder.add("a", "test"); + builder.close(); + } + { + builder.add("m11", ValueType.OBJECT); + builder.add(TestEnum.A.name(), "test"); + builder.add(TestEnum.B.name(), "test"); + builder.close(); + } + builder.close(); + final TestEntityMapStringableKey entity = new VPack.Builder().build().deserialize(builder.slice(), + TestEntityMapStringableKey.class); + { + assertThat(entity.m1.size(), is(2)); + checkMapAttribute(entity.m1.get(true)); + checkMapAttribute(entity.m1.get(false)); + } + { + assertThat(entity.m2.size(), is(2)); + checkMapAttribute(entity.m2.get(1)); + checkMapAttribute(entity.m2.get(2)); + } + { + assertThat(entity.m3.size(), is(2)); + checkMapAttribute(entity.m3.get(1L)); + checkMapAttribute(entity.m3.get(2L)); + } + { + assertThat(entity.m4.size(), is(2)); + checkMapAttribute(entity.m4.get(1.5F)); + checkMapAttribute(entity.m4.get(2.25F)); + } + { + assertThat(entity.m5.size(), is(2)); + checkMapAttribute(entity.m5.get(new Short("1"))); + checkMapAttribute(entity.m5.get(new Short("2"))); + } + { + assertThat(entity.m6.size(), is(2)); + checkMapAttribute(entity.m6.get(1.5)); + checkMapAttribute(entity.m6.get(2.25)); + } + { + assertThat(entity.m7.size(), is(2)); + checkMapAttribute(entity.m7.get(new Double(1.5))); + checkMapAttribute(entity.m7.get(new Double(1L))); + } + { + assertThat(entity.m8.size(), is(2)); + checkMapAttribute(entity.m8.get(new BigInteger("1"))); + checkMapAttribute(entity.m8.get(new BigInteger("2"))); + } + { + assertThat(entity.m9.size(), is(2)); + checkMapAttribute(entity.m9.get(new BigDecimal("1.5"))); + checkMapAttribute(entity.m9.get(new BigDecimal("2.25"))); + } + { + assertThat(entity.m10.size(), is(2)); + checkMapAttribute(entity.m10.get('1')); + checkMapAttribute(entity.m10.get('a')); + } + { + assertThat(entity.m11.size(), is(2)); + checkMapAttribute(entity.m11.get(TestEnum.A)); + checkMapAttribute(entity.m11.get(TestEnum.B)); + } + } + + private void checkMapAttribute(final VPackSlice attr) { + assertThat(attr.isString(), is(true)); + assertThat(attr.getAsString(), is("test")); + } + + private void checkMapAttribute(final String attr) { + assertThat(attr, is("test")); + } + + protected static class TestEntityMapWithObjectKey { + private Map m1; + private Map m2; + + public Map getM1() { + return m1; + } + + public void setM1(final Map m1) { + this.m1 = m1; + } + + public Map getM2() { + return m2; + } + + public void setM2(final Map m2) { + this.m2 = m2; + } + } + + @Test + public void fromMapWithObjectKey() throws VPackException { + final TestEntityMapWithObjectKey entity = new TestEntityMapWithObjectKey(); + { + final Map m1 = new HashMap(); + m1.put(new TestEntityLong(), new TestEntityCollection()); + m1.put(new TestEntityLong(), new TestEntityCollection()); + entity.setM1(m1); + } + { + final Map m2 = new HashMap(); + m2.put(new TestEntityLong(), "test"); + m2.put(new TestEntityLong(), "test"); + m2.put(new TestEntityLong(), "test"); + entity.setM2(m2); + } + final VPackSlice vpack = new VPack.Builder().build().serialize(entity); + assertThat(vpack.isObject(), is(true)); + { + final VPackSlice m1 = vpack.get("m1"); + assertThat(m1.isArray(), is(true)); + assertThat(m1.getLength(), is(2)); + for (int i = 0; i < m1.getLength(); i++) { + final VPackSlice at = m1.get(i); + assertThat(at.isObject(), is(true)); + assertThat(at.getLength(), is(2)); + { + final VPackSlice key = at.get("key"); + assertThat(key.isObject(), is(true)); + final VPackSlice l1 = key.get("l1"); + assertThat(l1.isInteger(), is(true)); + assertThat(l1.getAsLong(), is(1L)); + } + { + final VPackSlice value = at.get("value"); + assertThat(value.isObject(), is(true)); + final VPackSlice c1 = value.get("c1"); + assertThat(c1.isArray(), is(true)); + } + } + } + { + final VPackSlice m2 = vpack.get("m2"); + assertThat(m2.isArray(), is(true)); + assertThat(m2.getLength(), is(3)); + for (int i = 0; i < m2.getLength(); i++) { + final VPackSlice at = m2.get(i); + assertThat(at.isObject(), is(true)); + assertThat(at.getLength(), is(2)); + { + final VPackSlice key = at.get("key"); + assertThat(key.isObject(), is(true)); + final VPackSlice l1 = key.get("l1"); + assertThat(l1.isInteger(), is(true)); + assertThat(l1.getAsLong(), is(1L)); + } + { + final VPackSlice value = at.get("value"); + assertThat(value.isString(), is(true)); + assertThat(value.getAsString(), is("test")); + } + } + } + } + + @Test + public void toMapWithObjectKey() throws VPackException { + final int size = 2; + final VPackBuilder builder = new VPackBuilder(); + builder.add(ValueType.OBJECT); + { + builder.add("m1", ValueType.ARRAY); + for (int i = 0; i < size; i++) { + builder.add(ValueType.OBJECT); + { + builder.add("key", ValueType.OBJECT); + builder.add("l1", 5L); + builder.close(); + } + { + builder.add("value", ValueType.OBJECT); + builder.add("c1", ValueType.ARRAY); + builder.add("test"); + builder.close(); + builder.close(); + } + builder.close(); + } + builder.close(); + } + { + builder.add("m2", ValueType.ARRAY); + for (int i = 0; i < size; i++) { + builder.add(ValueType.OBJECT); + { + builder.add("key", ValueType.OBJECT); + builder.add("l1", 5L); + builder.close(); + } + { + builder.add("value", "test"); + } + builder.close(); + } + builder.close(); + } + builder.close(); + final TestEntityMapWithObjectKey entity = new VPack.Builder().build().deserialize(builder.slice(), + TestEntityMapWithObjectKey.class); + assertThat(entity, is(notNullValue())); + { + assertThat(entity.m1, is(notNullValue())); + assertThat(entity.m1.size(), is(size)); + for (final Entry entry : entity.m1.entrySet()) { + assertThat(entry.getKey().l1, is(5L)); + assertThat(entry.getValue().c1.size(), is(1)); + assertThat(entry.getValue().c1.iterator().next(), is("test")); + } + } + { + assertThat(entity.m2, is(notNullValue())); + assertThat(entity.m2.size(), is(2)); + for (final Entry entry : entity.m2.entrySet()) { + assertThat(entry.getKey().l1, is(5L)); + assertThat(entry.getValue(), is("test")); + } + } + } + + protected static class TestEntityEmpty { + + } + + @Test + public void fromEmptyObject() throws VPackException { + final VPackSlice vpack = new VPack.Builder().build().serialize(new TestEntityEmpty()); + assertThat(vpack, is(notNullValue())); + assertThat(vpack.isObject(), is(true)); + assertThat(vpack.getLength(), is(0)); + } + + @Test + public void toEmptyObject() throws VPackException { + final VPackBuilder builder = new VPackBuilder(); + builder.add(ValueType.OBJECT); + builder.close(); + final TestEntityEmpty entity = new VPack.Builder().build().deserialize(builder.slice(), TestEntityEmpty.class); + assertThat(entity, is(notNullValue())); + } + + protected static class TestEntityEmptyMap { + private Map m; + + public Map getM() { + return m; + } + + public void setM(final Map m) { + this.m = m; + } + } + + @Test + public void fromEmptyMap() throws VPackException { + final TestEntityEmptyMap entity = new TestEntityEmptyMap(); + entity.setM(new HashMap()); + final VPackSlice vpack = new VPack.Builder().build().serialize(entity); + assertThat(vpack, is(notNullValue())); + assertThat(vpack.isObject(), is(true)); + assertThat(vpack.getLength(), is(1)); + final VPackSlice m = vpack.get("m"); + assertThat(m.isObject(), is(true)); + assertThat(m.getLength(), is(0)); + } + + @Test + public void toEmptyMap() throws VPackException { + final VPackBuilder builder = new VPackBuilder(); + builder.add(ValueType.OBJECT); + builder.add("m", ValueType.OBJECT); + builder.close(); + builder.close(); + final TestEntityEmptyMap entity = new VPack.Builder().build().deserialize(builder.slice(), + TestEntityEmptyMap.class); + assertThat(entity, is(notNullValue())); + assertThat(entity.m, is(notNullValue())); + assertThat(entity.m.size(), is(0)); + } + + protected static class TestEntityBaseAttributes { + private String _key = "test1"; + private String _rev = "test2"; + private String _id = "test3"; + private String _from = "test4"; + private String _to = "test5"; + + public String get_key() { + return _key; + } + + public void set_key(final String _key) { + this._key = _key; + } + + public String get_rev() { + return _rev; + } + + public void set_rev(final String _rev) { + this._rev = _rev; + } + + public String get_id() { + return _id; + } + + public void set_id(final String _id) { + this._id = _id; + } + + public String get_from() { + return _from; + } + + public void set_from(final String _from) { + this._from = _from; + } + + public String get_to() { + return _to; + } + + public void set_to(final String _to) { + this._to = _to; + } + + } + + @Test + public void fromObjectWithAttributeAdapter() throws VPackException { + final VPackSlice vpack = new VPack.Builder().build().serialize(new TestEntityBaseAttributes()); + assertThat(vpack.isObject(), is(true)); + assertThat(vpack.getLength(), is(5)); + { + final VPackSlice key = vpack.get("_key"); + assertThat(key.isString(), is(true)); + assertThat(key.getAsString(), is("test1")); + } + { + final VPackSlice rev = vpack.get("_rev"); + assertThat(rev.isString(), is(true)); + assertThat(rev.getAsString(), is("test2")); + } + { + final VPackSlice id = vpack.get("_id"); + assertThat(id.isString(), is(true)); + assertThat(id.getAsString(), is("test3")); + } + { + final VPackSlice from = vpack.get("_from"); + assertThat(from.isString(), is(true)); + assertThat(from.getAsString(), is("test4")); + } + { + final VPackSlice to = vpack.get("_to"); + assertThat(to.isString(), is(true)); + assertThat(to.getAsString(), is("test5")); + } + } + + @Test + public void toObjectWithAttributeAdapter() throws VPackException { + final VPackBuilder builder = new VPackBuilder(); + { + builder.add(ValueType.OBJECT); + builder.add("_key", "a"); + builder.add("_rev", "b"); + builder.add("_id", "c"); + builder.add("_from", "d"); + builder.add("_to", "e"); + builder.close(); + } + final TestEntityBaseAttributes entity = new VPack.Builder().build().deserialize(builder.slice(), + TestEntityBaseAttributes.class); + assertThat(entity, is(notNullValue())); + assertThat(entity._key, is("a")); + assertThat(entity._rev, is("b")); + assertThat(entity._id, is("c")); + assertThat(entity._from, is("d")); + assertThat(entity._to, is("e")); + } + + @Test + public void fromMapWithAttributeAdapter() throws VPackException { + final TestEntityMap entity = new TestEntityMap(); + { + final Map m1 = new HashMap(); + m1.put("_key", "test1"); + m1.put("_rev", "test2"); + m1.put("_id", "test3"); + m1.put("_from", "test4"); + m1.put("_to", "test5"); + entity.setM1(m1); + } + final VPackSlice vpack = new VPack.Builder().build().serialize(entity); + assertThat(vpack.isObject(), is(true)); + final VPackSlice m1 = vpack.get("m1"); + assertThat(m1.isObject(), is(true)); + assertThat(m1.getLength(), is(5)); + { + final VPackSlice key = m1.get("_key"); + assertThat(key.isString(), is(true)); + assertThat(key.getAsString(), is("test1")); + } + { + final VPackSlice rev = m1.get("_rev"); + assertThat(rev.isString(), is(true)); + assertThat(rev.getAsString(), is("test2")); + } + { + final VPackSlice id = m1.get("_id"); + assertThat(id.isString(), is(true)); + assertThat(id.getAsString(), is("test3")); + } + { + final VPackSlice from = m1.get("_from"); + assertThat(from.isString(), is(true)); + assertThat(from.getAsString(), is("test4")); + } + { + final VPackSlice to = m1.get("_to"); + assertThat(to.isString(), is(true)); + assertThat(to.getAsString(), is("test5")); + } + } + + @Test + public void toMapWithAttributeAdapter() throws VPackException { + final VPackBuilder builder = new VPackBuilder(); + { + builder.add(ValueType.OBJECT); + builder.add("m1", ValueType.OBJECT); + builder.add("_key", "a"); + builder.add("_rev", "b"); + builder.add("_id", "c"); + builder.add("_from", "d"); + builder.add("_to", "e"); + builder.close(); + builder.close(); + } + final TestEntityMap entity = new VPack.Builder().build().deserialize(builder.slice(), TestEntityMap.class); + assertThat(entity, is(notNullValue())); + assertThat(entity.m1, is(notNullValue())); + assertThat(entity.m1.size(), is(5)); + } + + @Test + public void customSerializer() throws VPackException { + final String value = "abc"; + final VPack vp = new VPack.Builder() + .registerSerializer(TestEntityString.class, new VPackSerializer() { + @Override + public void serialize( + final VPackBuilder builder, + final String attribute, + final TestEntityString entity, + final VPackSerializationContext context) throws VPackException { + builder.add(attribute, ValueType.OBJECT); + builder.add("not-s", entity.s); + builder.close(); + } + }).build(); + final TestEntityString entity = new TestEntityString(); + entity.setS(value); + final VPackSlice vpack = vp.serialize(entity); + assertThat(vpack, is(notNullValue())); + assertThat(vpack.isObject(), is(true)); + { + final VPackSlice s = vpack.get("not-s"); + assertThat(s.isString(), is(true)); + assertThat(s.getAsString(), is(value)); + } + } + + @Test + public void customDeserializer() throws VPackException { + final String value = "abc"; + final VPackBuilder builder = new VPackBuilder(); + builder.add(ValueType.OBJECT); + builder.add("not-s", value); + builder.close(); + final VPack vp = new VPack.Builder() + .registerDeserializer(TestEntityString.class, new VPackDeserializer() { + @Override + public TestEntityString deserialize( + final VPackSlice parent, + final VPackSlice vpack, + final VPackDeserializationContext context) throws VPackException { + final TestEntityString entity = new TestEntityString(); + final VPackSlice nots = vpack.get("not-s"); + if (nots.isString()) { + entity.s = nots.getAsString(); + } + return entity; + } + }).build(); + final TestEntityString entity = vp.deserialize(builder.slice(), TestEntityString.class); + assertThat(entity, is(notNullValue())); + assertThat(entity.s, is(notNullValue())); + assertThat(entity.s, is(value)); + } + + @Test + public void customDeserializerByName() throws VPackException { + final VPackBuilder builder = new VPackBuilder(); + builder.add(ValueType.OBJECT); + builder.add("s", "test"); + builder.close(); + final TestEntityString entity = new VPack.Builder() + .registerDeserializer("s", String.class, new VPackDeserializer() { + @Override + public String deserialize( + final VPackSlice parent, + final VPackSlice vpack, + final VPackDeserializationContext context) throws VPackException { + return vpack.getAsString() + "s"; + } + + }).build().deserialize(builder.slice(), TestEntityString.class); + assertThat(entity, is(notNullValue())); + assertThat(entity.s, is(notNullValue())); + assertThat(entity.s, is("tests")); + } + + @Test + public void customDeserializerByNameWrongType() throws VPackException { + final VPackBuilder builder = new VPackBuilder(); + builder.add(ValueType.OBJECT); + builder.add("s", "test"); + builder.close(); + final TestEntityString entity = new VPack.Builder() + .registerDeserializer("s", Integer.class, new VPackDeserializer() { + @Override + public String deserialize( + final VPackSlice parent, + final VPackSlice vpack, + final VPackDeserializationContext context) throws VPackException { + return "fail"; + } + }).build().deserialize(builder.slice(), TestEntityString.class); + assertThat(entity, is(notNullValue())); + assertThat(entity.s, is(notNullValue())); + assertThat(entity.s, is("test")); + } + + @Test + public void customSerializerWithContext() throws VPackException { + final VPack vp = new VPack.Builder() + .registerSerializer(TestEntityObject.class, new VPackSerializer() { + @Override + public void serialize( + final VPackBuilder builder, + final String attribute, + final TestEntityObject entity, + final VPackSerializationContext context) throws VPackException { + builder.add(attribute, ValueType.OBJECT); + context.serialize(builder, "test", entity.o1); + builder.close(); + } + }).build(); + final TestEntityObject entity = new TestEntityObject(); + final VPackSlice vpack = vp.serialize(entity); + assertThat(vpack, is(notNullValue())); + assertThat(vpack.isObject(), is(true)); + { + final VPackSlice test = vpack.get("test"); + assertThat(test.isObject(), is(true)); + final VPackSlice l1 = test.get("l1"); + assertThat(l1.isInteger(), is(true)); + assertThat(l1.getAsInt(), is(1)); + } + } + + @Test + public void customDeserializerWithContext() throws VPackException { + final VPackBuilder builder = new VPackBuilder(); + builder.add(ValueType.OBJECT); + builder.add("test", ValueType.OBJECT); + builder.add("l1", 5); + builder.close(); + builder.close(); + final VPack vp = new VPack.Builder() + .registerDeserializer(TestEntityObject.class, new VPackDeserializer() { + @Override + public TestEntityObject deserialize( + final VPackSlice parent, + final VPackSlice vpack, + final VPackDeserializationContext context) throws VPackException { + final TestEntityObject entity = new TestEntityObject(); + entity.o1 = context.deserialize(vpack.get("test"), TestEntityLong.class); + return entity; + } + }).build(); + final TestEntityObject entity = vp.deserialize(builder.slice(), TestEntityObject.class); + assertThat(entity, is(notNullValue())); + assertThat(entity.o1, is(notNullValue())); + assertThat(entity.o1.l1, is(5L)); + } + + protected static class TestEntitySerializeAnnotation { + + @SerializedName("abc") + private String test = "test"; + + public String getTest() { + return test; + } + + public void setTest(final String test) { + this.test = test; + } + + } + + @Test + public void fromSerializedName() throws VPackException { + final TestEntitySerializeAnnotation entity = new TestEntitySerializeAnnotation(); + final VPackSlice vpack = new VPack.Builder().build().serialize(entity); + assertThat(vpack.isObject(), is(true)); + assertThat(vpack.getLength(), is(1)); + final VPackSlice abc = vpack.get("abc"); + assertThat(abc.isString(), is(true)); + assertThat(abc.getAsString(), is("test")); + } + + @Test + public void toSerializedName() throws VPackException { + final VPackBuilder builder = new VPackBuilder(); + builder.add(ValueType.OBJECT); + builder.add("abc", "test2"); + builder.close(); + final TestEntitySerializeAnnotation entity = new VPack.Builder().build().deserialize(builder.slice(), + TestEntitySerializeAnnotation.class); + assertThat(entity, is(notNullValue())); + assertThat(entity.test, is(notNullValue())); + assertThat(entity.test, is("test2")); + } + + protected static class TestEntityExpose { + private String a; + @Expose + private String b; + @Expose(serialize = true, deserialize = true) + private String c; + @Expose(serialize = true, deserialize = false) + private String d; + @Expose(serialize = false, deserialize = true) + private String e; + @Expose(serialize = false, deserialize = false) + private String f; + + public String getA() { + return a; + } + + public void setA(final String a) { + this.a = a; + } + + public String getB() { + return b; + } + + public void setB(final String b) { + this.b = b; + } + + public String getC() { + return c; + } + + public void setC(final String c) { + this.c = c; + } + + public String getD() { + return d; + } + + public void setD(final String d) { + this.d = d; + } + + public String getE() { + return e; + } + + public void setE(final String e) { + this.e = e; + } + + public String getF() { + return f; + } + + public void setF(final String f) { + this.f = f; + } + } + + @Test + public void fromExpose() throws VPackException { + final TestEntityExpose entity = new TestEntityExpose(); + entity.a = entity.b = entity.c = entity.d = entity.e = entity.f = "test"; + final VPackSlice vpack = new VPack.Builder().build().serialize(entity); + assertThat(vpack.isObject(), is(true)); + assertThat(vpack.getLength(), is(4)); + { + final VPackSlice a = vpack.get("a"); + assertThat(a.isString(), is(true)); + assertThat(a.getAsString(), is("test")); + } + { + final VPackSlice b = vpack.get("b"); + assertThat(b.isString(), is(true)); + assertThat(b.getAsString(), is("test")); + } + { + final VPackSlice c = vpack.get("c"); + assertThat(c.isString(), is(true)); + assertThat(c.getAsString(), is("test")); + } + { + final VPackSlice d = vpack.get("d"); + assertThat(d.isString(), is(true)); + assertThat(d.getAsString(), is("test")); + } + } + + @Test + public void toExpose() throws VPackException { + final VPackBuilder builder = new VPackBuilder(); + builder.add(ValueType.OBJECT); + builder.add("a", "test"); + builder.add("b", "test"); + builder.add("c", "test"); + builder.add("d", "test"); + builder.add("e", "test"); + builder.add("f", "test"); + builder.close(); + final TestEntityExpose entity = new VPack.Builder().build().deserialize(builder.slice(), + TestEntityExpose.class); + assertThat(entity, is(notNullValue())); + assertThat(entity.a, is(notNullValue())); + assertThat(entity.a, is("test")); + assertThat(entity.b, is(notNullValue())); + assertThat(entity.b, is("test")); + assertThat(entity.c, is(notNullValue())); + assertThat(entity.c, is("test")); + assertThat(entity.e, is(notNullValue())); + assertThat(entity.e, is("test")); + assertThat(entity.d, is(nullValue())); + assertThat(entity.f, is(nullValue())); + } + + @Test + public void directFromCollection() throws VPackException { + final Collection list = new ArrayList(); + list.add("test"); + final VPackSlice vpack = new VPack.Builder().build().serialize(list); + assertThat(vpack, is(notNullValue())); + assertThat(vpack.isArray(), is(true)); + assertThat(vpack.size(), is(1)); + final VPackSlice test = vpack.get(0); + assertThat(test.isString(), is(true)); + assertThat(test.getAsString(), is("test")); + } + + @Test + public void directFromCollectionWithType() throws VPackException { + final Collection list = new ArrayList(); + list.add(new TestEntityString()); + list.add(new TestEntityString()); + + final VPackSlice vpack = new VPack.Builder().build().serialize(list, new Type>() { + }.getType()); + assertThat(vpack, is(notNullValue())); + assertThat(vpack.isArray(), is(true)); + assertThat(vpack.getLength(), is(list.size())); + for (int i = 0; i < list.size(); i++) { + final VPackSlice entry = vpack.get(i); + assertThat(entry.isObject(), is(true)); + assertThat(entry.getLength(), is(3)); + final VPackSlice s = entry.get("s"); + assertThat(s.isString(), is(true)); + assertThat(s.getAsString(), is("test")); + } + } + + @Test + public void directToCollection() throws VPackException { + final VPackBuilder builder = new VPackBuilder(); + builder.add(ValueType.ARRAY); + builder.add(ValueType.OBJECT); + builder.add("s", "abc"); + builder.close(); + builder.close(); + final List list = new VPack.Builder().build().deserialize(builder.slice(), + new Type>() { + }.getType()); + assertThat(list, is(notNullValue())); + assertThat(list.size(), is(1)); + final TestEntityString entry = list.get(0); + assertThat(entry.s, is("abc")); + } + + @Test + public void directFromStringMap() throws VPackException { + final Map map = new HashMap(); + map.put("a", new TestEntityString()); + map.put("b", new TestEntityString()); + + final VPackSlice vpack = new VPack.Builder().build().serialize(map, new Type>() { + }.getType()); + assertThat(vpack, is(notNullValue())); + assertThat(vpack.isObject(), is(true)); + assertThat(vpack.getLength(), is(2)); + final VPackSlice a = vpack.get("a"); + checkStringEntity(a); + } + + @Test + public void directToStringMap() throws VPackException { + final VPackBuilder builder = new VPackBuilder(); + builder.add(ValueType.OBJECT); + builder.add("a", ValueType.OBJECT); + builder.add("s", "abc"); + builder.close(); + builder.close(); + final Map map = new VPack.Builder().build().deserialize(builder.slice(), + new Type>() { + }.getType()); + assertThat(map, is(notNullValue())); + assertThat(map.size(), is(1)); + final TestEntityString a = map.get("a"); + assertThat(a, is(notNullValue())); + assertThat(a.s, is("abc")); + } + + @Test + public void directFromObjectMap() throws VPackException { + final Map map = new HashMap(); + map.put(new TestEntityString(), new TestEntityString()); + map.put(new TestEntityString(), new TestEntityString()); + + final VPackSlice vpack = new VPack.Builder().build().serialize(map, + new Type>() { + }.getType()); + assertThat(vpack, is(notNullValue())); + assertThat(vpack.isArray(), is(true)); + assertThat(vpack.getLength(), is(map.size())); + for (int i = 0; i < map.size(); i++) { + final VPackSlice entry = vpack.get(i); + final VPackSlice key = entry.get("key"); + checkStringEntity(key); + final VPackSlice value = entry.get("value"); + checkStringEntity(value); + } + } + + @Test + public void directFromMap() throws VPackException { + final Map map = new HashMap(); + final TestEntityA entity = new TestEntityA(); + entity.a = "test"; + map.put("test", entity); + final VPackSlice vpack = new VPack.Builder().build().serialize(map); + assertThat(vpack, is(notNullValue())); + assertThat(vpack.isObject(), is(true)); + final VPackSlice test = vpack.get("test"); + assertThat(test.isObject(), is(true)); + final VPackSlice a = test.get("a"); + assertThat(a.isString(), is(true)); + assertThat(a.getAsString(), is("test")); + } + + @Test + public void directFromMapWithinMap() throws VPackException { + final Map map = new HashMap(); + final Map map2 = new HashMap(); + map2.put("b", "test"); + map.put("a", map2); + final VPackSlice vpack = new VPack.Builder().build().serialize(map); + assertThat(vpack, is(notNullValue())); + assertThat(vpack.isObject(), is(true)); + assertThat(vpack.size(), is(1)); + final VPackSlice a = vpack.get("a"); + assertThat(a.isObject(), is(true)); + assertThat(a.size(), is(1)); + final VPackSlice b = a.get("b"); + assertThat(b.isString(), is(true)); + assertThat(b.getAsString(), is("test")); + } + + private void checkStringEntity(final VPackSlice vpack) throws VPackException { + final TestEntityString expected = new TestEntityString(); + assertThat(vpack.isObject(), is(true)); + assertThat(vpack.getLength(), is(3)); + final VPackSlice s = vpack.get("s"); + assertThat(s.isString(), is(true)); + assertThat(s.getAsString(), is(expected.s)); + final VPackSlice c1 = vpack.get("c1"); + assertThat(c1.isString(), is(true)); + assertThat(new Character(c1.getAsChar()), is(expected.c1)); + final VPackSlice c2 = vpack.get("c2"); + assertThat(c2.isString(), is(true)); + assertThat(c2.getAsChar(), is(expected.c2)); + } + + @Test + public void directToObjectMap() throws VPackException { + final VPackBuilder builder = new VPackBuilder(); + builder.add(ValueType.ARRAY); + builder.add(ValueType.OBJECT); + builder.add("key", ValueType.OBJECT); + builder.add("s", "abc"); + builder.close(); + builder.add("value", ValueType.OBJECT); + builder.add("s", "abc"); + builder.close(); + builder.close(); + builder.close(); + final Map map = new VPack.Builder().build().deserialize(builder.slice(), + new Type>() { + }.getType()); + assertThat(map, is(notNullValue())); + assertThat(map.size(), is(1)); + for (final Entry entry : map.entrySet()) { + assertThat(entry.getKey().s, is("abc")); + assertThat(entry.getValue().s, is("abc")); + } + } + + @SuppressWarnings("unchecked") + @Test + public void directToMapWithinMap() throws VPackException { + final VPackBuilder builder = new VPackBuilder(); + builder.add(ValueType.OBJECT); + builder.add("a", ValueType.OBJECT); + builder.add("b", "test"); + builder.add("c", true); + builder.add("d", 1L); + builder.add("e", 1.5); + final Date date = new Date(); + builder.add("f", date); + builder.add("g", ValueType.ARRAY); + builder.close(); + builder.close(); + builder.close(); + final Map map = new VPack.Builder().build().deserialize(builder.slice(), Map.class); + assertThat(map, is(notNullValue())); + assertThat(map.size(), is(1)); + final Object a = map.get("a"); + assertThat(Map.class.isAssignableFrom(a.getClass()), is(true)); + final Map mapA = (Map) a; + assertThat(mapA.size(), is(6)); + final Object b = mapA.get("b"); + assertThat(String.class.isAssignableFrom(b.getClass()), is(true)); + assertThat(b.toString(), is("test")); + final Object c = mapA.get("c"); + assertThat(Boolean.class.isAssignableFrom(c.getClass()), is(true)); + assertThat(Boolean.class.cast(c), is(true)); + final Object d = mapA.get("d"); + assertThat(Number.class.isAssignableFrom(d.getClass()), is(true)); + assertThat(Number.class.cast(d).longValue(), is(1L)); + final Object e = mapA.get("e"); + assertThat(Double.class.isAssignableFrom(e.getClass()), is(true)); + assertThat(Double.class.cast(e), is(1.5)); + final Object f = mapA.get("f"); + assertThat(Date.class.isAssignableFrom(f.getClass()), is(true)); + assertThat(Date.class.cast(f), is(date)); + final Object g = mapA.get("g"); + assertThat(Collection.class.isAssignableFrom(g.getClass()), is(true)); + assertThat(List.class.isAssignableFrom(g.getClass()), is(true)); + } + + @Test + public void dontSerializeNullValues() throws VPackException { + final VPack serializer = new VPack.Builder().serializeNullValues(false).build(); + final TestEntityString entity = new TestEntityString(); + entity.setS(null); + final VPackSlice vpack = serializer.serialize(entity); + assertThat(vpack, is(notNullValue())); + assertThat(vpack.isObject(), is(true)); + final VPackSlice s = vpack.get("s"); + assertThat(s.isNone(), is(true)); + } + + @Test + public void serializeNullValue() throws VPackException { + final VPack serializer = new VPack.Builder().serializeNullValues(true).build(); + final TestEntityString entity = new TestEntityString(); + entity.setS(null); + final VPackSlice vpack = serializer.serialize(entity); + assertThat(vpack, is(notNullValue())); + final VPackSlice s = vpack.get("s"); + assertThat(s.isNull(), is(true)); + } + + @Test + public void toNullValue() throws VPackException { + final VPackBuilder builder = new VPackBuilder(); + builder.add(ValueType.OBJECT); + builder.add("s", ValueType.NULL); + builder.close(); + final TestEntityString entity = new VPack.Builder().build().deserialize(builder.slice(), + TestEntityString.class); + assertThat(entity, is(notNullValue())); + assertThat(entity.s, is(nullValue())); + assertThat(entity.c1, is(notNullValue())); + assertThat(entity.c2, is(notNullValue())); + } + + @Test + public void additionalFields() throws VPackException { + final TestEntityString entity = new TestEntityString(); + final Map additionalFields = new HashMap(); + additionalFields.put("a", "test"); + final VPackSlice vpack = new VPack.Builder().build().serialize(entity, additionalFields); + assertThat(vpack, is(notNullValue())); + assertThat(vpack.getLength(), is(4)); + final VPackSlice s = vpack.get("s"); + assertThat(s.isString(), is(true)); + assertThat(s.getAsString(), is("test")); + final VPackSlice a = vpack.get("a"); + assertThat(a.isString(), is(true)); + assertThat(a.getAsString(), is("test")); + } + + @Test + public void additionalDuplicatedFields() throws VPackException { + final TestEntityString entity = new TestEntityString(); + final Map additionalFields = new HashMap(); + additionalFields.put("s", "test1"); + final VPackSlice vpack = new VPack.Builder().build().serialize(entity, additionalFields); + assertThat(vpack, is(notNullValue())); + assertThat(vpack.getLength(), is(3)); + final VPackSlice s = vpack.get("s"); + assertThat(s.isString(), is(true)); + assertThat(s.getAsString(), is("test")); + } + + @Test + public void additionalNullFieldsExcludeNull() throws VPackException { + final TestEntityString entity = new TestEntityString(); + final Map additionalFields = new HashMap(); + additionalFields.put("a", null); + final VPackSlice vpack = new VPack.Builder().build().serialize(entity, additionalFields); + assertThat(vpack, is(notNullValue())); + assertThat(vpack.getLength(), is(3)); + final VPackSlice s = vpack.get("s"); + assertThat(s.isString(), is(true)); + assertThat(s.getAsString(), is("test")); + } + + @Test + public void additionalNullFieldsIncludeNull() throws VPackException { + final TestEntityString entity = new TestEntityString(); + final Map additionalFields = new HashMap(); + additionalFields.put("a", null); + final VPack serializer = new VPack.Builder().serializeNullValues(true).build(); + final VPackSlice vpack = serializer.serialize(entity, additionalFields); + assertThat(vpack, is(notNullValue())); + assertThat(vpack.getLength(), is(4)); + final VPackSlice s = vpack.get("s"); + assertThat(s.isString(), is(true)); + assertThat(s.getAsString(), is("test")); + final VPackSlice a = vpack.get("a"); + assertThat(a.isNull(), is(true)); + } + + @Test + public void toSimpleString() throws VPackException { + final VPackBuilder builder = new VPackBuilder(); + builder.add("test"); + final String s = new VPack.Builder().build().deserialize(builder.slice(), String.class); + assertThat(s, is(notNullValue())); + assertThat(s, is("test")); + } + + @Test + public void fromSimpleString() throws VPackException { + final VPackSlice vpack = new VPack.Builder().build().serialize("test"); + assertThat(vpack, is(notNullValue())); + assertThat(vpack.isString(), is(true)); + assertThat(vpack.getAsString(), is("test")); + } + + protected static class TestEntityTyped { + private T e; + } + + @Test + public void fromStringTypedEntity() throws VPackException { + final TestEntityTyped entity = new TestEntityTyped(); + entity.e = "test"; + final VPackSlice vpack = new VPack.Builder().build().serialize(entity); + assertThat(vpack, is(notNullValue())); + assertThat(vpack.isObject(), is(true)); + final VPackSlice e = vpack.get("e"); + assertThat(e, is(notNullValue())); + assertThat(e.isString(), is(true)); + assertThat(e.getAsString(), is("test")); + } + + @Test + public void fromObjectTypedEntity() throws VPackException { + final TestEntityTyped entity = new TestEntityTyped(); + entity.e = new TestEntityString(); + entity.e.s = "test2"; + final VPackSlice vpack = new VPack.Builder().build().serialize(entity); + assertThat(vpack, is(notNullValue())); + assertThat(vpack.isObject(), is(true)); + final VPackSlice e = vpack.get("e"); + assertThat(e, is(notNullValue())); + assertThat(e.isObject(), is(true)); + final VPackSlice s = e.get("s"); + assertThat(s, is(notNullValue())); + assertThat(s.isString(), is(true)); + assertThat(s.getAsString(), is("test2")); + } + + @Test + public void fromTypedTypedEntity() throws VPackException { + final TestEntityTyped> entity = new TestEntityTyped>(); + entity.e = new TestEntityTyped(); + entity.e.e = "test"; + final VPackSlice vpack = new VPack.Builder().build().serialize(entity, + new Type>>() { + }.getType()); + assertThat(vpack, is(notNullValue())); + assertThat(vpack.isObject(), is(true)); + final VPackSlice e = vpack.get("e"); + assertThat(e, is(notNullValue())); + assertThat(e.isObject(), is(true)); + final VPackSlice e2 = e.get("e"); + assertThat(e2, is(notNullValue())); + assertThat(e2.isString(), is(true)); + assertThat(e2.getAsString(), is("test")); + } + + @Test + public void fieldNamingStrategySerialize() throws VPackException { + final VPackSlice vpack = new VPack.Builder().fieldNamingStrategy(new VPackFieldNamingStrategy() { + @Override + public String translateName(final Field field) { + return "bla"; + } + }).build().serialize(new TestEntityA()); + assertThat(vpack, is(notNullValue())); + assertThat(vpack.isObject(), is(true)); + final VPackSlice bla = vpack.get("bla"); + assertThat(bla.isString(), is(true)); + assertThat(bla.getAsString(), is("a")); + } + + @Test + public void fieldNamingStrategyDeserialize() throws VPackException { + final VPackBuilder builder = new VPackBuilder(); + builder.add(ValueType.OBJECT); + builder.add("bla", "test"); + builder.close(); + final TestEntityA entity = new VPack.Builder().fieldNamingStrategy(new VPackFieldNamingStrategy() { + @Override + public String translateName(final Field field) { + return "bla"; + } + }).build().deserialize(builder.slice(), TestEntityA.class); + assertThat(entity, is(notNullValue())); + assertThat(entity.a, is("test")); + } + + @Test + public void serializeVPack() throws VPackException { + final VPackBuilder builder = new VPackBuilder(); + builder.add("test"); + final VPackSlice slice = builder.slice(); + final VPackSlice vpack = new VPack.Builder().build().serialize(slice); + assertThat(vpack, is(notNullValue())); + assertThat(vpack.isString(), is(true)); + assertThat(vpack.getAsString(), is("test")); + } + + @Test + public void deserializeVPack() throws VPackException { + final VPackBuilder builder = new VPackBuilder(); + builder.add("test"); + final VPackSlice slice = builder.slice(); + final VPackSlice vpack = new VPack.Builder().build().deserialize(slice, slice.getClass()); + assertThat(vpack, is(notNullValue())); + assertThat(vpack.isString(), is(true)); + assertThat(vpack.getAsString(), is("test")); + } + + protected static class TestEntityDate { + private java.util.Date utilDate = new Date(1474988621); + private java.sql.Date sqlDate = new java.sql.Date(1474988621); + private java.sql.Timestamp timestamp = new java.sql.Timestamp(1474988621); + + public java.util.Date getUtilDate() { + return utilDate; + } + + public void setUtilDate(final java.util.Date utilDate) { + this.utilDate = utilDate; + } + + public java.sql.Date getSqlDate() { + return sqlDate; + } + + public void setSqlDate(final java.sql.Date sqlDate) { + this.sqlDate = sqlDate; + } + + public java.sql.Timestamp getTimestamp() { + return timestamp; + } + + public void setTimestamp(final java.sql.Timestamp timestamp) { + this.timestamp = timestamp; + } + + } + + @Test + public void fromDate() throws VPackException { + final VPackSlice vpack = new VPack.Builder().build().serialize(new TestEntityDate()); + assertThat(vpack, is(notNullValue())); + assertThat(vpack.isObject(), is(true)); + { + assertThat(vpack.get("utilDate").isDate(), is(true)); + assertThat(vpack.get("utilDate").getAsDate(), is(new Date(1474988621))); + } + { + assertThat(vpack.get("sqlDate").isDate(), is(true)); + assertThat(vpack.get("sqlDate").getAsSQLDate(), is(new java.sql.Date(1474988621))); + } + { + assertThat(vpack.get("timestamp").isDate(), is(true)); + assertThat(vpack.get("timestamp").getAsSQLTimestamp(), is(new java.sql.Timestamp(1474988621))); + } + } + + @Test + public void toDate() throws VPackException { + final VPackBuilder builder = new VPackBuilder(); + builder.add(ValueType.OBJECT); + builder.add("utilDate", new Date(1475062216)); + builder.add("sqlDate", new java.sql.Date(1475062216)); + builder.add("timestamp", new java.sql.Timestamp(1475062216)); + builder.close(); + + final TestEntityDate entity = new VPack.Builder().build().deserialize(builder.slice(), TestEntityDate.class); + assertThat(entity, is(notNullValue())); + assertThat(entity.utilDate, is(new Date(1475062216))); + assertThat(entity.sqlDate, is(new java.sql.Date(1475062216))); + assertThat(entity.timestamp, is(new java.sql.Timestamp(1475062216))); + } + +} diff --git a/src/test/java/com/arangodb/velocypack/VPackSliceTest.java b/src/test/java/com/arangodb/velocypack/VPackSliceTest.java new file mode 100644 index 000000000..56f818ee9 --- /dev/null +++ b/src/test/java/com/arangodb/velocypack/VPackSliceTest.java @@ -0,0 +1,1246 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.velocypack; + +import static org.hamcrest.Matchers.is; +import static org.junit.Assert.assertThat; + +import java.math.BigInteger; +import java.util.Arrays; +import java.util.Collection; +import java.util.Date; +import java.util.Iterator; +import java.util.Map.Entry; + +import org.junit.Test; + +import com.arangodb.velocypack.exception.VPackException; +import com.arangodb.velocypack.exception.VPackValueTypeException; + +/** + * @author Mark - mark at arangodb.com + * + */ +public class VPackSliceTest { + + @Test + public void isNone() { + final byte[] vpack = { 0x00 }; + final VPackSlice slice = new VPackSlice(vpack); + assertThat(slice.isNone(), is(true)); + } + + @Test + public void isNull() { + final byte[] vpack = { 0x18 }; + final VPackSlice slice = new VPackSlice(vpack); + assertThat(slice.isNull(), is(true)); + } + + @Test + public void isIllegal() { + final byte[] vpack = { 0x17 }; + final VPackSlice slice = new VPackSlice(vpack); + assertThat(slice.isIllegal(), is(true)); + } + + @Test + public void booleanTrue() { + final byte[] vpack = { 0x1a }; + final VPackSlice slice = new VPackSlice(vpack); + assertThat(slice.isBoolean(), is(true)); + assertThat(slice.isTrue(), is(true)); + assertThat(slice.isFalse(), is(false)); + assertThat(slice.getByteSize(), is(1)); + } + + @Test + public void booleanFalse() { + final byte[] vpack = { 0x19 }; + final VPackSlice slice = new VPackSlice(vpack); + assertThat(slice.isBoolean(), is(true)); + assertThat(slice.isFalse(), is(true)); + assertThat(slice.isTrue(), is(false)); + assertThat(slice.getByteSize(), is(1)); + } + + @Test + public void isArray() { + checkArray(new byte[] { 0x01 }); + checkArray(new byte[] { 0x02 }); + checkArray(new byte[] { 0x03 }); + checkArray(new byte[] { 0x04 }); + checkArray(new byte[] { 0x05 }); + checkArray(new byte[] { 0x06 }); + checkArray(new byte[] { 0x07 }); + checkArray(new byte[] { 0x08 }); + checkArray(new byte[] { 0x09 }); + checkArray(new byte[] { 0x13 }); + } + + private void checkArray(final byte[] vpack) { + final VPackSlice slice = new VPackSlice(vpack); + assertThat(slice.isArray(), is(true)); + } + + @Test + public void isObject() { + checkObject(new byte[] { 0x0b }); + checkObject(new byte[] { 0x0c }); + checkObject(new byte[] { 0x0d }); + checkObject(new byte[] { 0x0e }); + checkObject(new byte[] { 0x0f }); + checkObject(new byte[] { 0x10 }); + checkObject(new byte[] { 0x11 }); + checkObject(new byte[] { 0x12 }); + checkObject(new byte[] { 0x14 }); + } + + private void checkObject(final byte[] vpack) { + final VPackSlice slice = new VPackSlice(vpack); + assertThat(slice.isObject(), is(true)); + } + + @Test + public void isDouble() { + final byte[] vpack = { 0x1b }; + final VPackSlice slice = new VPackSlice(vpack); + assertThat(slice.isDouble(), is(true)); + assertThat(slice.isNumber(), is(true)); + } + + @Test + public void isUTCDate() { + final byte[] vpack = { 0x1c }; + final VPackSlice slice = new VPackSlice(vpack); + assertThat(slice.isDate(), is(true)); + } + + @Test + public void isExternal() { + final byte[] vpack = { 0x1d }; + final VPackSlice slice = new VPackSlice(vpack); + assertThat(slice.isExternal(), is(true)); + } + + @Test + public void isMinKey() { + final byte[] vpack = { 0x1e }; + final VPackSlice slice = new VPackSlice(vpack); + assertThat(slice.isMinKey(), is(true)); + } + + @Test + public void isMaxKey() { + final byte[] vpack = { 0x1f }; + final VPackSlice slice = new VPackSlice(vpack); + assertThat(slice.isMaxKey(), is(true)); + } + + @Test + public void isInt() { + checkInt(new byte[] { 0x20 }); + checkInt(new byte[] { 0x21 }); + checkInt(new byte[] { 0x22 }); + checkInt(new byte[] { 0x23 }); + checkInt(new byte[] { 0x24 }); + checkInt(new byte[] { 0x25 }); + checkInt(new byte[] { 0x26 }); + checkInt(new byte[] { 0x27 }); + } + + private void checkInt(final byte[] vpack) { + final VPackSlice slice = new VPackSlice(vpack); + assertThat(slice.isInt(), is(true)); + assertThat(slice.isInteger(), is(true)); + assertThat(slice.isNumber(), is(true)); + } + + @Test + public void isUInt() { + checkUInt(new byte[] { 0x28 }); + checkUInt(new byte[] { 0x29 }); + checkUInt(new byte[] { 0x2a }); + checkUInt(new byte[] { 0x2b }); + checkUInt(new byte[] { 0x2c }); + checkUInt(new byte[] { 0x2d }); + checkUInt(new byte[] { 0x2e }); + checkUInt(new byte[] { 0x2f }); + } + + private void checkUInt(final byte[] vpack) { + final VPackSlice slice = new VPackSlice(vpack); + assertThat(slice.isUInt(), is(true)); + assertThat(slice.isInteger(), is(true)); + assertThat(slice.isNumber(), is(true)); + } + + @Test + public void isSmallInt() { + checkSmallInt(new byte[] { 0x30 }); + checkSmallInt(new byte[] { 0x31 }); + checkSmallInt(new byte[] { 0x32 }); + checkSmallInt(new byte[] { 0x33 }); + checkSmallInt(new byte[] { 0x34 }); + checkSmallInt(new byte[] { 0x35 }); + checkSmallInt(new byte[] { 0x36 }); + checkSmallInt(new byte[] { 0x37 }); + checkSmallInt(new byte[] { 0x38 }); + checkSmallInt(new byte[] { 0x39 }); + checkSmallInt(new byte[] { 0x3a }); + checkSmallInt(new byte[] { 0x3b }); + checkSmallInt(new byte[] { 0x3c }); + checkSmallInt(new byte[] { 0x3d }); + checkSmallInt(new byte[] { 0x3e }); + checkSmallInt(new byte[] { 0x3f }); + } + + private void checkSmallInt(final byte[] vpack) { + final VPackSlice slice = new VPackSlice(vpack); + assertThat(slice.isSmallInt(), is(true)); + assertThat(slice.isInteger(), is(true)); + assertThat(slice.isNumber(), is(true)); + } + + @Test + public void isString() { + checkString(new byte[] { 0x40 }); + checkString(new byte[] { 0x41 }); + checkString(new byte[] { 0x42 }); + checkString(new byte[] { 0x43 }); + checkString(new byte[] { 0x44 }); + checkString(new byte[] { 0x45 }); + checkString(new byte[] { 0x46 }); + checkString(new byte[] { 0x47 }); + checkString(new byte[] { 0x48 }); + checkString(new byte[] { 0x49 }); + checkString(new byte[] { 0x4a }); + checkString(new byte[] { 0x4b }); + checkString(new byte[] { 0x4c }); + checkString(new byte[] { 0x4d }); + checkString(new byte[] { 0x4e }); + checkString(new byte[] { 0x4f }); + checkString(new byte[] { 0x50 }); + checkString(new byte[] { 0x51 }); + checkString(new byte[] { 0x52 }); + checkString(new byte[] { 0x53 }); + checkString(new byte[] { 0x54 }); + checkString(new byte[] { 0x55 }); + checkString(new byte[] { 0x56 }); + checkString(new byte[] { 0x57 }); + checkString(new byte[] { 0x58 }); + checkString(new byte[] { 0x59 }); + checkString(new byte[] { 0x5a }); + checkString(new byte[] { 0x5b }); + checkString(new byte[] { 0x5c }); + checkString(new byte[] { 0x5d }); + checkString(new byte[] { 0x5e }); + checkString(new byte[] { 0x5f }); + checkString(new byte[] { 0x60 }); + checkString(new byte[] { 0x61 }); + checkString(new byte[] { 0x62 }); + checkString(new byte[] { 0x63 }); + checkString(new byte[] { 0x64 }); + checkString(new byte[] { 0x65 }); + checkString(new byte[] { 0x66 }); + checkString(new byte[] { 0x67 }); + checkString(new byte[] { 0x68 }); + checkString(new byte[] { 0x69 }); + checkString(new byte[] { 0x6a }); + checkString(new byte[] { 0x6b }); + checkString(new byte[] { 0x6c }); + checkString(new byte[] { 0x6d }); + checkString(new byte[] { 0x6e }); + checkString(new byte[] { 0x6f }); + checkString(new byte[] { 0x70 }); + checkString(new byte[] { 0x71 }); + checkString(new byte[] { 0x72 }); + checkString(new byte[] { 0x73 }); + checkString(new byte[] { 0x74 }); + checkString(new byte[] { 0x75 }); + checkString(new byte[] { 0x76 }); + checkString(new byte[] { 0x77 }); + checkString(new byte[] { 0x78 }); + checkString(new byte[] { 0x79 }); + checkString(new byte[] { 0x7a }); + checkString(new byte[] { 0x7b }); + checkString(new byte[] { 0x7c }); + checkString(new byte[] { 0x7d }); + checkString(new byte[] { 0x7e }); + checkString(new byte[] { 0x7f }); + checkString(new byte[] { (byte) 0x80 }); + checkString(new byte[] { (byte) 0x81 }); + checkString(new byte[] { (byte) 0x82 }); + checkString(new byte[] { (byte) 0x83 }); + checkString(new byte[] { (byte) 0x84 }); + checkString(new byte[] { (byte) 0x85 }); + checkString(new byte[] { (byte) 0x86 }); + checkString(new byte[] { (byte) 0x87 }); + checkString(new byte[] { (byte) 0x88 }); + checkString(new byte[] { (byte) 0x89 }); + checkString(new byte[] { (byte) 0x8a }); + checkString(new byte[] { (byte) 0x8b }); + checkString(new byte[] { (byte) 0x8c }); + checkString(new byte[] { (byte) 0x8d }); + checkString(new byte[] { (byte) 0x8e }); + checkString(new byte[] { (byte) 0x8f }); + checkString(new byte[] { (byte) 0x90 }); + checkString(new byte[] { (byte) 0x91 }); + checkString(new byte[] { (byte) 0x92 }); + checkString(new byte[] { (byte) 0x93 }); + checkString(new byte[] { (byte) 0x94 }); + checkString(new byte[] { (byte) 0x95 }); + checkString(new byte[] { (byte) 0x96 }); + checkString(new byte[] { (byte) 0x97 }); + checkString(new byte[] { (byte) 0x98 }); + checkString(new byte[] { (byte) 0x99 }); + checkString(new byte[] { (byte) 0x9a }); + checkString(new byte[] { (byte) 0x9b }); + checkString(new byte[] { (byte) 0x9c }); + checkString(new byte[] { (byte) 0x9d }); + checkString(new byte[] { (byte) 0x9e }); + checkString(new byte[] { (byte) 0x9f }); + checkString(new byte[] { (byte) 0xa0 }); + checkString(new byte[] { (byte) 0xa1 }); + checkString(new byte[] { (byte) 0xa2 }); + checkString(new byte[] { (byte) 0xa3 }); + checkString(new byte[] { (byte) 0xa4 }); + checkString(new byte[] { (byte) 0xa5 }); + checkString(new byte[] { (byte) 0xa6 }); + checkString(new byte[] { (byte) 0xa7 }); + checkString(new byte[] { (byte) 0xa8 }); + checkString(new byte[] { (byte) 0xa9 }); + checkString(new byte[] { (byte) 0xaa }); + checkString(new byte[] { (byte) 0xab }); + checkString(new byte[] { (byte) 0xac }); + checkString(new byte[] { (byte) 0xad }); + checkString(new byte[] { (byte) 0xae }); + checkString(new byte[] { (byte) 0xaf }); + checkString(new byte[] { (byte) 0xb0 }); + checkString(new byte[] { (byte) 0xb1 }); + checkString(new byte[] { (byte) 0xb2 }); + checkString(new byte[] { (byte) 0xb3 }); + checkString(new byte[] { (byte) 0xb4 }); + checkString(new byte[] { (byte) 0xb5 }); + checkString(new byte[] { (byte) 0xb6 }); + checkString(new byte[] { (byte) 0xb7 }); + checkString(new byte[] { (byte) 0xb8 }); + checkString(new byte[] { (byte) 0xb9 }); + checkString(new byte[] { (byte) 0xba }); + checkString(new byte[] { (byte) 0xbb }); + checkString(new byte[] { (byte) 0xbc }); + checkString(new byte[] { (byte) 0xbd }); + checkString(new byte[] { (byte) 0xbe }); + checkString(new byte[] { (byte) 0xbf }); + } + + private void checkString(final byte[] vpack) { + final VPackSlice slice = new VPackSlice(vpack); + assertThat(slice.isString(), is(true)); + } + + @Test + public void isBinary() { + checkBinary(new byte[] { (byte) 0xc0 }); + checkBinary(new byte[] { (byte) 0xc1 }); + checkBinary(new byte[] { (byte) 0xc2 }); + checkBinary(new byte[] { (byte) 0xc3 }); + checkBinary(new byte[] { (byte) 0xc4 }); + checkBinary(new byte[] { (byte) 0xc5 }); + checkBinary(new byte[] { (byte) 0xc6 }); + checkBinary(new byte[] { (byte) 0xc7 }); + } + + private void checkBinary(final byte[] vpack) { + final VPackSlice slice = new VPackSlice(vpack); + assertThat(slice.isBinary(), is(true)); + } + + @Test + public void isBCD() { + checkBCD(new byte[] { (byte) 0xc8 }); + checkBCD(new byte[] { (byte) 0xc9 }); + checkBCD(new byte[] { (byte) 0xca }); + checkBCD(new byte[] { (byte) 0xcb }); + checkBCD(new byte[] { (byte) 0xcc }); + checkBCD(new byte[] { (byte) 0xcd }); + checkBCD(new byte[] { (byte) 0xce }); + checkBCD(new byte[] { (byte) 0xcf }); + checkBCD(new byte[] { (byte) 0xd0 }); + checkBCD(new byte[] { (byte) 0xd1 }); + checkBCD(new byte[] { (byte) 0xd2 }); + checkBCD(new byte[] { (byte) 0xd3 }); + checkBCD(new byte[] { (byte) 0xd4 }); + checkBCD(new byte[] { (byte) 0xd5 }); + checkBCD(new byte[] { (byte) 0xd6 }); + checkBCD(new byte[] { (byte) 0xd7 }); + } + + private void checkBCD(final byte[] vpack) { + final VPackSlice slice = new VPackSlice(vpack); + assertThat(slice.isBCD(), is(true)); + } + + @Test + public void isCustom() { + checkCustom(new byte[] { (byte) 0xf0 }); + checkCustom(new byte[] { (byte) 0xf1 }); + checkCustom(new byte[] { (byte) 0xf2 }); + checkCustom(new byte[] { (byte) 0xf3 }); + checkCustom(new byte[] { (byte) 0xf4 }); + checkCustom(new byte[] { (byte) 0xf5 }); + checkCustom(new byte[] { (byte) 0xf6 }); + checkCustom(new byte[] { (byte) 0xf7 }); + checkCustom(new byte[] { (byte) 0xf8 }); + checkCustom(new byte[] { (byte) 0xf9 }); + checkCustom(new byte[] { (byte) 0xfa }); + checkCustom(new byte[] { (byte) 0xfb }); + checkCustom(new byte[] { (byte) 0xfc }); + checkCustom(new byte[] { (byte) 0xfd }); + checkCustom(new byte[] { (byte) 0xfe }); + checkCustom(new byte[] { (byte) 0xff }); + } + + private void checkCustom(final byte[] vpack) { + final VPackSlice slice = new VPackSlice(vpack); + assertThat(slice.isCustom(), is(true)); + } + + @Test + public void getBooleanTrue() throws VPackException { + final byte[] vpack = { 0x1a }; + final VPackSlice slice = new VPackSlice(vpack); + assertThat(slice.getAsBoolean(), is(true)); + } + + @Test + public void getBooleanFalse() throws VPackException { + final byte[] vpack = { 0x19 }; + final VPackSlice slice = new VPackSlice(vpack); + assertThat(slice.getAsBoolean(), is(false)); + } + + @Test(expected = VPackValueTypeException.class) + public void getBooleanFail() { + final VPackSlice slice = new VPackSlice(new byte[] { 0x00 }); + slice.getAsBoolean(); + } + + @Test + public void getDouble() throws VPackException { + { + final byte[] vpack = { 0x1b, 0x66, 0x66, 0x66, 0x66, 0x66, (byte) 0xb6, 0x60, 0x40 }; + final VPackSlice slice = new VPackSlice(vpack); + assertThat(slice.getAsDouble(), is(133.7)); + } + { + final byte[] vpack = { 0x1b, 0x66, 0x66, 0x66, 0x66, 0x66, (byte) 0xb6, 0x60, (byte) 0xc0 }; + final VPackSlice slice = new VPackSlice(vpack); + assertThat(slice.getAsDouble(), is(-133.7)); + } + } + + @Test + public void getDoubleAsNumber() throws VPackException { + { + final byte[] vpack = { 0x1b, 0x66, 0x66, 0x66, 0x66, 0x66, (byte) 0xb6, 0x60, 0x40 }; + final VPackSlice slice = new VPackSlice(vpack); + assertThat(slice.getAsNumber().doubleValue(), is(133.7)); + } + { + final byte[] vpack = { 0x1b, 0x66, 0x66, 0x66, 0x66, 0x66, (byte) 0xb6, 0x60, (byte) 0xc0 }; + final VPackSlice slice = new VPackSlice(vpack); + assertThat(slice.getAsNumber().doubleValue(), is(-133.7)); + } + } + + @Test(expected = VPackValueTypeException.class) + public void getDoubleFail() { + final VPackSlice slice = new VPackSlice(new byte[] { 0x00 }); + slice.getAsDouble(); + } + + @Test(expected = VPackValueTypeException.class) + public void getNumberFail() { + final VPackSlice slice = new VPackSlice(new byte[] { 0x00 }); + slice.getAsNumber(); + } + + @Test + public void getSmallInt() throws VPackException { + checkSmallInt(0, new byte[] { 0x30 }); + checkSmallInt(1, new byte[] { 0x31 }); + checkSmallInt(2, new byte[] { 0x32 }); + checkSmallInt(3, new byte[] { 0x33 }); + checkSmallInt(4, new byte[] { 0x34 }); + checkSmallInt(5, new byte[] { 0x35 }); + checkSmallInt(6, new byte[] { 0x36 }); + checkSmallInt(7, new byte[] { 0x37 }); + checkSmallInt(8, new byte[] { 0x38 }); + checkSmallInt(9, new byte[] { 0x39 }); + checkSmallInt(-6, new byte[] { 0x3a }); + checkSmallInt(-5, new byte[] { 0x3b }); + checkSmallInt(-4, new byte[] { 0x3c }); + checkSmallInt(-3, new byte[] { 0x3d }); + checkSmallInt(-2, new byte[] { 0x3e }); + checkSmallInt(-1, new byte[] { 0x3f }); + } + + private void checkSmallInt(final int expecteds, final byte[] vpack) throws VPackException { + final VPackSlice slice = new VPackSlice(vpack); + assertThat(slice.getAsInt(), is(expecteds)); + } + + @Test + public void getInt() throws VPackException { + checkInt(Short.MAX_VALUE, new byte[] { 0x29, (byte) 0xff, 0x7f }); + checkInt(Integer.MAX_VALUE, new byte[] { 0x2b, (byte) 0xff, (byte) 0xff, (byte) 0xff, 0x7f }); + checkInt(Long.MAX_VALUE, new byte[] { 0x27, -1, -1, -1, -1, -1, -1, -1, 127 }); + } + + private void checkInt(final long expextedValue, final byte[] vpack) throws VPackException { + final VPackSlice slice = new VPackSlice(vpack); + assertThat(slice.getAsLong(), is(expextedValue)); + } + + @Test + public void getUInt() throws VPackException { + checkUInt(Short.MAX_VALUE, new byte[] { 0x29, -1, 127 }); + checkUInt(Integer.MAX_VALUE, new byte[] { 0x2b, -1, -1, -1, 127 }); + checkUInt(Long.MAX_VALUE, new byte[] { 0x2f, -1, -1, -1, -1, -1, -1, -1, 127 }); + } + + @Test + public void getUIntAsBigInteger() throws VPackException { + checkUIntAsBigInteger(new BigInteger(String.valueOf(Short.MAX_VALUE)), new byte[] { 0x29, -1, 127 }); + checkUIntAsBigInteger(new BigInteger(String.valueOf(Integer.MAX_VALUE)), new byte[] { 0x2b, -1, -1, -1, 127 }); + final BigInteger longMax = new BigInteger(String.valueOf(Long.MAX_VALUE)); + checkUIntAsBigInteger(longMax, new byte[] { 0x2f, -1, -1, -1, -1, -1, -1, -1, 127 }); + checkUIntAsBigInteger(longMax.add(longMax), new byte[] { 0x2f, -2, -1, -1, -1, -1, -1, -1, -1 }); + } + + private void checkUInt(final long expecteds, final byte[] vpack) throws VPackException { + final VPackSlice slice = new VPackSlice(vpack); + assertThat(slice.getAsLong(), is(expecteds)); + } + + private void checkUIntAsBigInteger(final BigInteger expecteds, final byte[] vpack) throws VPackException { + final VPackSlice slice = new VPackSlice(vpack); + assertThat(slice.getAsBigInteger(), is(expecteds)); + } + + @Test(expected = VPackValueTypeException.class) + public void getBigIntegerFail() { + final VPackSlice slice = new VPackSlice(new byte[] { 0x00 }); + slice.getAsBigInteger(); + } + + @Test + public void getDate() throws VPackException { + final byte[] vpack = { 0x1c, 0, 83, 115, 5, -114, 0, 0, 0, }; + final VPackSlice slice = new VPackSlice(vpack); + assertThat(slice.getAsDate(), is(new Date(609976800000l))); + } + + @Test(expected = VPackValueTypeException.class) + public void getDateFail() { + final VPackSlice slice = new VPackSlice(new byte[] { 0x00 }); + slice.getAsDate(); + } + + @Test + public void getString() throws VPackException { + checkString("Hallo Welt!", new byte[] { 0x4b, 72, 97, 108, 108, 111, 32, 87, 101, 108, 116, 33 }); + checkString("Hello World!", new byte[] { 0x4c, 72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33 }); + checkString( + "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus.", + new byte[] { (byte) 0xbf, 0x37, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x4c, 0x6f, 0x72, 0x65, 0x6d, + 0x20, 0x69, 0x70, 0x73, 0x75, 0x6d, 0x20, 0x64, 0x6f, 0x6c, 0x6f, 0x72, 0x20, 0x73, 0x69, 0x74, + 0x20, 0x61, 0x6d, 0x65, 0x74, 0x2c, 0x20, 0x63, 0x6f, 0x6e, 0x73, 0x65, 0x63, 0x74, 0x65, 0x74, + 0x75, 0x65, 0x72, 0x20, 0x61, 0x64, 0x69, 0x70, 0x69, 0x73, 0x63, 0x69, 0x6e, 0x67, 0x20, 0x65, + 0x6c, 0x69, 0x74, 0x2e, 0x20, 0x41, 0x65, 0x6e, 0x65, 0x61, 0x6e, 0x20, 0x63, 0x6f, 0x6d, 0x6d, + 0x6f, 0x64, 0x6f, 0x20, 0x6c, 0x69, 0x67, 0x75, 0x6c, 0x61, 0x20, 0x65, 0x67, 0x65, 0x74, 0x20, + 0x64, 0x6f, 0x6c, 0x6f, 0x72, 0x2e, 0x20, 0x41, 0x65, 0x6e, 0x65, 0x61, 0x6e, 0x20, 0x6d, 0x61, + 0x73, 0x73, 0x61, 0x2e, 0x20, 0x43, 0x75, 0x6d, 0x20, 0x73, 0x6f, 0x63, 0x69, 0x69, 0x73, 0x20, + 0x6e, 0x61, 0x74, 0x6f, 0x71, 0x75, 0x65, 0x20, 0x70, 0x65, 0x6e, 0x61, 0x74, 0x69, 0x62, 0x75, + 0x73, 0x20, 0x65, 0x74, 0x20, 0x6d, 0x61, 0x67, 0x6e, 0x69, 0x73, 0x20, 0x64, 0x69, 0x73, 0x20, + 0x70, 0x61, 0x72, 0x74, 0x75, 0x72, 0x69, 0x65, 0x6e, 0x74, 0x20, 0x6d, 0x6f, 0x6e, 0x74, 0x65, + 0x73, 0x2c, 0x20, 0x6e, 0x61, 0x73, 0x63, 0x65, 0x74, 0x75, 0x72, 0x20, 0x72, 0x69, 0x64, 0x69, + 0x63, 0x75, 0x6c, 0x75, 0x73, 0x20, 0x6d, 0x75, 0x73, 0x2e, 0x20, 0x44, 0x6f, 0x6e, 0x65, 0x63, + 0x20, 0x71, 0x75, 0x61, 0x6d, 0x20, 0x66, 0x65, 0x6c, 0x69, 0x73, 0x2c, 0x20, 0x75, 0x6c, 0x74, + 0x72, 0x69, 0x63, 0x69, 0x65, 0x73, 0x20, 0x6e, 0x65, 0x63, 0x2c, 0x20, 0x70, 0x65, 0x6c, 0x6c, + 0x65, 0x6e, 0x74, 0x65, 0x73, 0x71, 0x75, 0x65, 0x20, 0x65, 0x75, 0x2c, 0x20, 0x70, 0x72, 0x65, + 0x74, 0x69, 0x75, 0x6d, 0x20, 0x71, 0x75, 0x69, 0x73, 0x2c, 0x20, 0x73, 0x65, 0x6d, 0x2e, 0x20, + 0x4e, 0x75, 0x6c, 0x6c, 0x61, 0x20, 0x63, 0x6f, 0x6e, 0x73, 0x65, 0x71, 0x75, 0x61, 0x74, 0x20, + 0x6d, 0x61, 0x73, 0x73, 0x61, 0x20, 0x71, 0x75, 0x69, 0x73, 0x20, 0x65, 0x6e, 0x69, 0x6d, 0x2e, + 0x20, 0x44, 0x6f, 0x6e, 0x65, 0x63, 0x20, 0x70, 0x65, 0x64, 0x65, 0x20, 0x6a, 0x75, 0x73, 0x74, + 0x6f, 0x2c, 0x20, 0x66, 0x72, 0x69, 0x6e, 0x67, 0x69, 0x6c, 0x6c, 0x61, 0x20, 0x76, 0x65, 0x6c, + 0x2c, 0x20, 0x61, 0x6c, 0x69, 0x71, 0x75, 0x65, 0x74, 0x20, 0x6e, 0x65, 0x63, 0x2c, 0x20, 0x76, + 0x75, 0x6c, 0x70, 0x75, 0x74, 0x61, 0x74, 0x65, 0x20, 0x65, 0x67, 0x65, 0x74, 0x2c, 0x20, 0x61, + 0x72, 0x63, 0x75, 0x2e, 0x20, 0x49, 0x6e, 0x20, 0x65, 0x6e, 0x69, 0x6d, 0x20, 0x6a, 0x75, 0x73, + 0x74, 0x6f, 0x2c, 0x20, 0x72, 0x68, 0x6f, 0x6e, 0x63, 0x75, 0x73, 0x20, 0x75, 0x74, 0x2c, 0x20, + 0x69, 0x6d, 0x70, 0x65, 0x72, 0x64, 0x69, 0x65, 0x74, 0x20, 0x61, 0x2c, 0x20, 0x76, 0x65, 0x6e, + 0x65, 0x6e, 0x61, 0x74, 0x69, 0x73, 0x20, 0x76, 0x69, 0x74, 0x61, 0x65, 0x2c, 0x20, 0x6a, 0x75, + 0x73, 0x74, 0x6f, 0x2e, 0x20, 0x4e, 0x75, 0x6c, 0x6c, 0x61, 0x6d, 0x20, 0x64, 0x69, 0x63, 0x74, + 0x75, 0x6d, 0x20, 0x66, 0x65, 0x6c, 0x69, 0x73, 0x20, 0x65, 0x75, 0x20, 0x70, 0x65, 0x64, 0x65, + 0x20, 0x6d, 0x6f, 0x6c, 0x6c, 0x69, 0x73, 0x20, 0x70, 0x72, 0x65, 0x74, 0x69, 0x75, 0x6d, 0x2e, + 0x20, 0x49, 0x6e, 0x74, 0x65, 0x67, 0x65, 0x72, 0x20, 0x74, 0x69, 0x6e, 0x63, 0x69, 0x64, 0x75, + 0x6e, 0x74, 0x2e, 0x20, 0x43, 0x72, 0x61, 0x73, 0x20, 0x64, 0x61, 0x70, 0x69, 0x62, 0x75, 0x73, + 0x2e, 0x20, 0x56, 0x69, 0x76, 0x61, 0x6d, 0x75, 0x73, 0x20, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x6e, + 0x74, 0x75, 0x6d, 0x20, 0x73, 0x65, 0x6d, 0x70, 0x65, 0x72, 0x20, 0x6e, 0x69, 0x73, 0x69, 0x2e, + 0x20, 0x41, 0x65, 0x6e, 0x65, 0x61, 0x6e, 0x20, 0x76, 0x75, 0x6c, 0x70, 0x75, 0x74, 0x61, 0x74, + 0x65, 0x20, 0x65, 0x6c, 0x65, 0x69, 0x66, 0x65, 0x6e, 0x64, 0x20, 0x74, 0x65, 0x6c, 0x6c, 0x75, + 0x73, 0x2e }); + } + + private void checkString(final String expecteds, final byte[] vpack) throws VPackException { + final VPackSlice slice = new VPackSlice(vpack); + assertThat(slice.getAsString(), is(expecteds)); + } + + @Test + public void getStringLength() throws VPackException { + checkStringLength(11, new byte[] { 0x4b, 72, 97, 108, 108, 111, 32, 87, 101, 108, 116, 33 }); + checkStringLength(12, new byte[] { 0x4c, 72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33 }); + checkStringLength(567, new byte[] { (byte) 0xbf, 0x37, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x4c, 0x6f, + 0x72, 0x65, 0x6d, 0x20, 0x69, 0x70, 0x73, 0x75, 0x6d, 0x20, 0x64, 0x6f, 0x6c, 0x6f, 0x72, 0x20, 0x73, + 0x69, 0x74, 0x20, 0x61, 0x6d, 0x65, 0x74, 0x2c, 0x20, 0x63, 0x6f, 0x6e, 0x73, 0x65, 0x63, 0x74, 0x65, + 0x74, 0x75, 0x65, 0x72, 0x20, 0x61, 0x64, 0x69, 0x70, 0x69, 0x73, 0x63, 0x69, 0x6e, 0x67, 0x20, 0x65, + 0x6c, 0x69, 0x74, 0x2e, 0x20, 0x41, 0x65, 0x6e, 0x65, 0x61, 0x6e, 0x20, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, + 0x64, 0x6f, 0x20, 0x6c, 0x69, 0x67, 0x75, 0x6c, 0x61, 0x20, 0x65, 0x67, 0x65, 0x74, 0x20, 0x64, 0x6f, + 0x6c, 0x6f, 0x72, 0x2e, 0x20, 0x41, 0x65, 0x6e, 0x65, 0x61, 0x6e, 0x20, 0x6d, 0x61, 0x73, 0x73, 0x61, + 0x2e, 0x20, 0x43, 0x75, 0x6d, 0x20, 0x73, 0x6f, 0x63, 0x69, 0x69, 0x73, 0x20, 0x6e, 0x61, 0x74, 0x6f, + 0x71, 0x75, 0x65, 0x20, 0x70, 0x65, 0x6e, 0x61, 0x74, 0x69, 0x62, 0x75, 0x73, 0x20, 0x65, 0x74, 0x20, + 0x6d, 0x61, 0x67, 0x6e, 0x69, 0x73, 0x20, 0x64, 0x69, 0x73, 0x20, 0x70, 0x61, 0x72, 0x74, 0x75, 0x72, + 0x69, 0x65, 0x6e, 0x74, 0x20, 0x6d, 0x6f, 0x6e, 0x74, 0x65, 0x73, 0x2c, 0x20, 0x6e, 0x61, 0x73, 0x63, + 0x65, 0x74, 0x75, 0x72, 0x20, 0x72, 0x69, 0x64, 0x69, 0x63, 0x75, 0x6c, 0x75, 0x73, 0x20, 0x6d, 0x75, + 0x73, 0x2e, 0x20, 0x44, 0x6f, 0x6e, 0x65, 0x63, 0x20, 0x71, 0x75, 0x61, 0x6d, 0x20, 0x66, 0x65, 0x6c, + 0x69, 0x73, 0x2c, 0x20, 0x75, 0x6c, 0x74, 0x72, 0x69, 0x63, 0x69, 0x65, 0x73, 0x20, 0x6e, 0x65, 0x63, + 0x2c, 0x20, 0x70, 0x65, 0x6c, 0x6c, 0x65, 0x6e, 0x74, 0x65, 0x73, 0x71, 0x75, 0x65, 0x20, 0x65, 0x75, + 0x2c, 0x20, 0x70, 0x72, 0x65, 0x74, 0x69, 0x75, 0x6d, 0x20, 0x71, 0x75, 0x69, 0x73, 0x2c, 0x20, 0x73, + 0x65, 0x6d, 0x2e, 0x20, 0x4e, 0x75, 0x6c, 0x6c, 0x61, 0x20, 0x63, 0x6f, 0x6e, 0x73, 0x65, 0x71, 0x75, + 0x61, 0x74, 0x20, 0x6d, 0x61, 0x73, 0x73, 0x61, 0x20, 0x71, 0x75, 0x69, 0x73, 0x20, 0x65, 0x6e, 0x69, + 0x6d, 0x2e, 0x20, 0x44, 0x6f, 0x6e, 0x65, 0x63, 0x20, 0x70, 0x65, 0x64, 0x65, 0x20, 0x6a, 0x75, 0x73, + 0x74, 0x6f, 0x2c, 0x20, 0x66, 0x72, 0x69, 0x6e, 0x67, 0x69, 0x6c, 0x6c, 0x61, 0x20, 0x76, 0x65, 0x6c, + 0x2c, 0x20, 0x61, 0x6c, 0x69, 0x71, 0x75, 0x65, 0x74, 0x20, 0x6e, 0x65, 0x63, 0x2c, 0x20, 0x76, 0x75, + 0x6c, 0x70, 0x75, 0x74, 0x61, 0x74, 0x65, 0x20, 0x65, 0x67, 0x65, 0x74, 0x2c, 0x20, 0x61, 0x72, 0x63, + 0x75, 0x2e, 0x20, 0x49, 0x6e, 0x20, 0x65, 0x6e, 0x69, 0x6d, 0x20, 0x6a, 0x75, 0x73, 0x74, 0x6f, 0x2c, + 0x20, 0x72, 0x68, 0x6f, 0x6e, 0x63, 0x75, 0x73, 0x20, 0x75, 0x74, 0x2c, 0x20, 0x69, 0x6d, 0x70, 0x65, + 0x72, 0x64, 0x69, 0x65, 0x74, 0x20, 0x61, 0x2c, 0x20, 0x76, 0x65, 0x6e, 0x65, 0x6e, 0x61, 0x74, 0x69, + 0x73, 0x20, 0x76, 0x69, 0x74, 0x61, 0x65, 0x2c, 0x20, 0x6a, 0x75, 0x73, 0x74, 0x6f, 0x2e, 0x20, 0x4e, + 0x75, 0x6c, 0x6c, 0x61, 0x6d, 0x20, 0x64, 0x69, 0x63, 0x74, 0x75, 0x6d, 0x20, 0x66, 0x65, 0x6c, 0x69, + 0x73, 0x20, 0x65, 0x75, 0x20, 0x70, 0x65, 0x64, 0x65, 0x20, 0x6d, 0x6f, 0x6c, 0x6c, 0x69, 0x73, 0x20, + 0x70, 0x72, 0x65, 0x74, 0x69, 0x75, 0x6d, 0x2e, 0x20, 0x49, 0x6e, 0x74, 0x65, 0x67, 0x65, 0x72, 0x20, + 0x74, 0x69, 0x6e, 0x63, 0x69, 0x64, 0x75, 0x6e, 0x74, 0x2e, 0x20, 0x43, 0x72, 0x61, 0x73, 0x20, 0x64, + 0x61, 0x70, 0x69, 0x62, 0x75, 0x73, 0x2e, 0x20, 0x56, 0x69, 0x76, 0x61, 0x6d, 0x75, 0x73, 0x20, 0x65, + 0x6c, 0x65, 0x6d, 0x65, 0x6e, 0x74, 0x75, 0x6d, 0x20, 0x73, 0x65, 0x6d, 0x70, 0x65, 0x72, 0x20, 0x6e, + 0x69, 0x73, 0x69, 0x2e, 0x20, 0x41, 0x65, 0x6e, 0x65, 0x61, 0x6e, 0x20, 0x76, 0x75, 0x6c, 0x70, 0x75, + 0x74, 0x61, 0x74, 0x65, 0x20, 0x65, 0x6c, 0x65, 0x69, 0x66, 0x65, 0x6e, 0x64, 0x20, 0x74, 0x65, 0x6c, + 0x6c, 0x75, 0x73, 0x2e }); + } + + private void checkStringLength(final int expected, final byte[] vpack) throws VPackException { + final VPackSlice slice = new VPackSlice(vpack); + assertThat(slice.getLength(), is(expected)); + assertThat(slice.getByteSize(), is(vpack.length)); + } + + @Test(expected = VPackValueTypeException.class) + public void getStringFail() { + final VPackSlice slice = new VPackSlice(new byte[] { 0x00 }); + slice.getAsString(); + } + + @Test + public void getBinary() throws VPackException { + final byte[] expected = new byte[] { 49, 50, 51, 52, 53, 54, 55, 56, 57 }; + checkBinary(expected, new byte[] { (byte) 0xc0, 9, 49, 50, 51, 52, 53, 54, 55, 56, 57 }); + checkBinary(expected, new byte[] { (byte) 0xc1, 9, 0, 49, 50, 51, 52, 53, 54, 55, 56, 57 }); + checkBinary(expected, new byte[] { (byte) 0xc2, 9, 0, 0, 49, 50, 51, 52, 53, 54, 55, 56, 57 }); + checkBinary(expected, new byte[] { (byte) 0xc3, 9, 0, 0, 0, 49, 50, 51, 52, 53, 54, 55, 56, 57 }); + checkBinary(expected, new byte[] { (byte) 0xc4, 9, 0, 0, 0, 0, 49, 50, 51, 52, 53, 54, 55, 56, 57 }); + checkBinary(expected, new byte[] { (byte) 0xc5, 9, 0, 0, 0, 0, 0, 49, 50, 51, 52, 53, 54, 55, 56, 57 }); + checkBinary(expected, new byte[] { (byte) 0xc6, 9, 0, 0, 0, 0, 0, 0, 49, 50, 51, 52, 53, 54, 55, 56, 57 }); + checkBinary(expected, new byte[] { (byte) 0xc7, 9, 0, 0, 0, 0, 0, 0, 0, 49, 50, 51, 52, 53, 54, 55, 56, 57 }); + } + + private void checkBinary(final byte[] expected, final byte[] vpack) throws VPackException { + final VPackSlice slice = new VPackSlice(vpack); + assertThat(slice.getAsBinary(), is(expected)); + assertThat(slice.getByteSize(), is(vpack.length)); + } + + @Test + public void getBinaryLength() throws VPackException { + final int expected = 9; + checkBinary(expected, new byte[] { (byte) 0xc0, 9, 49, 50, 51, 52, 53, 54, 55, 56, 57 }); + checkBinary(expected, new byte[] { (byte) 0xc1, 9, 0, 49, 50, 51, 52, 53, 54, 55, 56, 57 }); + checkBinary(expected, new byte[] { (byte) 0xc2, 9, 0, 0, 49, 50, 51, 52, 53, 54, 55, 56, 57 }); + checkBinary(expected, new byte[] { (byte) 0xc3, 9, 0, 0, 0, 49, 50, 51, 52, 53, 54, 55, 56, 57 }); + checkBinary(expected, new byte[] { (byte) 0xc4, 9, 0, 0, 0, 0, 49, 50, 51, 52, 53, 54, 55, 56, 57 }); + checkBinary(expected, new byte[] { (byte) 0xc5, 9, 0, 0, 0, 0, 0, 49, 50, 51, 52, 53, 54, 55, 56, 57 }); + checkBinary(expected, new byte[] { (byte) 0xc6, 9, 0, 0, 0, 0, 0, 0, 49, 50, 51, 52, 53, 54, 55, 56, 57 }); + checkBinary(expected, new byte[] { (byte) 0xc7, 9, 0, 0, 0, 0, 0, 0, 0, 49, 50, 51, 52, 53, 54, 55, 56, 57 }); + } + + private void checkBinary(final int expected, final byte[] vpack) throws VPackException { + final VPackSlice slice = new VPackSlice(vpack); + assertThat(slice.getBinaryLength(), is(expected)); + assertThat(slice.getByteSize(), is(vpack.length)); + } + + @Test(expected = VPackValueTypeException.class) + public void getBinaryFail() { + final VPackSlice slice = new VPackSlice(new byte[] { 0x00 }); + slice.getAsBinary(); + } + + @Test(expected = VPackValueTypeException.class) + public void getBinaryLengthFail() { + final VPackSlice slice = new VPackSlice(new byte[] { 0x00 }); + slice.getBinaryLength(); + } + + @Test(expected = VPackValueTypeException.class) + public void notArrayAt() throws VPackException { + final VPackSlice slice = new VPackSlice(new byte[] { 0x1a }); + slice.get(1); + } + + @Test + public void arrayEmpty() throws VPackException { + checkArray(new long[] {}, new byte[] { 0x01 }); + } + + @Test(expected = IndexOutOfBoundsException.class) + public void arrayEmptyAt() throws VPackException { + final VPackSlice slice = new VPackSlice(new byte[] { 0x01 }); + slice.get(1); + } + + @Test(expected = IndexOutOfBoundsException.class) + public void arrayWrongIndex() throws VPackException { + // [1, 2 ,3] + final VPackSlice slice = new VPackSlice(new byte[] { 0x02, 0x05, 0x31, 0x32, 0x33 }); + slice.get(4); + } + + @Test + public void arrayWithoutIndexTable() throws VPackException { + final long[] expected = new long[] { 1, 2, 3 }; + checkArray(expected, new byte[] { 0x02, 0x05, 0x31, 0x32, 0x33 }); + checkArray(expected, new byte[] { 0x03, 0x06, 0x00, 0x31, 0x32, 0x33 }); + checkArray(expected, new byte[] { 0x04, 0x08, 0x00, 0x00, 0x00, 0x31, 0x32, 0x33 }); + checkArray(expected, new byte[] { 0x05, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x31, 0x32, 0x33 }); + } + + @Test + public void arrayWithIndexTable() throws VPackException { + final long[] expected = new long[] { 1, 2, 3 }; + checkArray(expected, new byte[] { 0x06, 0x09, 0x03, 0x31, 0x32, 0x33, 0x03, 0x04, 0x05 }); + checkArray(expected, + new byte[] { 0x07, 0x0e, 0x00, 0x03, 0x00, 0x31, 0x32, 0x33, 0x05, 0x00, 0x06, 0x00, 0x07, 0x00 }); + checkArray(expected, new byte[] { 0x08, 0x18, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x31, 0x32, 0x33, 0x09, + 0x00, 0x00, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x00, 0x00 }); + } + + @Test + public void arrayWithIndexTable8bytes() throws VPackException { + final long[] expected = new long[] { 1, 2, 3 }; + checkArray(expected, + new byte[] { 0x09, 0x2c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x31, 0x32, 0x33, 0x09, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }); + } + + @Test + public void arrayCompact() throws VPackException { + final long[] expected = { 1, 16 }; + checkArray(expected, new byte[] { 0x13, 0x06, 0x31, 0x28, 0x10, 0x02 }); + } + + @Test(expected = IndexOutOfBoundsException.class) + public void arrayCompactWrongIndex() throws VPackException { + // [1, 16] + final VPackSlice slice = new VPackSlice(new byte[] { 0x13, 0x06, 0x31, 0x28, 0x10, 0x02 }); + slice.get(3); + } + + @Test + public void arrayIncludesArray() throws VPackException { + final long[][] expected = { { 1, 2, 3 }, { 1, 2, 3 } }; + checkArray(expected, new byte[] { 0x02, 0x0c, 0x02, 0x05, 0x31, 0x32, 0x33, 0x02, 0x05, 0x31, 0x32, 0x33 }); + } + + @Test + public void arrayIncludesArrayCompact() throws VPackException { + final long[][] expected = { { 1, 2, 3 }, { 1, 2, 3 } }; + checkArray(expected, + new byte[] { 0x02, 0x0e, 0x13, 0x06, 0x31, 0x32, 0x33, 0x03, 0x13, 0x06, 0x31, 0x32, 0x33, 0x03 }); + } + + @Test + public void arrayIncludesObject() throws VPackException { + // [{"a": 12, "b": true, "c": "xyz"},{"a": 12, "b": true, "c": "xyz"}] + checkLength(2, + new byte[] { 0x13, 0x23, 0x14, 0x10, 0x41, 0x61, 0x28, 0x0c, 0x41, 0x62, 0x1a, 0x41, 0x63, 0x43, 0x78, 0x79, + 0x7a, 0x03, 0x14, 0x10, 0x41, 0x61, 0x28, 0x0c, 0x41, 0x62, 0x1a, 0x41, 0x63, 0x43, 0x78, 0x79, + 0x7a, 0x03, 0x02 }); + } + + @Test + public void arrayIncludesLongString() throws VPackException { + checkLength(1, new byte[] { 0x03, 0x49, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, (byte) 0xbf, 0x37, 0x02, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x4c, 0x6f, 0x72, 0x65, 0x6d, 0x20, 0x69, 0x70, 0x73, 0x75, 0x6d, 0x20, + 0x64, 0x6f, 0x6c, 0x6f, 0x72, 0x20, 0x73, 0x69, 0x74, 0x20, 0x61, 0x6d, 0x65, 0x74, 0x2c, 0x20, 0x63, + 0x6f, 0x6e, 0x73, 0x65, 0x63, 0x74, 0x65, 0x74, 0x75, 0x65, 0x72, 0x20, 0x61, 0x64, 0x69, 0x70, 0x69, + 0x73, 0x63, 0x69, 0x6e, 0x67, 0x20, 0x65, 0x6c, 0x69, 0x74, 0x2e, 0x20, 0x41, 0x65, 0x6e, 0x65, 0x61, + 0x6e, 0x20, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x64, 0x6f, 0x20, 0x6c, 0x69, 0x67, 0x75, 0x6c, 0x61, 0x20, + 0x65, 0x67, 0x65, 0x74, 0x20, 0x64, 0x6f, 0x6c, 0x6f, 0x72, 0x2e, 0x20, 0x41, 0x65, 0x6e, 0x65, 0x61, + 0x6e, 0x20, 0x6d, 0x61, 0x73, 0x73, 0x61, 0x2e, 0x20, 0x43, 0x75, 0x6d, 0x20, 0x73, 0x6f, 0x63, 0x69, + 0x69, 0x73, 0x20, 0x6e, 0x61, 0x74, 0x6f, 0x71, 0x75, 0x65, 0x20, 0x70, 0x65, 0x6e, 0x61, 0x74, 0x69, + 0x62, 0x75, 0x73, 0x20, 0x65, 0x74, 0x20, 0x6d, 0x61, 0x67, 0x6e, 0x69, 0x73, 0x20, 0x64, 0x69, 0x73, + 0x20, 0x70, 0x61, 0x72, 0x74, 0x75, 0x72, 0x69, 0x65, 0x6e, 0x74, 0x20, 0x6d, 0x6f, 0x6e, 0x74, 0x65, + 0x73, 0x2c, 0x20, 0x6e, 0x61, 0x73, 0x63, 0x65, 0x74, 0x75, 0x72, 0x20, 0x72, 0x69, 0x64, 0x69, 0x63, + 0x75, 0x6c, 0x75, 0x73, 0x20, 0x6d, 0x75, 0x73, 0x2e, 0x20, 0x44, 0x6f, 0x6e, 0x65, 0x63, 0x20, 0x71, + 0x75, 0x61, 0x6d, 0x20, 0x66, 0x65, 0x6c, 0x69, 0x73, 0x2c, 0x20, 0x75, 0x6c, 0x74, 0x72, 0x69, 0x63, + 0x69, 0x65, 0x73, 0x20, 0x6e, 0x65, 0x63, 0x2c, 0x20, 0x70, 0x65, 0x6c, 0x6c, 0x65, 0x6e, 0x74, 0x65, + 0x73, 0x71, 0x75, 0x65, 0x20, 0x65, 0x75, 0x2c, 0x20, 0x70, 0x72, 0x65, 0x74, 0x69, 0x75, 0x6d, 0x20, + 0x71, 0x75, 0x69, 0x73, 0x2c, 0x20, 0x73, 0x65, 0x6d, 0x2e, 0x20, 0x4e, 0x75, 0x6c, 0x6c, 0x61, 0x20, + 0x63, 0x6f, 0x6e, 0x73, 0x65, 0x71, 0x75, 0x61, 0x74, 0x20, 0x6d, 0x61, 0x73, 0x73, 0x61, 0x20, 0x71, + 0x75, 0x69, 0x73, 0x20, 0x65, 0x6e, 0x69, 0x6d, 0x2e, 0x20, 0x44, 0x6f, 0x6e, 0x65, 0x63, 0x20, 0x70, + 0x65, 0x64, 0x65, 0x20, 0x6a, 0x75, 0x73, 0x74, 0x6f, 0x2c, 0x20, 0x66, 0x72, 0x69, 0x6e, 0x67, 0x69, + 0x6c, 0x6c, 0x61, 0x20, 0x76, 0x65, 0x6c, 0x2c, 0x20, 0x61, 0x6c, 0x69, 0x71, 0x75, 0x65, 0x74, 0x20, + 0x6e, 0x65, 0x63, 0x2c, 0x20, 0x76, 0x75, 0x6c, 0x70, 0x75, 0x74, 0x61, 0x74, 0x65, 0x20, 0x65, 0x67, + 0x65, 0x74, 0x2c, 0x20, 0x61, 0x72, 0x63, 0x75, 0x2e, 0x20, 0x49, 0x6e, 0x20, 0x65, 0x6e, 0x69, 0x6d, + 0x20, 0x6a, 0x75, 0x73, 0x74, 0x6f, 0x2c, 0x20, 0x72, 0x68, 0x6f, 0x6e, 0x63, 0x75, 0x73, 0x20, 0x75, + 0x74, 0x2c, 0x20, 0x69, 0x6d, 0x70, 0x65, 0x72, 0x64, 0x69, 0x65, 0x74, 0x20, 0x61, 0x2c, 0x20, 0x76, + 0x65, 0x6e, 0x65, 0x6e, 0x61, 0x74, 0x69, 0x73, 0x20, 0x76, 0x69, 0x74, 0x61, 0x65, 0x2c, 0x20, 0x6a, + 0x75, 0x73, 0x74, 0x6f, 0x2e, 0x20, 0x4e, 0x75, 0x6c, 0x6c, 0x61, 0x6d, 0x20, 0x64, 0x69, 0x63, 0x74, + 0x75, 0x6d, 0x20, 0x66, 0x65, 0x6c, 0x69, 0x73, 0x20, 0x65, 0x75, 0x20, 0x70, 0x65, 0x64, 0x65, 0x20, + 0x6d, 0x6f, 0x6c, 0x6c, 0x69, 0x73, 0x20, 0x70, 0x72, 0x65, 0x74, 0x69, 0x75, 0x6d, 0x2e, 0x20, 0x49, + 0x6e, 0x74, 0x65, 0x67, 0x65, 0x72, 0x20, 0x74, 0x69, 0x6e, 0x63, 0x69, 0x64, 0x75, 0x6e, 0x74, 0x2e, + 0x20, 0x43, 0x72, 0x61, 0x73, 0x20, 0x64, 0x61, 0x70, 0x69, 0x62, 0x75, 0x73, 0x2e, 0x20, 0x56, 0x69, + 0x76, 0x61, 0x6d, 0x75, 0x73, 0x20, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x6e, 0x74, 0x75, 0x6d, 0x20, 0x73, + 0x65, 0x6d, 0x70, 0x65, 0x72, 0x20, 0x6e, 0x69, 0x73, 0x69, 0x2e, 0x20, 0x41, 0x65, 0x6e, 0x65, 0x61, + 0x6e, 0x20, 0x76, 0x75, 0x6c, 0x70, 0x75, 0x74, 0x61, 0x74, 0x65, 0x20, 0x65, 0x6c, 0x65, 0x69, 0x66, + 0x65, 0x6e, 0x64, 0x20, 0x74, 0x65, 0x6c, 0x6c, 0x75, 0x73, 0x2e }); + } + + private void checkArray(final long[][] expected, final byte[] vpack) throws VPackException { + checkLength(expected.length, vpack); + final VPackSlice slice = new VPackSlice(vpack); + for (int i = 0; i < expected.length; i++) { + final long[] childArray = expected[i]; + final VPackSlice at = slice.get(i); + assertThat(at.isArray(), is(true)); + assertThat(at.getLength(), is(childArray.length)); + for (int j = 0; j < childArray.length; j++) { + final VPackSlice atat = at.get(j); + assertThat(atat.isInteger(), is(true)); + assertThat(atat.getAsLong(), is(childArray[j])); + } + } + } + + private void checkArray(final long[] expected, final byte[] vpack) throws VPackException { + checkLength(expected.length, vpack); + final VPackSlice slice = new VPackSlice(vpack); + for (int i = 0; i < expected.length; i++) { + final VPackSlice at = slice.get(i); + assertThat(at.isInteger(), is(true)); + assertThat(at.getAsLong(), is(expected[i])); + } + } + + @Test + public void arrayIterator() throws VPackException { + final Collection expected = Arrays.asList("a", "b", "c", "d", "e", "f"); + final VPackSlice slice = new VPackSlice(new byte[] { 0x13, 0x0f, 0x41, 0x61, 0x41, 0x62, 0x41, 0x63, 0x41, 0x64, + 0x41, 0x65, 0x41, 0x66, 0x06 }); + final Iterator iteratorSlice = slice.arrayIterator(); + for (final Iterator iterator = expected.iterator(); iterator.hasNext();) { + final String string = iterator.next(); + final VPackSlice next = iteratorSlice.next(); + assertThat(next.isString(), is(true)); + assertThat(next.getAsString(), is(string)); + } + } + + @Test + public void objectIterator() throws VPackException { + // {"a":"test","b":"test","c":"test"} + final String[] fields = new String[] { "a", "b", "c" }; + final VPackSlice slice = new VPackSlice(new byte[] { 0x0b, 0x1b, 0x03, 0x41, 0x61, 0x44, 0x74, 0x65, 0x73, 0x74, + 0x41, 0x62, 0x44, 0x74, 0x65, 0x73, 0x74, 0x41, 0x63, 0x44, 0x74, 0x65, 0x73, 0x74, 0x03, 0x0a, 0x11 }); + int i = 0; + for (final Iterator> iterator = slice.objectIterator(); iterator.hasNext();) { + final Entry next = iterator.next(); + assertThat(next.getKey(), is(fields[i++])); + assertThat(next.getValue().getAsString(), is("test")); + } + } + + @Test(expected = VPackValueTypeException.class) + public void nonArrayIterator() { + final VPackSlice vpack = new VPackSlice(new byte[] { 0x1a }); + vpack.arrayIterator(); + } + + @Test(expected = VPackValueTypeException.class) + public void nonObjectIterator() { + final VPackSlice vpack = new VPackSlice(new byte[] { 0x1a }); + vpack.objectIterator(); + } + + @Test + public void objectEmpty() throws VPackException { + checkLength(0, new byte[] { 0x0a }); + } + + @Test + public void objectLength() throws VPackException { + // {"a": 12, "b": true, "c": "xyz"} + final int expected = 3; + checkLength(expected, new byte[] { 0x0b, 0x13, 0x03, 0x41, 0x62, 0x1a, 0x41, 0x61, 0x28, 0x0c, 0x41, 0x63, 0x43, + 0x78, 0x79, 0x7a, 0x06, 0x03, 0x0a }); + checkLength(expected, + new byte[] { 0x0d, 0x22, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x41, 0x62, 0x03, 0x41, 0x61, 0x28, 0x0c, + 0x41, 0x63, 0x43, 0x78, 0x79, 0x7a, 0x0c, 0x00, 0x00, 0x00, 0x09, 0x00, 0x00, 0x00, 0x10, 0x00, + 0x00, 0x00 }); + checkLength(expected, new byte[] { 0x0f, 0x13, 0x03, 0x41, 0x62, 0x03, 0x41, 0x61, 0x28, 0x0c, 0x41, 0x63, 0x43, + 0x78, 0x79, 0x7a, 0x03, 0x06, 0x0a }); + } + + @Test + public void objectCompactLength() throws VPackException { + // {"a":1, "b":16} + checkLength(2, new byte[] { 0x14, 0x0a, 0x41, 0x61, 0x31, 0x41, 0x62, 0x28, 0x10, 0x02 }); + } + + private void checkLength(final int expected, final byte[] vpack) throws VPackException { + final VPackSlice slice = new VPackSlice(vpack); + assertThat(slice.getLength(), is(expected)); + assertThat(slice.getByteSize(), is(vpack.length)); + } + + @Test + public void objectEmptyGet() throws VPackException { + final VPackSlice slice = new VPackSlice(new byte[] { 0x0a }); + final VPackSlice slice2 = slice.get("abc"); + assertThat(slice2.isNone(), is(true)); + } + + @Test + public void objectSingleEntryString() throws VPackException { + // {"a":"b"} + final VPackSlice slice = new VPackSlice(new byte[] { 0x0b, 0x07, 0x01, 0x41, 0x61, 0x41, 0x62 }); + final VPackSlice sliceNone = slice.get("abc"); + assertThat(sliceNone.isNone(), is(true)); + final VPackSlice sliceA = slice.get("a"); + assertThat(sliceA.isString(), is(true)); + } + + @Test + public void objectSorted4Entries() throws VPackException { + // {"a":"b","c":"d","e":"f","g":"h"} + final VPackSlice slice = new VPackSlice(new byte[] { 0x0b, 0x17, 0x04, 0x41, 0x61, 0x41, 0x62, 0x41, 0x63, 0x41, + 0x64, 0x41, 0x65, 0x41, 0x66, 0x41, 0x67, 0x41, 0x68, 0x03, 0x07, 0x0b, 0x0f }); + checkString("b", slice.get("a")); + checkString("d", slice.get("c")); + checkString("f", slice.get("e")); + checkString("h", slice.get("g")); + } + + @Test + public void objectSortedUnder4Entries() throws VPackException { + // {"a":"b","c":"d","e":"f"} + final VPackSlice slice = new VPackSlice(new byte[] { 0x0b, 0x12, 0x03, 0x41, 0x61, 0x41, 0x62, 0x41, 0x63, 0x41, + 0x64, 0x41, 0x65, 0x41, 0x66, 0x03, 0x07, 0x0b }); + checkString("b", slice.get("a")); + checkString("d", slice.get("c")); + checkString("f", slice.get("e")); + } + + @Test + public void objectCompact() throws VPackException { + // {"a":"b","c":"d","e":"f"} + final VPackSlice slice = new VPackSlice(new byte[] { 0x14, 0x0f, 0x41, 0x61, 0x41, 0x62, 0x41, 0x63, 0x41, 0x64, + 0x41, 0x65, 0x41, 0x66, 0x03 }); + checkString("b", slice.get("a")); + checkString("d", slice.get("c")); + checkString("f", slice.get("e")); + } + + private void checkString(final String expected, final VPackSlice slice) throws VPackException { + assertThat(slice.isString(), is(true)); + assertThat(slice.getAsString(), is(expected)); + } + + @Test + public void objectKeyValueAtIndex() throws VPackException { + // {"a":"b","c":"d","e":"f"} + final String[] keys = { "a", "c", "e" }; + final String[] values = { "b", "d", "f" }; + final VPackSlice slice = new VPackSlice(new byte[] { 0x14, 0x0f, 0x41, 0x61, 0x41, 0x62, 0x41, 0x63, 0x41, 0x64, + 0x41, 0x65, 0x41, 0x66, 0x03 }); + for (int i = 0; i < 3; i++) { + checkString(keys[i], slice.keyAt(i)); + checkString(values[i], slice.valueAt(i)); + } + } + + @Test + public void object1ByteOffset() throws VPackException { + /* + * {"0":{"0":"test","1":"test","2":"test","3":"test","4":"test"}, + * "1":{"0":"test","1":"test","2":"test","3":"test","4":"test"}, + * "2":{"0":"test","1":"test","2":"test","3":"test","4":"test"}, + * "3":{"0":"test","1":"test","2":"test","3":"test","4":"test"}, + * "4":{"0":"test","1":"test","2":"test","3":"test","4":"test"}} + */ + final VPackSlice slice = new VPackSlice(new byte[] { 0x0b, (byte) 0xe9, 0x05, 0x41, 0x30, 0x0b, 0x2b, 0x05, + 0x41, 0x30, 0x44, 0x74, 0x65, 0x73, 0x74, 0x41, 0x31, 0x44, 0x74, 0x65, 0x73, 0x74, 0x41, 0x32, 0x44, + 0x74, 0x65, 0x73, 0x74, 0x41, 0x33, 0x44, 0x74, 0x65, 0x73, 0x74, 0x41, 0x34, 0x44, 0x74, 0x65, 0x73, + 0x74, 0x03, 0x0a, 0x11, 0x18, 0x1f, 0x41, 0x31, 0x0b, 0x2b, 0x05, 0x41, 0x30, 0x44, 0x74, 0x65, 0x73, + 0x74, 0x41, 0x31, 0x44, 0x74, 0x65, 0x73, 0x74, 0x41, 0x32, 0x44, 0x74, 0x65, 0x73, 0x74, 0x41, 0x33, + 0x44, 0x74, 0x65, 0x73, 0x74, 0x41, 0x34, 0x44, 0x74, 0x65, 0x73, 0x74, 0x03, 0x0a, 0x11, 0x18, 0x1f, + 0x41, 0x32, 0x0b, 0x2b, 0x05, 0x41, 0x30, 0x44, 0x74, 0x65, 0x73, 0x74, 0x41, 0x31, 0x44, 0x74, 0x65, + 0x73, 0x74, 0x41, 0x32, 0x44, 0x74, 0x65, 0x73, 0x74, 0x41, 0x33, 0x44, 0x74, 0x65, 0x73, 0x74, 0x41, + 0x34, 0x44, 0x74, 0x65, 0x73, 0x74, 0x03, 0x0a, 0x11, 0x18, 0x1f, 0x41, 0x33, 0x0b, 0x2b, 0x05, 0x41, + 0x30, 0x44, 0x74, 0x65, 0x73, 0x74, 0x41, 0x31, 0x44, 0x74, 0x65, 0x73, 0x74, 0x41, 0x32, 0x44, 0x74, + 0x65, 0x73, 0x74, 0x41, 0x33, 0x44, 0x74, 0x65, 0x73, 0x74, 0x41, 0x34, 0x44, 0x74, 0x65, 0x73, 0x74, + 0x03, 0x0a, 0x11, 0x18, 0x1f, 0x41, 0x34, 0x0b, 0x2b, 0x05, 0x41, 0x30, 0x44, 0x74, 0x65, 0x73, 0x74, + 0x41, 0x31, 0x44, 0x74, 0x65, 0x73, 0x74, 0x41, 0x32, 0x44, 0x74, 0x65, 0x73, 0x74, 0x41, 0x33, 0x44, + 0x74, 0x65, 0x73, 0x74, 0x41, 0x34, 0x44, 0x74, 0x65, 0x73, 0x74, 0x03, 0x0a, 0x11, 0x18, 0x1f, 0x03, + 0x30, 0x5d, (byte) 0x8a, (byte) 0xb7 }); + final int size = 5; + assertThat(slice.isObject(), is(true)); + assertThat(slice.getLength(), is(size)); + for (int i = 0; i < size; i++) { + final VPackSlice attr = slice.get(String.valueOf(i)); + assertThat(attr.isObject(), is(true)); + assertThat(attr.getLength(), is(size)); + for (int j = 0; j < size; j++) { + final VPackSlice childAttr = attr.get(String.valueOf(j)); + assertThat(childAttr.isString(), is(true)); + } + } + } + + @Test + public void object2ByteOffset() throws VPackException { + /* + * {"0":{"0":"test","1":"test","2":"test","3":"test","4":"test","5": + * "test","6":"test","7":"test","8":"test","9":"test"}, + * "1":{"0":"test","1":"test","2":"test","3":"test","4":"test","5": + * "test","6":"test","7":"test","8":"test","9":"test"}, + * "2":{"0":"test","1":"test","2":"test","3":"test","4":"test","5": + * "test","6":"test","7":"test","8":"test","9":"test"}, + * "3":{"0":"test","1":"test","2":"test","3":"test","4":"test","5": + * "test","6":"test","7":"test","8":"test","9":"test"}, + * "4":{"0":"test","1":"test","2":"test","3":"test","4":"test","5": + * "test","6":"test","7":"test","8":"test","9":"test"}, + * "5":{"0":"test","1":"test","2":"test","3":"test","4":"test","5": + * "test","6":"test","7":"test","8":"test","9":"test"}, + * "6":{"0":"test","1":"test","2":"test","3":"test","4":"test","5": + * "test","6":"test","7":"test","8":"test","9":"test"}, + * "7":{"0":"test","1":"test","2":"test","3":"test","4":"test","5": + * "test","6":"test","7":"test","8":"test","9":"test"}, + * "8":{"0":"test","1":"test","2":"test","3":"test","4":"test","5": + * "test","6":"test","7":"test","8":"test","9":"test"}, + * "9":{"0":"test","1":"test","2":"test","3":"test","4":"test","5": + * "test","6":"test","7":"test","8":"test","9":"test"}} + */ + final VPackSlice slice = new VPackSlice(new byte[] { 0x0c, 0x6f, 0x03, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x41, + 0x30, 0x0b, 0x53, 0x0a, 0x41, 0x30, 0x44, 0x74, 0x65, 0x73, 0x74, 0x41, 0x31, 0x44, 0x74, 0x65, 0x73, + 0x74, 0x41, 0x32, 0x44, 0x74, 0x65, 0x73, 0x74, 0x41, 0x33, 0x44, 0x74, 0x65, 0x73, 0x74, 0x41, 0x34, + 0x44, 0x74, 0x65, 0x73, 0x74, 0x41, 0x35, 0x44, 0x74, 0x65, 0x73, 0x74, 0x41, 0x36, 0x44, 0x74, 0x65, + 0x73, 0x74, 0x41, 0x37, 0x44, 0x74, 0x65, 0x73, 0x74, 0x41, 0x38, 0x44, 0x74, 0x65, 0x73, 0x74, 0x41, + 0x39, 0x44, 0x74, 0x65, 0x73, 0x74, 0x03, 0x0a, 0x11, 0x18, 0x1f, 0x26, 0x2d, 0x34, 0x3b, 0x42, 0x41, + 0x31, 0x0b, 0x53, 0x0a, 0x41, 0x30, 0x44, 0x74, 0x65, 0x73, 0x74, 0x41, 0x31, 0x44, 0x74, 0x65, 0x73, + 0x74, 0x41, 0x32, 0x44, 0x74, 0x65, 0x73, 0x74, 0x41, 0x33, 0x44, 0x74, 0x65, 0x73, 0x74, 0x41, 0x34, + 0x44, 0x74, 0x65, 0x73, 0x74, 0x41, 0x35, 0x44, 0x74, 0x65, 0x73, 0x74, 0x41, 0x36, 0x44, 0x74, 0x65, + 0x73, 0x74, 0x41, 0x37, 0x44, 0x74, 0x65, 0x73, 0x74, 0x41, 0x38, 0x44, 0x74, 0x65, 0x73, 0x74, 0x41, + 0x39, 0x44, 0x74, 0x65, 0x73, 0x74, 0x03, 0x0a, 0x11, 0x18, 0x1f, 0x26, 0x2d, 0x34, 0x3b, 0x42, 0x41, + 0x32, 0x0b, 0x53, 0x0a, 0x41, 0x30, 0x44, 0x74, 0x65, 0x73, 0x74, 0x41, 0x31, 0x44, 0x74, 0x65, 0x73, + 0x74, 0x41, 0x32, 0x44, 0x74, 0x65, 0x73, 0x74, 0x41, 0x33, 0x44, 0x74, 0x65, 0x73, 0x74, 0x41, 0x34, + 0x44, 0x74, 0x65, 0x73, 0x74, 0x41, 0x35, 0x44, 0x74, 0x65, 0x73, 0x74, 0x41, 0x36, 0x44, 0x74, 0x65, + 0x73, 0x74, 0x41, 0x37, 0x44, 0x74, 0x65, 0x73, 0x74, 0x41, 0x38, 0x44, 0x74, 0x65, 0x73, 0x74, 0x41, + 0x39, 0x44, 0x74, 0x65, 0x73, 0x74, 0x03, 0x0a, 0x11, 0x18, 0x1f, 0x26, 0x2d, 0x34, 0x3b, 0x42, 0x41, + 0x33, 0x0b, 0x53, 0x0a, 0x41, 0x30, 0x44, 0x74, 0x65, 0x73, 0x74, 0x41, 0x31, 0x44, 0x74, 0x65, 0x73, + 0x74, 0x41, 0x32, 0x44, 0x74, 0x65, 0x73, 0x74, 0x41, 0x33, 0x44, 0x74, 0x65, 0x73, 0x74, 0x41, 0x34, + 0x44, 0x74, 0x65, 0x73, 0x74, 0x41, 0x35, 0x44, 0x74, 0x65, 0x73, 0x74, 0x41, 0x36, 0x44, 0x74, 0x65, + 0x73, 0x74, 0x41, 0x37, 0x44, 0x74, 0x65, 0x73, 0x74, 0x41, 0x38, 0x44, 0x74, 0x65, 0x73, 0x74, 0x41, + 0x39, 0x44, 0x74, 0x65, 0x73, 0x74, 0x03, 0x0a, 0x11, 0x18, 0x1f, 0x26, 0x2d, 0x34, 0x3b, 0x42, 0x41, + 0x34, 0x0b, 0x53, 0x0a, 0x41, 0x30, 0x44, 0x74, 0x65, 0x73, 0x74, 0x41, 0x31, 0x44, 0x74, 0x65, 0x73, + 0x74, 0x41, 0x32, 0x44, 0x74, 0x65, 0x73, 0x74, 0x41, 0x33, 0x44, 0x74, 0x65, 0x73, 0x74, 0x41, 0x34, + 0x44, 0x74, 0x65, 0x73, 0x74, 0x41, 0x35, 0x44, 0x74, 0x65, 0x73, 0x74, 0x41, 0x36, 0x44, 0x74, 0x65, + 0x73, 0x74, 0x41, 0x37, 0x44, 0x74, 0x65, 0x73, 0x74, 0x41, 0x38, 0x44, 0x74, 0x65, 0x73, 0x74, 0x41, + 0x39, 0x44, 0x74, 0x65, 0x73, 0x74, 0x03, 0x0a, 0x11, 0x18, 0x1f, 0x26, 0x2d, 0x34, 0x3b, 0x42, 0x41, + 0x35, 0x0b, 0x53, 0x0a, 0x41, 0x30, 0x44, 0x74, 0x65, 0x73, 0x74, 0x41, 0x31, 0x44, 0x74, 0x65, 0x73, + 0x74, 0x41, 0x32, 0x44, 0x74, 0x65, 0x73, 0x74, 0x41, 0x33, 0x44, 0x74, 0x65, 0x73, 0x74, 0x41, 0x34, + 0x44, 0x74, 0x65, 0x73, 0x74, 0x41, 0x35, 0x44, 0x74, 0x65, 0x73, 0x74, 0x41, 0x36, 0x44, 0x74, 0x65, + 0x73, 0x74, 0x41, 0x37, 0x44, 0x74, 0x65, 0x73, 0x74, 0x41, 0x38, 0x44, 0x74, 0x65, 0x73, 0x74, 0x41, + 0x39, 0x44, 0x74, 0x65, 0x73, 0x74, 0x03, 0x0a, 0x11, 0x18, 0x1f, 0x26, 0x2d, 0x34, 0x3b, 0x42, 0x41, + 0x36, 0x0b, 0x53, 0x0a, 0x41, 0x30, 0x44, 0x74, 0x65, 0x73, 0x74, 0x41, 0x31, 0x44, 0x74, 0x65, 0x73, + 0x74, 0x41, 0x32, 0x44, 0x74, 0x65, 0x73, 0x74, 0x41, 0x33, 0x44, 0x74, 0x65, 0x73, 0x74, 0x41, 0x34, + 0x44, 0x74, 0x65, 0x73, 0x74, 0x41, 0x35, 0x44, 0x74, 0x65, 0x73, 0x74, 0x41, 0x36, 0x44, 0x74, 0x65, + 0x73, 0x74, 0x41, 0x37, 0x44, 0x74, 0x65, 0x73, 0x74, 0x41, 0x38, 0x44, 0x74, 0x65, 0x73, 0x74, 0x41, + 0x39, 0x44, 0x74, 0x65, 0x73, 0x74, 0x03, 0x0a, 0x11, 0x18, 0x1f, 0x26, 0x2d, 0x34, 0x3b, 0x42, 0x41, + 0x37, 0x0b, 0x53, 0x0a, 0x41, 0x30, 0x44, 0x74, 0x65, 0x73, 0x74, 0x41, 0x31, 0x44, 0x74, 0x65, 0x73, + 0x74, 0x41, 0x32, 0x44, 0x74, 0x65, 0x73, 0x74, 0x41, 0x33, 0x44, 0x74, 0x65, 0x73, 0x74, 0x41, 0x34, + 0x44, 0x74, 0x65, 0x73, 0x74, 0x41, 0x35, 0x44, 0x74, 0x65, 0x73, 0x74, 0x41, 0x36, 0x44, 0x74, 0x65, + 0x73, 0x74, 0x41, 0x37, 0x44, 0x74, 0x65, 0x73, 0x74, 0x41, 0x38, 0x44, 0x74, 0x65, 0x73, 0x74, 0x41, + 0x39, 0x44, 0x74, 0x65, 0x73, 0x74, 0x03, 0x0a, 0x11, 0x18, 0x1f, 0x26, 0x2d, 0x34, 0x3b, 0x42, 0x41, + 0x38, 0x0b, 0x53, 0x0a, 0x41, 0x30, 0x44, 0x74, 0x65, 0x73, 0x74, 0x41, 0x31, 0x44, 0x74, 0x65, 0x73, + 0x74, 0x41, 0x32, 0x44, 0x74, 0x65, 0x73, 0x74, 0x41, 0x33, 0x44, 0x74, 0x65, 0x73, 0x74, 0x41, 0x34, + 0x44, 0x74, 0x65, 0x73, 0x74, 0x41, 0x35, 0x44, 0x74, 0x65, 0x73, 0x74, 0x41, 0x36, 0x44, 0x74, 0x65, + 0x73, 0x74, 0x41, 0x37, 0x44, 0x74, 0x65, 0x73, 0x74, 0x41, 0x38, 0x44, 0x74, 0x65, 0x73, 0x74, 0x41, + 0x39, 0x44, 0x74, 0x65, 0x73, 0x74, 0x03, 0x0a, 0x11, 0x18, 0x1f, 0x26, 0x2d, 0x34, 0x3b, 0x42, 0x41, + 0x39, 0x0b, 0x53, 0x0a, 0x41, 0x30, 0x44, 0x74, 0x65, 0x73, 0x74, 0x41, 0x31, 0x44, 0x74, 0x65, 0x73, + 0x74, 0x41, 0x32, 0x44, 0x74, 0x65, 0x73, 0x74, 0x41, 0x33, 0x44, 0x74, 0x65, 0x73, 0x74, 0x41, 0x34, + 0x44, 0x74, 0x65, 0x73, 0x74, 0x41, 0x35, 0x44, 0x74, 0x65, 0x73, 0x74, 0x41, 0x36, 0x44, 0x74, 0x65, + 0x73, 0x74, 0x41, 0x37, 0x44, 0x74, 0x65, 0x73, 0x74, 0x41, 0x38, 0x44, 0x74, 0x65, 0x73, 0x74, 0x41, + 0x39, 0x44, 0x74, 0x65, 0x73, 0x74, 0x03, 0x0a, 0x11, 0x18, 0x1f, 0x26, 0x2d, 0x34, 0x3b, 0x42, 0x09, + 0x00, 0x5e, 0x00, (byte) 0xb3, 0x00, 0x08, 0x01, 0x5d, 0x01, (byte) 0xb2, 0x01, 0x07, 0x02, 0x5c, 0x02, + (byte) 0xb1, 0x02, 0x06, 0x03 }); + final int size = 10; + assertThat(slice.isObject(), is(true)); + assertThat(slice.getLength(), is(size)); + for (int i = 0; i < size; i++) { + final VPackSlice attr = slice.get(String.valueOf(i)); + assertThat(attr.isObject(), is(true)); + assertThat(attr.getLength(), is(size)); + for (int j = 0; j < size; j++) { + final VPackSlice childAttr = attr.get(String.valueOf(j)); + assertThat(childAttr.isString(), is(true)); + } + } + } + + @Test + public void attributeAdapter() throws VPackException { + // {1:"a"} + // {"_key":"a"} + final VPackSlice slice = new VPackSlice(new byte[] { 0x0b, 0x06, 0x01, 0x31, 0x41, 0x61 }); + assertThat(slice.isObject(), is(true)); + assertThat(slice.getLength(), is(1)); + final VPackSlice key = slice.get("_key"); + assertThat(key.isString(), is(true)); + assertThat(key.getAsString(), is("a")); + } + + @Test + public void attributeAdapterDefaults() throws VPackException { + // {1:"a",2:"b",3:"c",4:"d",5:"e"} + // {"_key":"a","_rev":"b","_id":"c","_from":"d","_to":"e"} + final VPackSlice slice = new VPackSlice(new byte[] { 0x14, 0x12, 0x31, 0x41, 0x61, 0x32, 0x41, 0x62, 0x33, 0x41, + 0x63, 0x34, 0x41, 0x64, 0x35, 0x41, 0x65, 0x05 }); + assertThat(slice.isObject(), is(true)); + assertThat(slice.getLength(), is(5)); + { + final VPackSlice key = slice.get("_key"); + assertThat(key.isString(), is(true)); + assertThat(key.getAsString(), is("a")); + } + { + final VPackSlice rev = slice.get("_rev"); + assertThat(rev.isString(), is(true)); + assertThat(rev.getAsString(), is("b")); + } + { + final VPackSlice id = slice.get("_id"); + assertThat(id.isString(), is(true)); + assertThat(id.getAsString(), is("c")); + } + { + final VPackSlice from = slice.get("_from"); + assertThat(from.isString(), is(true)); + assertThat(from.getAsString(), is("d")); + } + { + final VPackSlice to = slice.get("_to"); + assertThat(to.isString(), is(true)); + assertThat(to.getAsString(), is("e")); + } + } + + @Test + public void attributeAdapterObjectWithIndexTable() throws VPackException { + // {1:"a",2:"b",3:"c",4:"d",5:"e"} + // {"_key":"a","_rev":"b","_id":"c","_from":"d","_to":"e"} + final VPackSlice slice = new VPackSlice(new byte[] { 0x0b, 0x21, 0x05, 0x31, 0x41, 0x61, 0x32, 0x42, 0x62, 0x62, + 0x33, 0x43, 0x63, 0x63, 0x63, 0x34, 0x44, 0x64, 0x64, 0x64, 0x64, 0x35, 0x45, 0x65, 0x65, 0x65, 0x65, + 0x65, 0x0f, 0x0a, 0x03, 0x06, 0x15 }); + assertThat(slice.isObject(), is(true)); + assertThat(slice.getLength(), is(5)); + { + final VPackSlice key = slice.get("_key"); + assertThat(key.isString(), is(true)); + assertThat(key.getAsString(), is("a")); + } + { + final VPackSlice rev = slice.get("_rev"); + assertThat(rev.isString(), is(true)); + assertThat(rev.getAsString(), is("bb")); + } + { + final VPackSlice id = slice.get("_id"); + assertThat(id.isString(), is(true)); + assertThat(id.getAsString(), is("ccc")); + } + { + final VPackSlice from = slice.get("_from"); + assertThat(from.isString(), is(true)); + assertThat(from.getAsString(), is("dddd")); + } + { + final VPackSlice to = slice.get("_to"); + assertThat(to.isString(), is(true)); + assertThat(to.getAsString(), is("eeeee")); + } + } + + @Test(expected = VPackValueTypeException.class) + public void getLengthFail() { + final VPackSlice slice = new VPackSlice(new byte[] { 0x00 }); + slice.getLength(); + } + + @Test(expected = VPackValueTypeException.class) + public void getNoObjectGetFail() throws VPackException { + final VPackSlice slice = new VPackSlice(new byte[] { 0x00 }); + slice.get("a"); + } + + @Test(expected = VPackValueTypeException.class) + public void getNoObjectKeyAtFail() { + final VPackSlice slice = new VPackSlice(new byte[] { 0x00 }); + slice.keyAt(0); + } + + @Test(expected = VPackValueTypeException.class) + public void getNoObjectValueAtFail() { + final VPackSlice slice = new VPackSlice(new byte[] { 0x00 }); + slice.valueAt(0); + } +} diff --git a/src/test/java/com/arangodb/velocypack/util/SliceIteratorTest.java b/src/test/java/com/arangodb/velocypack/util/SliceIteratorTest.java new file mode 100644 index 000000000..929b4b1d4 --- /dev/null +++ b/src/test/java/com/arangodb/velocypack/util/SliceIteratorTest.java @@ -0,0 +1,128 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.velocypack.util; + +import static org.hamcrest.Matchers.is; +import static org.junit.Assert.assertThat; + +import java.util.Map.Entry; +import java.util.NoSuchElementException; + +import org.junit.Test; + +import com.arangodb.velocypack.ArrayIterator; +import com.arangodb.velocypack.ObjectIterator; +import com.arangodb.velocypack.VPackSlice; +import com.arangodb.velocypack.exception.VPackValueTypeException; + +/** + * @author Mark - mark at arangodb.com + * + */ +public class SliceIteratorTest { + + @Test + public void objectIterator() { + // {"a":1, "b":16} + final VPackSlice slice = new VPackSlice( + new byte[] { 0x14, 0x0a, 0x41, 0x61, 0x31, 0x41, 0x62, 0x28, 0x10, 0x02 }); + { + final ObjectIterator iterator = new ObjectIterator(slice); + for (final String s : new String[] { "a", "b" }) { + final Entry next = iterator.next(); + assertThat(next.getKey(), is(s)); + } + } + { + final ObjectIterator iterator = new ObjectIterator(slice); + for (final int i : new int[] { 1, 16 }) { + final Entry next = iterator.next(); + assertThat(next.getValue().getAsInt(), is(i)); + } + } + } + + @Test(expected = NoSuchElementException.class) + public void objectIteratorNoNext() { + // {"a":1, "b":16} + final VPackSlice slice = new VPackSlice( + new byte[] { 0x14, 0x0a, 0x41, 0x61, 0x31, 0x41, 0x62, 0x28, 0x10, 0x02 }); + final ObjectIterator iterator = new ObjectIterator(slice); + + for (final String s : new String[] { "a", "b" }) { + final Entry next = iterator.next(); + assertThat(next.getKey(), is(s)); + } + iterator.next();// no more elements + } + + @Test(expected = VPackValueTypeException.class) + public void objectIteratorWithArrayFail() { + final VPackSlice slice = new VPackSlice(new byte[] { 0x13, 0x06, 0x31, 0x28, 0x10, 0x02 }); + new ObjectIterator(slice); + } + + @Test + public void emptyObjectIterator() { + final VPackSlice slice = new VPackSlice(new byte[] { 0x0a }); + final ObjectIterator iterator = new ObjectIterator(slice); + assertThat(iterator.hasNext(), is(false)); + } + + @Test + public void arrayIterator() { + // { 1, 16 } + final VPackSlice slice = new VPackSlice(new byte[] { 0x13, 0x06, 0x31, 0x28, 0x10, 0x02 }); + final ArrayIterator iterator = new ArrayIterator(slice); + + for (final int i : new int[] { 1, 16 }) { + final VPackSlice next = iterator.next(); + assertThat(next.getAsInt(), is(i)); + } + } + + @Test(expected = NoSuchElementException.class) + public void arrayIteratorNoNext() { + // { 1, 16 } + final VPackSlice slice = new VPackSlice(new byte[] { 0x13, 0x06, 0x31, 0x28, 0x10, 0x02 }); + final ArrayIterator iterator = new ArrayIterator(slice); + + for (final int i : new int[] { 1, 16 }) { + final VPackSlice next = iterator.next(); + assertThat(next.getAsInt(), is(i)); + } + iterator.next();// no more elements + } + + @Test(expected = VPackValueTypeException.class) + public void arrayIteratorWithObjectFail() { + final VPackSlice slice = new VPackSlice( + new byte[] { 0x14, 0x0a, 0x41, 0x61, 0x31, 0x41, 0x62, 0x28, 0x10, 0x02 }); + new ArrayIterator(slice); + } + + @Test(expected = UnsupportedOperationException.class) + public void removeFail() { + final VPackSlice slice = new VPackSlice(new byte[] { 0x13, 0x06, 0x31, 0x28, 0x10, 0x02 }); + final ArrayIterator iterator = new ArrayIterator(slice); + iterator.remove(); + } +} diff --git a/src/test/java/com/arangodb/velocypack/util/ValueTest.java b/src/test/java/com/arangodb/velocypack/util/ValueTest.java new file mode 100644 index 000000000..19a6a670f --- /dev/null +++ b/src/test/java/com/arangodb/velocypack/util/ValueTest.java @@ -0,0 +1,57 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.velocypack.util; + +import java.math.BigInteger; + +import org.junit.Test; + +import com.arangodb.velocypack.ValueType; +import com.arangodb.velocypack.exception.VPackValueTypeException; +import com.arangodb.velocypack.internal.Value; + +/** + * @author Mark - mark at arangodb.com + * + */ +public class ValueTest { + + @Test(expected = VPackValueTypeException.class) + public void wrongType() { + new Value(ValueType.STRING); + } + + @Test(expected = VPackValueTypeException.class) + public void wrongLongType() { + new Value(1L, ValueType.STRING); + } + + @Test(expected = VPackValueTypeException.class) + public void wrongIntegerType() { + new Value(new Long(1L), ValueType.STRING); + } + + @Test(expected = VPackValueTypeException.class) + public void wrongBigIntegerType() { + new Value(new BigInteger("1"), ValueType.STRING); + } + +} diff --git a/src/test/resources/arangodb-slave.properties b/src/test/resources/arangodb-slave.properties deleted file mode 100644 index 8ec0ad3fd..000000000 --- a/src/test/resources/arangodb-slave.properties +++ /dev/null @@ -1,3 +0,0 @@ -port=8529 -host=arango-test-server-slave -enableCURLLogger=true diff --git a/src/test/resources/arangodb-test.properties b/src/test/resources/arangodb-test.properties deleted file mode 100644 index 56d6a26ec..000000000 --- a/src/test/resources/arangodb-test.properties +++ /dev/null @@ -1,5 +0,0 @@ -arangoHost=arango-test-server:9999 -fallbackArangoHost=arango-test-server:9998 -retryCount=10 -defaultDatabase=mydb2 -enableCURLLogger=false diff --git a/src/test/resources/arangodb.properties b/src/test/resources/arangodb.properties index a61c68591..b4f4818b4 100644 --- a/src/test/resources/arangodb.properties +++ b/src/test/resources/arangodb.properties @@ -1,5 +1,3 @@ -port=8529 -host=localhost -user=root -password= -enableCURLLogger=false +arangodb.host=127.0.0.1 +arangodb.port=8529 +arangodb.user=root \ No newline at end of file diff --git a/src/test/resources/logback.xml b/src/test/resources/logback-test.xml similarity index 94% rename from src/test/resources/logback.xml rename to src/test/resources/logback-test.xml index 645d34624..425b55ef8 100644 --- a/src/test/resources/logback.xml +++ b/src/test/resources/logback-test.xml @@ -8,7 +8,7 @@ - + diff --git a/src/test/resources/ssl-arangodb.properties b/src/test/resources/ssl-arangodb.properties deleted file mode 100644 index 545733d83..000000000 --- a/src/test/resources/ssl-arangodb.properties +++ /dev/null @@ -1,6 +0,0 @@ -port=8530 -host=localhost -user=root -useSsl=true -password= -enableCURLLogger=false diff --git a/src/test/resources/test-data/jp-tokyo-station.tsv b/src/test/resources/test-data/jp-tokyo-station.tsv deleted file mode 100644 index ef6176a44..000000000 --- a/src/test/resources/test-data/jp-tokyo-station.tsv +++ /dev/null @@ -1,632 +0,0 @@ -2 JR東日本 11302 JR山手線 1130201 大崎 東京都品川区大崎一丁目21-4 139.728439 35.619772 -2 JR東日本 11302 JR山手線 1130202 五反田 東京都品川区東五反田一丁目26 139.723822 35.625974 -2 JR東日本 11302 JR山手線 1130203 目黒 東京都品川区上大崎二丁目16-9 139.715775 35.633923 -2 JR東日本 11302 JR山手線 1130204 恵比寿 東京都渋谷区恵比寿南一丁目5-5 139.71007 35.646685 -2 JR東日本 11302 JR山手線 1130205 渋谷 東京都渋谷区道玄坂一丁目1-1 139.701238 35.658871 -2 JR東日本 11302 JR山手線 1130206 原宿 東京都渋谷区神宮前一丁目18 139.702592 35.670646 -2 JR東日本 11302 JR山手線 1130207 代々木 東京都渋谷区代々木一丁目34-1 139.702042 35.683061 -2 JR東日本 11302 JR山手線 1130208 新宿 東京都新宿区新宿三丁目38-1 139.700464 35.689729 -2 JR東日本 11302 JR山手線 1130209 新大久保 東京都新宿区百人町一丁目10-15 139.700261 35.700875 -2 JR東日本 11302 JR山手線 1130210 高田馬場 東京都新宿区高田馬場一丁目35-1 139.703715 35.712677 -2 JR東日本 11302 JR山手線 1130211 目白 東京都豊島区目白三丁目3-1 139.706228 35.720476 -2 JR東日本 11302 JR山手線 1130212 池袋 東京都豊島区南池袋一丁目28-2 139.711086 35.730256 -2 JR東日本 11302 JR山手線 1130213 大塚 東京都豊島区南大塚三丁目33-1 139.728584 35.731412 -2 JR東日本 11302 JR山手線 1130214 巣鴨 東京都豊島区巣鴨一丁目16-1 139.739303 35.733445 -2 JR東日本 11302 JR山手線 1130215 駒込 東京都豊島区駒込二丁目1-1 139.748053 35.736825 -2 JR東日本 11302 JR山手線 1130216 田端 東京都北区東田端一丁目17-1 139.761229 35.737781 -2 JR東日本 11302 JR山手線 1130217 西日暮里 東京都荒川区西日暮里五丁目22-1 139.766857 35.731954 -2 JR東日本 11302 JR山手線 1130218 日暮里 東京都荒川区西日暮里二丁目19-1 139.771287 35.727908 -2 JR東日本 11302 JR山手線 1130219 鶯谷 東京都台東区根岸一丁目4-1 139.778015 35.721484 -2 JR東日本 11302 JR山手線 1130220 上野 東京都台東区上野七丁目1-1 139.777043 35.71379 -2 JR東日本 11302 JR山手線 1130221 御徒町 東京都台東区上野五丁目27 139.774727 35.707282 -2 JR東日本 11302 JR山手線 1130222 秋葉原 東京都千代田区外神田一丁目17 139.773288 35.698619 -2 JR東日本 11302 JR山手線 1130223 神田 東京都千代田区鍛冶町二丁目13-1 139.770641 35.691173 -2 JR東日本 11302 JR山手線 1130224 東京 東京都千代田区丸の内一丁目9-1 139.766103 35.681391 -2 JR東日本 11302 JR山手線 1130225 有楽町 東京都千代田区有楽町二丁目9 139.763806 35.675441 -2 JR東日本 11302 JR山手線 1130226 新橋 東京都港区新橋二丁目17 139.758587 35.666195 -2 JR東日本 11302 JR山手線 1130227 浜松町 東京都港区海岸一丁目3-1 139.757135 35.655391 -2 JR東日本 11302 JR山手線 1130228 田町 東京都港区芝五丁目33-36 139.747575 35.645736 -2 JR東日本 11302 JR山手線 1130229 品川 東京都港区高輪三丁目26-26 139.738999 35.62876 -2 JR東日本 11312 JR中央線(快速) 1131201 東京 東京都千代田区丸の内一丁目 139.766103 35.681391 -2 JR東日本 11312 JR中央線(快速) 1131202 神田 東京都千代田区鍛冶町二丁目13-1 139.770641 35.691173 -2 JR東日本 11312 JR中央線(快速) 1131203 御茶ノ水 千代田区神田駿河台2丁目 139.764955 35.699605 -2 JR東日本 11312 JR中央線(快速) 1131204 水道橋 千代田区三崎町2丁目 139.754312 35.702039 -2 JR東日本 11312 JR中央線(快速) 1131205 飯田橋 東京都千代田区飯田橋四丁目10-2 139.745143 35.701835 -2 JR東日本 11312 JR中央線(快速) 1131206 市ケ谷 東京都新宿区市谷田町一丁目1 139.735241 35.691105 -2 JR東日本 11312 JR中央線(快速) 1131207 四ツ谷 東京都新宿区四谷一丁目 139.730644 35.686041 -2 JR東日本 11312 JR中央線(快速) 1131208 信濃町 新宿区信濃町 139.720729 35.680031 -2 JR東日本 11312 JR中央線(快速) 1131209 千駄ケ谷 東京都渋谷区千駄ヶ谷一丁目35-10 139.711644 35.681231 -2 JR東日本 11312 JR中央線(快速) 1131210 代々木 東京都渋谷区代々木一丁目34-1 139.702042 35.683061 -2 JR東日本 11312 JR中央線(快速) 1131211 新宿 東京都新宿区新宿三丁目38-1 139.700464 35.689729 -2 JR東日本 11312 JR中央線(快速) 1131212 大久保 新宿区百人町1丁目 139.69732 35.700784 -2 JR東日本 11312 JR中央線(快速) 1131213 東中野 中野区東中野4丁目 139.684436 35.706529 -2 JR東日本 11312 JR中央線(快速) 1131214 中野 中野区中野5丁目 139.665835 35.705765 -2 JR東日本 11312 JR中央線(快速) 1131215 高円寺 杉並区高円寺南4丁目 139.649664 35.705326 -2 JR東日本 11312 JR中央線(快速) 1131216 阿佐ケ谷 東京都杉並区阿佐谷南三丁目36-3 139.635868 35.704818 -2 JR東日本 11312 JR中央線(快速) 1131217 荻窪 杉並区上荻1丁目 139.620109 35.704523 -2 JR東日本 11312 JR中央線(快速) 1131218 西荻窪 杉並区西荻南3丁目 139.599361 35.703842 -2 JR東日本 11312 JR中央線(快速) 1131219 吉祥寺 東京都武蔵野市吉祥寺南町 139.579765 35.703119 -2 JR東日本 11312 JR中央線(快速) 1131220 三鷹 東京都三鷹市下連雀三丁目46-1 139.560325 35.702683 -2 JR東日本 11312 JR中央線(快速) 1131221 武蔵境 武蔵野市境1丁目 139.543402 35.702083 -2 JR東日本 11312 JR中央線(快速) 1131222 東小金井 小金井市梶野町5丁目 139.524837 35.701643 -2 JR東日本 11312 JR中央線(快速) 1131223 武蔵小金井 小金井市本町6丁目 139.506483 35.701337 -2 JR東日本 11312 JR中央線(快速) 1131224 国分寺 東京都国分寺市本町二丁目1-23 139.480841 35.700123 -2 JR東日本 11312 JR中央線(快速) 1131225 西国分寺 国分寺市西恋ケ窪2丁目 139.465994 35.699744 -2 JR東日本 11312 JR中央線(快速) 1131226 国立 国立市北1丁目 139.44634 35.69923 -2 JR東日本 11312 JR中央線(快速) 1131227 立川 東京都立川市曙町二丁目1-1 139.413704 35.698202 -2 JR東日本 11312 JR中央線(快速) 1131228 日野 日野市大坂上1丁目 139.39393 35.679244 -2 JR東日本 11312 JR中央線(快速) 1131229 豊田 日野市豊田4丁目 139.381495 35.659502 -2 JR東日本 11312 JR中央線(快速) 1131230 八王子 東京都八王子市旭町1-1 139.338998 35.655555 -2 JR東日本 11312 JR中央線(快速) 1131231 西八王子 八王子市千人町2丁目 139.31264 35.656621 -2 JR東日本 11312 JR中央線(快速) 1131232 高尾 八王子市高尾町 139.282288 35.642026 -2 JR東日本 11313 JR中央・総武線 1131301 三鷹 東京都三鷹市下連雀三丁目46-1 139.560325 35.702683 -2 JR東日本 11313 JR中央・総武線 1131302 吉祥寺 東京都武蔵野市吉祥寺南町 139.579765 35.703119 -2 JR東日本 11313 JR中央・総武線 1131303 西荻窪 杉並区西荻南3丁目 139.599361 35.703842 -2 JR東日本 11313 JR中央・総武線 1131304 荻窪 杉並区上荻1丁目 139.620109 35.704523 -2 JR東日本 11313 JR中央・総武線 1131305 阿佐ケ谷 東京都杉並区阿佐谷南三丁目36-2 139.635868 35.704818 -2 JR東日本 11313 JR中央・総武線 1131306 高円寺 杉並区高円寺南4丁目 139.649664 35.705326 -2 JR東日本 11313 JR中央・総武線 1131307 中野 中野区中野5丁目 139.665835 35.705765 -2 JR東日本 11313 JR中央・総武線 1131308 東中野 中野区東中野4丁目 139.684436 35.706529 -2 JR東日本 11313 JR中央・総武線 1131309 大久保 新宿区百人町1丁目 139.69732 35.700784 -2 JR東日本 11313 JR中央・総武線 1131310 新宿 東京都新宿区新宿三丁目38-1 139.700464 35.689729 -2 JR東日本 11313 JR中央・総武線 1131311 代々木 東京都渋谷区代々木一丁目34-1 139.702042 35.683061 -2 JR東日本 11313 JR中央・総武線 1131312 千駄ケ谷 東京都渋谷区千駄ヶ谷一丁目35-10 139.711644 35.681231 -2 JR東日本 11313 JR中央・総武線 1131313 信濃町 新宿区信濃町 139.720729 35.680031 -2 JR東日本 11313 JR中央・総武線 1131314 四ツ谷 東京都新宿区四谷一丁目 139.730644 35.686041 -2 JR東日本 11313 JR中央・総武線 1131315 市ケ谷 東京都新宿区市谷田町一丁目1 139.735241 35.691105 -2 JR東日本 11313 JR中央・総武線 1131316 飯田橋 東京都千代田区飯田橋四丁目10-2 139.745143 35.701835 -2 JR東日本 11313 JR中央・総武線 1131317 水道橋 千代田区三崎町2丁目 139.754312 35.702039 -2 JR東日本 11313 JR中央・総武線 1131318 御茶ノ水 千代田区神田駿河台2丁目 139.764955 35.699605 -2 JR東日本 11313 JR中央・総武線 1131319 秋葉原 東京都千代田区外神田一丁目17-6 139.773288 35.698619 -2 JR東日本 11313 JR中央・総武線 1131320 浅草橋 台東区浅草橋1丁目 139.784427 35.697403 -2 JR東日本 11313 JR中央・総武線 1131321 両国 墨田区横網1丁目 139.793334 35.69579 -2 JR東日本 11313 JR中央・総武線 1131322 錦糸町 墨田区江東橋3丁目 139.814136 35.696802 -2 JR東日本 11313 JR中央・総武線 1131323 亀戸 江東区亀戸5丁目 139.826262 35.697345 -2 JR東日本 11313 JR中央・総武線 1131324 平井 江戸川区平井3丁目 139.842181 35.70643 -2 JR東日本 11313 JR中央・総武線 1131325 新小岩 葛飾区新小岩1丁目 139.857777 35.716903 -2 JR東日本 11313 JR中央・総武線 1131326 小岩 江戸川区南小岩7丁目 139.881755 35.733207 -2 JR東日本 11313 JR中央・総武線 1131327 市川 市川市市川1丁目 139.908142 35.728903 -2 JR東日本 11313 JR中央・総武線 1131328 本八幡 市川市八幡2丁目 139.92741 35.720898 -2 JR東日本 11313 JR中央・総武線 1131329 下総中山 船橋市本中山2丁目 139.943092 35.714276 -2 JR東日本 11313 JR中央・総武線 1131330 西船橋 船橋市西船4丁目 139.959536 35.707283 -2 JR東日本 11313 JR中央・総武線 1131331 船橋 船橋市本町7丁目 139.984707 35.701865 -2 JR東日本 11313 JR中央・総武線 1131332 東船橋 船橋市東船橋2丁目 140.00393 35.699811 -2 JR東日本 11313 JR中央・総武線 1131333 津田沼 習志野市津田沼1丁目 140.020179 35.691367 -2 JR東日本 11313 JR中央・総武線 1131334 幕張本郷 千葉市花見川区幕張本郷1丁目 140.042241 35.672664 -2 JR東日本 11313 JR中央・総武線 1131335 幕張 千葉市花見川区幕張町5丁目 140.057899 35.6594 -2 JR東日本 11313 JR中央・総武線 1131336 新検見川 千葉市花見川区南花園 140.073025 35.65169 -2 JR東日本 11313 JR中央・総武線 1131337 稲毛 千葉市稲毛区稲毛東3丁目 140.09256 35.637264 -2 JR東日本 11313 JR中央・総武線 1131338 西千葉 千葉市中央区春日2丁目 140.103337 35.622639 -2 JR東日本 11313 JR中央・総武線 1131339 千葉 千葉市中央区新千葉1丁目 140.112837 35.613425 -2 JR東日本 11321 JR埼京線 1132101 大崎 東京都品川区大崎一丁目21-4 139.728439 35.619772 -2 JR東日本 11321 JR埼京線 1132102 恵比寿 東京都渋谷区恵比寿南一丁目5-5 139.71007 35.646685 -2 JR東日本 11321 JR埼京線 1132103 渋谷 東京都渋谷区道玄坂一丁目1-1 139.701238 35.658871 -2 JR東日本 11321 JR埼京線 1132104 新宿 東京都新宿区新宿三丁目38-1 139.700464 35.689729 -2 JR東日本 11321 JR埼京線 1132105 池袋 東京都豊島区 139.711086 35.730256 -2 JR東日本 11321 JR埼京線 1132106 板橋 板橋区板橋1丁目 139.719507 35.745435 -2 JR東日本 11321 JR埼京線 1132107 十条 北区上十条1丁目 139.722233 35.760321 -2 JR東日本 11321 JR埼京線 1132108 赤羽 北区赤羽1丁目 139.720928 35.778026 -2 JR東日本 11321 JR埼京線 1132109 北赤羽 北区赤羽北2丁目 139.70569 35.787007 -2 JR東日本 11321 JR埼京線 1132110 浮間舟渡 北区浮間4丁目 139.691341 35.791209 -2 JR東日本 11321 JR埼京線 1132111 戸田公園 戸田市本町4丁目 139.678203 35.807906 -2 JR東日本 11321 JR埼京線 1132112 戸田 戸田市新曽字柳原 139.669548 35.817665 -2 JR東日本 11321 JR埼京線 1132113 北戸田 戸田市新曽字芦原 139.661201 35.826883 -2 JR東日本 11321 JR埼京線 1132114 武蔵浦和 さいたま市南区別所七丁目12-1 139.646809 35.845422 -2 JR東日本 11321 JR埼京線 1132115 中浦和 さいたま市南区鹿手袋1丁目 139.6375 35.853769 -2 JR東日本 11321 JR埼京線 1132116 南与野 さいたま市中央区鈴谷2丁目 139.631117 35.867456 -2 JR東日本 11321 JR埼京線 1132117 与野本町 さいたま市中央区本町東2丁目 139.626075 35.880968 -2 JR東日本 11321 JR埼京線 1132118 北与野 さいたま市中央区上落合 139.628521 35.890678 -2 JR東日本 11321 JR埼京線 1132119 大宮 さいたま市大宮区錦町 139.62405 35.906439 -2 JR東日本 11321 JR埼京線 1132120 日進 さいたま市北区日進町2丁目 139.606111 35.931555 -2 JR東日本 11321 JR埼京線 1132121 指扇 さいたま市西区宝来 139.564951 35.917023 -2 JR東日本 11321 JR埼京線 1132122 南古谷 川越市並木 139.519082 35.903344 -2 JR東日本 11321 JR埼京線 1132123 川越 川越市脇田町 139.483078 35.906742 -2 JR東日本 11322 JR川越線 1132201 大宮 さいたま市大宮区錦町 139.62405 35.906439 -2 JR東日本 11322 JR川越線 1132202 日進 さいたま市北区日進町2丁目 139.606111 35.931555 -2 JR東日本 11322 JR川越線 1132203 指扇 さいたま市西区宝来 139.564951 35.917023 -2 JR東日本 11322 JR川越線 1132204 南古谷 川越市並木 139.519082 35.903344 -2 JR東日本 11322 JR川越線 1132205 川越 川越市脇田町 139.483078 35.906742 -2 JR東日本 11322 JR川越線 1132206 西川越 川越市小ケ谷 139.459746 35.91909 -2 JR東日本 11322 JR川越線 1132207 的場 川越市的場 139.435376 35.917478 -2 JR東日本 11322 JR川越線 1132208 笠幡 川越市笠幡上野 139.40622 35.907551 -2 JR東日本 11322 JR川越線 1132209 武蔵高萩 日高市高萩 139.371123 35.901729 -2 JR東日本 11322 JR川越線 1132210 高麗川 日高市原宿 139.33809 35.896328 -2 JR東日本 11322 JR川越線 1132211 西大宮 さいたま市西区大字指扇3582-4 139.581535 35.922906 -2 JR東日本 11323 JR高崎線 1132301 上野 東京都台東区上野七丁目1-1 139.777043 35.71379 -2 JR東日本 11323 JR高崎線 1132302 尾久 北区昭和町1丁目 139.753846 35.74683 -2 JR東日本 11323 JR高崎線 1132303 赤羽 北区赤羽1丁目 139.720928 35.778026 -2 JR東日本 11323 JR高崎線 1132304 浦和 さいたま市浦和区高砂1丁目 139.657109 35.858496 -2 JR東日本 11323 JR高崎線 1132305 さいたま新都心 さいたま市大宮区吉敷町4丁目57番地3 139.633587 35.893867 -2 JR東日本 11323 JR高崎線 1132306 大宮 さいたま市大宮区錦町 139.62405 35.906439 -2 JR東日本 11323 JR高崎線 1132307 宮原 さいたま市北区宮原町3丁目 139.609455 35.940256 -2 JR東日本 11323 JR高崎線 1132308 上尾 上尾市柏座1丁目 139.588434 35.973522 -2 JR東日本 11323 JR高崎線 1132309 北上尾 上尾市原新町 139.577223 35.985632 -2 JR東日本 11323 JR高崎線 1132310 桶川 桶川市南1丁目 139.564274 35.998375 -2 JR東日本 11323 JR高崎線 1132311 北本 北本市北本1丁目 139.533591 36.032112 -2 JR東日本 11323 JR高崎線 1132312 鴻巣 鴻巣市本町1丁目 139.509552 36.0592 -2 JR東日本 11323 JR高崎線 1132313 北鴻巣 鴻巣市赤見台1丁目 139.476894 36.085529 -2 JR東日本 11323 JR高崎線 1132314 吹上 鴻巣市吹上本町1丁目 139.45312 36.103062 -2 JR東日本 11323 JR高崎線 1132315 行田 行田市壱里山町 139.432103 36.113879 -2 JR東日本 11323 JR高崎線 1132316 熊谷 熊谷市筑波2丁目 139.389528 36.139627 -2 JR東日本 11323 JR高崎線 1132317 籠原 熊谷市大字新堀 139.330199 36.17448 -2 JR東日本 11323 JR高崎線 1132318 深谷 深谷市西島町1丁目 139.28127 36.191344 -2 JR東日本 11323 JR高崎線 1132319 岡部 深谷市岡 139.237622 36.205645 -2 JR東日本 11323 JR高崎線 1132320 本庄 本庄市銀座3丁目 139.188299 36.236229 -2 JR東日本 11323 JR高崎線 1132321 神保原 児玉郡上里町大字神保原町 139.149172 36.25359 -2 JR東日本 11323 JR高崎線 1132322 新町 高崎市新町 139.105457 36.272984 -2 JR東日本 11323 JR高崎線 1132323 倉賀野 高崎市倉賀野町 139.049474 36.300216 -2 JR東日本 11323 JR高崎線 1132324 高崎 高崎市八島町 139.012354 36.322239 -2 JR東日本 11324 JR外房線 1132401 千葉 千葉市中央区新千葉1丁目 140.112837 35.613425 -2 JR東日本 11324 JR外房線 1132402 本千葉 千葉市中央区長洲町1丁目 140.120987 35.601202 -2 JR東日本 11324 JR外房線 1132403 蘇我 千葉市中央区今井2丁目 140.130767 35.582065 -2 JR東日本 11324 JR外房線 1132404 鎌取 千葉市緑区鎌取町 140.178583 35.562795 -2 JR東日本 11324 JR外房線 1132405 誉田 千葉市緑区誉田町2丁目 140.213748 35.546996 -2 JR東日本 11324 JR外房線 1132406 土気 千葉市緑区土気町 140.269783 35.530866 -2 JR東日本 11324 JR外房線 1132407 大網 山武郡大網白里町南玉 140.311111 35.522427 -2 JR東日本 11324 JR外房線 1132408 永田 山武郡大網白里町永田 140.311162 35.503129 -2 JR東日本 11324 JR外房線 1132409 本納 茂原市本納 140.30758 35.48227 -2 JR東日本 11324 JR外房線 1132410 新茂原 茂原市長尾 140.29983 35.449477 -2 JR東日本 11324 JR外房線 1132411 茂原 茂原市町保 140.304121 35.426733 -2 JR東日本 11324 JR外房線 1132412 八積 長生郡長生村岩沼 140.345367 35.403971 -2 JR東日本 11324 JR外房線 1132413 上総一ノ宮 長生郡一宮町一宮 140.365138 35.373401 -2 JR東日本 11324 JR外房線 1132414 東浪見 長生郡一宮町東浪見 140.376706 35.34669 -2 JR東日本 11324 JR外房線 1132415 太東 いすみ市岬町椎木 140.381184 35.319942 -2 JR東日本 11324 JR外房線 1132416 長者町 いすみ市岬町長者 140.385021 35.295839 -2 JR東日本 11324 JR外房線 1132417 三門 いすみ市日在 140.391567 35.282377 -2 JR東日本 11324 JR外房線 1132418 大原 いすみ市大原 140.390864 35.251097 -2 JR東日本 11324 JR外房線 1132419 浪花 いすみ市小沢 140.379428 35.222674 -2 JR東日本 11324 JR外房線 1132420 御宿 夷隅郡御宿町須賀 140.35197 35.188028 -2 JR東日本 11324 JR外房線 1132421 勝浦 勝浦市墨名 140.312142 35.152722 -2 JR東日本 11324 JR外房線 1132422 鵜原 勝浦市鵜原 140.278446 35.140828 -2 JR東日本 11324 JR外房線 1132423 上総興津 勝浦市興津 140.250487 35.137146 -2 JR東日本 11324 JR外房線 1132424 行川アイランド 勝浦市浜行川 140.226962 35.11832 -2 JR東日本 11324 JR外房線 1132425 安房小湊 鴨川市内浦 140.190337 35.128597 -2 JR東日本 11324 JR外房線 1132426 安房天津 鴨川市天津 140.154487 35.125473 -2 JR東日本 11324 JR外房線 1132427 安房鴨川 鴨川市横渚 140.103566 35.107465 -2 JR東日本 11325 JR内房線 1132501 千葉 千葉市中央区新千葉1丁目 140.112837 35.613425 -2 JR東日本 11325 JR内房線 1132502 本千葉 千葉市中央区長洲町1丁目 140.120987 35.601202 -2 JR東日本 11325 JR内房線 1132503 蘇我 千葉市中央区今井2丁目 140.130767 35.582065 -2 JR東日本 11325 JR内房線 1132504 浜野 千葉市中央区村田町 140.132089 35.551876 -2 JR東日本 11325 JR内房線 1132505 八幡宿 市原市八幡 140.120072 35.536189 -2 JR東日本 11325 JR内房線 1132506 五井 市原市五井 140.089522 35.512985 -2 JR東日本 11325 JR内房線 1132507 姉ケ崎 千葉県市原市姉崎528-2 140.041749 35.4786 -2 JR東日本 11325 JR内房線 1132508 長浦 袖ケ浦市蔵波 139.995478 35.450234 -2 JR東日本 11325 JR内房線 1132509 袖ケ浦 千葉県袖ケ浦市奈良輪1198 139.95788 35.431997 -2 JR東日本 11325 JR内房線 1132510 巌根 木更津市岩根3丁目 139.933229 35.414285 -2 JR東日本 11325 JR内房線 1132511 木更津 木更津市富士見1丁目 139.92611 35.381668 -2 JR東日本 11325 JR内房線 1132512 君津 君津市東坂田1丁目 139.895697 35.333619 -2 JR東日本 11325 JR内房線 1132513 青堀 富津市大堀 139.858189 35.330304 -2 JR東日本 11325 JR内房線 1132514 大貫 富津市千種新田 139.855541 35.291661 -2 JR東日本 11325 JR内房線 1132515 佐貫町 富津市亀田 139.876106 35.260113 -2 JR東日本 11325 JR内房線 1132516 上総湊 富津市湊 139.871016 35.221855 -2 JR東日本 11325 JR内房線 1132517 竹岡 富津市萩生 139.830159 35.197582 -2 JR東日本 11325 JR内房線 1132518 浜金谷 富津市金谷 139.822141 35.168215 -2 JR東日本 11325 JR内房線 1132519 保田 安房郡鋸南町保田 139.838114 35.14148 -2 JR東日本 11325 JR内房線 1132520 安房勝山 安房郡鋸南町竜島 139.83339 35.114022 -2 JR東日本 11325 JR内房線 1132521 岩井 南房総市市部 139.849839 35.093062 -2 JR東日本 11325 JR内房線 1132522 富浦 南房総市富浦町原岡 139.837811 35.04614 -2 JR東日本 11325 JR内房線 1132523 那古船形 館山市船形 139.851388 35.028987 -2 JR東日本 11325 JR内房線 1132524 館山 館山市北条 139.861888 34.9959 -2 JR東日本 11325 JR内房線 1132525 九重 館山市二子 139.911383 34.99752 -2 JR東日本 11325 JR内房線 1132526 千倉 南房総市千倉町瀬戸 139.954738 34.976704 -2 JR東日本 11325 JR内房線 1132527 千歳 南房総市千倉町白子 139.966378 34.991701 -2 JR東日本 11325 JR内房線 1132528 南三原 南房総市和田町松田 139.979204 35.021065 -2 JR東日本 11325 JR内房線 1132529 和田浦 南房総市和田町仁我浦 140.019569 35.041885 -2 JR東日本 11325 JR内房線 1132530 江見 鴨川市西江見 140.061026 35.062513 -2 JR東日本 11325 JR内房線 1132531 太海 鴨川市太海 140.096229 35.081435 -2 JR東日本 11325 JR内房線 1132532 安房鴨川 鴨川市横渚 140.103566 35.107465 -2 JR東日本 11326 JR京葉線 1132601 東京 東京都千代田区丸の内一丁目 139.766103 35.681391 -2 JR東日本 11326 JR京葉線 1132602 八丁堀 中央区八丁堀3丁目 139.777705 35.674617 -2 JR東日本 11326 JR京葉線 1132603 越中島 江東区越中島2丁目 139.792713 35.667946 -2 JR東日本 11326 JR京葉線 1132604 潮見 江東区潮見2丁目 139.817341 35.658702 -2 JR東日本 11326 JR京葉線 1132605 新木場 東京都江東区新木場一丁目5 139.827402 35.646172 -2 JR東日本 11326 JR京葉線 1132606 葛西臨海公園 江戸川区臨海町6丁目 139.861529 35.644392 -2 JR東日本 11326 JR京葉線 1132607 舞浜 浦安市舞浜 139.883714 35.636115 -2 JR東日本 11326 JR京葉線 1132608 新浦安 浦安市入船1丁目 139.912553 35.649526 -2 JR東日本 11326 JR京葉線 1132609 市川塩浜 市川市塩浜2丁目 139.923684 35.666554 -2 JR東日本 11326 JR京葉線 1132610 西船橋 船橋市西船4丁目 139.959536 35.707283 -2 JR東日本 11326 JR京葉線 1132611 二俣新町 市川市二俣新町 139.959525 35.691273 -2 JR東日本 11326 JR京葉線 1132612 南船橋 船橋市若松2丁目 139.995773 35.681804 -2 JR東日本 11326 JR京葉線 1132613 新習志野 習志野市茜浜2丁目 140.012825 35.667342 -2 JR東日本 11326 JR京葉線 1132614 海浜幕張 千葉市美浜区ひび野 140.041917 35.648373 -2 JR東日本 11326 JR京葉線 1132615 検見川浜 千葉市美浜区真砂4丁目 140.058888 35.637291 -2 JR東日本 11326 JR京葉線 1132616 稲毛海岸 千葉市美浜区高洲3丁目 140.074034 35.629501 -2 JR東日本 11326 JR京葉線 1132617 千葉みなと 千葉市中央区中央港1丁目 140.10341 35.606172 -2 JR東日本 11326 JR京葉線 1132618 蘇我 千葉市中央区今井2丁目 140.130767 35.582065 -2 JR東日本 11332 JR京浜東北線 1133201 大宮 さいたま市大宮区錦町 139.62405 35.906439 -2 JR東日本 11332 JR京浜東北線 1133202 さいたま新都心 さいたま市大宮区吉敷町4丁目57番地3 139.633587 35.893867 -2 JR東日本 11332 JR京浜東北線 1133203 与野 さいたま市浦和区上木崎1丁目 139.639085 35.884393 -2 JR東日本 11332 JR京浜東北線 1133204 北浦和 さいたま市浦和区北浦和3丁目 139.645951 35.872053 -2 JR東日本 11332 JR京浜東北線 1133205 浦和 さいたま市浦和区高砂1丁目 139.657109 35.858496 -2 JR東日本 11332 JR京浜東北線 1133206 南浦和 さいたま市南区南浦和2丁目 139.669125 35.847648 -2 JR東日本 11332 JR京浜東北線 1133207 蕨 蕨市中央1丁目 139.690357 35.827959 -2 JR東日本 11332 JR京浜東北線 1133208 西川口 川口市並木町2丁目 139.704312 35.815514 -2 JR東日本 11332 JR京浜東北線 1133209 川口 川口市栄町3丁目 139.717472 35.801869 -2 JR東日本 11332 JR京浜東北線 1133210 赤羽 北区赤羽1丁目 139.720928 35.778026 -2 JR東日本 11332 JR京浜東北線 1133211 東十条 北区東十条3丁目 139.726858 35.763803 -2 JR東日本 11332 JR京浜東北線 1133212 王子 北区王子1丁目 139.73809 35.752538 -2 JR東日本 11332 JR京浜東北線 1133213 上中里 北区上中里1丁目 139.745769 35.74728 -2 JR東日本 11332 JR京浜東北線 1133214 田端 東京都北区東田端一丁目17-1 139.761229 35.737781 -2 JR東日本 11332 JR京浜東北線 1133215 西日暮里 東京都荒川区西日暮里五丁目22-1 139.766857 35.731954 -2 JR東日本 11332 JR京浜東北線 1133216 日暮里 東京都荒川区西日暮里二丁目 139.771287 35.727908 -2 JR東日本 11332 JR京浜東北線 1133217 鶯谷 東京都台東区根岸一丁目4-1 139.778015 35.721484 -2 JR東日本 11332 JR京浜東北線 1133218 上野 東京都台東区上野七丁目1-1 139.777043 35.71379 -2 JR東日本 11332 JR京浜東北線 1133219 御徒町 東京都台東区上野五丁目27 139.774727 35.707282 -2 JR東日本 11332 JR京浜東北線 1133220 秋葉原 東京都千代田区外神田一丁目17-6 139.773288 35.698619 -2 JR東日本 11332 JR京浜東北線 1133221 神田 東京都千代田区鍛冶町二丁目13-1 139.770641 35.691173 -2 JR東日本 11332 JR京浜東北線 1133222 東京 東京都千代田区丸の内一丁目 139.766103 35.681391 -2 JR東日本 11332 JR京浜東北線 1133223 有楽町 東京都千代田区有楽町二丁目9-17 139.763806 35.675441 -2 JR東日本 11332 JR京浜東北線 1133224 新橋 東京都港区新橋二丁目17 139.758587 35.666195 -2 JR東日本 11332 JR京浜東北線 1133225 浜松町 東京都港区海岸一丁目3-1 139.757135 35.655391 -2 JR東日本 11332 JR京浜東北線 1133226 田町 東京都港区芝五丁目33-36 139.747575 35.645736 -2 JR東日本 11332 JR京浜東北線 1133227 品川 東京都港区高輪三丁目26-26 139.738999 35.62876 -2 JR東日本 11332 JR京浜東北線 1133228 大井町 品川区大井1丁目 139.73485 35.606257 -2 JR東日本 11332 JR京浜東北線 1133229 大森 大田区大森北1丁目 139.728079 35.588903 -2 JR東日本 11332 JR京浜東北線 1133230 蒲田 大田区蒲田5丁目 139.716032 35.562517 -2 JR東日本 11332 JR京浜東北線 1133231 川崎 川崎市川崎区駅前本町 139.697485 35.531311 -2 JR東日本 11332 JR京浜東北線 1133232 鶴見 横浜市鶴見区鶴見中央 139.67614 35.508387 -2 JR東日本 11332 JR京浜東北線 1133233 新子安 横浜市神奈川区子安通 139.654776 35.487064 -2 JR東日本 11332 JR京浜東北線 1133234 東神奈川 横浜市神奈川区東神奈川 139.633466 35.47804 -2 JR東日本 11332 JR京浜東北線 1133235 横浜 横浜市西区高島2丁目 139.622704 35.466195 -2 JR東日本 11332 JR京浜東北線 1133236 桜木町 横浜市中区桜木町1丁目 139.630881 35.451112 -2 JR東日本 11332 JR京浜東北線 1133237 関内 横浜市中区港町1丁目 139.636984 35.443336 -2 JR東日本 11332 JR京浜東北線 1133238 石川町 横浜市中区石川町2丁目 139.642934 35.438808 -2 JR東日本 11332 JR京浜東北線 1133239 山手 横浜市中区大和町2丁目 139.646425 35.426891 -2 JR東日本 11332 JR京浜東北線 1133240 根岸 横浜市磯子区東町 139.636034 35.415887 -2 JR東日本 11332 JR京浜東北線 1133241 磯子 横浜市磯子区森1丁目 139.617916 35.399881 -2 JR東日本 11332 JR京浜東北線 1133242 新杉田 横浜市磯子区新杉田町 139.619483 35.386863 -2 JR東日本 11332 JR京浜東北線 1133243 洋光台 横浜市磯子区洋光台3丁目 139.596852 35.378785 -2 JR東日本 11332 JR京浜東北線 1133244 港南台 横浜市港南区港南台3丁目 139.576243 35.375183 -2 JR東日本 11332 JR京浜東北線 1133245 本郷台 横浜市栄区小菅ケ谷町 139.550159 35.36787 -2 JR東日本 11332 JR京浜東北線 1133246 大船 鎌倉市大船1丁目 139.531127 35.353466 -2 JR東日本 11333 JR湘南新宿ライン 1133301 大宮 さいたま市大宮区錦町 139.62405 35.906439 -2 JR東日本 11333 JR湘南新宿ライン 1133302 赤羽 北区赤羽1丁目 139.720928 35.778026 -2 JR東日本 11333 JR湘南新宿ライン 1133303 池袋 東京都豊島区 139.711086 35.730256 -2 JR東日本 11333 JR湘南新宿ライン 1133304 新宿 東京都新宿区新宿三丁目38-1 139.700464 35.689729 -2 JR東日本 11333 JR湘南新宿ライン 1133305 渋谷 東京都渋谷区道玄坂一丁目1-1 139.701238 35.658871 -2 JR東日本 11333 JR湘南新宿ライン 1133306 恵比寿 東京都渋谷区恵比寿南一丁目5-5 139.71007 35.646685 -2 JR東日本 11333 JR湘南新宿ライン 1133307 大崎 東京都品川区大崎一丁目21-4 139.728439 35.619772 -2 JR東日本 11333 JR湘南新宿ライン 1133308 西大井 品川区西大井1丁目 139.721729 35.601616 -2 JR東日本 11333 JR湘南新宿ライン 1133309 新川崎 川崎市幸区鹿島田 139.671481 35.551784 -2 JR東日本 11333 JR湘南新宿ライン 1133310 横浜 横浜市西区高島2丁目 139.622704 35.466195 -2 JR東日本 11333 JR湘南新宿ライン 1133311 保土ケ谷 横浜市保土ケ谷区岩井町 139.599671 35.446746 -2 JR東日本 11333 JR湘南新宿ライン 1133312 東戸塚 横浜市戸塚区品濃町 139.556794 35.430353 -2 JR東日本 11333 JR湘南新宿ライン 1133313 戸塚 横浜市戸塚区戸塚町 139.534282 35.400432 -2 JR東日本 11333 JR湘南新宿ライン 1133314 大船 鎌倉市大船1丁目 139.531127 35.353466 -2 JR東日本 11333 JR湘南新宿ライン 1133315 武蔵小杉 川崎市中原区小杉町三丁目492 139.65963 35.57669 -2 JR東日本 11333 JR湘南新宿ライン 1133316 浦和 さいたま市浦和区高砂1丁目 139.657109 35.858496 -18 東京メトロ 28001 東京メトロ銀座線 2800101 浅草 東京都台東区 139.797592 35.710733 -18 東京メトロ 28001 東京メトロ銀座線 2800102 田原町 台東区西浅草1-1-18 139.790897 35.709897 -18 東京メトロ 28001 東京メトロ銀座線 2800103 稲荷町 台東区東上野3-33-11 139.782593 35.711273 -18 東京メトロ 28001 東京メトロ銀座線 2800104 上野 東京都台東区東上野三丁目19-6 139.777122 35.711482 -18 東京メトロ 28001 東京メトロ銀座線 2800105 上野広小路 台東区上野3-29-3 139.772877 35.70768 -18 東京メトロ 28001 東京メトロ銀座線 2800106 末広町 千代田区外神田4-7-3 139.771713 35.702972 -18 東京メトロ 28001 東京メトロ銀座線 2800107 神田 東京都千代田区神田須田町一丁目16 139.770899 35.693587 -18 東京メトロ 28001 東京メトロ銀座線 2800108 三越前 中央区日本橋室町1-8-1 139.773594 35.687101 -18 東京メトロ 28001 東京メトロ銀座線 2800109 日本橋 中央区日本橋1丁目 139.773516 35.682078 -18 東京メトロ 28001 東京メトロ銀座線 2800110 京橋 中央区京橋2-2-10 139.770126 35.676856 -18 東京メトロ 28001 東京メトロ銀座線 2800111 銀座 中央区銀座4-1-2 139.763965 35.671989 -18 東京メトロ 28001 東京メトロ銀座線 2800112 新橋 東京都港区新橋二丁目17-5 139.758432 35.667434 -18 東京メトロ 28001 東京メトロ銀座線 2800113 虎ノ門 港区虎ノ門1-1-21 139.749832 35.670236 -18 東京メトロ 28001 東京メトロ銀座線 2800114 溜池山王 千代田区永田町2-11-1 139.741419 35.673621 -18 東京メトロ 28001 東京メトロ銀座線 2800115 赤坂見附 港区赤坂3-1-6 139.737047 35.677021 -18 東京メトロ 28001 東京メトロ銀座線 2800116 青山一丁目 港区南青山1-1-19 139.724159 35.672765 -18 東京メトロ 28001 東京メトロ銀座線 2800117 外苑前 港区北青山2-7-16 139.717857 35.670527 -18 東京メトロ 28001 東京メトロ銀座線 2800118 表参道 港区北青山3丁目 139.712314 35.665247 -18 東京メトロ 28001 東京メトロ銀座線 2800119 渋谷 東京都渋谷区道玄坂一丁目1-1 139.701 35.659066 -18 東京メトロ 28002 東京メトロ丸ノ内線 2800201 池袋 東京都豊島区 139.711086 35.730256 -18 東京メトロ 28002 東京メトロ丸ノ内線 2800202 新大塚 文京区大塚4-51-5 139.729971 35.72569 -18 東京メトロ 28002 東京メトロ丸ノ内線 2800203 茗荷谷 文京区小日向4-6-15 139.737184 35.716989 -18 東京メトロ 28002 東京メトロ丸ノ内線 2800204 後楽園 文京区春日1-2-3 139.751864 35.707898 -18 東京メトロ 28002 東京メトロ丸ノ内線 2800205 本郷三丁目 文京区本郷2-39-1 139.759914 35.706671 -18 東京メトロ 28002 東京メトロ丸ノ内線 2800206 御茶ノ水 千代田区神田駿河台2丁目 139.763952 35.700614 -18 東京メトロ 28002 東京メトロ丸ノ内線 2800207 淡路町 千代田区神田淡路町1-2 139.767575 35.695434 -18 東京メトロ 28002 東京メトロ丸ノ内線 2800208 大手町 千代田区大手町1丁目 139.7662 35.686564 -18 東京メトロ 28002 東京メトロ丸ノ内線 2800209 東京 東京都千代田区丸の内一丁目 139.764708 35.681753 -18 東京メトロ 28002 東京メトロ丸ノ内線 2800210 銀座 中央区銀座4-1-2 139.763965 35.671989 -18 東京メトロ 28002 東京メトロ丸ノ内線 2800211 霞ケ関 千代田区霞が関2丁目 139.750899 35.673838 -18 東京メトロ 28002 東京メトロ丸ノ内線 2800212 国会議事堂前 千代田区永田町1丁目 139.745219 35.67393 -18 東京メトロ 28002 東京メトロ丸ノ内線 2800213 赤坂見附 港区赤坂3-1-6 139.737047 35.677021 -18 東京メトロ 28002 東京メトロ丸ノ内線 2800214 四ツ谷 新宿区四谷1丁目 139.729947 35.684586 -18 東京メトロ 28002 東京メトロ丸ノ内線 2800215 四谷三丁目 新宿区四谷3-8 139.720103 35.687958 -18 東京メトロ 28002 東京メトロ丸ノ内線 2800216 新宿御苑前 新宿区新宿1-8-1 139.71069 35.688588 -18 東京メトロ 28002 東京メトロ丸ノ内線 2800217 新宿三丁目 新宿区新宿3-14-1 139.704895 35.690847 -18 東京メトロ 28002 東京メトロ丸ノ内線 2800218 新宿 東京都新宿区西新宿一丁目 西口地下街1号 139.700711 35.69235 -18 東京メトロ 28002 東京メトロ丸ノ内線 2800219 西新宿 新宿区西新宿6-7-51 139.692778 35.694298 -18 東京メトロ 28002 東京メトロ丸ノ内線 2800220 中野坂上 中野区中央2-1-2 139.68291 35.69792 -18 東京メトロ 28002 東京メトロ丸ノ内線 2800221 新中野 中野区中央4-2-15 139.66903 35.697491 -18 東京メトロ 28002 東京メトロ丸ノ内線 2800222 東高円寺 杉並区和田3-55-42 139.657822 35.697802 -18 東京メトロ 28002 東京メトロ丸ノ内線 2800223 新高円寺 杉並区高円寺南2-20-1 139.648068 35.697985 -18 東京メトロ 28002 東京メトロ丸ノ内線 2800224 南阿佐ケ谷 杉並区阿佐谷南1-15-7 139.63576 35.699624 -18 東京メトロ 28002 東京メトロ丸ノ内線 2800225 荻窪 杉並区上荻1丁目 139.620116 35.704304 -18 東京メトロ 28002 東京メトロ丸ノ内線 2800226 中野新橋 中野区弥生町2-26-8 139.673997 35.692123 -18 東京メトロ 28002 東京メトロ丸ノ内線 2800227 中野富士見町 中野区弥生町5-24-4 139.666933 35.690514 -18 東京メトロ 28002 東京メトロ丸ノ内線 2800228 方南町 杉並区堀ノ内1-1-1 139.656498 35.683496 -18 東京メトロ 28003 東京メトロ日比谷線 2800301 北千住 足立区千住旭町 139.804276 35.748916 -18 東京メトロ 28003 東京メトロ日比谷線 2800302 南千住 荒川区南千住4丁目 139.799273 35.733398 -18 東京メトロ 28003 東京メトロ日比谷線 2800303 三ノ輪 台東区三ノ輪2-14-7 139.791485 35.729623 -18 東京メトロ 28003 東京メトロ日比谷線 2800304 入谷 台東区入谷1-6-4 139.783924 35.719862 -18 東京メトロ 28003 東京メトロ日比谷線 2800305 上野 東京都台東区東上野三丁目19-6 139.777122 35.711482 -18 東京メトロ 28003 東京メトロ日比谷線 2800306 仲御徒町 台東区上野5-24-12 139.776138 35.706649 -18 東京メトロ 28003 東京メトロ日比谷線 2800307 秋葉原 東京都千代田区神田佐久間町一丁目21 139.775459 35.698162 -18 東京メトロ 28003 東京メトロ日比谷線 2800308 小伝馬町 中央区日本橋小伝馬町11-1 139.778433 35.690737 -18 東京メトロ 28003 東京メトロ日比谷線 2800309 人形町 中央区日本橋人形町2-6-5 139.782285 35.686307 -18 東京メトロ 28003 東京メトロ日比谷線 2800310 茅場町 中央区日本橋茅場町1-4-6 139.780005 35.679752 -18 東京メトロ 28003 東京メトロ日比谷線 2800311 八丁堀 中央区八丁堀3丁目 139.776982 35.674851 -18 東京メトロ 28003 東京メトロ日比谷線 2800312 築地 中央区築地3-15-1 139.772603 35.668115 -18 東京メトロ 28003 東京メトロ日比谷線 2800313 東銀座 中央区銀座4-12-15 139.767253 35.669464 -18 東京メトロ 28003 東京メトロ日比谷線 2800314 銀座 中央区銀座4-1-2 139.763965 35.671989 -18 東京メトロ 28003 東京メトロ日比谷線 2800315 日比谷 千代田区有楽町1丁目 139.76017 35.67459 -18 東京メトロ 28003 東京メトロ日比谷線 2800316 霞ケ関 千代田区霞が関2丁目 139.750899 35.673838 -18 東京メトロ 28003 東京メトロ日比谷線 2800317 神谷町 港区虎ノ門5-12-11 139.745069 35.662978 -18 東京メトロ 28003 東京メトロ日比谷線 2800318 六本木 港区六本木6-1-25 139.731443 35.662836 -18 東京メトロ 28003 東京メトロ日比谷線 2800319 広尾 港区南麻布5-10-28 139.722202 35.652279 -18 東京メトロ 28003 東京メトロ日比谷線 2800320 恵比寿 東京都渋谷区恵比寿南一丁目5-5 139.708988 35.647332 -18 東京メトロ 28003 東京メトロ日比谷線 2800321 中目黒 目黒区上目黒3-4-1 139.698621 35.643854 -18 東京メトロ 28004 東京メトロ東西線 2800401 中野 中野区中野5丁目 139.665835 35.705765 -18 東京メトロ 28004 東京メトロ東西線 2800402 落合 新宿区上落合2-13-7 139.687284 35.710976 -18 東京メトロ 28004 東京メトロ東西線 2800403 高田馬場 東京都新宿区高田馬場一丁目35-1 139.704745 35.713338 -18 東京メトロ 28004 東京メトロ東西線 2800404 早稲田 東京都新宿区 139.721319 35.705723 -18 東京メトロ 28004 東京メトロ東西線 2800405 神楽坂 新宿区矢来町112 139.734546 35.70379 -18 東京メトロ 28004 東京メトロ東西線 2800406 飯田橋 東京都千代田区飯田橋四丁目10-3 139.745986 35.701725 -18 東京メトロ 28004 東京メトロ東西線 2800407 九段下 千代田区九段南1-6-1 139.751948 35.695589 -18 東京メトロ 28004 東京メトロ東西線 2800408 竹橋 千代田区一ツ橋1-1-1 139.756817 35.690662 -18 東京メトロ 28004 東京メトロ東西線 2800409 大手町 千代田区大手町1丁目 139.766086 35.684801 -18 東京メトロ 28004 東京メトロ東西線 2800410 日本橋 中央区日本橋1丁目 139.773516 35.682078 -18 東京メトロ 28004 東京メトロ東西線 2800411 茅場町 中央区日本橋茅場町1-4-6 139.780005 35.679752 -18 東京メトロ 28004 東京メトロ東西線 2800412 門前仲町 江東区門前仲町1丁目 139.796209 35.671851 -18 東京メトロ 28004 東京メトロ東西線 2800413 木場 江東区木場5-5-1 139.807042 35.669351 -18 東京メトロ 28004 東京メトロ東西線 2800414 東陽町 江東区東陽4-2-1 139.817596 35.669629 -18 東京メトロ 28004 東京メトロ東西線 2800415 南砂町 江東区南砂3-11-85 139.83065 35.668796 -18 東京メトロ 28004 東京メトロ東西線 2800416 西葛西 江戸川区西葛西6-14-1 139.859259 35.664631 -18 東京メトロ 28004 東京メトロ東西線 2800417 葛西 江戸川区中葛西5-43-11 139.872458 35.663554 -18 東京メトロ 28004 東京メトロ東西線 2800418 浦安 浦安市北栄1-13-1 139.893193 35.665932 -18 東京メトロ 28004 東京メトロ東西線 2800419 南行徳 市川市相之川4-17-1 139.902311 35.672687 -18 東京メトロ 28004 東京メトロ東西線 2800420 行徳 市川市行徳駅前2-4-1 139.914254 35.682686 -18 東京メトロ 28004 東京メトロ東西線 2800421 妙典 市川市富浜1-2-10 139.924209 35.690935 -18 東京メトロ 28004 東京メトロ東西線 2800422 原木中山 船橋市本中山7-7-1 139.942029 35.703517 -18 東京メトロ 28004 東京メトロ東西線 2800423 西船橋 船橋市西船4丁目 139.958972 35.707127 -18 東京メトロ 28005 東京メトロ千代田線 2800501 北綾瀬 足立区谷中2丁目 139.832035 35.777117 -18 東京メトロ 28005 東京メトロ千代田線 2800502 綾瀬 足立区綾瀬3丁目 139.825019 35.762222 -18 東京メトロ 28005 東京メトロ千代田線 2800503 北千住 足立区千住旭町 139.804276 35.748916 -18 東京メトロ 28005 東京メトロ千代田線 2800504 町屋 荒川区町屋1丁目 139.780501 35.742733 -18 東京メトロ 28005 東京メトロ千代田線 2800505 西日暮里 東京都荒川区西日暮里五丁目14-1 139.766511 35.732257 -18 東京メトロ 28005 東京メトロ千代田線 2800506 千駄木 文京区千駄木2丁目 139.763243 35.725549 -18 東京メトロ 28005 東京メトロ千代田線 2800507 根津 文京区根津1丁目 139.765655 35.7174 -18 東京メトロ 28005 東京メトロ千代田線 2800508 湯島 文京区湯島3丁目 139.769916 35.708243 -18 東京メトロ 28005 東京メトロ千代田線 2800509 新御茶ノ水 千代田区神田駿河台3丁目 139.766014 35.698072 -18 東京メトロ 28005 東京メトロ千代田線 2800510 大手町 千代田区大手町1丁目 139.763399 35.686154 -18 東京メトロ 28005 東京メトロ千代田線 2800511 二重橋前 千代田区丸の内2丁目 139.761948 35.681071 -18 東京メトロ 28005 東京メトロ千代田線 2800512 日比谷 千代田区有楽町1丁目 139.758732 35.674241 -18 東京メトロ 28005 東京メトロ千代田線 2800513 霞ケ関 千代田区霞が関2丁目 139.750899 35.673838 -18 東京メトロ 28005 東京メトロ千代田線 2800514 国会議事堂前 千代田区永田町1丁目 139.745219 35.67393 -18 東京メトロ 28005 東京メトロ千代田線 2800515 赤坂 港区赤坂5丁目 139.738348 35.67323 -18 東京メトロ 28005 東京メトロ千代田線 2800516 乃木坂 港区南青山1丁目 139.726215 35.666572 -18 東京メトロ 28005 東京メトロ千代田線 2800517 表参道 港区北青山3丁目 139.712314 35.665247 -18 東京メトロ 28005 東京メトロ千代田線 2800518 明治神宮前〈原宿〉 渋谷区神宮前1丁目 139.703995 35.669071 -18 東京メトロ 28005 東京メトロ千代田線 2800519 代々木公園 渋谷区富ケ谷1丁目 139.689099 35.669187 -18 東京メトロ 28005 東京メトロ千代田線 2800520 代々木上原 渋谷区西原3丁目 139.680153 35.669159 -18 東京メトロ 28006 東京メトロ有楽町線 2800601 和光市 埼玉県和光市本町4-6 139.612434 35.788507 -18 東京メトロ 28006 東京メトロ有楽町線 2800602 地下鉄成増 東京都板橋区成増二丁目11-3 139.631497 35.776557 -18 東京メトロ 28006 東京メトロ有楽町線 2800603 地下鉄赤塚 東京都練馬区北町八丁目37-16 139.644021 35.769939 -18 東京メトロ 28006 東京メトロ有楽町線 2800604 平和台 東京都練馬区早宮2-17-48 139.653762 35.757863 -18 東京メトロ 28006 東京メトロ有楽町線 2800605 氷川台 東京都練馬区氷川台三丁目38-18 139.665567 35.74955 -18 東京メトロ 28006 東京メトロ有楽町線 2800606 小竹向原 東京都練馬区小竹町二丁目16-15 139.678572 35.743803 -18 東京メトロ 28006 東京メトロ有楽町線 2800607 千川 東京都豊島区要町三丁目10-7 139.689271 35.738229 -18 東京メトロ 28006 東京メトロ有楽町線 2800608 要町 東京都豊島区要町一丁目1-10 139.698715 35.73323 -18 東京メトロ 28006 東京メトロ有楽町線 2800609 池袋 東京都豊島区西池袋三丁目28-14 139.710088 35.729565 -18 東京メトロ 28006 東京メトロ有楽町線 2800610 東池袋 東京都豊島区東池袋四丁目4-4 139.719546 35.725732 -18 東京メトロ 28006 東京メトロ有楽町線 2800611 護国寺 東京都文京区大塚五丁目40-8 139.72754 35.719044 -18 東京メトロ 28006 東京メトロ有楽町線 2800612 江戸川橋 東京都文京区関口一丁目19-6 139.733538 35.709495 -18 東京メトロ 28006 東京メトロ有楽町線 2800613 飯田橋 東京都新宿区神楽坂一丁目13 139.743669 35.701934 -18 東京メトロ 28006 東京メトロ有楽町線 2800614 市ケ谷 東京都新宿区市谷田町一丁目1 139.73647 35.691958 -18 東京メトロ 28006 東京メトロ有楽町線 2800615 麹町 東京都千代田区麹町三丁目2 139.737613 35.684006 -18 東京メトロ 28006 東京メトロ有楽町線 2800616 永田町 東京都千代田区永田町一丁目11-28 139.740258 35.678757 -18 東京メトロ 28006 東京メトロ有楽町線 2800617 桜田門 東京都千代田区霞が関二丁目1-1 139.75149 35.677405 -18 東京メトロ 28006 東京メトロ有楽町線 2800618 有楽町 東京都千代田区有楽町一丁目11-1 139.763265 35.675714 -18 東京メトロ 28006 東京メトロ有楽町線 2800619 銀座一丁目 東京都中央区銀座一丁目7-12 139.767045 35.67435 -18 東京メトロ 28006 東京メトロ有楽町線 2800620 新富町 東京都中央区築地一丁目1-1 139.773711 35.670462 -18 東京メトロ 28006 東京メトロ有楽町線 2800621 月島 東京都中央区月島一丁目3-9 139.784233 35.664871 -18 東京メトロ 28006 東京メトロ有楽町線 2800622 豊洲 東京都江東区豊洲四丁目1-1 139.79621 35.654908 -18 東京メトロ 28006 東京メトロ有楽町線 2800623 辰巳 東京都江東区辰巳一丁目1-44 139.81052 35.645576 -18 東京メトロ 28006 東京メトロ有楽町線 2800624 新木場 東京都江東区新木場一丁目6 139.826254 35.645832 -18 東京メトロ 28007 東京メトロ有楽町新線 2800701 新線池袋 東京都豊島区西池袋 139.710388 35.730645 -18 東京メトロ 28007 東京メトロ有楽町新線 2800702 小竹向原 東京都練馬区小竹町二丁目16-15 139.678572 35.743803 -18 東京メトロ 28008 東京メトロ半蔵門線 2800801 渋谷 東京都渋谷区道玄坂二丁目1-1 139.701 35.659066 -18 東京メトロ 28008 東京メトロ半蔵門線 2800802 表参道 港区北青山3丁目 139.712314 35.665247 -18 東京メトロ 28008 東京メトロ半蔵門線 2800803 青山一丁目 港区南青山1-1-19 139.724159 35.672765 -18 東京メトロ 28008 東京メトロ半蔵門線 2800804 永田町 東京都千代田区永田町一丁目11-29 139.740258 35.678757 -18 東京メトロ 28008 東京メトロ半蔵門線 2800805 半蔵門 千代田区麹町1-6 139.74163 35.685703 -18 東京メトロ 28008 東京メトロ半蔵門線 2800806 九段下 千代田区九段南1-6-1 139.751948 35.695589 -18 東京メトロ 28008 東京メトロ半蔵門線 2800807 神保町 千代田区神田神保町2-2 139.757606 35.695966 -18 東京メトロ 28008 東京メトロ半蔵門線 2800808 大手町 千代田区大手町1丁目 139.764107 35.68686 -18 東京メトロ 28008 東京メトロ半蔵門線 2800809 三越前 中央区日本橋室町1-8-1 139.773147 35.684908 -18 東京メトロ 28008 東京メトロ半蔵門線 2800810 水天宮前 中央区日本橋蛎殻町2-1-1 139.785377 35.682683 -18 東京メトロ 28008 東京メトロ半蔵門線 2800811 清澄白河 江東区白河1-7-14 139.798851 35.682105 -18 東京メトロ 28008 東京メトロ半蔵門線 2800812 錦糸町 墨田区江東橋3丁目 139.814941 35.697578 -18 東京メトロ 28008 東京メトロ半蔵門線 2800813 押上〈スカイツリー前〉 墨田区押上一丁目 139.812935 35.710702 -18 東京メトロ 28008 東京メトロ半蔵門線 2800814 住吉 江東区住吉2-23-12 139.815681 35.689073 -18 東京メトロ 28009 東京メトロ南北線 2800901 赤羽岩淵 北区赤羽1-52-8 139.722103 35.783417 -18 東京メトロ 28009 東京メトロ南北線 2800902 志茂 北区志茂2-1-18 139.732599 35.777948 -18 東京メトロ 28009 東京メトロ南北線 2800903 王子神谷 北区王子5-2-11 139.735933 35.765172 -18 東京メトロ 28009 東京メトロ南北線 2800904 王子 北区王子1丁目 139.737618 35.753966 -18 東京メトロ 28009 東京メトロ南北線 2800905 西ケ原 東京都北区西ヶ原二丁目3-8 139.742322 35.746008 -18 東京メトロ 28009 東京メトロ南北線 2800906 駒込 東京都豊島区駒込二丁目 139.746442 35.736959 -18 東京メトロ 28009 東京メトロ南北線 2800907 本駒込 文京区向丘2-37-1 139.753828 35.724155 -18 東京メトロ 28009 東京メトロ南北線 2800908 東大前 文京区向丘1-19-2 139.758025 35.717633 -18 東京メトロ 28009 東京メトロ南北線 2800909 後楽園 文京区春日1-2-3 139.751864 35.707898 -18 東京メトロ 28009 東京メトロ南北線 2800910 飯田橋 東京都新宿区神楽坂一丁目13 139.743669 35.701934 -18 東京メトロ 28009 東京メトロ南北線 2800911 市ケ谷 東京都千代田区五番町2-1 139.736642 35.691295 -18 東京メトロ 28009 東京メトロ南北線 2800912 四ツ谷 新宿区四谷1丁目 139.72955 35.686032 -18 東京メトロ 28009 東京メトロ南北線 2800913 永田町 東京都千代田区永田町一丁目11-28 139.740258 35.678757 -18 東京メトロ 28009 東京メトロ南北線 2800914 溜池山王 千代田区永田町2-11-1 139.741419 35.673621 -18 東京メトロ 28009 東京メトロ南北線 2800915 六本木一丁目 港区六本木1-4-1 139.739 35.665595 -18 東京メトロ 28009 東京メトロ南北線 2800916 麻布十番 港区麻布十番4-4-9 139.737051 35.654682 -18 東京メトロ 28009 東京メトロ南北線 2800917 白金高輪 港区高輪1-3-20 139.734104 35.642903 -18 東京メトロ 28009 東京メトロ南北線 2800918 白金台 港区白金台3-2 139.726133 35.637917 -18 東京メトロ 28009 東京メトロ南北線 2800919 目黒 東京都品川区上大崎四丁目2-1 139.7155 35.633272 -18 東京メトロ 28010 東京メトロ副都心線 2801001 和光市 埼玉県和光市本町4-6 139.612434 35.788507 -18 東京メトロ 28010 東京メトロ副都心線 2801002 地下鉄成増 東京都板橋区成増二丁目11-3 139.631497 35.776557 -18 東京メトロ 28010 東京メトロ副都心線 2801003 地下鉄赤塚 東京都練馬区北町八丁目37-16 139.644021 35.769939 -18 東京メトロ 28010 東京メトロ副都心線 2801004 平和台 東京都練馬区早宮2-17-48 139.653762 35.757863 -18 東京メトロ 28010 東京メトロ副都心線 2801005 氷川台 東京都練馬区氷川台三丁目38-18 139.665567 35.74955 -18 東京メトロ 28010 東京メトロ副都心線 2801006 小竹向原 東京都練馬区小竹町二丁目16-15 139.678572 35.743803 -18 東京メトロ 28010 東京メトロ副都心線 2801007 千川 東京都豊島区要町三丁目10-7 139.689271 35.738229 -18 東京メトロ 28010 東京メトロ副都心線 2801008 要町 東京都豊島区要町一丁目1-10 139.698715 35.73323 -18 東京メトロ 28010 東京メトロ副都心線 2801009 池袋 東京都豊島区 139.708291 35.731464 -18 東京メトロ 28010 東京メトロ副都心線 2801010 雑司が谷 豊島区雑司が谷二丁目 139.714795 35.720233 -18 東京メトロ 28010 東京メトロ副都心線 2801011 西早稲田 新宿区西早稲田二丁目 139.709101 35.708242 -18 東京メトロ 28010 東京メトロ副都心線 2801012 東新宿 新宿区新宿7-27-3 139.707593 35.698915 -18 東京メトロ 28010 東京メトロ副都心線 2801013 新宿三丁目 新宿区新宿3-14-1 139.704828 35.690853 -18 東京メトロ 28010 東京メトロ副都心線 2801014 北参道 渋谷区千駄ヶ谷4丁目 139.705453 35.678459 -18 東京メトロ 28010 東京メトロ副都心線 2801015 明治神宮前〈原宿〉 渋谷区神宮前1丁目 139.705367 35.668497 -18 東京メトロ 28010 東京メトロ副都心線 2801016 渋谷 東京都渋谷区道玄坂二丁目1-1 139.702417 35.659545 -119 東京都交通局 99301 都営大江戸線 9930101 都庁前 新宿区西新宿2-8-1 139.69257 35.690551 -119 東京都交通局 99301 都営大江戸線 9930102 新宿西口 新宿区西新宿1-3-17 139.699155 35.693315 -119 東京都交通局 99301 都営大江戸線 9930103 東新宿 新宿区新宿7-27-3 139.707549 35.69792 -119 東京都交通局 99301 都営大江戸線 9930104 若松河田 新宿区河田町10-10 139.718184 35.699218 -119 東京都交通局 99301 都営大江戸線 9930105 牛込柳町 新宿区原町2-32 139.725027 35.699518 -119 東京都交通局 99301 都営大江戸線 9930106 牛込神楽坂 新宿区箪笥町15 139.735802 35.700851 -119 東京都交通局 99301 都営大江戸線 9930107 飯田橋 東京都文京区後楽一丁目9-5 139.744999 35.702927 -119 東京都交通局 99301 都営大江戸線 9930108 春日 文京区春日1-16-17 139.75325 35.709598 -119 東京都交通局 99301 都営大江戸線 9930109 本郷三丁目 文京区本郷2-39-1 139.760095 35.707462 -119 東京都交通局 99301 都営大江戸線 9930110 上野御徒町 台東区上野5-26-6 139.774332 35.707893 -119 東京都交通局 99301 都営大江戸線 9930111 新御徒町 台東区元浅草1-5-2 139.781958 35.707045 -119 東京都交通局 99301 都営大江戸線 9930112 蔵前 台東区蔵前2-3-1 139.790931 35.703236 -119 東京都交通局 99301 都営大江戸線 9930113 両国 墨田区横網1丁目 139.797421 35.696881 -119 東京都交通局 99301 都営大江戸線 9930114 森下 江東区森下2-17-17 139.797042 35.68796 -119 東京都交通局 99301 都営大江戸線 9930115 清澄白河 江東区白河1-7-14 139.798851 35.682105 -119 東京都交通局 99301 都営大江戸線 9930116 門前仲町 江東区門前仲町1丁目 139.796209 35.671851 -119 東京都交通局 99301 都営大江戸線 9930117 月島 東京都中央区月島一丁目3-9 139.784233 35.664871 -119 東京都交通局 99301 都営大江戸線 9930118 勝どき 中央区勝どき2-10-15 139.776442 35.658507 -119 東京都交通局 99301 都営大江戸線 9930119 築地市場 中央区築地5-1-2 139.766915 35.664895 -119 東京都交通局 99301 都営大江戸線 9930120 汐留 港区東新橋1丁目5 139.760642 35.663703 -119 東京都交通局 99301 都営大江戸線 9930121 大門 港区浜松町1-27-12 139.75466 35.656785 -119 東京都交通局 99301 都営大江戸線 9930122 赤羽橋 港区東麻布1-28-13 139.743642 35.655007 -119 東京都交通局 99301 都営大江戸線 9930123 麻布十番 港区麻布十番4-4-9 139.736116 35.656503 -119 東京都交通局 99301 都営大江戸線 9930124 六本木 港区六本木6-1-25 139.731567 35.663921 -119 東京都交通局 99301 都営大江戸線 9930125 青山一丁目 港区南青山1-1-19 139.72396 35.672929 -119 東京都交通局 99301 都営大江戸線 9930126 国立競技場 新宿区霞ケ丘町10-3 139.714932 35.679831 -119 東京都交通局 99301 都営大江戸線 9930127 代々木 東京都渋谷区代々木一丁目35-5 139.701666 35.683218 -119 東京都交通局 99301 都営大江戸線 9930128 新宿 東京都渋谷区代々木二丁目1-1 139.698812 35.68869 -119 東京都交通局 99301 都営大江戸線 9930129 西新宿五丁目 新宿区西新宿5-25-9 139.684304 35.689798 -119 東京都交通局 99301 都営大江戸線 9930130 中野坂上 中野区中央2-1-2 139.682279 35.69709 -119 東京都交通局 99301 都営大江戸線 9930131 東中野 中野区東中野4丁目 139.682987 35.706891 -119 東京都交通局 99301 都営大江戸線 9930132 中井 新宿区中落合1-19-1 139.686356 35.714035 -119 東京都交通局 99301 都営大江戸線 9930133 落合南長崎 新宿区西落合3-1-18 139.683303 35.723608 -119 東京都交通局 99301 都営大江戸線 9930134 新江古田 中野区江原町2-29-13 139.670653 35.732538 -119 東京都交通局 99301 都営大江戸線 9930135 練馬 練馬区練馬1-3-5 139.65477 35.737404 -119 東京都交通局 99301 都営大江戸線 9930136 豊島園 練馬区練馬4-16-5 139.64911 35.742067 -119 東京都交通局 99301 都営大江戸線 9930137 練馬春日町 練馬区春日町3-29-25 139.640236 35.751452 -119 東京都交通局 99301 都営大江戸線 9930138 光が丘 練馬区光が丘2-9-5 139.628603 35.758526 -119 東京都交通局 99302 都営浅草線 9930201 西馬込 大田区西馬込2-1-6 139.705942 35.586859 -119 東京都交通局 99302 都営浅草線 9930202 馬込 大田区北馬込2-31-9 139.711772 35.596435 -119 東京都交通局 99302 都営浅草線 9930203 中延 品川区中延4-5-5 139.713736 35.605769 -119 東京都交通局 99302 都営浅草線 9930204 戸越 品川区戸越3-4-17 139.716495 35.614633 -119 東京都交通局 99302 都営浅草線 9930205 五反田 東京都品川区東五反田一丁目26-14 139.724175 35.627102 -119 東京都交通局 99302 都営浅草線 9930206 高輪台 港区白金台2-26-7 139.730305 35.631679 -119 東京都交通局 99302 都営浅草線 9930207 泉岳寺 港区高輪2-16-34 139.74002 35.638692 -119 東京都交通局 99302 都営浅草線 9930208 三田 港区芝5-34-10 139.748775 35.64818 -119 東京都交通局 99302 都営浅草線 9930209 大門 港区浜松町1-27-12 139.75466 35.656785 -119 東京都交通局 99302 都営浅草線 9930210 新橋 東京都港区新橋二丁目21-1 139.759451 35.665577 -119 東京都交通局 99302 都営浅草線 9930211 東銀座 中央区銀座4-12-15 139.767253 35.669464 -119 東京都交通局 99302 都営浅草線 9930212 宝町 中央区京橋2-13-11 139.771767 35.675461 -119 東京都交通局 99302 都営浅草線 9930213 日本橋 中央区日本橋1丁目 139.775721 35.681688 -119 東京都交通局 99302 都営浅草線 9930214 人形町 中央区日本橋人形町2-6-5 139.782285 35.686307 -119 東京都交通局 99302 都営浅草線 9930215 東日本橋 中央区東日本橋3-11-8 139.784821 35.692126 -119 東京都交通局 99302 都営浅草線 9930216 浅草橋 台東区浅草橋1丁目 139.786305 35.697451 -119 東京都交通局 99302 都営浅草線 9930217 蔵前 台東区蔵前2-3-1 139.790931 35.703236 -119 東京都交通局 99302 都営浅草線 9930218 浅草 東京都台東区 139.79697 35.709461 -119 東京都交通局 99302 都営浅草線 9930219 本所吾妻橋 墨田区吾妻橋3-7-16 139.804624 35.70858 -119 東京都交通局 99302 都営浅草線 9930220 押上(スカイツリー前) 墨田区押上一丁目 139.812935 35.710702 -119 東京都交通局 99303 都営三田線 9930301 目黒 東京都品川区上大崎四丁目2-1 139.7155 35.633272 -119 東京都交通局 99303 都営三田線 9930302 白金台 港区白金台3-2 139.726133 35.637917 -119 東京都交通局 99303 都営三田線 9930303 白金高輪 港区高輪1-3-20 139.734104 35.642903 -119 東京都交通局 99303 都営三田線 9930304 三田 港区芝5-34-10 139.748775 35.64818 -119 東京都交通局 99303 都営三田線 9930305 芝公園 港区芝公園4-8-14 139.749824 35.654074 -119 東京都交通局 99303 都営三田線 9930306 御成門 港区西新橋3-24-6 139.751535 35.661215 -119 東京都交通局 99303 都営三田線 9930307 内幸町 千代田区内幸町2-2-3 139.75561 35.66975 -119 東京都交通局 99303 都営三田線 9930308 日比谷 千代田区有楽町1丁目 139.759998 35.676036 -119 東京都交通局 99303 都営三田線 9930309 大手町 千代田区大手町1丁目 139.762959 35.684856 -119 東京都交通局 99303 都営三田線 9930310 神保町 千代田区神田神保町2-2 139.75812 35.695492 -119 東京都交通局 99303 都営三田線 9930311 水道橋 千代田区三崎町2丁目 139.75516 35.703398 -119 東京都交通局 99303 都営三田線 9930312 春日 文京区春日1-16-17 139.75325 35.709598 -119 東京都交通局 99303 都営三田線 9930313 白山 文京区白山5-36-10 139.752136 35.721408 -119 東京都交通局 99303 都営三田線 9930314 千石 文京区千石1-29-13 139.744792 35.727957 -119 東京都交通局 99303 都営三田線 9930315 巣鴨 東京都豊島区巣鴨 139.738519 35.733502 -119 東京都交通局 99303 都営三田線 9930316 西巣鴨 豊島区西巣鴨3-25-13 139.728712 35.743508 -119 東京都交通局 99303 都営三田線 9930317 新板橋 板橋区板橋1-53-17 139.720101 35.748785 -119 東京都交通局 99303 都営三田線 9930318 板橋区役所前 板橋区板橋2-66-17 139.710102 35.751284 -119 東京都交通局 99303 都営三田線 9930319 板橋本町 板橋区大和町17-1 139.705535 35.761339 -119 東京都交通局 99303 都営三田線 9930320 本蓮沼 板橋区蓮沼町19-8 139.702324 35.768782 -119 東京都交通局 99303 都営三田線 9930321 志村坂上 板橋区志村1-14-13 139.69538 35.775725 -119 東京都交通局 99303 都営三田線 9930322 志村三丁目 板橋区志村3-23-1 139.685937 35.777391 -119 東京都交通局 99303 都営三田線 9930323 蓮根 板橋区蓮根2-31-30 139.678993 35.784335 -119 東京都交通局 99303 都営三田線 9930324 西台 板橋区高島平9-1-1 139.673971 35.78699 -119 東京都交通局 99303 都営三田線 9930325 高島平 板橋区高島平8-2-1 139.661216 35.789056 -119 東京都交通局 99303 都営三田線 9930326 新高島平 板橋区高島平7-1 139.654275 35.790189 -119 東京都交通局 99303 都営三田線 9930327 西高島平 板橋区高島平6-1 139.64594 35.791833 -119 東京都交通局 99304 都営新宿線 9930401 新宿 東京都新宿区西新宿一丁目18 139.698812 35.68869 -119 東京都交通局 99304 都営新宿線 9930402 新宿三丁目 新宿区新宿3-14-1 139.706271 35.690616 -119 東京都交通局 99304 都営新宿線 9930403 曙橋 新宿区住吉町7-1 139.722881 35.692402 -119 東京都交通局 99304 都営新宿線 9930404 市ヶ谷 東京都新宿区市谷田町一丁目1 139.735794 35.692594 -119 東京都交通局 99304 都営新宿線 9930405 九段下 千代田区九段南1-6-1 139.751948 35.695589 -119 東京都交通局 99304 都営新宿線 9930406 神保町 千代田区神田神保町2-2 139.757606 35.695966 -119 東京都交通局 99304 都営新宿線 9930407 小川町 千代田区神田小川町1-6 139.767551 35.695487 -119 東京都交通局 99304 都営新宿線 9930408 岩本町 千代田区神田岩本町1 139.775866 35.695534 -119 東京都交通局 99304 都営新宿線 9930409 馬喰横山 中央区日本橋横山町4-13 139.782768 35.69212 -119 東京都交通局 99304 都営新宿線 9930410 浜町 中央区日本橋浜町2-59-3 139.788154 35.688516 -119 東京都交通局 99304 都営新宿線 9930411 森下 江東区森下2-17-17 139.797042 35.68796 -119 東京都交通局 99304 都営新宿線 9930412 菊川 墨田区菊川3-16-2 139.806016 35.688379 -119 東京都交通局 99304 都営新宿線 9930413 住吉 江東区住吉2-23-12 139.815681 35.689073 -119 東京都交通局 99304 都営新宿線 9930414 西大島 江東区大島2-41-19 139.826206 35.689349 -119 東京都交通局 99304 都営新宿線 9930415 大島 江東区大島5-10-8 139.83565 35.689905 -119 東京都交通局 99304 都営新宿線 9930416 東大島 江東区大島9-3-14 139.845963 35.690355 -119 東京都交通局 99304 都営新宿線 9930417 船堀 江戸川区船堀3-6-1 139.864258 35.683795 -119 東京都交通局 99304 都営新宿線 9930418 一之江 江戸川区春江町4-2 139.882934 35.686055 -119 東京都交通局 99304 都営新宿線 9930419 瑞江 江戸川区瑞江2-2-1 139.89761 35.693318 -119 東京都交通局 99304 都営新宿線 9930420 篠崎 江戸川区篠崎町7-27-1 139.903698 35.706017 -119 東京都交通局 99304 都営新宿線 9930421 本八幡 市川市八幡2丁目 139.926628 35.722929 -119 東京都交通局 99305 都電荒川線 9930501 三ノ輪橋 荒川区南千住1 139.791412 35.732248 -119 東京都交通局 99305 都電荒川線 9930502 荒川一中前 荒川区南千住1-1 139.788988 35.733659 -119 東京都交通局 99305 都電荒川線 9930503 荒川区役所前 荒川区荒川1 139.786456 35.73493 -119 東京都交通局 99305 都電荒川線 9930504 荒川二丁目 荒川区荒川2 139.784696 35.738623 -119 東京都交通局 99305 都電荒川線 9930505 荒川七丁目 荒川区荒川7 139.78417 35.741975 -119 東京都交通局 99305 都電荒川線 9930506 町屋駅前 荒川区荒川7 139.781145 35.74275 -119 東京都交通局 99305 都電荒川線 9930507 町屋二丁目 荒川区荒川6 139.776625 35.743837 -119 東京都交通局 99305 都電荒川線 9930508 東尾久三丁目 荒川区東尾久3 139.774386 35.745398 -119 東京都交通局 99305 都電荒川線 9930509 熊野前 荒川区東尾久5 139.769204 35.749212 -119 東京都交通局 99305 都電荒川線 9930510 宮ノ前 荒川区東尾久5 139.764955 35.750135 -119 東京都交通局 99305 都電荒川線 9930511 小台 荒川区西尾久5 139.761779 35.750579 -119 東京都交通局 99305 都電荒川線 9930512 荒川遊園地前 荒川区西尾久5 139.757767 35.750744 -119 東京都交通局 99305 都電荒川線 9930513 荒川車庫前 荒川区西尾久7 139.752617 35.750909 -119 東京都交通局 99305 都電荒川線 9930514 梶原 北区堀船3 139.747403 35.751162 -119 東京都交通局 99305 都電荒川線 9930515 栄町 北区栄町 139.742124 35.750909 -119 東京都交通局 99305 都電荒川線 9930516 王子駅前 北区王子1 139.737661 35.753199 -119 東京都交通局 99305 都電荒川線 9930517 飛鳥山 北区滝野川1 139.737382 35.750248 -119 東京都交通局 99305 都電荒川線 9930518 滝野川一丁目 北区滝野川1 139.735376 35.747374 -119 東京都交通局 99305 都電荒川線 9930519 西ヶ原四丁目 東京都北区西ヶ原四丁目 139.732779 35.744501 -119 東京都交通局 99305 都電荒川線 9930520 新庚申塚 豊島区西巣鴨4 139.730451 35.741348 -119 東京都交通局 99305 都電荒川線 9930521 庚申塚 豊島区西巣鴨3 139.729743 35.739563 -119 東京都交通局 99305 都電荒川線 9930522 巣鴨新田 豊島区西巣鴨1 139.727769 35.735488 -119 東京都交通局 99305 都電荒川線 9930523 大塚駅前 豊島区南大塚3 139.729593 35.732082 -119 東京都交通局 99305 都電荒川線 9930524 向原 豊島区南大塚3 139.724894 35.728938 -119 東京都交通局 99305 都電荒川線 9930525 東池袋四丁目 豊島区東池袋5 139.720012 35.72528 -119 東京都交通局 99305 都電荒川線 9930526 都電雑司ヶ谷 東京都豊島区南池袋 139.718006 35.724261 -119 東京都交通局 99305 都電荒川線 9930527 鬼子母神前 豊島区雑司が谷2 139.714916 35.720403 -119 東京都交通局 99305 都電荒川線 9930528 学習院下 豊島区高田2 139.71247 35.716248 -119 東京都交通局 99305 都電荒川線 9930529 面影橋 新宿区西早稲田3 139.714444 35.712981 -119 東京都交通局 99305 都電荒川線 9930530 早稲田 東京都新宿区 139.718928 35.711848 -119 東京都交通局 99342 日暮里・舎人ライナー 9934201 日暮里 東京都荒川区西日暮里二丁目19-1 139.771287 35.727908 -119 東京都交通局 99342 日暮里・舎人ライナー 9934202 西日暮里 東京都荒川区西日暮里五丁目31-7 139.766857 35.731954 -119 東京都交通局 99342 日暮里・舎人ライナー 9934203 赤土小学校前 荒川区東尾久4-7-7 139.768989 35.742454 -119 東京都交通局 99342 日暮里・舎人ライナー 9934204 熊野前 荒川区東尾久5 139.769695 35.748972 -119 東京都交通局 99342 日暮里・舎人ライナー 9934205 足立小台 足立区小台1-20-1 139.770381 35.754658 -119 東京都交通局 99342 日暮里・舎人ライナー 9934206 扇大橋 足立区扇2-25-7 139.770808 35.763897 -119 東京都交通局 99342 日暮里・舎人ライナー 9934207 高野 足立区扇2-45-1 139.770679 35.768359 -119 東京都交通局 99342 日暮里・舎人ライナー 9934208 江北 足立区江北4-30-27 139.770306 35.774021 -119 東京都交通局 99342 日暮里・舎人ライナー 9934209 西新井大師西 足立区江北6-30-23 139.770094 35.781505 -119 東京都交通局 99342 日暮里・舎人ライナー 9934210 谷在家 足立区谷在家3-20-23 139.770043 35.788774 -119 東京都交通局 99342 日暮里・舎人ライナー 9934211 舎人公園 足立区舎人公園1-10 139.770183 35.79623 -119 東京都交通局 99342 日暮里・舎人ライナー 9934212 舎人 足立区舎人1-16-15 139.770108 35.8057 -119 東京都交通局 99342 日暮里・舎人ライナー 9934213 見沼代親水公園 足立区舎人2-21-13 139.770719 35.814544 diff --git a/tests/travis/setup_arangodb.sh b/tests/travis/setup_arangodb.sh old mode 100644 new mode 100755 index a4c6ce749..0f3c1c4a9 --- a/tests/travis/setup_arangodb.sh +++ b/tests/travis/setup_arangodb.sh @@ -29,8 +29,9 @@ 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 \ + --server.endpoint vpp+tcp://127.0.0.1:8529 \ + --server.endpoint vpp+ssl://127.0.0.1:8530 \ + --server.endpoint tcp://127.0.0.1:8531 \ --ssl.keyfile ./server.pem \ --javascript.app-path ${ARANGODB_DIR}/js/apps \ --javascript.startup-directory ${ARANGODB_DIR}/js \ @@ -47,8 +48,8 @@ if [ "x$process" == "x" ]; then exit 1 fi -echo "Waiting until ArangoDB is ready on port 8529" -while [[ -z `curl -uroot: -s 'http://127.0.0.1:8529/_api/version' ` ]] ; do +echo "Waiting until ArangoDB is ready on port 8531" +while [[ -z `curl -uroot: -s 'http://127.0.0.1:8531/_api/version' ` ]] ; do echo -n "." sleep 2s done