code
stringlengths
3
1.18M
language
stringclasses
1 value
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * JTreeFromXMLFile.java * * Created on 10-06-2009, 14:28:32 */ package doanlythuyet_javaoutlook.MyUserControl; import BUS.MyContactBUS; import DTO.MyContactDTO; import doanlythuyet_javaoutlook.EventListener_ClickChuotVaoCayDuyetFile; import doanlythuyet_javaoutlook.MyEmum.JEnum_ContactGroupBy; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.io.File; import java.sql.SQLException; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; import javax.xml.parsers.*; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import org.w3c.dom.*; import java.io.IOException; //import javax.swing.; import java.text.AttributedCharacterIterator.Attribute; import java.util.Enumeration; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPopupMenu; import javax.swing.JTree; import javax.swing.UIManager; import javax.swing.event.MouseInputListener; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeCellRenderer; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.MutableTreeNode; import javax.swing.tree.TreeNode; import javax.swing.tree.TreePath; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.xml.sax.SAXException; /** * * @author ShineShiao */ public class JPanel_HienThiContact extends javax.swing.JPanel { private boolean m_chiDoc; private final JPopupMenu m_popupMenu; private JEnum_ContactGroupBy m_ThuocTinhGroupBy;// = "C:\\Documents and Settings\\Administrator\\Desktop\\JavaMail\\ 0512324-0512328-0512333-mailclient\\DoAnLyThuyet_JavaOutLook\\src\\Database\\XML_ThuMucNguoiDung.xml"; /** Creates new form JTreeFromXMLFile */ public void expandTree (TreePath path){ jTreeThuMucNguoiDung.expandPath(path); } // If expand is true, expands all nodes in the tree. // Otherwise, collapses all nodes in the tree. public static void expandAll(JTree tree, boolean expand) { TreeNode root = (TreeNode)tree.getModel().getRoot(); // Traverse tree from root expandAll(tree, new TreePath(root), expand); } private static void expandAll(JTree tree, TreePath parent, boolean expand) { // Traverse children TreeNode node = (TreeNode)parent.getLastPathComponent(); if (node.getChildCount() >= 0) { for (Enumeration e=node.children(); e.hasMoreElements(); ) { TreeNode n = (TreeNode)e.nextElement(); TreePath path = parent.pathByAddingChild(n); expandAll(tree, path, expand); } } // Expansion or collapse must be done bottom-up if (expand) { tree.expandPath(parent); } else { tree.collapsePath(parent); } } public JPanel_HienThiContact(JEnum_ContactGroupBy thuocTinhGroupBy, Boolean chiDoc) throws SQLException, SAXException, ParserConfigurationException { m_chiDoc = chiDoc; m_ThuocTinhGroupBy = thuocTinhGroupBy; m_popupMenu = new JPopupMenu(); if (!chiDoc){ String cacHanhViThayDoiCauTruc[] = {"Thêm mới", "Xóa", "Đổi Tên"}; for (String HanhVi : cacHanhViThayDoiCauTruc) { JMenuItem menuItem = new JMenuItem(HanhVi); menuItem.addMouseListener(new PopupMenu_MouseListerner_MyCayHienThiThuMuc(menuItem.getText())); m_popupMenu.add(menuItem); } m_popupMenu.addSeparator(); } String cacHanhViKhongThayDoiCauTruc[] = {"Đánh dấu đã đọc", "Đánh dấu chưa đọc", "Gỡ dấu"}; for (String HanhVi : cacHanhViKhongThayDoiCauTruc) { JMenuItem menuItem = new JMenuItem(HanhVi); menuItem.addMouseListener(new PopupMenu_MouseListerner_MyCayHienThiThuMuc(menuItem.getText())); m_popupMenu.add(menuItem); } initComponents(); try { thayDoiIconCuaTree(); MyContactBUS contactBUS = new MyContactBUS(); ArrayList<MyContactDTO> cacContactDTO= contactBUS.layTatCaContact(); TaoCay(cacContactDTO); //expandTree(new TreePath(jTreeThuMucNguoiDung.getModel().getRoot())); expandAll(jTreeThuMucNguoiDung, true); } catch (IOException ex) { Logger.getLogger(JTreeFromXMLFile.class.getName()).log(Level.SEVERE, null, ex); JOptionPane.showMessageDialog(null, "Tao cay thu muc tu file XML loi: " + ex.getMessage()); } jTreeThuMucNguoiDung.addMouseListener(new MouseListener() { public void mouseClicked(MouseEvent e) { //throw new UnsupportedOperationException("Not supported yet."); if (jTreeThuMucNguoiDung.getSelectionPath() == null) return; String strPath = StringPathFromTreePath(jTreeThuMucNguoiDung.getSelectionPath()); getM_popupMenu().setToolTipText(strPath); if (e.getButton() == MouseEvent.BUTTON3) { getM_popupMenu().show(e.getComponent(), e.getX(), e.getY()); //return; } } public void mousePressed(MouseEvent e) { //throw new UnsupportedOperationException("Not supported yet."); } public void mouseReleased(MouseEvent e) { //throw new UnsupportedOperationException("Not supported yet."); } public void mouseEntered(MouseEvent e) { //throw new UnsupportedOperationException("Not supported yet."); } public void mouseExited(MouseEvent e) { //throw new UnsupportedOperationException("Not supported yet."); } }); } public static TreePath TreePathFromStringPath (String stringPath){ String cacPath[] = stringPath.split("\\\\"); MutableTreeNode cacNode[] = new MutableTreeNode[cacPath.length]; for (int i = 0; i < cacPath.length; i++) cacNode[i] = new DefaultMutableTreeNode(cacPath[i]); return new TreePath(cacNode); } public static String StringPathFromTreePath (TreePath treePath){ String Kq = ""; Object cacNode[] = treePath.getPath(); for (int i = 0; i < cacNode.length; i++) Kq += ((DefaultMutableTreeNode)cacNode[i]).getUserObject().toString() + "\\"; return Kq; } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jScrollPane1 = new javax.swing.JScrollPane(); jTreeThuMucNguoiDung = new javax.swing.JTree(); setName("Form"); // NOI18N jScrollPane1.setName("jScrollPane1"); // NOI18N jTreeThuMucNguoiDung.setName("jTreeThuMucNguoiDung"); // NOI18N jTreeThuMucNguoiDung.addTreeSelectionListener(new javax.swing.event.TreeSelectionListener() { public void valueChanged(javax.swing.event.TreeSelectionEvent evt) { jTreeThuMucNguoiDungValueChanged(evt); } }); jScrollPane1.setViewportView(jTreeThuMucNguoiDung); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 336, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 265, Short.MAX_VALUE) ); }// </editor-fold>//GEN-END:initComponents private void jTreeThuMucNguoiDungValueChanged(javax.swing.event.TreeSelectionEvent evt) {//GEN-FIRST:event_jTreeThuMucNguoiDungValueChanged // TODO add your handling code here: String strPath = StringPathFromTreePath(jTreeThuMucNguoiDung.getSelectionPath()); initEvent_ClickChuotVaoCayDuyetFile(strPath); }//GEN-LAST:event_jTreeThuMucNguoiDungValueChanged public void TaoCay(ArrayList<MyContactDTO> cacContactDTO) throws SAXException, IOException, ParserConfigurationException{ DefaultTreeModel model = (DefaultTreeModel)getJTreeThuMucNguoiDung().getModel(); MutableTreeNode newNode = new DefaultMutableTreeNode("Contacts"); model.setRoot(newNode); String strGroupHienTai = ""; String strGroupCuaPhanTuTiepTheo = ""; for (MyContactDTO contactDTO : cacContactDTO){ strGroupCuaPhanTuTiepTheo = layGroupCuaPhanTuTiepTheo(contactDTO); if (!strGroupCuaPhanTuTiepTheo.equals(strGroupHienTai)){ strGroupHienTai = strGroupCuaPhanTuTiepTheo; } } } public void ThemXMLElementVaoTree(DefaultTreeModel model,Element ele,MutableTreeNode nodeCha){ MutableTreeNode newNode = new DefaultMutableTreeNode(ele.getAttribute("name")); model.insertNodeInto(newNode, nodeCha, nodeCha.getChildCount()); for (int i =0;i<ele.getChildNodes().getLength();i++){ ThemXMLElementVaoTree(model, (Element)ele.getChildNodes().item(i), newNode); } } /** Thay đổi icon của cây * * */ public void thayDoiIconCuaTree(){ // Retrieve the three icons Icon leafIcon = new ImageIcon("leaf.gif"); Icon openIcon = new ImageIcon("open.gif"); Icon closedIcon = new ImageIcon("closed.gif"); // Update only one tree instance DefaultTreeCellRenderer renderer = (DefaultTreeCellRenderer)jTreeThuMucNguoiDung.getCellRenderer(); renderer.setLeafIcon(leafIcon); renderer.setClosedIcon(closedIcon); renderer.setOpenIcon(openIcon); // Remove the icons renderer.setLeafIcon(null); renderer.setClosedIcon(null); renderer.setOpenIcon(null); // Change defaults so that all new tree components will have new icons UIManager.put("Tree.leafIcon", leafIcon); UIManager.put("Tree.openIcon", openIcon); UIManager.put("Tree.closedIcon", closedIcon); // Create tree with new icons //setJTreeThuMucNguoiDung(tree); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTree jTreeThuMucNguoiDung; // End of variables declaration//GEN-END:variables /** * @return the jTreeThuMucNguoiDung */ public javax.swing.JTree getJTreeThuMucNguoiDung() { return jTreeThuMucNguoiDung; } /** * @param jTreeThuMucNguoiDung the jTreeThuMucNguoiDung to set */ public void setJTreeThuMucNguoiDung(javax.swing.JTree jTreeThuMucNguoiDung) { this.jTreeThuMucNguoiDung = jTreeThuMucNguoiDung; } //<editor-fold defaultstate="collapsed" desc="Dung de phat sinh su kien"> //Các hàm sau phục vụ cho việc gởi sự kiện click chuột vào bảng ra ngoài (tham khảo từ nhiều nguồn trên mạng) //http://www.exampledepot.com/egs/java.util/CustEvent.html // Tạo một listener list protected javax.swing.event.EventListenerList listenerList = new javax.swing.event.EventListenerList(); /** * Phát sinh sử kiện click chuột vào tree * @param evt tham số cho sự kiện click chuột vào tree (ở đây là tên của file đang được chọn) */ // This private class is used to fire MyEvents void initEvent_ClickChuotVaoCayDuyetFile(String evt) { Object[] listeners = listenerList.getListenerList(); // Each listener occupies two elements - the first is the listener class // and the second is the listener instance for (int i = 0; i < listeners.length; i += 2) { if (listeners[i] == EventListener_ClickChuotVaoCayDuyetFile.class) { ((EventListener_ClickChuotVaoCayDuyetFile) listeners[i + 1]).Event_ClickChuotVaoCayDuyetFile_Occurred(evt); } } } /** * Đăng ký sự kiện cho classes * @param listener Sự kiện cần đăng ký */ public void addEventListener_ClickChuotVaoCayDuyetFile(EventListener_ClickChuotVaoCayDuyetFile listener) { listenerList.add(EventListener_ClickChuotVaoCayDuyetFile.class, listener); } /** * Gỡ bỏ sự kiện khỏi classes * @param listener Sự kiện cần gỡ bỏ */ public void delEventListener_ClickChuotVaoCayDuyetFile(EventListener_ClickChuotVaoCayDuyetFile listener) { listenerList.remove(EventListener_ClickChuotVaoCayDuyetFile.class, listener); } /** * @return the m_popupMenu */ public JPopupMenu getM_popupMenu() { return m_popupMenu; } private String layGroupCuaPhanTuTiepTheo(MyContactDTO contactDTO) { String strGroupCuaPhanTuTiepTheo = ""; switch (m_ThuocTinhGroupBy) { case Adress: { strGroupCuaPhanTuTiepTheo = contactDTO.getM_Email(); break; } case Company: { strGroupCuaPhanTuTiepTheo = contactDTO.getM_CongTy(); break; } default: { break; } } return strGroupCuaPhanTuTiepTheo; } //</editor-fold> }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package doanlythuyet_javaoutlook.MyUserControl; import BUS.MyMailBUS; import doanlythuyet_javaoutlook.DoAnLyThuyet_JavaOutLookApp; import doanlythuyet_javaoutlook.DoAnLyThuyet_JavaOutLookView; import doanlythuyet_javaoutlook.EventListener_ClickChuotVaoCayDuyetFile; import doanlythuyet_javaoutlook.MyUserControl.JDialog_NhapTenThuMuc; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPopupMenu; import doanlythuyet_javaoutlook.MyUserControl.JTreeFromXMLFile; import java.io.File; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import org.xml.sax.SAXException; /** * * @author Administrator */ public class PopupMenu_MouseListerner_MyCayHienThiThuMuc implements MouseListener{ private String m_HanhViDuocChon; private String sdataPath; //public String m_ThuMucDangChon; public PopupMenu_MouseListerner_MyCayHienThiThuMuc(String hanhVi){ m_HanhViDuocChon = hanhVi; listenerList = new javax.swing.event.EventListenerList(); } public void mouseClicked(MouseEvent e) { //throw new UnsupportedOperationException("Not supported yet."); } public void mousePressed(MouseEvent e) { //throw new UnsupportedOperationException("Not supported yet."); //JOptionPane.showMessageDialog(null, "Hanh vi duoc chon: " + m_HanhViDuocChon + "xu ly code tai dong file popupmenu_mycay....java"); String strPath = ((JPopupMenu) ((JMenuItem)e.getSource()).getParent()).getToolTipText(); //String dataPath = DoAnLyThuyet_JavaOutLookApp.getCurdir() + "\\src\\Database\\"; // dataPath = this.getClass().getResource("/Database/").getPath().replace("%20", " ").substring(6); //strPath = ; String fileName = "XML_ThuMucNguoiDung.xml"; String strFileName = new File(".").getAbsolutePath() + "\\Database\\" + fileName; //JOptionPane.showMessageDialog(null, strFileName); JTreeFromXMLFile tree = new JTreeFromXMLFile(strFileName, false); //Xử Lý Thêm Thư Mục if (m_HanhViDuocChon.equals("Thêm mới")){ try { JDialog_NhapTenThuMuc dialog = new JDialog_NhapTenThuMuc(null, true); dialog.setVisible(true); String tenThuMuc = dialog.getTenThuMuc(); dialog.dispose(); if (tenThuMuc.equals("")) return; tree.ThemThuMucMoiVaoXML(strPath, dialog.getTenThuMuc(), strFileName); } catch (ParserConfigurationException ex) { Logger.getLogger(PopupMenu_MouseListerner_MyCayHienThiThuMuc.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(PopupMenu_MouseListerner_MyCayHienThiThuMuc.class.getName()).log(Level.SEVERE, null, ex); } catch (SAXException ex) { Logger.getLogger(PopupMenu_MouseListerner_MyCayHienThiThuMuc.class.getName()).log(Level.SEVERE, null, ex); } catch (TransformerConfigurationException ex) { Logger.getLogger(PopupMenu_MouseListerner_MyCayHienThiThuMuc.class.getName()).log(Level.SEVERE, null, ex); } catch (TransformerException ex) { Logger.getLogger(PopupMenu_MouseListerner_MyCayHienThiThuMuc.class.getName()).log(Level.SEVERE, null, ex); } } else if (m_HanhViDuocChon.equals("Xóa")){ try { tree.XoaThuMucTrongXML(strPath, strFileName); } catch (ParserConfigurationException ex) { Logger.getLogger(PopupMenu_MouseListerner_MyCayHienThiThuMuc.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(PopupMenu_MouseListerner_MyCayHienThiThuMuc.class.getName()).log(Level.SEVERE, null, ex); } catch (SAXException ex) { Logger.getLogger(PopupMenu_MouseListerner_MyCayHienThiThuMuc.class.getName()).log(Level.SEVERE, null, ex); } catch (TransformerConfigurationException ex) { Logger.getLogger(PopupMenu_MouseListerner_MyCayHienThiThuMuc.class.getName()).log(Level.SEVERE, null, ex); } catch (TransformerException ex) { Logger.getLogger(PopupMenu_MouseListerner_MyCayHienThiThuMuc.class.getName()).log(Level.SEVERE, null, ex); } } else if (m_HanhViDuocChon.equals("Đổi Tên")){ try { JDialog_NhapTenThuMuc dialog = new JDialog_NhapTenThuMuc(null, true); dialog.setVisible(true); String tenThuMuc = dialog.getTenThuMuc(); dialog.dispose(); if (tenThuMuc.equals("")) return; tree.DoiTenThuMucTrongXML(strPath, dialog.getTenThuMuc(), strFileName); } catch (ParserConfigurationException ex) { Logger.getLogger(PopupMenu_MouseListerner_MyCayHienThiThuMuc.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(PopupMenu_MouseListerner_MyCayHienThiThuMuc.class.getName()).log(Level.SEVERE, null, ex); } catch (SAXException ex) { Logger.getLogger(PopupMenu_MouseListerner_MyCayHienThiThuMuc.class.getName()).log(Level.SEVERE, null, ex); } catch (TransformerConfigurationException ex) { Logger.getLogger(PopupMenu_MouseListerner_MyCayHienThiThuMuc.class.getName()).log(Level.SEVERE, null, ex); } catch (TransformerException ex) { Logger.getLogger(PopupMenu_MouseListerner_MyCayHienThiThuMuc.class.getName()).log(Level.SEVERE, null, ex); } } //vẽ lại cây try { tree.TaoCay(); DoAnLyThuyet_JavaOutLookView.getJTree_ThuMucTrenMay().getJTreeThuMucNguoiDung().setModel(tree.getJTreeThuMucNguoiDung().getModel()); } catch (SAXException ex) { Logger.getLogger(PopupMenu_MouseListerner_MyBangDanhSachFile.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(PopupMenu_MouseListerner_MyBangDanhSachFile.class.getName()).log(Level.SEVERE, null, ex); } catch (ParserConfigurationException ex) { Logger.getLogger(PopupMenu_MouseListerner_MyBangDanhSachFile.class.getName()).log(Level.SEVERE, null, ex); } // ThemThuMucMoiVaoXML(strPath,"New folder"); } public void mouseReleased(MouseEvent e) { //throw new UnsupportedOperationException("Not supported yet."); } public void mouseEntered(MouseEvent e) { //throw new UnsupportedOperationException("Not supported yet."); } public void mouseExited(MouseEvent e) { //throw new UnsupportedOperationException("Not supported yet."); } //<editor-fold defaultstate="collapsed" desc="Dung de phat sinh su kien"> //Các hàm sau phục vụ cho việc gởi sự kiện click chuột vào bảng ra ngoài (tham khảo từ nhiều nguồn trên mạng) //http://www.exampledepot.com/egs/java.util/CustEvent.html // Tạo một listener list protected javax.swing.event.EventListenerList listenerList = new javax.swing.event.EventListenerList(); /** * Phát sinh sử kiện click chuột vào tree * @param evt tham số cho sự kiện click chuột vào tree (ở đây là tên của file đang được chọn) */ // This private class is used to fire MyEvents void initEvent_ClickChuotVaoCayDuyetFile(String evt) { Object[] listeners = listenerList.getListenerList(); // Each listener occupies two elements - the first is the listener class // and the second is the listener instance for (int i = 0; i < listeners.length; i += 2) { if (listeners[i] == EventListener_ClickChuotVaoCayDuyetFile.class) { ((EventListener_ClickChuotVaoCayDuyetFile) listeners[i + 1]).Event_ClickChuotVaoCayDuyetFile_Occurred(evt); } } } /** * Đăng ký sự kiện cho classes * @param listener Sự kiện cần đăng ký */ public void addEventListener_ClickChuotVaoCayDuyetFile(EventListener_ClickChuotVaoCayDuyetFile listener) { listenerList.add(EventListener_ClickChuotVaoCayDuyetFile.class, listener); } /** * Gỡ bỏ sự kiện khỏi classes * @param listener Sự kiện cần gỡ bỏ */ public void delEventListener_ClickChuotVaoCayDuyetFile(EventListener_ClickChuotVaoCayDuyetFile listener) { listenerList.remove(EventListener_ClickChuotVaoCayDuyetFile.class, listener); } //</editor-fold> }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package doanlythuyet_javaoutlook.MyUserControl; import java.util.ArrayList; /** * * @author Administrator */ public class jClass_ChuDe { private static ArrayList<String> cacChuDe = new ArrayList<String>(); /** * @return the cacChuDe */ public static ArrayList<String> getCacChuDe() { return cacChuDe; } /** * @param aCacChuDe the cacChuDe to set */ public static void setCacChuDe(ArrayList<String> aCacChuDe) { cacChuDe = aCacChuDe; } public jClass_ChuDe(){ cacChuDe.add("Không có"); cacChuDe.add("<html><head></head><body><b style='color:red'>Khẩn cấp<b><body>"); cacChuDe.add("<html><head></head><body><b style='color:blue'>Chậm<b><body>"); cacChuDe.add("<html><head></head><body><b style='color:green'>Xong<b><body>"); } public static void Them (String ten){ getCacChuDe().add(ten); } public static void Xoa (String ten){ getCacChuDe().remove(ten); } public static int LaySTT (String ten){ return getCacChuDe().indexOf(ten); } public static String LayTen (int index){ return getCacChuDe().get(index); } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * JPanel_XemMail.java * * Created on May 27, 2009, 9:23:59 AM */ package doanlythuyet_javaoutlook.MyUserControl; import BUS.MyAttachBUS; import BUS.MyMailBUS; import DTO.MyMailDTO; import doanlythuyet_javaoutlook.DoAnLyThuyet_JavaOutLookApp; import doanlythuyet_javaoutlook.MyEmum.JEnum_TinhTrang; import doanlythuyet_javaoutlook.MyMail; import java.awt.Component; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.sql.SQLException; import java.util.ArrayList; import java.util.Hashtable; import java.util.logging.Level; import java.util.logging.Logger; import javax.mail.Part; import javax.mail.Session; import javax.mail.internet.MimeMessage; import javax.swing.AbstractButton; import javax.swing.DefaultComboBoxModel; import javax.swing.DefaultListModel; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPopupMenu; import javax.swing.JTable; import javax.swing.UIManager; import javax.swing.event.MouseInputListener; import javax.swing.table.DefaultTableModel; import javax.swing.table.JTableHeader; import javax.swing.table.TableCellRenderer; import javax.swing.table.TableColumn; import javax.swing.table.TableColumnModel; import javax.swing.table.TableModel; /** * * @author Dang Thi Phuong Thao */ public class JPanel_XemMail extends javax.swing.JPanel { //private Boolean tatCaDuocChon = false; private final JPopupMenu popupMenu; /** * lay cac id mail duoc danh dau check trong bang * @return */ public ArrayList<Integer> LayCacIdMailDuocChon (){ ArrayList<Integer> Kq = new ArrayList<Integer>(); for (int i = 0; i < jTable_danhsachmail.getRowCount(); i++) if (jTable_danhsachmail.getValueAt(i, 0) != null && (Boolean)jTable_danhsachmail.getValueAt(i, 0)) Kq.add(Integer.parseInt(jTable_danhsachmail.getValueAt(i, jTable_danhsachmail.getColumnCount() - 1).toString())); return Kq; } private void ChuyenMailDTOLenGiaoDien (MyMailDTO mailDTO){ FileInputStream inputStream = null; try { jLabel_chude.setText(mailDTO.getM_ChuDe()); jLabel_goitu.setText(mailDTO.getM_NguoiGoi()); jLabel_den.setText(mailDTO.getM_NguoiNhan()); jLabel_ngay.setText(mailDTO.getM_Ngay().toString()); inputStream = new FileInputStream(new File(DoAnLyThuyet_JavaOutLookApp.getCurdir() + mailDTO.getM_DuongDanFileChuaNoiDung())); MyMail mail = new MyMail(DoAnLyThuyet_JavaOutLookApp.getSmtp_host(), DoAnLyThuyet_JavaOutLookApp.getPop3_host(), DoAnLyThuyet_JavaOutLookApp.getUser() , DoAnLyThuyet_JavaOutLookApp.getPass(), DoAnLyThuyet_JavaOutLookApp.getProxy(), DoAnLyThuyet_JavaOutLookApp.getPort()); Session sess = mail.getMailSession(false); MimeMessage mess = new MimeMessage(sess, inputStream); Part textPart = MyMail.layPartNoiDung(mess); if (textPart != null){ jEditorPane_chitietmail.setContentType(textPart.getContentType()); jEditorPane_chitietmail.setText(textPart.getContent().toString()); } else{ jEditorPane_chitietmail.setText(mess.getContent().toString()); } } catch (Exception ex) { Logger.getLogger(JPanel_XemMail.class.getName()).log(Level.SEVERE, null, ex); JOptionPane.showMessageDialog(null, ex.toString()); } try { inputStream.close(); } catch (IOException ex) { Logger.getLogger(JPanel_XemMail.class.getName()).log(Level.SEVERE, null, ex); } } private void XemSoLuocMail (int MailID){ try { jEditorPane_chitietmail.setText("viet ham lay Mine Message cua mailid: " + MailID + " (file JPanel_XamMail.java dong 55)"); MyMailBUS mailBUS = new MyMailBUS(); MyMailDTO mailDTO = mailBUS.layMailVoidMailID(String.valueOf(MailID)); if (mailDTO.getM_TinhTrang() == JEnum_TinhTrang.Moi.value()){ mailDTO.setM_TinhTrang(JEnum_TinhTrang.DaXem.value()); mailBUS.capNhatMail(mailDTO); refreshBang(mailBUS); } if (mailDTO != null) ChuyenMailDTOLenGiaoDien(mailDTO); else return; } catch (IOException ex) { Logger.getLogger(JPanel_XemMail.class.getName()).log(Level.SEVERE, null, ex); } } /** Creates new form JPanel_XemMail */ public JPanel_XemMail() { initComponents(); DefaultComboBoxModel model = new DefaultComboBoxModel(); jClass_ChuDe cacChuDe = new jClass_ChuDe(); for (String str : jClass_ChuDe.getCacChuDe()){ model.addElement(str); } //model.addElement("Thêm mới!"); jComboBox1.setModel(model); popupMenu = new JPopupMenu(); String[] cacHanhVi = {"Di Chuyen", "Copy", "Xoa"}; for (String HanhVi : cacHanhVi) { JMenuItem menuItem = new JMenuItem(HanhVi); menuItem.addMouseListener(new PopupMenu_MouseListerner_MyBangDanhSachFile(menuItem.getText())); popupMenu.add(menuItem); } jTable_danhsachmail.addMouseListener(new MouseInputListener() { public void mouseClicked(MouseEvent e) { if (e.isPopupTrigger()){ //popupMenu.getComponentAt(e.getX(), e.getY()).get //return; } if (jTable_danhsachmail.getSelectedRow() == -1) return; //if (e.getButton() == MouseEvent.BUTTON1){ int row = jTable_danhsachmail.getSelectedRow(); //(PopupMenu_MouseListerner_MyBangDanhSachFile) popupMenu.getli //jTable_danhsachmail.getColumnModel().getColumn(1).getCellEditor().getCellEditorValue() //int MailID = Integer.getInteger(jTable_danhsachmail.getValueAt(row, jTable_danhsachmail.getColumnCount() - 1).toString()); String strMailID = jTable_danhsachmail.getValueAt(row, jTable_danhsachmail.getColumnCount() - 1).toString(); getPopupMenu().setToolTipText(strMailID); //int MailID = Integer.valueOf(strMailID); int MailID = Integer.valueOf(strMailID); //if (e.getClickCount() == 1){ //JOptionPane.showMessageDialog(null, MailID); //jLabel_chude.setText(String.valueOf(MailID)); //jLabel_chude.setText(String.valueOf(MailID)); XemSoLuocMail(MailID); //} if (e.getClickCount() == 2 && e.getButton() == MouseEvent.BUTTON1){ JFrame_ChiTietMail chiTietMail = new JFrame_ChiTietMail(MailID); chiTietMail.setVisible(true); } //} if (e.getButton() == MouseEvent.BUTTON3) { getPopupMenu().show(e.getComponent(), e.getX(), e.getY()); //return; } //throw new UnsupportedOperationException("Not supported yet."); } public void mousePressed(MouseEvent e) { //throw new UnsupportedOperationException("Not supported yet."); } public void mouseReleased(MouseEvent e) { //throw new UnsupportedOperationException("Not supported yet."); } public void mouseEntered(MouseEvent e) { //throw new UnsupportedOperationException("Not supported yet."); } public void mouseExited(MouseEvent e) { //throw new UnsupportedOperationException("Not supported yet."); } public void mouseDragged(MouseEvent e) { //throw new UnsupportedOperationException("Not supported yet."); } public void mouseMoved(MouseEvent e) { //throw new UnsupportedOperationException("Not supported yet."); } }); //DuaDanhSachMailVaoBang(DanhSachMail); } public void ThemDongVaoBang (JTable table, Object[][] CacGiaTri){ DefaultTableModel model = (DefaultTableModel) table.getModel(); //model } public void XoaDongTrongBang (JTable table, int[] Indexs){ DefaultTableModel model = (DefaultTableModel) table.getModel(); //model. } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jSplitPane1 = new javax.swing.JSplitPane(); jPanel_DanhSachMail = new javax.swing.JPanel(); jScrollPane1 = new javax.swing.JScrollPane(); jToolBar1 = new javax.swing.JToolBar(); jButton_Xoa = new javax.swing.JButton(); jSeparator1 = new javax.swing.JToolBar.Separator(); jButton_DDDaDoc = new javax.swing.JButton(); jButtonDDChuaDoc = new javax.swing.JButton(); jSeparator2 = new javax.swing.JToolBar.Separator(); jButton_DiChuyen = new javax.swing.JButton(); jSeparator3 = new javax.swing.JToolBar.Separator(); jLabel5 = new javax.swing.JLabel(); jComboBox1 = new javax.swing.JComboBox(); jPanel_ChiTietMail = new javax.swing.JPanel(); jScrollPane2 = new javax.swing.JScrollPane(); jEditorPane_chitietmail = new javax.swing.JEditorPane(); jPanel1 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jLabel_chude = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel_goitu = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel_ngay = new javax.swing.JLabel(); jLabel_den = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); setName("Form"); // NOI18N addAncestorListener(new javax.swing.event.AncestorListener() { public void ancestorMoved(javax.swing.event.AncestorEvent evt) { } public void ancestorAdded(javax.swing.event.AncestorEvent evt) { formAncestorAdded(evt); } public void ancestorRemoved(javax.swing.event.AncestorEvent evt) { } }); jSplitPane1.setDividerLocation(200); jSplitPane1.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT); jSplitPane1.setName("jSplitPane1"); // NOI18N org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(doanlythuyet_javaoutlook.DoAnLyThuyet_JavaOutLookApp.class).getContext().getResourceMap(JPanel_XemMail.class); jPanel_DanhSachMail.setForeground(resourceMap.getColor("jPanel_DanhSachMail.foreground")); // NOI18N jPanel_DanhSachMail.setFont(resourceMap.getFont("jPanel_DanhSachMail.font")); // NOI18N jPanel_DanhSachMail.setName("jPanel_DanhSachMail"); // NOI18N jScrollPane1.setName("jScrollPane1"); // NOI18N jToolBar1.setRollover(true); jToolBar1.setName("jToolBar1"); // NOI18N jButton_Xoa.setIcon(resourceMap.getIcon("jButton_Xoa.icon")); // NOI18N jButton_Xoa.setText(resourceMap.getString("jButton_Xoa.text")); // NOI18N jButton_Xoa.setFocusable(false); jButton_Xoa.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); jButton_Xoa.setName("jButton_Xoa"); // NOI18N jButton_Xoa.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); jButton_Xoa.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton_XoaActionPerformed(evt); } }); jToolBar1.add(jButton_Xoa); jSeparator1.setName("jSeparator1"); // NOI18N jToolBar1.add(jSeparator1); jButton_DDDaDoc.setIcon(resourceMap.getIcon("jButton_DDDaDoc.icon")); // NOI18N jButton_DDDaDoc.setText(resourceMap.getString("jButton_DDDaDoc.text")); // NOI18N jButton_DDDaDoc.setFocusable(false); jButton_DDDaDoc.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); jButton_DDDaDoc.setName("jButton_DDDaDoc"); // NOI18N jButton_DDDaDoc.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); jButton_DDDaDoc.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton_DDDaDocActionPerformed(evt); } }); jToolBar1.add(jButton_DDDaDoc); jButtonDDChuaDoc.setIcon(resourceMap.getIcon("jButtonDDChuaDoc.icon")); // NOI18N jButtonDDChuaDoc.setText(resourceMap.getString("jButtonDDChuaDoc.text")); // NOI18N jButtonDDChuaDoc.setFocusable(false); jButtonDDChuaDoc.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); jButtonDDChuaDoc.setName("jButtonDDChuaDoc"); // NOI18N jButtonDDChuaDoc.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); jButtonDDChuaDoc.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonDDChuaDocActionPerformed(evt); } }); jToolBar1.add(jButtonDDChuaDoc); jSeparator2.setName("jSeparator2"); // NOI18N jToolBar1.add(jSeparator2); jButton_DiChuyen.setIcon(resourceMap.getIcon("jButton_DiChuyen.icon")); // NOI18N jButton_DiChuyen.setText(resourceMap.getString("jButton_DiChuyen.text")); // NOI18N jButton_DiChuyen.setFocusable(false); jButton_DiChuyen.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); jButton_DiChuyen.setName("jButton_DiChuyen"); // NOI18N jButton_DiChuyen.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); jButton_DiChuyen.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton_DiChuyenActionPerformed(evt); } }); jToolBar1.add(jButton_DiChuyen); jSeparator3.setName("jSeparator3"); // NOI18N jToolBar1.add(jSeparator3); jLabel5.setText(resourceMap.getString("jLabel5.text")); // NOI18N jLabel5.setName("jLabel5"); // NOI18N jToolBar1.add(jLabel5); jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" })); jComboBox1.setName("jComboBox1"); // NOI18N jComboBox1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jComboBox1ActionPerformed(evt); } }); jToolBar1.add(jComboBox1); javax.swing.GroupLayout jPanel_DanhSachMailLayout = new javax.swing.GroupLayout(jPanel_DanhSachMail); jPanel_DanhSachMail.setLayout(jPanel_DanhSachMailLayout); jPanel_DanhSachMailLayout.setHorizontalGroup( jPanel_DanhSachMailLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 557, Short.MAX_VALUE) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel_DanhSachMailLayout.createSequentialGroup() .addContainerGap() .addComponent(jToolBar1, javax.swing.GroupLayout.DEFAULT_SIZE, 537, Short.MAX_VALUE) .addContainerGap()) ); jPanel_DanhSachMailLayout.setVerticalGroup( jPanel_DanhSachMailLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel_DanhSachMailLayout.createSequentialGroup() .addGap(11, 11, 11) .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 47, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 190, javax.swing.GroupLayout.PREFERRED_SIZE)) ); jSplitPane1.setTopComponent(jPanel_DanhSachMail); jPanel_ChiTietMail.setName("jPanel_ChiTietMail"); // NOI18N jScrollPane2.setName("jScrollPane2"); // NOI18N jEditorPane_chitietmail.setContentType(resourceMap.getString("jEditorPane_chitietmail.contentType")); // NOI18N jEditorPane_chitietmail.setName("jEditorPane_chitietmail"); // NOI18N jScrollPane2.setViewportView(jEditorPane_chitietmail); jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(resourceMap.getString("jPanel1.border.title"))); // NOI18N jPanel1.setName("jPanel1"); // NOI18N jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N jLabel1.setName("jLabel1"); // NOI18N jLabel_chude.setBackground(resourceMap.getColor("jLabel_chude.background")); // NOI18N jLabel_chude.setFont(resourceMap.getFont("jLabel_chude.font")); // NOI18N jLabel_chude.setForeground(resourceMap.getColor("jLabel_chude.foreground")); // NOI18N jLabel_chude.setText(resourceMap.getString("jLabel_chude.text")); // NOI18N jLabel_chude.setName("jLabel_chude"); // NOI18N jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N jLabel2.setName("jLabel2"); // NOI18N jLabel_goitu.setFont(resourceMap.getFont("jLabel_goitu.font")); // NOI18N jLabel_goitu.setForeground(resourceMap.getColor("jLabel_goitu.foreground")); // NOI18N jLabel_goitu.setText(resourceMap.getString("jLabel_goitu.text")); // NOI18N jLabel_goitu.setName("jLabel_goitu"); // NOI18N jLabel4.setText(resourceMap.getString("jLabel4.text")); // NOI18N jLabel4.setName("jLabel4"); // NOI18N jLabel_ngay.setFont(resourceMap.getFont("jLabel_ngay.font")); // NOI18N jLabel_ngay.setForeground(resourceMap.getColor("jLabel_ngay.foreground")); // NOI18N jLabel_ngay.setText(resourceMap.getString("jLabel_ngay.text")); // NOI18N jLabel_ngay.setName("jLabel_ngay"); // NOI18N jLabel_den.setFont(resourceMap.getFont("jLabel_den.font")); // NOI18N jLabel_den.setForeground(resourceMap.getColor("jLabel_den.foreground")); // NOI18N jLabel_den.setText(resourceMap.getString("jLabel_den.text")); // NOI18N jLabel_den.setName("jLabel_den"); // NOI18N jLabel3.setText(resourceMap.getString("jLabel3.text")); // NOI18N jLabel3.setName("jLabel3"); // NOI18N javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel_chude, javax.swing.GroupLayout.PREFERRED_SIZE, 54, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel4)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jLabel_goitu) .addGap(218, 218, 218) .addComponent(jLabel3))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel_den) .addComponent(jLabel_ngay)) .addGap(171, 171, 171)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(jLabel_chude, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel4) .addComponent(jLabel_ngay)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(jLabel_goitu) .addComponent(jLabel3) .addComponent(jLabel_den))) ); javax.swing.GroupLayout jPanel_ChiTietMailLayout = new javax.swing.GroupLayout(jPanel_ChiTietMail); jPanel_ChiTietMail.setLayout(jPanel_ChiTietMailLayout); jPanel_ChiTietMailLayout.setHorizontalGroup( jPanel_ChiTietMailLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 557, Short.MAX_VALUE) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 557, Short.MAX_VALUE) ); jPanel_ChiTietMailLayout.setVerticalGroup( jPanel_ChiTietMailLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel_ChiTietMailLayout.createSequentialGroup() .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 262, Short.MAX_VALUE)) ); jSplitPane1.setRightComponent(jPanel_ChiTietMail); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 559, Short.MAX_VALUE) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jSplitPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 538, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); }// </editor-fold>//GEN-END:initComponents private void formAncestorAdded(javax.swing.event.AncestorEvent evt) {//GEN-FIRST:event_formAncestorAdded }//GEN-LAST:event_formAncestorAdded private void jButton_XoaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_XoaActionPerformed // TODO add your handling code here: ArrayList<Integer> cacIdDangChon = LayCacIdMailDuocChon(); MyMailBUS mailBUS = new MyMailBUS(); for (int i=0;i<cacIdDangChon.size();i++){ try { mailBUS.xoaMail(cacIdDangChon.get(i).toString()); refreshBang(mailBUS); } catch (IOException ex) { Logger.getLogger(JPanel_XemMail.class.getName()).log(Level.SEVERE, null, ex); } } refreshBang(mailBUS); }//GEN-LAST:event_jButton_XoaActionPerformed private void jButtonDDChuaDocActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonDDChuaDocActionPerformed // TODO add your handling code here: ArrayList<Integer> cacIdDangChon = LayCacIdMailDuocChon(); MyMailBUS mailBUS = new MyMailBUS(); for (int i=0;i<cacIdDangChon.size();i++){ MyMailDTO mailDTO = new MyMailDTO(); try { mailDTO = mailBUS.layMailVoidMailID(cacIdDangChon.get(i).toString()); mailDTO.setM_TinhTrang(1); mailBUS.capNhatMail(mailDTO); refreshBang(mailBUS); } catch (IOException ex) { Logger.getLogger(JPanel_XemMail.class.getName()).log(Level.SEVERE, null, ex); } } }//GEN-LAST:event_jButtonDDChuaDocActionPerformed private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox1ActionPerformed // TODO add your handling code here: //thach: viet code o day JComboBox cb = (JComboBox)evt.getSource(); String strMucDo = (String)cb.getSelectedItem(); int iMucDo = jClass_ChuDe.LaySTT(strMucDo); MyMailBUS mailBUS = new MyMailBUS(); ArrayList<Integer> dsMail = LayCacIdMailDuocChon(); for (int i = 0 ; i < dsMail.size();i++){ try { MyMailDTO mailDTO = new MyMailDTO(); mailDTO = mailBUS.layMailVoidMailID(dsMail.get(i).toString()); mailDTO.setM_MucDo(iMucDo); mailBUS.capNhatMail(mailDTO); refreshBang(mailBUS); } catch (IOException ex) { Logger.getLogger(JPanel_XemMail.class.getName()).log(Level.SEVERE, null, ex); } } }//GEN-LAST:event_jComboBox1ActionPerformed private void jButton_DDDaDocActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_DDDaDocActionPerformed // TODO add your handling code here: ArrayList<Integer> cacIdDangChon = LayCacIdMailDuocChon(); MyMailBUS mailBUS = new MyMailBUS(); for (int i=0;i<cacIdDangChon.size();i++){ MyMailDTO mailDTO = new MyMailDTO(); try { mailDTO = mailBUS.layMailVoidMailID(cacIdDangChon.get(i).toString()); mailDTO.setM_TinhTrang(2); mailBUS.capNhatMail(mailDTO); refreshBang(mailBUS); } catch (IOException ex) { Logger.getLogger(JPanel_XemMail.class.getName()).log(Level.SEVERE, null, ex); } } }//GEN-LAST:event_jButton_DDDaDocActionPerformed private void jButton_DiChuyenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_DiChuyenActionPerformed // TODO add your handling code here: MyMailBUS mailBUS = new MyMailBUS(); ArrayList<Integer> dsMail = LayCacIdMailDuocChon(); JDialog_ChonThuMucDich dialog_ChonThuMucDich = new JDialog_ChonThuMucDich(null, true); dialog_ChonThuMucDich.setVisible(true); String thuMucDich = dialog_ChonThuMucDich.getM_ThuMucDuocChon(); dialog_ChonThuMucDich.dispose(); if (thuMucDich.equals("")) return; int somailcapnhat = 0; for (int i = 0 ; i < dsMail.size();i++){ try { mailBUS.thayDoiDuongDanThuMuc(dsMail.get(i).toString(), thuMucDich); somailcapnhat ++; } catch (IOException ex) { Logger.getLogger(JPanel_XemMail.class.getName()).log(Level.SEVERE, null, ex); } } JOptionPane.showMessageDialog(null, "Đã di chuyển " + somailcapnhat + " mail"); refreshBang(mailBUS); }//GEN-LAST:event_jButton_DiChuyenActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButtonDDChuaDoc; private javax.swing.JButton jButton_DDDaDoc; private javax.swing.JButton jButton_DiChuyen; private javax.swing.JButton jButton_Xoa; private javax.swing.JComboBox jComboBox1; private javax.swing.JEditorPane jEditorPane_chitietmail; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel_chude; private javax.swing.JLabel jLabel_den; private javax.swing.JLabel jLabel_goitu; private javax.swing.JLabel jLabel_ngay; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel_ChiTietMail; private javax.swing.JPanel jPanel_DanhSachMail; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JToolBar.Separator jSeparator1; private javax.swing.JToolBar.Separator jSeparator2; private javax.swing.JToolBar.Separator jSeparator3; private javax.swing.JSplitPane jSplitPane1; private javax.swing.JToolBar jToolBar1; // End of variables declaration//GEN-END:variables private JTable jTable_danhsachmail = new JTable(); public void DuaDanhSachMailVaoBang(ArrayList<MyMailDTO>DanhSachMail) throws IOException, SQLException{ final String cacCotDuLieu[] = {"Tất cả","Tình trạng","Đính kèm","Người Gởi","Chủ Đề", "Ngày", "Phân loại", "MailID"}; Object DuLieu[][] = new Object[DanhSachMail.size()][cacCotDuLieu.length]; for(int i = 0; i < DanhSachMail.size();i++){ int index = 0; DuLieu[i][index++] = false; //for(int j = 1; i < model.) dulieu[index] = new Object(); if (DanhSachMail.get(i).getM_TinhTrang() == JEnum_TinhTrang.Moi.value()){ Icon icon = new ImageIcon(this.getClass().getResource("/doanlythuyet_javaoutlook/MyUserControl/resources/new mail.png")); DuLieu[i][index] = icon; } index++; if (new MyAttachBUS().layTatCaAttachCuaMailID(DanhSachMail.get(i).getM_Id()).size() != 0){ Icon icon = new ImageIcon(this.getClass().getResource("/doanlythuyet_javaoutlook/MyUserControl/resources/attach.png")); DuLieu[i][index] = icon; } index++; DuLieu[i][index++] = DanhSachMail.get(i).getM_NguoiGoi(); //dulieu[index++] = DanhSachMail.get(i).getM_NguoiGoi(); DuLieu[i][index++] = DanhSachMail.get(i).getM_ChuDe(); DuLieu[i][index++] = DanhSachMail.get(i).getM_Ngay().toString(); jClass_ChuDe chude = new jClass_ChuDe(); int MucDo = DanhSachMail.get(i).getM_MucDo(); if (MucDo > 0) DuLieu[i][index++] = jClass_ChuDe.LayTen(MucDo); else DuLieu[i][index++] = ""; DuLieu[i][index++] = DanhSachMail.get(i).getM_Id(); } final Object bangDuLieu[][] = DuLieu; DefaultTableModel modelBangHienThi = new DefaultTableModel(bangDuLieu,cacCotDuLieu) { @Override public Class getColumnClass(int columnIndex) { switch (columnIndex){ case 0: return Boolean.class; case 1: return ImageIcon.class; case 2: return ImageIcon.class; default: return String.class; } } @Override public int getColumnCount() { return cacCotDuLieu.length; } @Override public String getColumnName(int column) { return cacCotDuLieu[column]; } @Override public int getRowCount() { return bangDuLieu.length; } @Override public Object getValueAt(int row, int column) { return bangDuLieu[row][column]; } @Override public void setValueAt(Object value, int row, int column) { bangDuLieu[row][column] = value; } @Override public boolean isCellEditable(int row, int column) { return column == 0; } }; jTable_danhsachmail.setModel(modelBangHienThi); //jTable_danhsachmail = new TableSelectionTest(cacCotDuLieu, bangDuLieu); TableColumn tc = jTable_danhsachmail.getColumnModel().getColumn(0); tc.setCellEditor(jTable_danhsachmail.getDefaultEditor(Boolean.class)); tc.setCellRenderer(jTable_danhsachmail.getDefaultRenderer(Boolean.class)); tc.setHeaderRenderer(new CheckBoxHeader(new MyItemListener())); // <editor-fold defaultstate="collapsed" desc="Cai dat giao dien cho bang"> //jTable_danhsachmail.setSize(500, 100); jTable_danhsachmail.getColumnModel().getColumn(0).setMaxWidth(25); jTable_danhsachmail.getColumnModel().getColumn(jTable_danhsachmail.getColumnCount() - 1).setMinWidth(0); jTable_danhsachmail.getColumnModel().getColumn(jTable_danhsachmail.getColumnCount() - 1).setMaxWidth(0); jTable_danhsachmail.getColumnModel().getColumn(jTable_danhsachmail.getColumnCount() - 1).setPreferredWidth(0); //jTable_danhsachmail. // </ediort-fold> jScrollPane1.setViewportView(jTable_danhsachmail); } private void DoiTrangThaiCotCheckBox (boolean isDuocChon){ TableModel tableModel = jTable_danhsachmail.getModel(); for (int i = 0; i < tableModel.getRowCount(); i++){ tableModel.setValueAt(isDuocChon, i, 0); } } /** * @return the popupMenu */ public JPopupMenu getPopupMenu() { return popupMenu; } private void refreshBang(MyMailBUS mailBUS) { //thanh:refresh giao dien de? cap nhat String str_fileduocchon = getToolTipText(); Hashtable<String, String> cacDieuKien = new Hashtable<String, String>(); cacDieuKien.put("DuongDanThuMuc", str_fileduocchon); try { ArrayList<MyMailDTO> cacMailDTO = mailBUS.layTatCaMailVoiDieuKien(str_fileduocchon, cacDieuKien); DuaDanhSachMailVaoBang(cacMailDTO); } catch (SQLException ex) { Logger.getLogger(JPanel_XemMail.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(JPanel_XemMail.class.getName()).log(Level.SEVERE, null, ex); } } class MyItemListener implements ItemListener{ public void itemStateChanged(ItemEvent e) { Object source = e.getSource(); if (source instanceof AbstractButton == false) return; boolean checked = e.getStateChange() == ItemEvent.SELECTED; DoiTrangThaiCotCheckBox(checked); } } } class CheckBoxHeader extends JCheckBox implements TableCellRenderer, MouseListener { protected CheckBoxHeader rendererComponent; protected int column; protected boolean mousePressed = false; public CheckBoxHeader(ItemListener itemListener) { rendererComponent = this; rendererComponent.addItemListener(itemListener); } public Component getTableCellRendererComponent( JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { if (table != null) { JTableHeader header = table.getTableHeader(); if (header != null) { rendererComponent.setForeground(header.getForeground()); rendererComponent.setBackground(header.getBackground()); rendererComponent.setFont(header.getFont()); header.addMouseListener(rendererComponent); } } setColumn(column); rendererComponent.setText(""); setBorder(UIManager.getBorder("TableHeader.cellBorder")); return rendererComponent; } protected void setColumn(int column) { this.column = column; } public int getColumn() { return column; } protected void handleClickEvent(MouseEvent e) { if (mousePressed) { mousePressed=false; JTableHeader header = (JTableHeader)(e.getSource()); JTable tableView = header.getTable(); TableColumnModel columnModel = tableView.getColumnModel(); int viewColumn = columnModel.getColumnIndexAtX(e.getX()); int columnindex = tableView.convertColumnIndexToModel(viewColumn); if (viewColumn == this.column && e.getClickCount() == 1 && columnindex != -1) { doClick(); } } } public void mouseClicked(MouseEvent e) { handleClickEvent(e); ((JTableHeader)e.getSource()).repaint(); } public void mousePressed(MouseEvent e) { mousePressed = true; } public void mouseReleased(MouseEvent e) { } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * JFrame_GuiMail.java * * Created on May 28, 2009, 1:34:23 AM */ package doanlythuyet_javaoutlook.MyUserControl; import BUS.MyAttachBUS; import BUS.MyMailBUS; import DTO.MyAttachDTO; import DTO.MyMailDTO; import doanlythuyet_javaoutlook.DoAnLyThuyet_JavaOutLookApp; import doanlythuyet_javaoutlook.MyEmum.JEnum_TinhTrang; import doanlythuyet_javaoutlook.MyMail; import java.awt.Dialog; import java.awt.event.WindowEvent; import java.awt.event.WindowStateListener; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.sql.SQLException; import java.util.ArrayList; import java.util.Date; import java.util.logging.Level; import java.util.logging.Logger; import javax.activation.DataHandler; import javax.activation.DataSource; import javax.activation.FileDataSource; import javax.mail.Folder; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Multipart; import javax.mail.Part; import javax.mail.Session; import javax.mail.Store; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; import javax.swing.DefaultListModel; import javax.swing.JDialog; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import javax.swing.ListModel; /** * * @author Dang Thi Phuong Thao */ public class JFrame_GuiMail extends javax.swing.JFrame { /** Creates new form JFrame_GuiMail */ public JFrame_GuiMail() { initComponents(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); //this.setc } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jToolBar1 = new javax.swing.JToolBar(); jButton_send2 = new javax.swing.JButton(); jButton_addressbook = new javax.swing.JButton(); jPanel1 = new javax.swing.JPanel(); jTextField_to = new javax.swing.JTextField(); jButton1 = new javax.swing.JButton(); jButton2 = new javax.swing.JButton(); jTextField_cc = new javax.swing.JTextField(); jButton4 = new javax.swing.JButton(); jTextField_bcc = new javax.swing.JTextField(); jLabel1 = new javax.swing.JLabel(); jTextField_subject = new javax.swing.JTextField(); jPanel2 = new javax.swing.JPanel(); jScrollPane1 = new javax.swing.JScrollPane(); jTextArea_noidung = new javax.swing.JTextArea(); jToolBar2 = new javax.swing.JToolBar(); jCheckBox_SendHTML = new javax.swing.JCheckBox(); jPanel3 = new javax.swing.JPanel(); jScrollPane_ListAttach = new javax.swing.JScrollPane(); jList_CacAttach = new javax.swing.JList(); jButton_ThemAttach = new javax.swing.JButton(); jButton_XoaAttach = new javax.swing.JButton(); jPanel4 = new javax.swing.JPanel(); jButton_Send = new javax.swing.JButton(); jButton_Send1 = new javax.swing.JButton(); menuBar = new javax.swing.JMenuBar(); javax.swing.JMenu fileMenu = new javax.swing.JMenu(); jMenu_New = new javax.swing.JMenu(); jMenuItem_Mail = new javax.swing.JMenuItem(); jMenuItem_Contact = new javax.swing.JMenuItem(); jMenuItem_Task = new javax.swing.JMenuItem(); jMenuItem_Folder = new javax.swing.JMenuItem(); jSeparator1 = new javax.swing.JSeparator(); jMenuItem_Save = new javax.swing.JMenuItem(); jMenuItem_SaveAs = new javax.swing.JMenuItem(); jMenuItem2 = new javax.swing.JMenuItem(); jSeparator5 = new javax.swing.JSeparator(); jMenuItem_delete = new javax.swing.JMenuItem(); jMenuItem3 = new javax.swing.JMenuItem(); jSeparator2 = new javax.swing.JSeparator(); javax.swing.JMenuItem jMenuItem_Close = new javax.swing.JMenuItem(); jMenu_Edit = new javax.swing.JMenu(); jMenuItem_Cut = new javax.swing.JMenuItem(); jMenuItem_Copy = new javax.swing.JMenuItem(); jMenuItem_Paste = new javax.swing.JMenuItem(); jSeparator3 = new javax.swing.JSeparator(); jMenuItem_SelectAll = new javax.swing.JMenuItem(); jSeparator4 = new javax.swing.JSeparator(); jMenuItem1 = new javax.swing.JMenuItem(); jMenu_Tools = new javax.swing.JMenu(); jMenuItem_Find = new javax.swing.JMenuItem(); javax.swing.JMenu helpMenu = new javax.swing.JMenu(); javax.swing.JMenuItem aboutMenuItem = new javax.swing.JMenuItem(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setName("Form"); // NOI18N jToolBar1.setRollover(true); jToolBar1.setName("jToolBar1"); // NOI18N org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(doanlythuyet_javaoutlook.DoAnLyThuyet_JavaOutLookApp.class).getContext().getResourceMap(JFrame_GuiMail.class); jButton_send2.setText(resourceMap.getString("jButton_send2.text")); // NOI18N jButton_send2.setFocusable(false); jButton_send2.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); jButton_send2.setName("jButton_send2"); // NOI18N jButton_send2.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); jToolBar1.add(jButton_send2); jButton_addressbook.setText(resourceMap.getString("jButton_addressbook.text")); // NOI18N jButton_addressbook.setFocusable(false); jButton_addressbook.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); jButton_addressbook.setName("jButton_addressbook"); // NOI18N jButton_addressbook.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); jToolBar1.add(jButton_addressbook); jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(resourceMap.getString("jPanel1.border.title"))); // NOI18N jPanel1.setName("jPanel1"); // NOI18N jTextField_to.setText(resourceMap.getString("jTextField_to.text")); // NOI18N jTextField_to.setName("jTextField_to"); // NOI18N jButton1.setText(resourceMap.getString("jButton_To.text")); // NOI18N jButton1.setName("jButton_To"); // NOI18N jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jButton2.setText(resourceMap.getString("jButton_cc.text")); // NOI18N jButton2.setName("jButton_cc"); // NOI18N jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); jTextField_cc.setText(resourceMap.getString("jTextField_cc.text")); // NOI18N jTextField_cc.setName("jTextField_cc"); // NOI18N jButton4.setText(resourceMap.getString("jButton4.text")); // NOI18N jButton4.setName("jButton4"); // NOI18N jButton4.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton4ActionPerformed(evt); } }); jTextField_bcc.setName("jTextField_bcc"); // NOI18N jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N jLabel1.setName("jLabel1"); // NOI18N jTextField_subject.setText(resourceMap.getString("jTextField_subject.text")); // NOI18N jTextField_subject.setName("jTextField_subject"); // NOI18N javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, 71, Short.MAX_VALUE) .addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, 71, Short.MAX_VALUE)) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel1))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jTextField_subject, javax.swing.GroupLayout.DEFAULT_SIZE, 607, Short.MAX_VALUE) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jTextField_cc, javax.swing.GroupLayout.PREFERRED_SIZE, 266, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 61, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jTextField_bcc, javax.swing.GroupLayout.DEFAULT_SIZE, 268, Short.MAX_VALUE)) .addComponent(jTextField_to, javax.swing.GroupLayout.DEFAULT_SIZE, 607, Short.MAX_VALUE)) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton1) .addComponent(jTextField_to, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextField_cc, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton4) .addComponent(jTextField_bcc, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton2)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextField_subject, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel1))) ); jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(resourceMap.getString("jPanel2.border.title"))); // NOI18N jPanel2.setName("jPanel2"); // NOI18N jScrollPane1.setName("jScrollPane1"); // NOI18N jTextArea_noidung.setColumns(20); jTextArea_noidung.setRows(5); jTextArea_noidung.setText(resourceMap.getString("jTextArea_noidungmail.text")); // NOI18N jTextArea_noidung.setName("jTextArea_noidungmail"); // NOI18N jTextArea_noidung.setNextFocusableComponent(jButton_Send); jScrollPane1.setViewportView(jTextArea_noidung); jToolBar2.setRollover(true); jToolBar2.setName("jToolBar2"); // NOI18N jCheckBox_SendHTML.setText(resourceMap.getString("jCheckBox_SendHTML.text")); // NOI18N jCheckBox_SendHTML.setFocusable(false); jCheckBox_SendHTML.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); jCheckBox_SendHTML.setName("jCheckBox_SendHTML"); // NOI18N jCheckBox_SendHTML.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); jCheckBox_SendHTML.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jCheckBox_SendHTMLActionPerformed(evt); } }); jToolBar2.add(jCheckBox_SendHTML); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 674, Short.MAX_VALUE) .addComponent(jToolBar2, javax.swing.GroupLayout.PREFERRED_SIZE, 430, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap()) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(jToolBar2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 174, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder(resourceMap.getString("jPanel3.border.title"))); // NOI18N jPanel3.setName("jPanel3"); // NOI18N jScrollPane_ListAttach.setName("jScrollPane_ListAttach"); // NOI18N jList_CacAttach.setModel(new DefaultListModel()); jList_CacAttach.setName("jList_CacAttach"); // NOI18N jScrollPane_ListAttach.setViewportView(jList_CacAttach); jButton_ThemAttach.setText(resourceMap.getString("jButton_ThemAttach.text")); // NOI18N jButton_ThemAttach.setName("jButton_ThemAttach"); // NOI18N jButton_ThemAttach.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton_ThemAttachActionPerformed(evt); } }); jButton_XoaAttach.setText(resourceMap.getString("jButton_XoaAttach.text")); // NOI18N jButton_XoaAttach.setName("jButton_XoaAttach"); // NOI18N jButton_XoaAttach.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton_XoaAttachActionPerformed(evt); } }); javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); jPanel3.setLayout(jPanel3Layout); jPanel3Layout.setHorizontalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addComponent(jScrollPane_ListAttach, javax.swing.GroupLayout.PREFERRED_SIZE, 382, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jButton_ThemAttach) .addComponent(jButton_XoaAttach)) .addContainerGap(36, Short.MAX_VALUE)) ); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane_ListAttach, javax.swing.GroupLayout.PREFERRED_SIZE, 61, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(jPanel3Layout.createSequentialGroup() .addComponent(jButton_ThemAttach) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButton_XoaAttach) .addContainerGap()) ); jPanel4.setBorder(javax.swing.BorderFactory.createTitledBorder(resourceMap.getString("jPanel4.border.title"))); // NOI18N jPanel4.setName("jPanel4"); // NOI18N jButton_Send.setText(resourceMap.getString("jButton_send.text")); // NOI18N jButton_Send.setName("jButton_send"); // NOI18N jButton_Send.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton_SendActionPerformed(evt); } }); jButton_Send1.setText(resourceMap.getString("jButton_Send1.text")); // NOI18N jButton_Send1.setName("jButton_Send1"); // NOI18N jButton_Send1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton_Send1ActionPerformed(evt); } }); javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4); jPanel4.setLayout(jPanel4Layout); jPanel4Layout.setHorizontalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addContainerGap() .addComponent(jButton_Send, javax.swing.GroupLayout.PREFERRED_SIZE, 74, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 44, Short.MAX_VALUE) .addComponent(jButton_Send1) .addContainerGap()) ); jPanel4Layout.setVerticalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel4Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jButton_Send1) .addComponent(jButton_Send, javax.swing.GroupLayout.DEFAULT_SIZE, 41, Short.MAX_VALUE)) .addContainerGap()) ); menuBar.setName("menuBar"); // NOI18N fileMenu.setText(resourceMap.getString("fileMenu.text")); // NOI18N fileMenu.setName("fileMenu"); // NOI18N jMenu_New.setText(resourceMap.getString("jMenu_New.text")); // NOI18N jMenu_New.setName("jMenu_New"); // NOI18N jMenuItem_Mail.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_N, java.awt.event.InputEvent.CTRL_MASK)); jMenuItem_Mail.setText(resourceMap.getString("jMenuItem_Mail.text")); // NOI18N jMenuItem_Mail.setName("jMenuItem_Mail"); // NOI18N jMenu_New.add(jMenuItem_Mail); jMenuItem_Contact.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_C, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK)); jMenuItem_Contact.setText(resourceMap.getString("jMenuItem_Contact.text")); // NOI18N jMenuItem_Contact.setName("jMenuItem_Contact"); // NOI18N jMenu_New.add(jMenuItem_Contact); jMenuItem_Task.setText(resourceMap.getString("jMenuItem_Task.text")); // NOI18N jMenuItem_Task.setName("jMenuItem_Task"); // NOI18N jMenu_New.add(jMenuItem_Task); jMenuItem_Folder.setText(resourceMap.getString("jMenuItem_Folder.text")); // NOI18N jMenuItem_Folder.setName("jMenuItem_Folder"); // NOI18N jMenu_New.add(jMenuItem_Folder); fileMenu.add(jMenu_New); jSeparator1.setName("jSeparator1"); // NOI18N fileMenu.add(jSeparator1); jMenuItem_Save.setText(resourceMap.getString("jMenuItem_Save.text")); // NOI18N jMenuItem_Save.setName("jMenuItem_Save"); // NOI18N fileMenu.add(jMenuItem_Save); jMenuItem_SaveAs.setText(resourceMap.getString("jMenuItem_SaveAs.text")); // NOI18N jMenuItem_SaveAs.setName("jMenuItem_SaveAs"); // NOI18N fileMenu.add(jMenuItem_SaveAs); jMenuItem2.setText(resourceMap.getString("jMenuItem2.text")); // NOI18N jMenuItem2.setName("jMenuItem2"); // NOI18N fileMenu.add(jMenuItem2); jSeparator5.setName("jSeparator5"); // NOI18N fileMenu.add(jSeparator5); jMenuItem_delete.setText(resourceMap.getString("jMenuItem_delete.text")); // NOI18N jMenuItem_delete.setName("jMenuItem_delete"); // NOI18N fileMenu.add(jMenuItem_delete); jMenuItem3.setText(resourceMap.getString("jMenuItem3.text")); // NOI18N jMenuItem3.setName("jMenuItem3"); // NOI18N fileMenu.add(jMenuItem3); jSeparator2.setName("jSeparator2"); // NOI18N fileMenu.add(jSeparator2); javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(doanlythuyet_javaoutlook.DoAnLyThuyet_JavaOutLookApp.class).getContext().getActionMap(JFrame_GuiMail.class, this); jMenuItem_Close.setAction(actionMap.get("quit")); // NOI18N jMenuItem_Close.setText(resourceMap.getString("jMenuItem_Close.text")); // NOI18N jMenuItem_Close.setName("jMenuItem_Close"); // NOI18N fileMenu.add(jMenuItem_Close); menuBar.add(fileMenu); jMenu_Edit.setText(resourceMap.getString("jMenu_Edit.text")); // NOI18N jMenu_Edit.setName("jMenu_Edit"); // NOI18N jMenuItem_Cut.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_X, java.awt.event.InputEvent.CTRL_MASK)); jMenuItem_Cut.setText(resourceMap.getString("jMenuItem_Cut.text")); // NOI18N jMenuItem_Cut.setName("jMenuItem_Cut"); // NOI18N jMenu_Edit.add(jMenuItem_Cut); jMenuItem_Copy.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_C, java.awt.event.InputEvent.CTRL_MASK)); jMenuItem_Copy.setText(resourceMap.getString("jMenuItem_Copy.text")); // NOI18N jMenuItem_Copy.setName("jMenuItem_Copy"); // NOI18N jMenu_Edit.add(jMenuItem_Copy); jMenuItem_Paste.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_V, java.awt.event.InputEvent.CTRL_MASK)); jMenuItem_Paste.setText(resourceMap.getString("jMenuItem_Paste.text")); // NOI18N jMenuItem_Paste.setName("jMenuItem_Paste"); // NOI18N jMenu_Edit.add(jMenuItem_Paste); jSeparator3.setName("jSeparator3"); // NOI18N jMenu_Edit.add(jSeparator3); jMenuItem_SelectAll.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_A, java.awt.event.InputEvent.CTRL_MASK)); jMenuItem_SelectAll.setText(resourceMap.getString("jMenuItem_SelectAll.text")); // NOI18N jMenuItem_SelectAll.setName("jMenuItem_SelectAll"); // NOI18N jMenu_Edit.add(jMenuItem_SelectAll); jSeparator4.setName("jSeparator4"); // NOI18N jMenu_Edit.add(jSeparator4); jMenuItem1.setText(resourceMap.getString("jMenuItem1.text")); // NOI18N jMenuItem1.setName("jMenuItem1"); // NOI18N jMenu_Edit.add(jMenuItem1); menuBar.add(jMenu_Edit); jMenu_Tools.setText(resourceMap.getString("jMenu_Tools.text")); // NOI18N jMenu_Tools.setName("jMenu_Tools"); // NOI18N jMenuItem_Find.setText(resourceMap.getString("jMenuItem_Find.text")); // NOI18N jMenuItem_Find.setName("jMenuItem_Find"); // NOI18N jMenu_Tools.add(jMenuItem_Find); menuBar.add(jMenu_Tools); helpMenu.setText(resourceMap.getString("helpMenu.text")); // NOI18N helpMenu.setName("helpMenu"); // NOI18N aboutMenuItem.setAction(actionMap.get("showAboutBox")); // NOI18N aboutMenuItem.setName("aboutMenuItem"); // NOI18N helpMenu.add(aboutMenuItem); menuBar.add(helpMenu); setJMenuBar(menuBar); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 663, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents public void ThucHienCacBuocGoiMailTuGiaoDienNguoiDung () throws Exception{ MimeMessage mess = GoiMailTuGiaoDienNguoiDung(); int idMail = luuMailVaoCSDL(mess,"Mails\\Sent\\"); luuAttachVaoCSDL(mess, idMail); JOptionPane.showMessageDialog(null, "Qua trinh ket thuc"); } /** * luu cac part vao HDD * @param cacPart * @param idmal id dung de tao attachdto cung dung de tao thu muc luu tru cho cac attach * @return cac AttachDTO cua file duoc luu * @throws java.io.IOException * @throws javax.mail.MessagingException * da hoan thanh */ public static ArrayList<MyAttachDTO> luuTruCacPartVaoHDD (ArrayList <Part> cacPart, int idMail) throws IOException, MessagingException{ int i = 0; String reDir = "\\MailAttachs\\"; ArrayList<MyAttachDTO> Kq = new ArrayList<MyAttachDTO>(); //<Kiem tra xem thu muc chua da co chua neu chua thi tao> String dir = new File(".").getAbsolutePath();;//DoAnLyThuyet_JavaOutLookApp.getCurdir(); dir += "\\MailAttachs\\" + idMail + "\\"; reDir += idMail + "\\"; File file = new File(dir); if (!file.exists()) { file.mkdirs(); } //</Kiem tra xem thu muc chua da co chua neu chua thi tao> for (Part part : cacPart){ //tao file moi dir += i++ + part.getFileName(); reDir += i + part.getFileName(); file = new File(dir); file.createNewFile(); //FileOutputStream outStream = new FileOutputStream(file); //part.writeTo(outStream); //ghi file InputStream input = part.getInputStream(); FileOutputStream fos = new FileOutputStream(file); BufferedOutputStream bos = new BufferedOutputStream(fos); BufferedInputStream bis = new BufferedInputStream(input); int aByte; while ((aByte = bis.read()) != -1) { bos.write(aByte); } bis.close(); bos.close(); //them duong dan vao Kq Kq.add(new MyAttachDTO(0, idMail, reDir, part.getFileName())); } return Kq; } /** * Luu tru message vao HDD * @param mess * @throws java.io.IOException * @throws javax.mail.MessagingException * @throws java.io.FileNotFoundException * @return file path cua file chua mess */ public static String luuTruMineMessageVaoHDD(MimeMessage mess) throws IOException, MessagingException, FileNotFoundException { //dataPath = String reDir = "\\MailItems\\"; String dir = new File(".").getAbsolutePath();;//DoAnLyThuyet_JavaOutLookApp.getCurdir(); // JOptionPane.showMessageDialog(null, new File(dir).getCanonicalPath()); File file = new File(dir + "\\MailItems\\"); if (!file.exists()) { file.mkdirs(); } reDir += String.valueOf(mess.getSentDate().getTime()) + ".mjm"; dir += reDir; file = new File(dir); file.createNewFile(); FileOutputStream outStream = new FileOutputStream(file); mess.writeTo(outStream); return reDir; //mess = new MimeMessage(mess.gets, is) } private MimeMessage taoMineMessageInputNguoiDung (boolean isToSend) throws Exception{ MyMail myMail = new MyMail(DoAnLyThuyet_JavaOutLookApp.getSmtp_host(), DoAnLyThuyet_JavaOutLookApp.getPop3_host(), DoAnLyThuyet_JavaOutLookApp.getUser() , DoAnLyThuyet_JavaOutLookApp.getPass(), DoAnLyThuyet_JavaOutLookApp.getProxy(), DoAnLyThuyet_JavaOutLookApp.getPort()); Session session = myMail.getMailSession(isToSend); //session. MimeMessage message = new MimeMessage(session); String user = myMail.getUser(); message.setFrom(new InternetAddress(user)); //Them danh sach nguoi nhan--------------------------------------------- String str_ToAdd = getJTextField_to().getText(); InternetAddress toAddress = new InternetAddress(str_ToAdd); message.addRecipient(Message.RecipientType.TO, toAddress); //----------------------------CC--------------------- String sAr_CCAdd[] = getJTextField_cc().getText().split(","); //InternetAddress[] CCAddress = new InternetAddress[sAr_CCAdd.length]; // To get the array of addresses InternetAddress CCAddress = new InternetAddress(); for( int i=0; i < sAr_CCAdd.length; i++ ) { if (!sAr_CCAdd[i].equals("")){ CCAddress = new InternetAddress(sAr_CCAdd[i]); message.addRecipient(Message.RecipientType.CC, CCAddress); } } /* for( int i=0; i < CCAddress.length; i++) { message.addRecipient(Message.RecipientType.CC, CCAddress[i]); } */ //---------------------------BCC--------------------------- String sAr_BCCAdd[] = jTextField_bcc.getText().split(","); //InternetAddress[] BCCAddress = new InternetAddress[sAr_BCCAdd.length]; // To get the array of addresses InternetAddress BCCAddress = new InternetAddress(); //Them danh sach nguoi nhanInternetAddress CCAddress = new InternetAddress(); for( int i=0; i < sAr_BCCAdd.length; i++ ) { if (!sAr_CCAdd[i].equals("")){ BCCAddress = new InternetAddress(sAr_CCAdd[i]); message.addRecipient(Message.RecipientType.CC, BCCAddress); } } /* for( int i=0; i < BCCAddress.length; i++ ) { BCCAddress[i] = new InternetAddress(sAr_BCCAdd[i]); } for( int i=0; i < BCCAddress.length; i++) { message.addRecipient(Message.RecipientType.BCC, BCCAddress[i]); } */ //-------------------------------------------------------------------------- String str_Subject = jTextField_subject.getText(); message.setSubject(str_Subject); String str_ContentType = "text/"; boolean b_IsSendHTML = jCheckBox_SendHTML.isSelected(); str_ContentType += b_IsSendHTML ? "html" : "plain"; String str_Content = jTextArea_noidung.getText(); /* message.setContent(str_Content, str_ContentType); * */ MimeBodyPart noiDungMail = new MimeBodyPart(); noiDungMail.setContent(str_Content, str_ContentType); ListModel model = jList_CacAttach.getModel(); MimeBodyPart cacAttach[] = new MimeBodyPart[model.getSize()]; for (int i = 0; i <model.getSize(); i++){ File file = new File(model.getElementAt(i).toString()); DataSource source = new FileDataSource(file); cacAttach[i] = new MimeBodyPart(); cacAttach[i].setDataHandler(new DataHandler(source)); cacAttach[i].setFileName(file.getName()); } Multipart multiPart = new MimeMultipart(); multiPart.addBodyPart(noiDungMail); for (int i = 0 ; i < cacAttach.length; i++) multiPart.addBodyPart(cacAttach[i]); message.setContent(multiPart); //message.setContent(str_Content, str_ContentType); return message; } /** * Goi mail voi cac input cua nguoi dung */ private MimeMessage GoiMailTuGiaoDienNguoiDung() throws Exception { MimeMessage mess = taoMineMessageInputNguoiDung(true); MyMail myMail = new MyMail(DoAnLyThuyet_JavaOutLookApp.getSmtp_host(), DoAnLyThuyet_JavaOutLookApp.getPop3_host(), DoAnLyThuyet_JavaOutLookApp.getUser() , DoAnLyThuyet_JavaOutLookApp.getPass(), DoAnLyThuyet_JavaOutLookApp.getProxy(), DoAnLyThuyet_JavaOutLookApp.getPort()); mess.setSentDate(new Date()); mess.setContentID(String.valueOf(new Date().getTime())); //luuAttachVaoCSDL(mess); myMail.sendMail(mess); return mess; } public static int luuMailVaoCSDL(MimeMessage mess, String duongDanThuMuc) throws MessagingException, IOException, IOException{ Folder folder = mess.getFolder(); Store store = null; if (folder != null){ store = folder.getStore(); store.connect(); folder.open(Folder.READ_ONLY); } MyMailDTO mailDTO = new MyMailDTO(mess); String duongDanFileChuaNoiDung = luuTruMineMessageVaoHDD(mess); mailDTO.setM_DuongDanFileChuaNoiDung(duongDanFileChuaNoiDung); mailDTO.setM_DuongDanThuMuc(duongDanThuMuc); if (duongDanThuMuc.equals("Mails\\Sent\\")) mailDTO.setM_TinhTrang(JEnum_TinhTrang.DaXem.value()); else mailDTO.setM_TinhTrang(JEnum_TinhTrang.Moi.value()); MyMailBUS mailBUS = new MyMailBUS(); int mailID = mailBUS.themMail(mailDTO); // JOptionPane.showMessageDialog(null, "Luu tru thanh cong mail ID:" + mailID); if (folder != null && store != null){ folder.close(false); store.close(); } return mailID; //mess = new MimeMessage(mess.gets, is) } /** * Dau tien tao danh sach attach tu mess * luu attach vao HDD sau do luu vao csdl * @param mess MimeMessage chua cac attach * @param idMail id cua MyMailDTO (dung de tao dinh danh cho file chua thong tin attach khi luu tren o cung) * @return danh sach cai id cua cac attach moi dc tao ra * @throws javax.mail.MessagingException * @throws java.io.IOException */ public static ArrayList<Integer> luuAttachVaoCSDL(MimeMessage mess, int idMail) throws MessagingException, IOException{ ArrayList<Part> cacAttach = MyMail.layCacAttachCuaMail(mess); ArrayList<MyAttachDTO> cacAttachDTO = luuTruCacPartVaoHDD(cacAttach, idMail); ArrayList<Integer> Kq = new ArrayList<Integer>(); MyAttachBUS attachBUS = new MyAttachBUS(); for (MyAttachDTO attachDTO : cacAttachDTO){ int i = attachBUS.themAttach(attachDTO); Kq.add(i); } return Kq; } private void jButton_SendActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_SendActionPerformed try { ThucHienCacBuocGoiMailTuGiaoDienNguoiDung(); } catch (Exception ex) { Logger.getLogger(JFrame_GuiMail.class.getName()).log(Level.SEVERE, null, ex); JOptionPane.showMessageDialog(null, ex.getMessage()); } }//GEN-LAST:event_jButton_SendActionPerformed private void jButton_ThemAttachActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_ThemAttachActionPerformed // TODO add your handling code here: File cacFileDuocChon[] = moDialogChonFile(true); DefaultListModel model = (DefaultListModel) jList_CacAttach.getModel(); for (File file : cacFileDuocChon){ model.addElement(file.getAbsolutePath()); } jList_CacAttach.setModel(model); }//GEN-LAST:event_jButton_ThemAttachActionPerformed private void jButton_XoaAttachActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_XoaAttachActionPerformed // TODO add your handling code here: DefaultListModel model = (DefaultListModel) jList_CacAttach.getModel(); //model. int soLuongAttachDuocXoa = 0; int cacAttachDuocChon[] = jList_CacAttach.getSelectedIndices(); for (int i : cacAttachDuocChon){ model.remove(i - soLuongAttachDuocXoa++); } jList_CacAttach.setModel(model); jScrollPane_ListAttach.setViewportView(jList_CacAttach); }//GEN-LAST:event_jButton_XoaAttachActionPerformed private void jButton_Send1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_Send1ActionPerformed // TODO add your handling code here: dispose(); }//GEN-LAST:event_jButton_Send1ActionPerformed private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed // TODO add your handling code here: JDialog_ChonContact chonContact = new JDialog_ChonContact(this, true); chonContact.setVisible(true); //frame_Contact.add if (chonContact.getCacEmailDuocChon().length() > 0) jTextField_to.setText(chonContact.getCacEmailDuocChon().split(",")[0]); chonContact.dispose(); }//GEN-LAST:event_jButton1ActionPerformed private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed // TODO add your handling code here: JDialog_ChonContact chonContact = new JDialog_ChonContact(this, true); chonContact.setVisible(true); //frame_Contact.add if (chonContact.getCacEmailDuocChon().length() > 0) jTextField_cc.setText(jTextField_cc.getText() + "," + chonContact.getCacEmailDuocChon()); chonContact.dispose(); }//GEN-LAST:event_jButton2ActionPerformed private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed // TODO add your handling code here: JDialog_ChonContact chonContact = new JDialog_ChonContact(this, true); chonContact.setVisible(true); //frame_Contact.add if (chonContact.getCacEmailDuocChon().length() > 0) jTextField_bcc.setText(jTextField_bcc.getText() + "," + chonContact.getCacEmailDuocChon()); chonContact.dispose(); }//GEN-LAST:event_jButton4ActionPerformed private void jCheckBox_SendHTMLActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBox_SendHTMLActionPerformed // TODO add your handling code here: String html = "<html>\n\t<head>\n\t</head>\n\t<body>\n\t\t" + jTextArea_noidung.getText() + "\n\t</body>\n</html>"; jTextArea_noidung.setText(html); }//GEN-LAST:event_jCheckBox_SendHTMLActionPerformed public static File[] moDialogChonFile(Boolean choPhepChonNhieuFile) { File Kq[] = new File[0]; JFileChooser fileChooser = new JFileChooser(); fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); fileChooser.setMultiSelectionEnabled(choPhepChonNhieuFile); int ketQuaShowOpenDialog = fileChooser.showOpenDialog(null); if (ketQuaShowOpenDialog == JFileChooser.APPROVE_OPTION){ //fileChooser.getf Kq = new File[fileChooser.getSelectedFiles().length]; Kq = fileChooser.getSelectedFiles(); } return Kq; } /** * @param args the command line arguments */ public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new JFrame_GuiMail().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JButton jButton4; private javax.swing.JButton jButton_Send; private javax.swing.JButton jButton_Send1; private javax.swing.JButton jButton_ThemAttach; private javax.swing.JButton jButton_XoaAttach; private javax.swing.JButton jButton_addressbook; private javax.swing.JButton jButton_send2; private javax.swing.JCheckBox jCheckBox_SendHTML; private javax.swing.JLabel jLabel1; private javax.swing.JList jList_CacAttach; private javax.swing.JMenuItem jMenuItem1; private javax.swing.JMenuItem jMenuItem2; private javax.swing.JMenuItem jMenuItem3; private javax.swing.JMenuItem jMenuItem_Contact; private javax.swing.JMenuItem jMenuItem_Copy; private javax.swing.JMenuItem jMenuItem_Cut; private javax.swing.JMenuItem jMenuItem_Find; private javax.swing.JMenuItem jMenuItem_Folder; private javax.swing.JMenuItem jMenuItem_Mail; private javax.swing.JMenuItem jMenuItem_Paste; private javax.swing.JMenuItem jMenuItem_Save; private javax.swing.JMenuItem jMenuItem_SaveAs; private javax.swing.JMenuItem jMenuItem_SelectAll; private javax.swing.JMenuItem jMenuItem_Task; private javax.swing.JMenuItem jMenuItem_delete; private javax.swing.JMenu jMenu_Edit; private javax.swing.JMenu jMenu_New; private javax.swing.JMenu jMenu_Tools; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JPanel jPanel4; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane_ListAttach; private javax.swing.JSeparator jSeparator1; private javax.swing.JSeparator jSeparator2; private javax.swing.JSeparator jSeparator3; private javax.swing.JSeparator jSeparator4; private javax.swing.JSeparator jSeparator5; private javax.swing.JTextArea jTextArea_noidung; private javax.swing.JTextField jTextField_bcc; private javax.swing.JTextField jTextField_cc; private javax.swing.JTextField jTextField_subject; private javax.swing.JTextField jTextField_to; private javax.swing.JToolBar jToolBar1; private javax.swing.JToolBar jToolBar2; private javax.swing.JMenuBar menuBar; // End of variables declaration//GEN-END:variables /** * @return the jTextField_cc */ public javax.swing.JTextField getJTextField_cc() { return jTextField_cc; } /** * @param jTextField_cc the jTextField_cc to set */ public void setJTextField_cc(javax.swing.JTextField jTextField_cc) { this.jTextField_cc = jTextField_cc; } /** * @return the jTextField_to */ public javax.swing.JTextField getJTextField_to() { return jTextField_to; } /** * @param jTextField_to the jTextField_to to set */ public void setJTextField_to(javax.swing.JTextField jTextField_to) { this.jTextField_to = jTextField_to; } //private JList jList_Attach = new JList(new DefaultListModel()); }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * JPanel_BusCard.java * * Created on Jun 21, 2009, 9:55:56 AM */ package doanlythuyet_javaoutlook.MyUserControl; import BUS.MyContactBUS; import DTO.MyContactDTO; import java.io.IOException; import java.sql.SQLException; /** * * @author Administrator */ public class JPanel_BusCard extends javax.swing.JPanel { /** Creates new form JPanel_BusCard */ public JPanel_BusCard() { initComponents(); } public void HienThiThongTin(int i) throws SQLException, IOException { MyContactDTO contactDTO = new MyContactBUS().layTatCaContactBangID(i); jLabel_Email.setText(contactDTO.getM_Email()); jLabel_Ten.setText(contactDTO.getM_Ten()); jLabel_CongTy.setText(contactDTO.getM_CongTy()); jLabel_DienThoai.setText(contactDTO.getM_DienThoai()); jLabel_DiaChi.setText(contactDTO.getM_DiaChi()); jLabel_CongTy1.setText(contactDTO.getM_NickName()); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel_CongTy = new javax.swing.JLabel(); jLabel_Email = new javax.swing.JLabel(); jLabel_DienThoai = new javax.swing.JLabel(); jLabel_DiaChi = new javax.swing.JLabel(); jLabel_Ten = new javax.swing.JLabel(); jPanel_Nick = new javax.swing.JPanel(); jLabel_CongTy1 = new javax.swing.JLabel(); org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(doanlythuyet_javaoutlook.DoAnLyThuyet_JavaOutLookApp.class).getContext().getResourceMap(JPanel_BusCard.class); setBackground(resourceMap.getColor("Form.background")); // NOI18N setBorder(new javax.swing.border.LineBorder(resourceMap.getColor("Form.border.lineColor"), 3, true)); // NOI18N setMaximumSize(new java.awt.Dimension(200, 150)); setName("Form"); // NOI18N setPreferredSize(new java.awt.Dimension(200, 150)); jLabel_CongTy.setText(resourceMap.getString("jLabel_CongTy.text")); // NOI18N jLabel_CongTy.setName("jLabel_CongTy"); // NOI18N jLabel_Email.setText(resourceMap.getString("jLabel_Email.text")); // NOI18N jLabel_Email.setName("jLabel_Email"); // NOI18N jLabel_DienThoai.setText(resourceMap.getString("jLabel_DienThoai.text")); // NOI18N jLabel_DienThoai.setName("jLabel_DienThoai"); // NOI18N jLabel_DiaChi.setText(resourceMap.getString("jLabel_DiaChi.text")); // NOI18N jLabel_DiaChi.setName("jLabel_DiaChi"); // NOI18N jLabel_Ten.setFont(resourceMap.getFont("jLabel_Ten.font")); // NOI18N jLabel_Ten.setText(resourceMap.getString("jLabel_Ten.text")); // NOI18N jLabel_Ten.setName("jLabel_Ten"); // NOI18N jPanel_Nick.setBackground(resourceMap.getColor("jPanel_Nick.background")); // NOI18N jPanel_Nick.setName("jPanel_Nick"); // NOI18N jLabel_CongTy1.setText(resourceMap.getString("jLabel_CongTy1.text")); // NOI18N jLabel_CongTy1.setName("jLabel_CongTy1"); // NOI18N javax.swing.GroupLayout jPanel_NickLayout = new javax.swing.GroupLayout(jPanel_Nick); jPanel_Nick.setLayout(jPanel_NickLayout); jPanel_NickLayout.setHorizontalGroup( jPanel_NickLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel_NickLayout.createSequentialGroup() .addComponent(jLabel_CongTy1, javax.swing.GroupLayout.DEFAULT_SIZE, 41, Short.MAX_VALUE) .addGap(184, 184, 184)) ); jPanel_NickLayout.setVerticalGroup( jPanel_NickLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel_CongTy1) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jLabel_CongTy, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel_Ten)) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jLabel_Email, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel_DienThoai, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel_DiaChi))) .addContainerGap(174, Short.MAX_VALUE)) .addComponent(jPanel_Nick, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jPanel_Nick, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel_Ten) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel_CongTy) .addGap(26, 26, 26) .addComponent(jLabel_DienThoai) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel_Email) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel_DiaChi) .addContainerGap()) ); }// </editor-fold>//GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel jLabel_CongTy; private javax.swing.JLabel jLabel_CongTy1; private javax.swing.JLabel jLabel_DiaChi; private javax.swing.JLabel jLabel_DienThoai; private javax.swing.JLabel jLabel_Email; private javax.swing.JLabel jLabel_Ten; private javax.swing.JPanel jPanel_Nick; // End of variables declaration//GEN-END:variables }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * JDialog_ChonContact.java * * Created on Jun 21, 2009, 2:51:35 PM */ package doanlythuyet_javaoutlook.MyUserControl; import java.util.ArrayList; /** * * @author Administrator */ public class JDialog_ChonContact extends javax.swing.JDialog { private String cacEmailDuocChon; /** Creates new form JDialog_ChonContact */ public JDialog_ChonContact(java.awt.Frame parent, boolean modal) { super(parent, modal); initComponents(); jTable_HienThiContact1.refreshBang(); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jScrollPane1 = new javax.swing.JScrollPane(); jTable_HienThiContact1 = new doanlythuyet_javaoutlook.MyUserControl.jTable_HienThiContact(); jButton1 = new javax.swing.JButton(); jButton2 = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setName("Form"); // NOI18N jScrollPane1.setName("jScrollPane1"); // NOI18N jTable_HienThiContact1.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null} }, new String [] { "Title 1", "Title 2", "Title 3", "Title 4" } )); jTable_HienThiContact1.setName("jTable_HienThiContact1"); // NOI18N jScrollPane1.setViewportView(jTable_HienThiContact1); org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(doanlythuyet_javaoutlook.DoAnLyThuyet_JavaOutLookApp.class).getContext().getResourceMap(JDialog_ChonContact.class); jButton1.setText(resourceMap.getString("jButton1.text")); // NOI18N jButton1.setName("jButton1"); // NOI18N jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jButton2.setText(resourceMap.getString("jButton2.text")); // NOI18N jButton2.setName("jButton2"); // NOI18N jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(jButton1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton2)) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 733, Short.MAX_VALUE))) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 231, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton2) .addComponent(jButton1)) .addGap(40, 40, 40)) ); pack(); }// </editor-fold>//GEN-END:initComponents public ArrayList<String> LayCacEMailDuocChon (){ ArrayList<String> Kq = new ArrayList<String>(); for (int i = 0; i < jTable_HienThiContact1.getRowCount(); i++) if (jTable_HienThiContact1.getValueAt(i, 0) != null && (Boolean)jTable_HienThiContact1.getValueAt(i, 0) && jTable_HienThiContact1.getValueAt(i, 3) != null) Kq.add(jTable_HienThiContact1.getValueAt(i, 3).toString()); return Kq; } private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed // TODO add your handling code here: ArrayList<String> cacEmail = LayCacEMailDuocChon(); cacEmailDuocChon = ""; for (int i = 0; i < cacEmail.size(); i++){ cacEmailDuocChon += cacEmail.get(i) + ","; } setVisible(false); }//GEN-LAST:event_jButton1ActionPerformed private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed // TODO add your handling code here: setVisible(false); }//GEN-LAST:event_jButton2ActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { JDialog_ChonContact dialog = new JDialog_ChonContact(new javax.swing.JFrame(), true); dialog.addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent e) { System.exit(0); } }); dialog.setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JScrollPane jScrollPane1; private doanlythuyet_javaoutlook.MyUserControl.jTable_HienThiContact jTable_HienThiContact1; // End of variables declaration//GEN-END:variables /** * @return the cacEmailDuocChon */ public String getCacEmailDuocChon() { return cacEmailDuocChon; } /** * @param cacEmailDuocChon the cacEmailDuocChon to set */ public void setCacEmailDuocChon(String cacEmailDuocChon) { this.cacEmailDuocChon = cacEmailDuocChon; } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * JPanel_BusCard.java * * Created on Jun 21, 2009, 9:55:56 AM */ package doanlythuyet_javaoutlook.MyUserControl; import BUS.MyContactBUS; import DTO.MyContactDTO; import java.io.IOException; import java.sql.SQLException; /** * * @author Administrator */ public class JPanel_AddCard extends javax.swing.JPanel { /** Creates new form JPanel_BusCard */ public JPanel_AddCard() { initComponents(); } public void HienThiThongTin(int i) throws SQLException, IOException { MyContactDTO contactDTO = new MyContactBUS().layTatCaContactBangID(i); jLabel_Email.setText(contactDTO.getM_Email()); jLabel_DienThoai.setText(contactDTO.getM_DiaChi()); jLabel_CongTy1.setText(contactDTO.getM_NickName()); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel_Email = new javax.swing.JLabel(); jLabel_DienThoai = new javax.swing.JLabel(); jPanel_Nick = new javax.swing.JPanel(); jLabel_CongTy1 = new javax.swing.JLabel(); org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(doanlythuyet_javaoutlook.DoAnLyThuyet_JavaOutLookApp.class).getContext().getResourceMap(JPanel_AddCard.class); setBackground(resourceMap.getColor("Form.background")); // NOI18N setBorder(new javax.swing.border.LineBorder(resourceMap.getColor("Form.border.lineColor"), 3, true)); // NOI18N setMaximumSize(new java.awt.Dimension(200, 75)); setName("Form"); // NOI18N setPreferredSize(new java.awt.Dimension(200, 75)); jLabel_Email.setText(resourceMap.getString("jLabel_Email.text")); // NOI18N jLabel_Email.setName("jLabel_Email"); // NOI18N jLabel_DienThoai.setText(resourceMap.getString("jLabel_DienThoai.text")); // NOI18N jLabel_DienThoai.setName("jLabel_DienThoai"); // NOI18N jPanel_Nick.setBackground(resourceMap.getColor("jPanel_Nick.background")); // NOI18N jPanel_Nick.setName("jPanel_Nick"); // NOI18N jLabel_CongTy1.setText(resourceMap.getString("jLabel_CongTy1.text")); // NOI18N jLabel_CongTy1.setName("jLabel_CongTy1"); // NOI18N javax.swing.GroupLayout jPanel_NickLayout = new javax.swing.GroupLayout(jPanel_Nick); jPanel_Nick.setLayout(jPanel_NickLayout); jPanel_NickLayout.setHorizontalGroup( jPanel_NickLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel_NickLayout.createSequentialGroup() .addComponent(jLabel_CongTy1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGap(184, 184, 184)) ); jPanel_NickLayout.setVerticalGroup( jPanel_NickLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel_CongTy1) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel_Nick, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jLabel_Email, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel_DienThoai)) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jPanel_Nick, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel_DienThoai) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel_Email)) ); }// </editor-fold>//GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel jLabel_CongTy1; private javax.swing.JLabel jLabel_DienThoai; private javax.swing.JLabel jLabel_Email; private javax.swing.JPanel jPanel_Nick; // End of variables declaration//GEN-END:variables }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * JFrame_TimMail.java * * Created on May 28, 2009, 8:22:00 AM */ package doanlythuyet_javaoutlook.MyUserControl; /** * * @author Dang Thi Phuong Thao */ public class JFrame_TimMail extends javax.swing.JFrame { /** Creates new form JFrame_TimMail */ public JFrame_TimMail() { initComponents(); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); jComboBox_noichua = new javax.swing.JComboBox(); jLabel2 = new javax.swing.JLabel(); jComboBox_tieuchi = new javax.swing.JComboBox(); jScrollPane1 = new javax.swing.JScrollPane(); jTable_danhsachmail = new javax.swing.JTable(); jScrollPane2 = new javax.swing.JScrollPane(); jTextArea_noidung = new javax.swing.JTextArea(); jRadioButton_giongtatca = new javax.swing.JRadioButton(); jRadioButton_giongvaitu = new javax.swing.JRadioButton(); jButton_tim = new javax.swing.JButton(); jButton_xoaketqua = new javax.swing.JButton(); jButton_Mo = new javax.swing.JButton(); jButton_xoa = new javax.swing.JButton(); jButton_luu = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setName("Form"); // NOI18N org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(doanlythuyet_javaoutlook.DoAnLyThuyet_JavaOutLookApp.class).getContext().getResourceMap(JFrame_TimMail.class); jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N jLabel1.setName("jLabel1"); // NOI18N jComboBox_noichua.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Inbox", "Deleted" })); jComboBox_noichua.setName("jComboBox_noichua"); // NOI18N jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N jLabel2.setName("jLabel2"); // NOI18N jComboBox_tieuchi.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Chủ đề", "Người gởi", "Ngày", "Mức độ", "Tình trạng", " " })); jComboBox_tieuchi.setName("jComboBox_tieuchi"); // NOI18N jScrollPane1.setName("jScrollPane1"); // NOI18N jTable_danhsachmail.setBackground(resourceMap.getColor("jTable_danhsachmail.background")); // NOI18N jTable_danhsachmail.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED)); jTable_danhsachmail.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null, null}, {null, null, null, null, null}, {null, null, null, null, null}, {null, null, null, null, null} }, new String [] { "Chủ đề", "Người gởi", "Ngày", "Mức độ", "Thư mục chứa" } ) { Class[] types = new Class [] { java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class }; public Class getColumnClass(int columnIndex) { return types [columnIndex]; } }); jTable_danhsachmail.setName("jTable_danhsachmail"); // NOI18N jScrollPane1.setViewportView(jTable_danhsachmail); jScrollPane2.setName("jScrollPane2"); // NOI18N jTextArea_noidung.setColumns(20); jTextArea_noidung.setRows(5); jTextArea_noidung.setName("jTextArea_noidung"); // NOI18N jScrollPane2.setViewportView(jTextArea_noidung); jRadioButton_giongtatca.setText(resourceMap.getString("jRadioButton_giongtatca.text")); // NOI18N jRadioButton_giongtatca.setName("jRadioButton_giongtatca"); // NOI18N jRadioButton_giongvaitu.setText(resourceMap.getString("jRadioButton_giongvaitu.text")); // NOI18N jRadioButton_giongvaitu.setName("jRadioButton_giongvaitu"); // NOI18N jButton_tim.setText(resourceMap.getString("jButton_tim.text")); // NOI18N jButton_tim.setName("jButton_tim"); // NOI18N jButton_xoaketqua.setText(resourceMap.getString("jButton_xoaketqua.text")); // NOI18N jButton_xoaketqua.setName("jButton_xoaketqua"); // NOI18N jButton_Mo.setText(resourceMap.getString("jButton_Mo.text")); // NOI18N jButton_Mo.setName("jButton_Mo"); // NOI18N jButton_xoa.setText(resourceMap.getString("jButton_xoa.text")); // NOI18N jButton_xoa.setName("jButton_xoa"); // NOI18N jButton_luu.setText(resourceMap.getString("jButton_luu.text")); // NOI18N jButton_luu.setName("jButton_luu"); // NOI18N javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 619, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup() .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jComboBox_noichua, 0, 249, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup() .addComponent(jRadioButton_giongtatca) .addGap(63, 63, 63) .addComponent(jRadioButton_giongvaitu) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jButton_tim) .addComponent(jLabel2)) .addGap(5, 5, 5) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jButton_xoaketqua) .addComponent(jComboBox_tieuchi, javax.swing.GroupLayout.PREFERRED_SIZE, 192, javax.swing.GroupLayout.PREFERRED_SIZE))) .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 619, Short.MAX_VALUE)) .addGap(31, 31, 31)) .addGroup(layout.createSequentialGroup() .addGap(112, 112, 112) .addComponent(jButton_Mo) .addGap(66, 66, 66) .addComponent(jButton_xoa) .addGap(55, 55, 55) .addComponent(jButton_luu) .addContainerGap(277, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jComboBox_tieuchi, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jComboBox_noichua, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel2)) .addGap(17, 17, 17) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jRadioButton_giongtatca) .addComponent(jRadioButton_giongvaitu) .addComponent(jButton_tim) .addComponent(jButton_xoaketqua)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 107, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton_Mo) .addComponent(jButton_luu) .addComponent(jButton_xoa)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents /** * @param args the command line arguments */ public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new JFrame_TimMail().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton_Mo; private javax.swing.JButton jButton_luu; private javax.swing.JButton jButton_tim; private javax.swing.JButton jButton_xoa; private javax.swing.JButton jButton_xoaketqua; private javax.swing.JComboBox jComboBox_noichua; private javax.swing.JComboBox jComboBox_tieuchi; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JRadioButton jRadioButton_giongtatca; private javax.swing.JRadioButton jRadioButton_giongvaitu; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JTable jTable_danhsachmail; private javax.swing.JTextArea jTextArea_noidung; // End of variables declaration//GEN-END:variables }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * JFrame_CauHinhProxy.java * * Created on 18-06-2009, 10:04:02 */ package doanlythuyet_javaoutlook.MyUserControl; import java.io.File; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import javax.xml.parsers.*; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.*; import org.xml.sax.SAXException; /** * * @author ShineShiao */ public class JFrame_CauHinhProxy extends javax.swing.JFrame { private String smtp_host; private String pop3_host; private String user ; private String pass; private String proxy ; private String port ; /** Creates new form JFrame_CauHinhProxy */ public JFrame_CauHinhProxy() { initComponents(); String dataPath = new File(".").getAbsolutePath(); String strFileName = dataPath + "\\Database\\XML_Proxy.xml"; //String strFileName = "G:\\New Folder\\DoAnLyThuyet_JavaOutLook\\src\\Database\\XML_Proxy.xml"; try { LayProxytuXML(strFileName); } catch (SAXException ex) { Logger.getLogger(JFrame_CauHinhProxy.class.getName()).log(Level.SEVERE, null, ex); } catch (ParserConfigurationException ex) { Logger.getLogger(JFrame_CauHinhProxy.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(JFrame_CauHinhProxy.class.getName()).log(Level.SEVERE, null, ex); } } /** * @return the smtp_host */ public String getSmtp_host() { return smtp_host; } /** * @param aSmtp_host the smtp_host to set */ public void setSmtp_host(String aSmtp_host) { smtp_host = aSmtp_host; } /** * @return the pop3_host */ public String getPop3_host() { return pop3_host; } /** * @param aPop3_host the pop3_host to set */ public void setPop3_host(String aPop3_host) { pop3_host = aPop3_host; } /** * @return the user */ public String getUser() { return user; } /** * @param aUser the user to set */ public void setUser(String aUser) { user = aUser; } /** * @return the pass */ public String getPass() { return pass; } /** * @param aPass the pass to set */ public void setPass(String aPass) { pass = aPass; } /** * @return the proxy */ public String getProxy() { return proxy; } /** * @param aProxy the proxy to set */ public void setProxy(String aProxy) { proxy = aProxy; } /** * @return the port */ public String getPort() { return port; } /** * @param aPort the port to set */ public void setPort(String aPort) { port = aPort; } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); jTextField_smtphost = new javax.swing.JTextField(); jLabel2 = new javax.swing.JLabel(); jTextField_pop3host = new javax.swing.JTextField(); jLabel3 = new javax.swing.JLabel(); jTextField_username = new javax.swing.JTextField(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jTextField_Proxy = new javax.swing.JTextField(); jLabel6 = new javax.swing.JLabel(); jTextField_Port = new javax.swing.JTextField(); jPanel2 = new javax.swing.JPanel(); jPanel1 = new javax.swing.JPanel(); jSeparator1 = new javax.swing.JSeparator(); jSeparator2 = new javax.swing.JSeparator(); jButton1 = new javax.swing.JButton(); jButton2 = new javax.swing.JButton(); jLabel7 = new javax.swing.JLabel(); jTextField_password = new javax.swing.JPasswordField(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setName("Form"); // NOI18N org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(doanlythuyet_javaoutlook.DoAnLyThuyet_JavaOutLookApp.class).getContext().getResourceMap(JFrame_CauHinhProxy.class); jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N jLabel1.setName("jLabel1"); // NOI18N jTextField_smtphost.setText(resourceMap.getString("jTextField_smtphost.text")); // NOI18N jTextField_smtphost.setName("jTextField_smtphost"); // NOI18N jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N jLabel2.setName("jLabel2"); // NOI18N jTextField_pop3host.setText(resourceMap.getString("jTextField_pop3host.text")); // NOI18N jTextField_pop3host.setName("jTextField_pop3host"); // NOI18N jLabel3.setText(resourceMap.getString("jLabel3.text")); // NOI18N jLabel3.setName("jLabel3"); // NOI18N jTextField_username.setText(resourceMap.getString("jTextField_username.text")); // NOI18N jTextField_username.setName("jTextField_username"); // NOI18N jLabel4.setText(resourceMap.getString("jLabel4.text")); // NOI18N jLabel4.setName("jLabel4"); // NOI18N jLabel5.setText(resourceMap.getString("jLabel5.text")); // NOI18N jLabel5.setName("jLabel5"); // NOI18N jTextField_Proxy.setText(resourceMap.getString("jTextField_Proxy.text")); // NOI18N jTextField_Proxy.setName("jTextField_Proxy"); // NOI18N jLabel6.setText(resourceMap.getString("jLabel6.text")); // NOI18N jLabel6.setName("jLabel6"); // NOI18N jTextField_Port.setText(resourceMap.getString("jTextField_Port.text")); // NOI18N jTextField_Port.setName("jTextField_Port"); // NOI18N jPanel2.setName("jPanel2"); // NOI18N jPanel2.setLayout(new java.awt.BorderLayout()); jPanel1.setName("jPanel1"); // NOI18N jPanel1.setLayout(new java.awt.CardLayout()); jSeparator1.setName("jSeparator1"); // NOI18N jSeparator2.setName("jSeparator2"); // NOI18N jButton1.setText(resourceMap.getString("jButton1.text")); // NOI18N jButton1.setName("jButton1"); // NOI18N jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jButton2.setText(resourceMap.getString("jButton2.text")); // NOI18N jButton2.setName("jButton2"); // NOI18N jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); jLabel7.setFont(resourceMap.getFont("jLabel7.font")); // NOI18N jLabel7.setText(resourceMap.getString("jLabel7.text")); // NOI18N jLabel7.setName("jLabel7"); // NOI18N jTextField_password.setText(resourceMap.getString("jTextField_password.text")); // NOI18N jTextField_password.setName("jTextField_password"); // NOI18N javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(21, 21, 21) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(jLabel5) .addGap(18, 18, 18) .addComponent(jTextField_Proxy, javax.swing.GroupLayout.PREFERRED_SIZE, 260, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(layout.createSequentialGroup() .addComponent(jLabel2) .addGap(18, 18, 18) .addComponent(jTextField_pop3host, javax.swing.GroupLayout.PREFERRED_SIZE, 260, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addComponent(jLabel1) .addGap(18, 18, 18) .addComponent(jTextField_smtphost, javax.swing.GroupLayout.PREFERRED_SIZE, 260, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel4) .addComponent(jLabel3)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jTextField_password) .addComponent(jTextField_username, javax.swing.GroupLayout.DEFAULT_SIZE, 260, Short.MAX_VALUE))))) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(jLabel6) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField_Port, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 260, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addContainerGap()) .addComponent(jSeparator1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 381, Short.MAX_VALUE) .addComponent(jSeparator2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 381, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addGap(76, 76, 76) .addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 212, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(93, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(129, 129, 129) .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 19, Short.MAX_VALUE) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(172, 172, 172) .addComponent(jButton2) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(27, 27, 27) .addComponent(jLabel7) .addGap(30, 30, 30) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextField_smtphost, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel1)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextField_pop3host, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel2)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextField_username, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel3)) .addGap(31, 31, 31) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextField_password, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel4)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(7, 7, 7) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextField_Proxy, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel5)) .addGap(21, 21, 21) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextField_Port, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel6)) .addGap(30, 30, 30) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton2) .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(63, 63, 63) .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents /** * xu ly button OK cua? giao dien * @param evt */ private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed // TODO add your handling code here: smtp_host = jTextField_smtphost.getText(); pop3_host = jTextField_pop3host.getText(); user = jTextField_username.getText(); pass = jTextField_password.getText(); proxy = jTextField_Proxy.getText(); port = jTextField_Port.getText(); String dataPath = new File(".").getAbsolutePath(); String strFileName = dataPath + "\\Database\\XML_Proxy.xml"; try { LuuVaoXML(strFileName); } catch (ParserConfigurationException ex) { Logger.getLogger(JFrame_CauHinhProxy.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(JFrame_CauHinhProxy.class.getName()).log(Level.SEVERE, null, ex); } catch (SAXException ex) { Logger.getLogger(JFrame_CauHinhProxy.class.getName()).log(Level.SEVERE, null, ex); } catch (TransformerConfigurationException ex) { Logger.getLogger(JFrame_CauHinhProxy.class.getName()).log(Level.SEVERE, null, ex); } catch (TransformerException ex) { Logger.getLogger(JFrame_CauHinhProxy.class.getName()).log(Level.SEVERE, null, ex); } this.dispose(); }//GEN-LAST:event_jButton1ActionPerformed private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed // TODO add your handling code here: this.dispose(); }//GEN-LAST:event_jButton2ActionPerformed /** * @param args the command line arguments */ /** * * @param strFileName :duong dan XML can lay Config * @throws org.xml.sax.SAXException * @throws javax.xml.parsers.ParserConfigurationException * @throws java.io.IOException */ public void LayProxytuXML(String strFileName) throws SAXException, ParserConfigurationException, IOException{ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder; builder = factory.newDocumentBuilder(); Document doc = builder.parse(new File(strFileName)); Element root = (Element) doc.getDocumentElement(); NodeList nodelist = root.getElementsByTagName("Config"); Element Ele = (Element)nodelist.item(0); NamedNodeMap attributes = Ele.getAttributes(); for(int i=0;i<attributes.getLength();++i) { Node attributeNode = attributes.item(i); String name = attributeNode.getNodeName(); String value = attributeNode.getNodeValue(); if (name.equals("smptport")) jTextField_smtphost.setText(value); if(name.equals("pop3host")) jTextField_pop3host.setText(value); if(name.equals("user")) jTextField_username.setText(value); if(name.equals("pass")) jTextField_password.setText(value); if(name.equals("proxy")) jTextField_Proxy.setText(value); if(name.equals("port")) jTextField_Port.setText(value); } } /** * @param strFileName :duong dan file xml * @throws javax.xml.parsers.ParserConfigurationException * @throws java.io.IOException * @throws org.xml.sax.SAXException * @throws javax.xml.transform.TransformerConfigurationException * @throws javax.xml.transform.TransformerException */ public void LuuVaoXML(String strFileName) throws ParserConfigurationException, IOException, SAXException, TransformerConfigurationException, TransformerException{ //doc file xml DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(new File(strFileName)); Element root = (Element) doc.getDocumentElement(); NodeList nodelist = root.getElementsByTagName("Config"); Element Config =(Element) nodelist.item(0); Config.setAttribute("smtphost", smtp_host); Config.setAttribute("pop3host", pop3_host); Config.setAttribute("user", user); Config.setAttribute("pass", pass); Config.setAttribute("proxy", proxy); Config.setAttribute("port", port); Transformer xformer = TransformerFactory.newInstance().newTransformer(); xformer.transform (new DOMSource(doc), new StreamResult(new File(strFileName))); } public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new JFrame_CauHinhProxy().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JSeparator jSeparator1; private javax.swing.JSeparator jSeparator2; private javax.swing.JTextField jTextField_Port; private javax.swing.JTextField jTextField_Proxy; private javax.swing.JPasswordField jTextField_password; private javax.swing.JTextField jTextField_pop3host; private javax.swing.JTextField jTextField_smtphost; private javax.swing.JTextField jTextField_username; // End of variables declaration//GEN-END:variables }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package doanlythuyet_javaoutlook.MyUserControl; import BUS.MyMailBUS; import doanlythuyet_javaoutlook.DoAnLyThuyet_JavaOutLookView; import doanlythuyet_javaoutlook.EventListener_ClickChuotVaoCayDuyetFile; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPopupMenu; import javax.xml.parsers.ParserConfigurationException; import org.xml.sax.SAXException; /** * * @author Administrator */ public class PopupMenu_MouseListerner_MyBangDanhSachFile implements MouseListener{ private String m_HanhViDuocChon; //public String m_ThuMucDangChon; public PopupMenu_MouseListerner_MyBangDanhSachFile(String hanhVi){ m_HanhViDuocChon = hanhVi; } public void mouseClicked(MouseEvent e) { //throw new UnsupportedOperationException("Not supported yet."); } public void mousePressed(MouseEvent e) { //throw new UnsupportedOperationException("Not supported yet."); //JOptionPane.showMessageDialog(null, "Hanh vi duoc chon: " + m_HanhViDuocChon + "xu ly code tai dong 530 file JPanel_XemMail.java"); String MailID = ((JPopupMenu) ((JMenuItem)e.getSource()).getParent()).getToolTipText(); MyMailBUS mailBUS = new MyMailBUS(); if (m_HanhViDuocChon.equals("Di Chuyen")){ try { JDialog_ChonThuMucDich dialog_ChonThuMucDich = new JDialog_ChonThuMucDich(null, true); dialog_ChonThuMucDich.setVisible(true); String thuMucDich = dialog_ChonThuMucDich.getM_ThuMucDuocChon(); dialog_ChonThuMucDich.dispose(); if (thuMucDich.equals("")) return; int soMailCapNhat = mailBUS.thayDoiDuongDanThuMuc(MailID, thuMucDich); JOptionPane.showMessageDialog(null, "Da cap nhat " + soMailCapNhat + "mail"); dialog_ChonThuMucDich.dispose(); } catch (IOException ex) { Logger.getLogger(PopupMenu_MouseListerner_MyBangDanhSachFile.class.getName()).log(Level.SEVERE, null, ex); } } else if(m_HanhViDuocChon.equals("Xoa")){ try { int soMailCapNhat = mailBUS.xoaMail(MailID); JOptionPane.showMessageDialog(null, "Da cap nhat " + soMailCapNhat + "mail"); } catch (IOException ex) { Logger.getLogger(PopupMenu_MouseListerner_MyBangDanhSachFile.class.getName()).log(Level.SEVERE, null, ex); } } initEvent_ClickChuotVaoCayDuyetFile(m_HanhViDuocChon); } public void mouseReleased(MouseEvent e) { //throw new UnsupportedOperationException("Not supported yet."); } public void mouseEntered(MouseEvent e) { //throw new UnsupportedOperationException("Not supported yet."); } public void mouseExited(MouseEvent e) { //throw new UnsupportedOperationException("Not supported yet."); } //<editor-fold defaultstate="collapsed" desc="Dung de phat sinh su kien"> //Các hàm sau phục vụ cho việc gởi sự kiện click chuột vào bảng ra ngoài (tham khảo từ nhiều nguồn trên mạng) //http://www.exampledepot.com/egs/java.util/CustEvent.html // Tạo một listener list protected javax.swing.event.EventListenerList listenerList = new javax.swing.event.EventListenerList(); /** * Phát sinh sử kiện click chuột vào tree * @param evt tham số cho sự kiện click chuột vào tree (ở đây là tên của file đang được chọn) */ // This private class is used to fire MyEvents void initEvent_ClickChuotVaoCayDuyetFile(String evt) { Object[] listeners = listenerList.getListenerList(); // Each listener occupies two elements - the first is the listener class // and the second is the listener instance for (int i = 0; i < listeners.length; i += 2) { if (listeners[i] == EventListener_ClickChuotVaoCayDuyetFile.class) { ((EventListener_ClickChuotVaoCayDuyetFile) listeners[i + 1]).Event_ClickChuotVaoCayDuyetFile_Occurred(evt); } } } /** * Đăng ký sự kiện cho classes * @param listener Sự kiện cần đăng ký */ public void addEventListener_ClickChuotVaoCayDuyetFile(EventListener_ClickChuotVaoCayDuyetFile listener) { listenerList.add(EventListener_ClickChuotVaoCayDuyetFile.class, listener); } /** * Gỡ bỏ sự kiện khỏi classes * @param listener Sự kiện cần gỡ bỏ */ public void delEventListener_ClickChuotVaoCayDuyetFile(EventListener_ClickChuotVaoCayDuyetFile listener) { listenerList.remove(EventListener_ClickChuotVaoCayDuyetFile.class, listener); } //</editor-fold> }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * JDialog_ChonThuMucDich.java * * Created on Jun 16, 2009, 1:57:53 AM */ package doanlythuyet_javaoutlook.MyUserControl; import doanlythuyet_javaoutlook.DoAnLyThuyet_JavaOutLookApp; import doanlythuyet_javaoutlook.EventListener_ClickChuotVaoCayDuyetFile; import java.io.File; import javax.swing.JOptionPane; /** * * @author Administrator */ public class JDialog_ChonThuMucDich extends javax.swing.JDialog { private String m_ThuMucDuocChon = ""; private JTreeFromXMLFile jTree_ThuMucMail; private JTreeFromXMLFile jTree_ThuMucNguoiDung; /** Creates new form JDialog_ChonThuMucDich */ public JDialog_ChonThuMucDich(java.awt.Frame parent, boolean modal) { super(parent, modal); initComponents(); initMyComponent(); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jButton_DongY = new javax.swing.JButton(); jPanel1 = new javax.swing.JPanel(); jScrollPane_ThuMucMail = new javax.swing.JScrollPane(); jScrollPane_ThuMucNguoiDung = new javax.swing.JScrollPane(); jLabel_DangChon = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setName("Form"); // NOI18N org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(doanlythuyet_javaoutlook.DoAnLyThuyet_JavaOutLookApp.class).getContext().getResourceMap(JDialog_ChonThuMucDich.class); jButton_DongY.setText(resourceMap.getString("jButton_DongY.text")); // NOI18N jButton_DongY.setName("jButton_DongY"); // NOI18N jButton_DongY.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton_DongYActionPerformed(evt); } }); jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(resourceMap.getString("jPanel1.border.title"))); // NOI18N jPanel1.setName("jPanel1"); // NOI18N jScrollPane_ThuMucMail.setName("jScrollPane_ThuMucMail"); // NOI18N jScrollPane_ThuMucNguoiDung.setName("jScrollPane_ThuMucNguoiDung"); // NOI18N javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jScrollPane_ThuMucMail, javax.swing.GroupLayout.PREFERRED_SIZE, 237, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane_ThuMucNguoiDung, javax.swing.GroupLayout.PREFERRED_SIZE, 237, javax.swing.GroupLayout.PREFERRED_SIZE)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane_ThuMucNguoiDung, javax.swing.GroupLayout.DEFAULT_SIZE, 242, Short.MAX_VALUE) .addComponent(jScrollPane_ThuMucMail, javax.swing.GroupLayout.DEFAULT_SIZE, 242, Short.MAX_VALUE)) .addContainerGap()) ); jLabel_DangChon.setText(resourceMap.getString("jLabel_DangChon.text")); // NOI18N jLabel_DangChon.setName("jLabel_DangChon"); // NOI18N javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel_DangChon) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 414, Short.MAX_VALUE) .addComponent(jButton_DongY))) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton_DongY) .addComponent(jLabel_DangChon)) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents public void initMyComponent (){ String dataPath = DoAnLyThuyet_JavaOutLookApp.getCurdir() + "\\src"; dataPath = new File(".").getAbsolutePath(); String fileName = "\\Database\\XML_ThuMucMail.xml"; //fileName = jTree_ThuMucMail = new JTreeFromXMLFile(dataPath + fileName, false); jScrollPane_ThuMucMail.setViewportView(jTree_ThuMucMail); jTree_ThuMucMail.addEventListener_ClickChuotVaoCayDuyetFile(new EventListener_ClickChuotVaoCayDuyetFile() { public void Event_ClickChuotVaoCayDuyetFile_Occurred(String str_fileduocchon) { jLabel_DangChon.setText(str_fileduocchon); } }); //String dataPath = DoAnLyThuyet_JavaOutLookApp.getCurdir() + "\\src\\Database\\"; fileName = "\\Database\\XML_ThuMucNguoiDung.xml"; jTree_ThuMucNguoiDung = new JTreeFromXMLFile(dataPath + fileName, false); jScrollPane_ThuMucNguoiDung.setViewportView(jTree_ThuMucNguoiDung); jTree_ThuMucNguoiDung.addEventListener_ClickChuotVaoCayDuyetFile(new EventListener_ClickChuotVaoCayDuyetFile() { public void Event_ClickChuotVaoCayDuyetFile_Occurred(String str_fileduocchon) { jLabel_DangChon.setText(str_fileduocchon); } }); //jTree_ThuMucMail.addEventListener_ClickChuotVaoCayDuyetFile(new EventListener_ClickChuotVaoCayDuyetFile() { //JTreeFromXMLFile tree = new JTreeFromXMLFile(xmlFilePath) } private void jButton_DongYActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_DongYActionPerformed // TODO add your handling code here: m_ThuMucDuocChon = jLabel_DangChon.getText(); if (m_ThuMucDuocChon.equals("")){ JOptionPane.showMessageDialog(null, "Xin chọn thư mục!"); return; } //this.getParent() setVisible(false); }//GEN-LAST:event_jButton_DongYActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { JDialog_ChonThuMucDich dialog = new JDialog_ChonThuMucDich(new javax.swing.JFrame(), true); dialog.addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent e) { System.exit(0); } }); dialog.setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton_DongY; private javax.swing.JLabel jLabel_DangChon; private javax.swing.JPanel jPanel1; private javax.swing.JScrollPane jScrollPane_ThuMucMail; private javax.swing.JScrollPane jScrollPane_ThuMucNguoiDung; // End of variables declaration//GEN-END:variables /** * @return the m_ThuMucDuocChon */ public String getM_ThuMucDuocChon() { return m_ThuMucDuocChon; } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package doanlythuyet_javaoutlook.MyUserControl; import BUS.MyContactBUS; import DTO.MyContactDTO; import doanlythuyet_javaoutlook.EventListener_ClickChuotVaoCayDuyetFile; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.io.IOException; import java.sql.SQLException; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.AbstractButton; import javax.swing.JTable; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableColumn; import javax.swing.table.TableModel; /** * * @author Administrator */ public class jTable_HienThiContact extends JTable { public jTable_HienThiContact(){ //File file = moDialogChonAnh(); setAutoCreateRowSorter(true); } //<editor-fold defaultstate="collapsed" desc="Dung de phat sinh su kien"> //Các hàm sau phục vụ cho việc gởi sự kiện click chuột vào bảng ra ngoài (tham khảo từ nhiều nguồn trên mạng) //http://www.exampledepot.com/egs/java.util/CustEvent.html // Tạo một listener list protected javax.swing.event.EventListenerList listenerList = new javax.swing.event.EventListenerList(); /** * Phát sinh sử kiện click chuột vào tree * @param evt tham số cho sự kiện click chuột vào tree (ở đây là tên của file đang được chọn) */ // This private class is used to fire MyEvents void initEvent_ClickChuotVaoCayDuyetFile(String evt) { Object[] listeners = listenerList.getListenerList(); // Each listener occupies two elements - the first is the listener class // and the second is the listener instance for (int i = 0; i < listeners.length; i += 2) { if (listeners[i] == EventListener_ClickChuotVaoCayDuyetFile.class) { ((EventListener_ClickChuotVaoCayDuyetFile) listeners[i + 1]).Event_ClickChuotVaoCayDuyetFile_Occurred(evt); } } } /** * Đăng ký sự kiện cho classes * @param listener Sự kiện cần đăng ký */ public void addEventListener_ClickChuotVaoCayDuyetFile(EventListener_ClickChuotVaoCayDuyetFile listener) { listenerList.add(EventListener_ClickChuotVaoCayDuyetFile.class, listener); } /** * Gỡ bỏ sự kiện khỏi classes * @param listener Sự kiện cần gỡ bỏ */ public void delEventListener_ClickChuotVaoCayDuyetFile(EventListener_ClickChuotVaoCayDuyetFile listener) { listenerList.remove(EventListener_ClickChuotVaoCayDuyetFile.class, listener); } //</editor-fold> public void DuaDanhSachMailVaoBang(ArrayList<MyContactDTO>DanhSachMail) throws IOException, SQLException{ final String cacCotDuLieu[] = {"Tất cả","Họ tên","Nickname","Email","Địa chỉ", "Cơ quan", "Điện thoại", "ID"}; Object DuLieu[][] = new Object[DanhSachMail.size()][cacCotDuLieu.length]; for(int i = 0; i < DanhSachMail.size();i++){ int index = 0; DuLieu[i][index++] = false; //for(int j = 1; i < model.) dulieu[index] = new Object(); DuLieu[i][index++] = DanhSachMail.get(i).getM_Ten(); DuLieu[i][index++] = DanhSachMail.get(i).getM_NickName(); DuLieu[i][index++] = DanhSachMail.get(i).getM_Email(); DuLieu[i][index++] = DanhSachMail.get(i).getM_DiaChi(); DuLieu[i][index++] = DanhSachMail.get(i).getM_CongTy(); DuLieu[i][index++] = DanhSachMail.get(i).getM_DienThoai(); DuLieu[i][index++] = DanhSachMail.get(i).getM_Id(); } final Object bangDuLieu[][] = DuLieu; DefaultTableModel modelBangHienThi = new DefaultTableModel(bangDuLieu,cacCotDuLieu) { @Override public Class getColumnClass(int columnIndex) { switch (columnIndex){ case 0: return Boolean.class; default: return String.class; } } @Override public int getColumnCount() { return cacCotDuLieu.length; } @Override public String getColumnName(int column) { return cacCotDuLieu[column]; } @Override public int getRowCount() { return bangDuLieu.length; } @Override public Object getValueAt(int row, int column) { return bangDuLieu[row][column]; } @Override public void setValueAt(Object value, int row, int column) { bangDuLieu[row][column] = value; } @Override public boolean isCellEditable(int row, int column) { return column == 0; } }; addMouseListener(new MouseListener() { public void mouseClicked(MouseEvent e) { //throw new UnsupportedOperationException("Not supported yet."); if (getSelectedRow() != -1){ initEvent_ClickChuotVaoCayDuyetFile(getValueAt(getSelectedRow(), getColumnCount() - 1).toString()); } } public void mousePressed(MouseEvent e) { //throw new UnsupportedOperationException("Not supported yet."); } public void mouseReleased(MouseEvent e) { //throw new UnsupportedOperationException("Not supported yet."); } public void mouseEntered(MouseEvent e) { //throw new UnsupportedOperationException("Not supported yet."); } public void mouseExited(MouseEvent e) { //throw new UnsupportedOperationException("Not supported yet."); } }); this.setModel(modelBangHienThi); //jTable_danhsachmail = new TableSelectionTest(cacCotDuLieu, bangDuLieu); TableColumn tc = this.getColumnModel().getColumn(0); tc.setCellEditor(this.getDefaultEditor(Boolean.class)); tc.setCellRenderer(this.getDefaultRenderer(Boolean.class)); tc.setHeaderRenderer(new CheckBoxHeader(new MyItemListener())); // <editor-fold defaultstate="collapsed" desc="Cai dat giao dien cho bang"> //jTable_danhsachmail.setSize(500, 100); this.getColumnModel().getColumn(0).setMaxWidth(25); this.getColumnModel().getColumn(this.getColumnCount() - 1).setMinWidth(0); this.getColumnModel().getColumn(this.getColumnCount() - 1).setMaxWidth(0); this.getColumnModel().getColumn(this.getColumnCount() - 1).setPreferredWidth(0); //jTable_danhsachmail. // </ediort-fold> } private void DoiTrangThaiCotCheckBox (boolean isDuocChon){ TableModel tableModel = this.getModel(); for (int i = 0; i < tableModel.getRowCount(); i++){ tableModel.setValueAt(isDuocChon, i, 0); } } public void refreshBang() { //thanh:refresh giao dien de? cap nhat try { MyContactBUS attachBUS = new MyContactBUS(); ArrayList<MyContactDTO> cacContactDTO = attachBUS.layTatCaContact(); DuaDanhSachMailVaoBang(cacContactDTO); } catch (SQLException ex) { Logger.getLogger(JPanel_XemMail.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(JPanel_XemMail.class.getName()).log(Level.SEVERE, null, ex); } } class MyItemListener implements ItemListener{ public void itemStateChanged(ItemEvent e) { Object source = e.getSource(); if (source instanceof AbstractButton == false) return; boolean checked = e.getStateChange() == ItemEvent.SELECTED; DoiTrangThaiCotCheckBox(checked); } } }
Java
/* * DoAnLyThuyet_JavaOutLookView.java */ package doanlythuyet_javaoutlook; import BUS.MyMailBUS; import DTO.MyMailDTO; import doanlythuyet_javaoutlook.MyUserControl.JFrame_CauHinhProxy; import doanlythuyet_javaoutlook.MyUserControl.JFrame_Contact; import doanlythuyet_javaoutlook.MyUserControl.JPanel_XemMail; import java.io.IOException; import java.sql.SQLException; import java.util.logging.Level; import java.util.logging.Logger; import org.jdesktop.application.Action; import org.jdesktop.application.ResourceMap; import org.jdesktop.application.SingleFrameApplication; import org.jdesktop.application.FrameView; import org.jdesktop.application.TaskMonitor; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.Timer; import javax.swing.Icon; import javax.swing.JDialog; import javax.swing.JFrame; import doanlythuyet_javaoutlook.MyUserControl.JFrame_GuiMail; import doanlythuyet_javaoutlook.MyUserControl.JTreeFromXMLFile; import doanlythuyet_javaoutlook.MyUserControl.PopupMenu_MouseListerner_MyBangDanhSachFile; import java.io.File; import java.util.ArrayList; import java.util.Hashtable; import javax.mail.Message; import javax.mail.Session; import javax.mail.internet.MimeMessage; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.MutableTreeNode; import javax.swing.tree.TreePath; import org.xml.sax.SAXException; /** * The application's main frame. */ public class DoAnLyThuyet_JavaOutLookView extends FrameView { /** * @return the jTree_ThuMucTrenMay */ public static JTreeFromXMLFile getJTree_ThuMucTrenMay() { return jTree_ThuMucTrenMay; } /** * @param aJTree_ThuMucTrenMay the jTree_ThuMucTrenMay to set */ public static void setJTree_ThuMucTrenMay(JTreeFromXMLFile aJTree_ThuMucTrenMay) { jTree_ThuMucTrenMay = aJTree_ThuMucTrenMay; } //private CayDuyetFile cayDuyetFile; private String thuMucDuocChon = ""; private JPanel_XemMail jPanel_XemMail = new JPanel_XemMail(); private JTreeFromXMLFile jTree_ThuMucMail; private static JTreeFromXMLFile jTree_ThuMucTrenMay; private void jXuLy_KhiNguoiDungDoiThuMucDuyetMail(String str_fileduocchon) { try { //throw new UnsupportedOperationException("Not supported yet."); //JOptionPane.showMessageDialog(null, "hien thi cac mail trong thu muc: " + str_fileduocchon + " (file DoAnLyThuyet_JavaOutLookView.java dong 54)"); MyMailBUS mailBUS = new MyMailBUS(); Hashtable<String, String> cacDieuKien = new Hashtable<String, String>(); cacDieuKien.put("DuongDanThuMuc", str_fileduocchon); ArrayList<MyMailDTO> cacMailDTO = mailBUS.layTatCaMailVoiDieuKien(str_fileduocchon, cacDieuKien); jScrollPane_Giua.setViewportView(jPanel_XemMail); jSplitPane_GiuaPhai.setDividerLocation(800); jPanel_XemMail.DuaDanhSachMailVaoBang(cacMailDTO); jPanel_XemMail.setToolTipText(thuMucDuocChon); } catch (SQLException ex) { Logger.getLogger(DoAnLyThuyet_JavaOutLookView.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(DoAnLyThuyet_JavaOutLookView.class.getName()).log(Level.SEVERE, null, ex); } } private void initMailsComponents(){ String dataPath = DoAnLyThuyet_JavaOutLookApp.getCurdir() + "\\src"; dataPath = new File(".").getAbsolutePath(); String fileName = "\\Database\\XML_ThuMucMail.xml"; jTree_ThuMucMail = new JTreeFromXMLFile(dataPath + fileName, true); jScrollPane_ThuMucMail.setViewportView(jTree_ThuMucMail); jTree_ThuMucMail.addEventListener_ClickChuotVaoCayDuyetFile(new EventListener_ClickChuotVaoCayDuyetFile() { public void Event_ClickChuotVaoCayDuyetFile_Occurred(String str_fileduocchon) { thuMucDuocChon = str_fileduocchon; jXuLy_KhiNguoiDungDoiThuMucDuyetMail(thuMucDuocChon); } }); fileName = "\\Database\\XML_ThuMucNguoiDung.xml"; setJTree_ThuMucTrenMay(new JTreeFromXMLFile(dataPath + fileName, false)); jScrollPane_ThuMucTrenMay.setViewportView(getJTree_ThuMucTrenMay()); getJTree_ThuMucTrenMay().addEventListener_ClickChuotVaoCayDuyetFile(new EventListener_ClickChuotVaoCayDuyetFile() { public void Event_ClickChuotVaoCayDuyetFile_Occurred(String str_fileduocchon) { thuMucDuocChon = str_fileduocchon; jXuLy_KhiNguoiDungDoiThuMucDuyetMail(thuMucDuocChon); } }); JMenuItem menuItem = (JMenuItem) jPanel_XemMail.getPopupMenu().getComponent(0); PopupMenu_MouseListerner_MyBangDanhSachFile mouseListerner = (PopupMenu_MouseListerner_MyBangDanhSachFile) menuItem.getMouseListeners()[1]; mouseListerner.addEventListener_ClickChuotVaoCayDuyetFile(new EventListener_ClickChuotVaoCayDuyetFile() { public void Event_ClickChuotVaoCayDuyetFile_Occurred(String str_fileduocchon) { //throw new UnsupportedOperationException("Not supported yet."); jXuLy_KhiNguoiDungDoiThuMucDuyetMail(thuMucDuocChon); } }); } public DoAnLyThuyet_JavaOutLookView(SingleFrameApplication app) throws SAXException { super(app); String dataPath = new File(".").getAbsolutePath(); String strFileName = dataPath + "\\Database\\XML_Proxy.xml"; DoAnLyThuyet_JavaOutLookApp.LayProxytuXML(strFileName); initComponents(); initMailsComponents(); // status bar initialization - message timeout, idle icon and busy animation, etc ResourceMap resourceMap = getResourceMap(); int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout"); messageTimer = new Timer(messageTimeout, new ActionListener() { public void actionPerformed(ActionEvent e) { statusMessageLabel.setText(""); } }); messageTimer.setRepeats(false); int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate"); for (int i = 0; i < busyIcons.length; i++) { busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]"); } busyIconTimer = new Timer(busyAnimationRate, new ActionListener() { public void actionPerformed(ActionEvent e) { busyIconIndex = (busyIconIndex + 1) % busyIcons.length; statusAnimationLabel.setIcon(busyIcons[busyIconIndex]); } }); idleIcon = resourceMap.getIcon("StatusBar.idleIcon"); statusAnimationLabel.setIcon(idleIcon); progressBar.setVisible(false); // connecting action tasks to status bar via TaskMonitor TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext()); taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener() { public void propertyChange(java.beans.PropertyChangeEvent evt) { String propertyName = evt.getPropertyName(); if ("started".equals(propertyName)) { if (!busyIconTimer.isRunning()) { statusAnimationLabel.setIcon(busyIcons[0]); busyIconIndex = 0; busyIconTimer.start(); } progressBar.setVisible(true); progressBar.setIndeterminate(true); } else if ("done".equals(propertyName)) { busyIconTimer.stop(); statusAnimationLabel.setIcon(idleIcon); progressBar.setVisible(false); progressBar.setValue(0); } else if ("message".equals(propertyName)) { String text = (String)(evt.getNewValue()); statusMessageLabel.setText((text == null) ? "" : text); messageTimer.restart(); } else if ("progress".equals(propertyName)) { int value = (Integer)(evt.getNewValue()); progressBar.setVisible(true); progressBar.setIndeterminate(false); progressBar.setValue(value); } } }); /* cayDuyetFile= new CayDuyetFile(jScrollPane_ThuMucMail); cayDuyetFile.addEventListener_ClickChuotVaoCayDuyetFile(new EventListener_ClickChuotVaoCayDuyetFile() { public void Event_ClickChuotVaoCayDuyetFile_Occurred(String str_fileduocchon) { //JOptionPane.showMessageDialog(null, str_fileduocchon); } });*/ //jXuLy_KhiNguoiDungDoiThuMucDuyetMail("Mails\\Inbox\\"); } @Action public void showAboutBox() { if (aboutBox == null) { JFrame mainFrame = DoAnLyThuyet_JavaOutLookApp.getApplication().getMainFrame(); aboutBox = new DoAnLyThuyet_JavaOutLookAboutBox(mainFrame); aboutBox.setLocationRelativeTo(mainFrame); } DoAnLyThuyet_JavaOutLookApp.getApplication().show(aboutBox); //initMyComponents(); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { mainPanel = new javax.swing.JPanel(); jPanel_Tren = new javax.swing.JPanel(); jToolBar2 = new javax.swing.JToolBar(); jButton_Tool_GetMail = new javax.swing.JButton(); jButton_NewMail = new javax.swing.JButton(); jButton_Find = new javax.swing.JButton(); jSplitPane_TraiVaGiua = new javax.swing.JSplitPane(); jSplitPane_GiuaPhai = new javax.swing.JSplitPane(); jPanel_BenPhai = new javax.swing.JPanel(); jScrollPane1 = new javax.swing.JScrollPane(); jEditorPane1 = new javax.swing.JEditorPane(); jScrollPane_Giua = new javax.swing.JScrollPane(); jLabel1 = new javax.swing.JLabel(); jPanel_BenTrai = new javax.swing.JPanel(); jToolBar1 = new javax.swing.JToolBar(); jButton_Contact = new javax.swing.JButton(); jButton1 = new javax.swing.JButton(); jSplitPane_ThuMuc = new javax.swing.JSplitPane(); jScrollPane_ThuMucMail = new javax.swing.JScrollPane(); jScrollPane_ThuMucTrenMay = new javax.swing.JScrollPane(); menuBar = new javax.swing.JMenuBar(); javax.swing.JMenu fileMenu = new javax.swing.JMenu(); jMenu_New = new javax.swing.JMenu(); jMenuItem_Mail = new javax.swing.JMenuItem(); jMenuItem_Contact = new javax.swing.JMenuItem(); jMenuItem_Task = new javax.swing.JMenuItem(); jMenuItem_Folder = new javax.swing.JMenuItem(); jMenu_Open = new javax.swing.JMenu(); jMenuItem_SelectItems = new javax.swing.JMenuItem(); jSeparator1 = new javax.swing.JSeparator(); jMenu_Folder = new javax.swing.JMenu(); jMenuItem_NewFolder = new javax.swing.JMenuItem(); jMenuItem_CopyFolder = new javax.swing.JMenuItem(); jMenuItem_DeleteFolder = new javax.swing.JMenuItem(); jMenuItem_RenameFolder = new javax.swing.JMenuItem(); jSeparator2 = new javax.swing.JSeparator(); javax.swing.JMenuItem exitMenuItem = new javax.swing.JMenuItem(); jMenu_Edit = new javax.swing.JMenu(); jMenuItem_Cut = new javax.swing.JMenuItem(); jMenuItem_Copy = new javax.swing.JMenuItem(); jMenuItem_Paste = new javax.swing.JMenuItem(); jSeparator3 = new javax.swing.JSeparator(); jMenuItem_SelectAll = new javax.swing.JMenuItem(); jSeparator4 = new javax.swing.JSeparator(); jMenuItem1 = new javax.swing.JMenuItem(); jMenu_Tools = new javax.swing.JMenu(); jMenuItem_Receive = new javax.swing.JMenuItem(); jMenuItem_Find = new javax.swing.JMenuItem(); jMenuItem_Addressbook = new javax.swing.JMenuItem(); javax.swing.JMenu helpMenu = new javax.swing.JMenu(); javax.swing.JMenuItem aboutMenuItem = new javax.swing.JMenuItem(); statusPanel = new javax.swing.JPanel(); javax.swing.JSeparator statusPanelSeparator = new javax.swing.JSeparator(); statusMessageLabel = new javax.swing.JLabel(); statusAnimationLabel = new javax.swing.JLabel(); progressBar = new javax.swing.JProgressBar(); mainPanel.setName("mainPanel"); // NOI18N mainPanel.setLayout(new java.awt.BorderLayout()); jPanel_Tren.setName("jPanel_Tren"); // NOI18N jToolBar2.setRollover(true); jToolBar2.setName("jToolBar2"); // NOI18N org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(doanlythuyet_javaoutlook.DoAnLyThuyet_JavaOutLookApp.class).getContext().getResourceMap(DoAnLyThuyet_JavaOutLookView.class); jButton_Tool_GetMail.setIcon(resourceMap.getIcon("jButton_Tool_GetMail.icon")); // NOI18N jButton_Tool_GetMail.setText(resourceMap.getString("jButton_Tool_GetMail.text")); // NOI18N jButton_Tool_GetMail.setFocusable(false); jButton_Tool_GetMail.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); jButton_Tool_GetMail.setName("jButton_Tool_GetMail"); // NOI18N jButton_Tool_GetMail.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); jButton_Tool_GetMail.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton_Tool_GetMailActionPerformed(evt); } }); jToolBar2.add(jButton_Tool_GetMail); jButton_NewMail.setIcon(resourceMap.getIcon("jButton_NewMail.icon")); // NOI18N jButton_NewMail.setText(resourceMap.getString("jButton_NewMail.text")); // NOI18N jButton_NewMail.setFocusable(false); jButton_NewMail.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); jButton_NewMail.setName("jButton_NewMail"); // NOI18N jButton_NewMail.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); jButton_NewMail.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton_NewMailActionPerformed(evt); } }); jToolBar2.add(jButton_NewMail); jButton_Find.setIcon(resourceMap.getIcon("jButton_Find.icon")); // NOI18N jButton_Find.setText(resourceMap.getString("jButton_Find.text")); // NOI18N jButton_Find.setFocusable(false); jButton_Find.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); jButton_Find.setName("jButton_Find"); // NOI18N jButton_Find.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); jButton_Find.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton_FindActionPerformed(evt); } }); jToolBar2.add(jButton_Find); javax.swing.GroupLayout jPanel_TrenLayout = new javax.swing.GroupLayout(jPanel_Tren); jPanel_Tren.setLayout(jPanel_TrenLayout); jPanel_TrenLayout.setHorizontalGroup( jPanel_TrenLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel_TrenLayout.createSequentialGroup() .addComponent(jToolBar2, javax.swing.GroupLayout.PREFERRED_SIZE, 655, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(189, Short.MAX_VALUE)) ); jPanel_TrenLayout.setVerticalGroup( jPanel_TrenLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel_TrenLayout.createSequentialGroup() .addContainerGap(41, Short.MAX_VALUE) .addComponent(jToolBar2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) ); mainPanel.add(jPanel_Tren, java.awt.BorderLayout.PAGE_START); jSplitPane_TraiVaGiua.setDividerLocation(200); jSplitPane_TraiVaGiua.setName("jSplitPane_TraiVaGiua"); // NOI18N jSplitPane_GiuaPhai.setDividerLocation(400); jSplitPane_GiuaPhai.setName("jSplitPane_GiuaPhai"); // NOI18N jPanel_BenPhai.setName("jPanel_BenPhai"); // NOI18N jScrollPane1.setName("jScrollPane1"); // NOI18N jEditorPane1.setContentType(resourceMap.getString("jEditorPane1.contentType")); // NOI18N jEditorPane1.setText(resourceMap.getString("jEditorPane1.text")); // NOI18N jEditorPane1.setName("jEditorPane1"); // NOI18N jScrollPane1.setViewportView(jEditorPane1); javax.swing.GroupLayout jPanel_BenPhaiLayout = new javax.swing.GroupLayout(jPanel_BenPhai); jPanel_BenPhai.setLayout(jPanel_BenPhaiLayout); jPanel_BenPhaiLayout.setHorizontalGroup( jPanel_BenPhaiLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 232, Short.MAX_VALUE) ); jPanel_BenPhaiLayout.setVerticalGroup( jPanel_BenPhaiLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 408, Short.MAX_VALUE) ); jSplitPane_GiuaPhai.setRightComponent(jPanel_BenPhai); jScrollPane_Giua.setName("jScrollPane_Giua"); // NOI18N jLabel1.setFont(resourceMap.getFont("jLabel1.font")); // NOI18N jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N jLabel1.setName("jLabel1"); // NOI18N jScrollPane_Giua.setViewportView(jLabel1); jSplitPane_GiuaPhai.setLeftComponent(jScrollPane_Giua); jSplitPane_TraiVaGiua.setRightComponent(jSplitPane_GiuaPhai); jPanel_BenTrai.setName("jPanel_BenTrai"); // NOI18N jToolBar1.setRollover(true); jToolBar1.setName("jToolBar1"); // NOI18N jButton_Contact.setIcon(resourceMap.getIcon("jButton_Contact.icon")); // NOI18N jButton_Contact.setText(resourceMap.getString("jButton_Contact.text")); // NOI18N jButton_Contact.setFocusable(false); jButton_Contact.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); jButton_Contact.setName("jButton_Contact"); // NOI18N jButton_Contact.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); jButton_Contact.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton_ContactActionPerformed(evt); } }); jToolBar1.add(jButton_Contact); jButton1.setIcon(resourceMap.getIcon("jButton1.icon")); // NOI18N jButton1.setText(resourceMap.getString("jButton1.text")); // NOI18N jButton1.setFocusable(false); jButton1.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); jButton1.setName("jButton1"); // NOI18N jButton1.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jToolBar1.add(jButton1); jSplitPane_ThuMuc.setDividerLocation(150); jSplitPane_ThuMuc.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT); jSplitPane_ThuMuc.setName("jSplitPane_ThuMuc"); // NOI18N jScrollPane_ThuMucMail.setName("jScrollPane_ThuMucMail"); // NOI18N jSplitPane_ThuMuc.setTopComponent(jScrollPane_ThuMucMail); jScrollPane_ThuMucTrenMay.setName("jScrollPane_ThuMucTrenMay"); // NOI18N jSplitPane_ThuMuc.setRightComponent(jScrollPane_ThuMucTrenMay); javax.swing.GroupLayout jPanel_BenTraiLayout = new javax.swing.GroupLayout(jPanel_BenTrai); jPanel_BenTrai.setLayout(jPanel_BenTraiLayout); jPanel_BenTraiLayout.setHorizontalGroup( jPanel_BenTraiLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jToolBar1, javax.swing.GroupLayout.DEFAULT_SIZE, 199, Short.MAX_VALUE) .addComponent(jSplitPane_ThuMuc, javax.swing.GroupLayout.DEFAULT_SIZE, 199, Short.MAX_VALUE) ); jPanel_BenTraiLayout.setVerticalGroup( jPanel_BenTraiLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel_BenTraiLayout.createSequentialGroup() .addComponent(jSplitPane_ThuMuc, javax.swing.GroupLayout.DEFAULT_SIZE, 356, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 48, javax.swing.GroupLayout.PREFERRED_SIZE)) ); jSplitPane_TraiVaGiua.setLeftComponent(jPanel_BenTrai); mainPanel.add(jSplitPane_TraiVaGiua, java.awt.BorderLayout.CENTER); menuBar.setName("menuBar"); // NOI18N fileMenu.setText(resourceMap.getString("fileMenu.text")); // NOI18N fileMenu.setName("fileMenu"); // NOI18N jMenu_New.setText(resourceMap.getString("jMenu_New.text")); // NOI18N jMenu_New.setName("jMenu_New"); // NOI18N jMenuItem_Mail.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_N, java.awt.event.InputEvent.CTRL_MASK)); jMenuItem_Mail.setText(resourceMap.getString("jMenuItem_Mail.text")); // NOI18N jMenuItem_Mail.setName("jMenuItem_Mail"); // NOI18N jMenu_New.add(jMenuItem_Mail); jMenuItem_Contact.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_C, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK)); jMenuItem_Contact.setText(resourceMap.getString("jMenuItem_Contact.text")); // NOI18N jMenuItem_Contact.setName("jMenuItem_Contact"); // NOI18N jMenu_New.add(jMenuItem_Contact); jMenuItem_Task.setText(resourceMap.getString("jMenuItem_Task.text")); // NOI18N jMenuItem_Task.setName("jMenuItem_Task"); // NOI18N jMenu_New.add(jMenuItem_Task); jMenuItem_Folder.setText(resourceMap.getString("jMenuItem_Folder.text")); // NOI18N jMenuItem_Folder.setName("jMenuItem_Folder"); // NOI18N jMenu_New.add(jMenuItem_Folder); fileMenu.add(jMenu_New); jMenu_Open.setText(resourceMap.getString("jMenu_Open.text")); // NOI18N jMenu_Open.setName("jMenu_Open"); // NOI18N jMenuItem_SelectItems.setText(resourceMap.getString("jMenuItem_SelectItems.text")); // NOI18N jMenuItem_SelectItems.setName("jMenuItem_SelectItems"); // NOI18N jMenu_Open.add(jMenuItem_SelectItems); fileMenu.add(jMenu_Open); jSeparator1.setName("jSeparator1"); // NOI18N fileMenu.add(jSeparator1); jMenu_Folder.setText(resourceMap.getString("jMenu_Folder.text")); // NOI18N jMenu_Folder.setName("jMenu_Folder"); // NOI18N jMenuItem_NewFolder.setText(resourceMap.getString("jMenuItem_NewFolder.text")); // NOI18N jMenuItem_NewFolder.setName("jMenuItem_NewFolder"); // NOI18N jMenu_Folder.add(jMenuItem_NewFolder); jMenuItem_CopyFolder.setText(resourceMap.getString("jMenuItem_CopyFolder.text")); // NOI18N jMenuItem_CopyFolder.setName("jMenuItem_CopyFolder"); // NOI18N jMenu_Folder.add(jMenuItem_CopyFolder); jMenuItem_DeleteFolder.setText(resourceMap.getString("jMenuItem_DeleteFolder.text")); // NOI18N jMenuItem_DeleteFolder.setName("jMenuItem_DeleteFolder"); // NOI18N jMenu_Folder.add(jMenuItem_DeleteFolder); jMenuItem_RenameFolder.setText(resourceMap.getString("jMenuItem_RenameFolder.text")); // NOI18N jMenuItem_RenameFolder.setName("jMenuItem_RenameFolder"); // NOI18N jMenu_Folder.add(jMenuItem_RenameFolder); fileMenu.add(jMenu_Folder); jSeparator2.setName("jSeparator2"); // NOI18N fileMenu.add(jSeparator2); javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(doanlythuyet_javaoutlook.DoAnLyThuyet_JavaOutLookApp.class).getContext().getActionMap(DoAnLyThuyet_JavaOutLookView.class, this); exitMenuItem.setAction(actionMap.get("quit")); // NOI18N exitMenuItem.setName("exitMenuItem"); // NOI18N fileMenu.add(exitMenuItem); menuBar.add(fileMenu); jMenu_Edit.setText(resourceMap.getString("jMenu_Edit.text")); // NOI18N jMenu_Edit.setName("jMenu_Edit"); // NOI18N jMenuItem_Cut.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_X, java.awt.event.InputEvent.CTRL_MASK)); jMenuItem_Cut.setText(resourceMap.getString("jMenuItem_Cut.text")); // NOI18N jMenuItem_Cut.setName("jMenuItem_Cut"); // NOI18N jMenu_Edit.add(jMenuItem_Cut); jMenuItem_Copy.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_C, java.awt.event.InputEvent.CTRL_MASK)); jMenuItem_Copy.setText(resourceMap.getString("jMenuItem_Copy.text")); // NOI18N jMenuItem_Copy.setName("jMenuItem_Copy"); // NOI18N jMenu_Edit.add(jMenuItem_Copy); jMenuItem_Paste.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_V, java.awt.event.InputEvent.CTRL_MASK)); jMenuItem_Paste.setText(resourceMap.getString("jMenuItem_Paste.text")); // NOI18N jMenuItem_Paste.setName("jMenuItem_Paste"); // NOI18N jMenu_Edit.add(jMenuItem_Paste); jSeparator3.setName("jSeparator3"); // NOI18N jMenu_Edit.add(jSeparator3); jMenuItem_SelectAll.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_A, java.awt.event.InputEvent.CTRL_MASK)); jMenuItem_SelectAll.setText(resourceMap.getString("jMenuItem_SelectAll.text")); // NOI18N jMenuItem_SelectAll.setName("jMenuItem_SelectAll"); // NOI18N jMenu_Edit.add(jMenuItem_SelectAll); jSeparator4.setName("jSeparator4"); // NOI18N jMenu_Edit.add(jSeparator4); jMenuItem1.setText(resourceMap.getString("jMenuItem1.text")); // NOI18N jMenuItem1.setName("jMenuItem1"); // NOI18N jMenu_Edit.add(jMenuItem1); menuBar.add(jMenu_Edit); jMenu_Tools.setText(resourceMap.getString("jMenu_Tools.text")); // NOI18N jMenu_Tools.setName("jMenu_Tools"); // NOI18N jMenuItem_Receive.setText(resourceMap.getString("jMenuItem_Receive.text")); // NOI18N jMenuItem_Receive.setName("jMenuItem_Receive"); // NOI18N jMenu_Tools.add(jMenuItem_Receive); jMenuItem_Find.setText(resourceMap.getString("jMenuItem_Find.text")); // NOI18N jMenuItem_Find.setName("jMenuItem_Find"); // NOI18N jMenu_Tools.add(jMenuItem_Find); jMenuItem_Addressbook.setText(resourceMap.getString("jMenuItem_Addressbook.text")); // NOI18N jMenuItem_Addressbook.setName("jMenuItem_Addressbook"); // NOI18N jMenu_Tools.add(jMenuItem_Addressbook); menuBar.add(jMenu_Tools); helpMenu.setText(resourceMap.getString("helpMenu.text")); // NOI18N helpMenu.setName("helpMenu"); // NOI18N aboutMenuItem.setAction(actionMap.get("showAboutBox")); // NOI18N aboutMenuItem.setName("aboutMenuItem"); // NOI18N helpMenu.add(aboutMenuItem); menuBar.add(helpMenu); statusPanel.setName("statusPanel"); // NOI18N statusPanelSeparator.setName("statusPanelSeparator"); // NOI18N statusMessageLabel.setName("statusMessageLabel"); // NOI18N statusAnimationLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT); statusAnimationLabel.setName("statusAnimationLabel"); // NOI18N progressBar.setName("progressBar"); // NOI18N javax.swing.GroupLayout statusPanelLayout = new javax.swing.GroupLayout(statusPanel); statusPanel.setLayout(statusPanelLayout); statusPanelLayout.setHorizontalGroup( statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(statusPanelSeparator, javax.swing.GroupLayout.DEFAULT_SIZE, 844, Short.MAX_VALUE) .addGroup(statusPanelLayout.createSequentialGroup() .addContainerGap() .addComponent(statusMessageLabel) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 674, Short.MAX_VALUE) .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(statusAnimationLabel) .addContainerGap()) ); statusPanelLayout.setVerticalGroup( statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(statusPanelLayout.createSequentialGroup() .addComponent(statusPanelSeparator, javax.swing.GroupLayout.PREFERRED_SIZE, 2, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(statusMessageLabel) .addComponent(statusAnimationLabel) .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(3, 3, 3)) ); setComponent(mainPanel); setMenuBar(menuBar); setStatusBar(statusPanel); }// </editor-fold>//GEN-END:initComponents private void jButton_ContactActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_ContactActionPerformed try { // TODO add your handling code here: JFrame_Contact contact = new JFrame_Contact(); contact.setVisible(true); } catch (IOException ex) { Logger.getLogger(DoAnLyThuyet_JavaOutLookView.class.getName()).log(Level.SEVERE, null, ex); } catch (SQLException ex) { Logger.getLogger(DoAnLyThuyet_JavaOutLookView.class.getName()).log(Level.SEVERE, null, ex); } }//GEN-LAST:event_jButton_ContactActionPerformed /** * lay cac mail moi * @return * @throws java.lang.Exception */ private int thucHienLayMailMoi () throws Exception{ int Kq = 0; MyMail myMail = new MyMail(DoAnLyThuyet_JavaOutLookApp.getSmtp_host(), DoAnLyThuyet_JavaOutLookApp.getPop3_host(), DoAnLyThuyet_JavaOutLookApp.getUser() , DoAnLyThuyet_JavaOutLookApp.getPass(), DoAnLyThuyet_JavaOutLookApp.getProxy(), DoAnLyThuyet_JavaOutLookApp.getPort()); Session session = myMail.getMailSession(true); Message mess[] = myMail.layCacMessageTrongInbox(session); DefaultTreeModel model = (DefaultTreeModel) jTree_ThuMucMail.getJTreeThuMucNguoiDung().getModel(); //TreePath treePath = jTree_ThuMucMail.getJTreeThuMucNguoiDung().getPathForRow(0).g MutableTreeNode treeNode = (MutableTreeNode) model.getRoot(); TreePath treePath = new TreePath(treeNode); treePath = treePath.pathByAddingChild(treeNode.getChildAt(0)); Kq = mess.length; //model.valueForPathChanged(treePath, "<html><head></head><body><b style=\"color:red\">" + // "Inbox (" + Kq + " new)" + // "</b></body></html>"); jTree_ThuMucMail.getJTreeThuMucNguoiDung().setModel(model); for (Message message: mess){ int idMail = JFrame_GuiMail.luuMailVaoCSDL((MimeMessage)message,"Mails\\Inbox\\"); JFrame_GuiMail.luuAttachVaoCSDL((MimeMessage)message, idMail); } return Kq; } private void jButton_Tool_GetMailActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_Tool_GetMailActionPerformed try { // TODO add your handling code here: int soMailMoi = thucHienLayMailMoi(); int conf = JOptionPane.showConfirmDialog(null, "Co " + soMailMoi + " thu moi! Ban co muon mo thu muc inbox ngay khong?", "Thong bao lay mail thanh cong!", JOptionPane.OK_OPTION); if (conf == JOptionPane.OK_OPTION){ jPanel_XemMail.setToolTipText("Mails\\Inbox\\"); jXuLy_KhiNguoiDungDoiThuMucDuyetMail("Mails\\Inbox\\"); } } catch (Exception ex) { Logger.getLogger(DoAnLyThuyet_JavaOutLookView.class.getName()).log(Level.SEVERE, null, ex); } }//GEN-LAST:event_jButton_Tool_GetMailActionPerformed private void jButton_FindActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_FindActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jButton_FindActionPerformed private void jButton_NewMailActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_NewMailActionPerformed // TODO add your handling code here: JFrame_GuiMail jFrame_GuiMail = new JFrame_GuiMail(); jFrame_GuiMail.show(); }//GEN-LAST:event_jButton_NewMailActionPerformed private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed // TODO add your handling code here: JFrame_CauHinhProxy jFrame_cauhinh = new JFrame_CauHinhProxy(); jFrame_cauhinh.show(); }//GEN-LAST:event_jButton1ActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JButton jButton_Contact; private javax.swing.JButton jButton_Find; private javax.swing.JButton jButton_NewMail; private javax.swing.JButton jButton_Tool_GetMail; private javax.swing.JEditorPane jEditorPane1; private javax.swing.JLabel jLabel1; private javax.swing.JMenuItem jMenuItem1; private javax.swing.JMenuItem jMenuItem_Addressbook; private javax.swing.JMenuItem jMenuItem_Contact; private javax.swing.JMenuItem jMenuItem_Copy; private javax.swing.JMenuItem jMenuItem_CopyFolder; private javax.swing.JMenuItem jMenuItem_Cut; private javax.swing.JMenuItem jMenuItem_DeleteFolder; private javax.swing.JMenuItem jMenuItem_Find; private javax.swing.JMenuItem jMenuItem_Folder; private javax.swing.JMenuItem jMenuItem_Mail; private javax.swing.JMenuItem jMenuItem_NewFolder; private javax.swing.JMenuItem jMenuItem_Paste; private javax.swing.JMenuItem jMenuItem_Receive; private javax.swing.JMenuItem jMenuItem_RenameFolder; private javax.swing.JMenuItem jMenuItem_SelectAll; private javax.swing.JMenuItem jMenuItem_SelectItems; private javax.swing.JMenuItem jMenuItem_Task; private javax.swing.JMenu jMenu_Edit; private javax.swing.JMenu jMenu_Folder; private javax.swing.JMenu jMenu_New; private javax.swing.JMenu jMenu_Open; private javax.swing.JMenu jMenu_Tools; private javax.swing.JPanel jPanel_BenPhai; private javax.swing.JPanel jPanel_BenTrai; private javax.swing.JPanel jPanel_Tren; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane_Giua; private javax.swing.JScrollPane jScrollPane_ThuMucMail; private javax.swing.JScrollPane jScrollPane_ThuMucTrenMay; private javax.swing.JSeparator jSeparator1; private javax.swing.JSeparator jSeparator2; private javax.swing.JSeparator jSeparator3; private javax.swing.JSeparator jSeparator4; private javax.swing.JSplitPane jSplitPane_GiuaPhai; private javax.swing.JSplitPane jSplitPane_ThuMuc; private javax.swing.JSplitPane jSplitPane_TraiVaGiua; private javax.swing.JToolBar jToolBar1; private javax.swing.JToolBar jToolBar2; private javax.swing.JPanel mainPanel; private javax.swing.JMenuBar menuBar; private javax.swing.JProgressBar progressBar; private javax.swing.JLabel statusAnimationLabel; private javax.swing.JLabel statusMessageLabel; private javax.swing.JPanel statusPanel; // End of variables declaration//GEN-END:variables private final Timer messageTimer; private final Timer busyIconTimer; private final Icon idleIcon; private final Icon[] busyIcons = new Icon[15]; private int busyIconIndex = 0; private JDialog aboutBox; }
Java
/* * DoAnLyThuyet_JavaOutLookApp.java */ package doanlythuyet_javaoutlook; import java.io.File; import java.io.IOException; import java.util.Properties; import java.util.logging.Level; import java.util.logging.Logger; import javax.xml.parsers.*; import javax.xml.transform.dom.*; import javax.xml.transform.*; import javax.xml.transform.stream.StreamResult; import org.jdesktop.application.Application; import org.jdesktop.application.SingleFrameApplication; import org.w3c.dom.*; import org.xml.sax.SAXException; /** * The main class of the application. */ public class DoAnLyThuyet_JavaOutLookApp extends SingleFrameApplication { //proxy: private static String Curdir = System.getProperty("user.dir"); private static String smtp_host;// = "smtp.gmail.com"; private static String pop3_host;// = "pop.gmail.com"; private static String user;// = "blueskyairlines05@gmail.com"; private static String pass;// = "987412365"; private static String proxy;// = ""; private static String port;// = ""; /** * @return the Curdir */ public static String getCurdir() { return Curdir; } /** * @param aCurdir the Curdir to set */ public static void setCurdir(String aCurdir) { Curdir = aCurdir; } /** * @return the smtp_host */ public static String getSmtp_host() { return smtp_host; } /** * @param aSmtp_host the smtp_host to set */ public static void setSmtp_host(String aSmtp_host) { smtp_host = aSmtp_host; } /** * @return the pop3_host */ public static String getPop3_host() { return pop3_host; } /** * @param aPop3_host the pop3_host to set */ public static void setPop3_host(String aPop3_host) { pop3_host = aPop3_host; } /** * @return the user */ public static String getUser() { return user; } /** * @param aUser the user to set */ public static void setUser(String aUser) { user = aUser; } /** * @return the pass */ public static String getPass() { return pass; } /** * @param aPass the pass to set */ public static void setPass(String aPass) { pass = aPass; } /** * @return the proxy */ public static String getProxy() { return proxy; } /** * @param aProxy the proxy to set */ public static void setProxy(String aProxy) { proxy = aProxy; } /** * @return the port */ public static String getPort() { return port; } /** * @param aPort the port to set */ public static void setPort(String aPort) { port = aPort; } public static void LayProxytuXML(String strFileName) throws SAXException{ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder; try { builder = factory.newDocumentBuilder(); Document doc = builder.parse(new File(strFileName)); Element root = (Element) doc.getDocumentElement(); NodeList nodelist = root.getElementsByTagName("Config"); Element Ele = (Element)nodelist.item(0); NamedNodeMap attributes = Ele.getAttributes(); for(int i=0;i<attributes.getLength();i++) { Node attributeNode = attributes.item(i); String name = attributeNode.getNodeName(); String value = attributeNode.getNodeValue(); if (name.equals("smtphost")) smtp_host = value; if(name.equals("pop3host")) pop3_host = value; if(name.equals("user")) user = value; if(name.equals("pass")) pass = value; if(name.equals("proxy")) proxy = value; if(name.equals("port")) port = value; } //String maSach = root.getAttribute("Inbox"); Transformer xformer = TransformerFactory.newInstance().newTransformer(); xformer.transform(new DOMSource(doc), new StreamResult(new File(strFileName))); } catch (ParserConfigurationException ex) { Logger.getLogger(DoAnLyThuyet_JavaOutLookApp.class.getName()).log(Level.SEVERE, null, ex); }catch (SAXException ex) { Logger.getLogger(DoAnLyThuyet_JavaOutLookApp.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(DoAnLyThuyet_JavaOutLookApp.class.getName()).log(Level.SEVERE, null, ex); }catch (TransformerConfigurationException ex) { Logger.getLogger(DoAnLyThuyet_JavaOutLookApp.class.getName()).log(Level.SEVERE, null, ex); }catch (TransformerException ex) { Logger.getLogger(DoAnLyThuyet_JavaOutLookApp.class.getName()).log(Level.SEVERE, null, ex); } } /** * At startup create and show the main frame of the application. */ @Override protected void startup() { try { show(new DoAnLyThuyet_JavaOutLookView(this)); } catch (SAXException ex) { Logger.getLogger(DoAnLyThuyet_JavaOutLookApp.class.getName()).log(Level.SEVERE, null, ex); } } /** * This method is to initialize the specified window by injecting resources. * Windows shown in our application come fully initialized from the GUI * builder, so this additional configuration is not needed. */ @Override protected void configureWindow(java.awt.Window root) { } /** * A convenient static getter for the application instance. * @return the instance of DoAnLyThuyet_JavaOutLookApp */ public static DoAnLyThuyet_JavaOutLookApp getApplication() { return Application.getInstance(DoAnLyThuyet_JavaOutLookApp.class); } /** * Main method launching the application. */ public static void main(String[] args) { launch(DoAnLyThuyet_JavaOutLookApp.class, args); } }
Java
package doanlythuyet_javaoutlook; import java.awt.*; import java.awt.event.*; import java.io.*; import java.util.*; import java.text.SimpleDateFormat; import javax.swing.*; import javax.mail.*; import javax.swing.tree.*; import javax.swing.event.*; /** * *Tham khao http://www.java2s.com/Code/Java/Swing-JFC/FileTreewithPopupMenu.htm * @author Dang Thi Phuong Thao */ public class CayDuyetFile { /** * ICON_CONPUTER la icon hinh compute */ public final ImageIcon ICON_COMPUTER = new ImageIcon(this.getClass().getResource(".\\resources\\Tree_computer.png")); /** * ICON_DISK la hinh icon disk */ public final ImageIcon ICON_DISK = new ImageIcon(this.getClass().getResource(".\\resources\\Tree_disk.png")); /** * m_tree la 1 tree, duoc su dung de duyet va dua file vao */ protected JTree m_tree; /** * m_model giu kieu cua node goc, la kieu ma m_tree su dung */ protected DefaultTreeModel m_model; /** * m_display */ // protected JTextField m_display; /** * m_popup luu lai nhung action de sao nay dua vao memu */ protected JPopupMenu m_popup; /** * m_action luu tru action dua vao m_popup */ protected Action m_action; /** * m_clickedPath luu nhung treepath da dc kick qua */ private TreePath m_clickedPath; private DirSelectionListener dirSelectionListener; /** * ham khoi tao CayDuyetFile voi thong so vao la 1 jcsrollPane s */ public CayDuyetFile(JScrollPane s) { Container content = new Container() ; Object[] hierarchy = { "Your mail", "Inbox", "Drafts", "Sent", "Trash", "Signature", }; DefaultMutableTreeNode root = processHierarchy(hierarchy); /* DefaultMutableTreeNode top = new DefaultMutableTreeNode( new IconData(ICON_COMPUTER, null, "Computer")); DefaultMutableTreeNode node; File[] roots = File.listRoots(); for (int k = 0; k < roots.length; k++) { node = new DefaultMutableTreeNode(new IconData(ICON_DISK, null, new FileNode(roots[k]))); top.add(node); node.add(new DefaultMutableTreeNode(new Boolean(true))); } */ m_model = new DefaultTreeModel(root); m_tree = new JTree(m_model); m_tree.putClientProperty("JTree.lineStyle", "Angled"); TreeCellRenderer renderer = new IconCellRenderer(); m_tree.setCellRenderer(renderer); m_tree.addTreeExpansionListener(new DirExpansionListener()); dirSelectionListener = new DirSelectionListener(); m_tree.addTreeSelectionListener(dirSelectionListener); m_tree.getSelectionModel().setSelectionMode( TreeSelectionModel.SINGLE_TREE_SELECTION); m_tree.setShowsRootHandles(true); m_tree.setEditable(false); m_tree.setScrollsOnExpand(true); s.getViewport().add(m_tree); // m_display = new JTextField(); // m_display.setEditable(false); m_popup = new JPopupMenu(); m_action = new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { if (getM_clickedPath() == null) { return; } if (m_tree.isExpanded(getM_clickedPath())) { m_tree.collapsePath(getM_clickedPath()); } else { m_tree.expandPath(getM_clickedPath()); } } }; m_popup.add(m_action); m_popup.addSeparator(); Action a3 = new AbstractAction("Open") { public void actionPerformed(ActionEvent e) { m_tree.repaint(); DefaultMutableTreeNode treenode = (DefaultMutableTreeNode) m_tree.getSelectionPath().getLastPathComponent(); IconData iconData = (IconData) treenode.getUserObject(); FileNode fileNode = (FileNode) iconData.getObject(); initEvent_ClickChuotVaoCayDuyetFile(fileNode.getFile().getPath()); } }; m_popup.add(a3); m_tree.add(m_popup); m_tree.addMouseListener(new PopupTrigger()); WindowListener wndCloser = new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }; //addWindowListener(wndCloser); //setVisible(true); } public DefaultMutableTreeNode processHierarchy(Object[] hierarchy) { DefaultMutableTreeNode node = new DefaultMutableTreeNode(hierarchy[0]); DefaultMutableTreeNode child; for(int i=1; i<hierarchy.length; i++) { Object nodeSpecifier = hierarchy[i]; if (nodeSpecifier instanceof Object[]) // Ie node with children child = processHierarchy((Object[])nodeSpecifier); else child = new DefaultMutableTreeNode(nodeSpecifier); // Ie Leaf node.add(child); } return(node); } public int capNhatCay(String path) { String[] strCacDuongDan = path.split("\\\\"); String strDuongDanHienTai = ""; DefaultMutableTreeNode node = (DefaultMutableTreeNode) m_model.getRoot(); File file = null; //Đầu tiên tìm node của phân vùng (hơi khác biệt vì dùng hàm listRoors) for (int i = 0; i < File.listRoots().length; i++){ file = File.listRoots()[i]; if (file.getAbsolutePath().contains(strCacDuongDan[0])){//tìm đúng phân vùng node = (DefaultMutableTreeNode) m_model.getChild(node, i); strDuongDanHienTai += strCacDuongDan[0]; break; } } int length = strCacDuongDan.length; //Nếu là quay về thư mục cha thì loại bỏ 2 cấp (.. và thư mục con gần nhất) if (strCacDuongDan[length - 1] == "..") length -= 2; //Lần lượt tiến sâu theo từng node (các đường dẫn tiếp theo) for (int i = 1; i < length; i++){ //Lấy đường dẫn tiếp theo String strDuongDanTiepTheo = strCacDuongDan[i]; //Duyệt xem stt của đường dẫn tiếp theo trong thư mục cha file = new File(strDuongDanHienTai).getAbsoluteFile(); int j = 0; for (File filecon : file.listFiles()) { if (!filecon.isDirectory()) continue; //Tìm thư mục con thì cập nhật node và đường dẫn hiện tại if (filecon.getName().equalsIgnoreCase(strDuongDanTiepTheo)){ node = (DefaultMutableTreeNode) m_model.getChild(node, j); strDuongDanHienTai += "\\" + strDuongDanTiepTheo; break; } else //tăng số thứ tự lên j++; } } final FileNode filenode = new FileNode(file); final DefaultMutableTreeNode finalNode = node; //cập nhật cây TreePath tf = new TreePath(m_model.getPathToRoot(finalNode)); if (m_clickedPath != tf) m_tree.fireTreeExpanded(tf); return m_tree.getSelectionRows()[0] * m_tree.getRowHeight(); } /** * lay ra 1 node tren tree * @param path la duong dan treepath * @return 1 node */ DefaultMutableTreeNode getTreeNode(TreePath path) { return (DefaultMutableTreeNode) (path.getLastPathComponent()); } /** * * @param node * @return */ FileNode getFileNode(DefaultMutableTreeNode node) { if (node == null) { return null; } Object obj = node.getUserObject(); if (obj instanceof IconData) { obj = ((IconData) obj).getObject(); } if (obj instanceof FileNode) { return (FileNode) obj; } else { return null; } } //Các hàm sau phục vụ cho việc gởi sự kiện click chuột vào bảng ra ngoài (tham khảo từ nhiều nguồn trên mạng) //http://www.exampledepot.com/egs/java.util/CustEvent.html // Tạo một listener list protected javax.swing.event.EventListenerList listenerList = new javax.swing.event.EventListenerList(); /** * Phát sinh sử kiện click chuột vào tree * @param evt tham số cho sự kiện click chuột vào tree (ở đây là tên của file đang được chọn) */ // This private class is used to fire MyEvents void initEvent_ClickChuotVaoCayDuyetFile(String evt) { Object[] listeners = listenerList.getListenerList(); // Each listener occupies two elements - the first is the listener class // and the second is the listener instance for (int i = 0; i < listeners.length; i += 2) { if (listeners[i] == EventListener_ClickChuotVaoCayDuyetFile.class) { ((EventListener_ClickChuotVaoCayDuyetFile) listeners[i + 1]).Event_ClickChuotVaoCayDuyetFile_Occurred(evt); } } } /** * Đăng ký sự kiện cho classes * @param listener Sự kiện cần đăng ký */ public void addEventListener_ClickChuotVaoCayDuyetFile(EventListener_ClickChuotVaoCayDuyetFile listener) { listenerList.add(EventListener_ClickChuotVaoCayDuyetFile.class, listener); } /** * Gỡ bỏ sự kiện khỏi classes * @param listener Sự kiện cần gỡ bỏ */ public void delEventListener_ClickChuotVaoCayDuyetFile(EventListener_ClickChuotVaoCayDuyetFile listener) { listenerList.remove(EventListener_ClickChuotVaoCayDuyetFile.class, listener); } /** * cap nhat lai cay duyet file sao khi click chuot vao bang * @param tree la cay duyet file hien tai * @param st_file file dang dc chon */ public void capNhatCay(CayDuyetFile tree, String st_file) { tree.initEvent_ClickChuotVaoCayDuyetFile(st_file); tree.addEventListener_ClickChuotVaoCayDuyetFile(new EventListener_ClickChuotVaoCayDuyetFile() { public void Event_ClickChuotVaoCayDuyetFile_Occurred(String str_fileduocchon) { } }); } /** * @return the dirSelectionListener */ public DirSelectionListener getDirSelectionListener() { return dirSelectionListener; } /** * @param dirSelectionListener the dirSelectionListener to set */ public void setDirSelectionListener(DirSelectionListener dirSelectionListener) { this.dirSelectionListener = dirSelectionListener; } /** * @return the m_clickedPath */ public TreePath getM_clickedPath() { return m_clickedPath; } /** * Lop PopupTrigger */ // NEW class PopupTrigger extends MouseAdapter { @Override public void mousePressed(MouseEvent e) { JTree tree = (JTree)e.getSource(); //tree.getPathForRow(0). int x = e.getX(); int y = e.getY(); TreePath path = m_tree.getPathForLocation(x, y); //m_model.valueForPathChanged(path, "Thanh"); String selecttext = path.getPath()[path.getPathCount() - 1].toString(); initEvent_ClickChuotVaoCayDuyetFile(selecttext); } @Override public void mouseReleased(MouseEvent e) { if (e.isPopupTrigger()) { int x = e.getX(); int y = e.getY(); TreePath path = m_tree.getPathForLocation(x, y); if (path != null) { if (m_tree.isExpanded(path)) { m_action.putValue(Action.NAME, "Collapse"); } else { m_action.putValue(Action.NAME, "Expand"); } m_popup.show(m_tree, x, y); m_clickedPath = path; } } } } // Make sure expansion is threaded and updating the tree model // only occurs within the event dispatching thread. /** * Lop DirExpansionListener */ class DirExpansionListener implements TreeExpansionListener { public void treeExpanded(TreeExpansionEvent event) { final DefaultMutableTreeNode node = getTreeNode( event.getPath()); final FileNode fnode = getFileNode(node); Thread runner = new Thread() { public void run() { if (fnode != null && fnode.expand(node)) { Runnable runnable = new Runnable() { public void run() { m_model.reload(node); } }; SwingUtilities.invokeLater(runnable); } } }; runner.start(); m_tree.setSelectionPath(event.getPath()); } public void treeCollapsed(TreeExpansionEvent event) { } } /** * Lop Dir SelectionListerner */ class DirSelectionListener implements TreeSelectionListener { public void valueChanged(TreeSelectionEvent event) { DefaultMutableTreeNode node = getTreeNode( event.getPath()); FileNode fnode = getFileNode(node); if (fnode != null) { // m_display.setText(fnode.getFile(). /// getAbsolutePath()); //initEvent_ClickChuotVaoCayDuyetFile(fnode.getFile().getAbsolutePath()); } // else // m_display.setText(""); } } } /** * Lop IconCellRenderer * @author Dang Thi Phuong Thao */ class IconCellRenderer extends JLabel implements TreeCellRenderer { protected Color m_textSelectionColor; protected Color m_textNonSelectionColor; protected Color m_bkSelectionColor; protected Color m_bkNonSelectionColor; protected Color m_borderSelectionColor; protected boolean m_selected; public IconCellRenderer() { super(); m_textSelectionColor = UIManager.getColor( "Tree.selectionForeground"); m_textNonSelectionColor = UIManager.getColor( "Tree.textForeground"); m_bkSelectionColor = UIManager.getColor( "Tree.selectionBackground"); m_bkNonSelectionColor = UIManager.getColor( "Tree.textBackground"); m_borderSelectionColor = UIManager.getColor( "Tree.selectionBorderColor"); setOpaque(false); } public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) { DefaultMutableTreeNode node = (DefaultMutableTreeNode) value; Object obj = node.getUserObject(); setText(obj.toString()); if (obj instanceof Boolean) { setText("Retrieving data..."); } if (obj instanceof IconData) { IconData idata = (IconData) obj; if (expanded) { setIcon(idata.getExpandedIcon()); } else { setIcon(idata.getIcon()); } } else { setIcon(null); } setFont(tree.getFont()); setForeground(sel ? m_textSelectionColor : m_textNonSelectionColor); setBackground(sel ? m_bkSelectionColor : m_bkNonSelectionColor); m_selected = sel; return this; } public void paintComponent(Graphics g) { Color bColor = getBackground(); Icon icon = getIcon(); g.setColor(bColor); int offset = 0; if (icon != null && getText() != null) { offset = (icon.getIconWidth() + getIconTextGap()); } g.fillRect(offset, 0, getWidth() - 1 - offset, getHeight() - 1); if (m_selected) { g.setColor(m_borderSelectionColor); g.drawRect(offset, 0, getWidth() - 1 - offset, getHeight() - 1); } super.paintComponent(g); } } /** * Lop IconData mo ta mot doi tuong chung cho cac node * @author Dang Thi Phuong Thao */ class IconData { protected Icon m_icon; protected Icon m_expandedIcon; protected Object m_data; public IconData(Icon icon, Object data) { m_icon = icon; m_expandedIcon = null; m_data = data; } public IconData(Icon icon, Icon expandedIcon, Object data) { m_icon = icon; m_expandedIcon = expandedIcon; m_data = data; } public Icon getIcon() { return m_icon; } public Icon getExpandedIcon() { return m_expandedIcon != null ? m_expandedIcon : m_icon; } public Object getObject() { return m_data; } public String toString() { return m_data.toString(); } } /** * FileNode la 1 doi tuong file, la mot node tren tree * @author Dang Thi Phuong Thao */ class FileNode { public final ImageIcon ICON_FOLDER = new ImageIcon(this.getClass().getResource(".\\resources\\Tree_folder.png")); public final ImageIcon ICON_EXPANDEDFOLDER = new ImageIcon(this.getClass().getResource(".\\resources\\Tree_expandedfolder.png")); protected File m_file; public FileNode(File file) { m_file = file; } public File getFile() { return m_file; } /** * Lay ten file va chuyen sang dang chuoi. * @return */ public String toString() { return m_file.getName().length() > 0 ? m_file.getName() : m_file.getPath(); } /** * Kiem tra xem 1 node co the co expand ra node con ko * @param parent : node cha * @return: true neu expand dc, false neu expand ko dc */ public boolean expand(DefaultMutableTreeNode parent) { DefaultMutableTreeNode flag = (DefaultMutableTreeNode) parent.getFirstChild(); if (flag == null) // No flag { return false; } Object obj = flag.getUserObject(); if (!(obj instanceof Boolean)) { return false; // Already expanded } parent.removeAllChildren(); // Remove Flag File[] files = listFiles(); if (files == null) { return true; } Vector v = new Vector(); for (int k = 0; k < files.length; k++) { File f = files[k]; if (!(f.isDirectory())) { continue; } FileNode newNode = new FileNode(f); boolean isAdded = false; for (int i = 0; i < v.size(); i++) { FileNode nd = (FileNode) v.elementAt(i); if (newNode.compareTo(nd) < 0) { v.insertElementAt(newNode, i); isAdded = true; break; } } if (!isAdded) { v.addElement(newNode); } } for (int i = 0; i < v.size(); i++) { FileNode nd = (FileNode) v.elementAt(i); IconData idata = new IconData(ICON_FOLDER, ICON_EXPANDEDFOLDER, nd); DefaultMutableTreeNode node = new DefaultMutableTreeNode(idata); parent.add(node); if (nd.hasSubDirs()) { node.add(new DefaultMutableTreeNode( new Boolean(true))); } } return true; } /** * Kiem tra xem trong cac file co thu muc con ko * @return true neu co thu muc con, false neu ko co */ public boolean hasSubDirs() { File[] files = listFiles(); if (files == null) { return false; } for (int k = 0; k < files.length; k++) { if (files[k].isDirectory()) { return true; } } return false; } public int compareTo(FileNode toCompare) { return m_file.getName().compareToIgnoreCase( toCompare.m_file.getName()); } /** * lay ra danh sach cac file neu co * neu ko co thi thong bao loi * @return danh sach cac file co trong m_file */ protected File[] listFiles() { if (!m_file.isDirectory()) { return null; } try { return m_file.listFiles(); } catch (Exception ex) { JOptionPane.showMessageDialog(null, "Error reading directory " + m_file.getAbsolutePath(), "Warning", JOptionPane.WARNING_MESSAGE); return null; } } }
Java
/* * DoAnLyThuyet_JavaOutLookAboutBox.java */ package doanlythuyet_javaoutlook; //import java.awt.Desktop.Action; import org.jdesktop.application.Action; public class DoAnLyThuyet_JavaOutLookAboutBox extends javax.swing.JDialog { public DoAnLyThuyet_JavaOutLookAboutBox(java.awt.Frame parent) { super(parent); initComponents(); getRootPane().setDefaultButton(closeButton); } @Action public void closeAboutBox() { dispose(); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { closeButton = new javax.swing.JButton(); javax.swing.JLabel appTitleLabel = new javax.swing.JLabel(); javax.swing.JLabel versionLabel = new javax.swing.JLabel(); javax.swing.JLabel appVersionLabel = new javax.swing.JLabel(); javax.swing.JLabel vendorLabel = new javax.swing.JLabel(); javax.swing.JLabel appVendorLabel = new javax.swing.JLabel(); javax.swing.JLabel homepageLabel = new javax.swing.JLabel(); javax.swing.JLabel appHomepageLabel = new javax.swing.JLabel(); javax.swing.JLabel appDescLabel = new javax.swing.JLabel(); javax.swing.JLabel imageLabel = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(doanlythuyet_javaoutlook.DoAnLyThuyet_JavaOutLookApp.class).getContext().getResourceMap(DoAnLyThuyet_JavaOutLookAboutBox.class); setTitle(resourceMap.getString("title")); // NOI18N setModal(true); setName("aboutBox"); // NOI18N setResizable(false); javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(doanlythuyet_javaoutlook.DoAnLyThuyet_JavaOutLookApp.class).getContext().getActionMap(DoAnLyThuyet_JavaOutLookAboutBox.class, this); closeButton.setAction(actionMap.get("closeAboutBox")); // NOI18N closeButton.setName("closeButton"); // NOI18N appTitleLabel.setFont(appTitleLabel.getFont().deriveFont(appTitleLabel.getFont().getStyle() | java.awt.Font.BOLD, appTitleLabel.getFont().getSize()+4)); appTitleLabel.setText(resourceMap.getString("Application.title")); // NOI18N appTitleLabel.setName("appTitleLabel"); // NOI18N versionLabel.setFont(versionLabel.getFont().deriveFont(versionLabel.getFont().getStyle() | java.awt.Font.BOLD)); versionLabel.setText(resourceMap.getString("versionLabel.text")); // NOI18N versionLabel.setName("versionLabel"); // NOI18N appVersionLabel.setText(resourceMap.getString("Application.version")); // NOI18N appVersionLabel.setName("appVersionLabel"); // NOI18N vendorLabel.setFont(vendorLabel.getFont().deriveFont(vendorLabel.getFont().getStyle() | java.awt.Font.BOLD)); vendorLabel.setText(resourceMap.getString("vendorLabel.text")); // NOI18N vendorLabel.setName("vendorLabel"); // NOI18N appVendorLabel.setText(resourceMap.getString("Application.vendor")); // NOI18N appVendorLabel.setName("appVendorLabel"); // NOI18N homepageLabel.setFont(homepageLabel.getFont().deriveFont(homepageLabel.getFont().getStyle() | java.awt.Font.BOLD)); homepageLabel.setText(resourceMap.getString("homepageLabel.text")); // NOI18N homepageLabel.setName("homepageLabel"); // NOI18N appHomepageLabel.setText(resourceMap.getString("Application.homepage")); // NOI18N appHomepageLabel.setName("appHomepageLabel"); // NOI18N appDescLabel.setText(resourceMap.getString("appDescLabel.text")); // NOI18N appDescLabel.setName("appDescLabel"); // NOI18N imageLabel.setIcon(resourceMap.getIcon("imageLabel.icon")); // NOI18N imageLabel.setName("imageLabel"); // NOI18N javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(imageLabel) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(versionLabel) .addComponent(vendorLabel) .addComponent(homepageLabel)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(appVersionLabel) .addComponent(appVendorLabel) .addComponent(appHomepageLabel))) .addComponent(appTitleLabel, javax.swing.GroupLayout.Alignment.LEADING) .addComponent(appDescLabel, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 266, Short.MAX_VALUE) .addComponent(closeButton)) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(imageLabel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(appTitleLabel) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(appDescLabel) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(versionLabel) .addComponent(appVersionLabel)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(vendorLabel) .addComponent(appVendorLabel)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(homepageLabel) .addComponent(appHomepageLabel)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 19, Short.MAX_VALUE) .addComponent(closeButton) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton closeButton; // End of variables declaration//GEN-END:variables }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package doanlythuyet_javaoutlook; /** * * @author Dang Thi Phuong Thao */ import java.io.IOException; import java.util.ArrayList; import java.util.Properties; import javax.mail.*; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; public class MyMail { private String smtp_host = "smtp.gmail.com"; private String pop3_host = "pop.gmail.com"; private String user = "blueskyairlines05@gmail.com"; private String pass = "987412365"; private String proxy = ""; private String port = ""; /** * @return the smtp_host */ public String getSmtp_host() { return smtp_host; } /** * @param smtp_host the smtp_host to set */ public void setSmtp_host(String smtp_host) { this.smtp_host = smtp_host; } /** * @return the pop3_host */ public String getPop3_host() { return pop3_host; } /** * @param pop3_host the pop3_host to set */ public void setPop3_host(String pop3_host) { this.pop3_host = pop3_host; } /** * @return the user */ public String getUser() { return user; } /** * @param user the user to set */ public void setUser(String user) { this.user = user; } /** * @return the pass */ public String getPass() { return pass; } /** * @param pass the pass to set */ public void setPass(String pass) { this.pass = pass; } public MyMail(String str_host,String str_pophost, String str_user, String str_pass, String str_proxy, String str_port) { smtp_host = str_host; pop3_host = str_pophost; user = str_user; pass = str_pass; proxy = str_proxy; port = str_port; } //http://stackoverflow.com/questions/46663/how-do-you-send-email-from-a-java-app-using-gmail public Session getMailSession(boolean pophost) throws Exception{ Properties props = System.getProperties(); props.put("mail.smtp.starttls.enable", "true"); if (!proxy.equals("") && !proxy.equals("0")){ Properties p = System.getProperties(); p.setProperty("proxySet","true"); p.setProperty("socksProxyHost",proxy); p.setProperty("socksProxyPort",port); } if(pophost) props.put("mail.smtp.host",getPop3_host()); else props.put("mail.smtp.host",getSmtp_host()); props.put("mail.smtp.user",getUser()); props.put("mail.smtp.password",getPass()); props.put("mail.smtp.port", "587"); props.put("mail.smtp.auth", "true"); return Session.getInstance(props, null); } public Message[] layCacMessageTrongInbox(Session session) throws NoSuchProviderException, MessagingException, IOException{ // tạo store từ session Folder folder ; Store store = session.getStore("pop3s"); store.connect(getPop3_host(), getUser(), getPass()); folder = store.getFolder("Inbox"); folder.open(Folder.READ_ONLY); Message Kq[] = folder.getMessages(); folder.close(false); store.close(); return Kq; } public void sendMail(String str_Subject, String str_ToAdd, String str_Content, String[] sAr_CCAdd, String[] sAr_BCCAdd, Boolean b_IsSendText) throws AddressException, MessagingException, Exception { //Tao MailSession Properties props = System.getProperties(); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host",getSmtp_host()); props.put("mail.smtp.user",getUser()); props.put("mail.smtp.password",getPass()); props.put("mail.smtp.port", "587"); props.put("mail.smtp.auth", "true"); Session session = Session.getDefaultInstance(props, null); MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(getUser())); //Them danh sach nguoi nhan--------------------------------------------- InternetAddress toAddress = new InternetAddress(str_ToAdd); message.addRecipient(Message.RecipientType.TO, toAddress); //----------------------------CC--------------------- InternetAddress[] CCAddress = new InternetAddress[sAr_CCAdd.length]; // To get the array of addresses for( int i=0; i < CCAddress.length; i++ ) { CCAddress[i] = new InternetAddress(sAr_CCAdd[i]); } for( int i=0; i < CCAddress.length; i++) { message.addRecipient(Message.RecipientType.CC, CCAddress[i]); } //---------------------------BCC--------------------------- InternetAddress[] BCCAddress = new InternetAddress[sAr_BCCAdd.length]; // To get the array of addresses //Them danh sach nguoi nhan for( int i=0; i < BCCAddress.length; i++ ) { BCCAddress[i] = new InternetAddress(sAr_BCCAdd[i]); } for( int i=0; i < BCCAddress.length; i++) { message.addRecipient(Message.RecipientType.BCC, BCCAddress[i]); } //-------------------------------------------------------------------------- message.setSubject(str_Subject); String str_ContentType = "text/"; str_ContentType += b_IsSendText ? "plain" : "html"; message.setContent(str_Content, str_ContentType); //message.setContent(str_Content, str_ContentType); Transport transport = session.getTransport("smtp"); transport.connect(getSmtp_host(), getUser(), getPass()); transport.sendMessage(message, message.getAllRecipients()); transport.close(); } public void sendMail (MimeMessage message) throws Exception{ Session session = getMailSession(false); Transport transport = session.getTransport("smtp"); transport.connect(getSmtp_host(), getUser(), getPass()); transport.sendMessage(message, message.getAllRecipients()); transport.close(); } public static ArrayList<Part> layCacAttachCuaMail (Message mess) throws IOException, MessagingException { ArrayList<Part> Kq = new ArrayList<Part>(); Object content = mess.getContent(); if (content instanceof Multipart){ Multipart multipart = (Multipart)mess.getContent(); for (int i=0; i<multipart.getCount(); i++) { Part part = multipart.getBodyPart(i); String disposition = part.getDisposition(); if ((disposition != null) && ((disposition.equals(Part.ATTACHMENT) || (disposition.equals(Part.INLINE))))) { Kq.add(part); } } } // JFrame_GuiMail.luuTruCacPartVaoHDD(Kq, "Thu thui"); return Kq; } public static Part layPartNoiDung (Message mess) throws IOException, MessagingException { Part Kq = null; Object content = mess.getContent(); if (content instanceof Multipart){ Multipart multipart = (Multipart)mess.getContent(); while ((multipart.getBodyPart(0).getContent()) instanceof Multipart){ multipart = (Multipart)multipart.getBodyPart(0).getContent(); } //for (int i=0; i<multipart.getCount(); i++) { Part part = multipart.getBodyPart(0); Kq = part; //} } // JFrame_GuiMail.luuTruCacPartVaoHDD(Kq, "Thu thui"); return Kq; } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package doanlythuyet_javaoutlook.MyEmum; /** * * @author Dang Thi Phuong Thao */ public enum JEnum_ContactGroupBy { KhongGroup(1), Adress(2), Company(3); private final int value; JEnum_ContactGroupBy(int value) { this.value = value; } int value(){ return this.value; } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package doanlythuyet_javaoutlook.MyEmum; /** * * @author Dang Thi Phuong Thao */ public enum JEnum_MucDo { BinhThuong(1), QuanTrong(2), RatQuanTrong(3); private final int value; JEnum_MucDo(int value) { this.value = value; } int value(){ return this.value; } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package doanlythuyet_javaoutlook.MyEmum; /** * * @author Dang Thi Phuong Thao */ public enum JEnum_TinhTrang { Moi(1), DaXem(2), DaXoa(3), LamNhap(4), Flagged(5), User(6); private final int value; JEnum_TinhTrang(int value) { this.value = value; } public int value(){ return this.value; } }
Java
package doanlythuyet_javaoutlook; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ import java.awt.Point; import java.util.EventListener; /** * * @author Dang Thi Phuong Thao */ public interface EventListener_ClickChuotVaoCayDuyetFile extends EventListener { public void Event_ClickChuotVaoCayDuyetFile_Occurred(String str_fileduocchon); }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package DAO; import DTO.MyAttachDTO; import java.io.IOException; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; /** * * @author Dang Thi Phuong Thao */ public class MyAttachDAO extends AbDAO{ private ArrayList<MyAttachDTO> capNhatTuResultSet(ResultSet rs) throws SQLException{ ArrayList<MyAttachDTO> Kq = new ArrayList<MyAttachDTO>(); /*String Chuoi = ""; try { for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) { Chuoi += rs.getMetaData().getColumnLabel(i) + ", "; } JOptionPane.showMessageDialog(null, Chuoi); } catch (SQLException ex) { Logger.getLogger(MyMailDAO.class.getName()).log(Level.SEVERE, null, ex); }*/ //index = rsmd.getColumnCount(); int index = 0; while (rs.next()) { index = 1; //String temp = rs.getString(index++); int Id = rs.getInt(index++); int IdMail = rs.getInt(index++); String DuongDan = rs.getString(index++); String TenFile = rs.getString(index++); MyAttachDTO myContactDTO = new MyAttachDTO(Id, IdMail,DuongDan,TenFile); Kq.add(myContactDTO); } return Kq; } public ArrayList<MyAttachDTO> layTatCaAttach () throws SQLException, IOException{ KetNoi(); ResultSet rs = thucThiTraVeResultSet("select * from attach"); ArrayList<MyAttachDTO> Kq = capNhatTuResultSet(rs); DongKetNoi(); return Kq; } public ArrayList<MyAttachDTO> layTatCaAttachCuaMailID (int MailID) throws SQLException, IOException{ KetNoi(); ResultSet rs = thucThiTraVeResultSet("select * from attach where IDMail = " + MailID); ArrayList<MyAttachDTO> Kq = capNhatTuResultSet(rs); DongKetNoi(); return Kq; } public int themAttach (MyAttachDTO myAttachDTO) throws IOException{ KetNoi(); //String date = mailDTO.getM_Ngay().toString().substring(0, "dd-MM-yyyy hh:mm:ss".length()); String sql = "insert into attach(IDMail,DuongDan,TenFile)values(" + myAttachDTO.getM_IdMail()+ ", " + "'" + myAttachDTO.getM_DuongDan()+ "', " + "'" + myAttachDTO.getM_TenFile()+"'" + ")"; int Kq = thucThiUpdate(sql); DongKetNoi(); return Kq; } public int xoaAttach(MyAttachDTO attachDTO) throws IOException{ KetNoi(); String sql = "Delete from attach Where ID ="+ attachDTO.getM_Id(); int kq = thucThiUpdate(sql); DongKetNoi(); return kq; } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package DAO; import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JOptionPane; /** * * @author Administrator */ public class AbDAO { protected Connection m_Conn; protected Statement m_Sm; protected void DongKetNoi(){ try { m_Sm.close(); m_Conn.close(); } catch (SQLException ex) { Logger.getLogger(AbDAO.class.getName()).log(Level.SEVERE, null, ex); JOptionPane.showMessageDialog(null, ex.getMessage()); } } protected void KetNoi() throws IOException{ String DBDriver = "sun.jdbc.odbc.JdbcOdbcDriver"; try { try { Class.forName(DBDriver).newInstance(); } catch (ClassNotFoundException ex) { Logger.getLogger(AbDAO.class.getName()).log(Level.SEVERE, null, ex); JOptionPane.showMessageDialog(null, ex.getMessage()); } } catch (InstantiationException ex) { Logger.getLogger(AbDAO.class.getName()).log(Level.SEVERE, null, ex); JOptionPane.showMessageDialog(null, ex.getMessage()); } catch (IllegalAccessException ex) { Logger.getLogger(AbDAO.class.getName()).log(Level.SEVERE, null, ex); JOptionPane.showMessageDialog(null, ex.getMessage()); } //String file = "../Database/CSDL JavaMail.mdb"; String file = new java.io.File(".").getCanonicalPath(); //file = file+="\\Database\\CSDL JavaMail.mdb"; //file = this.getClass().getResource("/Database/").getPath().replace("%20", " ") + "CSDL JavaMail.mdb"; //String file = "G:\\New Folder\\DoAnLyThuyet_JavaOutLook\\src\\Database\\CSDL JavaMail.mdb"; String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ="+file; try { m_Conn = DriverManager.getConnection(url); } catch (SQLException ex) { Logger.getLogger(AbDAO.class.getName()).log(Level.SEVERE, null, ex); JOptionPane.showMessageDialog(null, ex.getMessage()); } } protected ResultSet thucThiTraVeResultSet (String CauTruyVan){ try { m_Sm = m_Conn.createStatement(); } catch (SQLException ex) { Logger.getLogger(AbDAO.class.getName()).log(Level.SEVERE, null, ex); JOptionPane.showMessageDialog(null, ex.getMessage()); } ResultSet rs = null; try { rs = m_Sm.executeQuery(CauTruyVan); } catch (SQLException ex) { Logger.getLogger(AbDAO.class.getName()).log(Level.SEVERE, null, ex); JOptionPane.showMessageDialog(null, ex.getMessage()); } return rs; } /** * thuc thi insert, update, delete * @param CauTruyVan cau sql * @return so dong bi tac dong, neu la cau insert thi tra ve autonumber vua duoc tao */ protected int thucThiUpdate (String CauTruyVan){ try { m_Sm = m_Conn.createStatement(); } catch (SQLException ex) { Logger.getLogger(AbDAO.class.getName()).log(Level.SEVERE, null, ex); JOptionPane.showMessageDialog(null, ex.getMessage()); } int rs = -1; try { rs = m_Sm.executeUpdate(CauTruyVan); if (CauTruyVan.trim().startsWith("insert")) rs = layAutonumberMoiThem(m_Sm); } catch (SQLException ex) { Logger.getLogger(AbDAO.class.getName()).log(Level.SEVERE, null, ex); JOptionPane.showMessageDialog(null, ex.getMessage()); } return rs; } /** * Lay autonumbuer vua moi duoc tao ra do cau lenh insert * @param sm Statement goi cau lenh insert * @return autonumber duoc tao * @throws java.sql.SQLException */ public static int layAutonumberMoiThem (Statement sm) throws SQLException{ int Kq = -1; ResultSet gKeysrs = sm.executeQuery("SELECT @@IDENTITY As TheNewId"); while (gKeysrs.next()){ Kq = gKeysrs.getInt(1); } return Kq; } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package DAO; import DTO.MyContactDTO; import java.io.IOException; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; //import AbDAO.java; /** * * @author Dang Thi Phuong Thao */ public class MyContactDAO extends AbDAO { private ArrayList<MyContactDTO> capNhatTuResultSet(ResultSet rs) throws SQLException{ ArrayList<MyContactDTO> Kq = new ArrayList<MyContactDTO>(); /*String Chuoi = ""; try { for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) { Chuoi += rs.getMetaData().getColumnLabel(i) + ", "; } JOptionPane.showMessageDialog(null, Chuoi); } catch (SQLException ex) { Logger.getLogger(MyMailDAO.class.getName()).log(Level.SEVERE, null, ex); }*/ //index = rsmd.getColumnCount(); int index = 0; while (rs.next()) { index = 1; //String temp = rs.getString(index++); int Id = rs.getInt(index++); String Ten = rs.getString(index++); String CongTy = rs.getString(index++); String Hinh = rs.getString(index++); String Email = rs.getString(index++); String DienThoai = rs.getString(index++); String NickName = rs.getString(index++); String DiaChi = rs.getString(index++); MyContactDTO myContactDTO = new MyContactDTO(Id, Ten,CongTy,Hinh,Email,DienThoai,NickName,DiaChi); Kq.add(myContactDTO); } return Kq; // return Kq; } public ArrayList<MyContactDTO> layTatCaContact () throws SQLException, IOException{ KetNoi(); ResultSet rs = thucThiTraVeResultSet("select * from Contact"); ArrayList<MyContactDTO> Kq = capNhatTuResultSet(rs); DongKetNoi(); return Kq; } public ArrayList<MyContactDTO> layTatCaContactBangID (String Id) throws SQLException, IOException{ KetNoi(); ResultSet rs = thucThiTraVeResultSet("select * from Contact where ID = " + Id) ; ArrayList<MyContactDTO> Kq = capNhatTuResultSet(rs); DongKetNoi(); return Kq; } public int themContact (MyContactDTO contactDTO) throws IOException{ KetNoi(); //String date = mailDTO.getM_Ngay().toString().substring(0, "dd-MM-yyyy hh:mm:ss".length()); String sql = "insert into Contact(Ten,CongTy,Hinh,Email,DienThoai,nickname,DiaChi)" + " values(" + "'" + contactDTO.getM_Ten() + "', " + "'" + contactDTO.getM_CongTy()+ "', " + "'" + contactDTO.getM_Hinh() + "', '" + contactDTO.getM_Email() + "', " + "'" + contactDTO.getM_DienThoai() + "', " + "'" + contactDTO.getM_NickName() + "', '" + contactDTO.getM_DiaChi() + "'" + ")"; int Kq = thucThiUpdate(sql); DongKetNoi(); return Kq; } public int xoaContact(int Id) throws IOException{ KetNoi(); String sql = "Delete from Contact Where ID ="+ Id; int kq = thucThiUpdate(sql); DongKetNoi(); return kq; } public int capNhatContact (MyContactDTO mailDTO) throws IOException{ KetNoi(); int Kq = 0; String sql = "update Contact set Ten = '" + mailDTO.getM_Ten() + "', CongTy = '" + mailDTO.getM_CongTy() + "'," + " Hinh = '" + mailDTO.getM_Hinh() + "', Email = '" + mailDTO.getM_Email() + "', DienThoai = '" + mailDTO.getM_DienThoai() + "', " + "nickname = '" + mailDTO.getM_NickName() + "', " + "DiaChi = '" + mailDTO.getM_DiaChi() + "' where id = " + mailDTO.getM_Id(); Kq = thucThiUpdate(sql); DongKetNoi(); return Kq; } }
Java
/* * To change this rs.getString(index++)late, choose Tools | rs.getString(index++)lates * and open the rs.getString(index++)late in the editor. */ package DAO; import DTO.MyMailDTO; import doanlythuyet_javaoutlook.MyEmum.JEnum_TinhTrang; import java.io.IOException; import java.sql.ResultSet; import java.sql.SQLException; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Enumeration; import java.util.Hashtable; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JOptionPane; /** * * @author Dang Thi Phuong Thao */ public class MyMailDAO extends AbDAO { /** * Chuyen mot ResultSet thanh mot arraylist cac MyMailDTO * @param rs ResultSet * @return Arraylist duoc tao * sau khi goi cau truy van chi can dung ham nay de chuyen doi ket qua, coi them o ham * layTatCaMail de biet cach su dung */ private ArrayList<MyMailDTO> capNhatTuResultSet(ResultSet rs){ ArrayList<MyMailDTO> Kq = new ArrayList<MyMailDTO>(); /*String Chuoi = ""; try { for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) { Chuoi += rs.getMetaData().getColumnLabel(i) + ", "; } JOptionPane.showMessageDialog(null, Chuoi); } catch (SQLException ex) { Logger.getLogger(MyMailDAO.class.getName()).log(Level.SEVERE, null, ex); }*/ try { //index = rsmd.getColumnCount(); int index = 0; while (rs.next()) { index = 1; //String temp = rs.getString(index++); int Id = rs.getInt(index++); String ChuDe = rs.getString(index++); String NguoiGoi = rs.getString(index++); DateFormat df=new SimpleDateFormat("dd-MM-yyyy hh:mm:ss"); Date Ngay = df.parse(rs.getString(index++)); int MucDo = rs.getInt(index++); String DuongDanThuMuc = rs.getString(index++); String DuongDanFileChuaNoiDung = rs.getString(index++); int TinhTrang = rs.getInt(index++); String NguoiNhan = rs.getString(index++); String CC = rs.getString(index++); if (CC == null) CC = ""; String BCC = rs.getString(index++); if (BCC == null) BCC = ""; MyMailDTO mailDTO = new MyMailDTO(Id, ChuDe, NguoiGoi, NguoiNhan, MucDo, TinhTrang, CC, BCC, Ngay, DuongDanThuMuc, DuongDanFileChuaNoiDung); Kq.add(mailDTO); } } catch (ParseException ex) { Logger.getLogger(MyMailDAO.class.getName()).log(Level.SEVERE, null, ex); JOptionPane.showMessageDialog(null, ex.getMessage()); } catch (SQLException ex) { Logger.getLogger(MyMailDTO.class.getName()).log(Level.SEVERE, null, ex); JOptionPane.showMessageDialog(null, ex.getMessage()); } return Kq; } public ArrayList<MyMailDTO> layTatCaMail () throws IOException{ KetNoi(); ResultSet rs = thucThiTraVeResultSet("select * from Mail"); ArrayList<MyMailDTO> Kq = capNhatTuResultSet(rs); DongKetNoi(); return Kq; } public int themMail (MyMailDTO mailDTO) throws IOException{ KetNoi(); DateFormat df=new SimpleDateFormat("dd-MM-yyyy hh:mm:ss"); String date = df.format(mailDTO.getM_Ngay()); //String date = mailDTO.getM_Ngay().toString().substring(0, "dd-MM-yyyy hh:mm:ss".length()); String sql = "insert into Mail(ChuDe, NguoiGui, Ngay, MucDo, DuongDanThuMuc, DuongDanFileChuaNoiDung, TinhTrang, NguoiNhan, CC, BCC)" + " values(" + "'" + mailDTO.getM_ChuDe() + "', " + "'" + mailDTO.getM_NguoiGoi() + "', " + "'" + date + "', " + mailDTO.getM_MucDo() + ", " + "'" + mailDTO.getM_DuongDanThuMuc() + "', " + "'" + mailDTO.getM_DuongDanFileChuaNoiDung() + "', " + mailDTO.getM_TinhTrang() + ", " + "'" + mailDTO.getM_NguoiNhan() + "', " + "'" + mailDTO.getM_CC() + "', " + "'" + mailDTO.getM_BCC() + "'" + ")"; int Kq = thucThiUpdate(sql); DongKetNoi(); return Kq; } /** * Xoa mot mail * @param mailDTO * @return * @throws java.io.IOException */ public int xoaMail(MyMailDTO mailDTO) throws IOException{ KetNoi(); String sql = "Delete from Mail Where ID ="+ mailDTO.getM_Id(); int kq = thucThiUpdate(sql); DongKetNoi(); return kq; } public ArrayList<MyMailDTO> layTatCaMailTrongThuMuc (String duongDan) throws IOException{ KetNoi(); ResultSet rs = thucThiTraVeResultSet("select * from Mail where duongdanthumuc = '" + duongDan + "'"); ArrayList<MyMailDTO> Kq = capNhatTuResultSet(rs); DongKetNoi(); return Kq; } public ArrayList<MyMailDTO> layTatCaMailVoiDieuKien (String duongDan, Hashtable<String, String> cacDieuKien) throws IOException{ KetNoi(); String whereString = " where TinhTrang <>" + JEnum_TinhTrang.DaXoa.value() + " and "; Enumeration<String> e = cacDieuKien.keys(); while(e.hasMoreElements()){ String key = e.nextElement(); whereString += " " + key + "="; if (!key.equalsIgnoreCase("TinhTrang") && !key.equalsIgnoreCase("MucDo") && !key.equalsIgnoreCase("ID")){ whereString += "'"; } if (!key.equalsIgnoreCase("Ngay")) whereString += cacDieuKien.get(key); else{ DateFormat df=new SimpleDateFormat("dd-MM-yyyy hh:mm:ss"); whereString += df.format(cacDieuKien.get(key)); } if (whereString.contains("'")) whereString +="'"; whereString += " and "; } if (whereString.contains(" and")) whereString = whereString.substring(0, whereString.lastIndexOf(" and ")); //JOptionPane.showMessageDialog(null, whereString); String sql = "select * from Mail " + whereString; ResultSet rs = thucThiTraVeResultSet(sql); ArrayList<MyMailDTO> Kq = capNhatTuResultSet(rs); DongKetNoi(); return Kq; } public int capNhatMail (MyMailDTO mailDTO) throws IOException{ KetNoi(); DateFormat df=new SimpleDateFormat("dd-MM-yyyy hh:mm:ss"); String date = df.format(mailDTO.getM_Ngay()); int Kq = 0; String sql = "update Mail set ChuDe = '" + mailDTO.getM_ChuDe() + "', NguoiGui = '" + mailDTO.getM_NguoiGoi() + "'," + " Ngay = '" + date + "', MucDo = " + mailDTO.getM_MucDo() + ", DuongDanThuMuc = '" + mailDTO.getM_DuongDanThuMuc() + "', " + "DuongDanFileChuaNoiDung = '" + mailDTO.getM_DuongDanFileChuaNoiDung() + "', " + "TinhTrang = " + mailDTO.getM_TinhTrang() + " , " + "NguoiNhan = '" + mailDTO.getM_NguoiGoi() + "', CC ='" + mailDTO.getM_NguoiGoi() + "', BCC = '" + mailDTO.getM_NguoiGoi() + "'"; sql+=" where id = " + mailDTO.getM_Id(); Kq = thucThiUpdate(sql); DongKetNoi(); return Kq; } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * JPanel_XemMail.java * * Created on May 27, 2009, 9:23:59 AM */ package DAO; import doanlythuyet_javaoutlook.MyUserControl.*; import BUS.MyMailBUS; import DTO.MyMailDTO; import java.awt.Component; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.AbstractButton; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JCheckBox; import javax.swing.JOptionPane; import javax.swing.JTable; import javax.swing.UIManager; import javax.swing.table.AbstractTableModel; import javax.swing.table.DefaultTableModel; import javax.swing.table.JTableHeader; import javax.swing.table.TableCellEditor; import javax.swing.table.TableCellRenderer; import javax.swing.table.TableColumn; import javax.swing.table.TableColumnModel; import javax.swing.table.TableModel; /** * * @author Dang Thi Phuong Thao */ public class JPanel_XemMail_1 extends javax.swing.JPanel { private Boolean tatCaDuocChon = false; /** Creates new form JPanel_XemMail */ public JPanel_XemMail_1() { initComponents(); //DuaDanhSachMailVaoBang(DanhSachMail); } public void ThemDongVaoBang (JTable table, Object[][] CacGiaTri){ DefaultTableModel model = (DefaultTableModel) table.getModel(); //model } public void XoaDongTrongBang (JTable table, int[] Indexs){ DefaultTableModel model = (DefaultTableModel) table.getModel(); //model. } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jSplitPane1 = new javax.swing.JSplitPane(); jPanel_DanhSachMail = new javax.swing.JPanel(); jScrollPane1 = new javax.swing.JScrollPane(); jTable_danhsachmail = new javax.swing.JTable(); jPanel_ChiTietMail = new javax.swing.JPanel(); jScrollPane2 = new javax.swing.JScrollPane(); jEditorPane_chitietmail = new javax.swing.JEditorPane(); jPanel1 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jLabel_chude = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel_goitu = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel_ngay = new javax.swing.JLabel(); setName("Form"); // NOI18N addAncestorListener(new javax.swing.event.AncestorListener() { public void ancestorMoved(javax.swing.event.AncestorEvent evt) { } public void ancestorAdded(javax.swing.event.AncestorEvent evt) { formAncestorAdded(evt); } public void ancestorRemoved(javax.swing.event.AncestorEvent evt) { } }); jSplitPane1.setDividerLocation(200); jSplitPane1.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT); jSplitPane1.setName("jSplitPane1"); // NOI18N jPanel_DanhSachMail.setName("jPanel_DanhSachMail"); // NOI18N jScrollPane1.setName("jScrollPane1"); // NOI18N jTable_danhsachmail.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null} }, new String [] { "Tất cả", "Chủ đề", "Người gởi", "Ngày" } ) { Class[] types = new Class [] { java.lang.Boolean.class, java.lang.String.class, java.lang.String.class, java.lang.String.class }; public Class getColumnClass(int columnIndex) { return types [columnIndex]; } }); jTable_danhsachmail.setCellSelectionEnabled(true); jTable_danhsachmail.setName("jTable_danhsachmail"); // NOI18N jTable_danhsachmail.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jTable_danhsachmailMouseClicked(evt); } }); jScrollPane1.setViewportView(jTable_danhsachmail); jTable_danhsachmail.getColumnModel().getColumn(0).setMinWidth(40); jTable_danhsachmail.getColumnModel().getColumn(0).setPreferredWidth(40); jTable_danhsachmail.getColumnModel().getColumn(0).setMaxWidth(40); jTable_danhsachmail.getColumnModel().getColumn(1).setPreferredWidth(150); javax.swing.GroupLayout jPanel_DanhSachMailLayout = new javax.swing.GroupLayout(jPanel_DanhSachMail); jPanel_DanhSachMail.setLayout(jPanel_DanhSachMailLayout); jPanel_DanhSachMailLayout.setHorizontalGroup( jPanel_DanhSachMailLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 597, Short.MAX_VALUE) ); jPanel_DanhSachMailLayout.setVerticalGroup( jPanel_DanhSachMailLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 199, Short.MAX_VALUE) ); jSplitPane1.setTopComponent(jPanel_DanhSachMail); jPanel_ChiTietMail.setName("jPanel_ChiTietMail"); // NOI18N jScrollPane2.setName("jScrollPane2"); // NOI18N jEditorPane_chitietmail.setName("jEditorPane_chitietmail"); // NOI18N jScrollPane2.setViewportView(jEditorPane_chitietmail); jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Thông tin chi tiết mail đang chọn:")); jPanel1.setName("jPanel1"); // NOI18N jLabel1.setName("jLabel1"); // NOI18N jLabel_chude.setName("jLabel_chude"); // NOI18N jLabel2.setName("jLabel2"); // NOI18N jLabel_goitu.setName("jLabel_goitu"); // NOI18N jLabel4.setName("jLabel4"); // NOI18N jLabel_ngay.setName("jLabel_ngay"); // NOI18N javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel_chude, javax.swing.GroupLayout.PREFERRED_SIZE, 54, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jLabel_goitu) .addGap(117, 117, 117) .addComponent(jLabel4) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel_ngay))) .addContainerGap(448, Short.MAX_VALUE)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(jLabel_chude, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(jLabel_goitu) .addComponent(jLabel4) .addComponent(jLabel_ngay))) ); javax.swing.GroupLayout jPanel_ChiTietMailLayout = new javax.swing.GroupLayout(jPanel_ChiTietMail); jPanel_ChiTietMail.setLayout(jPanel_ChiTietMailLayout); jPanel_ChiTietMailLayout.setHorizontalGroup( jPanel_ChiTietMailLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 597, Short.MAX_VALUE) ); jPanel_ChiTietMailLayout.setVerticalGroup( jPanel_ChiTietMailLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel_ChiTietMailLayout.createSequentialGroup() .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 276, Short.MAX_VALUE)) ); jSplitPane1.setRightComponent(jPanel_ChiTietMail); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 599, Short.MAX_VALUE) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jSplitPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 538, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(20, Short.MAX_VALUE)) ); }// </editor-fold>//GEN-END:initComponents private void formAncestorAdded(javax.swing.event.AncestorEvent evt) {//GEN-FIRST:event_formAncestorAdded try { // TODO add your handling code here: MyMailBUS busMail = new MyMailBUS(); ArrayList<MyMailDTO> DanhSachMail = busMail.layTatCaMail(); DuaDanhSachMailVaoBang(DanhSachMail); } catch (IOException ex) { Logger.getLogger(JPanel_XemMail.class.getName()).log(Level.SEVERE, null, ex); } }//GEN-LAST:event_formAncestorAdded private void jTable_danhsachmailMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable_danhsachmailMouseClicked // TODO add your handling code here: // TableColumnModel colModel = jTable_danhsachmail.getColumnModel(); // int columnModelIndex = colModel.getColumnIndexAtX(evt.getX()); // int modelIndex = colModel.getColumn(columnModelIndex).getModelIndex(); // JOptionPane.showMessageDialog(null, modelIndex); }//GEN-LAST:event_jTable_danhsachmailMouseClicked // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JEditorPane jEditorPane_chitietmail; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel_chude; private javax.swing.JLabel jLabel_goitu; private javax.swing.JLabel jLabel_ngay; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel_ChiTietMail; private javax.swing.JPanel jPanel_DanhSachMail; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JSplitPane jSplitPane1; private javax.swing.JTable jTable_danhsachmail; // End of variables declaration//GEN-END:variables public void DuaDanhSachMailVaoBang(ArrayList<MyMailDTO>DanhSachMail){ // DanhSachMail.get(1); /*Tabl tableMode = jTable_danhsachmail.getModel(); TableColumnModel columnModel = jTable_danhsachmail.getColumnModel(); TableColumn column= columnModel.getColumn(1); int countColum = jTable_danhsachmail.getColumnCount(); int i =0; int j = 1; for(;j<countColum;j++) { //TableCellEditor cellEditor =jTable_danhsachmail } */ Icon icon = new ImageIcon("C:\\1.png"); final String cacCotDuLieu[] = {"Tất cả","Tình trạng","Đính kèm","Chủ đề","Người gởi", "Ngày"}; Object DuLieu[][] = new Object[DanhSachMail.size()][cacCotDuLieu.length]; for(int i = 0; i < DanhSachMail.size();i++){ int index = 0; DuLieu[i][index++] = false; //for(int j = 1; i < model.) dulieu[index] = new Object(); if (i % 2 == 0){ DuLieu[i][index++] = icon; } if (i % 2 == 0){ //Icon icon = new ImageIcon("C:\\1.png"); DuLieu[i][index++] = icon; } DuLieu[i][index++] = DanhSachMail.get(i).getM_NguoiGoi(); //dulieu[index++] = DanhSachMail.get(i).getM_NguoiGoi(); DuLieu[i][index++] = DanhSachMail.get(i).getM_ChuDe(); DuLieu[i][index++] = DanhSachMail.get(i).getM_Ngay().toString(); } final Object bangDuLieu[][] = DuLieu; DefaultTableModel modelBangHienThi = new DefaultTableModel(bangDuLieu,cacCotDuLieu) { @Override public Class getColumnClass(int columnIndex) { return (columnIndex == 0) ? Boolean.class : String.class; } @Override public int getColumnCount() { return cacCotDuLieu.length; } @Override public String getColumnName(int column) { return cacCotDuLieu[column]; } @Override public int getRowCount() { return bangDuLieu.length; } @Override public Object getValueAt(int row, int column) { return bangDuLieu[row][column]; } @Override public boolean isCellEditable(int row, int column) { return column == 0; } }; //JTable table = new JTable(modelBangHienThi); //modelBangHienThi.isCellEditable(1, 1); jTable_danhsachmail.setModel(modelBangHienThi); TableColumn tc = jTable_danhsachmail.getColumnModel().getColumn(0); tc.setCellEditor(jTable_danhsachmail.getDefaultEditor(Boolean.class)); tc.setCellRenderer(jTable_danhsachmail.getDefaultRenderer(Boolean.class)); tc.setHeaderRenderer(new CheckBoxHeader(new MyItemListener())); /*jTable_danhsachmail.getColumnModel().getColumn(0).setCellRenderer(new TableCellRenderer() { // the method gives the component like whome the cell must be rendered public Component getTableCellRendererComponent( JTable table, Object value, boolean isSelected, boolean isFocused, int row, int col) { boolean marked = (Boolean) value; JCheckBox rendererComponent = new JCheckBox(); if (marked) { rendererComponent.setSelected(true); //JOptionPane.showMessageDialog(null, "F"); } return rendererComponent; } }); */JTableHeader header = jTable_danhsachmail.getTableHeader(); header.addMouseListener(new MouseListener() { public void mouseClicked(MouseEvent e) { //throw new UnsupportedOperationException("Not supported yet."); JTableHeader tableHeader = (JTableHeader) e.getSource(); //tableHeader.isFocusOwner(); //JOptionPane.showMessageDialog(null, tableHeader.getColumnModel().getColumnIndexAtX(e.getX())); if(tableHeader.getColumnModel().getColumnIndexAtX(e.getX())==0) //jTable_danhsachmail.getColumnModel().getColumn(1).s tatCaDuocChon = !tatCaDuocChon; DoiTrangThaiCotCheckBox(tatCaDuocChon); } public void mousePressed(MouseEvent e) { //throw new UnsupportedOperationException("Not supported yet."); } public void mouseReleased(MouseEvent e) { //throw new UnsupportedOperationException("Not supported yet."); } public void mouseEntered(MouseEvent e) { //throw new UnsupportedOperationException("Not supported yet."); } public void mouseExited(MouseEvent e) { //throw new UnsupportedOperationException("Not supported yet."); } }); /* DefaultTableModel model = (DefaultTableModel)jTable_danhsachmail.getModel(); // int countcolumn =tableModel.getColumnCount(); // int index =1; model.setRowCount(WIDTH); for(int i = 0; i < DanhSachMail.size();i++){ int index = 1; Object dulieu[] = new Object[model.getColumnCount()]; //for(int j = 1; i < model.) dulieu[index] = new Object(); dulieu[index++] = DanhSachMail.get(i).getM_NguoiGoi(); //dulieu[index++] = DanhSachMail.get(i).getM_NguoiGoi(); dulieu[index++] = DanhSachMail.get(i).getM_ChuDe(); dulieu[index] = DanhSachMail.get(i).getM_Ngay().toString(); model.addRow(dulieu); }*/ } private void DoiTrangThaiCotCheckBox (boolean isDuocChon){ TableModel tableModel = jTable_danhsachmail.getModel(); for (int i = 0; i < tableModel.getRowCount(); i++){ tableModel.setValueAt(isDuocChon, i, 0); } } class MyItemListener implements ItemListener{ public void itemStateChanged(ItemEvent e) { Object source = e.getSource(); if (source instanceof AbstractButton == false) return; boolean checked = e.getStateChange() == ItemEvent.SELECTED; for(int x = 0, y = jTable_danhsachmail.getRowCount(); x < y; x++) { jTable_danhsachmail.setValueAt(new Boolean(checked),x,0); } } } } class CheckBoxHeader extends JCheckBox implements TableCellRenderer, MouseListener { protected CheckBoxHeader rendererComponent; protected int column; protected boolean mousePressed = false; public CheckBoxHeader(ItemListener itemListener) { rendererComponent = this; rendererComponent.addItemListener(itemListener); } public Component getTableCellRendererComponent( JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { if (table != null) { JTableHeader header = table.getTableHeader(); if (header != null) { rendererComponent.setForeground(header.getForeground()); rendererComponent.setBackground(header.getBackground()); rendererComponent.setFont(header.getFont()); header.addMouseListener(rendererComponent); } } setColumn(column); rendererComponent.setText(""); setBorder(UIManager.getBorder("TableHeader.cellBorder")); return rendererComponent; } protected void setColumn(int column) { this.column = column; } public int getColumn() { return column; } protected void handleClickEvent(MouseEvent e) { if (mousePressed) { mousePressed=false; JTableHeader header = (JTableHeader)(e.getSource()); JTable tableView = header.getTable(); TableColumnModel columnModel = tableView.getColumnModel(); int viewColumn = columnModel.getColumnIndexAtX(e.getX()); int column = tableView.convertColumnIndexToModel(viewColumn); if (viewColumn == this.column && e.getClickCount() == 1 && column != -1) { doClick(); } } } public void mouseClicked(MouseEvent e) { handleClickEvent(e); ((JTableHeader)e.getSource()).repaint(); } public void mousePressed(MouseEvent e) { mousePressed = true; } public void mouseReleased(MouseEvent e) { } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } }
Java
/* * Copyright 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.stats; /** * A helper class that tracks a minimum and a maximum of a variable. * * @author Sandor Dornbush */ public class ExtremityMonitor { /** * The smallest value seen so far. */ private double min; /** * The largest value seen so far. */ private double max; public ExtremityMonitor() { reset(); } /** * Updates the min and the max with the new value. * * @param value the new value for the monitor * @return true if an extremity was found */ public boolean update(double value) { boolean changed = false; if (value < min) { min = value; changed = true; } if (value > max) { max = value; changed = true; } return changed; } /** * Gets the minimum value seen. * * @return The minimum value passed into the update() function */ public double getMin() { return min; } /** * Gets the maximum value seen. * * @return The maximum value passed into the update() function */ public double getMax() { return max; } /** * Resets this object to it's initial state where the min and max are unknown. */ public void reset() { min = Double.POSITIVE_INFINITY; max = Double.NEGATIVE_INFINITY; } /** * Sets the minimum and maximum values. */ public void set(double min, double max) { this.min = min; this.max = max; } /** * Sets the minimum value. */ public void setMin(double min) { this.min = min; } /** * Sets the maximum value. */ public void setMax(double max) { this.max = max; } public boolean hasData() { return min != Double.POSITIVE_INFINITY && max != Double.NEGATIVE_INFINITY; } @Override public String toString() { return "Min: " + min + " Max: " + max; } }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.stats; import android.os.Parcel; import android.os.Parcelable; /** * Statistical data about a trip. * The data in this class should be filled out by TripStatisticsBuilder. * * TODO: hashCode and equals * * @author Rodrigo Damazio */ public class TripStatistics implements Parcelable { /** * The start time for the trip. This is system time which might not match gps * time. */ private long startTime = -1L; /** * The stop time for the trip. This is the system time which might not match * gps time. */ private long stopTime = -1L; /** * The total time that we believe the user was traveling in milliseconds. */ private long movingTime; /** * The total time of the trip in milliseconds. * This is only updated when new points are received, so it may be stale. */ private long totalTime; /** * The total distance in meters that the user traveled on this trip. */ private double totalDistance; /** * The total elevation gained on this trip in meters. */ private double totalElevationGain; /** * The maximum speed in meters/second reported that we believe to be a valid * speed. */ private double maxSpeed; /** * The min and max latitude values seen in this trip. */ private final ExtremityMonitor latitudeExtremities = new ExtremityMonitor(); /** * The min and max longitude values seen in this trip. */ private final ExtremityMonitor longitudeExtremities = new ExtremityMonitor(); /** * The min and max elevation seen on this trip in meters. */ private final ExtremityMonitor elevationExtremities = new ExtremityMonitor(); /** * The minimum and maximum grade calculations on this trip. */ private final ExtremityMonitor gradeExtremities = new ExtremityMonitor(); /** * Default constructor. */ public TripStatistics() { } /** * Copy constructor. * * @param other another statistics data object to copy from */ public TripStatistics(TripStatistics other) { this.maxSpeed = other.maxSpeed; this.movingTime = other.movingTime; this.startTime = other.startTime; this.stopTime = other.stopTime; this.totalDistance = other.totalDistance; this.totalElevationGain = other.totalElevationGain; this.totalTime = other.totalTime; this.latitudeExtremities.set(other.latitudeExtremities.getMin(), other.latitudeExtremities.getMax()); this.longitudeExtremities.set(other.longitudeExtremities.getMin(), other.longitudeExtremities.getMax()); this.elevationExtremities.set(other.elevationExtremities.getMin(), other.elevationExtremities.getMax()); this.gradeExtremities.set(other.gradeExtremities.getMin(), other.gradeExtremities.getMax()); } /** * Combines these statistics with those from another object. * This assumes that the time periods covered by each do not intersect. * * @param other the other waypoint */ public void merge(TripStatistics other) { startTime = Math.min(startTime, other.startTime); stopTime = Math.max(stopTime, other.stopTime); totalTime += other.totalTime; movingTime += other.movingTime; totalDistance += other.totalDistance; totalElevationGain += other.totalElevationGain; maxSpeed = Math.max(maxSpeed, other.maxSpeed); latitudeExtremities.update(other.latitudeExtremities.getMax()); latitudeExtremities.update(other.latitudeExtremities.getMin()); longitudeExtremities.update(other.longitudeExtremities.getMax()); longitudeExtremities.update(other.longitudeExtremities.getMin()); elevationExtremities.update(other.elevationExtremities.getMax()); elevationExtremities.update(other.elevationExtremities.getMin()); gradeExtremities.update(other.gradeExtremities.getMax()); gradeExtremities.update(other.gradeExtremities.getMin()); } /** * Gets the time that this track started. * * @return The number of milliseconds since epoch to the time when this track * started */ public long getStartTime() { return startTime; } /** * Gets the time that this track stopped. * * @return The number of milliseconds since epoch to the time when this track * stopped */ public long getStopTime() { return stopTime; } /** * Gets the total time that this track has been active. * This statistic is only updated when a new point is added to the statistics, * so it may be off. If you need to calculate the proper total time, use * {@link #getStartTime} with the current time. * * @return The total number of milliseconds the track was active */ public long getTotalTime() { return totalTime; } /** * Gets the total distance the user traveled. * * @return The total distance traveled in meters */ public double getTotalDistance() { return totalDistance; } /** * Gets the the average speed the user traveled. * This calculation only takes into account the displacement until the last * point that was accounted for in statistics. * * @return The average speed in m/s */ public double getAverageSpeed() { if (totalTime == 0L) { return 0.0; } return totalDistance / ((double) totalTime / 1000.0); } /** * Gets the the average speed the user traveled when they were actively * moving. * * @return The average moving speed in m/s */ public double getAverageMovingSpeed() { if (movingTime == 0L) { return 0.0; } return totalDistance / ((double) movingTime / 1000.0); } /** * Gets the the maximum speed for this track. * * @return The maximum speed in m/s */ public double getMaxSpeed() { return maxSpeed; } /** * Gets the moving time. * * @return The total number of milliseconds the user was moving */ public long getMovingTime() { return movingTime; } /** * Gets the total elevation gain for this trip. This is calculated as the sum * of all positive differences in the smoothed elevation. * * @return The elevation gain in meters for this trip */ public double getTotalElevationGain() { return totalElevationGain; } /** * Returns the leftmost position (lowest longitude) of the track, in signed degrees. */ public double getLeftDegrees() { return longitudeExtremities.getMin(); } /** * Returns the leftmost position (lowest longitude) of the track, in signed millions of degrees. */ public int getLeft() { return (int) (longitudeExtremities.getMin() * 1E6); } /** * Returns the rightmost position (highest longitude) of the track, in signed degrees. */ public double getRightDegrees() { return longitudeExtremities.getMax(); } /** * Returns the rightmost position (highest longitude) of the track, in signed millions of degrees. */ public int getRight() { return (int) (longitudeExtremities.getMax() * 1E6); } /** * Returns the bottommost position (lowest latitude) of the track, in signed degrees. */ public double getBottomDegrees() { return latitudeExtremities.getMin(); } /** * Returns the bottommost position (lowest latitude) of the track, in signed millions of degrees. */ public int getBottom() { return (int) (latitudeExtremities.getMin() * 1E6); } /** * Returns the topmost position (highest latitude) of the track, in signed degrees. */ public double getTopDegrees() { return latitudeExtremities.getMax(); } /** * Returns the topmost position (highest latitude) of the track, in signed millions of degrees. */ public int getTop() { return (int) (latitudeExtremities.getMax() * 1E6); } /** * Returns the mean position (center latitude) of the track, in signed degrees. */ public double getMeanLatitude() { return (getBottomDegrees() + getTopDegrees()) / 2.0; } /** * Returns the mean position (center longitude) of the track, in signed degrees. */ public double getMeanLongitude() { return (getLeftDegrees() + getRightDegrees()) / 2.0; } /** * Gets the minimum elevation seen on this trip. This is calculated from the * smoothed elevation so this can actually be more than the current elevation. * * @return The smallest elevation reading for this trip in meters */ public double getMinElevation() { return elevationExtremities.getMin(); } /** * Gets the maximum elevation seen on this trip. This is calculated from the * smoothed elevation so this can actually be less than the current elevation. * * @return The largest elevation reading for this trip in meters */ public double getMaxElevation() { return elevationExtremities.getMax(); } /** * Gets the maximum grade for this trip. * * @return The maximum grade for this trip as a fraction */ public double getMaxGrade() { return gradeExtremities.getMax(); } /** * Gets the minimum grade for this trip. * * @return The minimum grade for this trip as a fraction */ public double getMinGrade() { return gradeExtremities.getMin(); } // Setters - to be used when restoring state or loading from the DB /** * Sets the start time for this trip. * * @param startTime the start time, in milliseconds since the epoch */ public void setStartTime(long startTime) { this.startTime = startTime; } /** * Sets the stop time for this trip. * * @param stopTime the stop time, in milliseconds since the epoch */ public void setStopTime(long stopTime) { this.stopTime = stopTime; } /** * Sets the total moving time. * * @param movingTime the moving time in milliseconds */ public void setMovingTime(long movingTime) { this.movingTime = movingTime; } /** * Sets the total trip time. * * @param totalTime the total trip time in milliseconds */ public void setTotalTime(long totalTime) { this.totalTime = totalTime; } /** * Sets the total trip distance. * * @param totalDistance the trip distance in meters */ public void setTotalDistance(double totalDistance) { this.totalDistance = totalDistance; } /** * Sets the total elevation variation during the trip. * * @param totalElevationGain the elevation variation in meters */ public void setTotalElevationGain(double totalElevationGain) { this.totalElevationGain = totalElevationGain; } /** * Sets the maximum speed reached during the trip. * * @param maxSpeed the maximum speed in meters per second */ public void setMaxSpeed(double maxSpeed) { this.maxSpeed = maxSpeed; } /** * Sets the minimum elevation reached during the trip. * * @param elevation the minimum elevation in meters */ public void setMinElevation(double elevation) { elevationExtremities.setMin(elevation); } /** * Sets the maximum elevation reached during the trip. * * @param elevation the maximum elevation in meters */ public void setMaxElevation(double elevation) { elevationExtremities.setMax(elevation); } /** * Sets the minimum grade obtained during the trip. * * @param grade the grade as a fraction (-1.0 would mean vertical downwards) */ public void setMinGrade(double grade) { gradeExtremities.setMin(grade); } /** * Sets the maximum grade obtained during the trip). * * @param grade the grade as a fraction (1.0 would mean vertical upwards) */ public void setMaxGrade(double grade) { gradeExtremities.setMax(grade); } /** * Sets the bounding box for this trip. * The unit for all parameters is signed decimal degrees (degrees * 1E6). * * @param leftE6 the westmost longitude reached * @param topE6 the northmost latitude reached * @param rightE6 the eastmost longitude reached * @param bottomE6 the southmost latitude reached */ public void setBounds(int leftE6, int topE6, int rightE6, int bottomE6) { latitudeExtremities.set(bottomE6 / 1E6, topE6 / 1E6); longitudeExtremities.set(leftE6 / 1E6, rightE6 / 1E6); } // Data manipulation methods /** * Adds to the current total distance. * * @param distance the distance to add in meters */ void addTotalDistance(double distance) { totalDistance += distance; } /** * Adds to the total elevation variation. * * @param gain the elevation variation in meters */ void addTotalElevationGain(double gain) { totalElevationGain += gain; } /** * Adds to the total moving time of the trip. * * @param time the time in milliseconds */ void addMovingTime(long time) { movingTime += time; } /** * Accounts for a new latitude value for the bounding box. * * @param latitude the latitude value in signed decimal degrees */ void updateLatitudeExtremities(double latitude) { latitudeExtremities.update(latitude); } /** * Accounts for a new longitude value for the bounding box. * * @param longitude the longitude value in signed decimal degrees */ void updateLongitudeExtremities(double longitude) { longitudeExtremities.update(longitude); } /** * Accounts for a new elevation value for the bounding box. * * @param elevation the elevation value in meters */ void updateElevationExtremities(double elevation) { elevationExtremities.update(elevation); } /** * Accounts for a new grade value. * * @param grade the grade value as a fraction */ void updateGradeExtremities(double grade) { gradeExtremities.update(grade); } // String conversion @Override public String toString() { return "TripStatistics { Start Time: " + getStartTime() + "; Total Time: " + getTotalTime() + "; Moving Time: " + getMovingTime() + "; Total Distance: " + getTotalDistance() + "; Elevation Gain: " + getTotalElevationGain() + "; Min Elevation: " + getMinElevation() + "; Max Elevation: " + getMaxElevation() + "; Average Speed: " + getAverageMovingSpeed() + "; Min Grade: " + getMinGrade() + "; Max Grade: " + getMaxGrade() + "}"; } // Parcelable interface and creator /** * Creator of statistics data from parcels. */ public static class Creator implements Parcelable.Creator<TripStatistics> { @Override public TripStatistics createFromParcel(Parcel source) { TripStatistics data = new TripStatistics(); data.startTime = source.readLong(); data.movingTime = source.readLong(); data.totalTime = source.readLong(); data.totalDistance = source.readDouble(); data.totalElevationGain = source.readDouble(); data.maxSpeed = source.readDouble(); double minLat = source.readDouble(); double maxLat = source.readDouble(); data.latitudeExtremities.set(minLat, maxLat); double minLong = source.readDouble(); double maxLong = source.readDouble(); data.longitudeExtremities.set(minLong, maxLong); double minElev = source.readDouble(); double maxElev = source.readDouble(); data.elevationExtremities.set(minElev, maxElev); double minGrade = source.readDouble(); double maxGrade = source.readDouble(); data.gradeExtremities.set(minGrade, maxGrade); return data; } @Override public TripStatistics[] newArray(int size) { return new TripStatistics[size]; } } /** * Creator of {@link TripStatistics} from parcels. */ public static final Creator CREATOR = new Creator(); @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeLong(startTime); dest.writeLong(movingTime); dest.writeLong(totalTime); dest.writeDouble(totalDistance); dest.writeDouble(totalElevationGain); dest.writeDouble(maxSpeed); dest.writeDouble(latitudeExtremities.getMin()); dest.writeDouble(latitudeExtremities.getMax()); dest.writeDouble(longitudeExtremities.getMin()); dest.writeDouble(longitudeExtremities.getMax()); dest.writeDouble(elevationExtremities.getMin()); dest.writeDouble(elevationExtremities.getMax()); dest.writeDouble(gradeExtremities.getMin()); dest.writeDouble(gradeExtremities.getMax()); } }
Java
/* * Copyright 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.content; import static com.google.android.apps.mytracks.lib.MyTracksLibConstants.TAG; import com.google.android.apps.mytracks.stats.TripStatistics; import com.google.protobuf.InvalidProtocolBufferException; import android.content.ContentResolver; import android.content.ContentValues; import android.database.Cursor; import android.location.Location; import android.net.Uri; import android.util.Log; import java.util.ArrayList; import java.util.List; import java.util.NoSuchElementException; /** * Helper class providing easy access to locations and tracks in the * MyTracksProvider. All static members. * * @author Leif Hendrik Wilden */ public class MyTracksProviderUtilsImpl implements MyTracksProviderUtils { private final ContentResolver contentResolver; private int defaultCursorBatchSize = 2000; public MyTracksProviderUtilsImpl(ContentResolver contentResolver) { this.contentResolver = contentResolver; } /** * Creates the ContentValues for a given location object. * * @param location a given location * @param trackId the id of the track it belongs to * @return a filled in ContentValues object */ private static ContentValues createContentValues( Location location, long trackId) { ContentValues values = new ContentValues(); values.put(TrackPointsColumns.TRACKID, trackId); values.put(TrackPointsColumns.LATITUDE, (int) (location.getLatitude() * 1E6)); values.put(TrackPointsColumns.LONGITUDE, (int) (location.getLongitude() * 1E6)); // This is an ugly hack for Samsung phones that don't properly populate the // time field. values.put(TrackPointsColumns.TIME, (location.getTime() == 0) ? System.currentTimeMillis() : location.getTime()); if (location.hasAltitude()) { values.put(TrackPointsColumns.ALTITUDE, location.getAltitude()); } if (location.hasBearing()) { values.put(TrackPointsColumns.BEARING, location.getBearing()); } if (location.hasAccuracy()) { values.put(TrackPointsColumns.ACCURACY, location.getAccuracy()); } if (location.hasSpeed()) { values.put(TrackPointsColumns.SPEED, location.getSpeed()); } if (location instanceof MyTracksLocation) { MyTracksLocation mtLocation = (MyTracksLocation) location; if (mtLocation.getSensorDataSet() != null) { values.put(TrackPointsColumns.SENSOR, mtLocation.getSensorDataSet().toByteArray()); } } return values; } @Override public ContentValues createContentValues(Track track) { ContentValues values = new ContentValues(); TripStatistics stats = track.getStatistics(); // Values id < 0 indicate no id is available: if (track.getId() >= 0) { values.put(TracksColumns._ID, track.getId()); } values.put(TracksColumns.NAME, track.getName()); values.put(TracksColumns.DESCRIPTION, track.getDescription()); values.put(TracksColumns.MAPID, track.getMapId()); values.put(TracksColumns.TABLEID, track.getTableId()); values.put(TracksColumns.CATEGORY, track.getCategory()); values.put(TracksColumns.NUMPOINTS, track.getNumberOfPoints()); values.put(TracksColumns.STARTID, track.getStartId()); values.put(TracksColumns.STARTTIME, stats.getStartTime()); values.put(TracksColumns.STOPTIME, stats.getStopTime()); values.put(TracksColumns.STOPID, track.getStopId()); values.put(TracksColumns.TOTALDISTANCE, stats.getTotalDistance()); values.put(TracksColumns.TOTALTIME, stats.getTotalTime()); values.put(TracksColumns.MOVINGTIME, stats.getMovingTime()); values.put(TracksColumns.MAXLAT, stats.getTop()); values.put(TracksColumns.MINLAT, stats.getBottom()); values.put(TracksColumns.MAXLON, stats.getRight()); values.put(TracksColumns.MINLON, stats.getLeft()); values.put(TracksColumns.AVGSPEED, stats.getAverageSpeed()); values.put(TracksColumns.AVGMOVINGSPEED, stats.getAverageMovingSpeed()); values.put(TracksColumns.MAXSPEED, stats.getMaxSpeed()); values.put(TracksColumns.MINELEVATION, stats.getMinElevation()); values.put(TracksColumns.MAXELEVATION, stats.getMaxElevation()); values.put(TracksColumns.ELEVATIONGAIN, stats.getTotalElevationGain()); values.put(TracksColumns.MINGRADE, stats.getMinGrade()); values.put(TracksColumns.MAXGRADE, stats.getMaxGrade()); return values; } private static ContentValues createContentValues(Waypoint waypoint) { ContentValues values = new ContentValues(); // Values id < 0 indicate no id is available: if (waypoint.getId() >= 0) { values.put(WaypointsColumns._ID, waypoint.getId()); } values.put(WaypointsColumns.NAME, waypoint.getName()); values.put(WaypointsColumns.DESCRIPTION, waypoint.getDescription()); values.put(WaypointsColumns.CATEGORY, waypoint.getCategory()); values.put(WaypointsColumns.ICON, waypoint.getIcon()); values.put(WaypointsColumns.TRACKID, waypoint.getTrackId()); values.put(WaypointsColumns.TYPE, waypoint.getType()); values.put(WaypointsColumns.LENGTH, waypoint.getLength()); values.put(WaypointsColumns.DURATION, waypoint.getDuration()); values.put(WaypointsColumns.STARTID, waypoint.getStartId()); values.put(WaypointsColumns.STOPID, waypoint.getStopId()); TripStatistics stats = waypoint.getStatistics(); if (stats != null) { values.put(WaypointsColumns.TOTALDISTANCE, stats.getTotalDistance()); values.put(WaypointsColumns.TOTALTIME, stats.getTotalTime()); values.put(WaypointsColumns.MOVINGTIME, stats.getMovingTime()); values.put(WaypointsColumns.AVGSPEED, stats.getAverageSpeed()); values.put(WaypointsColumns.AVGMOVINGSPEED, stats.getAverageMovingSpeed()); values.put(WaypointsColumns.MAXSPEED, stats.getMaxSpeed()); values.put(WaypointsColumns.MINELEVATION, stats.getMinElevation()); values.put(WaypointsColumns.MAXELEVATION, stats.getMaxElevation()); values.put(WaypointsColumns.ELEVATIONGAIN, stats.getTotalElevationGain()); values.put(WaypointsColumns.MINGRADE, stats.getMinGrade()); values.put(WaypointsColumns.MAXGRADE, stats.getMaxGrade()); values.put(WaypointsColumns.STARTTIME, stats.getStartTime()); } Location location = waypoint.getLocation(); if (location != null) { values.put(WaypointsColumns.LATITUDE, (int) (location.getLatitude() * 1E6)); values.put(WaypointsColumns.LONGITUDE, (int) (location.getLongitude() * 1E6)); values.put(WaypointsColumns.TIME, location.getTime()); if (location.hasAltitude()) { values.put(WaypointsColumns.ALTITUDE, location.getAltitude()); } if (location.hasBearing()) { values.put(WaypointsColumns.BEARING, location.getBearing()); } if (location.hasAccuracy()) { values.put(WaypointsColumns.ACCURACY, location.getAccuracy()); } if (location.hasSpeed()) { values.put(WaypointsColumns.SPEED, location.getSpeed()); } } return values; } @Override public Location createLocation(Cursor cursor) { Location location = new MyTracksLocation(""); fillLocation(cursor, location); return location; } /** * A cache of track column indices. */ private static class CachedTrackColumnIndices { public final int idxId; public final int idxLatitude; public final int idxLongitude; public final int idxAltitude; public final int idxTime; public final int idxBearing; public final int idxAccuracy; public final int idxSpeed; public final int idxSensor; public CachedTrackColumnIndices(Cursor cursor) { idxId = cursor.getColumnIndex(TrackPointsColumns._ID); idxLatitude = cursor.getColumnIndexOrThrow(TrackPointsColumns.LATITUDE); idxLongitude = cursor.getColumnIndexOrThrow(TrackPointsColumns.LONGITUDE); idxAltitude = cursor.getColumnIndexOrThrow(TrackPointsColumns.ALTITUDE); idxTime = cursor.getColumnIndexOrThrow(TrackPointsColumns.TIME); idxBearing = cursor.getColumnIndexOrThrow(TrackPointsColumns.BEARING); idxAccuracy = cursor.getColumnIndexOrThrow(TrackPointsColumns.ACCURACY); idxSpeed = cursor.getColumnIndexOrThrow(TrackPointsColumns.SPEED); idxSensor = cursor.getColumnIndexOrThrow(TrackPointsColumns.SENSOR); } } private void fillLocation(Cursor cursor, CachedTrackColumnIndices columnIndices, Location location) { location.reset(); if (!cursor.isNull(columnIndices.idxLatitude)) { location.setLatitude(1. * cursor.getInt(columnIndices.idxLatitude) / 1E6); } if (!cursor.isNull(columnIndices.idxLongitude)) { location.setLongitude(1. * cursor.getInt(columnIndices.idxLongitude) / 1E6); } if (!cursor.isNull(columnIndices.idxAltitude)) { location.setAltitude(cursor.getFloat(columnIndices.idxAltitude)); } if (!cursor.isNull(columnIndices.idxTime)) { location.setTime(cursor.getLong(columnIndices.idxTime)); } if (!cursor.isNull(columnIndices.idxBearing)) { location.setBearing(cursor.getFloat(columnIndices.idxBearing)); } if (!cursor.isNull(columnIndices.idxSpeed)) { location.setSpeed(cursor.getFloat(columnIndices.idxSpeed)); } if (!cursor.isNull(columnIndices.idxAccuracy)) { location.setAccuracy(cursor.getFloat(columnIndices.idxAccuracy)); } if (location instanceof MyTracksLocation && !cursor.isNull(columnIndices.idxSensor)) { MyTracksLocation mtLocation = (MyTracksLocation) location; // TODO get the right buffer. Sensor.SensorDataSet sensorData; try { sensorData = Sensor.SensorDataSet.parseFrom(cursor.getBlob(columnIndices.idxSensor)); mtLocation.setSensorData(sensorData); } catch (InvalidProtocolBufferException e) { Log.w(TAG, "Failed to parse sensor data.", e); } } } @Override public void fillLocation(Cursor cursor, Location location) { CachedTrackColumnIndices columnIndicies = new CachedTrackColumnIndices(cursor); fillLocation(cursor, columnIndicies, location); } @Override public Track createTrack(Cursor cursor) { int idxId = cursor.getColumnIndexOrThrow(TracksColumns._ID); int idxName = cursor.getColumnIndexOrThrow(TracksColumns.NAME); int idxDescription = cursor.getColumnIndexOrThrow(TracksColumns.DESCRIPTION); int idxMapId = cursor.getColumnIndexOrThrow(TracksColumns.MAPID); int idxTableId = cursor.getColumnIndexOrThrow(TracksColumns.TABLEID); int idxCategory = cursor.getColumnIndexOrThrow(TracksColumns.CATEGORY); int idxStartId = cursor.getColumnIndexOrThrow(TracksColumns.STARTID); int idxStartTime = cursor.getColumnIndexOrThrow(TracksColumns.STARTTIME); int idxStopTime = cursor.getColumnIndexOrThrow(TracksColumns.STOPTIME); int idxStopId = cursor.getColumnIndexOrThrow(TracksColumns.STOPID); int idxNumPoints = cursor.getColumnIndexOrThrow(TracksColumns.NUMPOINTS); int idxMaxlat = cursor.getColumnIndexOrThrow(TracksColumns.MAXLAT); int idxMinlat = cursor.getColumnIndexOrThrow(TracksColumns.MINLAT); int idxMaxlon = cursor.getColumnIndexOrThrow(TracksColumns.MAXLON); int idxMinlon = cursor.getColumnIndexOrThrow(TracksColumns.MINLON); int idxTotalDistance = cursor.getColumnIndexOrThrow(TracksColumns.TOTALDISTANCE); int idxTotalTime = cursor.getColumnIndexOrThrow(TracksColumns.TOTALTIME); int idxMovingTime = cursor.getColumnIndexOrThrow(TracksColumns.MOVINGTIME); int idxMaxSpeed = cursor.getColumnIndexOrThrow(TracksColumns.MAXSPEED); int idxMinElevation = cursor.getColumnIndexOrThrow(TracksColumns.MINELEVATION); int idxMaxElevation = cursor.getColumnIndexOrThrow(TracksColumns.MAXELEVATION); int idxElevationGain = cursor.getColumnIndexOrThrow(TracksColumns.ELEVATIONGAIN); int idxMinGrade = cursor.getColumnIndexOrThrow(TracksColumns.MINGRADE); int idxMaxGrade = cursor.getColumnIndexOrThrow(TracksColumns.MAXGRADE); Track track = new Track(); TripStatistics stats = track.getStatistics(); if (!cursor.isNull(idxId)) { track.setId(cursor.getLong(idxId)); } if (!cursor.isNull(idxName)) { track.setName(cursor.getString(idxName)); } if (!cursor.isNull(idxDescription)) { track.setDescription(cursor.getString(idxDescription)); } if (!cursor.isNull(idxMapId)) { track.setMapId(cursor.getString(idxMapId)); } if (!cursor.isNull(idxTableId)) { track.setTableId(cursor.getString(idxTableId)); } if (!cursor.isNull(idxCategory)) { track.setCategory(cursor.getString(idxCategory)); } if (!cursor.isNull(idxStartId)) { track.setStartId(cursor.getInt(idxStartId)); } if (!cursor.isNull(idxStartTime)) { stats.setStartTime(cursor.getLong(idxStartTime)); } if (!cursor.isNull(idxStopTime)) { stats.setStopTime(cursor.getLong(idxStopTime)); } if (!cursor.isNull(idxStopId)) { track.setStopId(cursor.getInt(idxStopId)); } if (!cursor.isNull(idxNumPoints)) { track.setNumberOfPoints(cursor.getInt(idxNumPoints)); } if (!cursor.isNull(idxTotalDistance)) { stats.setTotalDistance(cursor.getFloat(idxTotalDistance)); } if (!cursor.isNull(idxTotalTime)) { stats.setTotalTime(cursor.getLong(idxTotalTime)); } if (!cursor.isNull(idxMovingTime)) { stats.setMovingTime(cursor.getLong(idxMovingTime)); } if (!cursor.isNull(idxMaxlat) && !cursor.isNull(idxMinlat) && !cursor.isNull(idxMaxlon) && !cursor.isNull(idxMinlon)) { int top = cursor.getInt(idxMaxlat); int bottom = cursor.getInt(idxMinlat); int right = cursor.getInt(idxMaxlon); int left = cursor.getInt(idxMinlon); stats.setBounds(left, top, right, bottom); } if (!cursor.isNull(idxMaxSpeed)) { stats.setMaxSpeed(cursor.getFloat(idxMaxSpeed)); } if (!cursor.isNull(idxMinElevation)) { stats.setMinElevation(cursor.getFloat(idxMinElevation)); } if (!cursor.isNull(idxMaxElevation)) { stats.setMaxElevation(cursor.getFloat(idxMaxElevation)); } if (!cursor.isNull(idxElevationGain)) { stats.setTotalElevationGain(cursor.getFloat(idxElevationGain)); } if (!cursor.isNull(idxMinGrade)) { stats.setMinGrade(cursor.getFloat(idxMinGrade)); } if (!cursor.isNull(idxMaxGrade)) { stats.setMaxGrade(cursor.getFloat(idxMaxGrade)); } return track; } @Override public Waypoint createWaypoint(Cursor cursor) { int idxId = cursor.getColumnIndexOrThrow(WaypointsColumns._ID); int idxName = cursor.getColumnIndexOrThrow(WaypointsColumns.NAME); int idxDescription = cursor.getColumnIndexOrThrow(WaypointsColumns.DESCRIPTION); int idxCategory = cursor.getColumnIndexOrThrow(WaypointsColumns.CATEGORY); int idxIcon = cursor.getColumnIndexOrThrow(WaypointsColumns.ICON); int idxTrackId = cursor.getColumnIndexOrThrow(WaypointsColumns.TRACKID); int idxType = cursor.getColumnIndexOrThrow(WaypointsColumns.TYPE); int idxLength = cursor.getColumnIndexOrThrow(WaypointsColumns.LENGTH); int idxDuration = cursor.getColumnIndexOrThrow(WaypointsColumns.DURATION); int idxStartTime = cursor.getColumnIndexOrThrow(WaypointsColumns.STARTTIME); int idxStartId = cursor.getColumnIndexOrThrow(WaypointsColumns.STARTID); int idxStopId = cursor.getColumnIndexOrThrow(WaypointsColumns.STOPID); int idxTotalDistance = cursor.getColumnIndexOrThrow(WaypointsColumns.TOTALDISTANCE); int idxTotalTime = cursor.getColumnIndexOrThrow(WaypointsColumns.TOTALTIME); int idxMovingTime = cursor.getColumnIndexOrThrow(WaypointsColumns.MOVINGTIME); int idxMaxSpeed = cursor.getColumnIndexOrThrow(WaypointsColumns.MAXSPEED); int idxMinElevation = cursor.getColumnIndexOrThrow(WaypointsColumns.MINELEVATION); int idxMaxElevation = cursor.getColumnIndexOrThrow(WaypointsColumns.MAXELEVATION); int idxElevationGain = cursor.getColumnIndexOrThrow(WaypointsColumns.ELEVATIONGAIN); int idxMinGrade = cursor.getColumnIndexOrThrow(WaypointsColumns.MINGRADE); int idxMaxGrade = cursor.getColumnIndexOrThrow(WaypointsColumns.MAXGRADE); int idxLatitude = cursor.getColumnIndexOrThrow(WaypointsColumns.LATITUDE); int idxLongitude = cursor.getColumnIndexOrThrow(WaypointsColumns.LONGITUDE); int idxAltitude = cursor.getColumnIndexOrThrow(WaypointsColumns.ALTITUDE); int idxTime = cursor.getColumnIndexOrThrow(WaypointsColumns.TIME); int idxBearing = cursor.getColumnIndexOrThrow(WaypointsColumns.BEARING); int idxAccuracy = cursor.getColumnIndexOrThrow(WaypointsColumns.ACCURACY); int idxSpeed = cursor.getColumnIndexOrThrow(WaypointsColumns.SPEED); Waypoint waypoint = new Waypoint(); if (!cursor.isNull(idxId)) { waypoint.setId(cursor.getLong(idxId)); } if (!cursor.isNull(idxName)) { waypoint.setName(cursor.getString(idxName)); } if (!cursor.isNull(idxDescription)) { waypoint.setDescription(cursor.getString(idxDescription)); } if (!cursor.isNull(idxCategory)) { waypoint.setCategory(cursor.getString(idxCategory)); } if (!cursor.isNull(idxIcon)) { waypoint.setIcon(cursor.getString(idxIcon)); } if (!cursor.isNull(idxTrackId)) { waypoint.setTrackId(cursor.getLong(idxTrackId)); } if (!cursor.isNull(idxType)) { waypoint.setType(cursor.getInt(idxType)); } if (!cursor.isNull(idxLength)) { waypoint.setLength(cursor.getDouble(idxLength)); } if (!cursor.isNull(idxDuration)) { waypoint.setDuration(cursor.getLong(idxDuration)); } if (!cursor.isNull(idxStartId)) { waypoint.setStartId(cursor.getLong(idxStartId)); } if (!cursor.isNull(idxStopId)) { waypoint.setStopId(cursor.getLong(idxStopId)); } TripStatistics stats = new TripStatistics(); boolean hasStats = false; if (!cursor.isNull(idxStartTime)) { stats.setStartTime(cursor.getLong(idxStartTime)); hasStats = true; } if (!cursor.isNull(idxTotalDistance)) { stats.setTotalDistance(cursor.getFloat(idxTotalDistance)); hasStats = true; } if (!cursor.isNull(idxTotalTime)) { stats.setTotalTime(cursor.getLong(idxTotalTime)); hasStats = true; } if (!cursor.isNull(idxMovingTime)) { stats.setMovingTime(cursor.getLong(idxMovingTime)); hasStats = true; } if (!cursor.isNull(idxMaxSpeed)) { stats.setMaxSpeed(cursor.getFloat(idxMaxSpeed)); hasStats = true; } if (!cursor.isNull(idxMinElevation)) { stats.setMinElevation(cursor.getFloat(idxMinElevation)); hasStats = true; } if (!cursor.isNull(idxMaxElevation)) { stats.setMaxElevation(cursor.getFloat(idxMaxElevation)); hasStats = true; } if (!cursor.isNull(idxElevationGain)) { stats.setTotalElevationGain(cursor.getFloat(idxElevationGain)); hasStats = true; } if (!cursor.isNull(idxMinGrade)) { stats.setMinGrade(cursor.getFloat(idxMinGrade)); hasStats = true; } if (!cursor.isNull(idxMaxGrade)) { stats.setMaxGrade(cursor.getFloat(idxMaxGrade)); hasStats = true; } if (hasStats) { waypoint.setStatistics(stats); } Location location = new Location(""); if (!cursor.isNull(idxLatitude) && !cursor.isNull(idxLongitude)) { location.setLatitude(1. * cursor.getInt(idxLatitude) / 1E6); location.setLongitude(1. * cursor.getInt(idxLongitude) / 1E6); } if (!cursor.isNull(idxAltitude)) { location.setAltitude(cursor.getFloat(idxAltitude)); } if (!cursor.isNull(idxTime)) { location.setTime(cursor.getLong(idxTime)); } if (!cursor.isNull(idxBearing)) { location.setBearing(cursor.getFloat(idxBearing)); } if (!cursor.isNull(idxSpeed)) { location.setSpeed(cursor.getFloat(idxSpeed)); } if (!cursor.isNull(idxAccuracy)) { location.setAccuracy(cursor.getFloat(idxAccuracy)); } waypoint.setLocation(location); return waypoint; } @Override public void deleteAllTracks() { contentResolver.delete(TracksColumns.CONTENT_URI, null, null); contentResolver.delete(TrackPointsColumns.CONTENT_URI, null, null); contentResolver.delete(WaypointsColumns.CONTENT_URI, null, null); } @Override public void deleteTrack(long trackId) { Track track = getTrack(trackId); if (track != null) { contentResolver.delete(TrackPointsColumns.CONTENT_URI, "_id>=" + track.getStartId() + " AND _id<=" + track.getStopId(), null); } contentResolver.delete(WaypointsColumns.CONTENT_URI, WaypointsColumns.TRACKID + "=" + trackId, null); contentResolver.delete( TracksColumns.CONTENT_URI, "_id=" + trackId, null); } @Override public void deleteWaypoint(long waypointId, DescriptionGenerator descriptionGenerator) { final Waypoint deletedWaypoint = getWaypoint(waypointId); if (deletedWaypoint != null && deletedWaypoint.getType() == Waypoint.TYPE_STATISTICS) { final Waypoint nextWaypoint = getNextStatisticsWaypointAfter(deletedWaypoint); if (nextWaypoint != null) { Log.d(TAG, "Correcting marker " + nextWaypoint.getId() + " after deleted marker " + deletedWaypoint.getId()); nextWaypoint.getStatistics().merge(deletedWaypoint.getStatistics()); nextWaypoint.setDescription( descriptionGenerator.generateWaypointDescription(nextWaypoint)); if (!updateWaypoint(nextWaypoint)) { Log.w(TAG, "Update of marker was unsuccessful."); } } else { Log.d(TAG, "No statistics marker after the deleted one was found."); } } contentResolver.delete( WaypointsColumns.CONTENT_URI, "_id=" + waypointId, null); } @Override public Waypoint getNextStatisticsWaypointAfter(Waypoint waypoint) { final String selection = WaypointsColumns._ID + ">" + waypoint.getId() + " AND " + WaypointsColumns.TRACKID + "=" + waypoint.getTrackId() + " AND " + WaypointsColumns.TYPE + "=" + Waypoint.TYPE_STATISTICS; final String sortOrder = WaypointsColumns._ID + " LIMIT 1"; Cursor cursor = null; try { cursor = contentResolver.query( WaypointsColumns.CONTENT_URI, null /*projection*/, selection, null /*selectionArgs*/, sortOrder); if (cursor != null && cursor.moveToFirst()) { return createWaypoint(cursor); } } catch (RuntimeException e) { Log.w(TAG, "Caught unexpected exception.", e); } finally { if (cursor != null) { cursor.close(); } } return null; } @Override public boolean updateWaypoint(Waypoint waypoint) { try { final int rows = contentResolver.update( WaypointsColumns.CONTENT_URI, createContentValues(waypoint), "_id=" + waypoint.getId(), null /*selectionArgs*/); return rows == 1; } catch (RuntimeException e) { Log.e(TAG, "Caught unexpected exception.", e); } return false; } /** * Finds a locations from the provider by the given selection. * * @param select a selection argument that identifies a unique location * @return the fist location matching, or null if not found */ private Location findLocationBy(String select) { Cursor cursor = null; try { cursor = contentResolver.query( TrackPointsColumns.CONTENT_URI, null, select, null, null); if (cursor != null && cursor.moveToNext()) { return createLocation(cursor); } } catch (RuntimeException e) { Log.w(TAG, "Caught an unexpeceted exception.", e); } finally { if (cursor != null) { cursor.close(); } } return null; } /** * Finds a track from the provider by the given selection. * * @param select a selection argument that identifies a unique track * @return the first track matching, or null if not found */ private Track findTrackBy(String select) { Cursor cursor = null; try { cursor = contentResolver.query( TracksColumns.CONTENT_URI, null, select, null, null); if (cursor != null && cursor.moveToNext()) { return createTrack(cursor); } } catch (RuntimeException e) { Log.w(TAG, "Caught unexpected exception.", e); } finally { if (cursor != null) { cursor.close(); } } return null; } @Override public Location getLastLocation() { return findLocationBy("_id=(select max(_id) from trackpoints)"); } @Override public Waypoint getFirstWaypoint(long trackId) { if (trackId < 0) { return null; } Cursor cursor = contentResolver.query( WaypointsColumns.CONTENT_URI, null /*projection*/, "trackid=" + trackId, null /*selectionArgs*/, "_id LIMIT 1"); if (cursor != null) { try { if (cursor.moveToFirst()) { return createWaypoint(cursor); } } catch (RuntimeException e) { Log.w(TAG, "Caught an unexpected exception.", e); } finally { cursor.close(); } } return null; } @Override public Waypoint getWaypoint(long waypointId) { if (waypointId < 0) { return null; } Cursor cursor = contentResolver.query( WaypointsColumns.CONTENT_URI, null /*projection*/, "_id=" + waypointId, null /*selectionArgs*/, null /*sortOrder*/); if (cursor != null) { try { if (cursor.moveToFirst()) { return createWaypoint(cursor); } } catch (RuntimeException e) { Log.w(TAG, "Caught an unexpected exception.", e); } finally { cursor.close(); } } return null; } @Override public long getLastLocationId(long trackId) { if (trackId < 0) { return -1; } final String[] projection = {"_id"}; Cursor cursor = contentResolver.query( TrackPointsColumns.CONTENT_URI, projection, "_id=(select max(_id) from trackpoints WHERE trackid=" + trackId + ")", null /*selectionArgs*/, null /*sortOrder*/); if (cursor != null) { try { if (cursor.moveToFirst()) { return cursor.getLong( cursor.getColumnIndexOrThrow(TrackPointsColumns._ID)); } } catch (RuntimeException e) { Log.w(TAG, "Caught an unexpected exception.", e); } finally { cursor.close(); } } return -1; } @Override public long getFirstWaypointId(long trackId) { if (trackId < 0) { return -1; } final String[] projection = {"_id"}; Cursor cursor = contentResolver.query( WaypointsColumns.CONTENT_URI, projection, "trackid=" + trackId, null /*selectionArgs*/, "_id LIMIT 1" /*sortOrder*/); if (cursor != null) { try { if (cursor.moveToFirst()) { return cursor.getLong( cursor.getColumnIndexOrThrow(WaypointsColumns._ID)); } } catch (RuntimeException e) { Log.w(TAG, "Caught an unexpected exception.", e); } finally { cursor.close(); } } return -1; } @Override public long getLastWaypointId(long trackId) { if (trackId < 0) { return -1; } final String[] projection = {"_id"}; Cursor cursor = contentResolver.query( WaypointsColumns.CONTENT_URI, projection, WaypointsColumns.TRACKID + "=" + trackId, null /*selectionArgs*/, "_id DESC LIMIT 1" /*sortOrder*/); if (cursor != null) { try { if (cursor.moveToFirst()) { return cursor.getLong( cursor.getColumnIndexOrThrow(WaypointsColumns._ID)); } } catch (RuntimeException e) { Log.w(TAG, "Caught an unexpected exception.", e); } finally { cursor.close(); } } return -1; } @Override public Track getLastTrack() { Cursor cursor = null; try { cursor = contentResolver.query( TracksColumns.CONTENT_URI, null, "_id=(select max(_id) from tracks)", null, null); if (cursor != null && cursor.moveToNext()) { return createTrack(cursor); } } catch (RuntimeException e) { Log.w(TAG, "Caught an unexpected exception.", e); } finally { if (cursor != null) { cursor.close(); } } return null; } @Override public long getLastTrackId() { String[] proj = { TracksColumns._ID }; Cursor cursor = contentResolver.query( TracksColumns.CONTENT_URI, proj, "_id=(select max(_id) from tracks)", null, null); if (cursor != null) { try { if (cursor.moveToFirst()) { return cursor.getLong( cursor.getColumnIndexOrThrow(TracksColumns._ID)); } } finally { cursor.close(); } } return -1; } @Override public Location getLocation(long id) { if (id < 0) { return null; } String selection = TrackPointsColumns._ID + "=" + id; return findLocationBy(selection); } @Override public Cursor getLocationsCursor(long trackId, long minTrackPointId, int maxLocations, boolean descending) { if (trackId < 0) { return null; } String selection; String[] selectionArgs; if (minTrackPointId >= 0) { String comparison = descending ? "<=" : ">="; selection = TrackPointsColumns.TRACKID + "=? AND " + TrackPointsColumns._ID + comparison + "?"; selectionArgs = new String[] { String.valueOf(trackId), String.valueOf(minTrackPointId) }; } else { selection = TrackPointsColumns.TRACKID + "=?"; selectionArgs = new String[] { String.valueOf(trackId) }; } String sortOrder = "_id " + (descending ? "DESC" : "ASC"); if (maxLocations > 0) { sortOrder += " LIMIT " + maxLocations; } return contentResolver.query(TrackPointsColumns.CONTENT_URI, null, selection, selectionArgs, sortOrder); } @Override public Cursor getWaypointsCursor(long trackId, long minWaypointId, int maxWaypoints) { if (trackId < 0) { return null; } String selection; String[] selectionArgs; if (minWaypointId > 0) { selection = String.format("%s = ? AND %s >= ?", WaypointsColumns.TRACKID, WaypointsColumns._ID); selectionArgs = new String[] { Long.toString(trackId), Long.toString(minWaypointId) }; } else { selection = String.format("%s=?", WaypointsColumns.TRACKID); selectionArgs = new String[] { Long.toString(trackId) }; } return getWaypointsCursor(selection, selectionArgs, null, maxWaypoints); } @Override public Cursor getWaypointsCursor(String selection, String[] selectionArgs, String order, int maxWaypoints) { if (order == null) { order = "_id ASC"; } if (maxWaypoints > 0) { order += " LIMIT " + maxWaypoints; } return contentResolver.query( WaypointsColumns.CONTENT_URI, null, selection, selectionArgs, order); } @Override public Track getTrack(long id) { if (id < 0) { return null; } String select = TracksColumns._ID + "=" + id; return findTrackBy(select); } @Override public List<Track> getAllTracks() { Cursor cursor = getTracksCursor(null, null, TracksColumns._ID); ArrayList<Track> tracks = new ArrayList<Track>(); if (cursor != null) { tracks.ensureCapacity(cursor.getCount()); if (cursor.moveToFirst()) { do { tracks.add(createTrack(cursor)); } while(cursor.moveToNext()); } cursor.close(); } return tracks; } @Override public Cursor getTracksCursor(String selection, String[] selectionArgs, String order) { return contentResolver.query( TracksColumns.CONTENT_URI, null, selection, selectionArgs, order); } @Override public Uri insertTrack(Track track) { Log.d(TAG, "MyTracksProviderUtilsImpl.insertTrack"); return contentResolver.insert(TracksColumns.CONTENT_URI, createContentValues(track)); } @Override public Uri insertTrackPoint(Location location, long trackId) { Log.d(TAG, "MyTracksProviderUtilsImpl.insertTrackPoint"); return contentResolver.insert(TrackPointsColumns.CONTENT_URI, createContentValues(location, trackId)); } @Override public int bulkInsertTrackPoints(Location[] locations, int length, long trackId) { if (length == -1) { length = locations.length; } ContentValues[] values = new ContentValues[length]; for (int i = 0; i < length; i++) { values[i] = createContentValues(locations[i], trackId); } return contentResolver.bulkInsert(TrackPointsColumns.CONTENT_URI, values); } @Override public Uri insertWaypoint(Waypoint waypoint) { Log.d(TAG, "MyTracksProviderUtilsImpl.insertWaypoint"); waypoint.setId(-1); return contentResolver.insert(WaypointsColumns.CONTENT_URI, createContentValues(waypoint)); } @Override public boolean trackExists(long id) { if (id < 0) { return false; } Cursor cursor = null; try { final String[] projection = { TracksColumns._ID }; cursor = contentResolver.query( TracksColumns.CONTENT_URI, projection, TracksColumns._ID + "=" + id/*selection*/, null/*selectionArgs*/, null/*sortOrder*/); if (cursor != null && cursor.moveToNext()) { return true; } } finally { if (cursor != null) { cursor.close(); } } return false; } @Override public void updateTrack(Track track) { Log.d(TAG, "MyTracksProviderUtilsImpl.updateTrack"); contentResolver.update(TracksColumns.CONTENT_URI, createContentValues(track), "_id=" + track.getId(), null); } @Override public LocationIterator getLocationIterator(final long trackId, final long startTrackPointId, final boolean descending, final LocationFactory locationFactory) { if (locationFactory == null) { throw new IllegalArgumentException("Expecting non-null locationFactory"); } return new LocationIterator() { private long lastTrackPointId = startTrackPointId; private Cursor cursor = getCursor(startTrackPointId); private final CachedTrackColumnIndices columnIndices = cursor != null ? new CachedTrackColumnIndices(cursor) : null; private Cursor getCursor(long trackPointId) { return getLocationsCursor(trackId, trackPointId, defaultCursorBatchSize, descending); } private boolean advanceCursorToNextBatch() { long pointId = lastTrackPointId + (descending ? -1 : 1); Log.d(TAG, "Advancing cursor point ID: " + pointId); cursor.close(); cursor = getCursor(pointId); return cursor != null; } @Override public long getLocationId() { return lastTrackPointId; } @Override public boolean hasNext() { if (cursor == null) { return false; } if (cursor.isAfterLast()) { return false; } if (cursor.isLast()) { // If the current batch size was less that max, we can safely return, otherwise // we need to advance to the next batch. return cursor.getCount() == defaultCursorBatchSize && advanceCursorToNextBatch() && !cursor.isAfterLast(); } return true; } @Override public Location next() { if (cursor == null || !(cursor.moveToNext() || advanceCursorToNextBatch() || cursor.moveToNext())) { throw new NoSuchElementException(); } lastTrackPointId = cursor.getLong(columnIndices.idxId); Location location = locationFactory.createLocation(); fillLocation(cursor, columnIndices, location); return location; } @Override public void close() { if (cursor != null) { cursor.close(); cursor = null; } } @Override public void remove() { throw new UnsupportedOperationException(); } }; } // @VisibleForTesting void setDefaultCursorBatchSize(int defaultCursorBatchSize) { this.defaultCursorBatchSize = defaultCursorBatchSize; } }
Java
/* * Copyright 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.content; import android.net.Uri; import android.provider.BaseColumns; /** * Defines the URI for the tracks provider and the available column names * and content types. * * @author Leif Hendrik Wilden */ public interface WaypointsColumns extends BaseColumns { public static final Uri CONTENT_URI = Uri.parse("content://com.google.android.maps.mytracks/waypoints"); public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.google.waypoint"; public static final String CONTENT_ITEMTYPE = "vnd.android.cursor.item/vnd.google.waypoint"; public static final String DEFAULT_SORT_ORDER = "_id"; /* All columns */ public static final String NAME = "name"; public static final String DESCRIPTION = "description"; public static final String CATEGORY = "category"; public static final String ICON = "icon"; public static final String TRACKID = "trackid"; public static final String TYPE = "type"; public static final String LENGTH = "length"; public static final String DURATION = "duration"; public static final String STARTTIME = "starttime"; public static final String STARTID = "startid"; public static final String STOPID = "stopid"; public static final String LATITUDE = "latitude"; public static final String LONGITUDE = "longitude"; public static final String ALTITUDE = "elevation"; public static final String BEARING = "bearing"; public static final String TIME = "time"; public static final String ACCURACY = "accuracy"; public static final String SPEED = "speed"; public static final String TOTALDISTANCE = "totaldistance"; public static final String TOTALTIME = "totaltime"; public static final String MOVINGTIME = "movingtime"; public static final String AVGSPEED = "avgspeed"; public static final String AVGMOVINGSPEED = "avgmovingspeed"; public static final String MAXSPEED = "maxspeed"; public static final String MINELEVATION = "minelevation"; public static final String MAXELEVATION = "maxelevation"; public static final String ELEVATIONGAIN = "elevationgain"; public static final String MINGRADE = "mingrade"; public static final String MAXGRADE = "maxgrade"; }
Java
/* * Copyright 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.content; import android.net.Uri; import android.provider.BaseColumns; /** * Defines the URI for the tracks provider and the available column names * and content types. * * @author Leif Hendrik Wilden */ public interface TracksColumns extends BaseColumns { public static final Uri CONTENT_URI = Uri.parse("content://com.google.android.maps.mytracks/tracks"); public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.google.track"; public static final String CONTENT_ITEMTYPE = "vnd.android.cursor.item/vnd.google.track"; public static final String DEFAULT_SORT_ORDER = "_id"; /* All columns */ public static final String NAME = "name"; public static final String DESCRIPTION = "description"; public static final String CATEGORY = "category"; public static final String STARTID = "startid"; public static final String STOPID = "stopid"; public static final String STARTTIME = "starttime"; public static final String STOPTIME = "stoptime"; public static final String NUMPOINTS = "numpoints"; public static final String TOTALDISTANCE = "totaldistance"; public static final String TOTALTIME = "totaltime"; public static final String MOVINGTIME = "movingtime"; public static final String AVGSPEED = "avgspeed"; public static final String AVGMOVINGSPEED = "avgmovingspeed"; public static final String MAXSPEED = "maxspeed"; public static final String MINELEVATION = "minelevation"; public static final String MAXELEVATION = "maxelevation"; public static final String ELEVATIONGAIN = "elevationgain"; public static final String MINGRADE = "mingrade"; public static final String MAXGRADE = "maxgrade"; public static final String MINLAT = "minlat"; public static final String MAXLAT = "maxlat"; public static final String MINLON = "minlon"; public static final String MAXLON = "maxlon"; public static final String MAPID = "mapid"; public static final String TABLEID = "tableid"; }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.content; import java.util.Vector; /** * An interface for an object that can generate descriptions of track and * waypoint. * * @author Sandor Dornbush */ public interface DescriptionGenerator { /** * Generates a track description. * * @param track the track * @param distances a vector of distances to generate the elevation chart * @param elevations a vector of elevations to generate the elevation chart */ public String generateTrackDescription( Track track, Vector<Double> distances, Vector<Double> elevations); /** * Generate a waypoint description. * * @param waypoint the waypoint */ public String generateWaypointDescription(Waypoint waypoint); }
Java
/* * Copyright 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.content; import com.google.android.apps.mytracks.stats.TripStatistics; import android.location.Location; import android.os.Parcel; import android.os.Parcelable; /** * A way point. It has a location, meta data such as name, description, * category, and icon, plus it can store track statistics for a "sub-track". * * TODO: hashCode and equals * * @author Leif Hendrik Wilden * @author Rodrigo Damazio */ public final class Waypoint implements Parcelable { /** * Creator for a Waypoint object */ public static class Creator implements Parcelable.Creator<Waypoint> { public Waypoint createFromParcel(Parcel source) { ClassLoader classLoader = getClass().getClassLoader(); Waypoint waypoint = new Waypoint(); waypoint.id = source.readLong(); waypoint.name = source.readString(); waypoint.description = source.readString(); waypoint.category = source.readString(); waypoint.icon = source.readString(); waypoint.trackId = source.readLong(); waypoint.type = source.readInt(); waypoint.startId = source.readLong(); waypoint.stopId = source.readLong(); byte hasStats = source.readByte(); if (hasStats > 0) { waypoint.stats = source.readParcelable(classLoader); } byte hasLocation = source.readByte(); if (hasLocation > 0) { waypoint.location = source.readParcelable(classLoader); } return waypoint; } public Waypoint[] newArray(int size) { return new Waypoint[size]; } } public static final Creator CREATOR = new Creator(); public static final int TYPE_WAYPOINT = 0; public static final int TYPE_STATISTICS = 1; private long id = -1; private String name = ""; private String description = ""; private String category = ""; private String icon = ""; private long trackId = -1; private int type = 0; private Location location; /** Start track point id */ private long startId = -1; /** Stop track point id */ private long stopId = -1; private TripStatistics stats; /** The length of the track, without smoothing. */ private double length; /** The total duration of the track (not from the last waypoint) */ private long duration; public void writeToParcel(Parcel dest, int flags) { dest.writeLong(id); dest.writeString(name); dest.writeString(description); dest.writeString(category); dest.writeString(icon); dest.writeLong(trackId); dest.writeInt(type); dest.writeLong(startId); dest.writeLong(stopId); dest.writeByte(stats == null ? (byte) 0 : (byte) 1); if (stats != null) { dest.writeParcelable(stats, 0); } dest.writeByte(location == null ? (byte) 0 : (byte) 1); if (location != null) { dest.writeParcelable(location, 0); } } // Getters and setters: //--------------------- public String getIcon() { return icon; } public void setIcon(String icon) { this.icon = icon; } public Location getLocation() { return location; } public void setTrackId(long trackId) { this.trackId = trackId; } public int describeContents() { return 0; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public long getTrackId() { return trackId; } public int getType() { return type; } public void setType(int type) { this.type = type; } public long getStartId() { return startId; } public void setStartId(long startId) { this.startId = startId; } public long getStopId() { return stopId; } public void setStopId(long stopId) { this.stopId = stopId; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public void setLocation(Location location) { this.location = location; } public TripStatistics getStatistics() { return stats; } public void setStatistics(TripStatistics stats) { this.stats = stats; } // WARNING: These fields are used for internal state keeping. You probably // want to look at getStatistics instead. public double getLength() { return length; } public void setLength(double length) { this.length = length; } public long getDuration() { return duration; } public void setDuration(long duration) { this.duration = duration; } }
Java
/* * Copyright 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.content; import com.google.android.apps.mytracks.stats.TripStatistics; import android.location.Location; import android.os.Parcel; import android.os.Parcelable; import java.util.ArrayList; /** * A class representing a (GPS) Track. * * TODO: hashCode and equals * * @author Leif Hendrik Wilden * @author Rodrigo Damazio */ public class Track implements Parcelable { /** * Creator for a Track object. */ public static class Creator implements Parcelable.Creator<Track> { public Track createFromParcel(Parcel source) { ClassLoader classLoader = getClass().getClassLoader(); Track track = new Track(); track.id = source.readLong(); track.name = source.readString(); track.description = source.readString(); track.mapId = source.readString(); track.category = source.readString(); track.startId = source.readLong(); track.stopId = source.readLong(); track.stats = source.readParcelable(classLoader); track.numberOfPoints = source.readInt(); for (int i = 0; i < track.numberOfPoints; ++i) { Location loc = source.readParcelable(classLoader); track.locations.add(loc); } track.tableId = source.readString(); return track; } public Track[] newArray(int size) { return new Track[size]; } } public static final Creator CREATOR = new Creator(); /** * The track points (which may not have been loaded). */ private ArrayList<Location> locations = new ArrayList<Location>(); /** * The number of location points (present even if the points themselves were * not loaded). */ private int numberOfPoints = 0; private long id = -1; private String name = ""; private String description = ""; private String mapId = ""; private String tableId = ""; private long startId = -1; private long stopId = -1; private String category = ""; private TripStatistics stats = new TripStatistics(); public Track() { } public void writeToParcel(Parcel dest, int flags) { dest.writeLong(id); dest.writeString(name); dest.writeString(description); dest.writeString(mapId); dest.writeString(category); dest.writeLong(startId); dest.writeLong(stopId); dest.writeParcelable(stats, 0); dest.writeInt(numberOfPoints); for (int i = 0; i < numberOfPoints; ++i) { dest.writeParcelable(locations.get(i), 0); } dest.writeString(tableId); } // Getters and setters: //--------------------- public int describeContents() { return 0; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public long getStartId() { return startId; } public void setStartId(long startId) { this.startId = startId; } public long getStopId() { return stopId; } public void setStopId(long stopId) { this.stopId = stopId; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getMapId() { return mapId; } public void setMapId(String mapId) { this.mapId = mapId; } public String getTableId() { return tableId; } public void setTableId(String tableId) { this.tableId = tableId; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public int getNumberOfPoints() { return numberOfPoints; } public void setNumberOfPoints(int numberOfPoints) { this.numberOfPoints = numberOfPoints; } public void addLocation(Location l) { locations.add(l); } public ArrayList<Location> getLocations() { return locations; } public void setLocations(ArrayList<Location> locations) { this.locations = locations; } public TripStatistics getStatistics() { return stats; } public void setStatistics(TripStatistics stats) { this.stats = stats; } }
Java
/* * Copyright 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.content; import android.net.Uri; import android.provider.BaseColumns; /** * Defines the URI for the track points provider and the available column names * and content types. * * @author Leif Hendrik Wilden */ public interface TrackPointsColumns extends BaseColumns { public static final Uri CONTENT_URI = Uri.parse("content://com.google.android.maps.mytracks/trackpoints"); public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.google.trackpoint"; public static final String CONTENT_ITEMTYPE = "vnd.android.cursor.item/vnd.google.trackpoint"; public static final String DEFAULT_SORT_ORDER = "_id"; /* All columns */ public static final String TRACKID = "trackid"; public static final String LATITUDE = "latitude"; public static final String LONGITUDE = "longitude"; public static final String ALTITUDE = "elevation"; public static final String BEARING = "bearing"; public static final String TIME = "time"; public static final String ACCURACY = "accuracy"; public static final String SPEED = "speed"; public static final String SENSOR = "sensor"; }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.content; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.location.Location; import android.net.Uri; import java.util.Iterator; import java.util.List; /** * Utility to access data from the mytracks content provider. * * @author Rodrigo Damazio */ public interface MyTracksProviderUtils { /** * Authority (first part of URI) for the MyTracks content provider: */ public static final String AUTHORITY = "com.google.android.maps.mytracks"; /** * Deletes all tracks (including track points) from the provider. */ void deleteAllTracks(); /** * Deletes a track with the given track id. * * @param trackId the unique track id */ void deleteTrack(long trackId); /** * Deletes a way point with the given way point id. * This will also correct the next statistics way point after the deleted one * to reflect the deletion. * The generator is needed to stitch together statistics waypoints. * * @param waypointId the unique way point id * @param descriptionGenerator the class to generate descriptions */ void deleteWaypoint(long waypointId, DescriptionGenerator descriptionGenerator); /** * Finds the next statistics waypoint after the given waypoint. * * @param waypoint a given waypoint * @return the next statistics waypoint, or null if none found. */ Waypoint getNextStatisticsWaypointAfter(Waypoint waypoint); /** * Updates the waypoint in the provider. * * @param waypoint * @return true if successful */ boolean updateWaypoint(Waypoint waypoint); /** * Finds the last recorded location from the location provider. * * @return the last location, or null if no locations available */ Location getLastLocation(); /** * Finds the first recorded waypoint for a given track from the location * provider. * This is a special waypoint that holds the stats for current segment. * * @param trackId the id of the track the waypoint belongs to * @return the first waypoint, or null if no waypoints available */ Waypoint getFirstWaypoint(long trackId); /** * Finds the given waypoint from the location provider. * * @param waypointId * @return the waypoint, or null if it does not exist */ Waypoint getWaypoint(long waypointId); /** * Finds the last recorded location id from the track points provider. * * @param trackId find last location on this track * @return the location id, or -1 if no locations available */ long getLastLocationId(long trackId); /** * Finds the id of the 1st waypoint for a given track. * The 1st waypoint is special as it contains the stats for the current * segment. * * @param trackId find last location on this track * @return the waypoint id, or -1 if no waypoints are available */ long getFirstWaypointId(long trackId); /** * Finds the id of the 1st waypoint for a given track. * The 1st waypoint is special as it contains the stats for the current * segment. * * @param trackId find last location on this track * @return the waypoint id, or -1 if no waypoints are available */ long getLastWaypointId(long trackId); /** * Finds the last recorded track from the track provider. * * @return the last track, or null if no tracks available */ Track getLastTrack(); /** * Finds the last recorded track id from the tracks provider. * * @return the track id, or -1 if no tracks available */ long getLastTrackId(); /** * Finds a location by given unique id. * * @param id the desired id * @return a Location object, or null if not found */ Location getLocation(long id); /** * Creates a cursor over the locations in the track points provider which * iterates over a given range of unique ids. * Caller owns the returned cursor and is responsible for closing it. * * @param trackId the id of the track for which to get the points * @param minTrackPointId the minimum id for the track points * @param maxLocations maximum number of locations retrieved * @param descending if true the results will be returned in descending id * order (latest location first) * @return A cursor over the selected range of locations */ Cursor getLocationsCursor(long trackId, long minTrackPointId, int maxLocations, boolean descending); /** * Creates a cursor over the waypoints of a track. * Caller owns the returned cursor and is responsible for closing it. * * @param trackId the id of the track for which to get the points * @param minWaypointId the minimum id for the track points * @param maxWaypoints the maximum number of waypoints to return * @return A cursor over the selected range of locations */ Cursor getWaypointsCursor(long trackId, long minWaypointId, int maxWaypoints); /** * Creates a cursor over waypoints with the given selection. * Caller owns the returned cursor and is responsible for closing it. * * @param selection a given selection * @param selectionArgs arguments for the given selection * @param order the order in which to return results * @param maxWaypoints the maximum number of waypoints to return * @return a cursor of the selected waypoints */ Cursor getWaypointsCursor(String selection, String[] selectionArgs, String order, int maxWaypoints); /** * Finds a track by given unique track id. * Note that the returned track object does not have any track points attached. * Use {@link #getLocationIterator(long, long, boolean, LocationFactory)} to load * the track points. * * @param id desired unique track id * @return a Track object, or null if not found */ Track getTrack(long id); /** * Retrieves all tracks without track points. If no tracks exist, an empty * list will be returned. Use {@link #getLocationIterator(long, long, boolean, LocationFactory)} * to load the track points. * * @return a list of all the recorded tracks */ List<Track> getAllTracks(); /** * Creates a cursor over the tracks provider with a given selection. * Caller owns the returned cursor and is responsible for closing it. * * @param selection a given selection * @param selectionArgs parameters for the given selection * @param order the order to return results in * @return a cursor of the selected tracks */ Cursor getTracksCursor(String selection, String[] selectionArgs, String order); /** * Inserts a track in the tracks provider. * Note: This does not insert any track points. * Use {@link #insertTrackPoint(Location, long)} to insert them. * * @param track the track to insert * @return the content provider URI for the inserted track */ Uri insertTrack(Track track); /** * Inserts a track point in the tracks provider. * * @param location the location to insert * @return the content provider URI for the inserted track point */ Uri insertTrackPoint(Location location, long trackId); /** * Inserts multiple track points in a single operation. * * @param locations an array of locations to insert * @param length the number of locations (from the beginning of the array) * to actually insert, or -1 for all of them * @param trackId the ID of the track to insert the points into * @return the number of points inserted */ int bulkInsertTrackPoints(Location[] locations, int length, long trackId); /** * Inserts a waypoint in the provider. * * @param waypoint the waypoint to insert * @return the content provider URI for the inserted track */ Uri insertWaypoint(Waypoint waypoint); /** * Tests if a track with given id exists. * * @param id the unique id * @return true if track exists */ boolean trackExists(long id); /** * Updates a track in the content provider. * Note: This will not update any track points. * * @param track a given track */ void updateTrack(Track track); /** * Creates a Track object from a given cursor. * * @param cursor a cursor pointing at a db or provider with tracks * @return a new Track object */ Track createTrack(Cursor cursor); /** * Creates the ContentValues for a given Track object. * * Note: If the track has an id<0 the id column will not be filled. * * @param track a given track object * @return a filled in ContentValues object */ ContentValues createContentValues(Track track); /** * Creates a location object from a given cursor. * * @param cursor a cursor pointing at a db or provider with locations * @return a new location object */ Location createLocation(Cursor cursor); /** * Fill a location object with values from a given cursor. * * @param cursor a cursor pointing at a db or provider with locations * @param location a location object to be overwritten */ void fillLocation(Cursor cursor, Location location); /** * Creates a waypoint object from a given cursor. * * @param cursor a cursor pointing at a db or provider with waypoints. * @return a new waypoint object */ Waypoint createWaypoint(Cursor cursor); /** * A lightweight wrapper around the original {@link Cursor} with a method to clean up. */ interface LocationIterator extends Iterator<Location> { /** * Returns ID of the most recently retrieved track point through a call to {@link #next()}. * * @return the ID of the most recent track point ID. */ long getLocationId(); /** * Should be called in case the underlying iterator hasn't reached the last record. * Calling it if it has reached the last record is a no-op. */ void close(); } /** * A factory for creating new {@class Location}s. */ interface LocationFactory { /** * Creates a new {@link Location} object to be populated from the underlying database record. * It's up to the implementing class to decide whether to create a new instance or reuse * existing to optimize for speed. * * @return a {@link Location} to be populated from the database. */ Location createLocation(); } /** * The default {@class Location}s factory, which creates a new location of 'gps' type. */ LocationFactory DEFAULT_LOCATION_FACTORY = new LocationFactory() { @Override public Location createLocation() { return new Location("gps"); } }; /** * A location factory which uses two location instances (one for the current location, * and one for the previous), useful when we need to keep the last location. */ public class DoubleBufferedLocationFactory implements LocationFactory { private final Location locs[] = new MyTracksLocation[] { new MyTracksLocation("gps"), new MyTracksLocation("gps") }; private int lastLoc = 0; @Override public Location createLocation() { lastLoc = (lastLoc + 1) % locs.length; return locs[lastLoc]; } } /** * Creates a new read-only iterator over all track points for the given track. It provides * a lightweight way of iterating over long tracks without failing due to the underlying cursor * limitations. Since it's a read-only iterator, {@link Iterator#remove()} always throws * {@class UnsupportedOperationException}. * * Each call to {@link LocationIterator#next()} may advance to the next DB record, and if so, * the iterator calls {@link LocationFactory#createLocation()} and populates it with information * retrieved from the record. * * When done with iteration, you must call {@link LocationIterator#close()} to make sure that all * resources are properly deallocated. * * Example use: * <code> * ... * LocationIterator it = providerUtils.getLocationIterator( * 1, MyTracksProviderUtils.DEFAULT_LOCATION_FACTORY); * try { * for (Location loc : it) { * ... // Do something useful with the location. * } * } finally { * it.close(); * } * ... * </code> * * @param trackId the ID of a track to retrieve locations for. * @param startTrackPointId the ID of the first track point to load, or -1 to start from * the first point. * @param descending if true the results will be returned in descending ID * order (latest location first). * @param locationFactory the factory for creating new locations. * * @return the read-only iterator over the given track's points. */ LocationIterator getLocationIterator(long trackId, long startTrackPointId, boolean descending, LocationFactory locationFactory); /** * A factory which can produce instances of {@link MyTracksProviderUtils}, * and can be overridden in tests (a.k.a. poor man's guice). */ public static class Factory { private static Factory instance = new Factory(); /** * Creates and returns an instance of {@link MyTracksProviderUtils} which * uses the given context to access its data. */ public static MyTracksProviderUtils get(Context context) { return instance.newForContext(context); } /** * Returns the global instance of this factory. */ public static Factory getInstance() { return instance; } /** * Overrides the global instance for this factory, to be used for testing. * If used, don't forget to set it back to the original value after the * test is run. */ public static void overrideInstance(Factory factory) { instance = factory; } /** * Creates an instance of {@link MyTracksProviderUtils}. */ protected MyTracksProviderUtils newForContext(Context context) { return new MyTracksProviderUtilsImpl(context.getContentResolver()); } } }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.content; import android.os.Parcel; import android.os.Parcelable; /** * A request for the service to create a waypoint at the current location. * * @author Sandor Dornbush */ public class WaypointCreationRequest implements Parcelable { public static enum WaypointType { MARKER, STATISTICS; } private WaypointType type; private String name; private String category; private String description; private String iconUrl; public final static WaypointCreationRequest DEFAULT_MARKER = new WaypointCreationRequest(WaypointType.MARKER); public final static WaypointCreationRequest DEFAULT_STATISTICS = new WaypointCreationRequest(WaypointType.STATISTICS); private WaypointCreationRequest(WaypointType type) { this.type = type; } public WaypointCreationRequest(WaypointType type, String name, String category, String description, String iconUrl) { this.type = type; this.name = name; this.category = category; this.description = description; this.iconUrl = iconUrl; } public static class Creator implements Parcelable.Creator<WaypointCreationRequest> { @Override public WaypointCreationRequest createFromParcel(Parcel source) { int i = source.readInt(); if (i > WaypointType.values().length) { throw new IllegalArgumentException("Could not find waypoint type: " + i); } WaypointCreationRequest request = new WaypointCreationRequest(WaypointType.values()[i]); request.name = source.readString(); request.category = source.readString(); request.description = source.readString(); request.iconUrl = source.readString(); return request; } public WaypointCreationRequest[] newArray(int size) { return new WaypointCreationRequest[size]; } } public static final Creator CREATOR = new Creator(); @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel parcel, int arg1) { parcel.writeInt(type.ordinal()); parcel.writeString(name); parcel.writeString(category); parcel.writeString(description); parcel.writeString(iconUrl); } public WaypointType getType() { return type; } public String getName() { return name; } public String getCategory() { return category; } public String getDescription() { return description; } public String getIconUrl() { return iconUrl; } }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.content; import android.location.Location; /** * This class extends the standard Android location with extra information. * * @author Sandor Dornbush */ public class MyTracksLocation extends Location { private Sensor.SensorDataSet sensorDataSet = null; /** * The id of this location from the provider. */ private int id = -1; public MyTracksLocation(Location location, Sensor.SensorDataSet sd) { super(location); this.sensorDataSet = sd; } public MyTracksLocation(String provider) { super(provider); } public Sensor.SensorDataSet getSensorDataSet() { return sensorDataSet; } public void setSensorData(Sensor.SensorDataSet sensorData) { this.sensorDataSet = sensorData; } public int getId() { return id; } public void setId(int id) { this.id = id; } public void reset() { super.reset(); sensorDataSet = null; id = -1; } }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.lib; /** * Constants for the My Tracks common library. * These constants should ideally not be used by third-party applications. * * @author Rodrigo Damazio */ public class MyTracksLibConstants { public static final String TAG = "MyTracksLib"; private MyTracksLibConstants() {} }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.signalstrength; import static com.google.android.apps.mytracks.signalstrength.SignalStrengthConstants.START_SAMPLING; import static com.google.android.apps.mytracks.signalstrength.SignalStrengthConstants.STOP_SAMPLING; import static com.google.android.apps.mytracks.signalstrength.SignalStrengthConstants.TAG; import com.google.android.apps.mytracks.content.WaypointCreationRequest; import com.google.android.apps.mytracks.services.ITrackRecordingService; import com.google.android.apps.mytracks.signalstrength.SignalStrengthListener.SignalStrengthCallback; import android.app.ActivityManager; import android.app.ActivityManager.RunningServiceInfo; import android.app.Service; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.os.IBinder; import android.os.RemoteException; import android.preference.PreferenceManager; import android.util.Log; import android.widget.Toast; import java.util.List; /** * Serivce which actually reads signal strength and sends it to My Tracks. * * @author Rodrigo Damazio */ public class SignalStrengthService extends Service implements ServiceConnection, SignalStrengthCallback, OnSharedPreferenceChangeListener { private ComponentName mytracksServiceComponent; private SharedPreferences preferences; private SignalStrengthListenerFactory signalListenerFactory; private SignalStrengthListener signalListener; private ITrackRecordingService mytracksService; private long lastSamplingTime; private long samplingPeriod; @Override public void onCreate() { super.onCreate(); mytracksServiceComponent = new ComponentName( getString(R.string.mytracks_service_package), getString(R.string.mytracks_service_class)); preferences = PreferenceManager.getDefaultSharedPreferences(this); signalListenerFactory = new SignalStrengthListenerFactory(); } @Override public void onStart(Intent intent, int startId) { handleCommand(intent); } @Override public int onStartCommand(Intent intent, int flags, int startId) { handleCommand(intent); return START_STICKY; } private void handleCommand(Intent intent) { String action = intent.getAction(); if (START_SAMPLING.equals(action)) { startSampling(); } else { stopSampling(); } } private void startSampling() { // TODO: Start foreground if (!isMytracksRunning()) { Log.w(TAG, "My Tracks not running!"); return; } Log.d(TAG, "Starting sampling"); Intent intent = new Intent(); intent.setComponent(mytracksServiceComponent); if (!bindService(intent, SignalStrengthService.this, 0)) { Log.e(TAG, "Couldn't bind to service."); return; } } private boolean isMytracksRunning() { ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE); List<RunningServiceInfo> services = activityManager.getRunningServices(Integer.MAX_VALUE); for (RunningServiceInfo serviceInfo : services) { if (serviceInfo.pid != 0 && serviceInfo.service.equals(mytracksServiceComponent)) { return true; } } return false; } @Override public void onServiceConnected(ComponentName name, IBinder service) { synchronized (this) { mytracksService = ITrackRecordingService.Stub.asInterface(service); Log.d(TAG, "Bound to My Tracks"); boolean recording = false; try { recording = mytracksService.isRecording(); } catch (RemoteException e) { Log.e(TAG, "Failed to talk to my tracks", e); } if (!recording) { Log.w(TAG, "My Tracks is not recording, bailing"); stopSampling(); return; } // We're ready to send waypoints, so register for signal sampling signalListener = signalListenerFactory.create(this, this); signalListener.register(); // Register for preference changes samplingPeriod = Long.parseLong(preferences.getString( getString(R.string.settings_min_signal_sampling_period_key), "-1")); preferences.registerOnSharedPreferenceChangeListener(this); // Tell the user we've started. Toast.makeText(this, R.string.started_sampling, Toast.LENGTH_SHORT).show(); } } @Override public void onSignalStrengthSampled(String description, String icon) { long now = System.currentTimeMillis(); if (now - lastSamplingTime < samplingPeriod * 60 * 1000) { return; } try { long waypointId; synchronized (this) { if (mytracksService == null) { Log.d(TAG, "No my tracks service to send to"); return; } // Create a waypoint. WaypointCreationRequest request = new WaypointCreationRequest(WaypointCreationRequest.WaypointType.MARKER, "Signal Strength", description, icon); waypointId = mytracksService.insertWaypoint(request); } if (waypointId >= 0) { Log.d(TAG, "Added signal marker"); lastSamplingTime = now; } else { Log.e(TAG, "Cannot insert waypoint marker?"); } } catch (RemoteException e) { Log.e(TAG, "Cannot talk to my tracks service", e); } } private void stopSampling() { Log.d(TAG, "Stopping sampling"); synchronized (this) { // Unregister from preference change updates preferences.unregisterOnSharedPreferenceChangeListener(this); // Unregister from receiving signal updates if (signalListener != null) { signalListener.unregister(); signalListener = null; } // Unbind from My Tracks if (mytracksService != null) { unbindService(this); mytracksService = null; } // Reset the last sampling time lastSamplingTime = 0; // Tell the user we've stopped Toast.makeText(this, R.string.stopped_sampling, Toast.LENGTH_SHORT).show(); // Stop stopSelf(); } } @Override public void onServiceDisconnected(ComponentName name) { Log.i(TAG, "Disconnected from My Tracks"); synchronized (this) { mytracksService = null; } } @Override public void onDestroy() { stopSampling(); super.onDestroy(); } @Override public void onSharedPreferenceChanged( SharedPreferences sharedPreferences, String key) { if (getString(R.string.settings_min_signal_sampling_period_key).equals(key)) { samplingPeriod = Long.parseLong(sharedPreferences.getString(key, "-1")); } } @Override public IBinder onBind(Intent intent) { return null; } public static void startService(Context context) { Intent intent = new Intent(); intent.setClass(context, SignalStrengthService.class); intent.setAction(START_SAMPLING); context.startService(intent); } public static void stopService(Context context) { Intent intent = new Intent(); intent.setClass(context, SignalStrengthService.class); intent.setAction(STOP_SAMPLING); context.startService(intent); } }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.signalstrength; /** * Interface for the service that reads signal strength. * * @author Rodrigo Damazio */ public interface SignalStrengthListener { /** * Interface for getting notified about a new sampled signal strength. */ public interface SignalStrengthCallback { void onSignalStrengthSampled( String description, String icon); } /** * Starts listening to signal strength. */ void register(); /** * Stops listening to signal strength. */ void unregister(); }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.signalstrength; import android.os.Build; /** * Constants for the signal sampler. * * @author Rodrigo Damazio */ public class SignalStrengthConstants { public static final String START_SAMPLING = "com.google.android.apps.mytracks.signalstrength.START"; public static final String STOP_SAMPLING = "com.google.android.apps.mytracks.signalstrength.STOP"; public static final int ANDROID_API_LEVEL = Integer.parseInt( Build.VERSION.SDK); public static final String TAG = "SignalStrengthSampler"; private SignalStrengthConstants() {} }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.signalstrength; import static com.google.android.apps.mytracks.signalstrength.SignalStrengthConstants.*; import android.content.Context; import android.telephony.PhoneStateListener; import android.telephony.SignalStrength; import android.telephony.TelephonyManager; import android.util.Log; /** * A class to monitor the network signal strength. * * TODO: i18n * * @author Sandor Dornbush */ public class SignalStrengthListenerEclair extends SignalStrengthListenerCupcake { private SignalStrength signalStrength = null; public SignalStrengthListenerEclair(Context ctx, SignalStrengthCallback callback) { super(ctx, callback); } @Override protected int getListenEvents() { return PhoneStateListener.LISTEN_SIGNAL_STRENGTHS; } @SuppressWarnings("hiding") @Override public void onSignalStrengthsChanged(SignalStrength signalStrength) { Log.d(TAG, "Signal Strength Modern: " + signalStrength); this.signalStrength = signalStrength; notifySignalSampled(); } /** * Gets a human readable description for the network type. * * @param type The integer constant for the network type * @return A human readable description of the network type */ @Override protected String getTypeAsString(int type) { switch (type) { case TelephonyManager.NETWORK_TYPE_1xRTT: return "1xRTT"; case TelephonyManager.NETWORK_TYPE_CDMA: return "CDMA"; case TelephonyManager.NETWORK_TYPE_EDGE: return "EDGE"; case TelephonyManager.NETWORK_TYPE_EVDO_0: return "EVDO 0"; case TelephonyManager.NETWORK_TYPE_EVDO_A: return "EVDO A"; case TelephonyManager.NETWORK_TYPE_GPRS: return "GPRS"; case TelephonyManager.NETWORK_TYPE_HSDPA: return "HSDPA"; case TelephonyManager.NETWORK_TYPE_HSPA: return "HSPA"; case TelephonyManager.NETWORK_TYPE_HSUPA: return "HSUPA"; case TelephonyManager.NETWORK_TYPE_UMTS: return "UMTS"; case TelephonyManager.NETWORK_TYPE_UNKNOWN: default: return "UNKNOWN"; } } /** * Gets the url for the waypoint icon for the current network type. * * @param type The network type * @return A url to a image to use as the waypoint icon */ @Override protected String getIcon(int type) { switch (type) { case TelephonyManager.NETWORK_TYPE_1xRTT: case TelephonyManager.NETWORK_TYPE_CDMA: case TelephonyManager.NETWORK_TYPE_GPRS: case TelephonyManager.NETWORK_TYPE_EDGE: return "http://maps.google.com/mapfiles/ms/micons/green.png"; case TelephonyManager.NETWORK_TYPE_EVDO_0: case TelephonyManager.NETWORK_TYPE_EVDO_A: case TelephonyManager.NETWORK_TYPE_HSDPA: case TelephonyManager.NETWORK_TYPE_HSPA: case TelephonyManager.NETWORK_TYPE_HSUPA: case TelephonyManager.NETWORK_TYPE_UMTS: return "http://maps.google.com/mapfiles/ms/micons/blue.png"; case TelephonyManager.NETWORK_TYPE_UNKNOWN: default: return "http://maps.google.com/mapfiles/ms/micons/red.png"; } } @Override public String getStrengthAsString() { if (signalStrength == null) { return "Strength: " + getContext().getString(R.string.unknown) + "\n"; } StringBuffer sb = new StringBuffer(); if (signalStrength.isGsm()) { appendSignal(signalStrength.getGsmSignalStrength(), R.string.gsm_strength, sb); maybeAppendSignal(signalStrength.getGsmBitErrorRate(), R.string.error_rate, sb); } else { appendSignal(signalStrength.getCdmaDbm(), R.string.cdma_strength, sb); appendSignal(signalStrength.getCdmaEcio() / 10.0, R.string.ecio, sb); appendSignal(signalStrength.getEvdoDbm(), R.string.evdo_strength, sb); appendSignal(signalStrength.getEvdoEcio() / 10.0, R.string.ecio, sb); appendSignal(signalStrength.getEvdoSnr(), R.string.signal_to_noise_ratio, sb); } return sb.toString(); } private void maybeAppendSignal( int signal, int signalFormat, StringBuffer sb) { if (signal > 0) { sb.append(getContext().getString(signalFormat, signal)); } } private void appendSignal(int signal, int signalFormat, StringBuffer sb) { sb.append(getContext().getString(signalFormat, signal)); sb.append("\n"); } private void appendSignal(double signal, int signalFormat, StringBuffer sb) { sb.append(getContext().getString(signalFormat, signal)); sb.append("\n"); } }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.signalstrength; import static com.google.android.apps.mytracks.signalstrength.SignalStrengthConstants.*; import com.google.android.apps.mytracks.signalstrength.SignalStrengthListener.SignalStrengthCallback; import android.content.Context; import android.util.Log; /** * Factory for producing a proper {@link SignalStrengthListenerCupcake} according to the * current API level. * * @author Rodrigo Damazio */ public class SignalStrengthListenerFactory { public SignalStrengthListener create(Context context, SignalStrengthCallback callback) { if (hasModernSignalStrength()) { Log.d(TAG, "TrackRecordingService using modern signal strength api."); return new SignalStrengthListenerEclair(context, callback); } else { Log.w(TAG, "TrackRecordingService using legacy signal strength api."); return new SignalStrengthListenerCupcake(context, callback); } } // @VisibleForTesting protected boolean hasModernSignalStrength() { return ANDROID_API_LEVEL >= 7; } }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.signalstrength; import static com.google.android.apps.mytracks.signalstrength.SignalStrengthConstants.*; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.util.Log; /** * Broadcast listener which gets notified when we start or stop recording a track. * * @author Rodrigo Damazio */ public class RecordingStateReceiver extends BroadcastReceiver { @Override public void onReceive(Context ctx, Intent intent) { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(ctx); String action = intent.getAction(); if (ctx.getString(R.string.track_started_broadcast_action).equals(action)) { boolean autoStart = preferences.getBoolean( ctx.getString(R.string.settings_auto_start_key), false); if (!autoStart) { Log.d(TAG, "Not auto-starting signal sampling"); return; } startService(ctx); } else if (ctx.getString(R.string.track_stopped_broadcast_action).equals(action)) { boolean autoStop = preferences.getBoolean( ctx.getString(R.string.settings_auto_stop_key), true); if (!autoStop) { Log.d(TAG, "Not auto-stopping signal sampling"); return; } stopService(ctx); } else { Log.e(TAG, "Unknown action received: " + action); } } // @VisibleForTesting protected void stopService(Context ctx) { SignalStrengthService.stopService(ctx); } // @VisibleForTesting protected void startService(Context ctx) { SignalStrengthService.startService(ctx); } }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.signalstrength; import android.os.Bundle; import android.preference.Preference; import android.preference.Preference.OnPreferenceClickListener; import android.preference.PreferenceActivity; /** * Main signal strength sampler activity, which displays preferences. * * @author Rodrigo Damazio */ public class SignalStrengthPreferences extends PreferenceActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preferences); // Attach service control funciontality findPreference(getString(R.string.settings_control_start_key)) .setOnPreferenceClickListener(new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { SignalStrengthService.startService(SignalStrengthPreferences.this); return true; } }); findPreference(getString(R.string.settings_control_stop_key)) .setOnPreferenceClickListener(new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { SignalStrengthService.stopService(SignalStrengthPreferences.this); return true; } }); // TODO: Check that my tracks is installed - if not, give a warning and // offer to go to the android market. } }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.signalstrength; import static com.google.android.apps.mytracks.signalstrength.SignalStrengthConstants.TAG; import android.content.ContentResolver; import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.telephony.CellLocation; import android.telephony.NeighboringCellInfo; import android.telephony.PhoneStateListener; import android.telephony.TelephonyManager; import android.util.Log; import java.util.List; /** * A class to monitor the network signal strength. * * TODO: i18n * * @author Sandor Dornbush */ public class SignalStrengthListenerCupcake extends PhoneStateListener implements SignalStrengthListener { private static final Uri APN_URI = Uri.parse("content://telephony/carriers"); private final Context context; private final SignalStrengthCallback callback; private TelephonyManager manager; private int signalStrength = -1; public SignalStrengthListenerCupcake(Context context, SignalStrengthCallback callback) { this.context = context; this.callback = callback; } @Override public void register() { manager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); if (manager == null) { Log.e(TAG, "Cannot get telephony manager."); } else { manager.listen(this, getListenEvents()); } } protected int getListenEvents() { return PhoneStateListener.LISTEN_SIGNAL_STRENGTH; } @SuppressWarnings("hiding") @Override public void onSignalStrengthChanged(int signalStrength) { Log.d(TAG, "Signal Strength: " + signalStrength); this.signalStrength = signalStrength; notifySignalSampled(); } protected void notifySignalSampled() { int networkType = manager.getNetworkType(); callback.onSignalStrengthSampled(getDescription(), getIcon(networkType)); } /** * Gets a human readable description for the network type. * * @param type The integer constant for the network type * @return A human readable description of the network type */ protected String getTypeAsString(int type) { switch (type) { case TelephonyManager.NETWORK_TYPE_EDGE: return "EDGE"; case TelephonyManager.NETWORK_TYPE_GPRS: return "GPRS"; case TelephonyManager.NETWORK_TYPE_UMTS: return "UMTS"; case TelephonyManager.NETWORK_TYPE_UNKNOWN: default: return "UNKNOWN"; } } /** * Builds a description for the current signal strength. * * @return A human readable description of the network state */ private String getDescription() { StringBuilder sb = new StringBuilder(); sb.append(getStrengthAsString()); sb.append("Network Type: "); sb.append(getTypeAsString(manager.getNetworkType())); sb.append('\n'); sb.append("Operator: "); sb.append(manager.getNetworkOperatorName()); sb.append(" / "); sb.append(manager.getNetworkOperator()); sb.append('\n'); sb.append("Roaming: "); sb.append(manager.isNetworkRoaming()); sb.append('\n'); appendCurrentApns(sb); List<NeighboringCellInfo> infos = manager.getNeighboringCellInfo(); Log.i(TAG, "Found " + infos.size() + " cells."); if (infos.size() > 0) { sb.append("Neighbors: "); for (NeighboringCellInfo info : infos) { sb.append(info.toString()); sb.append(' '); } sb.append('\n'); } CellLocation cell = manager.getCellLocation(); if (cell != null) { sb.append("Cell: "); sb.append(cell.toString()); sb.append('\n'); } return sb.toString(); } private void appendCurrentApns(StringBuilder output) { ContentResolver contentResolver = context.getContentResolver(); Cursor cursor = contentResolver.query( APN_URI, new String[] { "name", "apn" }, "current=1", null, null); if (cursor == null) { return; } try { String name = null; String apn = null; while (cursor.moveToNext()) { int nameIdx = cursor.getColumnIndex("name"); int apnIdx = cursor.getColumnIndex("apn"); if (apnIdx < 0 || nameIdx < 0) { continue; } name = cursor.getString(nameIdx); apn = cursor.getString(apnIdx); output.append("APN: "); if (name != null) { output.append(name); } if (apn != null) { output.append(" ("); output.append(apn); output.append(")\n"); } } } finally { cursor.close(); } } /** * Gets the url for the waypoint icon for the current network type. * * @param type The network type * @return A url to a image to use as the waypoint icon */ protected String getIcon(int type) { switch (type) { case TelephonyManager.NETWORK_TYPE_GPRS: case TelephonyManager.NETWORK_TYPE_EDGE: return "http://maps.google.com/mapfiles/ms/micons/green.png"; case TelephonyManager.NETWORK_TYPE_UMTS: return "http://maps.google.com/mapfiles/ms/micons/blue.png"; case TelephonyManager.NETWORK_TYPE_UNKNOWN: default: return "http://maps.google.com/mapfiles/ms/micons/red.png"; } } @Override public void unregister() { if (manager != null) { manager.listen(this, PhoneStateListener.LISTEN_NONE); manager = null; } } public String getStrengthAsString() { return "Strength: " + signalStrength + "\n"; } protected Context getContext() { return context; } public SignalStrengthCallback getSignalStrengthCallback() { return callback; } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks; import com.google.android.maps.MapView; import com.google.android.maps.Projection; import android.content.Context; import android.graphics.Rect; /** * Elements for Tests for the MyTracks map overlay. * * @author Bartlomiej Niechwiej * @author Vangelis S. * * A mock version of {@code MapOverlay} that does not use * {@class MapView}. */ public class MockMyTracksOverlay extends MapOverlay { private Projection mockProjection; public MockMyTracksOverlay(Context context) { super(context); mockProjection = new MockProjection(); } @Override public Projection getMapProjection(MapView mapView) { return mockProjection; } @Override public Rect getMapViewRect(MapView mapView) { return new Rect(0, 0, 100, 100); } }
Java
// Copyright 2010 Google Inc. All Rights Reserved. package com.google.android.apps.mytracks.testing; import com.google.android.apps.mytracks.content.MyTracksProviderUtils; import com.google.android.apps.mytracks.content.MyTracksProviderUtils.Factory; import android.content.Context; /** * A fake factory for {@link MyTracksProviderUtils} which always returns a * predefined instance. * * @author Rodrigo Damazio */ public class TestingProviderUtilsFactory extends Factory { private MyTracksProviderUtils instance; public TestingProviderUtilsFactory(MyTracksProviderUtils instance) { this.instance = instance; } @Override protected MyTracksProviderUtils newForContext(Context context) { return instance; } public static Factory installWithInstance(MyTracksProviderUtils instance) { Factory oldFactory = Factory.getInstance(); Factory factory = new TestingProviderUtilsFactory(instance); MyTracksProviderUtils.Factory.overrideInstance(factory); return oldFactory; } public static void restoreOldFactory(Factory factory) { MyTracksProviderUtils.Factory.overrideInstance(factory); } }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.services.tasks; import static com.google.android.testing.mocking.AndroidMock.capture; import static com.google.android.testing.mocking.AndroidMock.eq; import static com.google.android.testing.mocking.AndroidMock.expect; import static com.google.android.testing.mocking.AndroidMock.same; import com.google.android.apps.mytracks.stats.TripStatistics; import com.google.android.apps.mytracks.util.StringUtils; import com.google.android.testing.mocking.AndroidMock; import com.google.android.testing.mocking.UsesMocks; import android.content.Context; import android.speech.tts.TextToSpeech; import android.speech.tts.TextToSpeech.OnInitListener; import android.speech.tts.TextToSpeech.OnUtteranceCompletedListener; import android.telephony.PhoneStateListener; import android.telephony.TelephonyManager; import android.test.AndroidTestCase; import java.util.HashMap; import java.util.Locale; import java.util.concurrent.atomic.AtomicBoolean; import org.easymock.Capture; /** * Tests for {@link StatusAnnouncerTask}. * WARNING: I'm not responsible if your eyes start bleeding while reading this * code. You have been warned. It's still better than no test, though. * * @author Rodrigo Damazio */ public class StatusAnnouncerTaskTest extends AndroidTestCase { // Use something other than our hardcoded value private static final Locale DEFAULT_LOCALE = Locale.KOREAN; private static final String ANNOUNCEMENT = "I can haz cheeseburger?"; private Locale oldDefaultLocale; private StatusAnnouncerTask task; private StatusAnnouncerTask mockTask; private Capture<OnInitListener> initListenerCapture; private Capture<PhoneStateListener> phoneListenerCapture; private TextToSpeechDelegate ttsDelegate; private TextToSpeechInterface tts; /** * Mockable interface that we delegate TTS calls to. */ interface TextToSpeechInterface { int addEarcon(String earcon, String packagename, int resourceId); int addEarcon(String earcon, String filename); int addSpeech(String text, String packagename, int resourceId); int addSpeech(String text, String filename); boolean areDefaultsEnforced(); String getDefaultEngine(); Locale getLanguage(); int isLanguageAvailable(Locale loc); boolean isSpeaking(); int playEarcon(String earcon, int queueMode, HashMap<String, String> params); int playSilence(long durationInMs, int queueMode, HashMap<String, String> params); int setEngineByPackageName(String enginePackageName); int setLanguage(Locale loc); int setOnUtteranceCompletedListener(OnUtteranceCompletedListener listener); int setPitch(float pitch); int setSpeechRate(float speechRate); void shutdown(); int speak(String text, int queueMode, HashMap<String, String> params); int stop(); int synthesizeToFile(String text, HashMap<String, String> params, String filename); } /** * Subclass of {@link TextToSpeech} which delegates calls to the interface * above. * The logic here is stupid and the author is ashamed of having to write it * like this, but basically the issue is that TextToSpeech cannot be mocked * without running its constructor, its constructor runs async operations * which call other methods (and then if the methods are part of a mock we'd * have to set a behavior, but we can't 'cause the object hasn't been fully * built yet). * The logic is that calls made during the constructor (when tts is not yet * set) will go up to the original class, but after tts is set we'll forward * them all to the mock. */ private class TextToSpeechDelegate extends TextToSpeech implements TextToSpeechInterface { public TextToSpeechDelegate(Context context, OnInitListener listener) { super(context, listener); } @Override public int addEarcon(String earcon, String packagename, int resourceId) { if (tts == null) { return super.addEarcon(earcon, packagename, resourceId); } return tts.addEarcon(earcon, packagename, resourceId); } @Override public int addEarcon(String earcon, String filename) { if (tts == null) { return super.addEarcon(earcon, filename); } return tts.addEarcon(earcon, filename); } @Override public int addSpeech(String text, String packagename, int resourceId) { if (tts == null) { return super.addSpeech(text, packagename, resourceId); } return tts.addSpeech(text, packagename, resourceId); } @Override public int addSpeech(String text, String filename) { if (tts == null) { return super.addSpeech(text, filename); } return tts.addSpeech(text, filename); } @Override public Locale getLanguage() { if (tts == null) { return super.getLanguage(); } return tts.getLanguage(); } @Override public int isLanguageAvailable(Locale loc) { if (tts == null) { return super.isLanguageAvailable(loc); } return tts.isLanguageAvailable(loc); } @Override public boolean isSpeaking() { if (tts == null) { return super.isSpeaking(); } return tts.isSpeaking(); } @Override public int playEarcon(String earcon, int queueMode, HashMap<String, String> params) { if (tts == null) { return super.playEarcon(earcon, queueMode, params); } return tts.playEarcon(earcon, queueMode, params); } @Override public int playSilence(long durationInMs, int queueMode, HashMap<String, String> params) { if (tts == null) { return super.playSilence(durationInMs, queueMode, params); } return tts.playSilence(durationInMs, queueMode, params); } @Override public int setLanguage(Locale loc) { if (tts == null) { return super.setLanguage(loc); } return tts.setLanguage(loc); } @Override public int setOnUtteranceCompletedListener( OnUtteranceCompletedListener listener) { if (tts == null) { return super.setOnUtteranceCompletedListener(listener); } return tts.setOnUtteranceCompletedListener(listener); } @Override public int setPitch(float pitch) { if (tts == null) { return super.setPitch(pitch); } return tts.setPitch(pitch); } @Override public int setSpeechRate(float speechRate) { if (tts == null) { return super.setSpeechRate(speechRate); } return tts.setSpeechRate(speechRate); } @Override public void shutdown() { if (tts == null) { super.shutdown(); return; } tts.shutdown(); } @Override public int speak( String text, int queueMode, HashMap<String, String> params) { if (tts == null) { return super.speak(text, queueMode, params); } return tts.speak(text, queueMode, params); } @Override public int stop() { if (tts == null) { return super.stop(); } return tts.stop(); } @Override public int synthesizeToFile(String text, HashMap<String, String> params, String filename) { if (tts == null) { return super.synthesizeToFile(text, params, filename); } return tts.synthesizeToFile(text, params, filename); } } @UsesMocks({ StatusAnnouncerTask.class, StringUtils.class, }) @Override protected void setUp() throws Exception { super.setUp(); oldDefaultLocale = Locale.getDefault(); Locale.setDefault(DEFAULT_LOCALE); // Eww, the effort required just to mock TextToSpeech is insane final AtomicBoolean listenerCalled = new AtomicBoolean(); OnInitListener blockingListener = new OnInitListener() { @Override public void onInit(int status) { synchronized (this) { listenerCalled.set(true); notify(); } } }; ttsDelegate = new TextToSpeechDelegate(getContext(), blockingListener); // Wait for all async operations done in the constructor to finish. synchronized (blockingListener) { while (!listenerCalled.get()) { // Releases the synchronized lock until we're woken up. blockingListener.wait(); } } // Phew, done, now we can start forwarding calls tts = AndroidMock.createMock(TextToSpeechInterface.class); initListenerCapture = new Capture<OnInitListener>(); phoneListenerCapture = new Capture<PhoneStateListener>(); // Create a partial forwarding mock mockTask = AndroidMock.createMock(StatusAnnouncerTask.class, getContext()); task = new StatusAnnouncerTask(getContext()) { @Override protected TextToSpeech newTextToSpeech(Context ctx, OnInitListener onInitListener) { return mockTask.newTextToSpeech(ctx, onInitListener); } @Override protected String getAnnouncement(TripStatistics stats) { return mockTask.getAnnouncement(stats); } @Override protected void listenToPhoneState( PhoneStateListener listener, int events) { mockTask.listenToPhoneState(listener, events); } }; } @Override protected void tearDown() { Locale.setDefault(oldDefaultLocale); } public void testStart() { doStart(); OnInitListener ttsInitListener = initListenerCapture.getValue(); assertNotNull(ttsInitListener); expect(tts.isLanguageAvailable(DEFAULT_LOCALE)) .andStubReturn(TextToSpeech.LANG_AVAILABLE); expect(tts.setLanguage(DEFAULT_LOCALE)) .andReturn(TextToSpeech.LANG_AVAILABLE); expect(tts.setSpeechRate(StatusAnnouncerTask.TTS_SPEECH_RATE)) .andReturn(TextToSpeech.SUCCESS); AndroidMock.replay(tts); ttsInitListener.onInit(TextToSpeech.SUCCESS); AndroidMock.verify(mockTask, tts); } public void testStart_languageNotSupported() { doStart(); OnInitListener ttsInitListener = initListenerCapture.getValue(); assertNotNull(ttsInitListener); expect(tts.isLanguageAvailable(DEFAULT_LOCALE)) .andStubReturn(TextToSpeech.LANG_NOT_SUPPORTED); expect(tts.setLanguage(Locale.ENGLISH)) .andReturn(TextToSpeech.LANG_AVAILABLE); expect(tts.setSpeechRate(StatusAnnouncerTask.TTS_SPEECH_RATE)) .andReturn(TextToSpeech.SUCCESS); AndroidMock.replay(tts); ttsInitListener.onInit(TextToSpeech.SUCCESS); AndroidMock.verify(mockTask, tts); } public void testStart_notReady() { doStart(); OnInitListener ttsInitListener = initListenerCapture.getValue(); assertNotNull(ttsInitListener); AndroidMock.replay(tts); ttsInitListener.onInit(TextToSpeech.ERROR); AndroidMock.verify(mockTask, tts); } public void testShutdown() { // First, start doStart(); AndroidMock.verify(mockTask); AndroidMock.reset(mockTask); // Then, shut down PhoneStateListener phoneListener = phoneListenerCapture.getValue(); mockTask.listenToPhoneState( same(phoneListener), eq(PhoneStateListener.LISTEN_NONE)); tts.shutdown(); AndroidMock.replay(mockTask, tts); task.shutdown(); AndroidMock.verify(mockTask, tts); } public void testRun() throws Exception { // Expect service data calls TripStatistics stats = new TripStatistics(); // Expect announcement building call expect(mockTask.getAnnouncement(same(stats))).andStubReturn(ANNOUNCEMENT); // Put task in "ready" state startTask(TextToSpeech.SUCCESS); // Expect actual announcement call expect(tts.speak( eq(ANNOUNCEMENT), eq(TextToSpeech.QUEUE_FLUSH), AndroidMock.<HashMap<String, String>>isNull())) .andReturn(TextToSpeech.SUCCESS); // Run the announcement AndroidMock.replay(tts); task.runWithStatistics(stats); AndroidMock.verify(mockTask, tts); } public void testRun_notReady() throws Exception { // Put task in "not ready" state startTask(TextToSpeech.ERROR); // Run the announcement AndroidMock.replay(tts); task.runWithStatistics(null); AndroidMock.verify(mockTask, tts); } public void testRun_duringCall() throws Exception { startTask(TextToSpeech.SUCCESS); expect(tts.isSpeaking()).andStubReturn(false); // Run the announcement AndroidMock.replay(tts); PhoneStateListener phoneListener = phoneListenerCapture.getValue(); phoneListener.onCallStateChanged(TelephonyManager.CALL_STATE_OFFHOOK, null); task.runWithStatistics(null); AndroidMock.verify(mockTask, tts); } public void testRun_ringWhileSpeaking() throws Exception { startTask(TextToSpeech.SUCCESS); expect(tts.isSpeaking()).andStubReturn(true); expect(tts.stop()).andReturn(TextToSpeech.SUCCESS); AndroidMock.replay(tts); // Update the state to ringing - this should stop the current announcement. PhoneStateListener phoneListener = phoneListenerCapture.getValue(); phoneListener.onCallStateChanged(TelephonyManager.CALL_STATE_RINGING, null); // Run the announcement - this should do nothing. task.runWithStatistics(null); AndroidMock.verify(mockTask, tts); } public void testRun_whileRinging() throws Exception { startTask(TextToSpeech.SUCCESS); expect(tts.isSpeaking()).andStubReturn(false); // Run the announcement AndroidMock.replay(tts); PhoneStateListener phoneListener = phoneListenerCapture.getValue(); phoneListener.onCallStateChanged(TelephonyManager.CALL_STATE_RINGING, null); task.runWithStatistics(null); AndroidMock.verify(mockTask, tts); } public void testRun_noService() throws Exception { startTask(TextToSpeech.SUCCESS); // Run the announcement AndroidMock.replay(tts); task.run(null); AndroidMock.verify(mockTask, tts); } public void testRun_noStats() throws Exception { // Expect service data calls startTask(TextToSpeech.SUCCESS); // Run the announcement AndroidMock.replay(tts); task.runWithStatistics(null); AndroidMock.verify(mockTask, tts); } /** * Tests {@link StatusAnnouncerTask#getAnnounceTime(long)} with time zero. */ public void testGetAnnounceTime_time_zero() { long time = 0; // 0 seconds assertEquals("0 minutes 0 seconds", task.getAnnounceTime(time)); } /** * Tests {@link StatusAnnouncerTask#getAnnounceTime(long)} with time one. */ public void testGetAnnounceTime_time_one() { long time = 1 * 1000; // 1 second assertEquals("0 minutes 1 second", task.getAnnounceTime(time)); } /** * Tests {@link StatusAnnouncerTask#getAnnounceTime(long)} with singular * numbers with the hour unit. */ public void testGetAnnounceTime_singular_has_hour() { long time = (1 * 60 * 60 * 1000) + (1 * 60 * 1000) + (1 * 1000); // 1 hour 1 minute 1 second assertEquals("1 hour 1 minute", task.getAnnounceTime(time)); } /** * Tests {@link StatusAnnouncerTask#getAnnounceTime(long)} with plural numbers * with the hour unit. */ public void testGetAnnounceTime_plural_has_hour() { long time = (2 * 60 * 60 * 1000) + (2 * 60 * 1000) + (2 * 1000); // 2 hours 2 minutes 2 seconds assertEquals("2 hours 2 minutes", task.getAnnounceTime(time)); } /** * Tests {@link StatusAnnouncerTask#getAnnounceTime(long)} with singular * numbers without the hour unit. */ public void testGetAnnounceTime_singular_no_hour() { long time = (1 * 60 * 1000) + (1 * 1000); // 1 minute 1 second assertEquals("1 minute 1 second", task.getAnnounceTime(time)); } /** * Tests {@link StatusAnnouncerTask#getAnnounceTime(long)} with plural numbers * without the hour unit. */ public void testGetAnnounceTime_plural_no_hour() { long time = (2 * 60 * 1000) + (2 * 1000); // 2 minutes 2 seconds assertEquals("2 minutes 2 seconds", task.getAnnounceTime(time)); } private void startTask(int state) { AndroidMock.resetToNice(tts); AndroidMock.replay(tts); doStart(); OnInitListener ttsInitListener = initListenerCapture.getValue(); ttsInitListener.onInit(state); AndroidMock.resetToDefault(tts); } private void doStart() { mockTask.listenToPhoneState(capture(phoneListenerCapture), eq(PhoneStateListener.LISTEN_CALL_STATE)); expect(mockTask.newTextToSpeech( same(getContext()), capture(initListenerCapture))) .andStubReturn(ttsDelegate); AndroidMock.replay(mockTask); task.start(); } }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.services.tasks; import android.test.AndroidTestCase; /** * Tests for {@link StatusAnnouncerFactory}. * These tests require Donut+ to run. * * @author Rodrigo Damazio */ public class StatusAnnouncerFactoryTest extends AndroidTestCase { public void testCreate() { PeriodicTaskFactory factory = new StatusAnnouncerFactory(); PeriodicTask task = factory.create(getContext()); assertTrue(task instanceof StatusAnnouncerTask); } }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.services; import com.google.android.apps.mytracks.util.StringUtils; import com.google.android.maps.mytracks.R; import android.test.AndroidTestCase; import java.text.SimpleDateFormat; import java.util.Date; /** * Tests {@link DefaultTrackNameFactory} * * @author Matthew Simmons */ public class DefaultTrackNameFactoryTest extends AndroidTestCase { private static final long TRACK_ID = 1L; private static final long START_TIME = 1288213406000L; public void testDefaultTrackName_date_local() { DefaultTrackNameFactory defaultTrackNameFactory = new DefaultTrackNameFactory(getContext()) { @Override String getTrackNameSetting() { return getContext().getString(R.string.settings_recording_track_name_date_local_value); } }; assertEquals(StringUtils.formatDateTime(getContext(), START_TIME), defaultTrackNameFactory.getDefaultTrackName(TRACK_ID, START_TIME)); } public void testDefaultTrackName_date_iso_8601() { DefaultTrackNameFactory defaultTrackNameFactory = new DefaultTrackNameFactory(getContext()) { @Override String getTrackNameSetting() { return getContext().getString(R.string.settings_recording_track_name_date_iso_8601_value); } }; SimpleDateFormat simpleDateFormat = new SimpleDateFormat( DefaultTrackNameFactory.ISO_8601_FORMAT); assertEquals(simpleDateFormat.format(new Date(START_TIME)), defaultTrackNameFactory.getDefaultTrackName(TRACK_ID, START_TIME)); } public void testDefaultTrackName_number() { DefaultTrackNameFactory defaultTrackNameFactory = new DefaultTrackNameFactory(getContext()) { @Override String getTrackNameSetting() { return getContext().getString(R.string.settings_recording_track_name_number_value); } }; assertEquals( "Track " + TRACK_ID, defaultTrackNameFactory.getDefaultTrackName(TRACK_ID, START_TIME)); } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.services.sensors.ant; import android.test.AndroidTestCase; public class AntChannelIdMessageTest extends AndroidTestCase { public void testParse() { byte[] rawMessage = { 0, // channel number 0x34, 0x12, // device number (byte) 0xaa, // device type id (byte) 0xbb, // transmission type }; AntChannelIdMessage message = new AntChannelIdMessage(rawMessage); assertEquals(0, message.getChannelNumber()); assertEquals(0x1234, message.getDeviceNumber()); assertEquals((byte) 0xaa, message.getDeviceTypeId()); assertEquals((byte) 0xbb, message.getTransmissionType()); } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.services.sensors.ant; import android.test.AndroidTestCase; public class AntMessageTest extends AndroidTestCase { private static class TestAntMessage extends AntMessage { public static short decodeShort(byte low, byte high) { return AntMessage.decodeShort(low, high); } } public void testDecode() { assertEquals(0x1234, TestAntMessage.decodeShort((byte) 0x34, (byte) 0x12)); } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.services.sensors.ant; import android.content.Context; import android.test.AndroidTestCase; import android.test.MoreAsserts; public class AntSensorManagerTest extends AndroidTestCase { private class TestAntSensorManager extends AntSensorManager { public TestAntSensorManager(Context context) { super(context); } public byte messageId; public byte[] messageData; @Override protected void setupAntSensorChannels() {} @SuppressWarnings("deprecation") @Override public void handleMessage(byte[] rawMessage) { super.handleMessage(rawMessage); } @SuppressWarnings("hiding") @Override public boolean handleMessage(byte messageId, byte[] messageData) { this.messageId = messageId; this.messageData = messageData; return true; } } private TestAntSensorManager sensorManager; @Override protected void setUp() throws Exception { super.setUp(); sensorManager = new TestAntSensorManager(getContext()); } public void testSimple() { byte[] rawMessage = { 0x03, // length 0x12, // message id 0x11, 0x22, 0x33, // body }; byte[] expectedBody = { 0x11, 0x22, 0x33 }; sensorManager.handleMessage(rawMessage); assertEquals((byte) 0x12, sensorManager.messageId); MoreAsserts.assertEquals(expectedBody, sensorManager.messageData); } public void testTooShort() { byte[] rawMessage = { 0x53, // length 0x12 // message id }; sensorManager.handleMessage(rawMessage); assertEquals(0, sensorManager.messageId); assertNull(sensorManager.messageData); } public void testLengthWrong() { byte[] rawMessage = { 0x53, // length 0x12, // message id 0x34, // body }; sensorManager.handleMessage(rawMessage); assertEquals(0, sensorManager.messageId); assertNull(sensorManager.messageData); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.services.sensors.ant; import android.test.AndroidTestCase; import android.test.suitebuilder.annotation.SmallTest; /** * @author Laszlo Molnar */ public class SensorEventCounterTest extends AndroidTestCase { @SmallTest public void testGetEventsPerMinute() { SensorEventCounter sec = new SensorEventCounter(); assertEquals(0, sec.getEventsPerMinute(0, 0, 0)); assertEquals(0, sec.getEventsPerMinute(1, 1024, 1000)); assertEquals(60, sec.getEventsPerMinute(2, 1024 * 2, 2000)); assertEquals(60, sec.getEventsPerMinute(2, 1024 * 2, 2500)); assertTrue(60 > sec.getEventsPerMinute(2, 1024 * 2, 4000)); } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.services.sensors.ant; import com.dsi.ant.AntDefine; import com.dsi.ant.AntMesg; import android.test.AndroidTestCase; public class AntChannelResponseMessageTest extends AndroidTestCase { public void testParse() { byte[] rawMessage = { 0, AntMesg.MESG_EVENT_ID, AntDefine.EVENT_RX_SEARCH_TIMEOUT }; AntChannelResponseMessage message = new AntChannelResponseMessage(rawMessage); assertEquals(0, message.getChannelNumber()); assertEquals(AntMesg.MESG_EVENT_ID, message.getMessageId()); assertEquals(AntDefine.EVENT_RX_SEARCH_TIMEOUT, message.getMessageCode()); } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.services.sensors.ant; import android.test.AndroidTestCase; public class AntStartupMessageTest extends AndroidTestCase { public void testParse() { byte[] rawMessage = { 0x12, }; AntStartupMessage message = new AntStartupMessage(rawMessage); assertEquals(0x12, message.getMessage()); } }
Java
/* * Copyright 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.services.sensors.ant; import com.dsi.ant.AntMesg; import com.google.android.apps.mytracks.Constants; import com.google.android.apps.mytracks.content.Sensor; import com.google.android.maps.mytracks.R; import android.content.Context; import android.content.SharedPreferences; import android.test.AndroidTestCase; import android.test.suitebuilder.annotation.SmallTest; public class AntDirectSensorManagerTest extends AndroidTestCase { private SharedPreferences sharedPreferences; private AntSensorBase heartRateSensor; private static final byte HEART_RATE_CHANNEL = 0; private class MockAntDirectSensorManager extends AntDirectSensorManager { public MockAntDirectSensorManager(Context context) { super(context); } @Override protected boolean setupChannel(AntSensorBase sensor, byte channel) { if (channel == HEART_RATE_CHANNEL) { heartRateSensor = sensor; return true; } return false; } } private AntDirectSensorManager manager; public void setUp() { sharedPreferences = getContext().getSharedPreferences( Constants.SETTINGS_NAME, Context.MODE_PRIVATE); // Let's use default values. sharedPreferences.edit().clear().apply(); manager = new MockAntDirectSensorManager(getContext()); } @SmallTest public void testBroadcastData() { manager.setupAntSensorChannels(); assertNotNull(heartRateSensor); heartRateSensor.setDeviceNumber((short) 42); byte[] buff = new byte[9]; buff[0] = HEART_RATE_CHANNEL; buff[8] = (byte) 220; manager.handleMessage(AntMesg.MESG_BROADCAST_DATA_ID, buff); Sensor.SensorDataSet sds = manager.getSensorDataSet(); assertNotNull(sds); assertTrue(sds.hasHeartRate()); assertEquals(Sensor.SensorState.SENDING, sds.getHeartRate().getState()); assertEquals(220, sds.getHeartRate().getValue()); assertFalse(sds.hasCadence()); assertFalse(sds.hasPower()); assertEquals(Sensor.SensorState.CONNECTED, manager.getSensorState()); } @SmallTest public void testChannelId() { manager.setupAntSensorChannels(); assertNotNull(heartRateSensor); byte[] buff = new byte[9]; buff[1] = 43; manager.handleMessage(AntMesg.MESG_CHANNEL_ID_ID, buff); assertEquals(43, heartRateSensor.getDeviceNumber()); assertEquals(43, sharedPreferences.getInt( getContext().getString(R.string.ant_heart_rate_sensor_id_key), -1)); assertNull(manager.getSensorDataSet()); } @SmallTest public void testResponseEvent() { manager.setupAntSensorChannels(); assertNotNull(heartRateSensor); manager.setHeartRate(210); heartRateSensor.setDeviceNumber((short) 42); assertEquals(Sensor.SensorState.CONNECTED, manager.getSensorState()); byte[] buff = new byte[3]; buff[0] = HEART_RATE_CHANNEL; buff[1] = AntMesg.MESG_UNASSIGN_CHANNEL_ID; buff[2] = 0; // code manager.handleMessage(AntMesg.MESG_RESPONSE_EVENT_ID, buff); assertEquals(Sensor.SensorState.CONNECTED, manager.getSensorState()); heartRateSensor.setDeviceNumber((short) 0); manager.handleMessage(AntMesg.MESG_RESPONSE_EVENT_ID, buff); assertEquals(Sensor.SensorState.DISCONNECTED, manager.getSensorState()); } // TODO: Test timeout too. }
Java
package com.google.android.apps.mytracks.services.sensors; import com.google.android.apps.mytracks.Constants; import com.google.android.maps.mytracks.R; import android.content.Context; import android.content.SharedPreferences; import android.test.AndroidTestCase; import android.test.suitebuilder.annotation.SmallTest; public class SensorManagerFactoryTest extends AndroidTestCase { private SharedPreferences sharedPreferences; @Override protected void setUp() throws Exception { super.setUp(); sharedPreferences = getContext().getSharedPreferences( Constants.SETTINGS_NAME, Context.MODE_PRIVATE); // Let's use default values. sharedPreferences.edit().clear().apply(); } @SmallTest public void testDefaultSettings() throws Exception { assertNull(SensorManagerFactory.getInstance().getSensorManager(getContext())); } @SmallTest public void testCreateZephyr() throws Exception { assertClassForName(ZephyrSensorManager.class, R.string.sensor_type_value_zephyr); } @SmallTest public void testCreatePolar() throws Exception { assertClassForName(PolarSensorManager.class, R.string.sensor_type_value_polar); } private void assertClassForName(Class<?> c, int i) { sharedPreferences.edit() .putString(getContext().getString(R.string.sensor_type_key), getContext().getString(i)) .apply(); SensorManager sm = SensorManagerFactory.getInstance().getSensorManager(getContext()); assertNotNull(sm); assertTrue(c.isInstance(sm)); SensorManagerFactory.getInstance().releaseSensorManager(sm); } }
Java
package com.google.android.apps.mytracks.services.sensors; import com.google.android.apps.mytracks.content.Sensor; import junit.framework.TestCase; public class ZephyrMessageParserTest extends TestCase { ZephyrMessageParser parser = new ZephyrMessageParser(); public void testIsValid() { byte[] smallBuf = new byte[59]; assertFalse(parser.isValid(smallBuf)); // A complete and valid Zephyr HxM packet byte[] buf = { 2,38,55,26,0,49,101,80,0,49,98,100,42,113,120,-53,-24,-60,-123,-61,117,-69,42,-75,74,-78,51,-79,27,-83,28,-88,28,-93,29,-98,25,-103,26,-108,26,-113,59,-118,0,0,0,0,0,0,-22,3,125,1,48,0,96,4,30,0 }; // Make buffer invalid buf[0] = buf[58] = buf[59] = 0; assertFalse(parser.isValid(buf)); buf[0] = 0x02; assertFalse(parser.isValid(buf)); buf[58] = 0x1E; assertFalse(parser.isValid(buf)); buf[59] = 0x03; assertTrue(parser.isValid(buf)); } public void testParseBuffer() { byte[] buf = new byte[60]; // Heart Rate (-1 =^ 255 unsigned byte) buf[12] = -1; // Battery Level buf[11] = 51; // Cadence (=^ 255*16 strides/min) buf[56] = -1; buf[57] = 15; Sensor.SensorDataSet sds = parser.parseBuffer(buf); assertTrue(sds.hasHeartRate()); assertTrue(sds.getHeartRate().getState() == Sensor.SensorState.SENDING); assertEquals(255, sds.getHeartRate().getValue()); assertTrue(sds.hasBatteryLevel()); assertTrue(sds.getBatteryLevel().getState() == Sensor.SensorState.SENDING); assertEquals(51, sds.getBatteryLevel().getValue()); assertTrue(sds.hasCadence()); assertTrue(sds.getCadence().getState() == Sensor.SensorState.SENDING); assertEquals(255, sds.getCadence().getValue()); } public void testFindNextAlignment() { byte[] buf = new byte[60]; assertEquals(-1, parser.findNextAlignment(buf)); buf[10] = 0x03; buf[11] = 0x02; assertEquals(10, parser.findNextAlignment(buf)); } }
Java
package com.google.android.apps.mytracks.services.sensors; import java.util.Arrays; import com.google.android.apps.mytracks.content.Sensor; import junit.framework.TestCase; public class PolarMessageParserTest extends TestCase { PolarMessageParser parser = new PolarMessageParser(); // A complete and valid Polar HxM packet // FE08F701D1001104FE08F702D1001104 private final byte[] originalBuf = {(byte) 0xFE, 0x08, (byte) 0xF7, 0x01, (byte) 0xD1, 0x00, 0x11, 0x04, (byte) 0xFE, 0x08, (byte) 0xF7, 0x02, (byte) 0xD1, 0x00, 0x11, 0x04}; private byte[] buf; public void setUp() { buf = Arrays.copyOf(originalBuf, originalBuf.length); } public void testIsValid() { assertTrue(parser.isValid(buf)); } public void testIsValid_invalidHeader() { // Invalidate header. buf[0] = 0x03; assertFalse(parser.isValid(buf)); } public void testIsValid_invalidCheckbyte() { // Invalidate checkbyte. buf[2] = 0x03; assertFalse(parser.isValid(buf)); } public void testIsValid_invalidSequence() { // Invalidate sequence. buf[3] = 0x11; assertFalse(parser.isValid(buf)); } public void testParseBuffer() { buf[5] = 70; Sensor.SensorDataSet sds = parser.parseBuffer(buf); assertTrue(sds.hasHeartRate()); assertTrue(sds.getHeartRate().getState() == Sensor.SensorState.SENDING); assertEquals(70, sds.getHeartRate().getValue()); } public void testFindNextAlignment_offset() { // The first 4 bytes are garbage buf = new byte[originalBuf.length + 4]; buf[0] = 4; buf[1] = 2; buf[2] = 4; buf[3] = 2; // Then the valid message. System.arraycopy(originalBuf, 0, buf, 4, originalBuf.length); assertEquals(4, parser.findNextAlignment(buf)); } public void testFindNextAlignment_invalid() { buf[0] = 0; assertEquals(-1, parser.findNextAlignment(buf)); } }
Java
// Copyright 2012 Google Inc. All Rights Reserved. package com.google.android.apps.mytracks.services; import android.app.Notification; import android.app.Service; import android.test.ServiceTestCase; import android.util.Log; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; /** * A {@link TrackRecordingService} that can be used with {@link ServiceTestCase}. * {@link ServiceTestCase} throws a null pointer exception when the service * calls {@link Service#startForeground(int, android.app.Notification)} and * {@link Service#stopForeground(boolean)}. * <p> * See http://code.google.com/p/android/issues/detail?id=12122 * <p> * Wrap these two methods in wrappers and override them. * * @author Jimmy Shih */ public class TestRecordingService extends TrackRecordingService { private static final String TAG = TestRecordingService.class.getSimpleName(); @Override protected void startForegroundService(Notification notification) { try { Method setForegroundMethod = Service.class.getMethod("setForeground", boolean.class); setForegroundMethod.invoke(this, true); } catch (SecurityException e) { Log.e(TAG, "Unable to start a service in foreground", e); } catch (NoSuchMethodException e) { Log.e(TAG, "Unable to start a service in foreground", e); } catch (IllegalArgumentException e) { Log.e(TAG, "Unable to start a service in foreground", e); } catch (IllegalAccessException e) { Log.e(TAG, "Unable to start a service in foreground", e); } catch (InvocationTargetException e) { Log.e(TAG, "Unable to start a service in foreground", e); } } @Override protected void stopForegroundService() { try { Method setForegroundMethod = Service.class.getMethod("setForeground", boolean.class); setForegroundMethod.invoke(this, false); } catch (SecurityException e) { Log.e(TAG, "Unable to start a service in foreground", e); } catch (NoSuchMethodException e) { Log.e(TAG, "Unable to start a service in foreground", e); } catch (IllegalArgumentException e) { Log.e(TAG, "Unable to start a service in foreground", e); } catch (IllegalAccessException e) { Log.e(TAG, "Unable to start a service in foreground", e); } catch (InvocationTargetException e) { Log.e(TAG, "Unable to start a service in foreground", e); } } }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.services; import static com.google.android.testing.mocking.AndroidMock.expect; import com.google.android.testing.mocking.AndroidMock; import com.google.android.testing.mocking.UsesMocks; import android.test.AndroidTestCase; import java.io.File; /** * Tests {@link RemoveTempFilesService}. * * @author Sandor Dornbush */ public class RemoveTempFilesServiceTest extends AndroidTestCase { private static final String DIR_NAME = "/tmp"; private static final String FILE_NAME = "foo"; private RemoveTempFilesService service; @UsesMocks({ File.class, }) protected void setUp() throws Exception { service = new RemoveTempFilesService(); }; /** * Tests when the directory doesn't exists. */ public void test_noDir() { File dir = AndroidMock.createMock(File.class, DIR_NAME); expect(dir.exists()).andStubReturn(false); AndroidMock.replay(dir); assertEquals(0, service.cleanTempDirectory(dir)); AndroidMock.verify(dir); } /** * Tests when the directory is empty. */ public void test_emptyDir() { File dir = AndroidMock.createMock(File.class, DIR_NAME); expect(dir.exists()).andStubReturn(true); expect(dir.listFiles()).andStubReturn(new File[0]); AndroidMock.replay(dir); assertEquals(0, service.cleanTempDirectory(dir)); AndroidMock.verify(dir); } /** * Tests when there is a new file and it shouldn't get deleted. */ public void test_newFile() { File file = AndroidMock.createMock(File.class, DIR_NAME + FILE_NAME); expect(file.lastModified()).andStubReturn(System.currentTimeMillis()); File dir = AndroidMock.createMock(File.class, DIR_NAME); expect(dir.exists()).andStubReturn(true); expect(dir.listFiles()).andStubReturn(new File[] { file }); AndroidMock.replay(dir, file); assertEquals(0, service.cleanTempDirectory(dir)); AndroidMock.verify(dir, file); } /** * Tests when there is an old file and it should get deleted. */ public void test_oldFile() { File file = AndroidMock.createMock(File.class, DIR_NAME + FILE_NAME); // qSet to one hour and 1 millisecond later than the current time expect(file.lastModified()).andStubReturn(System.currentTimeMillis() - 3600001); expect(file.delete()).andStubReturn(true); File dir = AndroidMock.createMock(File.class, DIR_NAME); expect(dir.exists()).andStubReturn(true); expect(dir.listFiles()).andStubReturn(new File[] { file }); AndroidMock.replay(dir, file); assertEquals(1, service.cleanTempDirectory(dir)); AndroidMock.verify(dir, file); } }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.services; import static com.google.android.apps.mytracks.Constants.RESUME_TRACK_EXTRA_NAME; import com.google.android.apps.mytracks.Constants; import com.google.android.apps.mytracks.content.MyTracksProvider; import com.google.android.apps.mytracks.content.MyTracksProviderUtils; import com.google.android.apps.mytracks.content.Track; import com.google.android.apps.mytracks.content.Waypoint; import com.google.android.apps.mytracks.content.WaypointCreationRequest; import com.google.android.apps.mytracks.stats.TripStatistics; import com.google.android.apps.mytracks.util.PreferencesUtils; import com.google.android.maps.mytracks.R; import android.content.BroadcastReceiver; import android.content.ContentResolver; import android.content.Context; import android.content.ContextWrapper; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.database.Cursor; import android.location.Location; import android.net.Uri; import android.os.Bundle; import android.os.IBinder; import android.provider.Settings; import android.test.RenamingDelegatingContext; import android.test.ServiceTestCase; import android.test.mock.MockContentProvider; import android.test.mock.MockContentResolver; import android.test.suitebuilder.annotation.MediumTest; import android.test.suitebuilder.annotation.SmallTest; import android.util.Log; import java.util.ArrayList; import java.util.List; /** * Tests for the MyTracks track recording service. * * @author Bartlomiej Niechwiej * * TODO: The original class, ServiceTestCase, has a few limitations, e.g. * it's not possible to properly shutdown the service, unless tearDown() * is called, which prevents from testing multiple scenarios in a single * test (see runFunctionTest for more details). */ public class TrackRecordingServiceTest extends ServiceTestCase<TestRecordingService> { private Context context; private MyTracksProviderUtils providerUtils; private SharedPreferences sharedPreferences; /* * In order to support starting and binding to the service in the same * unit test, we provide a workaround, as the original class doesn't allow * to bind after the service has been previously started. */ private boolean bound; private Intent serviceIntent; public TrackRecordingServiceTest() { super(TestRecordingService.class); } /** * A context wrapper with the user provided {@link ContentResolver}. * * TODO: Move to test utils package. */ public static class MockContext extends ContextWrapper { private final ContentResolver contentResolver; public MockContext(ContentResolver contentResolver, Context base) { super(base); this.contentResolver = contentResolver; } @Override public ContentResolver getContentResolver() { return contentResolver; } } @Override protected IBinder bindService(Intent intent) { if (getService() != null) { if (bound) { throw new IllegalStateException( "Service: " + getService() + " is already bound"); } bound = true; serviceIntent = intent.cloneFilter(); return getService().onBind(intent); } else { return super.bindService(intent); } } @Override protected void shutdownService() { if (bound) { assertNotNull(getService()); getService().onUnbind(serviceIntent); bound = false; } super.shutdownService(); } @Override protected void setUp() throws Exception { super.setUp(); /* * Create a mock context that uses a mock content resolver and a renaming * delegating context. */ MockContentResolver mockContentResolver = new MockContentResolver(); RenamingDelegatingContext renamingDelegatingContext = new RenamingDelegatingContext( getContext(), getContext(), "test."); context = new MockContext(mockContentResolver, renamingDelegatingContext); // Set up the mock content resolver MyTracksProvider myTracksProvider = new MyTracksProvider(); myTracksProvider.attachInfo(context, null); mockContentResolver.addProvider(MyTracksProviderUtils.AUTHORITY, myTracksProvider); MockContentProvider settingsProvider = new MockContentProvider(context) { @Override public Bundle call(String method, String arg, Bundle extras) { return null; } @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { return null; } }; mockContentResolver.addProvider(Settings.AUTHORITY, settingsProvider); // Set the context setContext(context); providerUtils = MyTracksProviderUtils.Factory.get(context); sharedPreferences = context.getSharedPreferences(Constants.SETTINGS_NAME, Context.MODE_PRIVATE); // Let's use default values. sharedPreferences.edit().clear().apply(); // Disable auto resume by default. updateAutoResumePrefs(0, -1); // No recording track. PreferencesUtils.setRecordingTrackId(context, -1L); } @SmallTest public void testStartable() { startService(createStartIntent()); assertNotNull(getService()); } @MediumTest public void testBindable() { IBinder service = bindService(createStartIntent()); assertNotNull(service); } @MediumTest public void testResumeAfterReboot_shouldResume() throws Exception { // Insert a dummy track and mark it as recording track. createDummyTrack(123L, System.currentTimeMillis(), true); // Clear the number of attempts and set the timeout to 10 min. updateAutoResumePrefs(0, 10); // Start the service in "resume" mode (simulates the on-reboot action). Intent startIntent = createStartIntent(); startIntent.putExtra(RESUME_TRACK_EXTRA_NAME, true); startService(startIntent); assertNotNull(getService()); // We expect to resume the previous track. assertTrue(getService().isRecording()); ITrackRecordingService service = bindAndGetService(createStartIntent()); assertEquals(123L, service.getRecordingTrackId()); } // TODO: shutdownService() has a bug and doesn't set mServiceCreated // to false, thus preventing from a second call to onCreate(). // Report the bug to Android team. Until then, the following tests // and checks must be commented out. // // TODO: If fixed, remove "disabled" prefix from the test name. @MediumTest public void disabledTestResumeAfterReboot_simulateReboot() throws Exception { updateAutoResumePrefs(0, 10); ITrackRecordingService service = bindAndGetService(createStartIntent()); assertFalse(service.isRecording()); // Simulate recording a track. long id = service.startNewTrack(); assertTrue(service.isRecording()); assertEquals(id, service.getRecordingTrackId()); shutdownService(); assertEquals(id, PreferencesUtils.getRecordingTrackId(context)); // Start the service in "resume" mode (simulates the on-reboot action). Intent startIntent = createStartIntent(); startIntent.putExtra(RESUME_TRACK_EXTRA_NAME, true); startService(startIntent); assertNotNull(getService()); assertTrue(getService().isRecording()); } @MediumTest public void testResumeAfterReboot_noRecordingTrack() throws Exception { // Insert a dummy track and mark it as recording track. createDummyTrack(123L, System.currentTimeMillis(), false); // Clear the number of attempts and set the timeout to 10 min. updateAutoResumePrefs(0, 10); // Start the service in "resume" mode (simulates the on-reboot action). Intent startIntent = createStartIntent(); startIntent.putExtra(RESUME_TRACK_EXTRA_NAME, true); startService(startIntent); assertNotNull(getService()); // We don't expect to resume the previous track, because it was stopped. assertFalse(getService().isRecording()); ITrackRecordingService service = bindAndGetService(createStartIntent()); assertEquals(-1L, service.getRecordingTrackId()); } @MediumTest public void testResumeAfterReboot_expiredTrack() throws Exception { // Insert a dummy track last updated 20 min ago. createDummyTrack(123L, System.currentTimeMillis() - 20 * 60 * 1000, true); // Clear the number of attempts and set the timeout to 10 min. updateAutoResumePrefs(0, 10); // Start the service in "resume" mode (simulates the on-reboot action). Intent startIntent = createStartIntent(); startIntent.putExtra(RESUME_TRACK_EXTRA_NAME, true); startService(startIntent); assertNotNull(getService()); // We don't expect to resume the previous track, because it has expired. assertFalse(getService().isRecording()); ITrackRecordingService service = bindAndGetService(createStartIntent()); assertEquals(-1L, service.getRecordingTrackId()); } @MediumTest public void testResumeAfterReboot_tooManyAttempts() throws Exception { // Insert a dummy track. createDummyTrack(123L, System.currentTimeMillis(), true); // Set the number of attempts to max. updateAutoResumePrefs( TrackRecordingService.MAX_AUTO_RESUME_TRACK_RETRY_ATTEMPTS, 10); // Start the service in "resume" mode (simulates the on-reboot action). Intent startIntent = createStartIntent(); startIntent.putExtra(RESUME_TRACK_EXTRA_NAME, true); startService(startIntent); assertNotNull(getService()); // We don't expect to resume the previous track, because there were already // too many attempts. assertFalse(getService().isRecording()); ITrackRecordingService service = bindAndGetService(createStartIntent()); assertEquals(-1L, service.getRecordingTrackId()); } @MediumTest public void testRecording_noTracks() throws Exception { List<Track> tracks = providerUtils.getAllTracks(); assertTrue(tracks.isEmpty()); ITrackRecordingService service = bindAndGetService(createStartIntent()); // Test if we start in no-recording mode by default. assertFalse(service.isRecording()); assertEquals(-1L, service.getRecordingTrackId()); } @MediumTest public void testRecording_oldTracks() throws Exception { createDummyTrack(123L, -1L, false); ITrackRecordingService service = bindAndGetService(createStartIntent()); assertFalse(service.isRecording()); assertEquals(-1L, service.getRecordingTrackId()); } @MediumTest public void testRecording_orphanedRecordingTrack() throws Exception { // Just set recording track to a bogus value. PreferencesUtils.setRecordingTrackId(context, 256L); // Make sure that the service will not start recording and will clear // the bogus track. ITrackRecordingService service = bindAndGetService(createStartIntent()); assertFalse(service.isRecording()); assertEquals(-1L, service.getRecordingTrackId()); } /** * Synchronous/waitable broadcast receiver to be used in testing. */ private class BlockingBroadcastReceiver extends BroadcastReceiver { private static final long MAX_WAIT_TIME_MS = 10000; private List<Intent> receivedIntents = new ArrayList<Intent>(); public List<Intent> getReceivedIntents() { return receivedIntents; } @Override public void onReceive(Context ctx, Intent intent) { Log.d("MyTracksTest", "Got broadcast: " + intent); synchronized (receivedIntents) { receivedIntents.add(intent); receivedIntents.notifyAll(); } } public boolean waitUntilReceived(int receiveCount) { long deadline = System.currentTimeMillis() + MAX_WAIT_TIME_MS; synchronized (receivedIntents) { while (receivedIntents.size() < receiveCount) { try { // Wait releases synchronized lock until it returns receivedIntents.wait(500); } catch (InterruptedException e) { // Do nothing } if (System.currentTimeMillis() > deadline) { return false; } } } return true; } } @MediumTest public void testStartNewTrack_noRecording() throws Exception { // NOTICE: due to the way Android permissions work, if this fails, // uninstall the test apk then retry - the test must be installed *after* // My Tracks (go figure). // Reference: http://code.google.com/p/android/issues/detail?id=5521 BlockingBroadcastReceiver startReceiver = new BlockingBroadcastReceiver(); String startAction = context.getString(R.string.track_started_broadcast_action); context.registerReceiver(startReceiver, new IntentFilter(startAction)); List<Track> tracks = providerUtils.getAllTracks(); assertTrue(tracks.isEmpty()); ITrackRecordingService service = bindAndGetService(createStartIntent()); assertFalse(service.isRecording()); long id = service.startNewTrack(); assertTrue(id >= 0); assertTrue(service.isRecording()); Track track = providerUtils.getTrack(id); assertNotNull(track); assertEquals(id, track.getId()); assertEquals(sharedPreferences.getString(context.getString(R.string.default_activity_key), ""), track.getCategory()); assertEquals(id, PreferencesUtils.getRecordingTrackId(context)); assertEquals(id, service.getRecordingTrackId()); // Verify that the start broadcast was received. assertTrue(startReceiver.waitUntilReceived(1)); List<Intent> receivedIntents = startReceiver.getReceivedIntents(); assertEquals(1, receivedIntents.size()); Intent broadcastIntent = receivedIntents.get(0); assertEquals(startAction, broadcastIntent.getAction()); assertEquals(id, broadcastIntent.getLongExtra( context.getString(R.string.track_id_broadcast_extra), -1L)); context.unregisterReceiver(startReceiver); } @MediumTest public void testStartNewTrack_alreadyRecording() throws Exception { createDummyTrack(123L, -1L, true); ITrackRecordingService service = bindAndGetService(createStartIntent()); assertTrue(service.isRecording()); // Starting a new track when there is a recording should just return -1L. long newTrack = service.startNewTrack(); assertEquals(-1L, newTrack); assertEquals(123L, PreferencesUtils.getRecordingTrackId(context)); assertEquals(123L, service.getRecordingTrackId()); } @MediumTest public void testEndCurrentTrack_alreadyRecording() throws Exception { // See comment above if this fails randomly. BlockingBroadcastReceiver stopReceiver = new BlockingBroadcastReceiver(); String stopAction = context.getString(R.string.track_stopped_broadcast_action); context.registerReceiver(stopReceiver, new IntentFilter(stopAction)); createDummyTrack(123L, -1L, true); ITrackRecordingService service = bindAndGetService(createStartIntent()); assertTrue(service.isRecording()); // End the current track. service.endCurrentTrack(); assertFalse(service.isRecording()); assertEquals(-1L, PreferencesUtils.getRecordingTrackId(context)); assertEquals(-1L, service.getRecordingTrackId()); // Verify that the stop broadcast was received. assertTrue(stopReceiver.waitUntilReceived(1)); List<Intent> receivedIntents = stopReceiver.getReceivedIntents(); assertEquals(1, receivedIntents.size()); Intent broadcastIntent = receivedIntents.get(0); assertEquals(stopAction, broadcastIntent.getAction()); assertEquals(123L, broadcastIntent.getLongExtra( context.getString(R.string.track_id_broadcast_extra), -1L)); context.unregisterReceiver(stopReceiver); } @MediumTest public void testEndCurrentTrack_noRecording() throws Exception { ITrackRecordingService service = bindAndGetService(createStartIntent()); assertFalse(service.isRecording()); // Ending the current track when there is no recording should not result in any error. service.endCurrentTrack(); assertEquals(-1L, PreferencesUtils.getRecordingTrackId(context)); assertEquals(-1L, service.getRecordingTrackId()); } @MediumTest public void testIntegration_completeRecordingSession() throws Exception { List<Track> tracks = providerUtils.getAllTracks(); assertTrue(tracks.isEmpty()); fullRecordingSession(); } @MediumTest public void testInsertStatisticsMarker_noRecordingTrack() throws Exception { ITrackRecordingService service = bindAndGetService(createStartIntent()); assertFalse(service.isRecording()); try { service.insertWaypoint(WaypointCreationRequest.DEFAULT_STATISTICS); fail("Expecting IllegalStateException"); } catch (IllegalStateException e) { // Expected. } } @MediumTest public void testInsertStatisticsMarker_validLocation() throws Exception { createDummyTrack(123L, -1L, true); ITrackRecordingService service = bindAndGetService(createStartIntent()); assertTrue(service.isRecording()); assertEquals(1, service.insertWaypoint(WaypointCreationRequest.DEFAULT_STATISTICS)); assertEquals(2, service.insertWaypoint(WaypointCreationRequest.DEFAULT_STATISTICS)); Waypoint wpt = providerUtils.getWaypoint(1); assertEquals(getContext().getString(R.string.marker_statistics_icon_url), wpt.getIcon()); assertEquals(getContext().getString(R.string.marker_edit_type_statistics), wpt.getName()); assertEquals(Waypoint.TYPE_STATISTICS, wpt.getType()); assertEquals(123L, wpt.getTrackId()); assertEquals(0.0, wpt.getLength()); assertNotNull(wpt.getLocation()); assertNotNull(wpt.getStatistics()); // TODO check the rest of the params. // TODO: Check waypoint 2. } @MediumTest public void testInsertWaypointMarker_noRecordingTrack() throws Exception { ITrackRecordingService service = bindAndGetService(createStartIntent()); assertFalse(service.isRecording()); try { service.insertWaypoint(WaypointCreationRequest.DEFAULT_MARKER); fail("Expecting IllegalStateException"); } catch (IllegalStateException e) { // Expected. } } @MediumTest public void testInsertWaypointMarker_validWaypoint() throws Exception { createDummyTrack(123L, -1L, true); ITrackRecordingService service = bindAndGetService(createStartIntent()); assertTrue(service.isRecording()); assertEquals(1, service.insertWaypoint(WaypointCreationRequest.DEFAULT_MARKER)); Waypoint wpt = providerUtils.getWaypoint(1); assertEquals(getContext().getString(R.string.marker_waypoint_icon_url), wpt.getIcon()); assertEquals(getContext().getString(R.string.marker_edit_type_waypoint), wpt.getName()); assertEquals(Waypoint.TYPE_WAYPOINT, wpt.getType()); assertEquals(123L, wpt.getTrackId()); assertEquals(0.0, wpt.getLength()); assertNotNull(wpt.getLocation()); assertNull(wpt.getStatistics()); } @MediumTest public void testWithProperties_noAnnouncementFreq() throws Exception { functionalTest(R.string.announcement_frequency_key, (Object) null); } @MediumTest public void testWithProperties_defaultAnnouncementFreq() throws Exception { functionalTest(R.string.announcement_frequency_key, 1); } @MediumTest public void testWithProperties_noMaxRecordingDist() throws Exception { functionalTest(R.string.max_recording_distance_key, (Object) null); } @MediumTest public void testWithProperties_defaultMaxRecordingDist() throws Exception { functionalTest(R.string.max_recording_distance_key, 5); } @MediumTest public void testWithProperties_noMinRecordingDist() throws Exception { functionalTest(R.string.min_recording_distance_key, (Object) null); } @MediumTest public void testWithProperties_defaultMinRecordingDist() throws Exception { functionalTest(R.string.min_recording_distance_key, 2); } @MediumTest public void testWithProperties_noSplitFreq() throws Exception { functionalTest(R.string.split_frequency_key, (Object) null); } @MediumTest public void testWithProperties_defaultSplitFreqByDist() throws Exception { functionalTest(R.string.split_frequency_key, 5); } @MediumTest public void testWithProperties_defaultSplitFreqByTime() throws Exception { functionalTest(R.string.split_frequency_key, -2); } @MediumTest public void testWithProperties_noMetricUnits() throws Exception { functionalTest(R.string.metric_units_key, (Object) null); } @MediumTest public void testWithProperties_metricUnitsEnabled() throws Exception { functionalTest(R.string.metric_units_key, true); } @MediumTest public void testWithProperties_metricUnitsDisabled() throws Exception { functionalTest(R.string.metric_units_key, false); } @MediumTest public void testWithProperties_noMinRecordingInterval() throws Exception { functionalTest(R.string.min_recording_interval_key, (Object) null); } @MediumTest public void testWithProperties_defaultMinRecordingInterval() throws Exception { functionalTest(R.string.min_recording_interval_key, 3); } @MediumTest public void testWithProperties_noMinRequiredAccuracy() throws Exception { functionalTest(R.string.min_required_accuracy_key, (Object) null); } @MediumTest public void testWithProperties_defaultMinRequiredAccuracy() throws Exception { functionalTest(R.string.min_required_accuracy_key, 500); } @MediumTest public void testWithProperties_noSensorType() throws Exception { functionalTest(R.string.sensor_type_key, (Object) null); } @MediumTest public void testWithProperties_zephyrSensorType() throws Exception { functionalTest(R.string.sensor_type_key, context.getString(R.string.sensor_type_value_zephyr)); } private ITrackRecordingService bindAndGetService(Intent intent) { ITrackRecordingService service = ITrackRecordingService.Stub.asInterface( bindService(intent)); assertNotNull(service); return service; } private Track createDummyTrack(long id, long stopTime, boolean isRecording) { Track dummyTrack = new Track(); dummyTrack.setId(id); dummyTrack.setName("Dummy Track"); TripStatistics tripStatistics = new TripStatistics(); tripStatistics.setStopTime(stopTime); dummyTrack.setStatistics(tripStatistics); addTrack(dummyTrack, isRecording); return dummyTrack; } private void updateAutoResumePrefs(int attempts, int timeoutMins) { Editor editor = sharedPreferences.edit(); editor.putInt(context.getString( R.string.auto_resume_track_current_retry_key), attempts); editor.putInt(context.getString( R.string.auto_resume_track_timeout_key), timeoutMins); editor.apply(); } private Intent createStartIntent() { Intent startIntent = new Intent(); startIntent.setClass(context, TrackRecordingService.class); return startIntent; } private void addTrack(Track track, boolean isRecording) { assertTrue(track.getId() >= 0); providerUtils.insertTrack(track); assertEquals(track.getId(), providerUtils.getTrack(track.getId()).getId()); PreferencesUtils.setRecordingTrackId(context, isRecording ? track.getId() : -1L); } // TODO: We support multiple values for readability, however this test's // base class doesn't properly shutdown the service, so it's not possible // to pass more than 1 value at a time. private void functionalTest(int resourceId, Object ...values) throws Exception { final String key = context.getString(resourceId); for (Object value : values) { // Remove all properties and set the property for the given key. Editor editor = sharedPreferences.edit(); editor.clear(); if (value instanceof String) { editor.putString(key, (String) value); } else if (value instanceof Long) { editor.putLong(key, (Long) value); } else if (value instanceof Integer) { editor.putInt(key, (Integer) value); } else if (value instanceof Boolean) { editor.putBoolean(key, (Boolean) value); } else if (value == null) { // Do nothing, as clear above has already removed this property. } editor.apply(); fullRecordingSession(); } } private void fullRecordingSession() throws Exception { ITrackRecordingService service = bindAndGetService(createStartIntent()); assertFalse(service.isRecording()); // Start a track. long id = service.startNewTrack(); assertTrue(id >= 0); assertTrue(service.isRecording()); Track track = providerUtils.getTrack(id); assertNotNull(track); assertEquals(id, track.getId()); assertEquals(id, PreferencesUtils.getRecordingTrackId(context)); assertEquals(id, service.getRecordingTrackId()); // Insert a few points, markers and statistics. long startTime = System.currentTimeMillis(); for (int i = 0; i < 30; i++) { Location loc = new Location("gps"); loc.setLongitude(35.0f + i / 10.0f); loc.setLatitude(45.0f - i / 5.0f); loc.setAccuracy(5); loc.setSpeed(10); loc.setTime(startTime + i * 10000); loc.setBearing(3.0f); service.recordLocation(loc); if (i % 10 == 0) { service.insertWaypoint(WaypointCreationRequest.DEFAULT_STATISTICS); } else if (i % 7 == 0) { service.insertWaypoint(WaypointCreationRequest.DEFAULT_MARKER); } } // Stop the track. Validate if it has correct data. service.endCurrentTrack(); assertFalse(service.isRecording()); assertEquals(-1L, service.getRecordingTrackId()); track = providerUtils.getTrack(id); assertNotNull(track); assertEquals(id, track.getId()); TripStatistics tripStatistics = track.getStatistics(); assertNotNull(tripStatistics); assertTrue(tripStatistics.getStartTime() > 0); assertTrue(tripStatistics.getStopTime() >= tripStatistics.getStartTime()); } }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks; import com.google.android.apps.mytracks.ChartValueSeries.ZoomSettings; import com.google.android.maps.mytracks.R; import android.graphics.Paint.Style; import android.test.AndroidTestCase; /** * @author Sandor Dornbush */ public class ChartValueSeriesTest extends AndroidTestCase { private ChartValueSeries series; @Override protected void setUp() throws Exception { series = new ChartValueSeries(getContext(), R.color.elevation_fill, R.color.elevation_border, new ZoomSettings(5, new int[] {100}), R.string.stat_elevation); } public void testInitialConditions() { assertEquals(0, series.getInterval()); assertEquals(1, series.getMaxLabelLength()); assertEquals(0, series.getMin()); assertEquals(0, series.getMax()); assertEquals(0.0, series.getSpread()); assertEquals(Style.STROKE, series.getPaint().getStyle()); assertEquals(getContext().getString(R.string.stat_elevation), series.getTitle()); assertTrue(series.isEnabled()); } public void testEnabled() { series.setEnabled(false); assertFalse(series.isEnabled()); } public void testSmallUpdates() { series.update(0); series.update(10); series.updateDimension(); assertEquals(100, series.getInterval()); assertEquals(3, series.getMaxLabelLength()); assertEquals(0, series.getMin()); assertEquals(100, series.getMax()); assertEquals(100.0, series.getSpread()); } public void testBigUpdates() { series.update(0); series.update(901); series.updateDimension(); assertEquals(100, series.getInterval()); assertEquals(5, series.getMaxLabelLength()); assertEquals(0, series.getMin()); assertEquals(1000, series.getMax()); assertEquals(1000.0, series.getSpread()); } public void testNotZeroBasedUpdates() { series.update(500); series.update(1401); series.updateDimension(); assertEquals(100, series.getInterval()); assertEquals(5, series.getMaxLabelLength()); assertEquals(500, series.getMin()); assertEquals(1500, series.getMax()); assertEquals(1000.0, series.getSpread()); } public void testZoomSettings_invalidArgs() { try { new ZoomSettings(0, new int[] {10, 50, 100}); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException e) { // OK. } try { new ZoomSettings(1, null); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException e) { // OK. } try { new ZoomSettings(1, new int[] {}); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException e) { // OK. } try { new ZoomSettings(1, new int[] {1, 3, 2}); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException e) { // OK. } } public void testZoomSettings_minAligned() { ZoomSettings settings = new ZoomSettings(5, new int[] {10, 50, 100}); assertEquals(10, settings.calculateInterval(0, 15)); assertEquals(10, settings.calculateInterval(0, 50)); assertEquals(50, settings.calculateInterval(0, 111)); assertEquals(50, settings.calculateInterval(0, 250)); assertEquals(100, settings.calculateInterval(0, 251)); assertEquals(100, settings.calculateInterval(0, 10000)); } public void testZoomSettings_minNotAligned() { ZoomSettings settings = new ZoomSettings(5, new int[] {10, 50, 100}); assertEquals(50, settings.calculateInterval(5, 55)); assertEquals(10, settings.calculateInterval(10, 60)); assertEquals(50, settings.calculateInterval(7, 250)); assertEquals(100, settings.calculateInterval(7, 257)); assertEquals(100, settings.calculateInterval(11, 10000)); // A regression test. settings = new ZoomSettings(5, new int[] {5, 10, 20}); assertEquals(10, settings.calculateInterval(-37.14, -11.89)); } }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.stats; import junit.framework.TestCase; /** * Tests for {@link TripStatistics}. * This only tests non-trivial pieces of that class. * * @author Rodrigo Damazio */ public class TripStatisticsTest extends TestCase { private TripStatistics statistics; @Override protected void setUp() throws Exception { super.setUp(); statistics = new TripStatistics(); } public void testSetBounds() { // This is not a trivial setter, conversion happens in it statistics.setBounds(12345, -34567, 56789, -98765); assertEquals(12345, statistics.getLeft()); assertEquals(-34567, statistics.getTop()); assertEquals(56789, statistics.getRight()); assertEquals(-98765, statistics.getBottom()); } public void testMerge() { TripStatistics statistics2 = new TripStatistics(); statistics.setStartTime(1000L); // Resulting start time statistics.setStopTime(2500L); statistics2.setStartTime(3000L); statistics2.setStopTime(4000L); // Resulting stop time statistics.setTotalTime(1500L); statistics2.setTotalTime(1000L); // Result: 1500+1000 statistics.setMovingTime(700L); statistics2.setMovingTime(600L); // Result: 700+600 statistics.setTotalDistance(750.0); statistics2.setTotalDistance(350.0); // Result: 750+350 statistics.setTotalElevationGain(50.0); statistics2.setTotalElevationGain(850.0); // Result: 850+50 statistics.setMaxSpeed(60.0); // Resulting max speed statistics2.setMaxSpeed(30.0); statistics.setMaxElevation(1250.0); statistics.setMinElevation(1200.0); // Resulting min elevation statistics2.setMaxElevation(3575.0); // Resulting max elevation statistics2.setMinElevation(2800.0); statistics.setMaxGrade(15.0); statistics.setMinGrade(-25.0); // Resulting min grade statistics2.setMaxGrade(35.0); // Resulting max grade statistics2.setMinGrade(0.0); // Resulting bounds: -10000, 35000, 30000, -40000 statistics.setBounds(-10000, 20000, 30000, -40000); statistics2.setBounds(-5000, 35000, 0, 20000); statistics.merge(statistics2); assertEquals(1000L, statistics.getStartTime()); assertEquals(4000L, statistics.getStopTime()); assertEquals(2500L, statistics.getTotalTime()); assertEquals(1300L, statistics.getMovingTime()); assertEquals(1100.0, statistics.getTotalDistance()); assertEquals(900.0, statistics.getTotalElevationGain()); assertEquals(60.0, statistics.getMaxSpeed()); assertEquals(-10000, statistics.getLeft()); assertEquals(30000, statistics.getRight()); assertEquals(35000, statistics.getTop()); assertEquals(-40000, statistics.getBottom()); assertEquals(1200.0, statistics.getMinElevation()); assertEquals(3575.0, statistics.getMaxElevation()); assertEquals(-25.0, statistics.getMinGrade()); assertEquals(35.0, statistics.getMaxGrade()); } public void testGetAverageSpeed() { statistics.setTotalDistance(1000.0); statistics.setTotalTime(50000); // in milliseconds assertEquals(20.0, statistics.getAverageSpeed()); } public void testGetAverageMovingSpeed() { statistics.setTotalDistance(1000.0); statistics.setMovingTime(20000); // in milliseconds assertEquals(50.0, statistics.getAverageMovingSpeed()); } }
Java
// Copyright 2009 Google Inc. All Rights Reserved. package com.google.android.apps.mytracks.stats; import com.google.android.apps.mytracks.Constants; import android.location.Location; import junit.framework.TestCase; /** * Test the the function of the TripStatisticsBuilder class. * * @author Sandor Dornbush */ public class TripStatisticsBuilderTest extends TestCase { private TripStatisticsBuilder builder = null; @Override protected void setUp() throws Exception { super.setUp(); builder = new TripStatisticsBuilder(System.currentTimeMillis()); } public void testAddLocationSimple() throws Exception { builder = new TripStatisticsBuilder(1000); TripStatistics stats = builder.getStatistics(); assertEquals(0.0, builder.getSmoothedElevation()); assertEquals(Double.POSITIVE_INFINITY, stats.getMinElevation()); assertEquals(Double.NEGATIVE_INFINITY, stats.getMaxElevation()); assertEquals(0.0, stats.getMaxSpeed()); assertEquals(Double.POSITIVE_INFINITY, stats.getMinGrade()); assertEquals(Double.NEGATIVE_INFINITY, stats.getMaxGrade()); assertEquals(0.0, stats.getTotalElevationGain()); assertEquals(0, stats.getMovingTime()); assertEquals(0.0, stats.getTotalDistance()); for (int i = 0; i < 100; i++) { Location l = new Location("test"); l.setAccuracy(1.0f); l.setLongitude(45.0); // Going up by 5 meters each time. l.setAltitude(i); // Moving by .1% of a degree latitude. l.setLatitude(i * .001); l.setSpeed(11.1f); // Each time slice is 10 seconds. long time = 1000 + 10000 * i; l.setTime(time); boolean moving = builder.addLocation(l, time); assertEquals((i != 0), moving); stats = builder.getStatistics(); assertEquals(10000 * i, stats.getTotalTime()); assertEquals(10000 * i, stats.getMovingTime()); assertEquals(i, builder.getSmoothedElevation(), Constants.ELEVATION_SMOOTHING_FACTOR / 2); assertEquals(0.0, stats.getMinElevation()); assertEquals(i, stats.getMaxElevation(), Constants.ELEVATION_SMOOTHING_FACTOR / 2); assertEquals(i, stats.getTotalElevationGain(), Constants.ELEVATION_SMOOTHING_FACTOR); if (i > Constants.SPEED_SMOOTHING_FACTOR) { assertEquals(11.1f, stats.getMaxSpeed(), 0.1); } if ((i > Constants.GRADE_SMOOTHING_FACTOR) && (i > Constants.ELEVATION_SMOOTHING_FACTOR)) { assertEquals(0.009, stats.getMinGrade(), 0.0001); assertEquals(0.009, stats.getMaxGrade(), 0.0001); } // 1 degree = 111 km // 1 timeslice = 0.001 degree = 111 m assertEquals(111.0 * i, stats.getTotalDistance(), 100); } } /** * Test that elevation works if the user is stable. */ public void testElevationSimple() throws Exception { for (double elevation = 0; elevation < 1000; elevation += 10) { builder = new TripStatisticsBuilder(System.currentTimeMillis()); for (int j = 0; j < 100; j++) { assertEquals(0.0, builder.updateElevation(elevation)); assertEquals(elevation, builder.getSmoothedElevation()); TripStatistics data = builder.getStatistics(); assertEquals(elevation, data.getMinElevation()); assertEquals(elevation, data.getMaxElevation()); assertEquals(0.0, data.getTotalElevationGain()); } } } public void testElevationGain() throws Exception { for (double i = 0; i < 1000; i++) { double expectedGain; if (i < (Constants.ELEVATION_SMOOTHING_FACTOR - 1)) { expectedGain = 0; } else if (i < Constants.ELEVATION_SMOOTHING_FACTOR) { expectedGain = 0.5; } else { expectedGain = 1.0; } assertEquals(expectedGain, builder.updateElevation(i)); assertEquals(i, builder.getSmoothedElevation(), 20); TripStatistics data = builder.getStatistics(); assertEquals(0.0, data.getMinElevation(), 0.0); assertEquals(i, data.getMaxElevation(), Constants.ELEVATION_SMOOTHING_FACTOR); assertEquals(i, data.getTotalElevationGain(), Constants.ELEVATION_SMOOTHING_FACTOR); } } public void testGradeSimple() throws Exception { for (double i = 0; i < 1000; i++) { // The value of the elevation does not matter. This is just to fill the // buffer. builder.updateElevation(i); builder.updateGrade(100, 100); if ((i > Constants.GRADE_SMOOTHING_FACTOR) && (i > Constants.ELEVATION_SMOOTHING_FACTOR)) { assertEquals(1.0, builder.getStatistics().getMaxGrade()); assertEquals(1.0, builder.getStatistics().getMinGrade()); } } for (double i = 0; i < 1000; i++) { // The value of the elevation does not matter. This is just to fill the // buffer. builder.updateElevation(i); builder.updateGrade(100, -100); if ((i > Constants.GRADE_SMOOTHING_FACTOR) && (i > Constants.ELEVATION_SMOOTHING_FACTOR)) { assertEquals(1.0, builder.getStatistics().getMaxGrade()); assertEquals(-1.0, builder.getStatistics().getMinGrade()); } } } public void testGradeIgnoreShort() throws Exception { for (double i = 0; i < 100; i++) { // The value of the elevation does not matter. This is just to fill the // buffer. builder.updateElevation(i); builder.updateGrade(1, 100); assertEquals(Double.NEGATIVE_INFINITY, builder.getStatistics().getMaxGrade()); assertEquals(Double.POSITIVE_INFINITY, builder.getStatistics().getMinGrade()); } } public void testUpdateSpeedIncludeZero() { for (int i = 0; i < 1000; i++) { builder.updateSpeed(i + 1000, 0.0, i, 4.0); assertEquals(0.0, builder.getStatistics().getMaxSpeed()); assertEquals((i + 1) * 1000, builder.getStatistics().getMovingTime()); } } public void testUpdateSpeedIngoreErrorCode() { builder.updateSpeed(12345000, 128.0, 12344000, 0.0); assertEquals(0.0, builder.getStatistics().getMaxSpeed()); assertEquals(1000, builder.getStatistics().getMovingTime()); } public void testUpdateSpeedIngoreLargeAcceleration() { builder.updateSpeed(12345000, 100.0, 12344000, 1.0); assertEquals(0.0, builder.getStatistics().getMaxSpeed()); assertEquals(1000, builder.getStatistics().getMovingTime()); } public void testUpdateSpeed() { for (int i = 0; i < 1000; i++) { builder.updateSpeed(i + 1000, 4.0, i, 4.0); assertEquals((i + 1) * 1000, builder.getStatistics().getMovingTime()); if (i > Constants.SPEED_SMOOTHING_FACTOR) { assertEquals(4.0, builder.getStatistics().getMaxSpeed()); } } } }
Java
/* * Copyright 2009 Google Inc. All Rights Reserved. */ package com.google.android.apps.mytracks.stats; import junit.framework.TestCase; /** * Test for the DoubleBuffer class. * * @author Sandor Dornbush */ public class DoubleBufferTest extends TestCase { /** * Tests that the constructor leaves the buffer in a valid state. */ public void testConstructor() { DoubleBuffer buffer = new DoubleBuffer(10); assertFalse(buffer.isFull()); assertEquals(0.0, buffer.getAverage()); double[] averageAndVariance = buffer.getAverageAndVariance(); assertEquals(0.0, averageAndVariance[0]); assertEquals(0.0, averageAndVariance[1]); } /** * Simple test with 10 of the same values. */ public void testBasic() { DoubleBuffer buffer = new DoubleBuffer(10); for (int i = 0; i < 9; i++) { buffer.setNext(1.0); assertFalse(buffer.isFull()); assertEquals(1.0, buffer.getAverage()); double[] averageAndVariance = buffer.getAverageAndVariance(); assertEquals(1.0, averageAndVariance[0]); assertEquals(0.0, averageAndVariance[1]); } buffer.setNext(1); assertTrue(buffer.isFull()); assertEquals(1.0, buffer.getAverage()); double[] averageAndVariance = buffer.getAverageAndVariance(); assertEquals(1.0, averageAndVariance[0]); assertEquals(0.0, averageAndVariance[1]); } /** * Tests with 5 entries of -10 and 5 entries of 10. */ public void testSplit() { DoubleBuffer buffer = new DoubleBuffer(10); for (int i = 0; i < 5; i++) { buffer.setNext(-10); assertFalse(buffer.isFull()); assertEquals(-10.0, buffer.getAverage()); double[] averageAndVariance = buffer.getAverageAndVariance(); assertEquals(-10.0, averageAndVariance[0]); assertEquals(0.0, averageAndVariance[1]); } for (int i = 1; i < 5; i++) { buffer.setNext(10); assertFalse(buffer.isFull()); double expectedAverage = ((i * 10.0) - 50.0) / (i + 5); assertEquals(buffer.toString(), expectedAverage, buffer.getAverage(), 0.01); double[] averageAndVariance = buffer.getAverageAndVariance(); assertEquals(expectedAverage, averageAndVariance[0]); } buffer.setNext(10); assertTrue(buffer.isFull()); assertEquals(0.0, buffer.getAverage()); double[] averageAndVariance = buffer.getAverageAndVariance(); assertEquals(0.0, averageAndVariance[0]); assertEquals(100.0, averageAndVariance[1]); } /** * Tests that reset leaves the buffer in a valid state. */ public void testReset() { DoubleBuffer buffer = new DoubleBuffer(10); for (int i = 0; i < 100; i++) { buffer.setNext(i); } assertTrue(buffer.isFull()); buffer.reset(); assertFalse(buffer.isFull()); assertEquals(0.0, buffer.getAverage()); double[] averageAndVariance = buffer.getAverageAndVariance(); assertEquals(0.0, averageAndVariance[0]); assertEquals(0.0, averageAndVariance[1]); } /** * Tests that if a lot of items are inserted the smoothing and looping works. */ public void testLoop() { DoubleBuffer buffer = new DoubleBuffer(10); for (int i = 0; i < 1000; i++) { buffer.setNext(i); assertEquals(i >= 9, buffer.isFull()); if (i > 10) { assertEquals(i - 4.5, buffer.getAverage()); } } } }
Java
/** * Copyright 2009 Google Inc. All Rights Reserved. */ package com.google.android.apps.mytracks.stats; import junit.framework.TestCase; import java.util.Random; /** * This class test the ExtremityMonitor class. * * @author Sandor Dornbush */ public class ExtremityMonitorTest extends TestCase { public ExtremityMonitorTest(String name) { super(name); } public void testInitialize() { ExtremityMonitor monitor = new ExtremityMonitor(); assertEquals(Double.POSITIVE_INFINITY, monitor.getMin()); assertEquals(Double.NEGATIVE_INFINITY, monitor.getMax()); } public void testSimple() { ExtremityMonitor monitor = new ExtremityMonitor(); assertTrue(monitor.update(0)); assertTrue(monitor.update(1)); assertEquals(0.0, monitor.getMin()); assertEquals(1.0, monitor.getMax()); assertFalse(monitor.update(1)); assertFalse(monitor.update(0.5)); } /** * Throws a bunch of random numbers between [0,1] at the monitor. */ public void testRandom() { ExtremityMonitor monitor = new ExtremityMonitor(); Random random = new Random(42); for (int i = 0; i < 1000; i++) { monitor.update(random.nextDouble()); } assertTrue(monitor.getMin() < 0.1); assertTrue(monitor.getMax() < 1.0); assertTrue(monitor.getMin() >= 0.0); assertTrue(monitor.getMax() > 0.9); } public void testReset() { ExtremityMonitor monitor = new ExtremityMonitor(); assertTrue(monitor.update(0)); assertTrue(monitor.update(1)); monitor.reset(); assertEquals(Double.POSITIVE_INFINITY, monitor.getMin()); assertEquals(Double.NEGATIVE_INFINITY, monitor.getMax()); assertTrue(monitor.update(0)); assertTrue(monitor.update(1)); assertEquals(0.0, monitor.getMin()); assertEquals(1.0, monitor.getMax()); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.content; import com.google.android.apps.mytracks.content.SearchEngine.ScoredResult; import com.google.android.apps.mytracks.content.SearchEngine.SearchQuery; import com.google.android.apps.mytracks.services.TrackRecordingServiceTest.MockContext; import com.google.android.apps.mytracks.stats.TripStatistics; import android.content.ContentUris; import android.location.Location; import android.net.Uri; import android.test.AndroidTestCase; import android.test.RenamingDelegatingContext; import android.test.mock.MockContentResolver; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * Tests for {@link SearchEngine}. * These are not meant to be quality tests, but instead feature-by-feature tests * (in other words, they don't test the mixing of different score boostings, just * each boosting separately) * * @author Rodrigo Damazio */ public class SearchEngineTest extends AndroidTestCase { private static final Location HERE = new Location("gps"); private static final long NOW = 1234567890000L; // After OLDEST_ALLOWED_TIMESTAMP private MyTracksProviderUtils providerUtils; private SearchEngine engine; @Override protected void setUp() throws Exception { super.setUp(); MockContentResolver mockContentResolver = new MockContentResolver(); RenamingDelegatingContext targetContext = new RenamingDelegatingContext( getContext(), getContext(), "test."); MockContext context = new MockContext(mockContentResolver, targetContext); MyTracksProvider provider = new MyTracksProvider(); provider.attachInfo(context, null); mockContentResolver.addProvider(MyTracksProviderUtils.AUTHORITY, provider); setContext(context); providerUtils = MyTracksProviderUtils.Factory.get(context); engine = new SearchEngine(providerUtils); } @Override protected void tearDown() throws Exception { providerUtils.deleteAllTracks(); super.tearDown(); } private long insertTrack(String title, String description, String category, double distance, long hoursAgo) { Track track = new Track(); track.setName(title); track.setDescription(description); track.setCategory(category); TripStatistics stats = track.getStatistics(); if (hoursAgo > 0) { // Started twice hoursAgo, so the average time is hoursAgo. stats.setStartTime(NOW - hoursAgo * 1000L * 60L * 60L * 2); stats.setStopTime(NOW); } int latitude = (int) ((HERE.getLatitude() + distance) * 1E6); int longitude = (int) ((HERE.getLongitude() + distance) * 1E6); stats.setBounds(latitude, longitude, latitude, longitude); Uri uri = providerUtils.insertTrack(track); return ContentUris.parseId(uri); } private long insertTrack(String title, String description, String category) { return insertTrack(title, description, category, 0, -1); } private long insertTrack(String title, double distance) { return insertTrack(title, "", "", distance, -1); } private long insertTrack(String title, long hoursAgo) { return insertTrack(title, "", "", 0.0, hoursAgo); } private long insertWaypoint(String title, String description, String category, double distance, long hoursAgo, long trackId) { Waypoint waypoint = new Waypoint(); waypoint.setName(title); waypoint.setDescription(description); waypoint.setCategory(category); waypoint.setTrackId(trackId); Location location = new Location(HERE); location.setLatitude(location.getLatitude() + distance); location.setLongitude(location.getLongitude() + distance); if (hoursAgo >= 0) { location.setTime(NOW - hoursAgo * 1000L * 60L * 60L); } waypoint.setLocation(location); Uri uri = providerUtils.insertWaypoint(waypoint); return ContentUris.parseId(uri); } private long insertWaypoint(String title, String description, String category) { return insertWaypoint(title, description, category, 0.0, -1, -1); } private long insertWaypoint(String title, double distance) { return insertWaypoint(title, "", "", distance, -1, -1); } private long insertWaypoint(String title, long hoursAgo) { return insertWaypoint(title, "", "", 0.0, hoursAgo, -1); } private long insertWaypoint(String title, long hoursAgo, long trackId) { return insertWaypoint(title, "", "", 0.0, hoursAgo, trackId); } public void testSearchText() { // Insert 7 tracks (purposefully out of result order): // - one which won't match // - one which will match the description // - one which will match the category // - one which will match the title // - one which will match in title and category // - one which will match in title and description // - one which will match in all fields insertTrack("bb", "cc", "dd"); long descriptionMatchId = insertTrack("bb", "aa", "cc"); long categoryMatchId = insertTrack("bb", "cc", "aa"); long titleMatchId = insertTrack("aa", "bb", "cc"); long titleCategoryMatchId = insertTrack("aa", "bb", "ca"); long titleDescriptionMatchId = insertTrack("aa", "ba", "cc"); long allMatchId = insertTrack("aa", "ba", "ca"); SearchQuery query = new SearchQuery("a", null, -1, NOW); ArrayList<ScoredResult> results = new ArrayList<ScoredResult>(engine.search(query)); // Title > Description > Category. assertTrackResults(results, allMatchId, titleDescriptionMatchId, titleCategoryMatchId, titleMatchId, descriptionMatchId, categoryMatchId); } public void testSearchWaypointText() { // Insert 7 waypoints (purposefully out of result order): // - one which won't match // - one which will match the description // - one which will match the category // - one which will match the title // - one which will match in title and category // - one which will match in title and description // - one which will match in all fields insertWaypoint("bb", "cc", "dd"); long descriptionMatchId = insertWaypoint("bb", "aa", "cc"); long categoryMatchId = insertWaypoint("bb", "cc", "aa"); long titleMatchId = insertWaypoint("aa", "bb", "cc"); long titleCategoryMatchId = insertWaypoint("aa", "bb", "ca"); long titleDescriptionMatchId = insertWaypoint("aa", "ba", "cc"); long allMatchId = insertWaypoint("aa", "ba", "ca"); SearchQuery query = new SearchQuery("a", null, -1, NOW); ArrayList<ScoredResult> results = new ArrayList<ScoredResult>(engine.search(query)); // Title > Description > Category. assertWaypointResults(results, allMatchId, titleDescriptionMatchId, titleCategoryMatchId, titleMatchId, descriptionMatchId, categoryMatchId); } public void testSearchMixedText() { // Insert 5 entries (purposefully out of result order): // - one waypoint which will match by description // - one waypoint which won't match // - one waypoint which will match by title // - one track which won't match // - one track which will match by title long descriptionWaypointId = insertWaypoint("bb", "aa", "cc"); insertWaypoint("bb", "cc", "dd"); long titleWaypointId = insertWaypoint("aa", "bb", "cc"); insertTrack("bb", "cc", "dd"); long trackId = insertTrack("aa", "bb", "cc"); SearchQuery query = new SearchQuery("a", null, -1, NOW); ArrayList<ScoredResult> results = new ArrayList<ScoredResult>(engine.search(query)); // Title > Description > Category. assertEquals(results.toString(), 3, results.size()); assertTrackResult(trackId, results.get(0)); assertWaypointResult(titleWaypointId, results.get(1)); assertWaypointResult(descriptionWaypointId, results.get(2)); } public void testSearchTrackDistance() { // All results match text, but they're at difference distances from the user. long farFarAwayId = insertTrack("aa", 0.3); long nearId = insertTrack("ab", 0.1); long farId = insertTrack("ac", 0.2); SearchQuery query = new SearchQuery("a", HERE, -1, NOW); ArrayList<ScoredResult> results = new ArrayList<ScoredResult>(engine.search(query)); // Distance order. assertTrackResults(results, nearId, farId, farFarAwayId); } public void testSearchWaypointDistance() { // All results match text, but they're at difference distances from the user. long farFarAwayId = insertWaypoint("aa", 0.3); long nearId = insertWaypoint("ab", 0.1); long farId = insertWaypoint("ac", 0.2); SearchQuery query = new SearchQuery("a", HERE, -1, NOW); ArrayList<ScoredResult> results = new ArrayList<ScoredResult>(engine.search(query)); // Distance order. assertWaypointResults(results, nearId, farId, farFarAwayId); } public void testSearchTrackRecent() { // All results match text, but they're were recorded at different times. long oldestId = insertTrack("aa", 3); long recentId = insertTrack("ab", 1); long oldId = insertTrack("ac", 2); SearchQuery query = new SearchQuery("a", null, -1, NOW); ArrayList<ScoredResult> results = new ArrayList<ScoredResult>(engine.search(query)); // Reverse time order. assertTrackResults(results, recentId, oldId, oldestId); } public void testSearchWaypointRecent() { // All results match text, but they're were recorded at different times. long oldestId = insertWaypoint("aa", 2); long recentId = insertWaypoint("ab", 0); long oldId = insertWaypoint("ac", 1); SearchQuery query = new SearchQuery("a", null, -1, NOW); ArrayList<ScoredResult> results = new ArrayList<ScoredResult>(engine.search(query)); // Reverse time order. assertWaypointResults(results, recentId, oldId, oldestId); } public void testSearchCurrentTrack() { // All results match text, but one of them is the current track. long currentId = insertTrack("ab", 1); long otherId = insertTrack("aa", 1); SearchQuery query = new SearchQuery("a", null, currentId, NOW); ArrayList<ScoredResult> results = new ArrayList<ScoredResult>(engine.search(query)); // Current track should be demoted. assertTrackResults(results, otherId, currentId); } public void testSearchCurrentTrackWaypoint() { // All results match text, but one of them is in the current track. long otherId = insertWaypoint("aa", 1, 456); long currentId = insertWaypoint("ab", 1, 123); SearchQuery query = new SearchQuery("a", null, 123, NOW); ArrayList<ScoredResult> results = new ArrayList<ScoredResult>(engine.search(query)); // Waypoint in current track should be promoted. assertWaypointResults(results, currentId, otherId); } private void assertTrackResult(long trackId, ScoredResult result) { assertNotNull("Not a track", result.track); assertNull("Ambiguous result", result.waypoint); assertEquals(trackId, result.track.getId()); } private void assertTrackResults(List<ScoredResult> results, long... trackIds) { String errMsg = "Expected IDs=" + Arrays.toString(trackIds) + "; results=" + results; assertEquals(results.size(), trackIds.length); for (int i = 0; i < results.size(); i++) { ScoredResult result = results.get(i); assertNotNull(errMsg, result.track); assertNull(errMsg, result.waypoint); assertEquals(errMsg, trackIds[i], result.track.getId()); } } private void assertWaypointResult(long waypointId, ScoredResult result) { assertNotNull("Not a waypoint", result.waypoint); assertNull("Ambiguous result", result.track); assertEquals(waypointId, result.waypoint.getId()); } private void assertWaypointResults(List<ScoredResult> results, long... waypointIds) { String errMsg = "Expected IDs=" + Arrays.toString(waypointIds) + "; results=" + results; assertEquals(results.size(), waypointIds.length); for (int i = 0; i < results.size(); i++) { ScoredResult result = results.get(i); assertNotNull(errMsg, result.waypoint); assertNull(errMsg, result.track); assertEquals(errMsg, waypointIds[i], result.waypoint.getId()); } } }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.content; import com.google.android.apps.mytracks.content.WaypointCreationRequest.WaypointType; import android.os.Parcel; import android.test.AndroidTestCase; /** * Tests for the WaypointCreationRequest class. * {@link WaypointCreationRequest} * * @author Sandor Dornbush */ public class WaypointCreationRequestTest extends AndroidTestCase { public void testTypeParceling() { WaypointCreationRequest original = WaypointCreationRequest.DEFAULT_MARKER; Parcel p = Parcel.obtain(); original.writeToParcel(p, 0); p.setDataPosition(0); WaypointCreationRequest copy = WaypointCreationRequest.CREATOR.createFromParcel(p); assertEquals(original.getType(), copy.getType()); assertNull(copy.getName()); assertNull(copy.getDescription()); assertNull(copy.getIconUrl()); } public void testAllAttributesParceling() { WaypointCreationRequest original = new WaypointCreationRequest(WaypointType.MARKER, "name", "category", "description", "img.png"); Parcel p = Parcel.obtain(); original.writeToParcel(p, 0); p.setDataPosition(0); WaypointCreationRequest copy = WaypointCreationRequest.CREATOR.createFromParcel(p); assertEquals(original.getType(), copy.getType()); assertEquals("name", copy.getName()); assertEquals("category", copy.getCategory()); assertEquals("description", copy.getDescription()); assertEquals("img.png", copy.getIconUrl()); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.content; import com.google.android.apps.mytracks.stats.TripStatistics; import com.google.android.apps.mytracks.util.StringUtils; import com.google.android.maps.mytracks.R; import android.test.AndroidTestCase; import android.util.Pair; /** * Tests for {@link DescriptionGeneratorImpl}. * * @author Jimmy Shih */ public class DescriptionGeneratorImplTest extends AndroidTestCase { private static final long START_TIME = 1288721514000L; private DescriptionGeneratorImpl descriptionGenerator; @Override protected void setUp() throws Exception { descriptionGenerator = new DescriptionGeneratorImpl(getContext()); } /** * Tests {@link DescriptionGeneratorImpl#generateTrackDescription(Track, * java.util.Vector, java.util.Vector)}. */ public void testGenerateTrackDescription() { Track track = new Track(); TripStatistics stats = new TripStatistics(); stats.setTotalDistance(20000); stats.setTotalTime(600000); stats.setMovingTime(300000); stats.setMaxSpeed(100); stats.setMaxElevation(550); stats.setMinElevation(-500); stats.setTotalElevationGain(6000); stats.setMaxGrade(0.42); stats.setMinGrade(0.11); stats.setStartTime(START_TIME); track.setStatistics(stats); track.setCategory("hiking"); String expected = "Created by" + " <a href='http://www.google.com/mobile/mytracks'>My Tracks</a> on Android.<p>" + "Total distance: 20.00 km (12.4 mi)<br>" + "Total time: 10:00<br>" + "Moving time: 05:00<br>" + "Average speed: 120.00 km/h (74.6 mi/h)<br>" + "Average moving speed: 240.00 km/h (149.1 mi/h)<br>" + "Max speed: 360.00 km/h (223.7 mi/h)<br>" + "Average pace: 0.50 min/km (0.8 min/mi)<br>" + "Average moving pace: 0.25 min/km (0.4 min/mi)<br>" + "Fastest pace: 0.17 min/km (0.3 min/mi)<br>" + "Max elevation: 550 m (1804 ft)<br>" + "Min elevation: -500 m (-1640 ft)<br>" + "Elevation gain: 6000 m (19685 ft)<br>" + "Max grade: 42 %<br>" + "Min grade: 11 %<br>" + "Recorded: " + StringUtils.formatDateTime(getContext(), START_TIME) + "<br>" + "Activity type: hiking<br>"; assertEquals(expected, descriptionGenerator.generateTrackDescription(track, null, null)); } /** * Tests {@link DescriptionGeneratorImpl#generateWaypointDescription(Waypoint)}. */ public void testGenerateWaypointDescription() { Waypoint waypoint = new Waypoint(); TripStatistics stats = new TripStatistics(); stats.setTotalDistance(20000); stats.setTotalTime(600000); stats.setMovingTime(300000); stats.setMaxSpeed(100); stats.setMaxElevation(550); stats.setMinElevation(-500); stats.setTotalElevationGain(6000); stats.setMaxGrade(0.42); stats.setMinGrade(0.11); stats.setStartTime(START_TIME); waypoint.setStatistics(stats); String expected = "Total distance: 20.00 km (12.4 mi)\n" + "Total time: 10:00\n" + "Moving time: 05:00\n" + "Average speed: 120.00 km/h (74.6 mi/h)\n" + "Average moving speed: 240.00 km/h (149.1 mi/h)\n" + "Max speed: 360.00 km/h (223.7 mi/h)\n" + "Average pace: 0.50 min/km (0.8 min/mi)\n" + "Average moving pace: 0.25 min/km (0.4 min/mi)\n" + "Fastest pace: 0.17 min/km (0.3 min/mi)\n" + "Max elevation: 550 m (1804 ft)\n" + "Min elevation: -500 m (-1640 ft)\n" + "Elevation gain: 6000 m (19685 ft)\n" + "Max grade: 42 %\n" + "Min grade: 11 %\n" + "Recorded: " + StringUtils.formatDateTime(getContext(), START_TIME) + "\n"; assertEquals(expected, descriptionGenerator.generateWaypointDescription(waypoint)); } /** * Tests {@link DescriptionGeneratorImpl#writeDistance(double, StringBuilder, * int, String)}. */ public void testWriteDistance() { StringBuilder builder = new StringBuilder(); descriptionGenerator.writeDistance(1100, builder, R.string.description_total_distance, "<br>"); assertEquals("Total distance: 1.10 km (0.7 mi)<br>", builder.toString()); } /** * Tests {@link DescriptionGeneratorImpl#writeTime(long, StringBuilder, int, * String)}. */ public void testWriteTime() { StringBuilder builder = new StringBuilder(); descriptionGenerator.writeTime(1000, builder, R.string.description_total_time, "<br>"); assertEquals("Total time: 00:01<br>", builder.toString()); } /** * Tests {@link DescriptionGeneratorImpl#writeSpeed(double, StringBuilder, * int, String)}. */ public void testWriteSpeed() { StringBuilder builder = new StringBuilder(); descriptionGenerator.writeSpeed(1.1, builder, R.string.description_average_speed, "\n"); assertEquals("Average speed: 3.96 km/h (2.5 mi/h)\n", builder.toString()); } /** * Tests {@link DescriptionGeneratorImpl#writeElevation(double, StringBuilder, * int, String)}. */ public void testWriteElevation() { StringBuilder builder = new StringBuilder(); descriptionGenerator.writeElevation(4.2, builder, R.string.description_min_elevation, "<br>"); assertEquals("Min elevation: 4 m (14 ft)<br>", builder.toString()); } /** * Tests {@link DescriptionGeneratorImpl#writePace(Pair, StringBuilder, int, * String)}. */ public void testWritePace() { StringBuilder builder = new StringBuilder(); descriptionGenerator.writePace( new Pair<Double, Double>(1.1, 2.2), builder, R.string.description_average_pace, "\n"); assertEquals("Average pace: 54.55 min/km (27.3 min/mi)\n", builder.toString()); } /** * Tests {@link DescriptionGeneratorImpl#writeGrade(double, StringBuilder, * int, String)}. */ public void testWriteGrade() { StringBuilder builder = new StringBuilder(); descriptionGenerator.writeGrade(.042, builder, R.string.description_max_grade, "<br>"); assertEquals("Max grade: 4 %<br>", builder.toString()); } /** * Tests {@link DescriptionGeneratorImpl#writeGrade(double, StringBuilder, * int, String)} with a NaN. */ public void testWriteGrade_nan() { StringBuilder builder = new StringBuilder(); descriptionGenerator.writeGrade(Double.NaN, builder, R.string.description_max_grade, "<br>"); assertEquals("Max grade: 0 %<br>", builder.toString()); } /** * Tests {@link DescriptionGeneratorImpl#writeGrade(double, StringBuilder, * int, String)} with an infinite number. */ public void testWriteGrade_infinite() { StringBuilder builder = new StringBuilder(); descriptionGenerator.writeGrade( Double.POSITIVE_INFINITY, builder, R.string.description_max_grade, "<br>"); assertEquals("Max grade: 0 %<br>", builder.toString()); } /** * Tests {@link DescriptionGeneratorImpl#getPace(double)}. */ public void testGetPace() { assertEquals(12.0, descriptionGenerator.getPace(5)); } /** * Tests {@link DescriptionGeneratorImpl#getPace(double)} with zero speed. */ public void testGetPace_zero() { assertEquals(0.0, descriptionGenerator.getPace(0)); } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.content; import static com.google.android.testing.mocking.AndroidMock.anyInt; import static com.google.android.testing.mocking.AndroidMock.capture; import static com.google.android.testing.mocking.AndroidMock.eq; import static com.google.android.testing.mocking.AndroidMock.expect; import static com.google.android.testing.mocking.AndroidMock.isA; import static com.google.android.testing.mocking.AndroidMock.leq; import static com.google.android.testing.mocking.AndroidMock.same; import com.google.android.apps.mytracks.Constants; import com.google.android.apps.mytracks.content.MyTracksProviderUtils.LocationFactory; import com.google.android.apps.mytracks.content.MyTracksProviderUtils.LocationIterator; import com.google.android.apps.mytracks.content.TrackDataHub.ListenerDataType; import com.google.android.apps.mytracks.content.TrackDataListener.ProviderState; import com.google.android.apps.mytracks.services.TrackRecordingServiceTest.MockContext; import com.google.android.apps.mytracks.util.PreferencesUtils; import com.google.android.maps.mytracks.R; import com.google.android.testing.mocking.AndroidMock; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.database.ContentObserver; import android.database.Cursor; import android.database.MatrixCursor; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.location.Location; import android.location.LocationListener; import android.provider.BaseColumns; import android.test.AndroidTestCase; import android.test.RenamingDelegatingContext; import android.test.mock.MockContentResolver; import java.lang.reflect.Constructor; import java.util.EnumSet; import java.util.HashSet; import java.util.Set; import org.easymock.Capture; import org.easymock.IAnswer; /** * Tests for {@link TrackDataHub}. * * @author Rodrigo Damazio */ public class TrackDataHubTest extends AndroidTestCase { private static final long TRACK_ID = 42L; private static final int TARGET_POINTS = 50; private MyTracksProviderUtils providerUtils; private TrackDataHub hub; private TrackDataListeners listeners; private DataSourcesWrapper dataSources; private SharedPreferences prefs; private TrackDataListener listener1; private TrackDataListener listener2; private Capture<OnSharedPreferenceChangeListener> preferenceListenerCapture = new Capture<SharedPreferences.OnSharedPreferenceChangeListener>(); private MockContext context; private float declination; @Override protected void setUp() throws Exception { super.setUp(); MockContentResolver mockContentResolver = new MockContentResolver(); RenamingDelegatingContext targetContext = new RenamingDelegatingContext( getContext(), getContext(), "test."); context = new MockContext(mockContentResolver, targetContext); prefs = context.getSharedPreferences(Constants.SETTINGS_NAME, Context.MODE_PRIVATE); providerUtils = AndroidMock.createMock("providerUtils", MyTracksProviderUtils.class); dataSources = AndroidMock.createNiceMock("dataSources", DataSourcesWrapper.class); listeners = new TrackDataListeners(); hub = new TrackDataHub(context, listeners, prefs, providerUtils, TARGET_POINTS) { @Override protected DataSourcesWrapper newDataSources() { return dataSources; } @Override protected void runInListenerThread(Runnable runnable) { // Run everything in the same thread. runnable.run(); } @Override protected float getDeclinationFor(Location location, long timestamp) { return declination; } }; listener1 = AndroidMock.createStrictMock("listener1", TrackDataListener.class); listener2 = AndroidMock.createStrictMock("listener2", TrackDataListener.class); PreferencesUtils.setRecordingTrackId(context, TRACK_ID); PreferencesUtils.setSelectedTrackId(context, TRACK_ID); } @Override protected void tearDown() throws Exception { AndroidMock.reset(dataSources); // Expect everything to be unregistered. if (preferenceListenerCapture.hasCaptured()) { dataSources.unregisterOnSharedPreferenceChangeListener(preferenceListenerCapture.getValue()); } dataSources.removeLocationUpdates(isA(LocationListener.class)); dataSources.unregisterSensorListener(isA(SensorEventListener.class)); dataSources.unregisterContentObserver(isA(ContentObserver.class)); AndroidMock.expectLastCall().times(3); AndroidMock.replay(dataSources); hub.stop(); hub = null; super.tearDown(); } public void testTrackListen() { Capture<ContentObserver> observerCapture = new Capture<ContentObserver>(); Track track = new Track(); expect(providerUtils.getTrack(TRACK_ID)).andStubReturn(track); expectStart(); dataSources.registerContentObserver( eq(TracksColumns.CONTENT_URI), eq(false), capture(observerCapture)); // Expect the initial loading. // Both listeners (registered before and after start) should get the same data. listener1.onTrackUpdated(track); listener2.onTrackUpdated(track); replay(); hub.registerTrackDataListener(listener1, EnumSet.of(ListenerDataType.TRACK_UPDATES)); hub.start(); hub.registerTrackDataListener(listener2, EnumSet.of(ListenerDataType.TRACK_UPDATES)); verifyAndReset(); ContentObserver observer = observerCapture.getValue(); expect(providerUtils.getTrack(TRACK_ID)).andStubReturn(track); // Now expect an update. listener1.onTrackUpdated(track); listener2.onTrackUpdated(track); replay(); observer.onChange(false); verifyAndReset(); // Unregister one, get another update. expect(providerUtils.getTrack(TRACK_ID)).andStubReturn(track); listener2.onTrackUpdated(track); replay(); hub.unregisterTrackDataListener(listener1); observer.onChange(false); verifyAndReset(); // Unregister the other, expect internal unregistration dataSources.unregisterContentObserver(observer); replay(); hub.unregisterTrackDataListener(listener2); observer.onChange(false); verifyAndReset(); } private static class FixedSizeCursorAnswer implements IAnswer<Cursor> { private final int size; public FixedSizeCursorAnswer(int size) { this.size = size; } @Override public Cursor answer() throws Throwable { MatrixCursor cursor = new MatrixCursor(new String[] { BaseColumns._ID }); for (long i = 1; i <= size; i++) { cursor.addRow(new Object[] { i }); } return cursor; } } private static class FixedSizeLocationIterator implements LocationIterator { private final long startId; private final Location[] locs; private final Set<Integer> splitIndexSet = new HashSet<Integer>(); private int currentIdx = -1; public FixedSizeLocationIterator(long startId, int size) { this(startId, size, null); } public FixedSizeLocationIterator(long startId, int size, int... splitIndices) { this.startId = startId; this.locs = new Location[size]; for (int i = 0; i < size; i++) { Location loc = new Location("gps"); loc.setLatitude(-15.0 + i / 1000.0); loc.setLongitude(37 + i / 1000.0); loc.setAltitude(i); locs[i] = loc; } if (splitIndices != null) { for (int splitIdx : splitIndices) { splitIndexSet.add(splitIdx); Location splitLoc = locs[splitIdx]; splitLoc.setLatitude(100.0); splitLoc.setLongitude(200.0); } } } public void expectLocationsDelivered(TrackDataListener listener) { for (int i = 0; i < locs.length; i++) { if (splitIndexSet.contains(i)) { listener.onSegmentSplit(); } else { listener.onNewTrackPoint(locs[i]); } } } public void expectSampledLocationsDelivered( TrackDataListener listener, int sampleFrequency, boolean includeSampledOut) { for (int i = 0; i < locs.length; i++) { if (splitIndexSet.contains(i)) { listener.onSegmentSplit(); } else if (i % sampleFrequency == 0) { listener.onNewTrackPoint(locs[i]); } else if (includeSampledOut) { listener.onSampledOutTrackPoint(locs[i]); } } } @Override public boolean hasNext() { return currentIdx < (locs.length - 1); } @Override public Location next() { currentIdx++; return locs[currentIdx]; } @Override public void remove() { throw new UnsupportedOperationException(); } @Override public long getLocationId() { return startId + currentIdx; } @Override public void close() { // Do nothing } } public void testWaypointListen() { Capture<ContentObserver> observerCapture = new Capture<ContentObserver>(); Waypoint wpt1 = new Waypoint(), wpt2 = new Waypoint(), wpt3 = new Waypoint(), wpt4 = new Waypoint(); Location loc = new Location("gps"); loc.setLatitude(10.0); loc.setLongitude(8.0); wpt1.setLocation(loc); wpt2.setLocation(loc); wpt3.setLocation(loc); wpt4.setLocation(loc); expect(providerUtils.getWaypointsCursor( eq(TRACK_ID), leq(0L), eq(Constants.MAX_DISPLAYED_WAYPOINTS_POINTS))) .andStubAnswer(new FixedSizeCursorAnswer(2)); expect(providerUtils.createWaypoint(isA(Cursor.class))) .andReturn(wpt1) .andReturn(wpt2) .andReturn(wpt1) .andReturn(wpt2); expectStart(); dataSources.registerContentObserver( eq(WaypointsColumns.CONTENT_URI), eq(false), capture(observerCapture)); // Expect the initial loading. // Both listeners (registered before and after start) should get the same data. listener1.clearWaypoints(); listener1.onNewWaypoint(wpt1); listener1.onNewWaypoint(wpt2); listener1.onNewWaypointsDone(); listener2.clearWaypoints(); listener2.onNewWaypoint(wpt1); listener2.onNewWaypoint(wpt2); listener2.onNewWaypointsDone(); replay(); hub.registerTrackDataListener(listener1, EnumSet.of(ListenerDataType.WAYPOINT_UPDATES)); hub.start(); hub.registerTrackDataListener(listener2, EnumSet.of(ListenerDataType.WAYPOINT_UPDATES)); verifyAndReset(); ContentObserver observer = observerCapture.getValue(); expect(providerUtils.getWaypointsCursor( eq(TRACK_ID), leq(0L), eq(Constants.MAX_DISPLAYED_WAYPOINTS_POINTS))) .andStubAnswer(new FixedSizeCursorAnswer(3)); expect(providerUtils.createWaypoint(isA(Cursor.class))) .andReturn(wpt1) .andReturn(wpt2) .andReturn(wpt3); // Now expect an update. listener1.clearWaypoints(); listener2.clearWaypoints(); listener1.onNewWaypoint(wpt1); listener2.onNewWaypoint(wpt1); listener1.onNewWaypoint(wpt2); listener2.onNewWaypoint(wpt2); listener1.onNewWaypoint(wpt3); listener2.onNewWaypoint(wpt3); listener1.onNewWaypointsDone(); listener2.onNewWaypointsDone(); replay(); observer.onChange(false); verifyAndReset(); // Unregister one, get another update. expect(providerUtils.getWaypointsCursor( eq(TRACK_ID), leq(0L), eq(Constants.MAX_DISPLAYED_WAYPOINTS_POINTS))) .andStubAnswer(new FixedSizeCursorAnswer(4)); expect(providerUtils.createWaypoint(isA(Cursor.class))) .andReturn(wpt1) .andReturn(wpt2) .andReturn(wpt3) .andReturn(wpt4); // Now expect an update. listener2.clearWaypoints(); listener2.onNewWaypoint(wpt1); listener2.onNewWaypoint(wpt2); listener2.onNewWaypoint(wpt3); listener2.onNewWaypoint(wpt4); listener2.onNewWaypointsDone(); replay(); hub.unregisterTrackDataListener(listener1); observer.onChange(false); verifyAndReset(); // Unregister the other, expect internal unregistration dataSources.unregisterContentObserver(observer); replay(); hub.unregisterTrackDataListener(listener2); observer.onChange(false); verifyAndReset(); } public void testPointsListen() { Capture<ContentObserver> observerCapture = new Capture<ContentObserver>(); expectStart(); dataSources.registerContentObserver( eq(TrackPointsColumns.CONTENT_URI), eq(false), capture(observerCapture)); FixedSizeLocationIterator locationIterator = new FixedSizeLocationIterator(1, 10, 5); expect(providerUtils.getLocationIterator( eq(TRACK_ID), eq(0L), eq(false), isA(LocationFactory.class))) .andReturn(locationIterator); expect(providerUtils.getLastLocationId(TRACK_ID)).andReturn(10L); listener1.clearTrackPoints(); locationIterator.expectLocationsDelivered(listener1); listener1.onNewTrackPointsDone(); replay(); hub.start(); hub.registerTrackDataListener(listener1, EnumSet.of(ListenerDataType.POINT_UPDATES)); verifyAndReset(); // Register a second listener - it will get the same points as the previous one locationIterator = new FixedSizeLocationIterator(1, 10, 5); expect(providerUtils.getLocationIterator( eq(TRACK_ID), eq(0L), eq(false), isA(LocationFactory.class))) .andReturn(locationIterator); expect(providerUtils.getLastLocationId(TRACK_ID)).andReturn(10L); listener2.clearTrackPoints(); locationIterator.expectLocationsDelivered(listener2); listener2.onNewTrackPointsDone(); replay(); hub.start(); hub.registerTrackDataListener(listener2, EnumSet.of(ListenerDataType.POINT_UPDATES)); verifyAndReset(); // Deliver more points - should go to both listeners, without clearing. ContentObserver observer = observerCapture.getValue(); locationIterator = new FixedSizeLocationIterator(11, 10, 1); expect(providerUtils.getLocationIterator( eq(TRACK_ID), eq(11L), eq(false), isA(LocationFactory.class))) .andReturn(locationIterator); expect(providerUtils.getLastLocationId(TRACK_ID)).andReturn(20L); locationIterator.expectLocationsDelivered(listener1); locationIterator.expectLocationsDelivered(listener2); listener1.onNewTrackPointsDone(); listener2.onNewTrackPointsDone(); replay(); observer.onChange(false); verifyAndReset(); // Unregister listener1, switch tracks to ensure data is cleared/reloaded. locationIterator = new FixedSizeLocationIterator(101, 10); expect(providerUtils.getLocationIterator( eq(TRACK_ID + 1), eq(0L), eq(false), isA(LocationFactory.class))) .andReturn(locationIterator); expect(providerUtils.getLastLocationId(TRACK_ID + 1)).andReturn(110L); listener2.clearTrackPoints(); locationIterator.expectLocationsDelivered(listener2); listener2.onNewTrackPointsDone(); replay(); hub.unregisterTrackDataListener(listener1); hub.loadTrack(TRACK_ID + 1); verifyAndReset(); } public void testPointsListen_beforeStart() { } public void testPointsListen_reRegister() { Capture<ContentObserver> observerCapture = new Capture<ContentObserver>(); expectStart(); dataSources.registerContentObserver( eq(TrackPointsColumns.CONTENT_URI), eq(false), capture(observerCapture)); FixedSizeLocationIterator locationIterator = new FixedSizeLocationIterator(1, 10, 5); expect(providerUtils.getLocationIterator( eq(TRACK_ID), eq(0L), eq(false), isA(LocationFactory.class))) .andReturn(locationIterator); expect(providerUtils.getLastLocationId(TRACK_ID)).andReturn(10L); listener1.clearTrackPoints(); locationIterator.expectLocationsDelivered(listener1); listener1.onNewTrackPointsDone(); replay(); hub.start(); hub.registerTrackDataListener(listener1, EnumSet.of(ListenerDataType.POINT_UPDATES)); verifyAndReset(); // Unregister ContentObserver observer = observerCapture.getValue(); dataSources.unregisterContentObserver(observer); replay(); hub.unregisterTrackDataListener(listener1); verifyAndReset(); // Register again, except only points since unregistered. dataSources.registerContentObserver( eq(TrackPointsColumns.CONTENT_URI), eq(false), capture(observerCapture)); locationIterator = new FixedSizeLocationIterator(11, 10); expect(providerUtils.getLocationIterator( eq(TRACK_ID), eq(11L), eq(false), isA(LocationFactory.class))) .andReturn(locationIterator); expect(providerUtils.getLastLocationId(TRACK_ID)).andReturn(20L); locationIterator.expectLocationsDelivered(listener1); listener1.onNewTrackPointsDone(); replay(); hub.registerTrackDataListener(listener1, EnumSet.of(ListenerDataType.POINT_UPDATES)); verifyAndReset(); // Deliver more points - should still be incremental. locationIterator = new FixedSizeLocationIterator(21, 10, 1); expect(providerUtils.getLocationIterator( eq(TRACK_ID), eq(21L), eq(false), isA(LocationFactory.class))) .andReturn(locationIterator); expect(providerUtils.getLastLocationId(TRACK_ID)).andReturn(30L); locationIterator.expectLocationsDelivered(listener1); listener1.onNewTrackPointsDone(); replay(); observer.onChange(false); verifyAndReset(); } public void testPointsListen_reRegisterTrackChanged() { Capture<ContentObserver> observerCapture = new Capture<ContentObserver>(); expectStart(); dataSources.registerContentObserver( eq(TrackPointsColumns.CONTENT_URI), eq(false), capture(observerCapture)); FixedSizeLocationIterator locationIterator = new FixedSizeLocationIterator(1, 10, 5); expect(providerUtils.getLocationIterator( eq(TRACK_ID), eq(0L), eq(false), isA(LocationFactory.class))) .andReturn(locationIterator); expect(providerUtils.getLastLocationId(TRACK_ID)).andReturn(10L); listener1.clearTrackPoints(); locationIterator.expectLocationsDelivered(listener1); listener1.onNewTrackPointsDone(); replay(); hub.start(); hub.registerTrackDataListener(listener1, EnumSet.of(ListenerDataType.POINT_UPDATES)); verifyAndReset(); // Unregister ContentObserver observer = observerCapture.getValue(); dataSources.unregisterContentObserver(observer); replay(); hub.unregisterTrackDataListener(listener1); verifyAndReset(); // Register again after track changed, expect all points. dataSources.registerContentObserver( eq(TrackPointsColumns.CONTENT_URI), eq(false), capture(observerCapture)); locationIterator = new FixedSizeLocationIterator(1, 10); expect(providerUtils.getLocationIterator( eq(TRACK_ID + 1), eq(0L), eq(false), isA(LocationFactory.class))) .andReturn(locationIterator); expect(providerUtils.getLastLocationId(TRACK_ID + 1)).andReturn(10L); listener1.clearTrackPoints(); locationIterator.expectLocationsDelivered(listener1); listener1.onNewTrackPointsDone(); replay(); hub.loadTrack(TRACK_ID + 1); hub.registerTrackDataListener(listener1, EnumSet.of(ListenerDataType.POINT_UPDATES)); verifyAndReset(); } public void testPointsListen_largeTrackSampling() { Capture<ContentObserver> observerCapture = new Capture<ContentObserver>(); expectStart(); dataSources.registerContentObserver( eq(TrackPointsColumns.CONTENT_URI), eq(false), capture(observerCapture)); FixedSizeLocationIterator locationIterator = new FixedSizeLocationIterator(1, 200, 4, 25, 71, 120); expect(providerUtils.getLocationIterator( eq(TRACK_ID), eq(0L), eq(false), isA(LocationFactory.class))) .andReturn(locationIterator); expect(providerUtils.getLastLocationId(TRACK_ID)).andReturn(200L); listener1.clearTrackPoints(); listener2.clearTrackPoints(); locationIterator.expectSampledLocationsDelivered(listener1, 4, false); locationIterator.expectSampledLocationsDelivered(listener2, 4, true); listener1.onNewTrackPointsDone(); listener2.onNewTrackPointsDone(); replay(); hub.registerTrackDataListener(listener1, EnumSet.of(ListenerDataType.POINT_UPDATES)); hub.registerTrackDataListener(listener2, EnumSet.of(ListenerDataType.POINT_UPDATES, ListenerDataType.SAMPLED_OUT_POINT_UPDATES)); hub.start(); verifyAndReset(); } public void testPointsListen_resampling() { Capture<ContentObserver> observerCapture = new Capture<ContentObserver>(); expectStart(); dataSources.registerContentObserver( eq(TrackPointsColumns.CONTENT_URI), eq(false), capture(observerCapture)); // Deliver 30 points (no sampling happens) FixedSizeLocationIterator locationIterator = new FixedSizeLocationIterator(1, 30, 5); expect(providerUtils.getLocationIterator( eq(TRACK_ID), eq(0L), eq(false), isA(LocationFactory.class))) .andReturn(locationIterator); expect(providerUtils.getLastLocationId(TRACK_ID)).andReturn(30L); listener1.clearTrackPoints(); locationIterator.expectLocationsDelivered(listener1); listener1.onNewTrackPointsDone(); replay(); hub.start(); hub.registerTrackDataListener(listener1, EnumSet.of(ListenerDataType.POINT_UPDATES)); verifyAndReset(); // Now deliver 30 more (incrementally sampled) ContentObserver observer = observerCapture.getValue(); locationIterator = new FixedSizeLocationIterator(31, 30); expect(providerUtils.getLocationIterator( eq(TRACK_ID), eq(31L), eq(false), isA(LocationFactory.class))) .andReturn(locationIterator); expect(providerUtils.getLastLocationId(TRACK_ID)).andReturn(60L); locationIterator.expectSampledLocationsDelivered(listener1, 2, false); listener1.onNewTrackPointsDone(); replay(); observer.onChange(false); verifyAndReset(); // Now another 30 (triggers resampling) locationIterator = new FixedSizeLocationIterator(1, 90); expect(providerUtils.getLocationIterator( eq(TRACK_ID), eq(0L), eq(false), isA(LocationFactory.class))) .andReturn(locationIterator); expect(providerUtils.getLastLocationId(TRACK_ID)).andReturn(90L); listener1.clearTrackPoints(); locationIterator.expectSampledLocationsDelivered(listener1, 2, false); listener1.onNewTrackPointsDone(); replay(); observer.onChange(false); verifyAndReset(); } public void testLocationListen() { // TODO } public void testCompassListen() throws Exception { AndroidMock.resetToDefault(listener1); Sensor compass = newSensor(); expect(dataSources.getSensor(Sensor.TYPE_ORIENTATION)).andReturn(compass); Capture<SensorEventListener> listenerCapture = new Capture<SensorEventListener>(); dataSources.registerSensorListener(capture(listenerCapture), same(compass), anyInt()); Capture<LocationListener> locationListenerCapture = new Capture<LocationListener>(); dataSources.requestLocationUpdates(capture(locationListenerCapture)); SensorEvent event = newSensorEvent(); event.sensor = compass; // First, get a dummy heading update. listener1.onCurrentHeadingChanged(0.0); // Then, get a heading update without a known location (thus can't calculate declination). listener1.onCurrentHeadingChanged(42.0f); // Also expect location updates which are not relevant to us. listener1.onProviderStateChange(isA(ProviderState.class)); AndroidMock.expectLastCall().anyTimes(); replay(); hub.registerTrackDataListener(listener1, EnumSet.of(ListenerDataType.COMPASS_UPDATES, ListenerDataType.LOCATION_UPDATES)); hub.start(); SensorEventListener sensorListener = listenerCapture.getValue(); LocationListener locationListener = locationListenerCapture.getValue(); event.values[0] = 42.0f; sensorListener.onSensorChanged(event); verifyAndReset(); // Expect the heading update to include declination. listener1.onCurrentHeadingChanged(52.0); // Also expect location updates which are not relevant to us. listener1.onProviderStateChange(isA(ProviderState.class)); AndroidMock.expectLastCall().anyTimes(); listener1.onCurrentLocationChanged(isA(Location.class)); AndroidMock.expectLastCall().anyTimes(); replay(); // Now try injecting a location update, triggering a declination update. Location location = new Location("gps"); location.setLatitude(10.0); location.setLongitude(20.0); location.setAltitude(30.0); declination = 10.0f; locationListener.onLocationChanged(location); sensorListener.onSensorChanged(event); verifyAndReset(); listener1.onCurrentHeadingChanged(52.0); replay(); // Now try changing the known declination - it should still return the old declination, since // updates only happen sparsely. declination = 20.0f; sensorListener.onSensorChanged(event); verifyAndReset(); } private Sensor newSensor() throws Exception { Constructor<Sensor> constructor = Sensor.class.getDeclaredConstructor(); constructor.setAccessible(true); return constructor.newInstance(); } private SensorEvent newSensorEvent() throws Exception { Constructor<SensorEvent> constructor = SensorEvent.class.getDeclaredConstructor(int.class); constructor.setAccessible(true); return constructor.newInstance(3); } public void testDisplayPreferencesListen() throws Exception { String metricUnitsKey = context.getString(R.string.metric_units_key); String speedKey = context.getString(R.string.report_speed_key); prefs.edit() .putBoolean(metricUnitsKey, true) .putBoolean(speedKey, true) .apply(); Capture<OnSharedPreferenceChangeListener> listenerCapture = new Capture<OnSharedPreferenceChangeListener>(); dataSources.registerOnSharedPreferenceChangeListener(capture(listenerCapture)); expect(listener1.onUnitsChanged(true)).andReturn(false); expect(listener2.onUnitsChanged(true)).andReturn(false); expect(listener1.onReportSpeedChanged(true)).andReturn(false); expect(listener2.onReportSpeedChanged(true)).andReturn(false); replay(); hub.registerTrackDataListener(listener1, EnumSet.of(ListenerDataType.DISPLAY_PREFERENCES)); hub.start(); hub.registerTrackDataListener(listener2, EnumSet.of(ListenerDataType.DISPLAY_PREFERENCES)); verifyAndReset(); expect(listener1.onReportSpeedChanged(false)).andReturn(false); expect(listener2.onReportSpeedChanged(false)).andReturn(false); replay(); prefs.edit() .putBoolean(speedKey, false) .apply(); OnSharedPreferenceChangeListener listener = listenerCapture.getValue(); listener.onSharedPreferenceChanged(prefs, speedKey); AndroidMock.verify(dataSources, providerUtils, listener1, listener2); AndroidMock.reset(dataSources, providerUtils, listener1, listener2); expect(listener1.onUnitsChanged(false)).andReturn(false); expect(listener2.onUnitsChanged(false)).andReturn(false); replay(); prefs.edit() .putBoolean(metricUnitsKey, false) .apply(); listener.onSharedPreferenceChanged(prefs, metricUnitsKey); verifyAndReset(); } private void expectStart() { dataSources.registerOnSharedPreferenceChangeListener(capture(preferenceListenerCapture)); } private void replay() { AndroidMock.replay(dataSources, providerUtils, listener1, listener2); } private void verifyAndReset() { AndroidMock.verify(listener1, listener2, dataSources, providerUtils); AndroidMock.reset(listener1, listener2, dataSources, providerUtils); } }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.content; import com.google.android.apps.mytracks.content.MyTracksProviderUtils.LocationFactory; import com.google.android.apps.mytracks.content.MyTracksProviderUtils.LocationIterator; import com.google.android.apps.mytracks.services.TrackRecordingServiceTest.MockContext; import android.content.Context; import android.location.Location; import android.test.AndroidTestCase; import android.test.RenamingDelegatingContext; import android.test.mock.MockContentResolver; import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; /** * A unit test for {@link MyTracksProviderUtilsImpl}. * * @author Bartlomiej Niechwiej */ public class MyTracksProviderUtilsImplTest extends AndroidTestCase { private Context context; private MyTracksProviderUtils providerUtils; @Override protected void setUp() throws Exception { super.setUp(); MockContentResolver mockContentResolver = new MockContentResolver(); RenamingDelegatingContext targetContext = new RenamingDelegatingContext( getContext(), getContext(), "test."); context = new MockContext(mockContentResolver, targetContext); MyTracksProvider provider = new MyTracksProvider(); provider.attachInfo(context, null); mockContentResolver.addProvider(MyTracksProviderUtils.AUTHORITY, provider); setContext(context); providerUtils = MyTracksProviderUtils.Factory.get(context); } public void testLocationIterator_noPoints() { testIterator(1, 0, 1, false, MyTracksProviderUtils.DEFAULT_LOCATION_FACTORY); } public void testLocationIterator_customFactory() { final Location location = new Location("test_location"); final AtomicInteger counter = new AtomicInteger(); testIterator(1, 15, 4, false, new LocationFactory() { @Override public Location createLocation() { counter.incrementAndGet(); return location; } }); // Make sure we were called exactly as many times as we had track points. assertEquals(15, counter.get()); } public void testLocationIterator_nullFactory() { try { testIterator(1, 15, 4, false, null); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException e) { // Expected. } } public void testLocationIterator_noBatchAscending() { testIterator(1, 50, 100, false, MyTracksProviderUtils.DEFAULT_LOCATION_FACTORY); testIterator(2, 50, 50, false, MyTracksProviderUtils.DEFAULT_LOCATION_FACTORY); } public void testLocationIterator_noBatchDescending() { testIterator(1, 50, 100, true, MyTracksProviderUtils.DEFAULT_LOCATION_FACTORY); testIterator(2, 50, 50, true, MyTracksProviderUtils.DEFAULT_LOCATION_FACTORY); } public void testLocationIterator_batchAscending() { testIterator(1, 50, 11, false, MyTracksProviderUtils.DEFAULT_LOCATION_FACTORY); testIterator(2, 50, 25, false, MyTracksProviderUtils.DEFAULT_LOCATION_FACTORY); } public void testLocationIterator_batchDescending() { testIterator(1, 50, 11, true, MyTracksProviderUtils.DEFAULT_LOCATION_FACTORY); testIterator(2, 50, 25, true, MyTracksProviderUtils.DEFAULT_LOCATION_FACTORY); } public void testLocationIterator_largeTrack() { testIterator(1, 20000, 2000, false, MyTracksProviderUtils.DEFAULT_LOCATION_FACTORY); } private List<Location> testIterator(long trackId, int numPoints, int batchSize, boolean descending, LocationFactory locationFactory) { long lastPointId = initializeTrack(trackId, numPoints); ((MyTracksProviderUtilsImpl) providerUtils).setDefaultCursorBatchSize(batchSize); List<Location> locations = new ArrayList<Location>(numPoints); LocationIterator it = providerUtils.getLocationIterator(trackId, -1, descending, locationFactory); try { while (it.hasNext()) { Location loc = it.next(); assertNotNull(loc); locations.add(loc); // Make sure the IDs are returned in the right order. assertEquals(descending ? lastPointId - locations.size() + 1 : lastPointId - numPoints + locations.size(), it.getLocationId()); } assertEquals(numPoints, locations.size()); } finally { it.close(); } return locations; } private long initializeTrack(long id, int numPoints) { Track track = new Track(); track.setId(id); track.setName("Test: " + id); track.setNumberOfPoints(numPoints); providerUtils.insertTrack(track); track = providerUtils.getTrack(id); assertNotNull(track); Location[] locations = new Location[numPoints]; for (int i = 0; i < numPoints; ++i) { Location loc = new Location("test"); loc.setLatitude(37.0 + (double) i / 10000.0); loc.setLongitude(57.0 - (double) i / 10000.0); loc.setAccuracy((float) i / 100.0f); loc.setAltitude(i * 2.5); locations[i] = loc; } providerUtils.bulkInsertTrackPoints(locations, numPoints, id); // Load all inserted locations. long lastPointId = -1; int counter = 0; LocationIterator it = providerUtils.getLocationIterator(id, -1, false, MyTracksProviderUtils.DEFAULT_LOCATION_FACTORY); try { while (it.hasNext()) { it.next(); lastPointId = it.getLocationId(); counter++; } } finally { it.close(); } assertTrue(numPoints == 0 || lastPointId > 0); assertEquals(numPoints, track.getNumberOfPoints()); assertEquals(numPoints, counter); return lastPointId; } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks; import android.graphics.Path; import android.graphics.PointF; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import junit.framework.Assert; /** * Elements for Tests for the MyTracks map overlay. * * @author Bartlomiej Niechwiej * @author Vangelis S. * * A mock class that intercepts {@code Path}'s and records calls to * {@code #moveTo()} and {@code #lineTo()}. */ public class MockPath extends Path { /** A list of disjoined path segments. */ public final List<List<PointF>> segments = new LinkedList<List<PointF>>(); /** The total number of points in this path. */ public int totalPoints; private List<PointF> currentSegment; @Override public void lineTo(float x, float y) { super.lineTo(x, y); Assert.assertNotNull(currentSegment); currentSegment.add(new PointF(x, y)); totalPoints++; } @Override public void moveTo(float x, float y) { super.moveTo(x, y); segments.add(currentSegment = new ArrayList<PointF>(Arrays.asList(new PointF(x, y)))); totalPoints++; } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks; import com.google.android.maps.mytracks.R; import android.test.AndroidTestCase; /** * Tests for the AntPreference. * * @author Youtao Liu */ public class AntPreferenceTest extends AndroidTestCase { public void testNotPaired() { AntPreference antPreference = new AntPreference(getContext()) { @Override protected int getPersistedInt(int defaultReturnValue) { return 0; } }; assertEquals(getContext().getString(R.string.settings_sensor_ant_not_paired), antPreference.getSummary()); } public void testPaired() { int persistInt = 1; AntPreference antPreference = new AntPreference(getContext()) { @Override protected int getPersistedInt(int defaultReturnValue) { return 1; } }; assertEquals( getContext().getString(R.string.settings_sensor_ant_paired, persistInt), antPreference.getSummary()); } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks; import com.google.android.maps.GeoPoint; import com.google.android.maps.Projection; import android.graphics.Point; /** * Elements for Tests for the MyTracks map overlay. * * @author Bartlomiej Niechwiej * @author Vangelis S. * * A mock {@code Projection} that acts as the identity matrix. */ public class MockProjection implements Projection { @Override public Point toPixels(GeoPoint in, Point out) { return out; } @Override public float metersToEquatorPixels(float meters) { return meters; } @Override public GeoPoint fromPixels(int x, int y) { return new GeoPoint(y, x); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks; import com.google.android.apps.mytracks.content.MyTracksLocation; import com.google.android.apps.mytracks.content.Sensor.SensorDataSet; import com.google.android.apps.mytracks.content.Track; import android.location.Location; /** * Commons utilities for creating stubs of track, location. The class will be * enriched if needs more similar stubs for test. * * @author Youtao Liu */ public class TrackStubUtils { static final String LOCATION_PROVIDER = "gps"; public static final double INITIAL_LATITUDE = 22; public static final double INITIAL_LONGITUDE = 22; public static final double INITIAL_ALTITUDE = 22; static final float INITIAL_ACCURACY = 5; static final float INITIAL_SPEED = 10; static final float INITIAL_BEARING = 3.0f; // Used to change the value of latitude, longitude, and altitude. static final double DIFFERENCE = 0.01; /** * Gets a a {@link Track} stub with specified number of locations. * * @param numberOfLocations the number of locations for the track * @return a track stub. */ public static Track createTrack(int numberOfLocations) { Track track = new Track(); for (int i = 0; i < numberOfLocations; i++) { track.addLocation(createMyTracksLocation(INITIAL_LATITUDE + i * DIFFERENCE, INITIAL_LONGITUDE + i * DIFFERENCE, INITIAL_ALTITUDE + i * DIFFERENCE)); } return track; } /** * Create a MyTracks location with default values. * * @return a track stub. */ public static MyTracksLocation createMyTracksLocation() { return createMyTracksLocation(INITIAL_LATITUDE, INITIAL_LONGITUDE, INITIAL_ALTITUDE); } /** * Creates a {@link MyTracksLocation} stub with specified values. * * @return a MyTracksLocation stub. */ public static MyTracksLocation createMyTracksLocation(double latitude, double longitude, double altitude) { // Initial Location Location loc = new Location(LOCATION_PROVIDER); loc.setLatitude(latitude); loc.setLongitude(longitude); loc.setAltitude(altitude); loc.setAccuracy(INITIAL_ACCURACY); loc.setSpeed(INITIAL_SPEED); loc.setTime(System.currentTimeMillis()); loc.setBearing(INITIAL_BEARING); SensorDataSet sd = SensorDataSet.newBuilder().build(); MyTracksLocation myTracksLocation = new MyTracksLocation(loc, sd); return myTracksLocation; } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks; import com.google.android.apps.mytracks.services.TrackRecordingService; import android.app.ActivityManager; import android.app.ActivityManager.RunningServiceInfo; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.test.AndroidTestCase; import java.util.List; /** * Tests for the BootReceiver. * * @author Youtao Liu */ public class BootReceiverTest extends AndroidTestCase { private static final String SERVICE_NAME = "com.google.android.apps.mytracks.services.TrackRecordingService"; /** * Tests the behavior when receive notification which is the phone boot. */ public void testOnReceive_startService() { // Make sure no TrackRecordingService Intent stopIntent = new Intent(getContext(), TrackRecordingService.class); getContext().stopService(stopIntent); assertFalse(isServiceExisted(getContext(), SERVICE_NAME)); BootReceiver bootReceiver = new BootReceiver(); Intent intent = new Intent(); intent.setAction(Intent.ACTION_BOOT_COMPLETED); bootReceiver.onReceive(getContext(), intent); // Check if the service is started assertTrue(isServiceExisted(getContext(), SERVICE_NAME)); } /** * Tests the behavior when receive notification which is not the phone boot. */ public void testOnReceive_noStartService() { // Make sure no TrackRecordingService Intent stopIntent = new Intent(getContext(), TrackRecordingService.class); getContext().stopService(stopIntent); assertFalse(isServiceExisted(getContext(), SERVICE_NAME)); BootReceiver bootReceiver = new BootReceiver(); Intent intent = new Intent(); intent.setAction(Intent.ACTION_BUG_REPORT); bootReceiver.onReceive(getContext(), intent); // Check if the service is not started assertFalse(isServiceExisted(getContext(), SERVICE_NAME)); } /** * Checks if a service is started in a context. * * @param context the context for checking a service * @param serviceName the service name to find if existed */ private boolean isServiceExisted(Context context, String serviceName) { ActivityManager activityManager = (ActivityManager) context .getSystemService(Context.ACTIVITY_SERVICE); List<ActivityManager.RunningServiceInfo> serviceList = activityManager .getRunningServices(Integer.MAX_VALUE); for (int i = 0; i < serviceList.size(); i++) { RunningServiceInfo serviceInfo = serviceList.get(i); ComponentName componentName = serviceInfo.service; if (componentName.getClassName().equals(serviceName)) { return true; } } return false; } }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks; import com.google.android.apps.mytracks.content.Waypoint; import com.google.android.apps.mytracks.maps.SingleColorTrackPathPainter; import com.google.android.maps.MapView; import android.graphics.Canvas; import android.graphics.Path; import android.location.Location; import android.test.AndroidTestCase; /** * Tests for the MyTracks map overlay. * * @author Bartlomiej Niechwiej * @author Vangelis S. */ public class MapOverlayTest extends AndroidTestCase { private Canvas canvas; private MockMyTracksOverlay myTracksOverlay; private MapView mockView; @Override protected void setUp() throws Exception { super.setUp(); canvas = new Canvas(); myTracksOverlay = new MockMyTracksOverlay(getContext()); // Enable drawing. myTracksOverlay.setTrackDrawingEnabled(true); // Set a TrackPathPainter with a MockPath. myTracksOverlay.setTrackPathPainter(new SingleColorTrackPathPainter(getContext()) { @Override public Path newPath() { return new MockPath(); } }); mockView = null; } public void testAddLocation() throws Exception { Location location = new Location("gps"); location.setLatitude(10); location.setLongitude(20); myTracksOverlay.addLocation(location); assertEquals(1, myTracksOverlay.getNumLocations()); assertEquals(0, myTracksOverlay.getNumWaypoints()); location.setLatitude(20); location.setLongitude(30); myTracksOverlay.addLocation(location); assertEquals(2, myTracksOverlay.getNumLocations()); assertEquals(0, myTracksOverlay.getNumWaypoints()); assertNull(myTracksOverlay.getTrackPathPainter().getLastPath()); // Draw and make sure that we don't lose any point. myTracksOverlay.draw(canvas, mockView, false); assertEquals(2, myTracksOverlay.getNumLocations()); assertEquals(0, myTracksOverlay.getNumWaypoints()); assertNotNull(myTracksOverlay.getTrackPathPainter().getLastPath()); assertTrue(myTracksOverlay.getTrackPathPainter().getLastPath() instanceof MockPath); MockPath path = (MockPath) myTracksOverlay.getTrackPathPainter().getLastPath(); assertEquals(2, path.totalPoints); myTracksOverlay.draw(canvas, mockView, true); assertEquals(2, myTracksOverlay.getNumLocations()); assertEquals(0, myTracksOverlay.getNumWaypoints()); assertNotNull(myTracksOverlay.getTrackPathPainter().getLastPath()); } public void testClearPoints() throws Exception { Location location = new Location("gps"); location.setLatitude(10); location.setLongitude(20); myTracksOverlay.addLocation(location); assertEquals(1, myTracksOverlay.getNumLocations()); myTracksOverlay.clearPoints(); assertEquals(0, myTracksOverlay.getNumLocations()); // Same after drawing on canvas. final int locations = 100; for (int i = 0; i < locations; ++i) { myTracksOverlay.addLocation(location); } assertEquals(locations, myTracksOverlay.getNumLocations()); myTracksOverlay.draw(canvas, mockView, false); myTracksOverlay.draw(canvas, mockView, true); myTracksOverlay.clearPoints(); assertEquals(0, myTracksOverlay.getNumLocations()); } public void testAddWaypoint() throws Exception { Location location = new Location("gps"); location.setLatitude(10); location.setLongitude(20); Waypoint waypoint = new Waypoint(); waypoint.setLocation(location); myTracksOverlay.addWaypoint(waypoint); assertEquals(1, myTracksOverlay.getNumWaypoints()); assertEquals(0, myTracksOverlay.getNumLocations()); assertNull(myTracksOverlay.getTrackPathPainter().getLastPath()); final int waypoints = 10; for (int i = 0; i < waypoints; ++i) { waypoint = new Waypoint(); waypoint.setLocation(location); myTracksOverlay.addWaypoint(waypoint); } assertEquals(1 + waypoints, myTracksOverlay.getNumWaypoints()); assertEquals(0, myTracksOverlay.getNumLocations()); assertNull(myTracksOverlay.getTrackPathPainter().getLastPath()); } public void testClearWaypoints() throws Exception { Location location = new Location("gps"); location.setLatitude(10); location.setLongitude(20); Waypoint waypoint = new Waypoint(); waypoint.setLocation(location); myTracksOverlay.addWaypoint(waypoint); assertEquals(1, myTracksOverlay.getNumWaypoints()); myTracksOverlay.clearWaypoints(); assertEquals(0, myTracksOverlay.getNumWaypoints()); } public void testDrawing() { Location location = new Location("gps"); location.setLatitude(10); for (int i = 0; i < 40; ++i) { location.setLongitude(20 + i); Waypoint waypoint = new Waypoint(); waypoint.setLocation(location); myTracksOverlay.addWaypoint(waypoint); } for (int i = 0; i < 100; ++i) { location = new Location("gps"); location.setLatitude(20 + i / 2); location.setLongitude(150 - i); myTracksOverlay.addLocation(location); } // Shadow. myTracksOverlay.draw(canvas, mockView, true); // We don't expect to do anything if assertNull(myTracksOverlay.getTrackPathPainter().getLastPath()); assertEquals(40, myTracksOverlay.getNumWaypoints()); assertEquals(100, myTracksOverlay.getNumLocations()); // No shadow. myTracksOverlay.draw(canvas, mockView, false); assertNotNull(myTracksOverlay.getTrackPathPainter().getLastPath()); assertTrue(myTracksOverlay.getTrackPathPainter().getLastPath() instanceof MockPath); MockPath path = (MockPath) myTracksOverlay.getTrackPathPainter().getLastPath(); assertEquals(40, myTracksOverlay.getNumWaypoints()); assertEquals(100, myTracksOverlay.getNumLocations()); assertEquals(100, path.totalPoints); // TODO: Check the points from the path (and the segments). } }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.io.file; import java.util.List; import org.w3c.dom.Document; import org.w3c.dom.Element; /** * Tests for {@link GpxTrackWriter}. * * @author Rodrigo Damazio */ public class GpxTrackWriterTest extends TrackFormatWriterTest { public void testXmlOutput() throws Exception { TrackFormatWriter writer = new GpxTrackWriter(getContext()); String result = writeTrack(writer); Document doc = parseXmlDocument(result); Element gpxTag = getChildElement(doc, "gpx"); Element trackTag = getChildElement(gpxTag, "trk"); assertEquals(TRACK_NAME, getChildTextValue(trackTag, "name")); assertEquals(TRACK_DESCRIPTION, getChildTextValue(trackTag, "desc")); List<Element> segmentTags = getChildElements(trackTag, "trkseg", 2); List<Element> segPointTags = getChildElements(segmentTags.get(0), "trkpt", 2); assertTagMatchesLocation(segPointTags.get(0), "0", "0", "1970-01-01T00:00:00.000Z", "0"); assertTagMatchesLocation(segPointTags.get(1), "1", "-1", "1970-01-01T00:01:40.000Z", "10"); segPointTags = getChildElements(segmentTags.get(1), "trkpt", 2); assertTagMatchesLocation(segPointTags.get(0), "2", "-2", "1970-01-01T00:03:20.000Z", "20"); assertTagMatchesLocation(segPointTags.get(1), "3", "-3", "1970-01-01T00:05:00.000Z", "30"); List<Element> waypointTags = getChildElements(gpxTag, "wpt", 2); Element wptTag = waypointTags.get(0); assertEquals(WAYPOINT1_NAME, getChildTextValue(wptTag, "name")); assertEquals(WAYPOINT1_DESCRIPTION, getChildTextValue(wptTag, "desc")); assertTagMatchesLocation(wptTag, "1", "-1", "1970-01-01T00:01:40.000Z", "10"); wptTag = waypointTags.get(1); assertEquals(WAYPOINT2_NAME, getChildTextValue(wptTag, "name")); assertEquals(WAYPOINT2_DESCRIPTION, getChildTextValue(wptTag, "desc")); assertTagMatchesLocation(wptTag, "2", "-2", "1970-01-01T00:03:20.000Z", "20"); } /** * Asserts that the given tag describes a location. * * @param tag the tag * @param latitude the location's latitude * @param longitude the location's longitude * @param time the location's time * @param elevation the location's elevation */ private void assertTagMatchesLocation( Element tag, String latitude, String longitude, String time, String elevation) { assertEquals(latitude, tag.getAttribute("lat")); assertEquals(longitude, tag.getAttribute("lon")); assertEquals(time, getChildTextValue(tag, "time")); assertEquals(elevation, getChildTextValue(tag, "ele")); } }
Java
// Copyright 2010 Google Inc. All Rights Reserved. package com.google.android.apps.mytracks.io.file; import static org.easymock.EasyMock.expect; import com.google.android.apps.mytracks.content.MyTracksProvider; import com.google.android.apps.mytracks.content.MyTracksProviderUtils; import com.google.android.apps.mytracks.content.MyTracksProviderUtils.Factory; import com.google.android.apps.mytracks.content.Track; import com.google.android.apps.mytracks.content.Waypoint; import com.google.android.apps.mytracks.services.TrackRecordingServiceTest.MockContext; import com.google.android.apps.mytracks.testing.TestingProviderUtilsFactory; import android.content.Context; import android.location.Location; import android.test.AndroidTestCase; import android.test.RenamingDelegatingContext; import android.test.mock.MockContentResolver; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.OutputStream; import org.easymock.EasyMock; import org.easymock.IArgumentMatcher; import org.easymock.IMocksControl; /** * Tests for the track writer. * * @author Rodrigo Damazio */ public class TrackWriterTest extends AndroidTestCase { /** * {@link TrackWriterImpl} subclass which mocks out methods called from * {@link TrackWriterImpl#openFile}. */ private static final class OpenFileTrackWriter extends TrackWriterImpl { private final ByteArrayOutputStream stream; private final boolean canWrite; /** * Constructor. * * @param stream the stream to return from * {@link TrackWriterImpl#newOutputStream}, or null to throw a * {@link FileNotFoundException} * @param canWrite the value that {@link TrackWriterImpl#canWriteFile} will * return */ private OpenFileTrackWriter(Context context, MyTracksProviderUtils providerUtils, Track track, TrackFormatWriter writer, ByteArrayOutputStream stream, boolean canWrite) { super(context, providerUtils, track, writer); this.stream = stream; this.canWrite = canWrite; // The directory is set in the canWriteFile. However, this class // overwrites canWriteFile, thus needs to set it. setDirectory(new File("/")); } @Override protected boolean canWriteFile() { return canWrite; } @Override protected OutputStream newOutputStream(String fileName) throws FileNotFoundException { assertEquals(FULL_TRACK_NAME, fileName); if (stream == null) { throw new FileNotFoundException(); } return stream; } } /** * {@link TrackWriterImpl} subclass which mocks out methods called from * {@link TrackWriterImpl#writeTrack}. */ private final class WriteTracksTrackWriter extends TrackWriterImpl { private final boolean openResult; /** * Constructor. * * @param openResult the return value for {@link TrackWriterImpl#openFile} */ private WriteTracksTrackWriter(Context context, MyTracksProviderUtils providerUtils, Track track, TrackFormatWriter writer, boolean openResult) { super(context, providerUtils, track, writer); this.openResult = openResult; } @Override protected boolean openFile() { openFileCalls++; return openResult; } @Override void writeDocument() { writeDocumentCalls++; } @Override protected void runOnUiThread(Runnable runnable) { runnable.run(); } } private static final long TRACK_ID = 1234567L; private static final String EXTENSION = "ext"; private static final String TRACK_NAME = "Swimming across the pacific"; private static final String FULL_TRACK_NAME = "Swimming across the pacific.ext"; private Track track; private TrackFormatWriter formatWriter; private TrackWriterImpl writer; private IMocksControl mocksControl; private MyTracksProviderUtils providerUtils; private Factory oldProviderUtilsFactory; // State used in specific tests private int writeDocumentCalls; private int openFileCalls; @Override protected void setUp() throws Exception { super.setUp(); MockContentResolver mockContentResolver = new MockContentResolver(); RenamingDelegatingContext targetContext = new RenamingDelegatingContext( getContext(), getContext(), "test."); Context context = new MockContext(mockContentResolver, targetContext); MyTracksProvider provider = new MyTracksProvider(); provider.attachInfo(context, null); mockContentResolver.addProvider(MyTracksProviderUtils.AUTHORITY, provider); setContext(context); providerUtils = MyTracksProviderUtils.Factory.get(context); oldProviderUtilsFactory = TestingProviderUtilsFactory.installWithInstance(providerUtils); mocksControl = EasyMock.createStrictControl(); formatWriter = mocksControl.createMock(TrackFormatWriter.class); expect(formatWriter.getExtension()).andStubReturn(EXTENSION); track = new Track(); track.setName(TRACK_NAME); track.setId(TRACK_ID); } @Override protected void tearDown() throws Exception { TestingProviderUtilsFactory.restoreOldFactory(oldProviderUtilsFactory); super.tearDown(); } public void testWriteTrack() { writer = new WriteTracksTrackWriter(getContext(), providerUtils, track, formatWriter, true); mocksControl.replay(); writer.writeTrack(); assertEquals(1, writeDocumentCalls); assertEquals(1, openFileCalls); mocksControl.verify(); } public void testWriteTrack_openFails() { writer = new WriteTracksTrackWriter(getContext(), providerUtils, track, formatWriter, false); mocksControl.replay(); writer.writeTrack(); assertEquals(0, writeDocumentCalls); assertEquals(1, openFileCalls); mocksControl.verify(); } public void testOpenFile() { final ByteArrayOutputStream stream = new ByteArrayOutputStream(); writer = new OpenFileTrackWriter( getContext(), providerUtils, track, formatWriter, stream, true); formatWriter.prepare(track, stream); mocksControl.replay(); assertTrue(writer.openFile()); mocksControl.verify(); } public void testOpenFile_cantWrite() { final ByteArrayOutputStream stream = new ByteArrayOutputStream(); writer = new OpenFileTrackWriter( getContext(), providerUtils, track, formatWriter, stream, false); mocksControl.replay(); assertFalse(writer.openFile()); mocksControl.verify(); } public void testOpenFile_streamError() { writer = new OpenFileTrackWriter( getContext(), providerUtils, track, formatWriter, null, true); mocksControl.replay(); assertFalse(writer.openFile()); mocksControl.verify(); } public void testWriteDocument_emptyTrack() throws Exception { writer = new TrackWriterImpl(getContext(), providerUtils, track, formatWriter); // Set expected mock behavior formatWriter.writeHeader(); formatWriter.writeFooter(); formatWriter.close(); mocksControl.replay(); writer.writeDocument(); assertTrue(writer.wasSuccess()); mocksControl.verify(); } public void testWriteDocument() throws Exception { writer = new TrackWriterImpl(getContext(), providerUtils, track, formatWriter); final Location[] locs = { new Location("fake0"), new Location("fake1"), new Location("fake2"), new Location("fake3"), new Location("fake4"), new Location("fake5") }; Waypoint[] wps = { new Waypoint(), new Waypoint(), new Waypoint() }; // Fill locations with valid values fillLocations(locs); // Make location 3 invalid locs[2].setLatitude(100); assertEquals(locs.length, providerUtils.bulkInsertTrackPoints(locs, locs.length, TRACK_ID)); for (int i = 0; i < wps.length; ++i) { Waypoint wpt = wps[i]; wpt.setTrackId(TRACK_ID); assertNotNull(providerUtils.insertWaypoint(wpt)); wpt.setId(i + 1); } formatWriter.writeHeader(); // Expect reading/writing of the waypoints (except the first) formatWriter.writeBeginWaypoints(); formatWriter.writeWaypoint(wptEq(wps[1])); formatWriter.writeWaypoint(wptEq(wps[2])); formatWriter.writeEndWaypoints(); // Begin the track formatWriter.writeBeginTrack(locEq(locs[0])); // Write locations 1-2 formatWriter.writeOpenSegment(); formatWriter.writeLocation(locEq(locs[0])); formatWriter.writeLocation(locEq(locs[1])); formatWriter.writeCloseSegment(); // Location 3 is not written - it's invalid // Write locations 4-6 formatWriter.writeOpenSegment(); formatWriter.writeLocation(locEq(locs[3])); formatWriter.writeLocation(locEq(locs[4])); formatWriter.writeLocation(locEq(locs[5])); formatWriter.writeCloseSegment(); // End the track formatWriter.writeEndTrack(locEq(locs[5])); formatWriter.writeFooter(); formatWriter.close(); mocksControl.replay(); writer.writeDocument(); assertTrue(writer.wasSuccess()); mocksControl.verify(); } private static Waypoint wptEq(final Waypoint wpt) { EasyMock.reportMatcher(new IArgumentMatcher() { @Override public boolean matches(Object wptObj2) { if (wptObj2 == null || wpt == null) return wpt == wptObj2; Waypoint wpt2 = (Waypoint) wptObj2; return wpt.getId() == wpt2.getId(); } @Override public void appendTo(StringBuffer buffer) { buffer.append("wptEq("); buffer.append(wpt); buffer.append(")"); } }); return null; } private static Location locEq(final Location loc) { EasyMock.reportMatcher(new IArgumentMatcher() { @Override public boolean matches(Object locObj2) { if (locObj2 == null || loc == null) return loc == locObj2; Location loc2 = (Location) locObj2; return loc.hasAccuracy() == loc2.hasAccuracy() && (!loc.hasAccuracy() || loc.getAccuracy() == loc2.getAccuracy()) && loc.hasAltitude() == loc2.hasAltitude() && (!loc.hasAltitude() || loc.getAltitude() == loc2.getAltitude()) && loc.hasBearing() == loc2.hasBearing() && (!loc.hasBearing() || loc.getBearing() == loc2.getBearing()) && loc.hasSpeed() == loc2.hasSpeed() && (!loc.hasSpeed() || loc.getSpeed() == loc2.getSpeed()) && loc.getLatitude() == loc2.getLatitude() && loc.getLongitude() == loc2.getLongitude() && loc.getTime() == loc2.getTime(); } @Override public void appendTo(StringBuffer buffer) { buffer.append("locEq("); buffer.append(loc); buffer.append(")"); } }); return null; } private void fillLocations(Location... locs) { assertTrue(locs.length < 90); for (int i = 0; i < locs.length; i++) { Location location = locs[i]; location.setLatitude(i + 1); location.setLongitude(i + 1); location.setTime(i + 1000); } } }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.io.file; import static com.google.android.testing.mocking.AndroidMock.eq; import static com.google.android.testing.mocking.AndroidMock.expect; import com.google.android.apps.mytracks.content.MyTracksProviderUtils; import com.google.android.apps.mytracks.content.Track; import com.google.android.apps.mytracks.content.TracksColumns; import com.google.android.apps.mytracks.content.MyTracksProviderUtils.Factory; import com.google.android.apps.mytracks.io.file.GpxImporter; import com.google.android.apps.mytracks.testing.TestingProviderUtilsFactory; import com.google.android.testing.mocking.AndroidMock; import com.google.android.testing.mocking.UsesMocks; import android.content.ContentUris; import android.location.Location; import android.location.LocationManager; import android.net.Uri; import android.test.AndroidTestCase; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.SimpleTimeZone; import javax.xml.parsers.ParserConfigurationException; import org.easymock.Capture; import org.easymock.IArgumentMatcher; import org.xml.sax.SAXException; /** * Tests for the GPX importer. * * @author Steffen Horlacher */ public class GpxImporterTest extends AndroidTestCase { private static final String TRACK_NAME = "blablub"; private static final String TRACK_DESC = "s'Laebe isch koi Schlotzer"; private static final String TRACK_LAT_1 = "48.768364"; private static final String TRACK_LON_1 = "9.177886"; private static final String TRACK_ELE_1 = "324.0"; private static final String TRACK_TIME_1 = "2010-04-22T18:21:00Z"; private static final String TRACK_LAT_2 = "48.768374"; private static final String TRACK_LON_2 = "9.177816"; private static final String TRACK_ELE_2 = "333.0"; private static final String TRACK_TIME_2 = "2010-04-22T18:21:50.123"; private static final SimpleDateFormat DATE_FORMAT1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS"); private static final SimpleDateFormat DATE_FORMAT2 = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss'Z'"); static { // We can't omit the timezones in the test, otherwise it'll use the local // timezone and fail depending on where the test runner is. SimpleTimeZone utc = new SimpleTimeZone(0, "UTC"); DATE_FORMAT1.setTimeZone(utc); DATE_FORMAT2.setTimeZone(utc); } // TODO: use real files from different sources with more track points. private static final String VALID_TEST_GPX = "<gpx><trk><name><![CDATA[" + TRACK_NAME + "]]></name><desc><![CDATA[" + TRACK_DESC + "]]></desc><trkseg>" + "<trkpt lat=\"" + TRACK_LAT_1 + "\" lon=\"" + TRACK_LON_1 + "\"><ele>" + TRACK_ELE_1 + "</ele><time>" + TRACK_TIME_1 + "</time></trkpt> +" + "<trkpt lat=\"" + TRACK_LAT_2 + "\" lon=\"" + TRACK_LON_2 + "\"><ele>" + TRACK_ELE_2 + "</ele><time>" + TRACK_TIME_2 + "</time></trkpt>" + "</trkseg></trk></gpx>"; // invalid xml private static final String INVALID_XML_TEST_GPX = VALID_TEST_GPX.substring( 0, VALID_TEST_GPX.length() - 50); private static final String INVALID_LOCATION_TEST_GPX = VALID_TEST_GPX .replaceAll(TRACK_LAT_1, "1000.0"); private static final String INVALID_TIME_TEST_GPX = VALID_TEST_GPX .replaceAll(TRACK_TIME_1, "invalid"); private static final String INVALID_ALTITUDE_TEST_GPX = VALID_TEST_GPX .replaceAll(TRACK_ELE_1, "invalid"); private static final String INVALID_LATITUDE_TEST_GPX = VALID_TEST_GPX .replaceAll(TRACK_LAT_1, "invalid"); private static final String INVALID_LONGITUDE_TEST_GPX = VALID_TEST_GPX .replaceAll(TRACK_LON_1, "invalid"); private static final long TRACK_ID = 1; private static final long TRACK_POINT_ID_1 = 1; private static final long TRACK_POINT_ID_2 = 2; private static final Uri TRACK_ID_URI = ContentUris.appendId( TracksColumns.CONTENT_URI.buildUpon(), TRACK_ID).build(); private MyTracksProviderUtils providerUtils; private Factory oldProviderUtilsFactory; @UsesMocks(MyTracksProviderUtils.class) @Override protected void setUp() throws Exception { super.setUp(); providerUtils = AndroidMock.createMock(MyTracksProviderUtils.class); oldProviderUtilsFactory = TestingProviderUtilsFactory.installWithInstance(providerUtils); } @Override protected void tearDown() throws Exception { TestingProviderUtilsFactory.restoreOldFactory(oldProviderUtilsFactory); super.tearDown(); } /** * Test import success. */ public void testImportSuccess() throws Exception { Capture<Track> trackParam = new Capture<Track>(); Location loc1 = new Location(LocationManager.GPS_PROVIDER); loc1.setTime(DATE_FORMAT2.parse(TRACK_TIME_1).getTime()); loc1.setLatitude(Double.parseDouble(TRACK_LAT_1)); loc1.setLongitude(Double.parseDouble(TRACK_LON_1)); loc1.setAltitude(Double.parseDouble(TRACK_ELE_1)); Location loc2 = new Location(LocationManager.GPS_PROVIDER); loc2.setTime(DATE_FORMAT1.parse(TRACK_TIME_2).getTime()); loc2.setLatitude(Double.parseDouble(TRACK_LAT_2)); loc2.setLongitude(Double.parseDouble(TRACK_LON_2)); loc2.setAltitude(Double.parseDouble(TRACK_ELE_2)); expect(providerUtils.insertTrack(AndroidMock.capture(trackParam))) .andReturn(TRACK_ID_URI); expect(providerUtils.getLastLocationId(TRACK_ID)).andReturn(TRACK_POINT_ID_1).andReturn(TRACK_POINT_ID_2); // A flush happens after the first insertion to get the starting point ID, // which is why we get two calls expect(providerUtils.bulkInsertTrackPoints(LocationsMatcher.eqLoc(loc1), eq(1), eq(TRACK_ID))).andReturn(1); expect(providerUtils.bulkInsertTrackPoints(LocationsMatcher.eqLoc(loc2), eq(1), eq(TRACK_ID))).andReturn(1); providerUtils.updateTrack(AndroidMock.capture(trackParam)); AndroidMock.replay(providerUtils); InputStream is = new ByteArrayInputStream(VALID_TEST_GPX.getBytes()); GpxImporter.importGPXFile(is, providerUtils); AndroidMock.verify(providerUtils); // verify track parameter Track track = trackParam.getValue(); assertEquals(TRACK_NAME, track.getName()); assertEquals(TRACK_DESC, track.getDescription()); assertEquals(DATE_FORMAT2.parse(TRACK_TIME_1).getTime(), track.getStatistics() .getStartTime()); assertNotSame(-1, track.getStartId()); assertNotSame(-1, track.getStopId()); } /** * Test with invalid location - track should be deleted. */ public void testImportLocationFailure() throws ParserConfigurationException, IOException { testInvalidXML(INVALID_LOCATION_TEST_GPX); } /** * Test with invalid time - track should be deleted. */ public void testImportTimeFailure() throws ParserConfigurationException, IOException { testInvalidXML(INVALID_TIME_TEST_GPX); } /** * Test with invalid xml - track should be deleted. */ public void testImportXMLFailure() throws ParserConfigurationException, IOException { testInvalidXML(INVALID_XML_TEST_GPX); } /** * Test with invalid altitude - track should be deleted. */ public void testImportInvalidAltitude() throws ParserConfigurationException, IOException { testInvalidXML(INVALID_ALTITUDE_TEST_GPX); } /** * Test with invalid latitude - track should be deleted. */ public void testImportInvalidLatitude() throws ParserConfigurationException, IOException { testInvalidXML(INVALID_LATITUDE_TEST_GPX); } /** * Test with invalid longitude - track should be deleted. */ public void testImportInvalidLongitude() throws ParserConfigurationException, IOException { testInvalidXML(INVALID_LONGITUDE_TEST_GPX); } private void testInvalidXML(String xml) throws ParserConfigurationException, IOException { expect(providerUtils.insertTrack((Track) AndroidMock.anyObject())) .andReturn(TRACK_ID_URI); expect(providerUtils.bulkInsertTrackPoints((Location[]) AndroidMock.anyObject(), AndroidMock.anyInt(), AndroidMock.anyLong())).andStubReturn(1); expect(providerUtils.getLastLocationId(TRACK_ID)).andStubReturn(TRACK_POINT_ID_1); providerUtils.deleteTrack(TRACK_ID); AndroidMock.replay(providerUtils); InputStream is = new ByteArrayInputStream(xml.getBytes()); try { GpxImporter.importGPXFile(is, providerUtils); } catch (SAXException e) { // expected exception } AndroidMock.verify(providerUtils); } /** * Workaround because of capture bug 2617107 in easymock: * http://sourceforge.net * /tracker/?func=detail&aid=2617107&group_id=82958&atid=567837 */ private static class LocationsMatcher implements IArgumentMatcher { private final Location[] matchLocs; private LocationsMatcher(Location[] expected) { this.matchLocs = expected; } public static Location[] eqLoc(Location[] expected) { IArgumentMatcher matcher = new LocationsMatcher(expected); AndroidMock.reportMatcher(matcher); return null; } public static Location[] eqLoc(Location expected) { return eqLoc(new Location[] { expected}); } @Override public void appendTo(StringBuffer buf) { buf.append("eqLoc(").append(Arrays.toString(matchLocs)).append(")"); } @Override public boolean matches(Object obj) { if (! (obj instanceof Location[])) { return false; } Location[] locs = (Location[]) obj; if (locs.length < matchLocs.length) { return false; } // Only check the first elements (those that will be taken into account) for (int i = 0; i < matchLocs.length; i++) { if (!locationsMatch(locs[i], matchLocs[i])) { return false; } } return true; } private boolean locationsMatch(Location loc1, Location loc2) { return (loc1.getTime() == loc2.getTime()) && (loc1.getLatitude() == loc2.getLatitude()) && (loc1.getLongitude() == loc2.getLongitude()) && (loc1.getAltitude() == loc2.getAltitude()); } } }
Java
// Copyright 2010 Google Inc. All Rights Reserved. package com.google.android.apps.mytracks.io.file; import com.google.android.apps.mytracks.content.MyTracksLocation; import com.google.android.apps.mytracks.content.Sensor; import com.google.android.apps.mytracks.content.Track; import com.google.android.apps.mytracks.content.Waypoint; import android.test.AndroidTestCase; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.StringReader; import java.util.ArrayList; import java.util.List; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.FactoryConfigurationError; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.dom.Text; import org.xml.sax.InputSource; import org.xml.sax.SAXException; /** * Base class for track format writer tests, which sets up a fake track and * gives auxiliary methods for verifying XML output. * * @author Rodrigo Damazio */ public abstract class TrackFormatWriterTest extends AndroidTestCase { // All the user-provided strings have "]]>" to ensure that proper escaping is // being done. protected static final String TRACK_NAME = "Home]]>"; protected static final String TRACK_CATEGORY = "Hiking"; protected static final String TRACK_DESCRIPTION = "The long ]]> journey home"; protected static final String WAYPOINT1_NAME = "point]]>1"; protected static final String WAYPOINT1_CATEGORY = "Statistics"; protected static final String WAYPOINT1_DESCRIPTION = "point 1]]>description"; protected static final String WAYPOINT2_NAME = "point]]>2"; protected static final String WAYPOINT2_CATEGORY = "Waypoint"; protected static final String WAYPOINT2_DESCRIPTION = "point 2]]>description"; private static final int BUFFER_SIZE = 10240; protected Track track; protected MyTracksLocation location1, location2, location3, location4; protected Waypoint wp1, wp2; @Override protected void setUp() throws Exception { super.setUp(); track = new Track(); track.setName(TRACK_NAME); track.setCategory(TRACK_CATEGORY); track.setDescription(TRACK_DESCRIPTION); location1 = new MyTracksLocation("mock"); location2 = new MyTracksLocation("mock"); location3 = new MyTracksLocation("mock"); location4 = new MyTracksLocation("mock"); populateLocations(location1, location2, location3, location4); wp1 = new Waypoint(); wp2 = new Waypoint(); wp1.setLocation(location2); wp1.setName(WAYPOINT1_NAME); wp1.setCategory(WAYPOINT1_CATEGORY); wp1.setDescription(WAYPOINT1_DESCRIPTION); wp2.setLocation(location3); wp2.setName(WAYPOINT2_NAME); wp2.setCategory(WAYPOINT2_CATEGORY); wp2.setDescription(WAYPOINT2_DESCRIPTION); } /** * Populates a list of locations with values. * * @param locations a list of locations */ private void populateLocations(MyTracksLocation... locations) { for (int i = 0; i < locations.length; i++) { MyTracksLocation location = locations[i]; location.setLatitude(i); location.setLongitude(-i); location.setAltitude(i * 10); location.setBearing(i * 100); location.setAccuracy(i * 1000); location.setSpeed(i * 10000); location.setTime(i * 100000); Sensor.SensorData.Builder power = Sensor.SensorData.newBuilder().setValue(100 + i) .setState(Sensor.SensorState.SENDING); Sensor.SensorData.Builder cadence = Sensor.SensorData.newBuilder().setValue(200 + i) .setState(Sensor.SensorState.SENDING); Sensor.SensorData.Builder heartRate = Sensor.SensorData.newBuilder().setValue(300 + i) .setState(Sensor.SensorState.SENDING); Sensor.SensorData.Builder batteryLevel = Sensor.SensorData.newBuilder().setValue(400 + i) .setState(Sensor.SensorState.SENDING); Sensor.SensorDataSet sensorDataSet = Sensor.SensorDataSet.newBuilder().setPower(power) .setCadence(cadence).setHeartRate(heartRate).setBatteryLevel(batteryLevel).build(); location.setSensorData(sensorDataSet); } } /** * Makes the right sequence of calls to the writer in order to write the fake * track in {@link #track}. * * @param writer the writer to write to * @return the written contents */ protected String writeTrack(TrackFormatWriter writer) throws Exception { OutputStream output = new ByteArrayOutputStream(BUFFER_SIZE); writer.prepare(track, output); writer.writeHeader(); writer.writeBeginWaypoints(); writer.writeWaypoint(wp1); writer.writeWaypoint(wp2); writer.writeEndWaypoints(); writer.writeBeginTrack(location1); writer.writeOpenSegment(); writer.writeLocation(location1); writer.writeLocation(location2); writer.writeCloseSegment(); writer.writeOpenSegment(); writer.writeLocation(location3); writer.writeLocation(location4); writer.writeCloseSegment(); writer.writeEndTrack(location4); writer.writeFooter(); writer.close(); return output.toString(); } /** * Gets the text data contained inside a tag. * * @param parent the parent of the tag containing the text * @param elementName the name of the tag containing the text * @return the text contents */ protected String getChildTextValue(Element parent, String elementName) { Element child = getChildElement(parent, elementName); assertTrue(child.hasChildNodes()); NodeList children = child.getChildNodes(); int length = children.getLength(); assertTrue(length > 0); // The children may be a sucession of text elements, just concatenate them String result = ""; for (int i = 0; i < length; i++) { Text textNode = (Text) children.item(i); result += textNode.getNodeValue(); } return result; } /** * Returns all child elements of a given parent which have the given name. * * @param parent the parent to get children from * @param elementName the element name to look for * @param expectedChildren the number of children we're expected to find * @return a list of the found elements */ protected List<Element> getChildElements(Node parent, String elementName, int expectedChildren) { assertTrue(parent.hasChildNodes()); NodeList children = parent.getChildNodes(); int length = children.getLength(); List<Element> result = new ArrayList<Element>(); for (int i = 0; i < length; i++) { Node childNode = children.item(i); if (childNode.getNodeType() == Node.ELEMENT_NODE && childNode.getNodeName().equalsIgnoreCase(elementName)) { result.add((Element) childNode); } } assertTrue(children.toString(), result.size() == expectedChildren); return result; } /** * Returns the single child element of the given parent with the given type. * * @param parent the parent to get a child from * @param elementName the name of the child to look for * @return the child element */ protected Element getChildElement(Node parent, String elementName) { return getChildElements(parent, elementName, 1).get(0); } /** * Parses the given XML contents and returns a DOM {@link Document} for it. */ protected Document parseXmlDocument(String contents) throws FactoryConfigurationError, ParserConfigurationException, SAXException, IOException { DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); builderFactory.setCoalescing(true); // TODO: Somehow do XML validation on Android // builderFactory.setValidating(true); builderFactory.setNamespaceAware(true); builderFactory.setIgnoringComments(true); builderFactory.setIgnoringElementContentWhitespace(true); DocumentBuilder documentBuilder = builderFactory.newDocumentBuilder(); Document doc = documentBuilder.parse( new InputSource(new StringReader(contents))); return doc; } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.io.file; /** * Tests for {@link CsvTrackWriter}. * * @author Rodrigo Damazio */ public class CsvTrackWriterTest extends TrackFormatWriterTest { private static final String BEGIN_TAG = "\""; private static final String END_TAG = "\"\n"; private static final String SEPARATOR = "\",\""; public void testCsvOutput() throws Exception { String expectedTrackHeader = getExpectedLine( "Name", "Activity type", "Description"); String expectedTrack = getExpectedLine(TRACK_NAME, TRACK_CATEGORY, TRACK_DESCRIPTION); String expectedMarkerHeader = getExpectedLine("Marker name", "Marker type", "Marker description", "Latitude (deg)", "Longitude (deg)", "Altitude (m)", "Bearing (deg)", "Accuracy (m)", "Speed (m/s)", "Time"); String expectedMarker1 = getExpectedLine(WAYPOINT1_NAME, WAYPOINT1_CATEGORY, WAYPOINT1_DESCRIPTION, "1.0", "-1.0", "10.0", "100.0", "1,000", "10,000", "1970-01-01T00:01:40.000Z"); String expectedMarker2 = getExpectedLine(WAYPOINT2_NAME, WAYPOINT2_CATEGORY, WAYPOINT2_DESCRIPTION, "2.0", "-2.0", "20.0", "200.0", "2,000", "20,000", "1970-01-01T00:03:20.000Z"); String expectedPointHeader = getExpectedLine("Segment", "Point", "Latitude (deg)", "Longitude (deg)", "Altitude (m)", "Bearing (deg)", "Accuracy (m)", "Speed (m/s)", "Time", "Power (W)", "Cadence (rpm)", "Heart rate (bpm)", "Battery level (%)"); String expectedPoint1 = getExpectedLine("1", "1", "0.0", "0.0", "0.0", "0.0", "0", "0", "1970-01-01T00:00:00.000Z", "100.0", "200.0", "300.0", "400.0"); String expectedPoint2 = getExpectedLine("1", "2", "1.0", "-1.0", "10.0", "100.0", "1,000", "10,000", "1970-01-01T00:01:40.000Z", "101.0", "201.0", "301.0", "401.0"); String expectedPoint3 = getExpectedLine("2", "1", "2.0", "-2.0", "20.0", "200.0", "2,000", "20,000", "1970-01-01T00:03:20.000Z", "102.0", "202.0", "302.0", "402.0"); String expectedPoint4 = getExpectedLine("2", "2", "3.0", "-3.0", "30.0", "300.0", "3,000", "30,000", "1970-01-01T00:05:00.000Z", "103.0", "203.0", "303.0", "403.0"); String expected = expectedTrackHeader + expectedTrack + "\n" + expectedMarkerHeader + expectedMarker1 + expectedMarker2 + "\n" + expectedPointHeader + expectedPoint1 + expectedPoint2 + expectedPoint3 + expectedPoint4; CsvTrackWriter writer = new CsvTrackWriter(getContext()); assertEquals(expected, writeTrack(writer)); } /** * Gets the expected CSV line from a list of expected values. * * @param values expected values */ private String getExpectedLine(String... values) { StringBuilder builder = new StringBuilder(); builder.append(BEGIN_TAG); boolean first = true; for (String value : values) { if (!first) { builder.append(SEPARATOR); } first = false; builder.append(value); } builder.append(END_TAG); return builder.toString(); } }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.io.file; import com.google.android.apps.mytracks.content.DescriptionGenerator; import com.google.android.apps.mytracks.content.Track; import com.google.android.apps.mytracks.content.Waypoint; import android.location.Location; import java.util.List; import java.util.Vector; import org.w3c.dom.Document; import org.w3c.dom.Element; /** * Tests for {@link KmlTrackWriter}. * * @author Rodrigo Damazio */ public class KmlTrackWriterTest extends TrackFormatWriterTest { private static final String FULL_TRACK_DESCRIPTION = "full track description"; /** * A fake version of {@link DescriptionGenerator} which returns a fixed track * description, thus not depending on the context. */ private class FakeDescriptionGenerator implements DescriptionGenerator { @Override public String generateTrackDescription( Track aTrack, Vector<Double> distances, Vector<Double> elevations) { return FULL_TRACK_DESCRIPTION; } @Override public String generateWaypointDescription(Waypoint waypoint) { return null; } } public void testXmlOutput() throws Exception { KmlTrackWriter writer = new KmlTrackWriter(getContext(), new FakeDescriptionGenerator()); String result = writeTrack(writer); Document doc = parseXmlDocument(result); Element kmlTag = getChildElement(doc, "kml"); Element docTag = getChildElement(kmlTag, "Document"); assertEquals(TRACK_NAME, getChildTextValue(docTag, "name")); assertEquals(TRACK_DESCRIPTION, getChildTextValue(docTag, "description")); // There are 3 placemarks - start, track, and end List<Element> placemarkTags = getChildElements(docTag, "Placemark", 3); assertTagIsPlacemark( placemarkTags.get(0), TRACK_NAME + " (Start)", TRACK_DESCRIPTION, location1); assertTagIsPlacemark( placemarkTags.get(2), TRACK_NAME + " (End)", FULL_TRACK_DESCRIPTION, location4); List<Element> folderTag = getChildElements(docTag, "Folder", 1); List<Element> folderPlacemarkTags = getChildElements(folderTag.get(0), "Placemark", 2); assertTagIsPlacemark( folderPlacemarkTags.get(0), WAYPOINT1_NAME, WAYPOINT1_DESCRIPTION, location2); assertTagIsPlacemark( folderPlacemarkTags.get(1), WAYPOINT2_NAME, WAYPOINT2_DESCRIPTION, location3); Element trackPlacemarkTag = placemarkTags.get(1); assertEquals(TRACK_NAME, getChildTextValue(trackPlacemarkTag, "name")); assertEquals(TRACK_DESCRIPTION, getChildTextValue(trackPlacemarkTag, "description")); Element multiTrackTag = getChildElement(trackPlacemarkTag, "gx:MultiTrack"); List<Element> trackTags = getChildElements(multiTrackTag, "gx:Track", 2); assertTagHasPoints(trackTags.get(0), location1, location2); assertTagHasPoints(trackTags.get(1), location3, location4); } /** * Asserts that the given tag is a placemark with the given properties. * * @param tag the tag * @param name the expected placemark name * @param description the expected placemark description * @param location the expected placemark location */ private void assertTagIsPlacemark( Element tag, String name, String description, Location location) { assertEquals(name, getChildTextValue(tag, "name")); assertEquals(description, getChildTextValue(tag, "description")); Element pointTag = getChildElement(tag, "Point"); String expected = location.getLongitude() + "," + location.getLatitude() + "," + location.getAltitude(); String actual = getChildTextValue(pointTag, "coordinates"); assertEquals(expected, actual); } /** * Asserts that the given tag has a list of "gx:coord" subtags matching the * expected locations. * * @param tag the parent tag * @param locations list of expected locations */ private void assertTagHasPoints(Element tag, Location... locations) { List<Element> coordTags = getChildElements(tag, "gx:coord", locations.length); for (int i = 0; i < locations.length; i++) { Location location = locations[i]; String expected = location.getLongitude() + " " + location.getLatitude() + " " + location.getAltitude(); String actual = coordTags.get(i).getFirstChild().getTextContent(); assertEquals(expected, actual); } } }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.io.file; import com.google.android.apps.mytracks.content.MyTracksLocation; import com.google.android.apps.mytracks.content.Sensor; import com.google.android.apps.mytracks.util.StringUtils; import java.util.List; import org.w3c.dom.Document; import org.w3c.dom.Element; /** * Tests for {@link TcxTrackWriter}. * * @author Sandor Dornbush */ public class TcxTrackWriterTest extends TrackFormatWriterTest { public void testXmlOutput() throws Exception { TrackFormatWriter writer = new TcxTrackWriter(getContext()); String result = writeTrack(writer); Document doc = parseXmlDocument(result); Element root = getChildElement(doc, "TrainingCenterDatabase"); Element activitiesTag = getChildElement(root, "Activities"); Element activityTag = getChildElement(activitiesTag, "Activity"); Element lapTag = getChildElement(activityTag, "Lap"); List<Element> segmentTags = getChildElements(lapTag, "Track", 2); Element segment1Tag = segmentTags.get(0); Element segment2Tag = segmentTags.get(1); List<Element> seg1PointTags = getChildElements(segment1Tag, "Trackpoint", 2); List<Element> seg2PointTags = getChildElements(segment2Tag, "Trackpoint", 2); assertTagsMatchPoints(seg1PointTags, location1, location2); assertTagsMatchPoints(seg2PointTags, location3, location4); } /** * Asserts that the given tags describe the given locations in the same order. * * @param tags list of tags * @param locations list of locations */ private void assertTagsMatchPoints(List<Element> tags, MyTracksLocation... locations) { assertEquals(locations.length, tags.size()); for (int i = 0; i < locations.length; i++) { assertTagMatchesLocation(tags.get(i), locations[i]); } } /** * Asserts that the given tag describes the given location. * * @param tag the tag * @param location the location */ private void assertTagMatchesLocation(Element tag, MyTracksLocation location) { assertEquals(StringUtils.formatDateTimeIso8601(location.getTime()), getChildTextValue(tag, "Time")); Element positionTag = getChildElement(tag, "Position"); assertEquals( Double.toString(location.getLatitude()), getChildTextValue(positionTag, "LatitudeDegrees")); assertEquals(Double.toString(location.getLongitude()), getChildTextValue(positionTag, "LongitudeDegrees")); assertEquals(Double.toString(location.getAltitude()), getChildTextValue(tag, "AltitudeMeters")); assertTrue(location.getSensorDataSet() != null); Sensor.SensorDataSet sds = location.getSensorDataSet(); List<Element> heartRate = getChildElements(tag, "HeartRateBpm", 1); assertEquals(Integer.toString(sds.getHeartRate().getValue()), getChildTextValue(heartRate.get(0), "Value")); List<Element> extensions = getChildElements(tag, "Extensions", 1); List<Element> tpx = getChildElements(extensions.get(0), "TPX", 1); assertEquals( Integer.toString(sds.getCadence().getValue()), getChildTextValue(tpx.get(0), "RunCadence")); assertEquals( Integer.toString(sds.getPower().getValue()), getChildTextValue(tpx.get(0), "Watts")); } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.io.file; import java.io.File; /** * A simple, fake {@link TrackWriter} subclass with all methods mocked out. * Tests are expected to override {@link #writeTrack}. * * @author Matthew Simmons * */ public class MockTrackWriter implements TrackWriter { public OnWriteListener onWriteListener; @Override public void setOnWriteListener(OnWriteListener onWriteListener) { this.onWriteListener = onWriteListener; } @Override public void setDirectory(File directory) { throw new UnsupportedOperationException("not implemented"); } @Override public String getAbsolutePath() { throw new UnsupportedOperationException("not implemented"); } @Override public void writeTrack() { throw new UnsupportedOperationException("not implemented"); } @Override public void stopWriteTrack() { throw new UnsupportedOperationException("not implemented"); } @Override public boolean wasSuccess() { return false; } @Override public int getErrorMessage() { return 0; } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.io.sendtogoogle; import com.google.android.maps.mytracks.R; import android.app.Dialog; import android.content.Intent; import android.test.ActivityInstrumentationTestCase2; import android.widget.LinearLayout; import android.widget.TextView; /** * Tests the {@link UploadResultActivity}. * * @author Youtao Liu */ public class UploadResultActivityTest extends ActivityInstrumentationTestCase2<UploadResultActivity> { private UploadResultActivity uploadResultActivity; /** * This method is necessary for ActivityInstrumentationTestCase2. */ public UploadResultActivityTest() { super(UploadResultActivity.class); } /** * Checks the display of dialog when send to all and all sends are successful. */ public void testAllSuccess() { initialActivity(true, true, true, true, true, true); Dialog dialog = uploadResultActivity.getDialog(); TextView textView = (TextView) dialog.findViewById(R.id.upload_result_success_footer); assertTrue(textView.isShown()); } /** * Checks the display of dialog when send to all and all sends are failed. */ public void testAllFailed() { // Send all kinds but all failed. initialActivity(true, true, true, false, false, false); Dialog dialog = uploadResultActivity.getDialog(); TextView textView = (TextView) dialog.findViewById(R.id.upload_result_error_footer); assertTrue(textView.isShown()); } /** * Checks the display of dialog when match following items: * <ul> * <li>Only send to Maps and Docs.</li> * <li>Send to Maps successful.</li> * <li>Send to Docs failed.</li> * </ul> */ public void testPartialSuccess() { initialActivity(true, false, true, true, false, false); Dialog dialog = uploadResultActivity.getDialog(); TextView textView = (TextView) dialog.findViewById(R.id.upload_result_error_footer); assertTrue(textView.isShown()); LinearLayout mapsResult = (LinearLayout) dialog.findViewById(R.id.upload_result_maps_result); assertTrue(mapsResult.isShown()); LinearLayout fusionTablesResult = (LinearLayout) dialog.findViewById( R.id.upload_result_fusion_tables_result); assertFalse(fusionTablesResult.isShown()); LinearLayout docsResult = (LinearLayout) dialog.findViewById(R.id.upload_result_docs_result); assertTrue(docsResult.isShown()); } /** * Initial a {@link SendRequest} and then initials a activity to be tested. * * @param isSendMaps * @param isSendFusionTables * @param isSendDocs * @param isMapsSuccess * @param isFusionTablesSuccess * @param isDocsSuccess */ private void initialActivity(boolean isSendMaps, boolean isSendFusionTables, boolean isSendDocs, boolean isMapsSuccess, boolean isFusionTablesSuccess, boolean isDocsSuccess) { Intent intent = new Intent(); SendRequest sendRequest = new SendRequest(1L, true, true, true); sendRequest.setSendMaps(isSendMaps); sendRequest.setSendFusionTables(isSendFusionTables); sendRequest.setSendDocs(isSendDocs); sendRequest.setMapsSuccess(isMapsSuccess); sendRequest.setFusionTablesSuccess(isFusionTablesSuccess); sendRequest.setDocsSuccess(isDocsSuccess); intent.putExtra(SendRequest.SEND_REQUEST_KEY, sendRequest); setActivityIntent(intent); uploadResultActivity = this.getActivity(); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.io.sendtogoogle; /** * Tests the {@link SendToGoogleUtils}. * * @author Youtao Liu */ import com.google.android.apps.mytracks.TrackStubUtils; import com.google.android.apps.mytracks.content.MyTracksLocation; import com.google.android.apps.mytracks.content.Track; import android.location.Location; import java.util.ArrayList; import java.util.List; import junit.framework.TestCase; public class SendToGoogleUtilsTest extends TestCase { private final static long TRACK_ID = 1L; private final static String TRACK_CATEGORY = "trackCategory"; private final static String TRACK_NAME = "trackName"; private final static double DIFFERENCE = 0.02; private final static double INVALID_LATITUDE = 91; /** * Tests the method * {@link SendToGoogleUtils#prepareTrackSegment(Track, java.util.ArrayList)} * when there is only one location in a segment. */ public void testPrepareTrackSegment_onlyOneLocation() { Track trackStub = TrackStubUtils.createTrack(1); assertFalse(SendToGoogleUtils.prepareTrackSegment(trackStub, null)); } /** * Tests the method * {@link SendToGoogleUtils#prepareTrackSegment(Track, ArrayList)} when there * is no stop time. */ public void testPrepareTrackSegment_noStopTime() { Track trackStub = TrackStubUtils.createTrack(2); assertEquals(-1L, trackStub.getStatistics().getStopTime()); ArrayList<Track> tracksArray = new ArrayList<Track>(); assertTrue(SendToGoogleUtils.prepareTrackSegment(trackStub, tracksArray)); assertEquals(trackStub, tracksArray.get(0)); // The stop time should be the time of last location assertEquals(trackStub.getLocations().get(1).getTime(), trackStub.getStatistics().getStopTime()); } /** * Tests the method * {@link SendToGoogleUtils#prepareTrackSegment(Track, java.util.ArrayList)} * when there is stop time. */ public void testPrepareTrackSegment_hasStopTime() { Track trackStub = TrackStubUtils.createTrack(2); // Gives a margin to make sure the this time will be not same with the last // location in the track. long stopTime = System.currentTimeMillis() + 1000; trackStub.getStatistics().setStopTime(stopTime); ArrayList<Track> tracksArray = new ArrayList<Track>(); SendToGoogleUtils.prepareTrackSegment(trackStub, tracksArray); assertEquals(trackStub, tracksArray.get(0)); assertEquals(stopTime, trackStub.getStatistics().getStopTime()); } /** * Tests the method * {@link SendToGoogleUtils#prepareLocations(Track, java.util.List)} . */ public void testPrepareLocations() { Track trackStub = TrackStubUtils.createTrack(2); trackStub.setId(TRACK_ID); trackStub.setName(TRACK_NAME); trackStub.setCategory(TRACK_CATEGORY); List<Location> locationsArray = new ArrayList<Location>(); // Adds 100 location to List. for (int i = 0; i < 100; i++) { // Use this variable as a flag to make all points in the track can be kept // after run the LocationUtils#decimate(Track, double) with // Ramer–Douglas–Peucker algorithm. double latitude = TrackStubUtils.INITIAL_LATITUDE; if (i % 2 == 0) { latitude -= DIFFERENCE * (i % 10); } // Inserts 9 points which have wrong latitude, so would have 10 segments. if (i % 10 == 0 && i > 0) { MyTracksLocation location = TrackStubUtils.createMyTracksLocation(); location.setLatitude(INVALID_LATITUDE); locationsArray.add(location); } else { locationsArray.add(TrackStubUtils.createMyTracksLocation(latitude, TrackStubUtils.INITIAL_LONGITUDE + DIFFERENCE * (i % 10), TrackStubUtils.INITIAL_ALTITUDE + DIFFERENCE * (i % 10))); } } ArrayList<Track> result = SendToGoogleUtils.prepareLocations(trackStub, locationsArray); assertEquals(10, result.size()); // Checks all segments. for (int i = 0; i < 10; i++) { Track segmentOne = result.get(i); assertEquals(TRACK_ID, segmentOne.getId()); assertEquals(TRACK_NAME, segmentOne.getName()); assertEquals(TRACK_CATEGORY, segmentOne.getCategory()); } // Checks all locations in the first segment. for (int j = 0; j < 9; j++) { double latitude = TrackStubUtils.INITIAL_LATITUDE; if (j % 2 == 0) { latitude -= DIFFERENCE * (j % 10); } Location oneLocation = result.get(0).getLocations().get(j); assertEquals(TrackStubUtils.createMyTracksLocation().getAltitude() + DIFFERENCE * (j % 10), oneLocation.getAltitude()); assertEquals(latitude, oneLocation.getLatitude()); assertEquals(TrackStubUtils.createMyTracksLocation().getLongitude() + DIFFERENCE * (j % 10), oneLocation.getLongitude()); } } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.io.sendtogoogle; import com.google.android.apps.mytracks.Constants; import com.google.android.maps.mytracks.R; import android.app.Instrumentation; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.test.ActivityInstrumentationTestCase2; import android.widget.CheckBox; import android.widget.RadioButton; /** * Tests the {@link UploadServiceChooserActivity}. * * @author Youtao Liu */ public class UploadServiceChooserActivityTest extends ActivityInstrumentationTestCase2<UploadServiceChooserActivity> { private Instrumentation instrumentation; private UploadServiceChooserActivity uploadServiceChooserActivity; public UploadServiceChooserActivityTest() { super(UploadServiceChooserActivity.class); } @Override protected void setUp() throws Exception { super.setUp(); instrumentation = getInstrumentation(); } /** * Tests the logic to display all options. */ public void testOnCreateDialog_displayAll() { // Initials activity to display all send items. initialActivity(true, true, true); instrumentation.waitForIdleSync(); assertTrue(getMapsCheckBox().isShown()); assertTrue(getFusionTablesCheckBox().isShown()); assertTrue(getDocsCheckBox().isShown()); // Clicks to disable all send items. uploadServiceChooserActivity.runOnUiThread(new Runnable() { public void run() { if (getMapsCheckBox().isChecked()) { getMapsCheckBox().performClick(); } if (getFusionTablesCheckBox().isChecked()) { getFusionTablesCheckBox().performClick(); } if (getDocsCheckBox().isChecked()) { getDocsCheckBox().performClick(); } } }); instrumentation.waitForIdleSync(); assertTrue(getMapsCheckBox().isShown()); assertTrue(getFusionTablesCheckBox().isShown()); assertTrue(getDocsCheckBox().isShown()); assertFalse(getNewMapRadioButton().isShown()); assertFalse(getExistingMapRadioButton().isShown()); } /** * Tests the logic to display only the "Send to Google Maps" option. */ public void testOnCreateDialog_displayOne() { // Initials activity to display all send items. initialActivity(true, false, false); instrumentation.waitForIdleSync(); assertTrue(getMapsCheckBox().isShown()); // Clicks to enable this items. uploadServiceChooserActivity.runOnUiThread(new Runnable() { public void run() { if (!getMapsCheckBox().isChecked()) { getMapsCheckBox().performClick(); } } }); instrumentation.waitForIdleSync(); assertTrue(getMapsCheckBox().isShown()); assertTrue(getNewMapRadioButton().isShown()); assertTrue(getExistingMapRadioButton().isShown()); } /** * Tests the logic to display no option. */ public void testOnCreateDialog_displayNone() { initialActivity(false, false, false); assertFalse(getMapsCheckBox().isShown()); assertFalse(getFusionTablesCheckBox().isShown()); assertFalse(getDocsCheckBox().isShown()); } /** * Tests the logic to initial state of check box to unchecked. This test cover * code in method {@link UploadServiceChooserActivity#onCreateDialog(int)}, * {@link UploadServiceChooserActivity#initState()}. */ public void testOnCreateDialog_initStateUnchecked() { initialActivity(true, true, true); // Initial all values to false in SharedPreferences. SharedPreferences prefs = uploadServiceChooserActivity.getSharedPreferences( Constants.SETTINGS_NAME, Context.MODE_PRIVATE); Editor editor = prefs.edit(); editor.putBoolean(uploadServiceChooserActivity.getString(R.string.send_to_maps_key), false); editor.putBoolean(uploadServiceChooserActivity.getString(R.string.send_to_fusion_tables_key), false); editor.putBoolean(uploadServiceChooserActivity.getString(R.string.send_to_docs_key), false); editor.commit(); uploadServiceChooserActivity.runOnUiThread(new Runnable() { public void run() { uploadServiceChooserActivity.initState(); } }); instrumentation.waitForIdleSync(); assertFalse(getMapsCheckBox().isChecked()); assertFalse(getFusionTablesCheckBox().isChecked()); assertFalse(getDocsCheckBox().isChecked()); } /** * Tests the logic to initial state of check box to checked. This test cover * code in method {@link UploadServiceChooserActivity#onCreateDialog(int)}, * {@link UploadServiceChooserActivity#initState()}. */ public void testOnCreateDialog_initStateChecked() { initialActivity(true, true, true); // Initial all values to true in SharedPreferences. SharedPreferences prefs = uploadServiceChooserActivity.getSharedPreferences( Constants.SETTINGS_NAME, Context.MODE_PRIVATE); Editor editor = prefs.edit(); editor.putBoolean(uploadServiceChooserActivity.getString(R.string.send_to_maps_key), true); editor.putBoolean(uploadServiceChooserActivity.getString(R.string.pick_existing_map_key), true); editor.putBoolean(uploadServiceChooserActivity.getString(R.string.send_to_fusion_tables_key), true); editor.putBoolean(uploadServiceChooserActivity.getString(R.string.send_to_docs_key), true); editor.commit(); uploadServiceChooserActivity.runOnUiThread(new Runnable() { public void run() { uploadServiceChooserActivity.initState(); } }); instrumentation.waitForIdleSync(); assertTrue(getMapsCheckBox().isChecked()); assertTrue(getFusionTablesCheckBox().isChecked()); assertTrue(getDocsCheckBox().isChecked()); assertTrue(getExistingMapRadioButton().isChecked()); assertFalse(getNewMapRadioButton().isChecked()); } /** * Tests the logic of saveState when click send button. This test cover code * in method {@link UploadServiceChooserActivity#initState()} and * {@link UploadServiceChooserActivity#saveState()}, */ public void testOnCreateDialog_saveState() { initialActivity(true, true, true); // Initial all values to true in SharedPreferences. SharedPreferences prefs = uploadServiceChooserActivity.getSharedPreferences( Constants.SETTINGS_NAME, Context.MODE_PRIVATE); Editor editor = prefs.edit(); editor.putBoolean(uploadServiceChooserActivity.getString(R.string.send_to_maps_key), true); editor.putBoolean(uploadServiceChooserActivity.getString(R.string.send_to_fusion_tables_key), true); editor.putBoolean(uploadServiceChooserActivity.getString(R.string.send_to_docs_key), true); editor.commit(); uploadServiceChooserActivity.runOnUiThread(new Runnable() { public void run() { uploadServiceChooserActivity.initState(); } }); instrumentation.waitForIdleSync(); uploadServiceChooserActivity.saveState(); // All values in SharedPreferences must be changed. assertTrue(prefs.getBoolean(uploadServiceChooserActivity.getString(R.string.send_to_maps_key), false)); assertTrue(prefs.getBoolean(uploadServiceChooserActivity.getString(R.string.send_to_maps_key), false)); assertTrue(prefs.getBoolean(uploadServiceChooserActivity.getString(R.string.send_to_maps_key), false)); } /** * Tests the logic of startNextActivity when click send button. This test * cover code in method {@link UploadServiceChooserActivity#initState()} and * {@link UploadServiceChooserActivity#startNextActivity()}. */ public void testOnCreateDialog_startNextActivity() { initialActivity(true, true, true); // Initial all values to true or false in SharedPreferences. SharedPreferences prefs = uploadServiceChooserActivity.getSharedPreferences( Constants.SETTINGS_NAME, Context.MODE_PRIVATE); Editor editor = prefs.edit(); editor.putBoolean(uploadServiceChooserActivity.getString(R.string.send_to_maps_key), true); editor.putBoolean(uploadServiceChooserActivity.getString(R.string.send_to_docs_key), true); editor.putBoolean(uploadServiceChooserActivity.getString(R.string.send_to_fusion_tables_key), false); editor.commit(); uploadServiceChooserActivity.runOnUiThread(new Runnable() { public void run() { uploadServiceChooserActivity.initState(); } }); instrumentation.waitForIdleSync(); uploadServiceChooserActivity.startNextActivity(); // All values in SendRequest must be same as set above. assertTrue(uploadServiceChooserActivity.getSendRequest().isSendMaps()); assertTrue(uploadServiceChooserActivity.getSendRequest().isSendDocs()); assertFalse(uploadServiceChooserActivity.getSendRequest().isSendFusionTables()); } /** * Initials a activity to be tested. * * @param showMaps * @param showFusionTables * @param showDocs */ private void initialActivity(boolean showMaps, boolean showFusionTables, boolean showDocs) { Intent intent = new Intent(); intent.putExtra(SendRequest.SEND_REQUEST_KEY, new SendRequest(1L, showMaps, showFusionTables, showDocs)); setActivityIntent(intent); uploadServiceChooserActivity = this.getActivity(); } private CheckBox getMapsCheckBox() { return (CheckBox) uploadServiceChooserActivity.getAlertDialog().findViewById(R.id.send_google_maps); } private CheckBox getFusionTablesCheckBox() { return (CheckBox) uploadServiceChooserActivity.getAlertDialog().findViewById( R.id.send_google_fusion_tables); } private CheckBox getDocsCheckBox() { return (CheckBox) uploadServiceChooserActivity.getAlertDialog().findViewById(R.id.send_google_docs); } private RadioButton getNewMapRadioButton() { return (RadioButton) uploadServiceChooserActivity.getAlertDialog().findViewById( R.id.send_google_new_map); } private RadioButton getExistingMapRadioButton() { return (RadioButton) uploadServiceChooserActivity.getAlertDialog().findViewById( R.id.send_google_existing_map); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.io.sendtogoogle; import android.accounts.Account; import android.os.Parcel; import android.os.Parcelable; import android.test.AndroidTestCase; /** * Tests the {@link SendRequest}. * * @author Youtao Liu */ public class SendRequestTest extends AndroidTestCase { private SendRequest sendRequest; final static private String ACCOUNTNAME = "testAccount1"; final static private String ACCOUNTYPE = "testType1"; final static private String MAPID = "mapId1"; @Override protected void setUp() throws Exception { super.setUp(); sendRequest = new SendRequest(1, true, true, true); } /** * Tests the method {@link SendRequest#getTrackId()}. The value should be set * to 1 when it is initialed in setup method. */ public void testGetTrackId() { assertEquals(1, sendRequest.getTrackId()); } /** * Tests the method {@link SendRequest#isShowMaps()}. The value should be set * to true when it is initialed in setup method. */ public void testIsShowMaps() { assertEquals(true, sendRequest.isShowMaps()); } /** * Tests the method {@link SendRequest#isShowFusionTables()}. The value should * be set to true when it is initialed in setup method. */ public void testIsShowFusionTables() { assertEquals(true, sendRequest.isShowFusionTables()); } /** * Tests the method {@link SendRequest#isShowDocs()}. The value should be set * to true when it is initialed in setup method. */ public void testIsShowDocs() { assertEquals(true, sendRequest.isShowDocs()); } public void testIsShowAll() { assertEquals(true, sendRequest.isShowAll()); sendRequest = new SendRequest(1, false, true, true); assertEquals(false, sendRequest.isShowAll()); sendRequest = new SendRequest(1, true, false, true); assertEquals(false, sendRequest.isShowAll()); sendRequest = new SendRequest(1, true, true, false); assertEquals(false, sendRequest.isShowAll()); sendRequest = new SendRequest(1, false, true, false); assertEquals(false, sendRequest.isShowAll()); sendRequest = new SendRequest(1, false, false, false); assertEquals(false, sendRequest.isShowAll()); } public void testIsSendMaps() { assertEquals(false, sendRequest.isSendMaps()); sendRequest.setSendMaps(true); assertEquals(true, sendRequest.isSendMaps()); } public void testIsSendFusionTables() { assertEquals(false, sendRequest.isSendFusionTables()); sendRequest.setSendFusionTables(true); assertEquals(true, sendRequest.isSendFusionTables()); } /** * Tests the method {@link SendRequest#isSendDocs()}. The value should be set * to false which is its default value when it is initialed in setup method. */ public void testIsSendDocs() { assertEquals(false, sendRequest.isSendDocs()); sendRequest.setSendDocs(true); assertEquals(true, sendRequest.isSendDocs()); } /** * Tests the method {@link SendRequest#isNewMap()}. The value should be set to * false which is its default value when it is initialed in setup method. */ public void testIsNewMap() { assertEquals(false, sendRequest.isNewMap()); sendRequest.setNewMap(true); assertEquals(true, sendRequest.isNewMap()); } /** * Tests the method {@link SendRequest#getAccount()}. The value should be set * to null which is its default value when it is initialed in setup method. */ public void testGetAccount() { assertEquals(null, sendRequest.getAccount()); Account account = new Account(ACCOUNTNAME, ACCOUNTYPE); sendRequest.setAccount(account); assertEquals(account, sendRequest.getAccount()); } /** * Tests the method {@link SendRequest#getMapId()}. The value should be set to * null which is its default value when it is initialed in setup method. */ public void testGetMapId() { assertEquals(null, sendRequest.getMapId()); sendRequest.setMapId("1"); assertEquals("1", "1"); } /** * Tests the method {@link SendRequest#isMapsSuccess()}. The value should be * set to false which is its default value when it is initialed in setup * method. */ public void testIsMapsSuccess() { assertEquals(false, sendRequest.isMapsSuccess()); sendRequest.setMapsSuccess(true); assertEquals(true, sendRequest.isMapsSuccess()); } /** * Tests the method {@link SendRequest#isFusionTablesSuccess()}. The value * should be set to false which is its default value when it is initialed in * setup method. */ public void testIsFusionTablesSuccess() { assertEquals(false, sendRequest.isFusionTablesSuccess()); sendRequest.setFusionTablesSuccess(true); assertEquals(true, sendRequest.isFusionTablesSuccess()); } /** * Tests the method {@link SendRequest#isDocsSuccess()}. The value should be * set to false which is its default value when it is initialed in setup * method. */ public void testIsDocsSuccess() { assertEquals(false, sendRequest.isDocsSuccess()); sendRequest.setDocsSuccess(true); assertEquals(true, sendRequest.isDocsSuccess()); } /** * Tests SendRequest.CREATOR.createFromParcel when all values are true. */ public void testCreateFromParcel_true() { Parcel sourceParcel = Parcel.obtain(); sourceParcel.setDataPosition(0); sourceParcel.writeLong(2); sourceParcel.writeByte((byte) 1); sourceParcel.writeByte((byte) 1); sourceParcel.writeByte((byte) 1); sourceParcel.writeByte((byte) 1); sourceParcel.writeByte((byte) 1); sourceParcel.writeByte((byte) 1); sourceParcel.writeByte((byte) 1); Account account = new Account(ACCOUNTNAME, ACCOUNTYPE); sourceParcel.writeParcelable(account, 0); sourceParcel.writeString(MAPID); sourceParcel.writeByte((byte) 1); sourceParcel.writeByte((byte) 1); sourceParcel.writeByte((byte) 1); sourceParcel.setDataPosition(0); sendRequest = SendRequest.CREATOR.createFromParcel(sourceParcel); assertEquals(2, sendRequest.getTrackId()); assertEquals(true, sendRequest.isShowMaps()); assertEquals(true, sendRequest.isShowFusionTables()); assertEquals(true, sendRequest.isShowDocs()); assertEquals(true, sendRequest.isSendMaps()); assertEquals(true, sendRequest.isSendFusionTables()); assertEquals(true, sendRequest.isSendDocs()); assertEquals(true, sendRequest.isNewMap()); assertEquals(account, sendRequest.getAccount()); assertEquals(MAPID, sendRequest.getMapId()); assertEquals(true, sendRequest.isMapsSuccess()); assertEquals(true, sendRequest.isFusionTablesSuccess()); assertEquals(true, sendRequest.isDocsSuccess()); } /** * Tests SendRequest.CREATOR.createFromParcel when all values are false. */ public void testCreateFromParcel_false() { Parcel sourceParcel = Parcel.obtain(); sourceParcel.setDataPosition(0); sourceParcel.writeLong(4); sourceParcel.writeByte((byte) 0); sourceParcel.writeByte((byte) 0); sourceParcel.writeByte((byte) 0); sourceParcel.writeByte((byte) 0); sourceParcel.writeByte((byte) 0); sourceParcel.writeByte((byte) 0); sourceParcel.writeByte((byte) 0); Account account = new Account(ACCOUNTNAME, ACCOUNTYPE); sourceParcel.writeParcelable(account, 0); sourceParcel.writeString(MAPID); sourceParcel.writeByte((byte) 0); sourceParcel.writeByte((byte) 0); sourceParcel.writeByte((byte) 0); sourceParcel.setDataPosition(0); sendRequest = SendRequest.CREATOR.createFromParcel(sourceParcel); assertEquals(4, sendRequest.getTrackId()); assertEquals(false, sendRequest.isShowMaps()); assertEquals(false, sendRequest.isShowFusionTables()); assertEquals(false, sendRequest.isShowDocs()); assertEquals(false, sendRequest.isSendMaps()); assertEquals(false, sendRequest.isSendFusionTables()); assertEquals(false, sendRequest.isSendDocs()); assertEquals(false, sendRequest.isNewMap()); assertEquals(account, sendRequest.getAccount()); assertEquals(MAPID, sendRequest.getMapId()); assertEquals(false, sendRequest.isMapsSuccess()); assertEquals(false, sendRequest.isFusionTablesSuccess()); assertEquals(false, sendRequest.isDocsSuccess()); } /** * Tests {@link SendRequest#writeToParcel(Parcel, int)} when all input values * are true or affirmative. */ public void testWriteToParcel_allTrue() { sendRequest = new SendRequest(1, false, false, false); Parcel parcelWrite1st = Parcel.obtain(); parcelWrite1st.setDataPosition(0); sendRequest.writeToParcel(parcelWrite1st, 1); parcelWrite1st.setDataPosition(0); long trackId = parcelWrite1st.readLong(); boolean showMaps = parcelWrite1st.readByte() == 1; boolean showFusionTables = parcelWrite1st.readByte() == 1; boolean showDocs = parcelWrite1st.readByte() == 1; boolean sendMaps = parcelWrite1st.readByte() == 1; boolean sendFusionTables = parcelWrite1st.readByte() == 1; boolean sendDocs = parcelWrite1st.readByte() == 1; boolean newMap = parcelWrite1st.readByte() == 1; Parcelable account = parcelWrite1st.readParcelable(null); String mapId = parcelWrite1st.readString(); boolean mapsSuccess = parcelWrite1st.readByte() == 1; boolean fusionTablesSuccess = parcelWrite1st.readByte() == 1; boolean docsSuccess = parcelWrite1st.readByte() == 1; assertEquals(1, trackId); assertEquals(false, showMaps); assertEquals(false, showFusionTables); assertEquals(false, showDocs); assertEquals(false, sendMaps); assertEquals(false, sendFusionTables); assertEquals(false, sendDocs); assertEquals(false, newMap); assertEquals(null, account); assertEquals(null, mapId); assertEquals(false, mapsSuccess); assertEquals(false, fusionTablesSuccess); assertEquals(false, docsSuccess); } /** * Tests {@link SendRequest#writeToParcel(Parcel, int)} when all input values * are false or negative. */ public void testWriteToParcel_allFalse() { sendRequest = new SendRequest(4, true, true, true); sendRequest.setSendMaps(true); sendRequest.setSendFusionTables(true); sendRequest.setSendDocs(true); sendRequest.setNewMap(true); Account accountNew = new Account(ACCOUNTNAME + "2", ACCOUNTYPE + "2"); sendRequest.setAccount(accountNew); sendRequest.setMapId(MAPID); sendRequest.setMapsSuccess(true); sendRequest.setFusionTablesSuccess(true); sendRequest.setDocsSuccess(true); Parcel parcelWrite2nd = Parcel.obtain(); parcelWrite2nd.setDataPosition(0); sendRequest.writeToParcel(parcelWrite2nd, 1); parcelWrite2nd.setDataPosition(0); long trackId = parcelWrite2nd.readLong(); boolean showMaps = parcelWrite2nd.readByte() == 1; boolean showFusionTables = parcelWrite2nd.readByte() == 1; boolean showDocs = parcelWrite2nd.readByte() == 1; boolean sendMaps = parcelWrite2nd.readByte() == 1; boolean sendFusionTables = parcelWrite2nd.readByte() == 1; boolean sendDocs = parcelWrite2nd.readByte() == 1; boolean newMap = parcelWrite2nd.readByte() == 1; Parcelable account = parcelWrite2nd.readParcelable(null); String mapId = parcelWrite2nd.readString(); boolean mapsSuccess = parcelWrite2nd.readByte() == 1; boolean fusionTablesSuccess = parcelWrite2nd.readByte() == 1; boolean docsSuccess = parcelWrite2nd.readByte() == 1; assertEquals(4, trackId); assertEquals(true, showMaps); assertEquals(true, showFusionTables); assertEquals(true, showDocs); assertEquals(true, sendMaps); assertEquals(true, sendFusionTables); assertEquals(true, sendDocs); assertEquals(true, newMap); assertEquals(accountNew, account); assertEquals(MAPID, mapId); assertEquals(true, mapsSuccess); assertEquals(true, fusionTablesSuccess); assertEquals(true, docsSuccess); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.io.fusiontables; import com.google.android.apps.mytracks.content.Track; import com.google.android.apps.mytracks.stats.TripStatistics; import android.location.Location; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.util.ArrayList; import junit.framework.TestCase; /** * Tests {@link SendFusionTablesUtils}. * * @author Jimmy Shih */ public class SendFusionTablesUtilsTest extends TestCase { /** * Tests {@link SendFusionTablesUtils#getMapUrl(Track)} with null track. */ public void testGetMapUrl_null_track() { assertEquals(null, SendFusionTablesUtils.getMapUrl(null)); } /** * Tests {@link SendFusionTablesUtils#getMapUrl(Track)} with null table id. */ public void testGetMapUrl_null_table_id() { Track track = new Track(); TripStatistics stats = new TripStatistics(); stats.setBounds((int) 100.E6, (int) 10.E6, (int) 50.E6, (int) 5.E6); track.setStatistics(stats); track.setTableId(null); assertEquals(null, SendFusionTablesUtils.getMapUrl(track)); } /** * Tests {@link SendFusionTablesUtils#getMapUrl(Track)} with null stats. */ public void testGetMapUrl_null_stats() { Track track = new Track(); track.setStatistics(null); track.setTableId("123"); assertEquals(null, SendFusionTablesUtils.getMapUrl(track)); } /** * Tests {@link SendFusionTablesUtils#getMapUrl(Track)} with a valid track. */ public void testGetMapUrl_valid_track() { Track track = new Track(); TripStatistics stats = new TripStatistics(); stats.setBounds((int) 100.E6, (int) 10.E6, (int) 50.E6, (int) 5.E6); track.setStatistics(stats); track.setTableId("123"); assertEquals( "https://www.google.com/fusiontables/embedviz?" + "viz=MAP&q=select+col0,+col1,+col2,+col3+from+123+&h=false&lat=7.500000&lng=75.000000" + "&z=15&t=1&l=col2", SendFusionTablesUtils.getMapUrl(track)); } /** * Tests (@link {@link SendFusionTablesUtils#formatSqlValues(String...)} with * no value. */ public void testFormatSqlValues_no_value() { assertEquals("()", SendFusionTablesUtils.formatSqlValues()); } /** * Tests (@link {@link SendFusionTablesUtils#formatSqlValues(String...)} with * an empty string. */ public void testFormatSqlValues_empty_string() { assertEquals("(\'\')", SendFusionTablesUtils.formatSqlValues("")); } /** * Tests (@link {@link SendFusionTablesUtils#formatSqlValues(String...)} with * one value. */ public void testFormatSqlValues_one_value() { assertEquals("(\'first\')", SendFusionTablesUtils.formatSqlValues("first")); } /** * Tests (@link {@link SendFusionTablesUtils#formatSqlValues(String...)} with * two values. */ public void testFormatSqlValues_two_values() { assertEquals( "(\'first\',\'second\')", SendFusionTablesUtils.formatSqlValues("first", "second")); } /** * Tests {@link SendFusionTablesUtils#escapeSqlString(String)} with a value * containing several single quotes. */ public void testEscapeSqValuel() { String value = "let's'"; assertEquals("let''s''", SendFusionTablesUtils.escapeSqlString(value)); } /** * Tests {@link SendFusionTablesUtils#getKmlPoint(Location)} with a null * point. */ public void testGetKmlPoint_null_point() { assertEquals( "<Point><coordinates></coordinates></Point>", SendFusionTablesUtils.getKmlPoint(null)); } /** * Tests {@link SendFusionTablesUtils#getKmlPoint(Location)} with a valid * point. */ public void testGetKmlPoint_valid_point() { Location location = new Location("test"); location.setLongitude(10.1); location.setLatitude(20.2); location.setAltitude(30.3); assertEquals("<Point><coordinates>10.1,20.2,30.3</coordinates></Point>", SendFusionTablesUtils.getKmlPoint(location)); } /** * Tests {@link SendFusionTablesUtils#getKmlLineString(ArrayList)} with a null * locations. */ public void testKmlLineString_null_locations() { assertEquals("<LineString><coordinates></coordinates></LineString>", SendFusionTablesUtils.getKmlLineString(null)); } /** * Tests {@link SendFusionTablesUtils#getKmlLineString(ArrayList)} with no * location. */ public void testKmlLineString_no_location() { ArrayList<Location> locations = new ArrayList<Location>(); assertEquals("<LineString><coordinates></coordinates></LineString>", SendFusionTablesUtils.getKmlLineString(locations)); } /** * Tests {@link SendFusionTablesUtils#getKmlLineString(ArrayList)} with one * location. */ public void testKmlLineString_one_location() { ArrayList<Location> locations = new ArrayList<Location>(); Location location = new Location("test"); location.setLongitude(10.1); location.setLatitude(20.2); location.setAltitude(30.3); locations.add(location); assertEquals("<LineString><coordinates>10.1,20.2,30.3</coordinates></LineString>", SendFusionTablesUtils.getKmlLineString(locations)); } /** * Tests {@link SendFusionTablesUtils#getKmlLineString(ArrayList)} with two * locations. */ public void testKmlLineString_two_locations() { ArrayList<Location> locations = new ArrayList<Location>(); Location location1 = new Location("test"); location1.setLongitude(10.1); location1.setLatitude(20.2); location1.setAltitude(30.3); locations.add(location1); Location location2 = new Location("test"); location2.setLongitude(1.1); location2.setLatitude(2.2); location2.removeAltitude(); locations.add(location2); assertEquals("<LineString><coordinates>10.1,20.2,30.3 1.1,2.2</coordinates></LineString>", SendFusionTablesUtils.getKmlLineString(locations)); } /** * Tests {@link SendFusionTablesUtils#appendLocation(Location, StringBuilder)} * with no altitude. */ public void testAppendLocation_no_altitude() { StringBuilder builder = new StringBuilder(); Location location = new Location("test"); location.setLongitude(10.1); location.setLatitude(20.2); location.removeAltitude(); SendFusionTablesUtils.appendLocation(location, builder); assertEquals("10.1,20.2", builder.toString()); } /** * Tests {@link SendFusionTablesUtils#appendLocation(Location, StringBuilder)} * with altitude. */ public void testAppendLocation_has_altitude() { StringBuilder builder = new StringBuilder(); Location location = new Location("test"); location.setLongitude(10.1); location.setLatitude(20.2); location.setAltitude(30.3); SendFusionTablesUtils.appendLocation(location, builder); assertEquals("10.1,20.2,30.3", builder.toString()); } /** * Tests {@link SendFusionTablesUtils#getTableId(InputStream)} with a null * inputstream. */ public void testGetTableId_null() { assertEquals(null, SendFusionTablesUtils.getTableId(null)); } /** * Tests {@link SendFusionTablesUtils#getTableId(InputStream)} with an * inputstream containing no data. */ public void testGetTableId_no_data() { InputStream inputStream = new ByteArrayInputStream(new byte[0]); assertEquals(null, SendFusionTablesUtils.getTableId(inputStream)); } /** * Tests {@link SendFusionTablesUtils#getTableId(InputStream)} with an empty * inputstream. */ public void testGetTableId_empty() { String string = ""; InputStream inputStream = new ByteArrayInputStream(string.getBytes()); assertEquals(null, SendFusionTablesUtils.getTableId(inputStream)); } /** * Tests {@link SendFusionTablesUtils#getTableId(InputStream)} with an one * line inputstream. */ public void testGetTableId_one_line() { String string = "tableid"; InputStream inputStream = new ByteArrayInputStream(string.getBytes()); assertEquals(null, SendFusionTablesUtils.getTableId(inputStream)); } /** * Tests {@link SendFusionTablesUtils#getTableId(InputStream)} with an * inputstream not containing "tableid". */ public void testGetTableId_no_table_id() { String string = "error\n123"; InputStream inputStream = new ByteArrayInputStream(string.getBytes()); assertEquals(null, SendFusionTablesUtils.getTableId(inputStream)); } /** * Tests {@link SendFusionTablesUtils#getTableId(InputStream)} with a valid * inputstream. */ public void testGetTableId() { String string = "tableid\n123"; InputStream inputStream = null; inputStream = new ByteArrayInputStream(string.getBytes()); assertEquals("123", SendFusionTablesUtils.getTableId(inputStream)); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.io.fusiontables; import com.google.android.apps.mytracks.io.docs.SendDocsActivity; import com.google.android.apps.mytracks.io.sendtogoogle.SendRequest; import com.google.android.apps.mytracks.io.sendtogoogle.UploadResultActivity; import android.test.AndroidTestCase; /** * Tests the {@link SendFusionTablesActivity}. * * @author Youtao Liu */ public class SendFusionTablesActivityTest extends AndroidTestCase { private SendFusionTablesActivity sendFusionTablesActivity; private SendRequest sendRequest; @Override protected void setUp() throws Exception { super.setUp(); sendRequest = new SendRequest(1L, true, false, true); sendFusionTablesActivity = new SendFusionTablesActivity(); } /** * Tests the method * {@link SendFusionTablesActivity#getNextClass(SendRequest, boolean)}. Sets * the flags of "sendDocs" and "cancel" to false and false. */ public void testGetNextClass_notCancelNotSendDocs() { sendRequest.setSendDocs(false); Class<?> next = sendFusionTablesActivity.getNextClass(sendRequest, false); assertEquals(UploadResultActivity.class, next); } /** * Tests the method * {@link SendFusionTablesActivity#getNextClass(SendRequest, boolean)}. Sets * the flags of "sendDocs" and "cancel" to true and false. */ public void testGetNextClass_notCancelSendDocs() { sendRequest.setSendDocs(true); Class<?> next = sendFusionTablesActivity.getNextClass(sendRequest, false); assertEquals(SendDocsActivity.class, next); } /** * Tests the method * {@link SendFusionTablesActivity#getNextClass(SendRequest,boolean)}. Sets * the flags of "sendDocs" and "cancel" to true and true. */ public void testGetNextClass_cancelSendDocs() { sendRequest.setSendDocs(true); Class<?> next = sendFusionTablesActivity.getNextClass(sendRequest, true); assertEquals(UploadResultActivity.class, next); } /** * Tests the method * {@link SendFusionTablesActivity#getNextClass(SendRequest,boolean)}. Sets * the flags of "sendDocs" and "cancel" to false and true. */ public void testGetNextClass_cancelNotSendDocs() { sendRequest.setSendDocs(false); Class<?> next = sendFusionTablesActivity.getNextClass(sendRequest, true); assertEquals(UploadResultActivity.class, next); } }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.io.backup; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import java.util.HashMap; import java.util.Map; import java.util.Set; import junit.framework.TestCase; /** * Tests for {@link PreferenceBackupHelper}. * * @author Rodrigo Damazio */ public class PreferenceBackupHelperTest extends TestCase { private Map<String, ?> preferenceValues; private SharedPreferences preferences; private PreferenceBackupHelper preferenceBackupHelper; /** * Mock shared preferences editor which does not persist state. */ private class MockPreferenceEditor implements SharedPreferences.Editor { private Map<String, Object> newPreferences = new HashMap<String, Object>(preferenceValues); @Override public Editor clear() { newPreferences.clear(); return this; } @Override public boolean commit() { apply(); return true; } @Override public void apply() { preferenceValues = newPreferences; } @Override public Editor putBoolean(String key, boolean value) { return put(key, value); } @Override public Editor putFloat(String key, float value) { return put(key, value); } @Override public Editor putInt(String key, int value) { return put(key, value); } @Override public Editor putLong(String key, long value) { return put(key, value); } @Override public Editor putString(String key, String value) { return put(key, value); } public Editor putStringSet(String key, Set<String> value) { return put(key, value); } private <T> Editor put(String key, T value) { newPreferences.put(key, value); return this; } @Override public Editor remove(String key) { newPreferences.remove(key); return this; } } /** * Mock shared preferences which does not persist state. */ private class MockPreferences implements SharedPreferences { @Override public boolean contains(String key) { return preferenceValues.containsKey(key); } @Override public Editor edit() { return new MockPreferenceEditor(); } @Override public Map<String, ?> getAll() { return preferenceValues; } @Override public boolean getBoolean(String key, boolean defValue) { return get(key, defValue); } @Override public float getFloat(String key, float defValue) { return get(key, defValue); } @Override public int getInt(String key, int defValue) { return get(key, defValue); } @Override public long getLong(String key, long defValue) { return get(key, defValue); } @Override public String getString(String key, String defValue) { return get(key, defValue); } public Set<String> getStringSet(String key, Set<String> defValue) { return get(key, defValue); } @Override public void registerOnSharedPreferenceChangeListener( OnSharedPreferenceChangeListener listener) { throw new UnsupportedOperationException(); } @Override public void unregisterOnSharedPreferenceChangeListener( OnSharedPreferenceChangeListener listener) { throw new UnsupportedOperationException(); } @SuppressWarnings("unchecked") private <T> T get(String key, T defValue) { Object value = preferenceValues.get(key); if (value == null) return defValue; return (T) value; } } @Override protected void setUp() throws Exception { super.setUp(); preferenceValues = new HashMap<String, Object>(); preferences = new MockPreferences(); preferenceBackupHelper = new PreferenceBackupHelper(); } public void testExportImportPreferences() throws Exception { // Populate with some initial values Editor editor = preferences.edit(); editor.clear(); editor.putBoolean("bool1", true); editor.putBoolean("bool2", false); editor.putFloat("flt1", 3.14f); editor.putInt("int1", 42); editor.putLong("long1", 123456789L); editor.putString("str1", "lolcat"); editor.apply(); // Export it byte[] exported = preferenceBackupHelper.exportPreferences(preferences); // Mess with the previous values editor = preferences.edit(); editor.clear(); editor.putString("str2", "Shouldn't be there after restore"); editor.putBoolean("bool2", true); editor.apply(); // Import it back preferenceBackupHelper.importPreferences(exported, preferences); assertFalse(preferences.contains("str2")); assertTrue(preferences.getBoolean("bool1", false)); assertFalse(preferences.getBoolean("bool2", true)); assertEquals(3.14f, preferences.getFloat("flt1", 0.0f)); assertEquals(42, preferences.getInt("int1", 0)); assertEquals(123456789L, preferences.getLong("long1", 0)); assertEquals("lolcat", preferences.getString("str1", "")); } }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.io.backup; import com.google.android.apps.mytracks.content.ContentTypeIds; import android.content.ContentValues; import android.net.Uri; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.ArrayList; import junit.framework.TestCase; /** * Tests for {@link DatabaseImporter}. * * @author Rodrigo Damazio */ public class DatabaseImporterTest extends TestCase { private static final Uri DESTINATION_URI = Uri.parse("http://www.google.com/"); private static final int TEST_BULK_SIZE = 10; private ArrayList<ContentValues> insertedValues; private class TestableDatabaseImporter extends DatabaseImporter { public TestableDatabaseImporter(boolean readNullFields) { super(DESTINATION_URI, null, readNullFields, TEST_BULK_SIZE); } @Override protected void doBulkInsert(ContentValues[] values) { insertedValues.ensureCapacity(insertedValues.size() + values.length); // We need to make a copy of the values since the objects are re-used for (ContentValues contentValues : values) { insertedValues.add(new ContentValues(contentValues)); } } } @Override protected void setUp() throws Exception { super.setUp(); insertedValues = new ArrayList<ContentValues>(); } public void testImportAllRows() throws Exception { testImportAllRows(false); } public void testImportAllRows_readNullFields() throws Exception { testImportAllRows(true); } private void testImportAllRows(boolean readNullFields) throws Exception { // Create a fake data stream to be read ByteArrayOutputStream outputStream = new ByteArrayOutputStream(1024); DataOutputStream writer = new DataOutputStream(outputStream); writeFullHeader(writer); // Add the number of rows writer.writeInt(2); // Add a row with all fields present writer.writeLong(0x7F); writer.writeInt(42); writer.writeBoolean(true); writer.writeUTF("lolcat"); writer.writeFloat(3.1415f); writer.writeDouble(2.72); writer.writeLong(123456789L); writer.writeInt(4); writer.writeBytes("blob"); // Add a row with some missing fields writer.writeLong(0x15); writer.writeInt(42); if (readNullFields) writer.writeBoolean(false); writer.writeUTF("lolcat"); if (readNullFields) writer.writeFloat(0.0f); writer.writeDouble(2.72); if (readNullFields) writer.writeLong(0L); if (readNullFields) writer.writeInt(0); // empty blob writer.flush(); // Do the importing DatabaseImporter importer = new TestableDatabaseImporter(readNullFields); byte[] dataBytes = outputStream.toByteArray(); importer.importAllRows(new DataInputStream(new ByteArrayInputStream(dataBytes))); assertEquals(2, insertedValues.size()); // Verify the first row ContentValues value = insertedValues.get(0); assertEquals(value.toString(), 7, value.size()); assertValue(42, "col1", value); assertValue(true, "col2", value); assertValue("lolcat", "col3", value); assertValue(3.1415f, "col4", value); assertValue(2.72, "col5", value); assertValue(123456789L, "col6", value); assertBlobValue("blob", "col7", value); // Verify the second row value = insertedValues.get(1); assertEquals(value.toString(), 3, value.size()); assertValue(42, "col1", value); assertValue("lolcat", "col3", value); assertValue(2.72, "col5", value); } public void testImportAllRows_noRows() throws Exception { // Create a fake data stream to be read ByteArrayOutputStream outputStream = new ByteArrayOutputStream(1024); DataOutputStream writer = new DataOutputStream(outputStream); writeFullHeader(writer); // Add the number of rows writer.writeInt(0); writer.flush(); // Do the importing DatabaseImporter importer = new TestableDatabaseImporter(false); byte[] dataBytes = outputStream.toByteArray(); importer.importAllRows(new DataInputStream(new ByteArrayInputStream(dataBytes))); assertTrue(insertedValues.isEmpty()); } public void testImportAllRows_emptyRows() throws Exception { testImportAllRowsWithEmptyRows(false); } public void testImportAllRows_emptyRowsWithNulls() throws Exception { testImportAllRowsWithEmptyRows(true); } private void testImportAllRowsWithEmptyRows(boolean readNullFields) throws Exception { // Create a fake data stream to be read ByteArrayOutputStream outputStream = new ByteArrayOutputStream(1024); DataOutputStream writer = new DataOutputStream(outputStream); writeFullHeader(writer); // Add the number of rows writer.writeInt(3); // Add 2 rows with no fields for (int i = 0; i < 2; i++) { writer.writeLong(0); if (readNullFields) { writer.writeInt(0); writer.writeBoolean(false); writer.writeUTF(""); writer.writeFloat(0.0f); writer.writeDouble(0.0); writer.writeLong(0L); writer.writeInt(0); // empty blob } } // Add a row with some missing fields writer.writeLong(0x15); writer.writeInt(42); if (readNullFields) writer.writeBoolean(false); writer.writeUTF("lolcat"); if (readNullFields) writer.writeFloat(0.0f); writer.writeDouble(2.72); if (readNullFields) writer.writeLong(0L); if (readNullFields) writer.writeInt(0); // empty blob writer.flush(); // Do the importing DatabaseImporter importer = new TestableDatabaseImporter(readNullFields); byte[] dataBytes = outputStream.toByteArray(); importer.importAllRows(new DataInputStream(new ByteArrayInputStream(dataBytes))); assertEquals(insertedValues.toString(), 3, insertedValues.size()); ContentValues value = insertedValues.get(0); assertEquals(value.toString(), 0, value.size()); value = insertedValues.get(1); assertEquals(value.toString(), 0, value.size()); // Verify the third row (only one with values) value = insertedValues.get(2); assertEquals(value.toString(), 3, value.size()); assertFalse(value.containsKey("col2")); assertFalse(value.containsKey("col4")); assertFalse(value.containsKey("col6")); assertValue(42, "col1", value); assertValue("lolcat", "col3", value); assertValue(2.72, "col5", value); } public void testImportAllRows_bulks() throws Exception { // Create a fake data stream to be read ByteArrayOutputStream outputStream = new ByteArrayOutputStream(1024); DataOutputStream writer = new DataOutputStream(outputStream); // Add the header writer.writeInt(2); writer.writeUTF("col1"); writer.writeByte(ContentTypeIds.INT_TYPE_ID); writer.writeUTF("col2"); writer.writeByte(ContentTypeIds.STRING_TYPE_ID); // Add lots of rows (so the insertions are split in multiple bulks) int numRows = TEST_BULK_SIZE * 5 / 2; writer.writeInt(numRows); for (int i = 0; i < numRows; i++) { writer.writeLong(3); writer.writeInt(i); writer.writeUTF(Integer.toString(i * 2)); } writer.flush(); // Do the importing DatabaseImporter importer = new TestableDatabaseImporter(false); byte[] dataBytes = outputStream.toByteArray(); importer.importAllRows(new DataInputStream(new ByteArrayInputStream(dataBytes))); // Verify the rows assertEquals(numRows, insertedValues.size()); for (int i = 0; i < numRows; i++) { ContentValues value = insertedValues.get(i); assertEquals(value.toString(), 2, value.size()); assertValue(i, "col1", value); assertValue(Integer.toString(i * 2), "col2", value); } } private void writeFullHeader(DataOutputStream writer) throws IOException { // Add the header writer.writeInt(7); writer.writeUTF("col1"); writer.writeByte(ContentTypeIds.INT_TYPE_ID); writer.writeUTF("col2"); writer.writeByte(ContentTypeIds.BOOLEAN_TYPE_ID); writer.writeUTF("col3"); writer.writeByte(ContentTypeIds.STRING_TYPE_ID); writer.writeUTF("col4"); writer.writeByte(ContentTypeIds.FLOAT_TYPE_ID); writer.writeUTF("col5"); writer.writeByte(ContentTypeIds.DOUBLE_TYPE_ID); writer.writeUTF("col6"); writer.writeByte(ContentTypeIds.LONG_TYPE_ID); writer.writeUTF("col7"); writer.writeByte(ContentTypeIds.BLOB_TYPE_ID); } private <T> void assertValue(T expectedValue, String name, ContentValues values) { @SuppressWarnings("unchecked") T value = (T) values.get(name); assertNotNull(value); assertEquals(expectedValue, value); } private void assertBlobValue(String expectedValue, String name, ContentValues values ){ byte[] blob = values.getAsByteArray(name); assertEquals(expectedValue, new String(blob)); } }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.io.backup; import com.google.android.apps.mytracks.content.ContentTypeIds; import android.database.MatrixCursor; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import junit.framework.TestCase; /** * Tests for {@link DatabaseDumper}. * * @author Rodrigo Damazio */ public class DatabaseDumperTest extends TestCase { /** * This class is the same as {@link MatrixCursor}, except this class * implements {@link #getBlob} ({@link MatrixCursor} leaves it * unimplemented). */ private class BlobAwareMatrixCursor extends MatrixCursor { public BlobAwareMatrixCursor(String[] columnNames) { super(columnNames); } @Override public byte[] getBlob(int columnIndex) { return getString(columnIndex).getBytes(); } } private static final String[] COLUMN_NAMES = { "intCol", "longCol", "floatCol", "doubleCol", "stringCol", "boolCol", "blobCol" }; private static final byte[] COLUMN_TYPES = { ContentTypeIds.INT_TYPE_ID, ContentTypeIds.LONG_TYPE_ID, ContentTypeIds.FLOAT_TYPE_ID, ContentTypeIds.DOUBLE_TYPE_ID, ContentTypeIds.STRING_TYPE_ID, ContentTypeIds.BOOLEAN_TYPE_ID, ContentTypeIds.BLOB_TYPE_ID }; private static final String[][] FAKE_DATA = { { "42", "123456789", "3.1415", "2.72", "lolcat", "1", "blob" }, { null, "123456789", "3.1415", "2.72", "lolcat", "1", "blob" }, { "42", null, "3.1415", "2.72", "lolcat", "1", "blob" }, { "42", "123456789", null, "2.72", "lolcat", "1", "blob" }, { "42", "123456789", "3.1415", null, "lolcat", "1", "blob" }, { "42", "123456789", "3.1415", "2.72", null, "1", "blob" }, { "42", "123456789", "3.1415", "2.72", "lolcat", null, "blob" }, { "42", "123456789", "3.1415", "2.72", "lolcat", "1", null }, }; private static final long[] EXPECTED_FIELD_SETS = { 0x7F, 0x7E, 0x7D, 0x7B, 0x77, 0x6F, 0x5F, 0x3F }; private BlobAwareMatrixCursor cursor; @Override protected void setUp() throws Exception { super.setUp(); // Add fake data to the cursor cursor = new BlobAwareMatrixCursor(COLUMN_NAMES); for (String[] row : FAKE_DATA) { cursor.addRow(row); } } public void testWriteAllRows_noNulls() throws Exception { testWriteAllRows(false); } public void testWriteAllRows_withNulls() throws Exception { testWriteAllRows(true); } private void testWriteAllRows(boolean hasNullFields) throws Exception { // Dump it DatabaseDumper dumper = new DatabaseDumper(COLUMN_NAMES, COLUMN_TYPES, hasNullFields); ByteArrayOutputStream outStream = new ByteArrayOutputStream(1024); DataOutputStream writer = new DataOutputStream(outStream ); dumper.writeAllRows(cursor, writer); // Read the results byte[] result = outStream.toByteArray(); ByteArrayInputStream inputStream = new ByteArrayInputStream(result); DataInputStream reader = new DataInputStream(inputStream); // Verify the header assertHeader(reader); // Verify the number of rows assertEquals(FAKE_DATA.length, reader.readInt()); // Row 0 -- everything populated assertEquals(EXPECTED_FIELD_SETS[0], reader.readLong()); assertEquals(42, reader.readInt()); assertEquals(123456789L, reader.readLong()); assertEquals(3.1415f, reader.readFloat()); assertEquals(2.72, reader.readDouble()); assertEquals("lolcat", reader.readUTF()); assertTrue(reader.readBoolean()); assertEquals(4, reader.readInt()); assertEquals("blob", readBlob(reader, 4)); // Row 1 -- no int assertEquals(EXPECTED_FIELD_SETS[1], reader.readLong()); if (hasNullFields) reader.readInt(); assertEquals(123456789L, reader.readLong()); assertEquals(3.1415f, reader.readFloat()); assertEquals(2.72, reader.readDouble()); assertEquals("lolcat", reader.readUTF()); assertTrue(reader.readBoolean()); assertEquals(4, reader.readInt()); assertEquals("blob", readBlob(reader, 4)); // Row 2 -- no long assertEquals(EXPECTED_FIELD_SETS[2], reader.readLong()); assertEquals(42, reader.readInt()); if (hasNullFields) reader.readLong(); assertEquals(3.1415f, reader.readFloat()); assertEquals(2.72, reader.readDouble()); assertEquals("lolcat", reader.readUTF()); assertTrue(reader.readBoolean()); assertEquals(4, reader.readInt()); assertEquals("blob", readBlob(reader, 4)); // Row 3 -- no float assertEquals(EXPECTED_FIELD_SETS[3], reader.readLong()); assertEquals(42, reader.readInt()); assertEquals(123456789L, reader.readLong()); if (hasNullFields) reader.readFloat(); assertEquals(2.72, reader.readDouble()); assertEquals("lolcat", reader.readUTF()); assertTrue(reader.readBoolean()); assertEquals(4, reader.readInt()); assertEquals("blob", readBlob(reader, 4)); // Row 4 -- no double assertEquals(EXPECTED_FIELD_SETS[4], reader.readLong()); assertEquals(42, reader.readInt()); assertEquals(123456789L, reader.readLong()); assertEquals(3.1415f, reader.readFloat()); if (hasNullFields) reader.readDouble(); assertEquals("lolcat", reader.readUTF()); assertTrue(reader.readBoolean()); assertEquals(4, reader.readInt()); assertEquals("blob", readBlob(reader, 4)); // Row 5 -- no string assertEquals(EXPECTED_FIELD_SETS[5], reader.readLong()); assertEquals(42, reader.readInt()); assertEquals(123456789L, reader.readLong()); assertEquals(3.1415f, reader.readFloat()); assertEquals(2.72, reader.readDouble()); if (hasNullFields) reader.readUTF(); assertTrue(reader.readBoolean()); assertEquals(4, reader.readInt()); assertEquals("blob", readBlob(reader, 4)); // Row 6 -- no boolean assertEquals(EXPECTED_FIELD_SETS[6], reader.readLong()); assertEquals(42, reader.readInt()); assertEquals(123456789L, reader.readLong()); assertEquals(3.1415f, reader.readFloat()); assertEquals(2.72, reader.readDouble()); assertEquals("lolcat", reader.readUTF()); if (hasNullFields) reader.readBoolean(); assertEquals(4, reader.readInt()); assertEquals("blob", readBlob(reader, 4)); // Row 7 -- no blob assertEquals(EXPECTED_FIELD_SETS[7], reader.readLong()); assertEquals(42, reader.readInt()); assertEquals(123456789L, reader.readLong()); assertEquals(3.1415f, reader.readFloat()); assertEquals(2.72, reader.readDouble()); assertEquals("lolcat", reader.readUTF()); assertTrue(reader.readBoolean()); if (hasNullFields) { int length = reader.readInt(); readBlob(reader, length); } } public void testFewerRows() throws Exception { // Dump only the first two rows DatabaseDumper dumper = new DatabaseDumper(COLUMN_NAMES, COLUMN_TYPES, false); ByteArrayOutputStream outStream = new ByteArrayOutputStream(1024); DataOutputStream writer = new DataOutputStream(outStream); dumper.writeHeaders(cursor, 2, writer); cursor.moveToFirst(); dumper.writeOneRow(cursor, writer); cursor.moveToNext(); dumper.writeOneRow(cursor, writer); // Read the results byte[] result = outStream.toByteArray(); ByteArrayInputStream inputStream = new ByteArrayInputStream(result); DataInputStream reader = new DataInputStream(inputStream); // Verify the header assertHeader(reader); // Verify the number of rows assertEquals(2, reader.readInt()); // Row 0 assertEquals(EXPECTED_FIELD_SETS[0], reader.readLong()); assertEquals(42, reader.readInt()); assertEquals(123456789L, reader.readLong()); assertEquals(3.1415f, reader.readFloat()); assertEquals(2.72, reader.readDouble()); assertEquals("lolcat", reader.readUTF()); assertTrue(reader.readBoolean()); assertEquals(4, reader.readInt()); assertEquals("blob", readBlob(reader, 4)); // Row 1 assertEquals(EXPECTED_FIELD_SETS[1], reader.readLong()); // Null field not read assertEquals(123456789L, reader.readLong()); assertEquals(3.1415f, reader.readFloat()); assertEquals(2.72, reader.readDouble()); assertEquals("lolcat", reader.readUTF()); assertTrue(reader.readBoolean()); assertEquals(4, reader.readInt()); assertEquals("blob", readBlob(reader, 4)); } private void assertHeader(DataInputStream reader) throws IOException { assertEquals(COLUMN_NAMES.length, reader.readInt()); for (int i = 0; i < COLUMN_NAMES.length; i++) { assertEquals(COLUMN_NAMES[i], reader.readUTF()); assertEquals(COLUMN_TYPES[i], reader.readByte()); } } private String readBlob(InputStream reader, int length) throws Exception { if (length == 0) { return ""; } byte[] blob = new byte[length]; assertEquals(length, reader.read(blob)); return new String(blob); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.io.docs; import com.google.android.apps.mytracks.content.Track; import com.google.android.apps.mytracks.io.gdata.docs.SpreadsheetsClient.WorksheetEntry; import com.google.android.apps.mytracks.stats.TripStatistics; import com.google.android.apps.mytracks.util.StringUtils; import com.google.wireless.gdata.data.Entry; import android.test.AndroidTestCase; /** * Tests {@link SendDocsUtils}. * * @author Jimmy Shih */ public class SendDocsUtilsTest extends AndroidTestCase { private static final long TIME = 1288721514000L; /** * Tests {@link SendDocsUtils#getEntryId(Entry)} with a valid id. */ public void testGetEntryId_valid() { Entry entry = new Entry(); entry.setId("https://docs.google.com/feeds/documents/private/full/spreadsheet%3A123"); assertEquals("123", SendDocsUtils.getEntryId(entry)); } /** * Tests {@link SendDocsUtils#getEntryId(Entry)} with an invalid id. */ public void testGetEntryId_invalid() { Entry entry = new Entry(); entry.setId("123"); assertEquals(null, SendDocsUtils.getEntryId(entry)); } /** * Tests {@link SendDocsUtils#getNewSpreadsheetId(String)} with a valid id. */ public void testGetNewSpreadsheetId_valid_id() { assertEquals("123", SendDocsUtils.getNewSpreadsheetId( "<id>https://docs.google.com/feeds/documents/private/full/spreadsheet%3A123</id>")); } /** * Tests {@link SendDocsUtils#getNewSpreadsheetId(String)} without an open * tag, <id>. */ public void testGetNewSpreadsheetId_no_open_tag() { assertEquals(null, SendDocsUtils.getNewSpreadsheetId( "https://docs.google.com/feeds/documents/private/full/spreadsheet%3A123</id>")); } /** * Tests {@link SendDocsUtils#getNewSpreadsheetId(String)} without an end tag, * </id>. */ public void testGetNewSpreadsheetId_no_end_tag() { assertEquals(null, SendDocsUtils.getNewSpreadsheetId( "<id>https://docs.google.com/feeds/documents/private/full/spreadsheet%3A123")); } /** * Tests {@link SendDocsUtils#getNewSpreadsheetId(String)} without the url * prefix, * https://docs.google.com/feeds/documents/private/full/spreadsheet%3A. */ public void testGetNewSpreadsheetId_no_prefix() { assertEquals(null, SendDocsUtils.getNewSpreadsheetId("<id>123</id>")); } /** * Tests {@link SendDocsUtils#getWorksheetEntryId(WorksheetEntry)} with a * valid entry. */ public void testGetWorksheetEntryId_valid() { WorksheetEntry entry = new WorksheetEntry(); entry.setId("/123"); assertEquals("123", SendDocsUtils.getWorksheetEntryId(entry)); } /** * Tests {@link SendDocsUtils#getWorksheetEntryId(WorksheetEntry)} with a * invalid entry. */ public void testGetWorksheetEntryId_invalid() { WorksheetEntry entry = new WorksheetEntry(); entry.setId("123"); assertEquals(null, SendDocsUtils.getWorksheetEntryId(entry)); } /** * Tests {@link SendDocsUtils#getRowContent(Track, boolean, * android.content.Context)} with metric units. */ public void testGetRowContent_metric() throws Exception { Track track = getTrack(); String expectedData = "<entry xmlns='http://www.w3.org/2005/Atom' " + "xmlns:gsx='http://schemas.google.com/spreadsheets/2006/extended'>" + "<gsx:name><![CDATA[trackName]]></gsx:name>" + "<gsx:description><![CDATA[trackDescription]]></gsx:description>" + "<gsx:date><![CDATA[" + StringUtils.formatDateTime(getContext(), TIME) + "]]></gsx:date>" + "<gsx:totaltime><![CDATA[0:00:05]]></gsx:totaltime>" + "<gsx:movingtime><![CDATA[0:00:04]]></gsx:movingtime>" + "<gsx:distance><![CDATA[20.00]]></gsx:distance>" + "<gsx:distanceunit><![CDATA[km]]></gsx:distanceunit>" + "<gsx:averagespeed><![CDATA[14,400.00]]></gsx:averagespeed>" + "<gsx:averagemovingspeed><![CDATA[18,000.00]]>" + "</gsx:averagemovingspeed>" + "<gsx:maxspeed><![CDATA[5,400.00]]></gsx:maxspeed>" + "<gsx:speedunit><![CDATA[km/h]]></gsx:speedunit>" + "<gsx:elevationgain><![CDATA[6,000]]></gsx:elevationgain>" + "<gsx:minelevation><![CDATA[-500]]></gsx:minelevation>" + "<gsx:maxelevation><![CDATA[550]]></gsx:maxelevation>" + "<gsx:elevationunit><![CDATA[m]]></gsx:elevationunit>" + "<gsx:map>" + "<![CDATA[https://maps.google.com/maps/ms?msa=0&msid=trackMapId]]>" + "</gsx:map>" + "</entry>"; assertEquals(expectedData, SendDocsUtils.getRowContent(track, true, getContext())); } /** * Tests {@link SendDocsUtils#getRowContent(Track, boolean, * android.content.Context)} with imperial units. */ public void testGetRowContent_imperial() throws Exception { Track track = getTrack(); String expectedData = "<entry xmlns='http://www.w3.org/2005/Atom' " + "xmlns:gsx='http://schemas.google.com/spreadsheets/2006/extended'>" + "<gsx:name><![CDATA[trackName]]></gsx:name>" + "<gsx:description><![CDATA[trackDescription]]></gsx:description>" + "<gsx:date><![CDATA[" + StringUtils.formatDateTime(getContext(), TIME) + "]]></gsx:date>" + "<gsx:totaltime><![CDATA[0:00:05]]></gsx:totaltime>" + "<gsx:movingtime><![CDATA[0:00:04]]></gsx:movingtime>" + "<gsx:distance><![CDATA[12.43]]></gsx:distance>" + "<gsx:distanceunit><![CDATA[mi]]></gsx:distanceunit>" + "<gsx:averagespeed><![CDATA[8,947.75]]></gsx:averagespeed>" + "<gsx:averagemovingspeed><![CDATA[11,184.68]]>" + "</gsx:averagemovingspeed>" + "<gsx:maxspeed><![CDATA[3,355.40]]></gsx:maxspeed>" + "<gsx:speedunit><![CDATA[mi/h]]></gsx:speedunit>" + "<gsx:elevationgain><![CDATA[19,685]]></gsx:elevationgain>" + "<gsx:minelevation><![CDATA[-1,640]]></gsx:minelevation>" + "<gsx:maxelevation><![CDATA[1,804]]></gsx:maxelevation>" + "<gsx:elevationunit><![CDATA[ft]]></gsx:elevationunit>" + "<gsx:map>" + "<![CDATA[https://maps.google.com/maps/ms?msa=0&msid=trackMapId]]>" + "</gsx:map>" + "</entry>"; assertEquals(expectedData, SendDocsUtils.getRowContent(track, false, getContext())); } /** * Gets a track for testing {@link SendDocsUtils#getRowContent(Track, boolean, * android.content.Context)}. */ private Track getTrack() { TripStatistics stats = new TripStatistics(); stats.setStartTime(TIME); stats.setTotalTime(5000); stats.setMovingTime(4000); stats.setTotalDistance(20000); stats.setMaxSpeed(1500); stats.setTotalElevationGain(6000); stats.setMinElevation(-500); stats.setMaxElevation(550); Track track = new Track(); track.setName("trackName"); track.setDescription("trackDescription"); track.setMapId("trackMapId"); track.setStatistics(stats); return track; } /** * Tests {@link SendDocsUtils#appendTag(StringBuilder, String, String)} with * repeated calls. */ public void testAppendTag() { StringBuilder stringBuilder = new StringBuilder(); SendDocsUtils.appendTag(stringBuilder, "name1", "value1"); assertEquals("<gsx:name1><![CDATA[value1]]></gsx:name1>", stringBuilder.toString()); SendDocsUtils.appendTag(stringBuilder, "name2", "value2"); assertEquals( "<gsx:name1><![CDATA[value1]]></gsx:name1><gsx:name2><![CDATA[value2]]></gsx:name2>", stringBuilder.toString()); } /** * Tests {@link SendDocsUtils#getDistance(double, boolean)} with metric units. */ public void testGetDistance_metric() { assertEquals("1.22", SendDocsUtils.getDistance(1222.3, true)); } /** * Tests {@link SendDocsUtils#getDistance(double, boolean)} with imperial * units. */ public void testGetDistance_imperial() { assertEquals("0.76", SendDocsUtils.getDistance(1222.3, false)); } /** * Tests {@link SendDocsUtils#getSpeed(double, boolean)} with metric units. */ public void testGetSpeed_metric() { assertEquals("15.55", SendDocsUtils.getSpeed(4.32, true)); } /** * Tests {@link SendDocsUtils#getSpeed(double, boolean)} with imperial units. */ public void testGetSpeed_imperial() { assertEquals("9.66", SendDocsUtils.getSpeed(4.32, false)); } /** * Tests {@link SendDocsUtils#getElevation(double, boolean)} with metric * units. */ public void testGetElevation_metric() { assertEquals("3", SendDocsUtils.getElevation(3.456, true)); } /** * Tests {@link SendDocsUtils#getElevation(double, boolean)} with imperial * units. */ public void testGetElevation_imperial() { assertEquals("11", SendDocsUtils.getElevation(3.456, false)); } }
Java