| margaretha | 398f472 | 2019-01-09 19:07:20 +0100 | [diff] [blame] | 1 | package de.ids_mannheim.korap.rewrite; |
| Michael Hanl | d956990 | 2016-05-28 17:04:31 +0200 | [diff] [blame] | 2 | |
| Michael Hanl | d956990 | 2016-05-28 17:04:31 +0200 | [diff] [blame] | 3 | import java.util.Iterator; |
| 4 | |
| margaretha | 4fa4b06 | 2019-01-28 19:43:30 +0100 | [diff] [blame^] | 5 | import com.fasterxml.jackson.databind.JsonNode; |
| 6 | import com.fasterxml.jackson.databind.node.ObjectNode; |
| 7 | |
| 8 | import de.ids_mannheim.korap.config.KustvaktConfiguration; |
| 9 | import de.ids_mannheim.korap.user.User; |
| 10 | import edu.emory.mathcs.backport.java.util.Arrays; |
| 11 | |
| 12 | /** EM: not used anymore. This rewrite was to remove an empty koral:doc group in operands. |
| 13 | * |
| Michael Hanl | d956990 | 2016-05-28 17:04:31 +0200 | [diff] [blame] | 14 | * @author hanl |
| 15 | * @date 28/07/2015 |
| 16 | */ |
| 17 | public class CollectionCleanRewrite implements RewriteTask.RewriteNodeAt { |
| 18 | |
| 19 | @Override |
| margaretha | 1bc9cca | 2018-12-11 15:09:44 +0100 | [diff] [blame] | 20 | public KoralNode rewriteQuery (KoralNode node, KustvaktConfiguration config, |
| Michael Hanl | d956990 | 2016-05-28 17:04:31 +0200 | [diff] [blame] | 21 | User user) { |
| margaretha | 1bc9cca | 2018-12-11 15:09:44 +0100 | [diff] [blame] | 22 | JsonNode jsonNode = process(node.rawNode()); |
| 23 | return node.wrapNode(jsonNode); |
| Michael Hanl | d956990 | 2016-05-28 17:04:31 +0200 | [diff] [blame] | 24 | } |
| 25 | |
| 26 | |
| 27 | private JsonNode process (JsonNode root) { |
| 28 | JsonNode sub = root; |
| 29 | if (root.isObject()) { |
| 30 | if (root.has("operands")) { |
| 31 | JsonNode node = root.at("/operands"); |
| 32 | Iterator<JsonNode> it = node.elements(); |
| 33 | while (it.hasNext()) { |
| 34 | JsonNode n = it.next(); |
| 35 | JsonNode s = process(n); |
| 36 | if (s == null) |
| 37 | it.remove(); |
| 38 | } |
| 39 | |
| 40 | int count = node.size(); |
| 41 | // remove group element and replace with single doc |
| 42 | if (count == 1) |
| 43 | sub = node.path(0); |
| 44 | // indicate empty group |
| 45 | else if (count == 0) // can't do anything here -- fixme: edge case?! |
| 46 | return null; |
| 47 | } |
| 48 | |
| 49 | // what happens to array nodes? |
| 50 | if (!root.equals(sub)) { |
| 51 | if (sub.isObject()) { |
| 52 | ObjectNode ob = (ObjectNode) root; |
| 53 | ob.remove(Arrays.asList(new String[] { "@type", |
| 54 | "operation", "operands" })); |
| 55 | ob.putAll((ObjectNode) sub); |
| 56 | } |
| 57 | } |
| 58 | } |
| 59 | return root; |
| 60 | } |
| 61 | |
| 62 | |
| 63 | @Override |
| 64 | public JsonNode rewriteResult (KoralNode node) { |
| 65 | return null; |
| 66 | } |
| 67 | |
| 68 | |
| 69 | @Override |
| 70 | public String at () { |
| 71 | return "/collection"; |
| 72 | } |
| 73 | } |