博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Java Swing窗体小工具实例 - 原创
阅读量:5241 次
发布时间:2019-06-14

本文共 59930 字,大约阅读时间需要 199 分钟。

Java Swing窗体小工具实例

 

  1、本地webserice发布,代码如下:

1.1 JdkWebService.java

package server;import java.net.InetAddress;import java.net.UnknownHostException;import javax.jws.WebParam;import javax.jws.WebService;import javax.xml.ws.Endpoint;import org.apache.log4j.Logger;@WebServicepublic class JdkWebService {    private static Logger logger = Logger.getLogger(JdkWebService.class.getName());        public String communicationTest(@WebParam(name="XML", /*targetNamespace = "http://para/",*/ mode = WebParam.Mode.IN)String xml) {        return "成功接收:" + xml;    }        public static void main(String[] args) {        try {            String hostAddress = InetAddress.getLocalHost().getHostAddress();            Endpoint.publish("http://" + hostAddress + ":18080/webservice/demo", new JdkWebService());            System.out.println("Webservice 发布成功!");        } catch (UnknownHostException e) {            logger.error(e);        }    }}
代码块

 

  2、Client客户端窗体

    通过地址,发送(XML格式字符串)数据,然后接收返回的数据并显示在Swing窗体文本框内,对字符串数据加解密。

    加解密所需jar包:org.apache.commons.codec_1.3.0.v201101211617.jar

    HTTP发送wsdl所需jar包:axis.jar、jaxrpc.jar、wsdl4j-1.6.2.jar、commons-logging-1.1.jar、commons-discovery-0.2.jar

2.1 ClienrFrame.java

