1 package com.foxinmy.weixin4j.util;
2
3 import java.io.ByteArrayInputStream;
4 import java.io.IOException;
5 import java.util.Map;
6 import java.util.concurrent.ConcurrentHashMap;
7
8 import org.xml.sax.Attributes;
9 import org.xml.sax.InputSource;
10 import org.xml.sax.SAXException;
11 import org.xml.sax.XMLReader;
12 import org.xml.sax.helpers.DefaultHandler;
13 import org.xml.sax.helpers.XMLReaderFactory;
14
15 import com.foxinmy.weixin4j.http.weixin.WeixinResponse;
16
17
18
19
20
21
22
23
24
25
26
27 public final class WeixinErrorUtil {
28
29 private static byte[] errorXmlByteArray;
30 private final static Map<String, String> errorCacheMap;
31
32 static {
33 errorCacheMap = new ConcurrentHashMap<String, String>();
34 try {
35 errorXmlByteArray = IOUtil.toByteArray(WeixinResponse.class.getResourceAsStream("error.xml"));
36 } catch (IOException e) {
37 ;
38 }
39 }
40
41 private static class ErrorTextHandler extends DefaultHandler {
42
43 private final String code;
44
45 public ErrorTextHandler(String code) {
46 this.code = code;
47 }
48
49 private String text;
50 private boolean codeElement;
51 private boolean textElement;
52 private boolean findElement;
53
54 @Override
55 public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
56 codeElement = qName.equalsIgnoreCase("code");
57 textElement = qName.equalsIgnoreCase("text");
58 }
59
60 @Override
61 public void endElement(String uri, String localName, String qName) throws SAXException {
62 }
63
64 @Override
65 public void characters(char[] ch, int start, int length) throws SAXException {
66 String _text = new String(ch, start, length);
67 if (codeElement && _text.equalsIgnoreCase(code)) {
68 findElement = true;
69 } else if (textElement && findElement) {
70 text = _text;
71 throw new SAXException("ENOUGH");
72 }
73 }
74
75 public String getText() {
76 return StringUtil.isBlank(text) ? "" : text;
77 }
78 }
79
80 public static String getText(String code) throws RuntimeException {
81 if (StringUtil.isBlank(code)) {
82 return "";
83 }
84 String text = errorCacheMap.get(code);
85 if (StringUtil.isBlank(text)) {
86 ErrorTextHandler textHandler = new ErrorTextHandler(code);
87 try {
88 XMLReader xmlReader = XMLReaderFactory.createXMLReader();
89 xmlReader.setContentHandler(textHandler);
90 xmlReader.parse(new InputSource(new ByteArrayInputStream(errorXmlByteArray)));
91 text = textHandler.getText();
92 errorCacheMap.put(code, text);
93 } catch (IOException e) {
94 throw new RuntimeException(e);
95 } catch (SAXException e) {
96 text = textHandler.getText();
97 errorCacheMap.put(code, text);
98 }
99 }
100 return text;
101 }
102
103
104 public static void main(String[] args) {
105 System.out.println(getText("30002"));
106 System.out.println(getText("30002"));
107 System.out.println(getText("88010"));
108 }
109 }