卫监接口项目一些零碎

把字符串写入XML文件

/**
     * 创建文件夹
     * @param filePath
     * @return
     */
    public boolean makeDirs() {
        String folderName = IReportServer.getTempDir()
                + File.separator + "hubei";
        if (StrFunc.isNull(folderName)) {
            return false;
        }
        File folder = new File(folderName);
        return (folder.exists() && folder.isDirectory()) ? true : folder.mkdirs();
    }
/**
     * 向工作目录写XML文件保存数据
     * @return
     * @throws Exception 
     */
    public void writeXml2WorkRoot(String xmlStr) throws Exception {
        Document document = DocumentHelper.parseText(xmlStr);
        //写入.xml文件  
        writerDocumentToNewFile(document);
    }

    //document写入新的文件  
    private void writerDocumentToNewFile(Document document) throws Exception {
        //输出格式  
        OutputFormat format = OutputFormat.createPrettyPrint();
        //设置编码  
        format.setEncoding("UTF-8");
        //XMLWriter 指定输出文件以及格式  
        if (makeDirs()) {
            XMLWriter writer = new XMLWriter(new OutputStreamWriter(new FileOutputStream(new File(IReportServer.getTempDir()
                    + File.separator + "hubei" + File.separator + System.currentTimeMillis() + ".xml")), "UTF-8"), format);
            try {
                System.out.println("写入XML成功");
                //写入新文件  
                writer.write(document);
                writer.flush();
            } finally {
                writer.close();
            }
        } else {
            System.out.println("写入XML失败");
        }
    }

根据不同的数据解析XML文件,一种直接解析XML文件,另外一种解析XML格式的字符串

/**
     * 解析XML
     * @param url
     * @return 
     * @throws Exception
     */
    public List readXml(String url) throws Exception {
        List messages = new ArrayList();
        SAXReader reader = new SAXReader();
        File file = new File(url);
        Document document = reader.read(file);
        Element root = document.getRootElement();
        List childElements = root.elements();
        ArrayList list = new ArrayList();
        initList(list);
        Connection conn = IReportServer.getInstance().getConnection();
        try {
            //clearTable(conn);
            /**
             * 解析XML文件,存入Data中
             */
            Iterator iterator = childElements.iterator();
            do {
                Element child = (Element) iterator.next();
                HashMap map = new HashMap();
                String id = child.elementText("ID");
                for (int i = 0; i < keys.length; i++) {
                    map.put(keys[i], child.elementText(keys[i]));
                }
                Data data = new Data(id, map);
                Message message = data.check();
                if (message == null) {
                    messages.add(insertData(messages, data, conn, list));
                } else {
                    messages.add(message);
                }
            } while (iterator.hasNext());

        } finally {
            conn.close();
        }
        return messages;
    }

    /**
     * 根据字符串解析
     * @param xml
     * @return
     * @throws Exception
     */
    public List readXmlByString(String xml) throws Exception {
        List messages = new ArrayList();
        Document document = DocumentHelper.parseText(xml);
        Element root = document.getRootElement();
        List childElements = root.elements();
        ArrayList list = new ArrayList();
        initList(list);
        Connection conn = IReportServer.getInstance().getConnection();
        try {
            //clearTable(conn);
            /**
             * 解析XML文件,存入Data中
             */
            Iterator iterator = childElements.iterator();
            do {
                Element child = (Element) iterator.next();
                HashMap map = new HashMap();
                String id = child.elementText("ID");
                for (int i = 0; i < keys.length; i++) {
                    map.put(keys[i], child.elementText(keys[i]));
                }
                Data data = new Data(id, map);
                Message message = data.check();
                if (message == null) {
                    messages.add(insertData(messages, data, conn, list));
                } else {
                    messages.add(message);
                }
            } while (iterator.hasNext());
        } finally {
            conn.close();
        }
        return messages;
    }

插入数据

