blob: 39df47d9e170ffbc891325a5f2b098814574c37c [file] [log] [blame]
margaretha3925c7a2016-02-24 11:20:49 +00001package de.mannheim.ids.korap.sru;
2
3import org.xml.sax.Attributes;
4import org.xml.sax.SAXException;
5import org.xml.sax.helpers.DefaultHandler;
6
margarethad7fda432016-08-17 15:49:02 +02007/** Handler for parsing the match snippet from KorAP search API.
8 *
9 * @author margaretha
10 *
11 */
margaretha3925c7a2016-02-24 11:20:49 +000012public class KorapMatchHandler extends DefaultHandler{
13
margarethaab24b652016-08-08 18:58:48 +020014 private KorapMatch match;
margaretha3925c7a2016-02-24 11:20:49 +000015 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}