All Downloads are FREE. Search and download functionalities are using the official Maven repository.

cn.ipokerface.weixin.request.WeixinErrorHolder Maven / Gradle / Ivy

There is a newer version: 1.5.0
Show newest version
package cn.ipokerface.weixin.request;

import cn.ipokerface.weixin.utils.IOUtils;
import cn.ipokerface.weixin.utils.StringUtil;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.helpers.XMLReaderFactory;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by       PokerFace
 * Create Date      2019-12-27.
 * Email:           [email protected]
 * Version          1.0.0
 * 

* Description: */ public class WeixinErrorHolder { private static byte[] errorXmlByteArray; private final static Map errorCacheMap; static { errorCacheMap = new ConcurrentHashMap(); try { errorXmlByteArray = IOUtils.toByteArray(WeixinErrorHolder.class.getResourceAsStream("error.xml")); } catch (IOException e) { ; } } private static class ErrorTextHandler extends DefaultHandler { private final String code; public ErrorTextHandler(String code) { this.code = code; } private String text; private boolean codeElement; private boolean textElement; private boolean findElement; @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { codeElement = qName.equalsIgnoreCase("code"); textElement = qName.equalsIgnoreCase("text"); } @Override public void endElement(String uri, String localName, String qName) throws SAXException { } @Override public void characters(char[] ch, int start, int length) throws SAXException { String _text = new String(ch, start, length); if (codeElement && _text.equalsIgnoreCase(code)) { findElement = true; } else if (textElement && findElement) { text = _text; throw new SAXException("ENOUGH"); } } public String getText() { return StringUtil.isBlank(text) ? "" : text; } } public static String getText(String code) throws RuntimeException { if (StringUtil.isBlank(code)) { return ""; } String text = errorCacheMap.get(code); if (StringUtil.isBlank(text)) { ErrorTextHandler textHandler = new ErrorTextHandler(code); try { XMLReader xmlReader = XMLReaderFactory.createXMLReader(); xmlReader.setContentHandler(textHandler); xmlReader.parse(new InputSource(new ByteArrayInputStream(errorXmlByteArray))); text = textHandler.getText(); errorCacheMap.put(code, text); } catch (IOException e) { throw new RuntimeException(e); } catch (SAXException e) { text = textHandler.getText(); errorCacheMap.put(code, text); } } return text; } }





© 2015 - 2024 Weber Informatics LLC | Privacy Policy