| margaretha | 3925c7a | 2016-02-24 11:20:49 +0000 | [diff] [blame] | 1 | package de.mannheim.ids.korap.sru; |
| 2 | |
| 3 | import org.xml.sax.Attributes; |
| 4 | import org.xml.sax.SAXException; |
| 5 | import org.xml.sax.helpers.DefaultHandler; |
| 6 | |
| margaretha | d7fda43 | 2016-08-17 15:49:02 +0200 | [diff] [blame] | 7 | /** Handler for parsing the match snippet from KorAP search API. |
| 8 | * |
| 9 | * @author margaretha |
| 10 | * |
| 11 | */ |
| margaretha | 3925c7a | 2016-02-24 11:20:49 +0000 | [diff] [blame] | 12 | public class KorapMatchHandler extends DefaultHandler{ |
| 13 | |
| margaretha | ab24b65 | 2016-08-08 18:58:48 +0200 | [diff] [blame] | 14 | private KorapMatch match; |
| margaretha | 3925c7a | 2016-02-24 11:20:49 +0000 | [diff] [blame] | 15 | boolean isLeftContext, isRightContext, isKeyword, isMore; |
| 16 | private StringBuilder sbLeft, sbRight, sbKey; |
| 17 | |
| 18 | public KorapMatchHandler(KorapMatch m) { |
| 19 | match = m; |
| 20 | } |
| 21 | |
| 22 | @Override |
| 23 | public void startElement(String uri, String localName, String qName, |
| 24 | Attributes attributes) throws SAXException { |
| 25 | super.startElement(uri, localName, qName, attributes); |
| 26 | |
| 27 | if (qName.equals("span") && attributes.getQName(0).equals("class")){ |
| 28 | switch (attributes.getValue(0)) { |
| 29 | case "context-left": |
| 30 | isLeftContext = true; |
| 31 | sbLeft = new StringBuilder(); |
| 32 | break; |
| 33 | case "context-right": |
| 34 | isRightContext = true; |
| 35 | sbRight = new StringBuilder(); |
| 36 | break; |
| 37 | case "match": |
| 38 | isKeyword = true; |
| 39 | sbKey = new StringBuilder(); |
| 40 | break; |
| 41 | case "more": |
| 42 | isMore = true; |
| 43 | break; |
| 44 | } |
| 45 | } |
| 46 | } |
| 47 | |
| 48 | @Override |
| 49 | public void endElement(String uri, String localName, String qName) |
| 50 | throws SAXException { |
| 51 | |
| 52 | if (qName.equals("span")){ |
| 53 | if (isMore){ |
| 54 | isMore = false; |
| 55 | } |
| 56 | else if (isLeftContext){ |
| 57 | match.setLeftContext(sbLeft.toString()); |
| 58 | isLeftContext = false; |
| 59 | } |
| 60 | else if (isKeyword){ |
| 61 | match.setKeyword(sbKey.toString()); |
| 62 | isKeyword = false; |
| 63 | } |
| 64 | else if (isRightContext){ |
| 65 | match.setRightContext(sbRight.toString()); |
| 66 | isRightContext = false; |
| 67 | } |
| 68 | } |
| 69 | } |
| 70 | |
| 71 | @Override |
| 72 | public void characters(char ch[], int start, int length) throws SAXException { |
| 73 | if (isKeyword){ |
| 74 | sbKey.append(ch, start, length); |
| 75 | } |
| 76 | else if (isLeftContext){ |
| 77 | sbLeft.append(ch, start, length); |
| 78 | } |
| 79 | else if (isRightContext){ |
| 80 | sbRight.append(ch, start, length); |
| 81 | } |
| 82 | } |
| 83 | } |