当前位置: 首页 > 工具软件 > XDoc-Java > 使用案例 >

java报表 word_Java报表统计导出Word-xdocin方式

乌俊健
2023-12-01

importorg.w3c.dom.Document;importorg.w3c.dom.Element;importorg.w3c.dom.NamedNodeMap;importorg.w3c.dom.NodeList;importorg.xml.sax.SAXException;importjavax.xml.parsers.DocumentBuilder;importjavax.xml.parsers.DocumentBuilderFactory;importjavax.xml.parsers.ParserConfigurationException;importjava.beans.BeanInfo;importjava.beans.Introspector;importjava.beans.PropertyDescriptor;import java.io.*;import java.lang.annotation.*;importjava.lang.reflect.Array;importjava.lang.reflect.Field;importjava.lang.reflect.Method;import java.net.*;importjava.text.SimpleDateFormat;import java.util.*;/*** XDoc服务

*

*@authorxdoc

*@version11.4.2*/

public classXDocService {/*** 默认服务器地址*/

public static String DEFAULT_URL = "http://www.xdocin.com";/*** 默认账号口令*/

public static String DEFAULT_KEY = "";privateString url;privateString key;/*** 服务地址

*

*@return

*/

publicString getUrl() {returnurl;

}/*** 服务地址

*

*@paramurl*/

public voidsetUrl(String url) {this.url =url;

}/*** 账号口令

*

*@return

*/

publicString getKey() {returnkey;

}/*** 账号口令

*

*@paramkey*/

public voidsetKey(String key) {this.key =key;

}/*** 构造器*/

publicXDocService() {this(DEFAULT_URL, DEFAULT_KEY);

}/*** 构造器

*

*@paramurl 服务地址*/

publicXDocService(String url) {this(url, DEFAULT_KEY);

}/*** 构造器

*

*@paramurl 服务地址

*@paramkey 账号*/

publicXDocService(String url, String key) {this.url =url;this.key =key;

}/*** 转换为其它格式文件

*

*@paramxdoc xdoc

*@paramfile 其它格式文件,如:a.pdf

*@throwsIOException*/

public void to(File xdoc, File file) throwsIOException {

to(xdoc.getAbsolutePath(), file);

}/*** 转换为其它格式文件

*

*@paramxdoc xdoc文本

* URL:文档URL地址,格式支持:xdoc、json、docx、epub、txt、rtf等,支持datauri协议,可传递二进制数据,支持本地文件

* 纯文本:以"text:"开头的文本

* JSON:符合XDOC-JSON规范的JSON文本

* XML:符合XDOC-XML规范的XML文本

* HTML:用html标签括起来的html文本,如:<html><h1>Hello</h1></html>

*@paramfile 其它格式文件,如:a.pdf

*@throwsIOException*/

public void to(String xdoc, File file) throwsIOException {

to(xdoc,newFileOutputStream(file), getFormat(file.getName()));

}/*** 转换为其它格式,保存到指定流中

*

*@paramxdoc xdoc

*@paramout 输出目标,OutputStream或HttpServletResponse

*@paramformat format

*@throwsIOException*/

public void to(String xdoc, Object out, String format) throwsIOException {

Map param = new HashMap();

param.put("_func", "to");

param.put("_xdoc", xdoc);

param.put("_format", format);

invoke(checkParam(param), out);

}/*** 转换为其它格式并发送

*

*@paramxdoc xdoc

*@paramto 目标,支持ftp、http、mail、datauri等

*@paramformat format

*@throwsIOException*/

public String to(String xdoc, String to, String format) throwsIOException {

Map param = new HashMap();

param.put("_func", "to");

param.put("_xdoc", xdoc);

param.put("_to", to);

param.put("_format", format);

ByteArrayOutputStream out= newByteArrayOutputStream();

invoke(checkParam(param), out);return new String(out.toByteArray(), "UTF-8");

}/*** 运行xdoc

*

*@paramxdoc xdoc

*@paramparam 参数

*@paramfile 目标文件

*@throwsIOException*/

public void run(File xdoc, Map param, File file) throwsIOException {if (!param.containsKey("_xformat")) {

param.put("_xformat", getFormat(file.getName()));

}

run(xdoc.getAbsolutePath(), param, file);

}/*** 运行xdoc

*

*@paramxdoc xdoc

*@paramparam 参数

*@paramfile 目标文件

*@throwsIOException*/

public void run(String xdoc, Map param, File file) throwsIOException {

run(xdoc, param,newFileOutputStream(file), getFormat(file.getName()));

}/*** 运行xdoc

*

*@paramxdoc xdoc

*@paramparam 参数

*@paramout 输出目标,OutputStream或HttpServletResponse

*@paramformat 目标格式

*@throwsIOException*/

public void run(String xdoc, Map param, Object out, String format) throwsIOException {

param.put("_func", "run");

param.put("_xdoc", xdoc);

param.put("_format", format);

invoke(checkParam(param), out);

}/*** 运行xdoc并发送

*

*@paramxdoc xdoc

*@paramparam 参数

*@paramto 目标,支持ftp、http、mail、datauri等

*@paramformat 目标格式

*@throwsIOException*/

public String run(String xdoc, Map param, String to, String format) throwsIOException {

param.put("_func", "run");

param.put("_xdoc", xdoc);

param.put("_to", to);

param.put("_format", format);

ByteArrayOutputStream out= newByteArrayOutputStream();

invoke(checkParam(param), out);return new String(out.toByteArray(), "UTF-8");

}/*** 运行注解XDoc

*

*@paramobj

*@paramfile

*@throwsIOException*/

public void run(Object obj, File file) throwsIOException {

run(obj,newFileOutputStream(file), getFormat(file.getName()));

}/*** 运行注解XDoc

*

*@paramobj

*@paramout 目标流

*@paramformat 目标格式

*@throwsIOException*/

public void run(Object obj, Object out, String format) throwsIOException {

run(obj, out,null, format);

}/*** 运行注解XDoc

*

*@paramobj

*@paramto 目标,支持ftp、http、mail、datauri等

*@paramformat 目标格式

*@throwsIOException*/

public void run(Object obj, String to, String format) throwsIOException {

run(obj,null, to, format);

}private void run(Object obj, Object out, String to, String format) throwsIOException {

String xurl= "";

XDoc xdoc= obj.getClass().getAnnotation(XDoc.class);if (xdoc != null) {

xurl=xdoc.value();

}if (xurl.length() == 0) {

xurl= "./" + obj.getClass().getSimpleName() + ".xdoc";

}

Field[] fields=obj.getClass().getDeclaredFields();boolean hasXParam = false;

XParam xParam;

Map param = new HashMap();

String name;

Object value;for(Field field : fields) {

xParam= field.getAnnotation(XParam.class);if (xParam != null) {

hasXParam= true;

name=xParam.value();if (name.length() == 0) {

name=field.getName();

}try{

field.setAccessible(true);

value=field.get(obj);if (name.equals("_xdoc")) {

xurl=String.valueOf(value);

}else{

param.put(name, value);

}

}catch(Exception e) {throw newIOException(e);

}

}

}if (!hasXParam) { //没有指定xparam,传入所有属性

for(Field field : fields) {try{

field.setAccessible(true);

param.put(field.getName(), field.get(obj));

}catch(Exception e) {throw newIOException(e);

}

}

}if (out != null) {this.run(xurl, param, out, format);

}else{this.run(xurl, param, to, format);

}

}/*** 招呼

*

*@return*@throwsIOException*/

public boolean hi() throwsIOException {return invokeStringFunc("hi").equals("ok");

}/*** 关于*/

public String about() throwsIOException {return invokeStringFunc("about");

}/*** 动态口令

*

*@return*@throwsIOException*/

public String dkey() throwsIOException {return invokeStringFunc("dkey");

}/*** 修改口令

*

*@return*@throwsIOException*/

public String ckey() throwsIOException {return invokeStringFunc("ckey");

}/*** 注册

*

*@parammail 邮件

*@return*@throwsIOException*/

public String reg(String mail) throwsIOException {

Map params = new HashMap();

params.put("_func", "reg");

params.put("_mail", mail);

ByteArrayOutputStream out= newByteArrayOutputStream();

invoke(params, out);return(String) parse(out.toByteArray());

}/*** 账户信息

*

*@return*@throwsIOException*/@SuppressWarnings("unchecked")public Map acc() throwsIOException {

Map params = new HashMap();

params.put("_func", "acc");

ByteArrayOutputStream out= newByteArrayOutputStream();

invoke(params, out);return (Map) parse(out.toByteArray());

}/*** 基于ID上传

*

*@paramid

*@paramfile

*@return*@throwsIOException*/

public void sup(String id, File file) throwsIOException {

sup(id, toDataURI(file.getAbsolutePath()));

}/*** 基于ID上传

*

*@paramid

*@paramin

*@throwsIOException*/

public void sup(String id, InputStream in) throwsIOException {

sup(id, toDataURI(in));

}private void sup(String id, String dataUri) throwsIOException {

Map params = new HashMap();

params.put("_func", "sup");

params.put("_id", id);

params.put("_data", dataUri);

ByteArrayOutputStream out= newByteArrayOutputStream();

invoke(params, out);

parse(out.toByteArray());

}/*** 基于ID下载

*

*@paramid

*@paramfile

*@throwsIOException*/

public void sdown(String id, File file) throwsIOException {

sdown(id,newFileOutputStream(file));

}/*** 基于ID下载

*

*@paramid

*@paramout 输出目标,OutputStream或HttpServletResponse

*@throwsIOException*/

public void sdown(String id, Object out) throwsIOException {

Map params = new HashMap();

params.put("_func", "sdown");

params.put("_id", id);

invoke(params, out);

}/*** 基于ID删除

*

*@paramid

*@return*@throwsIOException*/

public boolean sremove(String id) throwsIOException {

Map params = new HashMap();

params.put("_func", "sremove");

params.put("_id", id);

ByteArrayOutputStream out= newByteArrayOutputStream();

invoke(params, out);return parse(out.toByteArray()).equals("ok");

}/*** 创建目录

*

*@paramdir

*@return*@throwsIOException*/

public boolean mkdir(String dir) throwsIOException {

Map params = new HashMap();

params.put("_func", "mkdir");

params.put("_dir", dir);

ByteArrayOutputStream out= newByteArrayOutputStream();

invoke(params, out);return parse(out.toByteArray()).equals("ok");

}/*** 目录列表

*

*@paramdir

*@return*@throwsIOException*/@SuppressWarnings("unchecked")public List> dirlist(String dir) throwsIOException {

Map params = new HashMap();

params.put("_func", "dirlist");

params.put("_dir", dir);

ByteArrayOutputStream out= newByteArrayOutputStream();

invoke(params, out);return (List>) parse(out.toByteArray());

}/*** 文件列表

*

*@paramdir

*@return*@throwsIOException*/@SuppressWarnings("unchecked")public List> filelist(String dir) throwsIOException {

Map params = new HashMap();

params.put("_func", "filelist");

params.put("_dir", dir);

ByteArrayOutputStream out= newByteArrayOutputStream();

invoke(params, out);return (List>) parse(out.toByteArray());

}/*** 上传

*

*@paramdir

*@paramfile

*@return*@throwsIOException*/

public void up(String dir, File file) throwsIOException {

up(dir, toDataURI(file.getAbsolutePath()));

}/*** 上传

*

*@paramdir

*@paramin

*@throwsIOException*/

public void up(String dir, InputStream in) throwsIOException {

up(dir, toDataURI(in));

}private void up(String dir, String dataUri) throwsIOException {

Map params = new HashMap();

params.put("_func", "up");

params.put("_dir", dir);

params.put("_data", dataUri);

ByteArrayOutputStream out= newByteArrayOutputStream();

invoke(params, out);

parse(out.toByteArray());

}/*** 下载

*

*@paramdir

*@paramfile

*@throwsIOException*/

public void down(String dir, File file) throwsIOException {

down(dir,newFileOutputStream(file));

}/*** 下载

*

*@paramdir

*@paramout 输出目标,OutputStream或HttpServletResponse

*@throwsIOException*/

public void down(String dir, Object out) throwsIOException {

Map params = new HashMap();

params.put("_func", "down");

params.put("_dir", dir);

invoke(params, out);

}/*** 删除

*

*@paramdir

*@return*@throwsIOException*/

public boolean remove(String dir) throwsIOException {

Map params = new HashMap();

params.put("_func", "remove");

params.put("_dir", dir);

ByteArrayOutputStream out= newByteArrayOutputStream();

invoke(params, out);return parse(out.toByteArray()).equals("ok");

}/*** 文件是否存在

*

*@paramdir

*@return*@throwsIOException*/

public boolean exists(String dir) throwsIOException {

Map params = new HashMap();

params.put("_func", "exists");

params.put("_dir", dir);

ByteArrayOutputStream out= newByteArrayOutputStream();

invoke(params, out);return parse(out.toByteArray()).equals("true");

}/*** 数据查询

*

*@paramsql SQL

*@return*@throwsIOException*/@SuppressWarnings("unchecked")public List> query(String sql) throwsIOException {

Map params = new HashMap();

params.put("_func", "query");

params.put("_sql", sql);

ByteArrayOutputStream out= newByteArrayOutputStream();

invoke(params, out);return (List>) parse(out.toByteArray());

}/*** 基于ID的XDATA转换

*

*@paramid

*@paramformat 目标格式:xml、json、csv

*@return*@throwsIOException*/

public String xdataById(String id, String format) throwsIOException {

Map params = new HashMap();

params.put("_func", "xdata");

params.put("_id", id);

params.put("_format", format);

ByteArrayOutputStream out= newByteArrayOutputStream();

invoke(params, out);return(String) parse(out.toByteArray());

}/*** XDATA转换

*

*@paramdata xdata数据,格式:xml、json、csv

*@paramformat 目标格式:xml、json、csv

*@return*@throwsIOException*/

public String xdata(String xdata, String format) throwsIOException {

Map params = new HashMap();

params.put("_func", "xdata");

params.put("_xdata", xdata);

params.put("_format", format);

ByteArrayOutputStream out= newByteArrayOutputStream();

invoke(params, out);return(String) parse(out.toByteArray());

}/*** 通过url地址调用服务,支持本地文件xdoc和xdata

*

*@paramargs*/

public static voidmain(String[] args) {if (args.length > 0 && args[0].length() > 0) {

String url= args[0];if (url.charAt(0) == '@') { //命令文件

File cmdFile = new File(url.substring(1));try{

FileReader reader= newFileReader(cmdFile);

url= (newBufferedReader(reader)).readLine();

reader.close();

cmdFile.delete();

}catch(Exception e) {

e.printStackTrace();return;

}

}

String server=DEFAULT_URL;int pos = url.indexOf('?');if (pos > 0) {

server= url.substring(0, pos);if (server.endsWith("/xdoc")) {

server= server.substring(0, server.length() - 5);

}

url= url.substring(pos + 1);

}

String xkey= "";try{

String[] params= url.split("&");

Map map = new HashMap();

String key, value;

String to= null;for (int i = 0; i < params.length; i++) {

pos= params[i].indexOf('=');if (pos > 0) {

key= decode(params[i].substring(0, pos));

value= decode(params[i].substring(pos + 1));if(isXDocData(key, value)) {

value=toDataURI(value);

}else if (key.indexOf("@file") > 0) {

key= key.substring(0, key.length() - 5);

value=toDataURI(value);

}else if (key.equals("_key")) {

xkey=value;continue;

}else if (key.equals("_to") &&isFile(value)) {

to=value;continue;

}

map.put(key, value);

}

}if (!map.containsKey("_format") && to != null && to.indexOf('.') > 0) {

map.put("_format", to.substring(to.lastIndexOf('.') + 1));

}

XDocService client= newXDocService(server, xkey);

OutputStream out;if (to != null) {

out= newFileOutputStream(to);

}else{

out=System.out;

}

client.invoke(map, out);if (to != null) {

out.flush();

out.close();

System.out.println(">> " +to);

}

}catch(Exception e) {

e.printStackTrace();

}

}

}private void invoke(Map param, Object out) throwsIOException {

String xurl= this.url + (this.url.endsWith("/") ? "xdoc" : "/xdoc");

HttpURLConnection httpConn= (HttpURLConnection) newURL(xurl).openConnection();

httpConn.setDoOutput(true);

OutputStream reqOut=httpConn.getOutputStream();

reqOut.write(("&_key=").getBytes());

reqOut.write(encode(this.key).getBytes());

Iterator it =param.keySet().iterator();

String key;while(it.hasNext()) {

key=it.next();

reqOut.write(("&" + encode(key) + "=").getBytes());

reqOut.write(encode(param.get(key)).getBytes());

}

reqOut.flush();

reqOut.close();

OutputStream os= null;if (out instanceofOutputStream) {

os=(OutputStream) out;

}else{try{

Method method= out.getClass().getMethod("getOutputStream");

os=(OutputStream) method.invoke(out);

method= out.getClass().getMethod("setHeader", String.class, String.class);

String[] headerNames= new String[]{"Content-Type", "Content-Disposition"};

String headerValue;for(String headerName : headerNames) {

headerValue=httpConn.getHeaderField(headerName);if (headerValue != null) {

method.invoke(out, headerName, headerValue);

}

}

}catch(Exception e) {throw newIOException(e);

}

}

pipe(httpConn.getInputStream(), os);

}private Object parse(byte[] data) throwsIOException {

DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();

factory.setValidating(false);try{

DocumentBuilder builder=factory.newDocumentBuilder();

Document document= builder.parse(newByteArrayInputStream(data));

document.getDocumentElement().normalize();

Element root=document.getDocumentElement();if (root.getAttribute("success").equals("true")) {

Element result= (Element) root.getElementsByTagName("result").item(0);

String dataType= result.getAttribute("dataType");if (dataType.equals("string")) {returnresult.getTextContent();

}else if (dataType.equals("map")) {

NodeList items= result.getElementsByTagName("value");

Map map = new HashMap();

Element value;

NamedNodeMap atts;for (int i = 0; i < items.getLength(); i++) {

value=(Element) items.item(i);

atts=value.getAttributes();for (int j = 0; j < atts.getLength(); j++) {

map.put(atts.item(j).getNodeName(), atts.item(j).getNodeValue());

}

}returnmap;

}else if (dataType.equals("rowset")) {

Map fieldMap = new HashMap();

String[] fields= result.getAttribute("fields").split(",");

String[] formerFields=fields;if (result.hasAttribute("formerFields")) {

formerFields= csvSplit(result.getAttribute("formerFields"));

}for (int j = 0; j < formerFields.length; j++) {

fieldMap.put(fields[j], formerFields[j]);

}

NodeList eleList= result.getElementsByTagName("row");

Element ele;

Mapmap;

List> List = new ArrayList>();for (int i = 0; i < eleList.getLength(); i++) {

ele=(Element) eleList.item(i);

map= new HashMap();

List.add(map);for (int j = 0; j < fields.length; j++) {

map.put(formerFields[j], ele.getAttribute(fields[j]));

}

}returnList;

}else{return "";

}

}else{throw new IOException(root.getElementsByTagName("error").item(0).getTextContent());

}

}catch(ParserConfigurationException e) {throw newIOException(e);

}catch(SAXException e) {throw newIOException(e);

}

}private String invokeStringFunc(String func) throwsIOException {

Map params = new HashMap();

params.put("_func", func);

ByteArrayOutputStream out= newByteArrayOutputStream();

invoke(params, out);return(String) parse(out.toByteArray());

}private Map checkParam(Map param) throwsIOException {

Map map = new HashMap();

String key, value;

Iterator it =param.keySet().iterator();while(it.hasNext()) {

key=it.next();

value=toParamString(param.get(key));if(isXDocData(key, value)) {

value=toDataURI(value);

}else if (key.endsWith("@file")) {

key= key.substring(0, key.length() - 5);

value=toDataURI(value);

}

map.put(key, value);

}returnmap;

}private static String toParamString(Object obj) throwsIOException {

String str;if (obj == null) {

str= "";

}else if(obj.getClass().isPrimitive()|| obj instanceofBoolean|| obj instanceofNumber|| obj instanceofCharSequence) {

str=obj.toString();

}else if (obj instanceofDate) {

str= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format((Date) obj);

}else if (obj instanceofFile) {

str=toDataURI(((File) obj).getAbsolutePath());

}else if (obj instanceofInputStream) {

str=toDataURI((InputStream) obj);

}else{

StringBuilder sb= newStringBuilder();

Set chainSet = new HashSet();

writeParamString(sb, obj, chainSet);

str=sb.toString();

}returnstr;

}private static void writeParamString(StringBuilder sb, Object obj, Set set) throwsIOException {if (obj == null) {

sb.append("null");

}else if(obj.getClass().isPrimitive()|| obj instanceofBoolean|| obj instanceofNumber) {

sb.append(toParamString(obj));

}else if (obj instanceofCharSequence|| obj instanceofDate) {

jencode(toParamString(obj), sb);

}else if (obj instanceofCollection) {

sb.append("[");boolean b = false;

Iterator> it = ((Collection>) obj).iterator();while(it.hasNext()) {if (b) sb.append(",");

writeParamString(sb, it.next(), set);

b= true;

}

sb.append("]");

}else if(obj.getClass().isArray()) {

sb.append("[");boolean b = false;int n =Array.getLength(obj);for (int i = 0; i < n; i++) {if (b) sb.append(",");

writeParamString(sb, Array.get(obj, i), set);

b= true;

}

sb.append("]");

}else if (obj instanceofMap) {

sb.append("{");

Map, ?> map = (Map, ?>) obj;boolean b = false;

Object key;

Iterator> it =map.keySet().iterator();while(it.hasNext()) {if (b) sb.append(",");

key=it.next();

jencode(key.toString(), sb);

sb.append(":");

writeParamString(sb, map.get(key), set);

b= true;

}

sb.append("}");

}else{

sb.append("{");if (!set.contains(obj) && obj.getClass() != Object.class && obj.getClass() != Class.class) {

set.add(obj);try{boolean b = false;

BeanInfo bi= Introspector.getBeanInfo(obj.getClass(), Object.class);

PropertyDescriptor[] pds=bi.getPropertyDescriptors();

Object res;

Method method;for(PropertyDescriptor pd : pds) {

method=pd.getReadMethod();if (method != null) {if (b) sb.append(",");

jencode(pd.getName(), sb);

sb.append(":");

res= method.invoke(obj, new Object[0]);

writeParamString(sb, res, set);

b= true;

}

}

}catch(Exception e) {throw newIOException(e);

}

set.remove(obj);

}

sb.append("}");

}

}private static voidjencode(String str, StringBuilder sb) {

sb.append("\"");charc;for (int i = 0; i < str.length(); i++) {

c=str.charAt(i);if (c == '\\') {

sb.append("\\\\");

}else if (c == '/') {

sb.append("\\/");

}else if (c == '\n') {

sb.append("\\n");

}else if (c == '\r') {

sb.append("\\r");

}else if (c == '\t') {

sb.append("\\t");

}else if (c == '\'') {

sb.append("\\\'");

}else if (c == '\"') {

sb.append("\\\"");

}else{

sb.append(c);

}

}

sb.append("\"");

}private static booleanisXDocData(String name, String value) {if (name.equals("_xdoc") || name.equals("_xdata")) {if (value.startsWith("./")|| value.startsWith("

}else{return true;

}

}return false;

}private staticString getFormat(String url) {

String format= "xdoc";int pos = url.lastIndexOf(".");if (pos > 0) {

format= url.substring(pos + 1).toLowerCase();if (format.equals("zip")) {

url= url.substring(0, pos);

pos= url.lastIndexOf(".");if (pos > 0) {

format= url.substring(pos + 1).toLowerCase() + ".zip";

}

}

}returnformat;

}private staticString encode(Object str) {try{return URLEncoder.encode(String.valueOf(str), "UTF-8");

}catch(UnsupportedEncodingException e) {returnString.valueOf(str);

}

}private staticString decode(String str) {try{return URLDecoder.decode(str, "UTF-8");

}catch(UnsupportedEncodingException e) {returnstr;

}

}private static void pipe(InputStream in, OutputStream out) throwsIOException {intlen;byte[] buf = new byte[4096];while (true) {

len=in.read(buf);if (len > 0) {

out.write(buf,0, len);

}else{break;

}

}

out.flush();

out.close();

in.close();

}private static booleanisFile(String url) {int pos = url.indexOf(':');return pos < 0

|| pos == 1

|| (pos == 2 && url.charAt(0) == '/');

}private static String toDataURI(InputStream in) throwsIOException {

ByteArrayOutputStream out= newByteArrayOutputStream();

pipe(in, out);

StringBuffer sb= newStringBuffer();

sb.append("data:application/octet-stream;base64,");

sb.append(toBase64(out.toByteArray()));returnsb.toString();

}private static String toDataURI(String url) throwsIOException {if (url.length() > 0) {

StringBuffer sb= newStringBuffer();

String format= null;

;

InputStream in= null;if (isFile(url) || url.startsWith("class://")) {int pos = url.lastIndexOf('.');if (pos > 0) {

format= url.substring(pos + 1);if (format.equals("jpg")) {

format= "jpeg";

}else if (format.equals("htm")) {

format= "html";

}if (format.equals("png") || format.equals("jpeg") || format.equals("gif")) {

format= "image/" +format;

}else if (format.equals("html") || format.equals("xml")) {

format= "text/" +format;

}else{

format= "application/" +format;

}

}if (url.startsWith("class://")) {

String cls= url.substring(8, url.indexOf("/", 8));

String path= url.substring(url.indexOf("/", 8) + 1);try{

in=Class.forName(cls).getResourceAsStream(path);

}catch(Exception e) {throw newIOException(e);

}

}else{

in= newFileInputStream(url);

}

}else{

URLConnection conn= newURL(url).openConnection();

in=conn.getInputStream();

format=((HttpURLConnection) conn).getContentType();

}if (format == null) {

format= "application/octet-stream";

}

ByteArrayOutputStream out= newByteArrayOutputStream();

pipe(in, out);

sb.append("data:").append(format).append(";base64,");

sb.append(toBase64(out.toByteArray()));returnsb.toString();

}else{return "";

}

}private static String toBase64(final byte[] data) {final char[] out = new char[((data.length + 2) / 3) * 4];for (int i = 0, index = 0; i < data.length; i += 3, index += 4) {boolean quad = false;boolean trip = false;int val = (0xFF &data[i]);

val<<= 8;if ((i + 1)

val|= (0xFF & data[i + 1]);

trip= true;

}

val<<= 8;if ((i + 2)

val|= (0xFF & data[i + 2]);

quad= true;

}

out[index+ 3] = alphabet[(quad ? (val & 0x3F) : 64)];

val>>= 6;

out[index+ 2] = alphabet[(trip ? (val & 0x3F) : 64)];

val>>= 6;

out[index+ 1] = alphabet[val & 0x3F];

val>>= 6;

out[index+ 0] = alphabet[val & 0x3F];

}return newString(out);

}private static char[] alphabet =

"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".toCharArray();private static byte[] codes = new byte[256];static{for (int i = 0; i < 256; i++) {

codes[i]= -1;

}for (int i = 'A'; i <= 'Z'; i++) {

codes[i]= (byte) (i - 'A');

}for (int i = 'a'; i <= 'z'; i++) {

codes[i]= (byte) (26 + i - 'a');

}for (int i = '0'; i <= '9'; i++) {

codes[i]= (byte) (52 + i - '0');

}

codes['+'] = 62;

codes['/'] = 63;

}private staticString[] csvSplit(String str) {

List> list =csvList(str);if (list.size() > 0) {

List cols = (List) list.get(0);

String[] strs= newString[cols.size()];for (int i = 0; i < strs.length; i++) {

strs[i]=cols.get(i);

}returnstrs;

}else{return new String[0];

}

}private static List>csvList(String txt) {if (txt.length() > 0) {

ArrayList> rows = new ArrayList>();

ArrayList cols = new ArrayList();

rows.add(cols);charc;boolean strBegin = false;

StringBuffer sb= newStringBuffer();for (int i = 0; i < txt.length(); i++) {

c=txt.charAt(i);if(strBegin) {if (c == '"') {if (i + 1

sb.append(c);

i++;

}else{

strBegin= false;

}

}else{

strBegin= false;

}

}else{

sb.append(c);

}

}else{if (c == ',') {

cols.add(sb.toString());

sb.setLength(0);

}else if (c == '\n') {

cols.add(sb.toString());

sb.setLength(0);

cols= new ArrayList();

rows.add(cols);

}else if (c == '"') {

strBegin= true;

}else if (c != '\r') {

sb.append(c);

}

}

}if (sb.length() > 0) {

cols.add(sb.toString());

}returnrows;

}else{return new ArrayList>();

}

}/*** XDOC注解

*

*@authorXDOC*/@Target(ElementType.TYPE)

@Retention(RetentionPolicy.RUNTIME)

@Documentedpublic @interfaceXDoc {/*** xdoc

*

*@return

*/

public String value() default "";

}/*** XDOC参数注解

*

*@authorXDOC*/@Target(ElementType.FIELD)

@Retention(RetentionPolicy.RUNTIME)

@Documentedpublic @interfaceXParam {/*** 参数名称

*

*@return

*/

public String value() default "";

}

}

 类似资料: