* @param tsdb The TSDB to which we belong
* @param query The HTTP query to work with
* @throws BadRequestException if the request was invalid.
*/
private void handleTree(TSDB tsdb, HttpQuery query) {
final Tree tree;
if (query.hasContent()) {
tree = query.serializer().parseTreeV1();
} else {
tree = parseTree(query);
}
try {
// if get, then we're just returning one or more trees
if (query.getAPIMethod() == HttpMethod.GET) {
if (tree.getTreeId() == 0) {
query.sendReply(query.serializer().formatTreesV1(
Tree.fetchAllTrees(tsdb).joinUninterruptibly()));
} else {
final Tree single_tree = Tree.fetchTree(tsdb, tree.getTreeId())
.joinUninterruptibly();
if (single_tree == null) {
throw new BadRequestException(HttpResponseStatus.NOT_FOUND,
"Unable to locate tree: " + tree.getTreeId());
}
query.sendReply(query.serializer().formatTreeV1(single_tree));
}
} else if (query.getAPIMethod() == HttpMethod.POST || query.getAPIMethod() == HttpMethod.PUT) {
// For post or put, we're either editing a tree or creating a new one.
// If the tree ID is missing, we need to create a new one, otherwise we
// edit an existing tree.
// if the tree ID is set, fetch, copy, save
if (tree.getTreeId() > 0) {
if (Tree.fetchTree(tsdb, tree.getTreeId())
.joinUninterruptibly() == null) {
throw new BadRequestException(HttpResponseStatus.NOT_FOUND,
"Unable to locate tree: " + tree.getTreeId());
} else {
if (tree.storeTree(tsdb, (query.getAPIMethod() == HttpMethod.PUT))
.joinUninterruptibly() != null) {
final Tree stored_tree = Tree.fetchTree(tsdb, tree.getTreeId())
.joinUninterruptibly();
query.sendReply(query.serializer().formatTreeV1(stored_tree));
} else {
throw new BadRequestException(
HttpResponseStatus.INTERNAL_SERVER_ERROR,
"Unable to save changes to tre tree: " + tree.getTreeId(),
"Plesae try again at a later time");
}
}
} else {
// create a new tree
final int tree_id = tree.createNewTree(tsdb).joinUninterruptibly();
if (tree_id > 0) {
final Tree stored_tree = Tree.fetchTree(tsdb, tree_id)
.joinUninterruptibly();
query.sendReply(query.serializer().formatTreeV1(stored_tree));
} else {
throw new BadRequestException(
HttpResponseStatus.INTERNAL_SERVER_ERROR,