Java做文件监控
Java做文件監控
Dao層 數據庫層,我們選用 JDBCTemplate 框架,輕量級 你要重量級就是hibrate這樣重量級的數據庫框架
二
package com.sunjun;import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Locale;import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener;import org.dom4j.Attribute; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader;import com.sunjun.dao.BorderDao; import com.sunjun.dao.StatusDao; import com.sunjun.dao.impl.BorderDaoImpl; import com.sunjun.dao.impl.StatusDaoImpl; import com.sunjun.domain.Border; import com.sunjun.domain.Status;public class InitListener implements ServletContextListener {@Overridepublic void contextInitialized(ServletContextEvent arg0) {BorderDao borderDao = new BorderDaoImpl();StatusDao statusDao = new StatusDaoImpl();final File file = new File("D:\\xmlbackup");new Thread(new Runnable() {@Overridepublic void run() {try {new WatchDir(file, true, new FileActionCallback() {@Overridepublic void create(File file) {try {System.out.println("創建文件 \t" + file.getAbsolutePath());Border border = new Border();SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");Thread.sleep(300);SAXReader reader = new SAXReader();Document document = reader.read(new File(file.getAbsolutePath()));Element root = document.getRootElement();Attribute testTimeAttr = root.attribute("testTime");String testTime = testTimeAttr.getText();DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");Date date = df.parse(testTimeAttr.getText());SimpleDateFormat df1 = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", Locale.UK);Date date1 = df1.parse(date.toString());DateFormat df2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");String value = df2.format(date1);border.setTestTime(sdf.parse(value));Attribute testStatusAttr = root.attribute("testStatus");border.setTestStatus(testStatusAttr.getText());Element contactElem = root.element("BoardXML");Attribute serialNumberAttr = contactElem.attribute("serialNumber");border.setSerialNumber(serialNumberAttr.getText());Attribute boardTypeAttr = contactElem.attribute("boardType");border.setBoardType(boardTypeAttr.getText());Element stationXML = root.element("StationXML");Attribute testerNameAttr = stationXML.attribute("testerName");border.setTesterName(testerNameAttr.getText());Border boder = borderDao.findBorderByserialNumbers(serialNumberAttr.getText());if (boder == null) {int add = borderDao.adds(border);System.out.println(add);} else {System.out.println("已經添加過");}List<Element> eleList = root.elements();List<Status> listStaus = new ArrayList<Status>();for(Element eles:eleList) {Status status =null;if(eles.getName().equals("TestXML")) {status = new Status();Element inElement = eles.element("IndictmentXML");status.setErrCode(inElement.attributeValue("indictmentType"));status.setSerialNumber(serialNumberAttr.getText());status.setImageFilename(inElement.attributeValue("imageFileName"));status.setAlgorithm(inElement.attributeValue("algorithm"));status.setSubType(inElement.attributeValue("subType"));List<Element> childList = inElement.elements();for(Element demo:childList) {if(demo.getName().equals("ComponentXML")) {Attribute attributedesignator = demo.attribute("designator");if(!"".equals(demo.attribute("pin").getValue())) {status.setPin(demo.attribute("pin").getValue().trim());}status.setLocation(attributedesignator.getValue());}if(demo.getName().equals("RepairActionXML")) {Attribute attributerepairStatus = demo.attribute("repairStatus");status.setRepairStatus(attributerepairStatus.getValue());}}}if(status !=null) {listStaus.add(status);}}int batchInsert = statusDao.batchInsert(listStaus);System.out.println("fail count " + batchInsert);} catch (DocumentException e) {e.printStackTrace();} catch (ParseException e) {e.printStackTrace();} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}});} catch (Exception e) {e.printStackTrace();}}}).start();System.out.println("開啟文件監控系統:" + file.getAbsolutePath());}@Overridepublic void contextDestroyed(ServletContextEvent sce) {}} package com.sunjun;import static java.nio.file.LinkOption.NOFOLLOW_LINKS;import java.io.File; import java.io.IOException; import java.nio.file.FileSystems; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.SimpleFileVisitor; import java.nio.file.StandardWatchEventKinds; import java.nio.file.WatchEvent; import java.nio.file.WatchEvent.Kind; import java.nio.file.WatchKey; import java.nio.file.WatchService; import java.nio.file.attribute.BasicFileAttributes; import java.util.HashMap; import java.util.Map;public class WatchDir {private final WatchService watcher;private final Map<WatchKey, Path> keys;private final boolean subDir;public WatchDir(File file, boolean subDir, FileActionCallback callback) throws Exception {if (!file.isDirectory())throw new Exception(file.getAbsolutePath() );this.watcher = FileSystems.getDefault().newWatchService();this.keys = new HashMap<WatchKey, Path>();this.subDir = subDir;Path dir = Paths.get(file.getAbsolutePath());if (subDir) {registerAll(dir);} else {register(dir);}processEvents(callback);}@SuppressWarnings("unchecked")static <T> WatchEvent<T> cast(WatchEvent<?> event) {return (WatchEvent<T>) event;}private void register(Path dir) throws IOException {WatchKey key = dir.register(watcher, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY);keys.put(key, dir);}private void registerAll(final Path start) throws IOException {Files.walkFileTree(start, new SimpleFileVisitor<Path>() {@Overridepublic FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {register(dir);return FileVisitResult.CONTINUE;}});}@SuppressWarnings("rawtypes")void processEvents(FileActionCallback callback) {for (;;) {WatchKey key;try {key = watcher.take();} catch (InterruptedException x) {return;}Path dir = keys.get(key);if (dir == null) {continue;}for (WatchEvent<?> event : key.pollEvents()) {Kind kind = event.kind();if (kind == StandardWatchEventKinds.OVERFLOW) {continue;}WatchEvent<Path> ev = cast(event);Path name = ev.context();Path child = dir.resolve(name);File file = child.toFile();if (kind.name().equals("ENTRY_DELETE")) {callback.delete(file);} else if (kind.name().equals("ENTRY_CREATE")) {callback.create(file);} else if (kind.name().equals("ENTRY_MODIFY")) {callback.modify(file);} else {continue;}if (subDir && (kind == StandardWatchEventKinds.ENTRY_CREATE)) {try {if (Files.isDirectory(child, NOFOLLOW_LINKS)) {registerAll(child);}} catch (IOException x) {}}}boolean valid = key.reset();if (!valid) {keys.remove(key);if (keys.isEmpty()) {break;}}}}} package com.sunjun.dao;import java.util.List; import java.util.Map;import com.sunjun.domain.Border;public interface BorderDao {int add(Border border);Border findBorderByserialNumber(String serialNumber);List<Border> findBorderTypesAll();int findTotalCount(Map<String, String[]> condition);int adds(Border border);Border findBorderByserialNumbers(String text);} package com.sunjun.dao;import java.util.List;import com.sunjun.domain.Status;public interface StatusDao {int batchInsert(List<Status> list) throws Exception; } package com.sunjun.dao.impl;import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set;import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate;import com.sunjun.dao.BorderDao; import com.sunjun.domain.Border; import com.sunjun.util.JDBCUtils;public class BorderDaoImpl implements BorderDao{private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());@Overridepublic int add(Border border) {String sql = "INSERT INTO `t_borders` VALUES(NULL,?,?,?,?,?)";return template.update(sql,border.getTestTime(),border.getSerialNumber(),border.getTesterName(),border.getTestStatus(),border.getBoardType());}@Overridepublic int adds(Border border) {String sql = "INSERT INTO `tt_borders` VALUES(?,?,?,?,?)";return template.update(sql,border.getSerialNumber(),border.getBoardType(),border.getTesterName(),border.getTestStatus(),border.getTestTime());}@Overridepublic Border findBorderByserialNumber(String serialNumber) {try{ String sql="SELECT * FROM `t_borders` WHERE serialNumber = ?";return template.queryForObject(sql, new BeanPropertyRowMapper<Border>(Border.class),serialNumber);} catch (Exception e) {e.printStackTrace();return null;}}@Overridepublic Border findBorderByserialNumbers(String serialNumber) {try{ String sql="SELECT * FROM `tt_borders` WHERE serialNumber = ?";return template.queryForObject(sql, new BeanPropertyRowMapper<Border>(Border.class),serialNumber);} catch (Exception e) {e.printStackTrace();return null;}}@Overridepublic List<Border> findBorderTypesAll() {String sql = "select `boardType` from `t_borders`";List<Border> lists = template.query(sql, new BeanPropertyRowMapper<Border>(Border.class));return lists;}@Overridepublic int findTotalCount(Map<String, String[]> condition) {//1.定義模板初始化sqlString sql = "select count(*) from t_borders where 1 = 1 ";StringBuilder sb = new StringBuilder(sql);//2.遍歷mapSet<String> keySet = condition.keySet();//定義參數的集合List<Object> params = new ArrayList<Object>();for (String key : keySet) {//排除分頁條件參數if("currentPage".equals(key) || "rows".equals(key)){continue;}//獲取valueString value = condition.get(key)[0];//判斷value是否有值if(value != null && !"".equals(value)){//有值sb.append(" and "+key+" like ? ");params.add("%"+value+"%");//?條件的值}}System.out.println(sb.toString());System.out.println(params);return template.queryForObject(sb.toString(),Integer.class,params.toArray());}} package com.sunjun.dao.impl;import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.List;import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.PreparedStatementSetter;import com.sunjun.dao.StatusDao; import com.sunjun.domain.Status; import com.sunjun.util.JDBCUtils;public class StatusDaoImpl implements StatusDao {private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());@Overridepublic int batchInsert(List<Status> list) throws Exception {String insertBatchSql = "INSERT INTO t_status (serial_number,location,pin,err_code,repair_status,image_filename,algorithm,sub_type) VALUES (?,?,?,?,?,?,?,?)";if(list.size()==0) {return 0;}String batchsql = getBatchInsertSql(insertBatchSql,list);int k = template.update(batchsql,new PreparedStatementSetter() {@Overridepublic void setValues(PreparedStatement ps) throws SQLException {ObjectToPs(ps,list);}});return k;}public void ObjectToPs(PreparedStatement ps,List<Status> list) throws SQLException{for(int i=0;i<list.size();++i) {Status statusModel = (Status)list.get(i);ps.setString(8*i+1, statusModel.getSerialNumber());ps.setString(8*i+2, statusModel.getLocation());ps.setString(8*i+3, statusModel.getPin());ps.setString(8*i+4, statusModel.getErrCode());ps.setString(8*i+5, statusModel.getRepairStatus());ps.setString(8*i+6, statusModel.getImageFilename());ps.setString(8*i+7, statusModel.getAlgorithm());ps.setString(8*i+8, statusModel.getSubType());}}public static String getBatchInsertSql(String keyStr,List list)throws Exception {int index = keyStr.indexOf("VALUES");String loopStr = keyStr.substring(index + 6);StringBuilder sb = new StringBuilder(keyStr.substring(0,index+6));for(int j=0;j<list.size();++j) {sb.append(loopStr);if(j<list.size()-1) {sb.append(",");}}return sb.toString();}}總結
- 上一篇: Qt实现截图的源码
- 下一篇: mysql的联表查询和去重复数据