Java源码示例:com.arangodb.ArangoDBException

示例1
/**
 * Create a new graph.
 *
 * @param name 						the name of the new graph
 * @param edgeDefinitions			the edge definitions for the graph
 * @param options 					additional graph options
 * @return the arango graph
 * @throws ArangoDBGraphException 	If the graph can not be created
 */

public ArangoGraph createGraph(String name,
       List<EdgeDefinition> edgeDefinitions,
	GraphCreateOptions options)
	throws ArangoDBGraphException {
	logger.info("Creating graph {}", name);
	try {
		logger.info("Creating graph in database.");
		db.createGraph(name, edgeDefinitions, options);
	} catch (ArangoDBException e) {
           logger.info("Error creating graph in database.", e);
           throw ArangoDBExceptions.getArangoDBException(e);
       }
	ArangoGraph g = db.graph(name);
	return g;
}
 
示例2
@Override
public DocumentEntity replace(final Object id, final Object value, final DocumentReplaceOptions options)
		throws DataAccessException {
	potentiallyEmitEvent(new BeforeSaveEvent<>(value));

	final DocumentEntity result;
	try {
		result = _collection(value.getClass(), id).replaceDocument(determineDocumentKeyFromId(id), toVPack(value),
			options);
	} catch (final ArangoDBException e) {
		throw translateExceptionIfPossible(e);
	}

	updateDBFields(value, result);
	potentiallyEmitEvent(new AfterSaveEvent<>(value));
	return result;
}
 
示例3
/**
 * Execute AQL query.
 *
 * @param <T> 						the generic type of the returned values
 * @param query 					the query string
 * @param bindVars 					the value of the bind parameters
 * @param aqlQueryOptions 			the aql query options
 * @param type            			the type of the result (POJO class, VPackSlice, String for Json, or Collection/List/Map)
 * @return the cursor result
 * @throws ArangoDBGraphException	if executing the query raised an exception
 */

public <T> ArangoCursor<T> executeAqlQuery(
	String query,
	Map<String, Object> bindVars,
	AqlQueryOptions aqlQueryOptions,
	final Class<T> type)
	throws ArangoDBGraphException {
	logger.debug("Executing AQL query ({}) against db, with bind vars: {}", query, bindVars);
	try {
		return db.query(query, bindVars, aqlQueryOptions, type);
	} catch (ArangoDBException e) {
		logger.error("Error executing query", e);
           throw ArangoDBExceptions.getArangoDBException(e);
	}
}
 
示例4
@Test
public void abortCommittedStreamTransactionShouldThrow() throws ExecutionException, InterruptedException {
    assumeTrue(isSingleServer());
    assumeTrue(isAtLeastVersion(3, 5));
    assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb));

    StreamTransactionEntity createdTx = db.beginStreamTransaction(null).get();
    db.commitStreamTransaction(createdTx.getId()).get();

    try {
        db.abortStreamTransaction(createdTx.getId()).get();
        fail();
    } catch (ExecutionException e) {
        assertThat(e.getCause(), instanceOf(ArangoDBException.class));
    }
}
 
示例5
public <T> T execute(
        final Request request,
        final ResponseDeserializer<T> responseDeserializer,
        final HostHandle hostHandle) throws ArangoDBException {

    try {

        final Response response = protocol.execute(request, hostHandle);
        T deserialize = responseDeserializer.deserialize(response);

        if (deserialize instanceof MetaAware) {
            LOG.debug("Response is MetaAware " + deserialize.getClass().getName());
            ((MetaAware) deserialize).setMeta(response.getMeta());
        }

        return deserialize;

    } catch (final VPackException e) {
        throw new ArangoDBException(e);
    }
}
 
示例6
@Test
public void replaceDocumentIgnoreRevsFalse() throws InterruptedException, ExecutionException {
    final BaseDocument doc = new BaseDocument();
    doc.addAttribute("a", "test");
    final DocumentCreateEntity<BaseDocument> createResult = db.collection(COLLECTION_NAME).insertDocument(doc, null)
            .get();
    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).get();
        fail();
    } catch (final ExecutionException e) {
        assertThat(e.getCause(), instanceOf(ArangoDBException.class));
    }
}
 
