Handles the plain /tree endpoint CRUD. If a POST or PUT is requested and no tree ID is provided, we'll assume the user wanted to create a new tree. @param tsdb The TSDB to which we belong @param query The HTTP query to work with @throws BadRequestException if the request was invalid.
(TSDB tsdb, HttpQuery query)
| 90 | * @throws BadRequestException if the request was invalid. |
| 91 | */ |
| 92 | private void handleTree(TSDB tsdb, HttpQuery query) { |
| 93 | final Tree tree; |
| 94 | if (query.hasContent()) { |
| 95 | tree = query.serializer().parseTreeV1(); |
| 96 | } else { |
| 97 | tree = parseTree(query); |
| 98 | } |
| 99 | |
| 100 | try { |
| 101 | // if get, then we're just returning one or more trees |
| 102 | if (query.getAPIMethod() == HttpMethod.GET) { |
| 103 | |
| 104 | if (tree.getTreeId() == 0) { |
| 105 | query.sendReply(query.serializer().formatTreesV1( |
| 106 | Tree.fetchAllTrees(tsdb).joinUninterruptibly())); |
| 107 | } else { |
| 108 | final Tree single_tree = Tree.fetchTree(tsdb, tree.getTreeId()) |
| 109 | .joinUninterruptibly(); |
| 110 | if (single_tree == null) { |
| 111 | throw new BadRequestException(HttpResponseStatus.NOT_FOUND, |
| 112 | "Unable to locate tree: " + tree.getTreeId()); |
| 113 | } |
| 114 | query.sendReply(query.serializer().formatTreeV1(single_tree)); |
| 115 | } |
| 116 | |
| 117 | } else if (query.getAPIMethod() == HttpMethod.POST || query.getAPIMethod() == HttpMethod.PUT) { |
| 118 | // For post or put, we're either editing a tree or creating a new one. |
| 119 | // If the tree ID is missing, we need to create a new one, otherwise we |
| 120 | // edit an existing tree. |
| 121 | |
| 122 | // if the tree ID is set, fetch, copy, save |
| 123 | if (tree.getTreeId() > 0) { |
| 124 | if (Tree.fetchTree(tsdb, tree.getTreeId()) |
| 125 | .joinUninterruptibly() == null) { |
| 126 | throw new BadRequestException(HttpResponseStatus.NOT_FOUND, |
| 127 | "Unable to locate tree: " + tree.getTreeId()); |
| 128 | } else { |
| 129 | if (tree.storeTree(tsdb, (query.getAPIMethod() == HttpMethod.PUT)) |
| 130 | .joinUninterruptibly() != null) { |
| 131 | final Tree stored_tree = Tree.fetchTree(tsdb, tree.getTreeId()) |
| 132 | .joinUninterruptibly(); |
| 133 | query.sendReply(query.serializer().formatTreeV1(stored_tree)); |
| 134 | } else { |
| 135 | throw new BadRequestException( |
| 136 | HttpResponseStatus.INTERNAL_SERVER_ERROR, |
| 137 | "Unable to save changes to tre tree: " + tree.getTreeId(), |
| 138 | "Plesae try again at a later time"); |
| 139 | } |
| 140 | } |
| 141 | } else { |
| 142 | // create a new tree |
| 143 | final int tree_id = tree.createNewTree(tsdb).joinUninterruptibly(); |
| 144 | if (tree_id > 0) { |
| 145 | final Tree stored_tree = Tree.fetchTree(tsdb, tree_id) |
| 146 | .joinUninterruptibly(); |
| 147 | query.sendReply(query.serializer().formatTreeV1(stored_tree)); |
| 148 | } else { |
| 149 | throw new BadRequestException( |
no test coverage detected