/**
     * 插入数据
     * @param data
     * @param conn
     * @param list
     * @return
     * @throws Exception
     */
    public Message insertData(List Messages, Data data, Connection conn, List list) throws Exception {
        //返回错误消息
        Message message = new Message();
        dataMap = data.getDataMap();
        message.setId(data.getID());
        //已知属性名情况下
        if (!list.contains(data.getID())) {
            list.add(data.getID());
            excuteDone(insertSql, 2, conn, data, dataMap);
            //设置成功
            message.setIsSuccess(0);
            message.setReason("插入成功");
        } else {
            //设置失败
            message.setIsSuccess(1);
            message.setReason("已存在");

            //更新数据
            //System.out.println(deleteSql);
            PreparedStatement pstat = conn.prepareStatement(deleteSql);
            try {
                pstat.setString(1, data.getID());
                pstat.executeQuery();
            } finally {
                pstat.close();
            }
            excuteDone(insertSql, 2, conn, data, dataMap);
            message.setIsSuccess(0);
            message.setReason("已存在但更新成功");
        }
        return message;
    }

    /**
     * 执行sql语句拼接加上操作
     * @param sql
     * @param index
     * @param conn
     * @param data
     * @throws SQLException
     * @throws ParseException
     */
    public void excuteDone(String sql, int index, Connection conn, Data data, HashMap dataMap) throws SQLException,
            ParseException {
        if (!StrFunc.isNull(sql)) {
            PreparedStatement pstat = conn.prepareStatement(sql);
            try {
                pstat.setString(1, data.getID());
                for (int i = 0; i < keys.length; i++) {
                    if ("VARCHAR".equals(types[i])) {
                        pstat.setString(i + index, (String) dataMap.get(keys[i]));
                    } else if ("CLOB".equals(types[i])) {
                        //pstat.setClob(i + 2, (oracle.sql.CLOB) data.getDataMap().get(keys[i]));
                        pstat.setString(i + index, (String) dataMap.get(keys[i]));
                    } else if ("DATE".equals(types[i])) {
                        if (StrFunc.isNull((String) dataMap.get(keys[i]))) {
                            pstat.setDate(i + index, null);
                        } else {
                            pstat.setDate(i + index, string2Date((String) dataMap.get(keys[i])));
                        }
                    } else if ("TIMESTAMP".equals(types[i])) {
                        if (!StrFunc.isNull((String) dataMap.get(keys[i]))) {
                            pstat.setTimestamp(i + index, string2Time((String) dataMap.get(keys[i])));
                        } else {
                            pstat.setTimestamp(i + index, null);
                        }
                    }
                }
                pstat.executeQuery();
            } finally {
                pstat.close();
            }
        } else {
            System.out.println("sql为空");
        }
    }

用TRUNCATE清楚表笔DELETE好

/**
     * 清除表
     * @param conn
     * @throws SQLException
     */
    private void clearTable(Connection conn) throws SQLException {
        Statement deleteState = conn.createStatement();
        try {
            deleteState.executeUpdate(truncateSql);
        } finally {
            deleteState.close();
        }
    }

将String类型转换成可以存到数据库的类型

/**
     * String转型到Timestamp
     * @param dateString
     * @return
     * @throws java.text.ParseException
     */
    public Timestamp string2Time(String dateString) throws java.text.ParseException {

        DateFormat dateFormat;
        dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss", Locale.CHINESE);// 设定格式
        dateFormat.setLenient(false);// 严格控制输入 比如2010-02-31,根本没有这一天 ,也会认为时间格式不对。
        Date timeDate = dateFormat.parse(dateString);// util类型
        Timestamp dateTime = new Timestamp(timeDate.getTime());// Timestamp类型,timeDate.getTime()返回一个long型   
        return dateTime;
    }

    /**
     * String转型到Date 而且是java.util.Date到java.sql.Date
     * @param str
     * @return
     * @throws ParseException
     */
    public java.sql.Date string2Date(String str) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");//小写的mm表示的是分钟
        Date date = sdf.parse(str);
        java.sql.Date sqlDate = new java.sql.Date(date.getTime());
        return sqlDate;
    }

返回的时候一种字符串的拼接

/**
     * 转换成JSON数据给返回
     * @param messages
     * @return
     */
    public String toJSON(List messages) {
        System.out.println(messages.size());
        if (messages.size() == 0) {
            return "数据为空";
        } else {
            StringBuffer str = new StringBuffer();
            str.append("[");
            Iterator iterator = messages.iterator();
            do {
                Message message = (Message) iterator.next();
                //组装一个对象   开始
                str.append("{\"id\":");
                str.append("\"" + message.getId() + "\",");
                str.append("\"reason\":");
                str.append("\"" + message.getReason() + "\",");
                str.append("\"isSuccess\":");
                str.append("\"" + message.getIsSuccess() + "\"}");
                //判断是否为最后一条数据,不是最后一条数据不需要加逗号---加了逗号也不影响,可以不判断
                str.append(",");
                //一个对象组装结束
                message.toString();
            } while (iterator.hasNext());
            str.append("]");
            return str.toString();
        }
    }
上一篇:磁力链接+爬虫


下一篇:CSS3 overflow-x 属性