示例7
private <T> Function<Throwable, T> handleGetDocumentExceptions(Boolean isCatchException) {
    return throwable -> {
        if (throwable instanceof CompletionException) {
            if (throwable.getCause() instanceof ArangoDBException) {
                ArangoDBException arangoDBException = (ArangoDBException) throwable.getCause();

                // handle Response: 404, Error: 1655 - transaction not found
                if (arangoDBException.getErrorNum() != null && arangoDBException.getErrorNum() == 1655) {
                    throw (CompletionException) throwable;
                }

                if ((arangoDBException.getResponseCode() != null && (arangoDBException.getResponseCode() == 404 || arangoDBException.getResponseCode() == 304
                        || arangoDBException.getResponseCode() == 412)) && isCatchException) {
                    return null;
                }
            }
            throw (CompletionException) throwable;
        }
        throw new CompletionException(throwable);
    };
}
 
示例8
@Test
public void updateDocumentIgnoreRevsFalse() throws InterruptedException, ExecutionException {
    final BaseDocument doc = new BaseDocument();
    doc.addAttribute("a", "test");
    final DocumentCreateEntity<BaseDocument> createResult = db.collection(COLLECTION_NAME).insertDocument(doc, null)
            .get();
    doc.updateAttribute("a", "test1");
    doc.setRevision("no");
    try {
        final DocumentUpdateOptions options = new DocumentUpdateOptions().ignoreRevs(false);
        db.collection(COLLECTION_NAME).updateDocument(createResult.getKey(), doc, options).get();
        fail();
    } catch (final ExecutionException e) {
        assertThat(e.getCause(), instanceOf(ArangoDBException.class));
    }
}
 
示例9
/**
 * Create a query to get all the edges of a vertex. 
 *
 * @param vertex            	the vertex
 * @param edgeLabels        	a list of edge labels to follow, empty if all type of edges
 * @param direction         	the direction of the edges
 * @return ArangoDBBaseQuery the query object
 * @throws ArangoDBException if there is an error executing the query
 */

public ArangoCursor<ArangoDBEdge> getVertexEdges(
	ArangoDBVertex vertex,
	List<String> edgeLabels,
	Direction direction)
	throws ArangoDBException {
	logger.debug("Get Vertex's {}:{} Edges, in {}, from collections {}", vertex, direction, graph.name(), edgeLabels);
	Map<String, Object> bindVars = new HashMap<>();
	ArangoDBQueryBuilder queryBuilder = new ArangoDBQueryBuilder();
	ArangoDBQueryBuilder.Direction arangoDirection = ArangoDBUtil.getArangoDirectionFromGremlinDirection(direction);
	logger.debug("Creating query");
	queryBuilder.iterateGraph(graph.name(), "v", Optional.of("e"),
			Optional.empty(), Optional.empty(), Optional.empty(),
			arangoDirection, vertex._id(), bindVars)
		.graphOptions(Optional.of(UniqueVertices.NONE), Optional.empty(), true)
		.filterSameCollections("e", edgeLabels, bindVars)
		.ret("e");
	
	String query = queryBuilder.toString();
	return executeAqlQuery(query, bindVars, null, ArangoDBEdge.class);
}
 
示例10
public static void checkError(final ArangoSerialization util, final Response response) throws ArangoDBException {
    try {
        final int responseCode = response.getResponseCode();
        if (responseCode >= ERROR_STATUS) {
            if (responseCode == ERROR_INTERNAL && response.getMeta().containsKey(HEADER_ENDPOINT)) {
                throw new ArangoDBRedirectException(String.format("Response Code: %s", responseCode),
                        response.getMeta().get(HEADER_ENDPOINT));
            } else if (response.getBody() != null) {
                final ErrorEntity errorEntity = util.deserialize(response.getBody(), ErrorEntity.class);
                throw new ArangoDBException(errorEntity);
            } else {
                throw new ArangoDBException(String.format("Response Code: %s", responseCode), responseCode);
            }
        }
    } catch (final VPackParserException e) {
        throw new ArangoDBException(e);
    }
}
 
示例11
@Test
public void getEdgeIfMatchFail() throws InterruptedException, ExecutionException {
    final BaseEdgeDocument value = createEdgeValue();
    final EdgeEntity edge = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).insertEdge(value, null).get();
    final GraphDocumentReadOptions options = new GraphDocumentReadOptions().ifMatch("no").catchException(false);
    try {
        db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME)
                .getEdge(edge.getKey(), BaseEdgeDocument.class, options).get();
        fail();
    } catch (final ExecutionException e) {
        assertThat(e.getCause(), instanceOf(ArangoDBException.class));
    }
}
 
示例12
@Test
public void queryClose() throws IOException, InterruptedException, ExecutionException {
    final ArangoCursorAsync<String> cursor = arangoDB.db()
            .query("for i in 1..2 return i", null, new AqlQueryOptions().batchSize(1), String.class).get();
    cursor.close();
    int count = 0;
    try {
        for (; cursor.hasNext(); cursor.next(), count++) {
        }
        fail();
    } catch (final ArangoDBException e) {
        assertThat(count, is(1));
    }

}
 
示例13
@Override
public Iterable<UserEntity> getUsers() throws DataAccessException {
	try {
		return arango.getUsers();
	} catch (final ArangoDBException e) {
		throw translateExceptionIfPossible(e);
	}
}
 
示例14
@Test
public void commitStreamTransactionWhenTransactionIdDoesNotExistsShouldThrow() throws ExecutionException, InterruptedException {
    assumeTrue(isSingleServer());
    assumeTrue(isAtLeastVersion(3, 5));
    assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb));

    try {
        db.commitStreamTransaction("000000").get();
        fail();
    } catch (ExecutionException e) {
        assertThat(e.getCause(), instanceOf(ArangoDBException.class));
    }
}
 
示例15
@Test
public void importDocumentsCompleteFail() throws InterruptedException {
    final Collection<BaseDocument> values = new ArrayList<>();
    values.add(new BaseDocument("1"));
    values.add(new BaseDocument("2"));
    values.add(new BaseDocument("2"));
    try {
        db.collection(COLLECTION_NAME).importDocuments(values, new DocumentImportOptions().complete(true)).get();
        fail();
    } catch (ExecutionException e) {
        assertThat(e.getCause(), instanceOf(ArangoDBException.class));
        assertThat(((ArangoDBException) e.getCause()).getErrorNum(), is(1210));
    }
}
 
示例16
@Override
public UserEntity replace(final UserUpdateOptions options) throws DataAccessException {
	try {
		return db.arango().replaceUser(username, options);
	} catch (final ArangoDBException e) {
		throw translateExceptionIfPossible(e);
	}
}
 
示例17
@Test
public void queryDepthTwo() throws ArangoDBException {
	String queryString = "FOR v IN 2..2 OUTBOUND 'circles/A' GRAPH 'traversalGraph' return v._key";
	ArangoCursor<String> cursor = db.query(queryString, null, null, String.class);
	Collection<String> 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"));
}
 
示例18
@Test
public void deleteSystemCollection() throws InterruptedException, ExecutionException {
    final String name = "_system_test";
    db.createCollection(name, new CollectionCreateOptions().isSystem(true)).get();
    db.collection(name).drop(true).get();
    try {
        db.collection(name).getInfo().get();
        fail();
    } catch (final ExecutionException e) {
        assertThat(e.getCause(), instanceOf(ArangoDBException.class));
    }
}
 
示例19
@Override
public boolean exists() throws ArangoDBException {
    try {
        getInfo();
        return true;
    } catch (final ArangoDBException e) {
        if (ArangoErrors.ERROR_ARANGO_DATA_SOURCE_NOT_FOUND.equals(e.getErrorNum())) {
            return false;
        }
        throw e;
    }
}
 
示例20
@Test
public void abortStreamTransactionWhenTransactionIdDoesNotExistsShouldThrow() throws ExecutionException, InterruptedException {
    assumeTrue(isSingleServer());
    assumeTrue(isAtLeastVersion(3, 5));
    assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb));

    try {
        db.abortStreamTransaction("000000").get();
        fail();
    } catch (ExecutionException e) {
        assertThat(e.getCause(), instanceOf(ArangoDBException.class));
    }
}
 
示例21
@Override
public CollectionPropertiesEntity getProperties() throws DataAccessException {
	try {
		return collection.getProperties();
	} catch (final ArangoDBException e) {
		throw translateExceptionIfPossible(e);
	}
}
 
示例22
@Override
public Collection<IndexEntity> getIndexes() throws DataAccessException {
	try {
		return collection.getIndexes();
	} catch (final ArangoDBException e) {
		throw translateExceptionIfPossible(e);
	}
}
 