package client;import java.awt.Dimension;import java.awt.Font;import java.awt.Toolkit;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.WindowEvent;import java.io.File;import java.net.InetAddress;import java.net.UnknownHostException;import java.util.Locale;import javax.swing.JButton;import javax.swing.JFileChooser;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JOptionPane;import javax.swing.JPanel;import javax.swing.JScrollPane;import javax.swing.JTextArea;import javax.swing.JTextField;import javax.xml.ws.Endpoint;import org.apache.log4j.Logger;import cn.sanxing.cim.util.CimEncodeUtil;import server.JdkWebService;public class ClientFrame extends JFrame implements ActionListener {    private static final long serialVersionUID = 1L;    private static Logger logger = Logger.getLogger(ClientFrame.class.getName());    JFrame mainFrame = new JFrame("Client-Interface Tool");    JPanel panel;    // 相关的Label标签    JLabel url_lable = new JLabel("URL :");    JLabel requestXML_lable = new JLabel("RequestXML :");    JLabel responseXML_lable = new JLabel("ResponseXML :");    // 相关的文本域    JTextField url_textfield = new JTextField(20);    // 滚动条以及请求的XML    JScrollPane jscrollPane;    JTextArea requestXML_textarea = new JTextArea();    // 滚动条以及返回的XML    JScrollPane jscrollPane1;    JTextArea responseXML_textarea = new JTextArea();    // 按钮    JButton xmlIport_button = new JButton("Import");    JButton encode_button = new JButton("Encrypt");    JButton send_button = new JButton("Send");    JButton decode_button = new JButton("Decrypt");    // String[] types = {"AXIS", "CXF"};    // JComboBox
webservice_type = new JComboBox
(types); // 标志 String encrypted_requestXML = null; String decrypted_responseXML = null; public void showFrame() { initPanel();// 初始化面板 initFrame();// 初始化窗体 } // 初始化窗体 public void initFrame() { // Setting the width and height of frame mainFrame.setSize(675, 590); mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); mainFrame.setResizable(false);// 固定窗体大小 Toolkit kit = Toolkit.getDefaultToolkit(); // 工具包 Dimension screenSize = kit.getScreenSize(); // 屏幕的尺寸 int screenWidth = screenSize.width / 2; // 屏幕的宽 int screenHeight = screenSize.height / 2; // 屏幕的高 int height = mainFrame.getHeight(); // 窗口高度 int width = mainFrame.getWidth(); // 窗口宽度 mainFrame.setLocation(screenWidth - width / 2, screenHeight - height / 2);// 将窗口设置到屏幕的中部 // Image myimage = kit.getImage("resourse/hxlogo.gif"); // 由tool获取图像 // mainframe.setIconImage(myimage); mainFrame.add(panel); mainFrame.setVisible(true); } // 初始化面板 public void initPanel() { this.panel = new JPanel(); panel.setLayout(null); // this.panel = new JPanel(new GridLayout(3,2)); //3行3列的容器 url_lable.setBounds(25, 20, 100, 25); this.panel.add(url_lable); // 地址输入框 url_textfield.setBounds(63, 20, 310, 25); this.panel.add(url_textfield); // webservice 类型 // webservice_type.setBounds(385, 20, 78, 25); // this.panel.add(webservice_type); // 导入按钮 xmlIport_button.setBounds(385, 20, 78, 25); this.panel.add(xmlIport_button); // 加密按钮 encode_button.setBounds(475, 20, 78, 25); this.panel.add(encode_button); // 发送按钮 send_button.setBounds(565, 20, 78, 25); this.panel.add(send_button); // 请求XML Label requestXML_lable.setBounds(10, 65, 80, 25); this.panel.add(requestXML_lable); // 请求XML文本框 // requestXML_textarea.setEditable(false); requestXML_textarea.setFont(new Font("标楷体", 12, 13)); jscrollPane = new JScrollPane(requestXML_textarea); jscrollPane.setBounds(10, 85, 650, 200); this.panel.add(jscrollPane); // 返回XML Label responseXML_lable.setBounds(10, 310, 90, 25); this.panel.add(responseXML_lable); // 返回XML文本框 responseXML_textarea.setFont(new Font("标楷体", 12, 13)); jscrollPane1 = new JScrollPane(responseXML_textarea); jscrollPane1.setBounds(10, 330, 650, 200); this.panel.add(jscrollPane1); // 解密按钮 decode_button.setBounds(565, 296, 78, 28); this.panel.add(decode_button); // 避免重复加解密 encrypted_requestXML = requestXML_textarea.getText(); decrypted_responseXML = responseXML_textarea.getText(); // 动作监听 xmlIport_button.addActionListener(this); encode_button.addActionListener(this); send_button.addActionListener(this); decode_button.addActionListener(this); } /** * 单击动作触发方法 * * @param event */ @Override public void actionPerformed(ActionEvent event) { // System.out.println(event.getActionCommand()); // 导入 if (event.getSource() == xmlIport_button) { xmlImport(); } // 加密 if (event.getSource() == encode_button) { encode(); } // 发送 if (event.getSource() == send_button) { send(); } // 解密 if (event.getSource() == decode_button) { decode(); } } // 导入 public void xmlImport() { File file = ClientUtil.openChoseWindow(JFileChooser.FILES_ONLY); if (file == null) { // JOptionPane.showMessageDialog(this.panel, "The file is not // exist.", // "Tips", 2);// 弹出提示对话框,warning return; } String xml_content = ClientUtil.readFile(file.getAbsolutePath()); requestXML_textarea.setText(xml_content); // System.out.println("The xml was imported seccessfully!"); } // 加密 public void encode() { String requestXML = ClientUtil.getString(requestXML_textarea.getText()); if (ClientUtil.isEmptyString(requestXML)) { JOptionPane.showMessageDialog(null, "The request is empty.", "Tips", 2);// 请求XML为空,warning return; } if (encrypted_requestXML.equals(requestXML)) {
// 不重复加密 return; } // System.out.println("Before encode:" + requestXML); String afterEncodeXML = ClientUtil.compressAndEncode(requestXML); // System.out.println("After dncode:" + encodeXML); if (ClientUtil.isEmptyString(afterEncodeXML)) { JOptionPane.showMessageDialog(null, "Encode failed!", "Tips", 2);// 加密失败,warning return; } encrypted_requestXML = ClientUtil.getString(afterEncodeXML); requestXML_textarea.setText(afterEncodeXML); } // 发送 public void send() { // System.out.println(url_textfield.getText()); boolean enCodeFlag = CimEncodeUtil.enCodeFlag; String url = ClientUtil.getString(url_textfield.getText()); String requestXML = ClientUtil.getString(requestXML_textarea.getText()); if (ClientUtil.isEmptyString(url)) { JOptionPane.showMessageDialog(null, "The URL is empty.", "Tips", 2);// 地址为空,warning return; } if (ClientUtil.isEmptyString(requestXML)) { JOptionPane.showMessageDialog(null, "The request is empty.", "Tips", 2);// 请求XML为空,warning return; } int index = url.lastIndexOf("?"); String type; if (url.lastIndexOf("?") > 0) { type = url.substring(index + 1, url.length()); } else { type = "http"; } String responseXML = ClientUtil.sendXml(url, requestXML, type); if (ClientUtil.isEmptyString(responseXML)) { responseXML_textarea.setText(responseXML); JOptionPane.showMessageDialog(null, "The response is empty, Please check the URL.", "Tips", 2);// 返回结果为空,warning return; } if (!enCodeFlag) { responseXML = ClientUtil.formatXML(responseXML); } responseXML_textarea.setText(responseXML); } // 解密 public void decode() { String responseXML = ClientUtil.getString(responseXML_textarea.getText()); if (ClientUtil.isEmptyString(responseXML)) { JOptionPane.showMessageDialog(null, "The result is empty.", "Tips", 2); return; } if (decrypted_responseXML.equals(responseXML)) {
// 不重复解密 return; } // System.out.println("Before decode:"+ responseXML_textarea.getText()); String afterDecodeXML = ClientUtil.decodeAndUncompress(responseXML); // System.out.println("After decode:"+ afterDecodeXML); // 解密失败 if (ClientUtil.isEmptyString(afterDecodeXML)) { JOptionPane.showMessageDialog(null, "Decryption failed!", "Tips", 2); return; } String afterFormatXML = ClientUtil.formatXML(afterDecodeXML); decrypted_responseXML = ClientUtil.getString(afterFormatXML); responseXML_textarea.setText(afterFormatXML); } public void windowClosed(WindowEvent arg0) { System.exit(0); } public void windowClosing(WindowEvent arg0) { System.exit(0); } public static void main(String[] args) { // 客户端 Locale.setDefault(Locale.ENGLISH); ClientFrame clientFrame = new ClientFrame(); clientFrame.showFrame(); // webservice发布 try { String hostAddress = InetAddress.getLocalHost().getHostAddress(); String url = "http://" + hostAddress + ":18080/webservice/demo"; Endpoint.publish(url, new JdkWebService()); JOptionPane.showConfirmDialog(null, "WebService address:\n" + url, "Local webService release success", 2); // System.out.println("WebService 发布成功!"); } catch (UnknownHostException e) { logger.error(e); } }}
客户端窗体代码

2.2 ClientUtil.java

package client;import java.io.BufferedInputStream;import java.io.BufferedReader;import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.OutputStream;import java.io.StringReader;import java.io.StringWriter;import java.net.HttpURLConnection;import java.net.URL;import java.rmi.RemoteException;import java.util.zip.GZIPInputStream;import java.util.zip.GZIPOutputStream;import javax.swing.JFileChooser;import javax.swing.JLabel;import javax.xml.namespace.QName;import javax.xml.rpc.ParameterMode;import javax.xml.rpc.ServiceException;import org.apache.axis.client.Call;import org.apache.axis.client.Service;import org.apache.axis.encoding.XMLType;import org.apache.commons.codec.binary.Base64;import org.apache.log4j.Logger;import org.dom4j.Document;import org.dom4j.DocumentException;import org.dom4j.io.OutputFormat;import org.dom4j.io.SAXReader;import org.dom4j.io.XMLWriter;public class ClientUtil {        private static Logger logger = Logger.getLogger(ClientUtil.class.getName());        public static String doPost(String path, String data, int timeout) throws Exception {        URL url = null;        HttpURLConnection conn = null;        InputStream is = null;        OutputStream os = null;        ByteArrayOutputStream bos = null;        String result = "";        try {            url = new URL(path);            conn = (HttpURLConnection) url.openConnection();            conn.setRequestMethod("POST");            conn.setReadTimeout(timeout);            conn.setConnectTimeout(timeout);            conn.setRequestProperty("Connection", "keep-alive");            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");            conn.setRequestProperty("Content-Length", String.valueOf(data.getBytes().length));            conn.setDoOutput(true); // 必须设置允许输出            conn.setDoInput(true); // 必须设置允许输入            os = conn.getOutputStream();            os.write(data.getBytes());            os.flush();            if (conn.getResponseCode() == 200) {                is = conn.getInputStream();                bos = new ByteArrayOutputStream();                int len = 0;                byte buffer[] = new byte[1024];                while ((len = is.read(buffer)) != -1) {                    bos.write(buffer, 0, len);                }                result = new String(bos.toByteArray());                bos.close();                is.close();                return result;            } else {                return null;            }        } catch (Exception e) {            throw e;        } finally {            try {                if (conn != null)                    conn.disconnect();                if (null != bos)                    bos.close();                if (null != is)                    is.close();            } catch (IOException e) {                logger.error("msg:", e);            }        }    }        //发送RequestXML    public static String sendXml(String url, String xml, String type) {        String mdcAddress = url;//        String mdcPath = sysMap.get("mdcPath");        String mdcXml="null";        try {            if("http".equals(type)){                mdcXml = doPost(mdcAddress,"xml="+xml,20000);            } else if("wsdl".equals(type)){                mdcXml = invokeRemoteFuc(mdcAddress,xml);            }        } catch (Exception e) {            logger.error("msg:", e);        }        return mdcXml;    }        public static String invokeRemoteFuc(String endpoint, String xml) {//        String endpoint = "http://localhost:8080/webservice/services/helloworld";        String result = null;        Service service = new Service();        Call call;        Object[] object = new Object[1];        object[0] = xml;//Object是用来存储方法的参数        try {            call = (Call) service.createCall();            call.setTargetEndpointAddress(endpoint);// 远程调用路径//            call.setOperationName("communicationTest");// 调用的方法名              //            if(type.equals("CXF")){//                call.setOperationName(new QName("", "communicationTest"));//            }//            if(type.equals("AXIS")){
call.setOperationName(new QName("http://server/", "communicationTest"));// 调用的方法名// } // 设置参数名: call.addParameter("XML", // 参数名 XMLType.XSD_STRING,// 参数类型:String ParameterMode.IN);// 参数模式:'IN' or 'OUT' // 设置返回值类型: call.setReturnType(XMLType.XSD_STRING);// 返回值类型:String result = (String) call.invoke(object);// 远程调用 } catch (ServiceException e) { logger.error("msg:", e); } catch (RemoteException e) { logger.error("msg:", e); } return result; } // Base64加密 public static String compressAndEncode(String xml) { byte[] xmlByte; try { xmlByte = xml.getBytes("UTF-8"); ByteArrayOutputStream outstream = new ByteArrayOutputStream(); GZIPOutputStream gzipOutstream; gzipOutstream = new GZIPOutputStream(outstream); gzipOutstream.write(xmlByte); gzipOutstream.close(); byte[] b = Base64.encodeBase64(outstream.toByteArray()); xml = new String(b); } catch (IOException e) {// logger.error("encode failed:", e); return null; } return xml; } //Base64解密 public static String decodeAndUncompress(String xml){ String s = ""; byte[] unencoded = Base64.decodeBase64(xml.getBytes()); ByteArrayInputStream bil = new ByteArrayInputStream(unencoded); GZIPInputStream gl; try { gl = new GZIPInputStream(bil); for (int c = gl.read(); c != -1; c = gl.read()) { s = s + (char) c; } } catch (IOException e) {// logger.error("解密失败:", e); return null; } return s; } //判空 public static final boolean isEmptyString(String s) { return s == null || s.trim().equals("") || s.equals("null") || s.equals("NULL") || s.trim().equals("undefined"); } public static String getString(Object s){ return s == null?"":String.valueOf(s).trim(); } //字符串格式化XML形式的字符串 public static String formatXML(String inputXML) { SAXReader reader = new SAXReader(); String requestXML = null; Document document; try { document = reader.read(new StringReader(inputXML)); XMLWriter writer = null; if (document != null) { try { StringWriter stringWriter = new StringWriter(); OutputFormat format = new OutputFormat(" ", true); writer = new XMLWriter(stringWriter, format); try { writer.write(document); writer.flush(); } catch (Exception e) { logger.error(e); } requestXML = stringWriter.getBuffer().toString(); } finally { if (writer != null) { try { writer.close(); } catch (IOException e) { logger.error(e); } } } } } catch (DocumentException e1) {// logger.error(e1); return inputXML;//非XML格式字符串 无法转换,返回原字符串 } return requestXML; } // 文件读取 public static String readFile(String filePath) { StringBuffer content = new StringBuffer(); String fileline; BufferedReader filedata = null; try { filedata = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), getCharset(filePath))); while ((fileline = filedata.readLine()) != null) { content.append(fileline + "\r\n"); } } catch (FileNotFoundException ex1) { logger.error(ex1); } catch (IOException ex2) { logger.error(ex2); } finally { if (filedata != null) { try { filedata.close(); } catch (IOException ex3) { logger.error(ex3); } } } return content.toString(); } // 文件编码格式 private static String getCharset(String fileName) throws IOException { @SuppressWarnings("resource") BufferedInputStream bin = new BufferedInputStream(new FileInputStream(fileName)); int p = (bin.read() << 8) + bin.read(); String code = null; switch (p) { case 0xefbb: code = "UTF-8"; break; case 0xfffe: code = "Unicode"; break; case 0xfeff: code = "UTF-16BE"; break; default: code = "GBK"; } return code; } /** * 打开"导入"文件窗口选择并返回文件 * * @param type * @return */ public static File openChoseWindow(int type) { JFileChooser jfc = new JFileChooser(); jfc.setFileSelectionMode(type);// 选择的文件类型(文件夹or文件) jfc.showDialog(new JLabel(), "Choose"); File file = jfc.getSelectedFile(); return file; }}
工具类代码

 

  3、Server服务端窗体

    接收客户端发送的xml字符串数据,显示在窗体文本框并以xml文件形式保存。

    所需jar包:dom4j-1.6.1.jar、log4j-1.2.13.jar

3.1 ServerFrame.java

package server;import java.awt.Dimension;import java.awt.GridLayout;import java.awt.Toolkit;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.MouseAdapter;import java.awt.event.MouseEvent;import java.io.BufferedOutputStream;import java.io.BufferedReader;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStreamReader;import java.text.SimpleDateFormat;import java.util.ArrayList;import java.util.Collections;import java.util.Comparator;import java.util.List;import javax.swing.BorderFactory;import javax.swing.DefaultListModel;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JList;import javax.swing.JPanel;import javax.swing.JScrollPane;import javax.swing.JTextArea;import org.apache.log4j.Logger;import org.dom4j.Document;import org.dom4j.DocumentException;import org.dom4j.DocumentHelper;import org.dom4j.Element;import cn.sanxing.cim.util.CimResult;public class ServerFrame extends JFrame implements ActionListener{    private static final long serialVersionUID = 1L;    private static Logger logger = Logger.getLogger(ServerFrame.class.getName());    SimpleDateFormat DATEFORMAT = new SimpleDateFormat("yyyyMMddHHmmss");//设置日期格式        JFrame mainFrame = new JFrame("Server-Interface Tool");    JPanel panel = new JPanel();    JLabel receiveLable = new JLabel("Receive the requested XML");    JButton refreshButton = new JButton("Refresh");    JLabel recordLabel = new JLabel();    //文件列表显示框    DefaultListModel
dlm = new DefaultListModel
(); private JList
jList = new JList
(dlm); JScrollPane file_jScrollPane = new JScrollPane(jList); //文件列表滚动条 // 接收并显示请求的XML JTextArea requestXML_textarea = new JTextArea(); JScrollPane jScrollPane = new JScrollPane(requestXML_textarea); //文本框添加滚动条 String rootPath = System.getProperty("user.dir")+"/saveFile/"; public void showFrame(String param, int time) { initPanel();// 初始化面板 initFrame();// 初始化窗体 //选中监听 mouseListener(); //校验是否为XML CimResult cr = ServerUtil.verifyXml2Object(param); if(!cr.isSuccess()){ requestXML_textarea.setText(cr.getMsg()); return; }else{ param = ServerUtil.formatXML(param); } //将接收参数显示到文本框 requestXML_textarea.setText(param); if(!ServerUtil.isEmptyString(param)){ writeFile(param, time); //保存 } } // 初始化面板 public void initPanel() { panel.setLayout(null); //接收XML标题 receiveLable.setBounds(170, 15, 200, 25); this.panel.add(receiveLable); //记录数 recordLabel.setBounds(840, 15, 80, 25); this.panel.add(recordLabel); //刷新按钮 refreshButton.setBounds(10, 18, 80, 20); this.panel.add(refreshButton); //参数文本显示框 jScrollPane.setBounds(170, 40, 710, 520); this.panel.add(jScrollPane); //保存文件 file_jScrollPane.setBounds(10, 40, 155, 520); this.panel.add(file_jScrollPane); // 对list添加滚动条 // vector = new Vector
();// 可实现自动增长对象数组 this.jList.setBorder(BorderFactory.createTitledBorder("File List")); //文件列表框标题 // 动作监听 refreshButton.addActionListener(this); } public void initFrame(){ mainFrame.setLayout(new GridLayout(1, 1)); // Setting the width and height of frame mainFrame.setSize(895, 600); mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//设置关闭,则终止程序 mainFrame.setResizable(false);// 固定窗体大小 Toolkit kit = Toolkit.getDefaultToolkit(); // 工具包 Dimension screenSize = kit.getScreenSize(); // 屏幕的尺寸 int screenWidth = screenSize.width / 2; // 屏幕的宽 int screenHeight = screenSize.height / 2; // 屏幕的高 int height = mainFrame.getHeight(); // 窗口高度 int width = mainFrame.getWidth(); // 窗口宽度 mainFrame.setLocation(screenWidth - width / 2, screenHeight - height / 2);// 将窗口设置到屏幕的中部// Image myimage = kit.getImage("resourse/hxlogo.gif"); // 由tool获取图像// mainframe.setIconImage(myimage); mainFrame.add(panel); mainFrame.setVisible(true); } //保存并写入xml文件 public void writeFile(String content,int number) { String name = "Interface"; Document doc = null; try { doc = DocumentHelper.parseText(content); } catch (DocumentException e1) { logger.error(e1); return; } Element Noun = doc.getRootElement().element("Header").element("Noun"); String nounText = Noun.getTextTrim(); if(!ServerUtil.isEmptyString(nounText) && ("MeterReadings".equals(nounText) || "EndDeviceEvents".equals(nounText))){ name = nounText; } byte[] contents = content.getBytes(); String fileName = name + "_" + number /*+DATEFORMAT.format(new Date())*/ +".xml"; String filePath = rootPath + fileName; File file = new File(filePath); File folder = new File(rootPath); if(!folder.exists()){ folder.mkdir(); } BufferedOutputStream outfile = null; try { while(true){ if (!file.exists()) { file.createNewFile(); break; } fileName = name + "_" + (++number) /*+DATEFORMAT.format(new Date())*/+".xml"; filePath = rootPath + fileName; file = new File(filePath); } outfile = new BufferedOutputStream(new FileOutputStream(filePath)); outfile.write(contents); outfile.flush();// System.out.println("保存成功!"); } catch (IOException ex1) { logger.error(ex1); } finally { if (outfile != null) { try { outfile.close(); } catch (IOException e) { logger.error(e); } } } } /** * 读取文件 * @param fileName * @param encode * @return */ public StringBuffer readFile(String fileName,String encode) { StringBuffer content = new StringBuffer(); String fileline; BufferedReader filedata = null; try { filedata=new BufferedReader(new InputStreamReader(new FileInputStream(fileName),encode)); while ((fileline = filedata.readLine()) != null) { content.append(fileline + "\r\n"); } } catch (FileNotFoundException ex1) { logger.error(ex1); } catch (IOException ex2) { logger.error(ex2); } finally { if (filedata != null) { try { filedata.close(); } catch (IOException ex3) { logger.error(ex3); } } } return content; } /** * 判断文件是否存在 * @param path * @return */ public boolean isFile(String path) { boolean flag = true; File dir = new File(path); if (!dir.exists()) { requestXML_textarea.setText("File does not exist"); flag = false; } return flag; } //事件监听 @Override public void actionPerformed(ActionEvent e) { if(e.getSource() == refreshButton){ //刷新文件列表 refreshFileList(); } } //获取文件列表 public void refreshFileList() { File file = new File(rootPath); List
fileList = new ArrayList
(); if(!file.exists()){ jList = null; requestXML_textarea.setText("Folders do not exist!"); }else{ this.dlm.clear(); File[] files = file.listFiles(); if(files.length == 0){ jList = null; requestXML_textarea.setText("The folder is empty!"); }else{ for(File file_xml : files){ String fileName = file_xml.getName(); String str_xml = fileName.substring(fileName.lastIndexOf(".") + 1); if(str_xml.equals("xml")){ fileList.add(file_xml); } } //文件名排序 Collections.sort(fileList, new Comparator
() { @Override public int compare(File o1, File o2) { int num1 = Integer.parseInt(o1.getName().substring(o1.getName().indexOf("_")+1, o1.getName().indexOf("."))); int num2 = Integer.parseInt(o2.getName().substring(o2.getName().indexOf("_")+1, o2.getName().indexOf("."))); if(num1 > num2){ return 1; } return -1; } });// Collections.sort(fileList, new Comparator
() { // @Override // public int compare(File o1, File o2) { // if (o1.isDirectory() && o2.isFile()) // return -1; // if (o1.isFile() && o2.isDirectory()) // return 1; // return o1.getName().compareTo(o2.getName()); // } // }); //加入到model for(File fileName : fileList){ dlm.addElement(fileName.getName()); } } } } //文件列表选中事件监听 public void mouseListener() { jList.addMouseListener(new MouseAdapter() { @SuppressWarnings("unchecked") public void mouseClicked(MouseEvent e) { if (jList.getSelectedIndex() != -1) { // 选中 if (e.getClickCount() == 1) { // 单击(若判断双击改为等于2)// System.out.println(jList.getSelectedValue().toString()); String selectedFileName = jList.getSelectedValue().toString().trim();//获取选中的文件名 String path = rootPath+selectedFileName; if(isFile(path)){ String Content = readFile(path,"UTF-8").toString();//根据文件名读取文件内容 requestXML_textarea.setText(Content);//将所读取的文件内容显示在文本框 //获取XML中表号个数赋值到recordLabel Document doc = null; try { doc = DocumentHelper.parseText(Content); } catch (DocumentException e1) { logger.error(e1); } if(doc != null){ Element Payload = doc.getRootElement().element("Payload"); String name = selectedFileName.substring(0, selectedFileName.lastIndexOf("_")); Element element = null; if(name.equals("MeterReadings") && Payload != null){ element = Payload.element("MeterReadings"); } if(name.equals("EndDeviceEvents") && Payload != null){ element = Payload.element("EndDeviceEvents"); } if(element != null){ List
list = element.elements(); recordLabel.setText(String.valueOf(list.size()));// System.out.println(list.size()); }else{ recordLabel.setText(""); } } } } } } }); } public static void main(String[] args) { ServerFrame serverFrame = new ServerFrame(); serverFrame.showFrame("Test Message!",1); } }
服务端窗体代码

3.2 ServerUtil.java

package server;import java.io.IOException;import java.io.StringReader;import java.io.StringWriter;import org.dom4j.Document;import org.dom4j.DocumentException;import org.dom4j.DocumentHelper;import org.dom4j.io.OutputFormat;import org.dom4j.io.SAXReader;import org.dom4j.io.XMLWriter;import cn.sanxing.cim.cis.CimCustomerModule;import cn.sanxing.cim.cis.CimDataLinkageModule;import cn.sanxing.cim.cis.CimEndDeviceModule;import cn.sanxing.cim.cis.CimGridModule;import cn.sanxing.cim.cis.CimHeader;import cn.sanxing.cim.cis.CimMeterModule;import cn.sanxing.cim.cis.CimModule;import cn.sanxing.cim.cis.CimReplyModule;import cn.sanxing.cim.cis.CimServiceRequest;import cn.sanxing.cim.type.VerbType;import cn.sanxing.cim.util.CimBaseCodeUtil;import cn.sanxing.cim.util.CimResult;import cn.sanxing.cim.util.CimUtil;import cn.sanxing.cim.util.CimXmlUtil;public class ServerUtil {    public static CimResult xml2Object(String xml) {        CimResult re = new CimResult(false);        re = verifyXml2Object(xml);        if (!re.isSuccess()) {            return re;        }        Document doc = CimXmlUtil.strToDom(xml);        re.setDataObject(CimXmlUtil.parseXml2Obj(doc));        re.setSuccess(true);        return re;    }        public static CimResult verifyXml2Object(String xml) {        CimResult re = new CimResult(true);        if (xml == null) {            re.setMsg(CimBaseCodeUtil.getReplyDetail("00004"));            re.setSuccess(false);            return re;        }        try {            DocumentHelper.parseText(xml);    //验证是否为标准xml格式的字符串xml        } catch (DocumentException e) {            re.setMsg(CimBaseCodeUtil.getReplyDetail("00005"));            re.setSuccess(false);            return re;        }        return re;    }        public static String doPost(CimResult cr) {        String ss = "";//        CimResult cr = CimUtil.xml2Object(xml);        if (cr.isSuccess()) {            CimHeader header = new CimHeader();            Object o = cr.getDataObject();            CimModule cm = new CimModule();            if (o instanceof CimGridModule) {                CimGridModule cgm = (CimGridModule) o;                cm = cgm;                header.setNoun(cgm.getNounType());            } else if (o instanceof CimMeterModule) {                CimMeterModule cmm = (CimMeterModule) o;                cm = cmm;                header.setNoun(cmm.getNounType());            } else if (o instanceof CimEndDeviceModule) {                CimEndDeviceModule cem = (CimEndDeviceModule) o;                cm = cem;                header.setNoun(cem.getNounType());            } else if (o instanceof CimCustomerModule) {                CimCustomerModule ccm = (CimCustomerModule) o;                cm = ccm;                header.setNoun(ccm.getNounType());            } else if (o instanceof CimDataLinkageModule) {                CimDataLinkageModule cdm = (CimDataLinkageModule) o;                cm = cdm;                header.setNoun(cdm.getNounType());            } else if (o instanceof CimServiceRequest) {                CimServiceRequest csr = (CimServiceRequest) o;                cm = csr;                header.setNoun(csr.getNounType());            }            CimReplyModule crm = new CimReplyModule();            crm.setAck(false);            crm.setCode("00000");            crm.setDetail("No Error");            header.setVerb(VerbType.reply);            header.setSource("MDC");            header.setRevision("2.0");            header.setCorrelationID(cm.getCorrelationID());            CimResult t = CimUtil.Object2xml(crm, header);            if (t.isSuccess()) {                ss = t.getXml();//                ss = CimXmlUtil.formatXML(ss);                return ss;            }        }        return ss;    }        public static String getString(Object s){        return s == null?"":String.valueOf(s).trim();    }        //判空    public static final boolean isEmptyString(String s) {        return s == null || s.trim().equals("") || s.equals("null") || s.equals("NULL") || s.trim().equals("undefined");    }        public static String formatXML(String inputXML) {        SAXReader reader = new SAXReader();        String requestXML = null;        Document document;        try {            document = reader.read(new StringReader(inputXML));            XMLWriter writer = null;            if (document != null) {                try {                    StringWriter stringWriter = new StringWriter();                    OutputFormat format = new OutputFormat("      ", true);                    writer = new XMLWriter(stringWriter, format);                    try {                        writer.write(document);                        writer.flush();                    } catch (Exception e) {                        e.printStackTrace();                    }                    requestXML = stringWriter.getBuffer().toString();                } finally {                    if (writer != null) {                        try {                            writer.close();                        } catch (IOException e) {                        }                    }                }            }        } catch (DocumentException e1) {            e1.printStackTrace();        }        return requestXML;    }    }
工具类代码

 

  4、生成xml窗体

    此工具参考价值不大,可学习swing日期控件如何使用,如何获取jar包资源(比如图片路径问题)。

    swing日期控件所需jar包:datepicker.jar

4.1 BuildXMLFrame.java

package generateXML;import java.awt.Dimension;import java.awt.Font;import java.awt.Toolkit;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.MouseAdapter;import java.awt.event.MouseEvent;import java.text.ParseException;import java.util.Arrays;import java.util.Date;import java.util.HashMap;import java.util.List;import java.util.Locale;import java.util.Map;import javax.swing.ImageIcon;import javax.swing.JButton;import javax.swing.JComboBox;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JOptionPane;import javax.swing.JPanel;import javax.swing.JScrollPane;import javax.swing.JTextArea;import javax.swing.JTextField;import org.apache.log4j.Logger;import com.eltima.components.ui.DatePicker;import cn.sanxing.cim.payload.MeterConfig;public class BuildXMLFrame extends JFrame implements ActionListener{    private static final long serialVersionUID = 1L;    private static Logger logger = Logger.getLogger(BuildXMLFrame.class.getName());        JFrame mainFrame = new JFrame("Build XML Tool");     JPanel panel;    //类型    JLabel typeLabel;    JComboBox
typeComBox; String[] typeString = { "MeterReadings", "EndDeviceEvents", "EndDeviceControls" }; //场景 JLabel scenariosLabel; JComboBox
scenariosComBox; String[] scenariosString = { "Billing Data", "Meter Reading", "Instantaneous Data", "LoadProfile1", "LoadProfile2" }; String[] meterNos = {"Billing Data", "LoadProfile1", "LoadProfile2", "Events"};//只需校验多表的scenarios String[] meterNo = {"Meter Reading", "Instantaneous Data", "Connect/Disconnect"};//只需校验单表+抄读项的scenarios List
scenariosList = Arrays.asList(meterNos); List
scenariosList1 = Arrays.asList(meterNo); //表号 JLabel meterNoLable; JTextField meterNoTextField; JButton addMeterNoButton; ImageIcon addMeterNoIcon = new ImageIcon(BuildXMLFrame.class.getClassLoader().getResource("image/add.jpg")); //抄读项 JLabel readingTypeLabel; JTextField readingTypeTextField; JButton addReadTypeButton; ImageIcon addReadTypeIcon = new ImageIcon(BuildXMLFrame.class.getClassLoader().getResource("image/add.jpg")); //时间 JLabel startTimeLabel; JLabel endTimeLabel; DatePicker startTimeDatePick;//时间控件 DatePicker endTimeDatePick; //生成XML按钮 JButton generateButton; //显示XML JTextArea xmlTextArea; JScrollPane xmlScroll; MyUtil util = new MyUtil(); MeterConfig meterConfig = new MeterConfig(); public void showFrame(){ initPanel(); //初始化Panel initFrame(); //初始化Frame } //初始化窗体 public void initFrame(){ mainFrame.setSize(770, 700); //窗体大小 mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //设置窗体点击关闭按钮,即终止程序 mainFrame.setResizable(false); //取消窗体的固定大小设置 Toolkit kit = Toolkit.getDefaultToolkit(); // 工具包 Dimension screenSize = kit.getScreenSize(); // 屏幕的尺寸 int screenWidth = screenSize.width / 2; // 屏幕的宽 int screenHeight = screenSize.height / 2; // 屏幕的高 int height = mainFrame.getHeight(); // 窗口高度 int width = mainFrame.getWidth(); // 窗口宽度 mainFrame.setLocation(screenWidth - width / 2, screenHeight - height / 2); // 将窗口设置到屏幕的中部 mainFrame.add(panel); //panel加入到窗体中 mainFrame.setVisible(true); //窗体设置可见 } //初始化面板 public void initPanel(){ panel = new JPanel(); panel.setLayout(null); //类型Label typeLabel = new JLabel("Type :"); typeLabel.setBounds(50, 20, 100, 25); this.panel.add(typeLabel); //类型下拉框 typeComBox = new JComboBox
(typeString); typeComBox.setBounds(90, 20, 150, 25); this.panel.add(typeComBox); //场景Label scenariosLabel = new JLabel("Scenarios :"); scenariosLabel.setBounds(270, 20, 100, 25); this.panel.add(scenariosLabel); //场景下拉框 scenariosComBox = new JComboBox
(scenariosString); scenariosComBox.setBounds(340, 20, 150, 25); this.panel.add(scenariosComBox); //表号Label meterNoLable = new JLabel("Meter No :"); meterNoLable.setBounds(530, 20, 100, 25); this.panel.add(meterNoLable); //表号文本框 meterNoTextField = new JTextField(); meterNoTextField.setBounds(595, 20, 150, 25); this.panel.add(meterNoTextField); //添加表号按钮 addMeterNoButton = new JButton(addMeterNoIcon); addMeterNoButton.setBounds(125, 0, 24, 24); meterNoTextField.add(addMeterNoButton); //开始时间Label startTimeLabel = new JLabel("Start Time : "); startTimeLabel.setBounds(20, 55, 100, 25); this.panel.add(startTimeLabel); //开始时间控件 startTimeDatePick = getDatePicker("startTime"); this.panel.add(startTimeDatePick); //结束时间Label endTimeLabel = new JLabel("End Time : "); endTimeLabel.setBounds(275, 55, 100, 25); this.panel.add(endTimeLabel); //结束时间控件 endTimeDatePick = getDatePicker("endTime"); this.panel.add(endTimeDatePick); //抄读项Label readingTypeLabel = new JLabel("ReadingType :"); readingTypeLabel.setBounds(510, 55, 100, 25); this.panel.add(readingTypeLabel); //抄读项文本框 readingTypeTextField = new JTextField(); readingTypeTextField.setBounds(595, 55, 150, 25); this.panel.add(readingTypeTextField); //添加抄读项按钮 addReadTypeButton = new JButton(addReadTypeIcon); addReadTypeButton.setBounds(125, 0, 24, 24); readingTypeTextField.add(addReadTypeButton); //生成XML按钮 generateButton = new JButton("Generate"); generateButton.setBounds(645, 95, 100, 25); this.panel.add(generateButton); //xml文本框 xmlTextArea = new JTextArea(); xmlScroll = new JScrollPane(xmlTextArea); //xmlTextArea添加滚动条 xmlScroll.setBounds(15, 130, 735, 530); this.panel.add(xmlScroll); //按钮加入监听 generateButton.addActionListener(this); typeComBox.addActionListener(this); addMeterNoButton.addActionListener(this); addMeterNoButton.addMouseListener(new MouseAdapter() { @Override public void mouseEntered(MouseEvent e) { addMeterNoButton.setToolTipText("Add meterNo."); // 添加表号按钮的提示 } }); addReadTypeButton.addActionListener(this); addReadTypeButton.addMouseListener(new MouseAdapter() { @Override public void mouseEntered(MouseEvent e) { addReadTypeButton.setToolTipText("Add readingType"); // 添加抄读项按钮的提示 } }); } //时间控件 public DatePicker getDatePicker(String flag) { DatePicker datepick; String DefaultFormat = "yyyy-MM-dd HH:mm:ss"; // 格式 Date date = new Date(); // 当前时间 Font font = new Font("Times New Roman", Font.BOLD, 14); // 字体 Dimension dimension = new Dimension(150, 24); //控件宽、高// int[] hilightDays = { 1, 3, 5, 7 };// int[] disabledDays = { 4, 6, 5, 9 }; // 构造方法(初始时间,时间显示格式,字体,控件大小) datepick = new DatePicker(date, DefaultFormat, font, dimension); if("startTime".equals(flag)){ datepick.setLocation(90, 55); } if("endTime".equals(flag)){ datepick.setLocation(340, 55); }// datepick.setBounds(137, 15, 177, 24); // setBounds()直接设置大小与位置// datepick.setHightlightdays(hilightDays, Color.red); // 设置一个月份中需要高亮显示的日子// datepick.setDisableddays(disabledDays); // 设置一个月份中不需要的日子,呈灰色显示 datepick.setLocale(Locale.US); // 设置国家 datepick.setTimePanleVisible(true); // 设置时、分、秒面板可见 return datepick; } //click触发按钮事件 @Override public void actionPerformed(ActionEvent e) { // type级联scenarios if (e.getSource() == typeComBox) { cascade(); } // 添加表号 if (e.getSource() == addMeterNoButton) { addMeterNo(); } // 添加抄读项 if (e.getSource() == addReadTypeButton) { addReadType(); } // 生成XML if (e.getSource() == generateButton) { if (verifyData()) { // 数据校验 showXML(); // 生成XML } } } //级联 public void cascade() { String typeSelected = util.getString(typeComBox.getSelectedItem()); if ("MeterReadings".equals(typeSelected)) { scenariosComBox.removeAllItems(); for (String scenarios : scenariosString) { scenariosComBox.addItem(scenarios); } } if ("EndDeviceEvents".equals(typeSelected)) { scenariosComBox.removeAllItems(); scenariosComBox.addItem("Events"); } if ("EndDeviceControls".equals(typeSelected)) { scenariosComBox.removeAllItems(); scenariosComBox.addItem("Connect/Disconnect"); } } //添加表号 public void addMeterNo() { String showInput = JOptionPane.showInputDialog(this.panel, "Add meter No.", "Tips", 3); if (!util.isEmptyString(showInput)) { if (!showInput.matches("[0-9]+")) { JOptionPane.showMessageDialog(this.panel, "The input must be a number.", "Tips", 2);// 表号错误 return; } if (util.isEmptyString(meterNoTextField.getText())) { meterNoTextField.setText(showInput); } else { meterNoTextField.setText(meterNoTextField.getText() + "," + showInput); } } } //添加抄读项 public void addReadType() { String showInput = JOptionPane.showInputDialog(this.panel, "Add readingType", "Tips", 3); if (!util.isEmptyString(showInput)) { //抄读项校验 if (!showInput.matches("[0-9A-Z]+")) { JOptionPane.showMessageDialog(this.panel, "The input must be a number or letter.", "Tips", 2);// 抄读项错误 return; } //赋值 if (util.isEmptyString(readingTypeTextField.getText())) { readingTypeTextField.setText(showInput); } else { readingTypeTextField.setText(readingTypeTextField.getText() + "," + showInput); } } } //数据校验 public boolean verifyData(){ String typeSelected = util.getString(typeComBox.getSelectedItem()); String scenariosSelected = util.getString(scenariosComBox.getSelectedItem()); String meterNoText = util.getString(meterNoTextField.getText()); String readTypeText = util.getString(readingTypeTextField.getText()); Map
map = new HashMap
(); map.put("type", typeSelected); map.put("scenarios", scenariosSelected); map.put("meterNo", meterNoText); map.put("readType", readTypeText); //MeterNo校验 if(meterNoisEmpty(meterNoText)){ return false; } //type switch (typeSelected) { case "MeterReadings": return MeterReadings(map); case "EndDeviceEvents": return EndDeviceEvents(map); case "EndDeviceControls": return EndDeviceControls(map); default: return true; } } public boolean MeterReadings(Map
map){ String scenarios = map.get("scenarios"); if (scenariosList.contains(scenarios)) { // 多表表号,需以逗号隔开 return meterNosFormat(map.get("meterNo")); } if (scenariosList1.contains(scenarios)) { // 单表表号校验 if(!meterNoFormat(map.get("meterNo"))){ return false; } // readType校验 return readTypeisEmpty(map.get("readType")); } return true; } public boolean EndDeviceEvents(Map
map) { String scenarios = map.get("scenarios"); if (scenariosList.contains(scenarios)) { // 多表表号,需以逗号隔开 return meterNosFormat(map.get("meterNo")); } return true; } public boolean EndDeviceControls(Map
map) { String scenarios = map.get("scenarios"); if (scenariosList1.contains(scenarios)) { // 单表表号校验 if (!meterNoFormat(map.get("meterNo"))) { return false; } // readType校验 return readTypeisEmpty(map.get("readType")); } return true; } //表号为空 public boolean meterNoisEmpty(String meterNo){ if(util.isEmptyString(meterNo)){ JOptionPane.showMessageDialog(this.panel, "MeterNo is empty!", "Tips", 2);// MeterNo为空,warning return true; } return false; } //单表表号格式校验 public boolean meterNoFormat(String meterNo){ if (!meterNo.matches("^\\d+$")) { JOptionPane.showMessageDialog(this.panel, "The format of the meterNo number must be a number!", "Tips", 2);// 表号必须数字格式,warning return false; } return true; } //多表表号格式校验 public boolean meterNosFormat(String meterNo){ if (!meterNo.matches("^\\d+($|,\\d+$)")) { JOptionPane.showMessageDialog(this.panel, "Multiple meterNos must be comma separated!", "Tips", 2);// 多表表号必须是数字格式且逗号分隔,warning return false; } return true; } //readType为空 public boolean readTypeisEmpty(String readType){ if (util.isEmptyString(readType)) { JOptionPane.showMessageDialog(this.panel, "ReadingType is empty!", "Tips", 2);// ReadingType为空,warning return false; } return true; } //生成XML public void showXML(){ Map
map = new HashMap
(); String type = util.getString(typeComBox.getSelectedItem()); String scenarios = util.getString(scenariosComBox.getSelectedItem()); String startTime = null; String endTime = null; String meterNo = util.getString(meterNoTextField.getText()); String readingType = util.getString(readingTypeTextField.getText()); try { startTime = util.sdfCim.format(util.sdfJava.parse(startTimeDatePick.getText().trim())); endTime = util.sdfCim.format(util.sdfJava.parse(endTimeDatePick.getText().trim())); } catch (ParseException e) { logger.error(e); } map.put("type", type); map.put("scenarios", scenarios); map.put("meterNo", meterNo); map.put("startTime", startTime); map.put("endTime", endTime); map.put("readType", readingType); String xml = util.createRequest(map); xmlTextArea.setText(xml); } public static void main(String[] args) { Locale.setDefault(Locale.ENGLISH);//设置控件为英文 BuildXMLFrame xmlFrame = new BuildXMLFrame(); xmlFrame.showFrame(); } }
生成xml的窗体代码

4.2 MyUtil.java

package generateXML;import java.io.IOException;import java.io.StringReader;import java.io.StringWriter;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;import java.text.SimpleDateFormat;import java.util.Date;import java.util.Map;import java.util.UUID;import org.dom4j.Document;import org.dom4j.DocumentException;import org.dom4j.DocumentHelper;import org.dom4j.Element;import org.dom4j.io.OutputFormat;import org.dom4j.io.SAXReader;import org.dom4j.io.XMLWriter;import cn.sanxing.cim.cis.CimHeader;import cn.sanxing.cim.util.CimResult;public class MyUtil {    public  String CIMDATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss'.0Z'";    public  String JAVADATE_FORMAT = "yyyy-MM-dd HH:mm:ss";    public  SimpleDateFormat sdfCim = new SimpleDateFormat(CIMDATE_FORMAT);    public  SimpleDateFormat sdfJava = new SimpleDateFormat(JAVADATE_FORMAT);    public static String XML_PRIFIX = "m:";        public String createRequest(Map
map) { Document doc = DocumentHelper.createDocument(); Element request = addRequestRoot(doc); Element headerElement = request.addElement("Header"); Element payLoadElement = request.addElement("Payload"); createHeader(headerElement, map); createPayLoad(payLoadElement, map); String xml = formatXML(doc.asXML()); return xml; } public Element addRequestRoot(Document doc) { Element request = doc.addElement("RequestMessage"); request.addNamespace("m", "http://iec.ch/TC57/2011/schema/message"); request.addNamespace("ns", "http://iec.ch/TC57/2011/schema/message"); request.addNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance"); request.addAttribute("xsi:schemaLocation", "http://iec.ch/TC57/2011/schema/message Message.xsd"); return request; } public void createHeader(Element headerElement, Map
map){ String randomID = UUID.randomUUID().toString().toUpperCase(); String type = map.get("type"); String scenarios = map.get("scenarios"); Element verbElement = headerElement.addElement("Verb"); Element nounElement = headerElement.addElement("Noun"); Element revisionElement = headerElement.addElement("Revision"); Element timestampElement = headerElement.addElement("Timestamp"); Element sourceElement = headerElement.addElement("Source"); Element ackRequiredElement = headerElement.addElement("AckRequired"); Element asyncReplyFlagElement = headerElement.addElement("AsyncReplyFlag"); Element messageIDElement = headerElement.addElement("MessageID"); Element correlationIDElement = headerElement.addElement("CorrelationID"); if("Billing Data".equals(scenarios)){ Element comment = headerElement.addElement("Comment"); comment.setText("This is test billing"); } //赋值 if("EndDeviceControls".equals(type)){ verbElement.setText("create"); }else{ verbElement.setText("get"); } nounElement.setText(type); revisionElement.setText("2.0"); timestampElement.setText(sdfCim.format(new Date())); sourceElement.setText("MDM"); ackRequiredElement.setText("false"); asyncReplyFlagElement.setText("false"); messageIDElement.setText(randomID); correlationIDElement.setText(randomID); } public void createPayLoad(Element payLoadElement, Map
map) { String type = map.get("type"); if(type.equals("MeterReadings")){ MeterReadings(payLoadElement, map); } if(type.equals("EndDeviceEvents")){ EndDeviceEvents(payLoadElement, map); } if(type.equals("EndDeviceControls")){ EndDeviceControls(payLoadElement, map); } } //PayLoad-MeterReadings public void MeterReadings(Element payLoadElement, Map
map){ String scenarios = map.get("scenarios"); if ("Billing Data".equals(scenarios) || "LoadProfile1".equals(scenarios) || "LoadProfile2".equals(scenarios)){ Element MeterReadings = payLoadElement.addElement("m:MeterReadings"); Element readingType = MeterReadings.addElement("m:ReadingType"); Element names = readingType.addElement("m:Names"); Element name = names.addElement("m:name"); Element nameType = names.addElement("m:NameType"); Element name1 = nameType.addElement("m:name"); if(scenarios.equals("LoadProfile1") || scenarios.equals("LoadProfile2")){ name.setText(scenarios); name1.setText("LoadProfileType"); } if(scenarios.equals("Billing Data")){ name.setText("MonthlyBilling"); name1.setText("BillingType"); } String meterNos = map.get("meterNo"); //多表,循环生成 if(meterNos.indexOf(",") != -1){ String[] meterNo = meterNos.split(","); for(String meter : meterNo){ map.put("meterNo", meter); createMeterNoElements(MeterReadings, map); } }else{ createMeterNoElements(MeterReadings, map); } } if("Meter Reading".equals(scenarios) || "Instantaneous Data".equals(scenarios)){ Element meterReadings = payLoadElement.addElement("m:MeterReadings"); Element meterReading = meterReadings.addElement("m:MeterReading"); Element meter = meterReading.addElement("m:Meter"); Element mRID = meter.addElement("m:mRID"); mRID.setText(map.get("meterNo")); //多个readingType抄读项 String readType = map.get("readType"); if(readType.indexOf(",") != -1){ String[] readTypes = readType.split(","); for(String read : readTypes){ map.put("readType", read); createReadTypeElements(meterReading, map); } }else{ createReadTypeElements(meterReading, map); } } } //PayLoad-EndDeviceEvents public void EndDeviceEvents(Element payLoadElement, Map
map) { Element endDeviceEvents = payLoadElement.addElement("m:EndDeviceEvents"); String meterNos = map.get("meterNo"); // 多表 if (meterNos.indexOf(",") != -1) { String[] meterNo = meterNos.split(","); for (String No : meterNo) { map.put("meterNo", No); createElements(endDeviceEvents, map); } } else { createElements(endDeviceEvents, map); } Element timeSchedule = endDeviceEvents.addElement("m:TimeSchedule"); Element scheduleInterval = timeSchedule.addElement("m:scheduleInterval"); Element end = scheduleInterval.addElement("m:end"); Element start = scheduleInterval.addElement("m:start"); end.setText(map.get("endTime")); start.setText(map.get("startTime")); } //PayLoad-EndDeviceEvents public void EndDeviceControls(Element payLoadElement, Map
map) { Element endDeviceControls = payLoadElement.addElement("m:EndDeviceControls"); Element endDeviceControl = endDeviceControls.addElement("m:EndDeviceControl"); Element endDevices = endDeviceControl.addElement("m:EndDevices"); Element mRID = endDevices.addElement("m:mRID"); Element endDeviceControlType = endDeviceControl.addElement("m:EndDeviceControlType"); mRID.setText(map.get("meterNo")); endDeviceControlType.addAttribute("ref", map.get("readType")); } //多表 public void createMeterNoElements(Element meterReadings, Map
map){ Element meterReading = meterReadings.addElement("m:MeterReading"); Element meter = meterReading.addElement("m:Meter"); Element mRID = meter.addElement("m:mRID"); Element readings = meterReading.addElement("m:Readings"); Element timePeriod = readings.addElement("m:timePeriod"); Element end = timePeriod.addElement("m:end"); Element start = timePeriod.addElement("m:start"); mRID.setText(map.get("meterNo")); end.setText(map.get("endTime")); start.setText(map.get("startTime")); } //多表 public void createElements(Element endDeviceEvents, Map
map) { Element meter = endDeviceEvents.addElement("m:Meter"); Element mRID = meter.addElement("m:mRID"); mRID.setText(map.get("meterNo")); } //多个readingType public void createReadTypeElements(Element meterReading, Map
map) { Element readings = meterReading.addElement("m:Readings"); Element reason = readings.addElement("m:reason"); Element readingType = readings.addElement("m:ReadingType"); if("Instantaneous Data".equals(map.get("scenarios"))){ reason.setText("reading"); } if("Meter Reading".equals(map.get("scenarios"))){ reason.setText("MeterReading"); } readingType.addAttribute("ref", map.get("readType")); } public CimResult Object2xml(Object obj, CimHeader header) { CimResult re = new CimResult(false); if (!re.isSuccess()) { return re; } try { Class
c = Class.forName(obj.getClass().getName()); Method setRunArgsMethod = c.getMethod("handler", new Class[] { CimHeader.class }); re = (CimResult) setRunArgsMethod.invoke(obj, new Object[] { header }); } catch (SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchMethodException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } return re; } //字符串XML格式化 public String formatXML(String inputXML) { SAXReader reader = new SAXReader(); String requestXML = null; Document document; try { document = reader.read(new StringReader(inputXML)); XMLWriter writer = null; if (document != null) { try { StringWriter stringWriter = new StringWriter(); OutputFormat format = new OutputFormat(" ", true); writer = new XMLWriter(stringWriter, format); try { writer.write(document); writer.flush(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } requestXML = stringWriter.getBuffer().toString(); } finally { if (writer != null) { try { writer.close(); } catch (IOException e) { } } } } } catch (DocumentException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } return requestXML; } //判空 public final boolean isEmptyString(String s) { return s == null || s.trim().equals("") || s.equals("null") || s.equals("NULL") || s.trim().equals("undefined"); } public String getString(Object s){ return s == null?"":String.valueOf(s).trim(); } }
工具类代码

 

转载于:https://www.cnblogs.com/coder-wzr/p/7839421.html

你可能感兴趣的文章
openwrt使用list
查看>>
函数对象
查看>>
Problem B: 占点游戏
查看>>
css3基础篇二
查看>>
进程间的八种通信方式----共享内存是最快的 IPC 方式
查看>>
DPDK初始化流程
查看>>
MEF: MSDN 杂志上的文章(14) 稳定的组合
查看>>
python常用模块之sys, os, random
查看>>
HDU 2548 A strange lift
查看>>
Linux服务器在外地,如何用eclipse连接hdfs
查看>>
react双组件传值和传参
查看>>
BNU29140——Taiko taiko——————【概率题、规律题】
查看>>
POJ 2289——Jamie's Contact Groups——————【多重匹配、二分枚举匹配次数】
查看>>
java 得到以后的日期
查看>>
[Kaggle] Sentiment Analysis on Movie Reviews
查看>>
python安装easy_intall和pip
查看>>
AC日记——舒适的路线 codevs 1001 (并查集+乱搞)
查看>>
宏脚本链接数据库
查看>>
HDU1004
查看>>
MySQL高速缓存
查看>>