示例23
public Response execute(final Request request, final HostHandle hostHandle) throws ArangoDBException, IOException {
    final AccessType accessType = RequestUtils.determineAccessType(request);
    Host host = hostHandler.get(hostHandle, accessType);
    try {
        while (true) {
            try {
                final HttpConnection connection = (HttpConnection) host.connection();
                final Response response = connection.execute(request);
                hostHandler.success();
                hostHandler.confirm();
                return response;
            } catch (final SocketException se) {
                hostHandler.fail();
                if (hostHandle != null && hostHandle.getHost() != null) {
                    hostHandle.setHost(null);
                }
                final Host failedHost = host;
                host = hostHandler.get(hostHandle, accessType);
                if (host != null) {
                    LOGGER.warn(String.format("Could not connect to %s. Try connecting to %s",
                            failedHost.getDescription(), host.getDescription()));
                } else {
                    throw se;
                }
            }
        }
    } catch (final ArangoDBException e) {
        if (e instanceof ArangoDBRedirectException) {
            final String location = ((ArangoDBRedirectException) e).getLocation();
            final HostDescription redirectHost = HostUtils.createFromLocation(location);
            hostHandler.closeCurrentOnError();
            hostHandler.fail();
            return execute(request, new HostHandle().setHost(redirectHost));
        } else {
            throw e;
        }
    }
}
 
示例24
@Test
public void deleteEdgeIfMatch() throws InterruptedException, ExecutionException {
    final BaseEdgeDocument doc = createEdgeValue();
    final EdgeEntity createResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).insertEdge(doc, null)
            .get();
    final EdgeDeleteOptions options = new EdgeDeleteOptions().ifMatch(createResult.getRev());
    db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).deleteEdge(createResult.getKey(), options).get();
    try {
        db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME)
                .getEdge(createResult.getKey(), BaseEdgeDocument.class, new GraphDocumentReadOptions().catchException(false)).get();
        fail();
    } catch (final ExecutionException e) {
        assertThat(e.getCause(), instanceOf(ArangoDBException.class));
    }
}
 
示例25
private Collection<String> resolveFromServer() throws ArangoDBException {

        Collection<String> response;

        try {

            response = executor.execute(
                    new Request(ArangoRequestParam.SYSTEM, RequestType.GET, "/_api/cluster/endpoints"),
                    response1 -> {
                        final VPackSlice field = response1.getBody().get("endpoints");
                        Collection<String> endpoints;
                        if (field.isNone()) {
                            endpoints = Collections.emptyList();
                        } else {
                            final Collection<Map<String, String>> tmp = arangoSerialization.deserialize(field, Collection.class);
                            endpoints = new ArrayList<>();
                            for (final Map<String, String> map : tmp) {
                                endpoints.addAll(map.values());
                            }
                        }
                        return endpoints;
                    }, null);
        } catch (final ArangoDBException e) {
            final Integer responseCode = e.getResponseCode();

            // responseCode == 403: single server < 3.7
            // responseCode == 501: single server >= 3.7
            if (responseCode != null && (responseCode == 403 || responseCode == 501)) {
                response = Collections.emptyList();
            } else {
                throw e;
            }
        }

        return response;
    }
 
示例26
@Test
public void beginStreamTransactionWithNonExistingCollectionsShouldThrow() throws ExecutionException, InterruptedException {
    assumeTrue(isSingleServer());
    assumeTrue(isAtLeastVersion(3, 5));
    assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb));

    try {
        db.beginStreamTransaction(new StreamTransactionOptions().writeCollections("notExistingCollection")).get();
        fail();
    } catch (ExecutionException e) {
        assertThat(e.getCause(), instanceOf(ArangoDBException.class));
    }
}
 
示例27
@Override
public void resetAccess(final String username) {
	try {
		collection.resetAccess(username);
	} catch (final ArangoDBException e) {
		throw translateExceptionIfPossible(e);
	}
}
 
示例28
@Test(expected = ArangoDBException.class)
public void findOneByIdInIncorrectNamedCollectionAqlTest() {
	repository.saveAll(customers);
	final Customer retrieved = repository.findOneByIdInIncorrectNamedCollectionAql(john.getId().split("/")[0],
		john.getId(), john.getId());
	assertEquals(john, retrieved);
}
 
示例29
@Test(expected = ArangoDBException.class)
public void findOneByIdInNamedCollectionAqlRejectedTest() {
	repository.saveAll(customers);
	final Customer retrieved = repository.findOneByIdInNamedCollectionAqlRejected(john.getId().split("/")[0],
		john.getId());
	assertEquals(john, retrieved);
}
 
示例30
@Override
public <T> CompletableFuture<T> getDocument(final String id, final Class<T> type, final DocumentReadOptions options)
        throws ArangoDBException {
    DocumentUtil.validateDocumentId(id);
    final String[] split = id.split("/");
    return collection(split[0]).getDocument(split[1], type, options);
}