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
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace DTO { public class HOADONDTO { private int _mahd; public int MaHD { get { return _mahd; } set { _mahd = value; } } private DateTime _ngaylap; public DateTime NgayLap { get { return _ngaylap; } set { _ngaylap = value; } } private int _tongtien; public int TongTien { get { return _tongtien; } set { _tongtien = value; } } private int _manvlap; public int MaNVLap { get { return _manvlap; } set { _manvlap = value; } } private int _makh; public int MaKH { get { return _makh; } set { _makh = value; } } } }
10650931065130doan
trunk/1065093_1065130_1065120_DoAn/DTO/HOADONDTO.cs
C#
asf20
950
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace DTO { class NHANVIENDTO { private int _manv; public int MaNV { get { return _manv; } set { _manv = value; } } private string _tennv; public string TenNV { get { return _tennv; } set { _tennv = value; } } private int _loainv; public int LoaiNV { get { return _loainv; } set { _loainv = value; } } private string _diachi; public string DiaChi { get { return _diachi; } set { _diachi = value; } } private int _luong; public int Luong { get { return _luong; } set { _luong = value; } } private string _sdtnv; public string SDTNV { get { return _sdtnv; } set { _sdtnv = value; } } } }
10650931065130doan
trunk/1065093_1065130_1065120_DoAn/DTO/NHANVIENDTO.cs
C#
asf20
1,087
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace DTO { public class QUAYDTO { private int _maquay; public int MaQuay { get { return _maquay; } set { _maquay = value; } } private string _tenquay; public string TenQuay { get { return _tenquay; } set { _tenquay = value; } } } }
10650931065130doan
trunk/1065093_1065130_1065120_DoAn/DTO/QUAYDTO.cs
C#
asf20
478
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace DTO { public class LOAISPDTO { private int _maloaisp; public int MaLoaiSP { get { return _maloaisp; } set { _maloaisp = value; } } private string _tenloaisp; public string TenLoaiSP { get { return _tenloaisp; } set { _tenloaisp = value; } } } }
10650931065130doan
trunk/1065093_1065130_1065120_DoAn/DTO/LOAISPDTO.cs
C#
asf20
496
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("DTO")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("DTO")] [assembly: AssemblyCopyright("Copyright © 2012")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("e0022e9d-4f4d-4293-9c72-8cc5d3f31073")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
10650931065130doan
trunk/1065093_1065130_1065120_DoAn/DTO/Properties/AssemblyInfo.cs
C#
asf20
1,418
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace DTO { public class THAMSODTO { private int _mats; public int MaTS { get { return _mats; } set { _mats = value; } } private string _tents; public string TenTS { get { return _tents; } set { _tents = value; } } private int _giatri; public int GiaTri { get { return _giatri; } set { _giatri = value; } } private string _kieu; public string Kieu { get { return _kieu; } set { _kieu = value; } } private DateTime _thoigianbd; public DateTime ThoiGianBD { get { return _thoigianbd; } set { _thoigianbd = value; } } private DateTime _thoigiankt; public DateTime ThoiGianKT { get { return _thoigiankt; } set { _thoigiankt = value; } } public THAMSODTO(int mats,string tents,int giatri,string kieu,DateTime ngaybd,DateTime ngaykt) { _mats = mats; _tents = tents; _giatri = giatri; _kieu = kieu; _thoigianbd = ngaybd; _thoigiankt = ngaykt; } } }
10650931065130doan
trunk/1065093_1065130_1065120_DoAn/DTO/THAMSODTO.cs
C#
asf20
1,450
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace DTO { public class TAIKHOANDTO { private int _id; public int Id { get { return _id; } set { _id = value; } } private string _matkhau; public string MatKhau { get { return _matkhau; } set { _matkhau = value; } } private int _loaitk; public int LoaiTK { get { return _loaitk; } set { _loaitk = value; } } public TAIKHOANDTO(int id,string matkhau,int loaitk) { _id = id; _matkhau = matkhau; _loaitk = loaitk; } } }
10650931065130doan
trunk/1065093_1065130_1065120_DoAn/DTO/TAIKHOANDTO.cs
C#
asf20
795
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace DTO { public class SANPHAMDTO { private int _masp; public int MaSP { get { return _masp; } set { _masp = value; } } private string _tensp; public string TenSP { get { return _tensp; } set { _tensp = value; } } private int _maxx; public int MaXX { get { return _maxx; } set { _maxx = value; } } private int _ghkho; public int GHKho { get { return _ghkho; } set { _ghkho = value; } } private int _ghquay; public int GHQuay { get { return _ghquay; } set { _ghquay = value; } } private int _soluonghttrongkho; public int SoLuongHTTrongKho { get { return _soluonghttrongkho; } set { _soluonghttrongkho = value; } } private int _soluonghttrongquay; public int SoLuongHTTrongQuay { get { return _soluonghttrongquay; } set { _soluonghttrongquay = value; } } private int _loaisp; public int LoaiSP { get { return _loaisp; } set { _loaisp = value; } } private int _makho; public int MaKho { get { return _makho; } set { _makho = value; } } private int _maquay; public int MaQuay { get { return _maquay; } set { _maquay = value; } } private int _gia; public int Gia { get { return _gia; } set { _gia = value; } } private string _tinhtrang; public string TinhTrang { get { return _tinhtrang; } set { _tinhtrang = value; } } private DateTime _ngaynhap; public DateTime NgayNhap { get { return _ngaynhap; } set { _ngaynhap = value; } } public SANPHAMDTO(int masp,string tensp,int maxx,int ghkho,int ghquay,int slhttrongkho,int slhttrongquay,int loaisp,int makho,int maquay,int gia,string tinhtrang,DateTime ngaynhap) { _masp = masp; _tensp = tensp; _maxx = maxx; _ghkho = ghkho; _ghquay = ghquay; _soluonghttrongkho = slhttrongkho; _soluonghttrongquay = slhttrongquay; _loaisp = loaisp; _makho = makho; _maquay = maquay; _gia = gia; _tinhtrang = tinhtrang; _ngaynhap = ngaynhap; } } }
10650931065130doan
trunk/1065093_1065130_1065120_DoAn/DTO/SANPHAMDTO.cs
C#
asf20
2,942
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace DTO { public class KHACHHANGDTO { private int _makh; public int MaKH { get { return _makh; } set { _makh = value; } } private string _tenkh; public string TenKH { get { return _tenkh; } set { _tenkh = value; } } private string _sdtkh; public string SDTKH { get { return _sdtkh; } set { _sdtkh = value; } } private int _diemtichluy; public int DiemTichKuy { get { return _diemtichluy; } set { _diemtichluy = value; } } } }
10650931065130doan
trunk/1065093_1065130_1065120_DoAn/DTO/KHACHHANGDTO.cs
C#
asf20
801
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace DTO { public class XUATXUDTOcs { private int _maxx; public int MaXX { get { return _maxx; } set { _maxx = value; } } private string _tenxx; public string TenXX { get { return _tenxx; } set { _tenxx = value; } } } }
10650931065130doan
trunk/1065093_1065130_1065120_DoAn/DTO/XUATXUDTOcs.cs
C#
asf20
466
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace DTO { public class KHODTO { private int _makho; public int MaKho { get { return _makho; } set { _makho = value; } } private string _tenkho; public string TenKho { get { return _tenkho; } set { _tenkho = value; } } } }
10650931065130doan
trunk/1065093_1065130_1065120_DoAn/DTO/KHODTO.cs
C#
asf20
469
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using BUS; namespace _1065093_1065130_1065120_DoAn { public partial class frm_MạinNVTinHoc : Form { public frm_MạinNVTinHoc() { InitializeComponent(); } private void quanLyTaiKhoanToolStripMenuItem_Click(object sender, EventArgs e) { QuanLyTaiKhoan qltk = new QuanLyTaiKhoan(); qltk.Show(); panel1.Controls.Add(qltk); } private void thoatToolStripMenuItem_Click(object sender, EventArgs e) { this.Close(); } } }
10650931065130doan
trunk/1065093_1065130_1065120_DoAn/1065093_1065130_1065120_DoAn/frm_MạinNVTinHoc.cs
C#
asf20
782
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace _1065093_1065130_1065120_DoAn { public partial class frm_QuanLyQuay : Form { public frm_QuanLyQuay() { InitializeComponent(); } } }
10650931065130doan
trunk/1065093_1065130_1065120_DoAn/1065093_1065130_1065120_DoAn/frm_QuanLyQuay.cs
C#
asf20
397
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Windows.Forms; using BUS; namespace _1065093_1065130_1065120_DoAn { public partial class DangNhap : UserControl { public DangNhap() { InitializeComponent(); } private void btndangnhap_Click(object sender, EventArgs e) { try { if (txtuser.Text == "") { MessageBox.Show("Hãy Nhập Thông Tin", "Thông Báo"); txtuser.Focus(); return; } if (txtpass.Text == "") { MessageBox.Show("Hãy Nhập Thông Tin", "Thông Báo"); txtpass.Focus(); return; } DataTable dt = new DataTable(); TAIKHOANBUS BUS = new TAIKHOANBUS(); dt = BUS.LoadDSTaiKhoan(); for (int i = 0; i < dt.Rows.Count; i++) { DataRow dr = dt.Rows[i]; if (int.Parse(txtuser.Text.Trim()) == int.Parse(dr["Id"].ToString()) && txtpass.Text.Trim() == dr["MatKhau"].ToString().Trim()) { MessageBox.Show("Đăng Nhập Thành Công", "Thông Báo"); //Close(); if (dr["LoaiTK"].ToString().Trim() == "1") { //ThanhToan X = new ThanhToan(); //Form1 main = new Form1(); //X.Dock = DockStyle.Fill; frm_nvThuNgan frm = new frm_nvThuNgan(); frm.ShowDialog(); } } else MessageBox.Show("Thông Tin Nhập Không Đúng", "Thông Báo"); } } catch (Exception) { MessageBox.Show(e.ToString(), "Thông Báo"); throw; } } } }
10650931065130doan
trunk/1065093_1065130_1065120_DoAn/1065093_1065130_1065120_DoAn/DangNhap.cs
C#
asf20
2,281
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Windows.Forms; namespace _1065093_1065130_1065120_DoAn { public partial class ThanhToan : UserControl { public ThanhToan() { InitializeComponent(); } } }
10650931065130doan
trunk/1065093_1065130_1065120_DoAn/1065093_1065130_1065120_DoAn/ThanhToan.cs
C#
asf20
394
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Windows.Forms; using BUS; namespace _1065093_1065130_1065120_DoAn { public partial class QuyDinhDiemThanThiet : UserControl { public QuyDinhDiemThanThiet() { InitializeComponent(); } public void LoadTS() { THAMSOBUS tsBUS = new THAMSOBUS(); DataTable dt = new DataTable(); dt = tsBUS.LoadThamSo(); dgvthamso.DataSource = dt; } private void dataGridView1_SelectionChanged(object sender, EventArgs e) { lbmats.Text = dgvthamso.CurrentRow.Cells[0].Value.ToString(); lbtents.Text = dgvthamso.CurrentRow.Cells[1].Value.ToString(); txtgiatri.Text = dgvthamso.CurrentRow.Cells[2].Value.ToString(); txtkieu.Text = dgvthamso.CurrentRow.Cells[3].Value.ToString(); } private void txtgiatri_KeyPress(object sender, KeyPressEventArgs e) { if (!Char.IsNumber(e.KeyChar)) { e.Handled = true; } } private void QuyDinhDiemThanThiet_Load(object sender, EventArgs e) { LoadTS(); } private void btnsua_Click(object sender, EventArgs e) { DialogResult result = MessageBox.Show("Bạn có muốn sửa?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (result == DialogResult.Yes) { try { int ma = Convert.ToInt32(lbmats.Text); int giatri = Convert.ToInt32(txtgiatri.Text); string kieu = txtkieu.Text; THAMSOBUS tsBus = new THAMSOBUS(); tsBus.SuaThamSo(ma,giatri,kieu); LoadTS(); MessageBox.Show("Thành công"); return; } catch (Exception ex) { MessageBox.Show(ex.Message); return; } } } } }
10650931065130doan
trunk/1065093_1065130_1065120_DoAn/1065093_1065130_1065120_DoAn/QuyDinhDiemThanThiet.cs
C#
asf20
2,307
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Windows.Forms; using BUS; using DTO; namespace _1065093_1065130_1065120_DoAn { public partial class QuanLySanPham : UserControl { public QuanLySanPham() { InitializeComponent(); } public void LoadSP() { SANPHAMBUS spBUS = new SANPHAMBUS(); DataTable dt = new DataTable(); dt = spBUS.LoadDsSanPham(); dgvdanhsachsp.DataSource = dt; } public void clr() { txttensp.Text = ""; txtgioihankho.Text = ""; txtgioihanquay.Text = ""; txtgia.Text = ""; txtslhttrongkho.Text = ""; txtslhttrongquay.Text = ""; lbmasp.Text = ""; } public void LoadTim() { string tukhoa = txtsearch.Text; SANPHAMBUS spBus = new SANPHAMBUS(); DataTable dt = new DataTable(); dt = spBus.LoadDsTimKiem(tukhoa); dgvdanhsachtimkiem.DataSource = dt; } private void QuanLySanPham_Load(object sender, EventArgs e) { LOAISPBUS loaispBUS = new LOAISPBUS(); DataTable dtLoaiSP = new DataTable(); dtLoaiSP = loaispBUS.LoadDsLoaiSP(); cmbloaisp.DataSource = dtLoaiSP; cmbloaisp.DisplayMember = "MaLoaiSP"; cmbloaisp.ValueMember = "MaLoaiSP"; XUATXUBUS xxBUS = new XUATXUBUS(); DataTable dtXX = new DataTable(); dtXX = xxBUS.LoadDsXuatXu(); cmbmaxx.DataSource = dtXX; cmbmaxx.DisplayMember = "MaXX"; cmbmaxx.ValueMember = "MaXX"; KHOBUS khoBUS = new KHOBUS(); DataTable dtKho = new DataTable(); dtKho = khoBUS.LoadDsKho(); cmbmakho.DataSource = dtKho; cmbmakho.DisplayMember = "MaKho"; cmbmakho.ValueMember = "MaKho"; QUAYBUS quayBUS = new QUAYBUS(); DataTable dtQuay = new DataTable(); dtQuay = quayBUS.LoadDsQuay(); cmbmaquay.DataSource = dtQuay; cmbmaquay.DisplayMember = "MaQuay"; cmbmaquay.ValueMember = "MaQuay"; cmbtinhtrang.Items.Add("CH"); cmbtinhtrang.Items.Add("HH"); cmbtinhtrang.Text = "CH"; LoadSP(); clr(); } private void btnthem_Click(object sender, EventArgs e) { try { string tensp = txttensp.Text; int maxx = Convert.ToInt32(cmbmaxx.SelectedValue.ToString()); int ghkho = Convert.ToInt32(txtgioihankho.Text); int ghquay = Convert.ToInt32(txtgioihanquay.Text); int slhttrongkho = Convert.ToInt32(txtslhttrongkho.Text); int slhttrongquay = Convert.ToInt32(txtslhttrongquay.Text); int loaisp = Convert.ToInt32(cmbloaisp.SelectedValue.ToString()); int makho = Convert.ToInt32(cmbmakho.SelectedValue.ToString()); int maquay = Convert.ToInt32(cmbmaquay.SelectedValue.ToString()); int gia = Convert.ToInt32(txtgia.Text); string tinhtrang = cmbtinhtrang.Text; DateTime ngaynhap = Convert.ToDateTime(dtpngaynhap.Text); SANPHAMBUS spBus = new SANPHAMBUS(); SANPHAMDTO spDto = new SANPHAMDTO(-1,tensp,maxx,ghkho,ghquay,slhttrongkho,slhttrongquay,loaisp,makho,maquay,gia,tinhtrang,ngaynhap); spBus.ThemSP(spDto); LoadSP(); clr(); MessageBox.Show("Thành công"); return; } catch (Exception ex) { MessageBox.Show(ex.Message); return; } } private void btnxoa_Click(object sender, EventArgs e) { DialogResult result = MessageBox.Show("Bạn có muốn xoá?","", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (result == DialogResult.Yes) { try { int ma = Convert.ToInt32(dgvdanhsachsp.CurrentRow.Cells[0].Value); SANPHAMBUS spBus = new SANPHAMBUS(); spBus.XoaSP(ma); LoadSP(); clr(); MessageBox.Show("Thành công"); return; } catch (Exception ex) { MessageBox.Show(ex.Message); return; } } } private void btnsua_Click(object sender, EventArgs e) { DialogResult result = MessageBox.Show("Bạn có muốn sửa?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (result == DialogResult.Yes) { try { int ma = Convert.ToInt32(lbmasp.Text); string tensp = txttensp.Text; int maxx = Convert.ToInt32(cmbmaxx.SelectedValue.ToString()); int ghkho = Convert.ToInt32(txtgioihankho.Text); int ghquay = Convert.ToInt32(txtgioihanquay.Text); int slhttrongkho = Convert.ToInt32(txtslhttrongkho.Text); int slhttrongquay = Convert.ToInt32(txtslhttrongquay.Text); int loaisp = Convert.ToInt32(cmbloaisp.SelectedValue.ToString()); int makho = Convert.ToInt32(cmbmakho.SelectedValue.ToString()); int maquay = Convert.ToInt32(cmbmaquay.SelectedValue.ToString()); int gia = Convert.ToInt32(txtgia.Text); string tinhtrang = cmbtinhtrang.Text; DateTime ngaynhap = Convert.ToDateTime(dtpngaynhap.Text); SANPHAMBUS spBus = new SANPHAMBUS(); SANPHAMDTO spDto = new SANPHAMDTO(ma,tensp, maxx, ghkho, ghquay, slhttrongkho, slhttrongquay, loaisp, makho, maquay, gia, tinhtrang, ngaynhap); spBus.SuaSP(spDto); LoadSP(); clr(); MessageBox.Show("Thành công"); return; } catch (Exception ex) { MessageBox.Show(ex.Message); return; } } } private void dgvdanhsachsp_SelectionChanged(object sender, EventArgs e) { lbmasp.Text = dgvdanhsachsp.CurrentRow.Cells[0].Value.ToString(); txttensp.Text = dgvdanhsachsp.CurrentRow.Cells[1].Value.ToString(); cmbmaxx.Text = dgvdanhsachsp.CurrentRow.Cells[2].Value.ToString(); txtgioihankho.Text = dgvdanhsachsp.CurrentRow.Cells[3].Value.ToString(); txtgioihanquay.Text = dgvdanhsachsp.CurrentRow.Cells[4].Value.ToString(); txtslhttrongkho.Text = dgvdanhsachsp.CurrentRow.Cells[5].Value.ToString(); txtslhttrongquay.Text = dgvdanhsachsp.CurrentRow.Cells[6].Value.ToString(); cmbloaisp.Text = dgvdanhsachsp.CurrentRow.Cells[7].Value.ToString(); cmbmakho.Text = dgvdanhsachsp.CurrentRow.Cells[8].Value.ToString(); cmbmaquay.Text = dgvdanhsachsp.CurrentRow.Cells[9].Value.ToString(); txtgia.Text = dgvdanhsachsp.CurrentRow.Cells[10].Value.ToString(); cmbtinhtrang.Text = dgvdanhsachsp.CurrentRow.Cells[11].Value.ToString(); dtpngaynhap.Text = dgvdanhsachsp.CurrentRow.Cells[12].Value.ToString(); } private void txtgioihankho_KeyPress(object sender, KeyPressEventArgs e) { if (!Char.IsNumber(e.KeyChar)) { e.Handled = true; } } private void txtgioihanquay_KeyPress(object sender, KeyPressEventArgs e) { if (!Char.IsNumber(e.KeyChar)) { e.Handled = true; } } private void txtgia_KeyPress(object sender, KeyPressEventArgs e) { if (!Char.IsNumber(e.KeyChar)) { e.Handled = true; } } private void txtslhttrongkho_KeyPress(object sender, KeyPressEventArgs e) { if (!Char.IsNumber(e.KeyChar)) { e.Handled = true; } } private void txtslhttrongquay_KeyPress(object sender, KeyPressEventArgs e) { if (!Char.IsNumber(e.KeyChar)) { e.Handled = true; } } private void btntim_Click(object sender, EventArgs e) { if (txtsearch.Text == "") { MessageBox.Show("Không có từ khoá cần tìm", ""); return; } LoadTim(); } } }
10650931065130doan
trunk/1065093_1065130_1065120_DoAn/1065093_1065130_1065120_DoAn/QuanLySanPham.cs
C#
asf20
9,366
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.SqlClient; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using BUS; using DTO; namespace _1065093_1065130_1065120_DoAn { public partial class frm_DangNhap : Form { public frm_DangNhap() { InitializeComponent(); } private void frm_DangNhap_Load(object sender, EventArgs e) { } private void btndangnhap_Click(object sender, EventArgs e) { try { progressBar1.Value = 0; for (int i = 0; i < progressBar1.Maximum - 1; i++) { progressBar1.Value += 1; } if (txtuser.Text == "") { MessageBox.Show("Hãy Nhập Thông Tin", "Thông Báo"); txtuser.Focus(); return; } if (txtpass.Text == "") { MessageBox.Show("Hãy Nhập Thông Tin", "Thông Báo"); txtpass.Focus(); return; } DataTable dt = new DataTable(); TAIKHOANBUS BUS = new TAIKHOANBUS(); dt = BUS.LoadDSTaiKhoan(); for (int i = 0; i < dt.Rows.Count; i++) { DataRow dr = dt.Rows[i]; if (int.Parse(txtuser.Text.Trim()) == int.Parse(dr["Id"].ToString()) && txtpass.Text.Trim() == dr["MatKhau"].ToString().Trim()) { MessageBox.Show("Đăng Nhập Thành Công", "Thông Báo"); this.Hide(); if (dr["LoaiTK"].ToString().Trim() == "1") { frm_nvThuNgan frm = new frm_nvThuNgan(); frm.ShowDialog(); //DangNhap X = new DangNhap(); ////X.Show(); //panel1.Controls.Add(X); } } else MessageBox.Show("Thông Tin Nhập Không Đúng", "Thông Báo"); } } catch (Exception) { MessageBox.Show(e.ToString(), "Thông Báo"); throw; } } } }
10650931065130doan
trunk/1065093_1065130_1065120_DoAn/1065093_1065130_1065120_DoAn/frm_DangNhap.cs
C#
asf20
2,644
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace _1065093_1065130_1065120_DoAn { public partial class frm_QuanLySanPham : Form { public frm_QuanLySanPham() { InitializeComponent(); } } }
10650931065130doan
trunk/1065093_1065130_1065120_DoAn/1065093_1065130_1065120_DoAn/frm_QuanLySanPham.cs
C#
asf20
405
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using DTO; using BUS; namespace _1065093_1065130_1065120_DoAn { public partial class frm_nvThuNgan : Form { public static int MaNV; public frm_nvThuNgan() { InitializeComponent(); } private void frm_nvThuNgan_Load(object sender, EventArgs e) { } private void btntest_Click(object sender, EventArgs e) { int flat = 0; if (txtmakh.Text =="") { MessageBox.Show("Chưa Nhập MaKh", "Thông Báo"); txtmakh.Focus(); return ; } for (int i = 0; i < txtmakh.Text.Count() - 1; i++) { if (char.IsDigit(txtmakh.Text[i]) == false) { MessageBox.Show("Mã Khách Hàng Không Hợp Lệ", "Thông Báo"); return; } } DataTable dt = new DataTable(); KHACHHANGBUS BUS = new KHACHHANGBUS(); dt = BUS.GET_KHACHHANG(); for (int i = 0; i < dt.Rows.Count; i++) { DataRow dr = dt.Rows[i]; if (int.Parse(txtmakh.Text.Trim()) == int.Parse(dr["MaKH"].ToString().Trim())) { flat = 1; MaNV = int.Parse(txtmakh.Text); frm_ThongTinKhachHang frm = new frm_ThongTinKhachHang(); frm.ShowDialog(); } } if (flat == 0) { MessageBox.Show("Mã Kh Không Tồn Tại ", "Thông Báo"); txtmakh.Focus(); return; } } private void btnthem_Click(object sender, EventArgs e) { frm_ThemKhachHang frm = new frm_ThemKhachHang(); frm.ShowDialog(); } } }
10650931065130doan
trunk/1065093_1065130_1065120_DoAn/1065093_1065130_1065120_DoAn/frm_nvThuNgan.cs
C#
asf20
2,200
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace _1065093_1065130_1065120_DoAn { public partial class frm_QuanLyKhoQuay : Form { public frm_QuanLyKhoQuay() { InitializeComponent(); } } }
10650931065130doan
trunk/1065093_1065130_1065120_DoAn/1065093_1065130_1065120_DoAn/frm_QuanLyKhoQuay.cs
C#
asf20
403
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using DTO; using BUS; namespace _1065093_1065130_1065120_DoAn { public partial class frm_ThemKhachHang : Form { public frm_ThemKhachHang() { InitializeComponent(); } private void frm_ThemKhachHang_Load(object sender, EventArgs e) { } private void btnthem_Click(object sender, EventArgs e) { KHACHHANGBUS BUS = new KHACHHANGBUS(); int diemtichluy = 0; int max = 0; BUS.THEM_KHACHHANG(txthoten.Text, txtsdt.Text, diemtichluy); DataTable dt = new DataTable(); dt = BUS.GET_KHACHHANG(); for (int i = 0; i < dt.Rows.Count; i++) { DataRow dr = dt.Rows[i]; if (int.Parse(dr["MaKH"].ToString().Trim()) > max) { max = int.Parse(dr["MaKH"].ToString().Trim()); } } MessageBox.Show("Thêm Thành Công_Mã Số Khách Hàng Là:" + max, "Thông Báo"); } } }
10650931065130doan
trunk/1065093_1065130_1065120_DoAn/1065093_1065130_1065120_DoAn/frm_ThemKhachHang.cs
C#
asf20
1,297
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("1065093_1065130_1065120_DoAn")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("1065093_1065130_1065120_DoAn")] [assembly: AssemblyCopyright("Copyright © 2012")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("d00d18e5-1dab-4a31-95f5-c12dc0f58f92")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
10650931065130doan
trunk/1065093_1065130_1065120_DoAn/1065093_1065130_1065120_DoAn/Properties/AssemblyInfo.cs
C#
asf20
1,468
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace _1065093_1065130_1065120_DoAn { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void đăngNhậpToolStripMenuItem_Click(object sender, EventArgs e) { frm_DangNhap frm = new frm_DangNhap(); frm.ShowDialog(); } } }
10650931065130doan
trunk/1065093_1065130_1065120_DoAn/1065093_1065130_1065120_DoAn/Form1.cs
C#
asf20
576
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Windows.Forms; using BUS; using DTO; namespace _1065093_1065130_1065120_DoAn { public partial class QuanLyTaiKhoan : UserControl { public QuanLyTaiKhoan() { InitializeComponent(); } private void QuanLyTaiKhoan_Load(object sender, EventArgs e) { DataTable dt = new DataTable(); NHANVIENBUS nvBus = new NHANVIENBUS(); dt = nvBus.LoadDSNhanVien(); cmbid.DataSource = dt; cmbid.DisplayMember = "MaNV"; cmbid.ValueMember = "MaNV"; DataTable dt1 = new DataTable(); LOAINHANVIENBUS lnvBus = new LOAINHANVIENBUS(); dt1 = lnvBus.LoadDSLoaiNV(); cmbloaitk.DataSource = dt1; cmbloaitk.DisplayMember = "MaLoaiNV"; cmbloaitk.ValueMember = "MaLoaiNV"; LoadTK(); } public void LoadTK() { TAIKHOANBUS tk = new TAIKHOANBUS(); DataTable dt = new DataTable(); dt = tk.LoadDSTaiKhoan(); dgvdanhsachtk.DataSource = dt; } private void btnthem_Click(object sender, EventArgs e) { try { int id = Convert.ToInt32(cmbid.SelectedValue.ToString()); string matkhau = txtmatkhau.Text; int loaitk = Convert.ToInt32(cmbloaitk.SelectedValue.ToString()); TAIKHOANBUS tkBus = new TAIKHOANBUS(); TAIKHOANDTO tkDto = new TAIKHOANDTO(id, matkhau, loaitk); tkBus.ThemTK(tkDto); LoadTK(); MessageBox.Show("Thành công"); return; } catch (Exception ex) { MessageBox.Show(ex.Message); return; } } private void btnxoa_Click(object sender, EventArgs e) { DialogResult result = MessageBox.Show("Bạn có muốn xoá?","", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (result == DialogResult.Yes) { try { int id = Convert.ToInt32(dgvdanhsachtk.CurrentRow.Cells[0].Value); TAIKHOANBUS tkBus = new TAIKHOANBUS(); tkBus.XoaTK(id); LoadTK(); MessageBox.Show("Thành công"); return; } catch (Exception ex) { MessageBox.Show(ex.Message); return; } } } private void dgvdanhsachtk_SelectionChanged(object sender, EventArgs e) { cmbid.Text = dgvdanhsachtk.CurrentRow.Cells[0].Value.ToString(); txtmatkhau.Text = dgvdanhsachtk.CurrentRow.Cells[1].Value.ToString(); cmbloaitk.Text = dgvdanhsachtk.CurrentRow.Cells[2].Value.ToString(); } private void btnsua_Click(object sender, EventArgs e) { DialogResult result = MessageBox.Show("Bạn có muốn sửa?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (result == DialogResult.Yes) { try { int id = Convert.ToInt32(cmbid.SelectedValue.ToString()); string matkhau = txtmatkhau.Text; int loaitk = Convert.ToInt32(cmbloaitk.SelectedValue.ToString()); TAIKHOANBUS tkBus = new TAIKHOANBUS(); TAIKHOANDTO tkDto = new TAIKHOANDTO(id, matkhau, loaitk); tkBus.SuaTK(tkDto); LoadTK(); MessageBox.Show("Thành công"); return; } catch (Exception ex) { MessageBox.Show(ex.Message); return; } } } private void btntim_Click(object sender, EventArgs e) { if (txtsearch.Text == "") { MessageBox.Show("Không có từ khoá cần tìm", ""); return; } LoadTim(); } public void LoadTim() { string tukhoa = txtsearch.Text; TAIKHOANBUS tkBus = new TAIKHOANBUS(); DataTable dt = new DataTable(); dt = tkBus.LoadDSTimKiem(tukhoa); dgvdanhsachtimkiem.DataSource = dt; } } }
10650931065130doan
trunk/1065093_1065130_1065120_DoAn/1065093_1065130_1065120_DoAn/QuanLyTaiKhoan.cs
C#
asf20
4,860
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Windows.Forms; using BUS; using DTO; namespace _1065093_1065130_1065120_DoAn { public partial class QuanLySoLuongSanPham : UserControl { public QuanLySoLuongSanPham() { InitializeComponent(); } public void LoadTim() { string tukhoa = txtsearch.Text; SANPHAMBUS spBus = new SANPHAMBUS(); DataTable dt = new DataTable(); dt = spBus.LoadDsTim(tukhoa); dgvsoluong.DataSource = dt; } private void btntim_Click(object sender, EventArgs e) { if (txtsearch.Text == "") { MessageBox.Show("Không có từ khoá cần tìm", ""); return; } LoadTim(); } private void dgvsoluong_SelectionChanged(object sender, EventArgs e) { lbmasp.Text = dgvsoluong.CurrentRow.Cells[0].Value.ToString(); lbtensp.Text = dgvsoluong.CurrentRow.Cells[1].Value.ToString(); txtghkho.Text = dgvsoluong.CurrentRow.Cells[2].Value.ToString(); txtghquay.Text = dgvsoluong.CurrentRow.Cells[3].Value.ToString(); txtslhttkho.Text = dgvsoluong.CurrentRow.Cells[4].Value.ToString(); txtslhttquay.Text = dgvsoluong.CurrentRow.Cells[5].Value.ToString(); } private void btnsua_Click(object sender, EventArgs e) { DialogResult result = MessageBox.Show("Bạn có muốn sửa?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (result == DialogResult.Yes) { try { int ma = Convert.ToInt32(lbmasp.Text); int ghkho = Convert.ToInt32(txtghkho.Text); int ghquay = Convert.ToInt32(txtghquay.Text); int slhttrongkho = Convert.ToInt32(txtslhttkho.Text); int slhttrongquay = Convert.ToInt32(txtslhttquay.Text); SANPHAMBUS spBus = new SANPHAMBUS(); spBus.SuaSL(ma,ghkho,ghquay,slhttrongkho,slhttrongquay); LoadTim(); MessageBox.Show("Thành công"); return; } catch (Exception ex) { MessageBox.Show(ex.Message); return; } } } private void txtghkho_KeyPress(object sender, KeyPressEventArgs e) { if (!Char.IsNumber(e.KeyChar)) { e.Handled = true; } } private void txtghquay_KeyPress(object sender, KeyPressEventArgs e) { if (!Char.IsNumber(e.KeyChar)) { e.Handled = true; } } private void txtslhttkho_KeyPress(object sender, KeyPressEventArgs e) { if (!Char.IsNumber(e.KeyChar)) { e.Handled = true; } } private void txtslhttquay_KeyPress(object sender, KeyPressEventArgs e) { if (!Char.IsNumber(e.KeyChar)) { e.Handled = true; } } } }
10650931065130doan
trunk/1065093_1065130_1065120_DoAn/1065093_1065130_1065120_DoAn/QuanLySoLuongSanPham.cs
C#
asf20
3,523
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Windows.Forms; namespace _1065093_1065130_1065120_DoAn { public partial class DigitTextbox : UserControl { public DigitTextbox() { InitializeComponent(); } private void textBox1_KeyPress(object sender, KeyPressEventArgs e) { if (!Char.IsNumber(e.KeyChar)) { e.Handled = true; } } } }
10650931065130doan
trunk/1065093_1065130_1065120_DoAn/1065093_1065130_1065120_DoAn/DigitTextbox.cs
C#
asf20
611
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace _1065093_1065130_1065120_DoAn { public partial class frm_ThongTinKhachHang : Form { public frm_ThongTinKhachHang() { InitializeComponent(); } private void frm_ThongTinKhachHang_Load(object sender, EventArgs e) { lbmanv.Text = frm_nvThuNgan.MaNV.ToString(); } } }
10650931065130doan
trunk/1065093_1065130_1065120_DoAn/1065093_1065130_1065120_DoAn/frm_ThongTinKhachHang.cs
C#
asf20
570
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace _1065093_1065130_1065120_DoAn { public partial class frm_NvTinHoc : Form { public frm_NvTinHoc() { InitializeComponent(); } } }
10650931065130doan
trunk/1065093_1065130_1065120_DoAn/1065093_1065130_1065120_DoAn/frm_NvTinHoc.cs
C#
asf20
393
using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; namespace _1065093_1065130_1065120_DoAn { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } }
10650931065130doan
trunk/1065093_1065130_1065120_DoAn/1065093_1065130_1065120_DoAn/Program.cs
C#
asf20
521
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace _1065093_1065130_1065120_DoAn { public partial class frm_NvQuanLy : Form { public frm_NvQuanLy() { InitializeComponent(); } private void thoátToolStripMenuItem_Click(object sender, EventArgs e) { this.Close(); } private void sảnPhẩmToolStripMenuItem_Click(object sender, EventArgs e) { panel1.Controls.Clear(); QuanLySanPham qlsp = new QuanLySanPham(); qlsp.Show(); panel1.Controls.Add(qlsp); } private void sốLượngHàngHoáToolStripMenuItem_Click(object sender, EventArgs e) { panel1.Controls.Clear(); QuanLySoLuongSanPham qlslsp = new QuanLySoLuongSanPham(); qlslsp.Show(); panel1.Controls.Add(qlslsp); } private void thamSốToolStripMenuItem_Click(object sender, EventArgs e) { panel1.Controls.Clear(); QuyDinhDiemThanThiet qdd = new QuyDinhDiemThanThiet(); qdd.Show(); panel1.Controls.Add(qdd); } private void khuyếnMãiToolStripMenuItem_Click(object sender, EventArgs e) { panel1.Controls.Clear(); QuyDinhKhuyenMai qdkm = new QuyDinhKhuyenMai(); qdkm.Show(); panel1.Controls.Add(qdkm); } } }
10650931065130doan
trunk/1065093_1065130_1065120_DoAn/1065093_1065130_1065120_DoAn/frm_NvQuanLy.cs
C#
asf20
1,641
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Windows.Forms; using BUS; using DTO; namespace _1065093_1065130_1065120_DoAn { public partial class QuyDinhKhuyenMai : UserControl { public QuyDinhKhuyenMai() { InitializeComponent(); } public void LoadKM() { THAMSOBUS tsBUS = new THAMSOBUS(); DataTable dt = new DataTable(); dt = tsBUS.LoadKhuyenMai(); dgvkhuyenmai.DataSource = dt; } private void QuyDinhKhuyenMai_Load(object sender, EventArgs e) { LoadKM(); } private void dgvkhuyenmai_SelectionChanged(object sender, EventArgs e) { lbmakm.Text = dgvkhuyenmai.CurrentRow.Cells[0].Value.ToString(); txttenkm.Text = dgvkhuyenmai.CurrentRow.Cells[1].Value.ToString(); txtgiatri.Text = dgvkhuyenmai.CurrentRow.Cells[2].Value.ToString(); txtkieu.Text = dgvkhuyenmai.CurrentRow.Cells[3].Value.ToString(); dtpngaybd.Text = dgvkhuyenmai.CurrentRow.Cells[4].Value.ToString(); dtpngaykt.Text = dgvkhuyenmai.CurrentRow.Cells[5].Value.ToString(); } private void txtgiatri_KeyPress(object sender, KeyPressEventArgs e) { if (!Char.IsNumber(e.KeyChar)) { e.Handled = true; } } private void btnthem_Click(object sender, EventArgs e) { try { string tenkm = txttenkm.Text; int giatri = Convert.ToInt32(txtgiatri.Text); string kieu = txtkieu.Text; DateTime ngaybd = Convert.ToDateTime(dtpngaybd.Text); DateTime ngaykt = Convert.ToDateTime(dtpngaykt.Text); THAMSOBUS tsBus = new THAMSOBUS(); THAMSODTO tsDto = new THAMSODTO(-1,tenkm,giatri,kieu,ngaybd,ngaykt); tsBus.ThemKhuyenMai(tsDto); LoadKM(); MessageBox.Show("Thành công"); return; } catch (Exception ex) { MessageBox.Show(ex.Message); return; } } private void btnxoa_Click(object sender, EventArgs e) { DialogResult result = MessageBox.Show("Bạn có muốn xoá?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (result == DialogResult.Yes) { try { int ma = Convert.ToInt32(dgvkhuyenmai.CurrentRow.Cells[0].Value); THAMSOBUS tsBus = new THAMSOBUS(); tsBus.XoaKhuyenMai(ma); LoadKM(); MessageBox.Show("Thành công"); return; } catch (Exception ex) { MessageBox.Show(ex.Message); return; } } } private void btnsua_Click(object sender, EventArgs e) { DialogResult result = MessageBox.Show("Bạn có muốn sửa?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (result == DialogResult.Yes) { try { int ma = Convert.ToInt32(lbmakm.Text); string tenkm = txttenkm.Text; int giatri = Convert.ToInt32(txtgiatri.Text); string kieu = txtkieu.Text; DateTime ngaybd = Convert.ToDateTime(dtpngaybd.Text); DateTime ngaykt = Convert.ToDateTime(dtpngaykt.Text); THAMSOBUS tsBus = new THAMSOBUS(); THAMSODTO tsDto = new THAMSODTO(ma,tenkm,giatri,kieu,ngaybd,ngaykt); tsBus.SuaKhuyenMai(tsDto); LoadKM(); MessageBox.Show("Thành công"); return; } catch (Exception ex) { MessageBox.Show(ex.Message); return; } } } } }
10650931065130doan
trunk/1065093_1065130_1065120_DoAn/1065093_1065130_1065120_DoAn/QuyDinhKhuyenMai.cs
C#
asf20
4,438
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; using System.Data.SqlClient; using DTO; namespace DAO { public class NHANVIENDAO { public DataTable LoadNhanVien() { DataTable dtNhanVien = new DataTable(); SqlConnection cn = Connection.ConnectionData(); SqlCommand cmd = new SqlCommand("sp_BangNV", cn); cmd.CommandType = CommandType.StoredProcedure; SqlDataAdapter da = new SqlDataAdapter(cmd); da.Fill(dtNhanVien); cn.Close(); return dtNhanVien; } } }
10650931065130doan
trunk/1065093_1065130_1065120_DoAn/DAO/NHANVIENDAO.cs
C#
asf20
673
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.SqlClient; namespace DAO { public class Connection { public static SqlConnection ConnectionData() { string constr = "server=Admin-PC1102mtj\\SQLEXPRESS;Database=QUANLYSIEUTHI;Integrated Security=True"; SqlConnection cn = new SqlConnection(constr); cn.Open(); return cn; } } }
10650931065130doan
trunk/1065093_1065130_1065120_DoAn/DAO/Connection.cs
C#
asf20
517
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; using System.Data.SqlClient; using DTO; namespace DAO { public class KHACHHANGDAO { public DataTable GET_KHACHHANG() { DataTable dt = new DataTable(); SqlConnection cn = Connection.ConnectionData(); SqlCommand cmd = new SqlCommand("GET_KHACHHANG", cn); cmd.CommandType = CommandType.StoredProcedure; SqlDataAdapter da = new SqlDataAdapter(cmd); da.Fill(dt); cn.Close(); return dt; } public void THEM_KHACHHANG(KHACHHANGDTO kh) { SqlConnection cn = Connection.ConnectionData(); SqlCommand cmd = new SqlCommand("THEM_KHACHHANG", cn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add("@tenkh", SqlDbType.NVarChar); cmd.Parameters.Add("@sdtkh", SqlDbType.Char); cmd.Parameters.Add("@diemtichluy", SqlDbType.Int); cmd.Parameters["@tenkh"].Value = kh.TenKH; cmd.Parameters["@sdtkh"].Value = kh.SDTKH; cmd.Parameters["@diemtichluy"].Value = kh.DiemTichKuy; cmd.ExecuteNonQuery(); cn.Close(); } public void CAPNHAT_KHACHHANG(KHACHHANGDTO kh) { SqlConnection cn = Connection.ConnectionData(); SqlCommand cmd = new SqlCommand("CAPNHAT_KHACHHANG", cn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add("@makh", SqlDbType.Int); cmd.Parameters.Add("@tenkh", SqlDbType.NVarChar); cmd.Parameters.Add("@sdtkh", SqlDbType.Char); cmd.Parameters.Add("@diemtichluy", SqlDbType.Int); cmd.Parameters["@makh"].Value = kh.MaKH; cmd.Parameters["@tenkh"].Value = kh.TenKH; cmd.Parameters["@sdtkh"].Value = kh.SDTKH; cmd.Parameters["@diemtichluy"].Value = kh.DiemTichKuy; cmd.ExecuteNonQuery(); cn.Close(); } public void XOA_KHACHHANG(KHACHHANGDTO kh) { SqlConnection cn = Connection.ConnectionData(); SqlCommand cmd = new SqlCommand("XOA_KHACHHANG", cn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add("@makh", SqlDbType.Int); cmd.Parameters["@makh"].Value = kh.MaKH; cmd.ExecuteNonQuery(); cn.Close(); } } }
10650931065130doan
trunk/1065093_1065130_1065120_DoAn/DAO/KHACHHANGDAO.cs
C#
asf20
2,606
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; using System.Data.SqlClient; using DTO; namespace DAO { public class SANPHAMDAO { public DataTable LoadSanPham() { DataTable dtSP = new DataTable(); SqlConnection cn = Connection.ConnectionData(); SqlCommand cmd = new SqlCommand("sp_BangSP", cn); cmd.CommandType = CommandType.StoredProcedure; SqlDataAdapter da = new SqlDataAdapter(cmd); da.Fill(dtSP); cn.Close(); return dtSP; } public void ThemSanPham(SANPHAMDTO spDTO) { SqlConnection cn = Connection.ConnectionData(); SqlCommand cmd = new SqlCommand("sp_ThemSP", cn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add("@tensp", SqlDbType.NVarChar); cmd.Parameters.Add("@maxx", SqlDbType.Int); cmd.Parameters.Add("@ghkho", SqlDbType.Int); cmd.Parameters.Add("@ghquay",SqlDbType.Int); cmd.Parameters.Add("@slhttk",SqlDbType.Int); cmd.Parameters.Add("@slhttq",SqlDbType.Int); cmd.Parameters.Add("@loaisp",SqlDbType.Int); cmd.Parameters.Add("@makho",SqlDbType.Int); cmd.Parameters.Add("@maquay",SqlDbType.Int); cmd.Parameters.Add("@gia",SqlDbType.Int); cmd.Parameters.Add("@tinhtrang",SqlDbType.Char); cmd.Parameters.Add("@ngaynhap",SqlDbType.DateTime); //gán giá trị cho tham số cmd.Parameters["@tensp"].Value = spDTO.TenSP; cmd.Parameters["@maxx"].Value = spDTO.MaXX; cmd.Parameters["@ghkho"].Value = spDTO.GHKho; cmd.Parameters["@ghquay"].Value = spDTO.GHQuay; cmd.Parameters["@slhttk"].Value = spDTO.SoLuongHTTrongKho; cmd.Parameters["@slhttq"].Value = spDTO.SoLuongHTTrongQuay; cmd.Parameters["@loaisp"].Value = spDTO.LoaiSP; cmd.Parameters["@makho"].Value = spDTO.MaKho; cmd.Parameters["@maquay"].Value = spDTO.MaQuay; cmd.Parameters["@gia"].Value = spDTO.Gia; cmd.Parameters["@tinhtrang"].Value = spDTO.TinhTrang; cmd.Parameters["@ngaynhap"].Value = spDTO.NgayNhap; //thực thi câu truy vấn cmd.ExecuteNonQuery(); cn.Close(); } public void XoaSanPham(int ma) { SqlConnection cn = Connection.ConnectionData(); SqlCommand cmd = new SqlCommand("sp_XoaSP", cn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add("@ma", SqlDbType.Int); cmd.Parameters["@ma"].Value = ma; cmd.ExecuteNonQuery(); cn.Close(); } public void SuaSanPham(SANPHAMDTO spDto) { SqlConnection cn = Connection.ConnectionData(); SqlCommand cmd = new SqlCommand("sp_SuaSP", cn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add("@ma", SqlDbType.Int); cmd.Parameters.Add("@tensp", SqlDbType.NVarChar); cmd.Parameters.Add("@maxx", SqlDbType.Int); cmd.Parameters.Add("@ghkho", SqlDbType.Int); cmd.Parameters.Add("@ghquay", SqlDbType.Int); cmd.Parameters.Add("@slhttk", SqlDbType.Int); cmd.Parameters.Add("@slhttq", SqlDbType.Int); cmd.Parameters.Add("@loaisp", SqlDbType.Int); cmd.Parameters.Add("@makho", SqlDbType.Int); cmd.Parameters.Add("@maquay", SqlDbType.Int); cmd.Parameters.Add("@gia", SqlDbType.Int); cmd.Parameters.Add("@tinhtrang", SqlDbType.Char); cmd.Parameters.Add("@ngaynhap", SqlDbType.DateTime); //gán giá trị cho tham số cmd.Parameters["@ma"].Value = spDto.MaSP; cmd.Parameters["@tensp"].Value = spDto.TenSP; cmd.Parameters["@maxx"].Value = spDto.MaXX; cmd.Parameters["@ghkho"].Value = spDto.GHKho; cmd.Parameters["@ghquay"].Value = spDto.GHQuay; cmd.Parameters["@slhttk"].Value = spDto.SoLuongHTTrongKho; cmd.Parameters["@slhttq"].Value = spDto.SoLuongHTTrongQuay; cmd.Parameters["@loaisp"].Value = spDto.LoaiSP; cmd.Parameters["@makho"].Value = spDto.MaKho; cmd.Parameters["@maquay"].Value = spDto.MaQuay; cmd.Parameters["@gia"].Value = spDto.Gia; cmd.Parameters["@tinhtrang"].Value = spDto.TinhTrang; cmd.Parameters["@ngaynhap"].Value = spDto.NgayNhap; //thực thi câu truy vấn cmd.ExecuteNonQuery(); cn.Close(); } public DataTable LoadTimKiem(string tukhoa) { DataTable dt = new DataTable(); SqlConnection cn = Connection.ConnectionData(); SqlCommand cmd = new SqlCommand("sp_TimSP", cn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add("@tukhoa", SqlDbType.VarChar); cmd.Parameters["@tukhoa"].Value = tukhoa; cmd.ExecuteNonQuery(); SqlDataAdapter da = new SqlDataAdapter(cmd); da.Fill(dt); cn.Close(); return dt; } public DataTable LoadTim(string tukhoa) { DataTable dt = new DataTable(); SqlConnection cn = Connection.ConnectionData(); SqlCommand cmd = new SqlCommand("sp_TimSL", cn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add("@tukhoa", SqlDbType.VarChar); cmd.Parameters["@tukhoa"].Value = tukhoa; cmd.ExecuteNonQuery(); SqlDataAdapter da = new SqlDataAdapter(cmd); da.Fill(dt); cn.Close(); return dt; } public void SuaSoLuong(int ma,int ghkho,int ghquay,int slhtkho,int slhtquay) { SqlConnection cn = Connection.ConnectionData(); SqlCommand cmd = new SqlCommand("sp_SuaSL", cn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add("@ma", SqlDbType.Int); cmd.Parameters.Add("@ghkho", SqlDbType.Int); cmd.Parameters.Add("@ghquay", SqlDbType.Int); cmd.Parameters.Add("@slhttk", SqlDbType.Int); cmd.Parameters.Add("@slhttq", SqlDbType.Int); //gán giá trị cho tham số cmd.Parameters["@ma"].Value = ma; cmd.Parameters["@ghkho"].Value = ghkho; cmd.Parameters["@ghquay"].Value = ghquay; cmd.Parameters["@slhttk"].Value = slhtkho; cmd.Parameters["@slhttq"].Value = slhtquay; //thực thi câu truy vấn cmd.ExecuteNonQuery(); cn.Close(); } } }
10650931065130doan
trunk/1065093_1065130_1065120_DoAn/DAO/SANPHAMDAO.cs
C#
asf20
7,097
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("DAO")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("DAO")] [assembly: AssemblyCopyright("Copyright © 2012")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("7087132f-467a-490f-8903-5c4b177865dc")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
10650931065130doan
trunk/1065093_1065130_1065120_DoAn/DAO/Properties/AssemblyInfo.cs
C#
asf20
1,418
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; using System.Data.SqlClient; namespace DAO { public class KHODAO { public DataTable LoadKho() { DataTable dtKho = new DataTable(); SqlConnection cn = Connection.ConnectionData(); SqlCommand cmd = new SqlCommand("sp_BangKho", cn); cmd.CommandType = CommandType.StoredProcedure; SqlDataAdapter da = new SqlDataAdapter(cmd); da.Fill(dtKho); cn.Close(); return dtKho; } } }
10650931065130doan
trunk/1065093_1065130_1065120_DoAn/DAO/KHODAO.cs
C#
asf20
637
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; using System.Data.SqlClient; namespace DAO { public class LOAISPDAO { public DataTable LoadLoaiSP() { DataTable dtLoaiSP = new DataTable(); SqlConnection cn = Connection.ConnectionData(); SqlCommand cmd = new SqlCommand("sp_BangLoaiSP", cn); cmd.CommandType = CommandType.StoredProcedure; SqlDataAdapter da = new SqlDataAdapter(cmd); da.Fill(dtLoaiSP); cn.Close(); return dtLoaiSP; } } }
10650931065130doan
trunk/1065093_1065130_1065120_DoAn/DAO/LOAISPDAO.cs
C#
asf20
655
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; using System.Data.SqlClient; namespace DAO { public class XUATXUDAO { public DataTable LoadXuatXu() { DataTable dtXX = new DataTable(); SqlConnection cn = Connection.ConnectionData(); SqlCommand cmd = new SqlCommand("sp_BangXX", cn); cmd.CommandType = CommandType.StoredProcedure; SqlDataAdapter da = new SqlDataAdapter(cmd); da.Fill(dtXX); cn.Close(); return dtXX; } } }
10650931065130doan
trunk/1065093_1065130_1065120_DoAn/DAO/XUATXUDAO.cs
C#
asf20
639
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; using System.Data.SqlClient; namespace DAO { public class QUAYDAO { public DataTable LoadQuay() { DataTable dtQuay = new DataTable(); SqlConnection cn = Connection.ConnectionData(); SqlCommand cmd = new SqlCommand("sp_BangQuay", cn); cmd.CommandType = CommandType.StoredProcedure; SqlDataAdapter da = new SqlDataAdapter(cmd); da.Fill(dtQuay); cn.Close(); return dtQuay; } } }
10650931065130doan
trunk/1065093_1065130_1065120_DoAn/DAO/QUAYDAO.cs
C#
asf20
643
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; using System.Data.SqlClient; using DTO; namespace DAO { public class THAMSODAO { public DataTable LoadThamSo() { DataTable dtTS = new DataTable(); SqlConnection cn = Connection.ConnectionData(); SqlCommand cmd = new SqlCommand("sp_BangTS", cn); cmd.CommandType = CommandType.StoredProcedure; SqlDataAdapter da = new SqlDataAdapter(cmd); da.Fill(dtTS); cn.Close(); return dtTS; } public void SuaThamSo(int ma, int giatri, string kieu) { SqlConnection cn = Connection.ConnectionData(); SqlCommand cmd = new SqlCommand("sp_SuaTS", cn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add("@ma", SqlDbType.Int); cmd.Parameters.Add("@giatri", SqlDbType.Int); cmd.Parameters.Add("@kieu", SqlDbType.VarChar); //gán giá trị cho tham số cmd.Parameters["@ma"].Value = ma; cmd.Parameters["@giatri"].Value = giatri; cmd.Parameters["@kieu"].Value = kieu; //thực thi câu truy vấn cmd.ExecuteNonQuery(); cn.Close(); } public DataTable LoadKhuyenMai() { DataTable dtKM = new DataTable(); SqlConnection cn = Connection.ConnectionData(); SqlCommand cmd = new SqlCommand("sp_BangKM", cn); cmd.CommandType = CommandType.StoredProcedure; SqlDataAdapter da = new SqlDataAdapter(cmd); da.Fill(dtKM); cn.Close(); return dtKM; } public void ThemKhuyenMai(THAMSODTO tsDTO) { SqlConnection cn = Connection.ConnectionData(); SqlCommand cmd = new SqlCommand("sp_ThemKM", cn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add("@tenkm", SqlDbType.VarChar); cmd.Parameters.Add("@giatri", SqlDbType.Int); cmd.Parameters.Add("@kieu",SqlDbType.VarChar); cmd.Parameters.Add("@ngaybd", SqlDbType.DateTime); cmd.Parameters.Add("@ngaykt", SqlDbType.DateTime); //gán giá trị cho tham số cmd.Parameters["@tenkm"].Value = tsDTO.TenTS; cmd.Parameters["@giatri"].Value = tsDTO.GiaTri; cmd.Parameters["@kieu"].Value = tsDTO.Kieu; cmd.Parameters["@ngaybd"].Value = tsDTO.ThoiGianBD; cmd.Parameters["@ngaykt"].Value = tsDTO.ThoiGianKT; //thực thi câu truy vấn cmd.ExecuteNonQuery(); cn.Close(); } public void XoaKhuyenMai(int ma) { SqlConnection cn = Connection.ConnectionData(); SqlCommand cmd = new SqlCommand("sp_XoaKM", cn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add("@ma", SqlDbType.Int); cmd.Parameters["@ma"].Value = ma; cmd.ExecuteNonQuery(); cn.Close(); } public void SuaKhuyenMai(THAMSODTO tsDto) { SqlConnection cn = Connection.ConnectionData(); SqlCommand cmd = new SqlCommand("sp_SuaKM", cn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add("@ma", SqlDbType.Int); cmd.Parameters.Add("@tenkm", SqlDbType.VarChar); cmd.Parameters.Add("@giatri", SqlDbType.Int); cmd.Parameters.Add("@kieu", SqlDbType.VarChar); cmd.Parameters.Add("@ngaybd", SqlDbType.DateTime); cmd.Parameters.Add("@ngaykt", SqlDbType.DateTime); //gán giá trị cho tham số cmd.Parameters["@ma"].Value = tsDto.MaTS; cmd.Parameters["@tenkm"].Value = tsDto.TenTS; cmd.Parameters["@giatri"].Value = tsDto.GiaTri; cmd.Parameters["@kieu"].Value = tsDto.Kieu; cmd.Parameters["@ngaybd"].Value = tsDto.ThoiGianBD; cmd.Parameters["@ngaykt"].Value = tsDto.ThoiGianKT; //thực thi câu truy vấn cmd.ExecuteNonQuery(); cn.Close(); } } }
10650931065130doan
trunk/1065093_1065130_1065120_DoAn/DAO/THAMSODAO.cs
C#
asf20
4,407
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; using System.Data.SqlClient; namespace DAO { public class LOAINHANVIENDAO { public DataTable LoadLoaiNV() { DataTable dtLoaiNV = new DataTable(); SqlConnection cn = Connection.ConnectionData(); SqlCommand cmd = new SqlCommand("sp_BangLoaiNV", cn); cmd.CommandType = CommandType.StoredProcedure; SqlDataAdapter da = new SqlDataAdapter(cmd); da.Fill(dtLoaiNV); cn.Close(); return dtLoaiNV; } } }
10650931065130doan
trunk/1065093_1065130_1065120_DoAn/DAO/LOAINHANVIENDAO.cs
C#
asf20
661
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; using System.Data.SqlClient; using DTO; namespace DAO { public class TAIKHOANDAO { public DataTable LoadTaiKhoan() { DataTable dt_taikhoan = new DataTable(); SqlConnection cn = Connection.ConnectionData(); SqlCommand cmd = new SqlCommand("sp_BangTK", cn); cmd.CommandType = CommandType.StoredProcedure; SqlDataAdapter da = new SqlDataAdapter(cmd); da.Fill(dt_taikhoan); cn.Close(); return dt_taikhoan; } public void ThemTaiKhoan(TAIKHOANDTO tkDto) { SqlConnection cn = Connection.ConnectionData(); SqlCommand cmd = new SqlCommand("sp_ThemTK",cn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add("@id",SqlDbType.Int); cmd.Parameters.Add("@matkhau",SqlDbType.VarChar); cmd.Parameters.Add("@loaitk",SqlDbType.Int); //gán giá trị cho tham số cmd.Parameters["@id"].Value = tkDto.Id; cmd.Parameters["@matkhau"].Value = tkDto.MatKhau; cmd.Parameters["@loaitk"].Value = tkDto.LoaiTK; //thực thi câu truy vấn cmd.ExecuteNonQuery(); cn.Close(); } public void XoaTaiKhoan(int id) { SqlConnection cn = Connection.ConnectionData(); SqlCommand cmd = new SqlCommand("sp_XoaTK", cn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add("@id", SqlDbType.Int); cmd.Parameters["@id"].Value = id; cmd.ExecuteNonQuery(); cn.Close(); } public void SuaTaiKhoan(TAIKHOANDTO tkDto) { SqlConnection cn = Connection.ConnectionData(); SqlCommand cmd = new SqlCommand("sp_SuaTK", cn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add("@id", SqlDbType.Int); cmd.Parameters.Add("@matkhau", SqlDbType.VarChar); cmd.Parameters.Add("@loaitk", SqlDbType.Int); //gán giá trị cho tham số cmd.Parameters["@id"].Value = tkDto.Id; cmd.Parameters["@matkhau"].Value = tkDto.MatKhau; cmd.Parameters["@loaitk"].Value = tkDto.LoaiTK; //thực thi câu truy vấn cmd.ExecuteNonQuery(); cn.Close(); } public DataTable LoadTimKiem(string tukhoa) { DataTable dt = new DataTable(); SqlConnection cn = Connection.ConnectionData(); SqlCommand cmd = new SqlCommand("sp_TimTK", cn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add("@tukhoa", SqlDbType.VarChar); cmd.Parameters["@tukhoa"].Value = tukhoa; cmd.ExecuteNonQuery(); SqlDataAdapter da = new SqlDataAdapter(cmd); da.Fill(dt); cn.Close(); return dt; } } }
10650931065130doan
trunk/1065093_1065130_1065120_DoAn/DAO/TAIKHOANDAO.cs
C#
asf20
3,205
/* NFC Spy is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. NFC Spy is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Wget. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 */ package com.sinpo.nfcspy; import static android.nfc.NfcAdapter.EXTRA_TAG; import android.app.Activity; import android.app.PendingIntent; import android.content.Intent; import android.content.IntentFilter; import android.nfc.NfcAdapter; import android.nfc.Tag; import android.nfc.tech.IsoDep; import android.os.Build.VERSION; import android.os.Build.VERSION_CODES; final class NfcManager { static boolean hasHCE() { return VERSION.SDK_INT >= VERSION_CODES.KITKAT; } NfcManager(Activity activity) { this.activity = activity; nfcAdapter = NfcAdapter.getDefaultAdapter(activity); pendingIntent = PendingIntent.getActivity(activity, 0, new Intent( activity, activity.getClass()) .addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0); } void onPause() { if (nfcAdapter != null) nfcAdapter.disableForegroundDispatch(activity); } void onResume() { if (nfcAdapter != null) nfcAdapter.enableForegroundDispatch(activity, pendingIntent, TAGFILTERS, TECHLISTS); } boolean isEnabled() { return nfcAdapter != null && nfcAdapter.isEnabled(); } static IsoDep attachCard(Intent intent) { Tag tag = (Tag) intent.getParcelableExtra(EXTRA_TAG); return (tag != null) ? IsoDep.get(tag) : null; } static String getCardId(IsoDep isodep) { if (isodep != null) { byte[] id = isodep.getTag().getId(); if (id != null && id.length > 0) return Logger.toHexString(id, 0, id.length); } return "UNKNOWN"; } static void closeConnect(IsoDep tag) { try { if (tag != null) tag.close(); } catch (Exception e) { } } static byte[] transceiveApdu(IsoDep tag, byte[] cmd) { if (tag != null) { try { if (!tag.isConnected()) { tag.connect(); tag.setTimeout(10000); } return tag.transceive(cmd); } catch (Exception e) { } } return null; } static byte[] transceiveApdu(IsoDep tag, int timeout, byte[] cmd) { if (tag != null) { try { if (tag.isConnected()) tag.close(); tag.connect(); tag.setTimeout(timeout); return tag.transceive(cmd); } catch (Exception e) { } } return null; } private final Activity activity; private NfcAdapter nfcAdapter; private PendingIntent pendingIntent; private static String[][] TECHLISTS; private static IntentFilter[] TAGFILTERS; static { try { TECHLISTS = new String[][] { { IsoDep.class.getName() } }; TAGFILTERS = new IntentFilter[] { new IntentFilter( NfcAdapter.ACTION_TECH_DISCOVERED, "*/*") }; } catch (Exception e) { } } }
0antwei-nfcsop
src/com/sinpo/nfcspy/NfcManager.java
Java
gpl3
3,169
/* NFC Spy is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. NFC Spy is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Wget. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 */ package com.sinpo.nfcspy; import static com.sinpo.nfcspy.ServiceFactory.STA_FAIL; import static com.sinpo.nfcspy.ServiceFactory.STA_SUCCESS; import static com.sinpo.nfcspy.ServiceFactory.STA_UNKNOWN; import android.net.wifi.p2p.WifiP2pConfig; import android.net.wifi.p2p.WifiP2pDevice; import android.net.wifi.p2p.WifiP2pDeviceList; import android.net.wifi.p2p.WifiP2pInfo; import android.net.wifi.p2p.WifiP2pManager.ActionListener; import android.net.wifi.p2p.WifiP2pManager.ConnectionInfoListener; import android.net.wifi.p2p.WifiP2pManager.PeerListListener; abstract class WiFiP2PCommand { final static int CMD_DiscoverPeers = 0x01000000; final static int CMD_StopPeerDiscovery = 0x02000000; final static int CMD_RequestPeers = 0x03000000; final static int CMD_ConnectPeer = 0x04000000; final static int CMD_CancelConnect = 0x05000000; final static int CMD_RemoveGroup = 0x06000000; final static int CMD_RequestConnectionInfo = 0x07000000; WiFiP2PCommand(ServiceFactory.SpyCallback cb) { callback = cb; status = STA_UNKNOWN; } void setListener(ServiceFactory.SpyCallback cb) { callback = cb; } boolean isFinished() { return status != STA_UNKNOWN; } boolean isSuccessed() { return status == STA_SUCCESS; } void execute(WiFiP2PManager ctx) { if (!ctx.isInited()) { onFinished(STA_FAIL); } else { executeImp(ctx); } } protected void onFinished(int sta) { status = sta; if (callback != null) callback.handleMessage(id(), sta, null); } protected void onFinished(int sta, Object obj) { status = sta; if (callback != null) callback.handleMessage(id(), sta, obj); } abstract protected int id(); abstract protected void executeImp(WiFiP2PManager ctx); protected int status; protected int error; private ServiceFactory.SpyCallback callback; } abstract class WiFiP2PAction extends WiFiP2PCommand implements ActionListener { WiFiP2PAction(ServiceFactory.SpyCallback callback) { super(callback); } public void onSuccess() { onFinished(STA_SUCCESS); } public void onFailure(int reason) { error = reason; onFinished(STA_FAIL); } } final class Wifip2pRequestConnectionInfo extends WiFiP2PCommand implements ConnectionInfoListener { Wifip2pRequestConnectionInfo(ServiceFactory.SpyCallback callback) { super(callback); } @Override protected void executeImp(WiFiP2PManager ctx) { this.ctx = ctx; ctx.wifip2p.requestConnectionInfo(ctx.channel, this); } @Override public void onConnectionInfoAvailable(WifiP2pInfo info) { if (info.groupFormed) { ctx.groupOwnerAddress = info.groupOwnerAddress; ctx.isGroupOwner = info.isGroupOwner; ctx.isWifiP2pConnected = true; onFinished(STA_SUCCESS, info); } else { ctx.groupOwnerAddress = null; ctx.isGroupOwner = false; ctx.isWifiP2pConnected = false; onFinished(STA_FAIL); } } private WiFiP2PManager ctx; @Override protected int id() { return CMD_RequestConnectionInfo; } } final class Wifip2pDiscoverPeers extends WiFiP2PAction { Wifip2pDiscoverPeers(ServiceFactory.SpyCallback callback) { super(callback); } @Override protected int id() { return CMD_DiscoverPeers; } @Override protected void executeImp(WiFiP2PManager ctx) { ctx.wifip2p.discoverPeers(ctx.channel, this); } } final class Wifip2pStopPeerDiscovery extends WiFiP2PAction { Wifip2pStopPeerDiscovery(ServiceFactory.SpyCallback callback) { super(callback); } @Override protected int id() { return CMD_StopPeerDiscovery; } @Override protected void executeImp(WiFiP2PManager ctx) { ctx.wifip2p.stopPeerDiscovery(ctx.channel, this); } } final class Wifip2pRequestPeers extends WiFiP2PCommand implements PeerListListener { Wifip2pRequestPeers(ServiceFactory.SpyCallback callback) { super(callback); } @Override protected int id() { return CMD_RequestPeers; } @Override protected void executeImp(WiFiP2PManager ctx) { ctx.wifip2p.requestPeers(ctx.channel, this); } @Override public void onPeersAvailable(WifiP2pDeviceList peers) { onFinished(STA_SUCCESS, peers.getDeviceList()); } } final class Wifip2pConnectPeer extends WiFiP2PAction { Wifip2pConnectPeer(WifiP2pDevice peer, ServiceFactory.SpyCallback callback) { super(callback); this.peer = peer; } @Override protected int id() { return CMD_ConnectPeer; } @Override protected void executeImp(WiFiP2PManager ctx) { final WifiP2pConfig config = new WifiP2pConfig(); config.wps.setup = android.net.wifi.WpsInfo.PBC; config.deviceAddress = peer.deviceAddress; ctx.wifip2p.connect(ctx.channel, config, this); } private final WifiP2pDevice peer; } final class Wifip2pCancelConnect extends WiFiP2PAction { Wifip2pCancelConnect(ServiceFactory.SpyCallback callback) { super(callback); } @Override protected int id() { return CMD_CancelConnect; } @Override protected void executeImp(WiFiP2PManager ctx) { ctx.wifip2p.cancelConnect(ctx.channel, this); } } final class Wifip2pRemoveGroup extends WiFiP2PAction { Wifip2pRemoveGroup(ServiceFactory.SpyCallback callback) { super(callback); } @Override protected int id() { return CMD_RemoveGroup; } @Override protected void executeImp(WiFiP2PManager ctx) { ctx.wifip2p.removeGroup(ctx.channel, this); } }
0antwei-nfcsop
src/com/sinpo/nfcspy/WiFiP2PCommand.java
Java
gpl3
5,911
/* NFC Spy is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. NFC Spy is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Wget. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 */ package com.sinpo.nfcspy; import static android.net.wifi.p2p.WifiP2pManager.EXTRA_NETWORK_INFO; import static android.net.wifi.p2p.WifiP2pManager.EXTRA_WIFI_STATE; import static android.net.wifi.p2p.WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION; import static android.net.wifi.p2p.WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION; import static android.net.wifi.p2p.WifiP2pManager.WIFI_P2P_STATE_ENABLED; import static com.sinpo.nfcspy.ServiceFactory.ACTION_NFC_ATTACH; import static com.sinpo.nfcspy.ServiceFactory.ACTION_NFC_DETTACH; import static com.sinpo.nfcspy.ServiceFactory.ACTION_SERVER_CHAT; import static com.sinpo.nfcspy.ServiceFactory.ACTION_SERVER_SET; import static com.sinpo.nfcspy.ServiceFactory.ACTION_SERVER_START; import static com.sinpo.nfcspy.ServiceFactory.ACTION_SERVER_STOP; import static com.sinpo.nfcspy.ServiceFactory.ERR_APDU_CMD; import static com.sinpo.nfcspy.ServiceFactory.ERR_APDU_RSP; import static com.sinpo.nfcspy.ServiceFactory.ERR_P2P; import static com.sinpo.nfcspy.ServiceFactory.MSG_CHAT_RECV; import static com.sinpo.nfcspy.ServiceFactory.MSG_CHAT_SEND; import static com.sinpo.nfcspy.ServiceFactory.MSG_HCE_APDU_CMD; import static com.sinpo.nfcspy.ServiceFactory.MSG_HCE_APDU_RSP; import static com.sinpo.nfcspy.ServiceFactory.MSG_HCE_ATTACH; import static com.sinpo.nfcspy.ServiceFactory.MSG_HCE_DEACTIVATED; import static com.sinpo.nfcspy.ServiceFactory.MSG_P2P_CONNECT; import static com.sinpo.nfcspy.ServiceFactory.MSG_P2P_DISCONN; import static com.sinpo.nfcspy.ServiceFactory.MSG_P2P_INIT; import static com.sinpo.nfcspy.ServiceFactory.MSG_P2P_SOCKET; import static com.sinpo.nfcspy.ServiceFactory.MSG_SERVER_KILL; import static com.sinpo.nfcspy.ServiceFactory.MSG_SERVER_VER; import static com.sinpo.nfcspy.ServiceFactory.STA_ERROR; import static com.sinpo.nfcspy.ServiceFactory.STA_FAIL; import static com.sinpo.nfcspy.ServiceFactory.STA_NOTCARE; import static com.sinpo.nfcspy.ServiceFactory.STA_P2P_WATING; import static com.sinpo.nfcspy.ServiceFactory.STA_SUCCESS; import static com.sinpo.nfcspy.WiFiP2PCommand.CMD_RequestConnectionInfo; import android.app.Service; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.net.NetworkInfo; import android.net.wifi.p2p.WifiP2pManager.ChannelListener; import android.nfc.tech.IsoDep; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.os.Messenger; import android.os.SystemClock; final class ServiceAgent extends BroadcastReceiver implements ChannelListener, ServiceFactory.SpyCallback { void handleIntent(Intent intent) { final String action = intent.getAction(); if (ACTION_NFC_ATTACH.equals(action)) onCardAttaching(intent); else if (ACTION_NFC_DETTACH.equals(action)) onCardDettached(intent); else if (ACTION_SERVER_START.equals(action)) onStartCommand(intent); else if (ACTION_SERVER_STOP.equals(action)) onStopCommand(intent); else if (ACTION_SERVER_CHAT.equals(action)) onSendChatMessage(intent); else if (ACTION_SERVER_SET.equals(action)) onSetCommand(intent); } @Override public void handleMessage(int type, int status, Object obj) { switch (type) { case MSG_HCE_APDU_CMD: processCommandApdu((byte[]) obj); break; case MSG_HCE_APDU_RSP: processResponseApdu((byte[]) obj); break; case MSG_HCE_ATTACH: Logger.logNfcAttach(new String((byte[]) obj)); sendBinary2Activity(MSG_HCE_ATTACH, (byte[]) obj); break; case MSG_HCE_DEACTIVATED: NfcManager.closeConnect(isodep); Logger.logHceDeactive(); sendStatus2Activity(MSG_HCE_DEACTIVATED, STA_NOTCARE, 0); break; case MSG_SERVER_VER: if (obj == null) sendBinary2Peer(MSG_SERVER_VER, ThisApplication.version() .getBytes()); else sendBinary2Activity(MSG_SERVER_VER, (byte[]) obj); break; case MSG_CHAT_SEND: sendBinary2Activity(MSG_CHAT_RECV, (byte[]) obj); break; case CMD_RequestConnectionInfo: if (lock()) { if (status == STA_SUCCESS) { new SocketConnector(p2p, this).start(); } else { sendStatus2Activity(MSG_P2P_SOCKET, status, 0); unlock(); } } break; case MSG_P2P_CONNECT: if (status == STA_SUCCESS) sendVersion2Peer(); // go through case MSG_P2P_DISCONN: if (status == STA_SUCCESS || status == STA_FAIL) unlock(); sendStatus2Activity(type, status, STA_NOTCARE); break; case MSG_SERVER_KILL: stopSelf(false); break; } } @Override public void onReceive(Context context, Intent i) { delayAction(MSG_SERVER_KILL, 120000); final String action = i.getAction(); if (WIFI_P2P_STATE_CHANGED_ACTION.equals(action)) { if (i.getIntExtra(EXTRA_WIFI_STATE, -1) != WIFI_P2P_STATE_ENABLED) disconnect(); } else if (WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)) { if (((NetworkInfo) i.getParcelableExtra(EXTRA_NETWORK_INFO)) .isConnected()) { new Wifip2pRequestConnectionInfo(this).execute(p2p); } } } private void onStartCommand(Intent intent) { Messenger messenger = ServiceFactory.getReplyMessengerExtra(intent); if ((outbox = messenger) != null) { if (p2p.isConnected()) { sendStatus2Activity(MSG_P2P_CONNECT, STA_SUCCESS, STA_NOTCARE); return; } if (!p2p.isInited()) { p2p.init(service, this); service.registerReceiver(this, P2PFILTER); sendStatus2Activity(MSG_P2P_INIT, STA_SUCCESS, STA_NOTCARE); } sendStatus2Activity(MSG_P2P_CONNECT, STA_P2P_WATING, STA_NOTCARE); delayAction(MSG_SERVER_KILL, 90000); new Wifip2pRequestConnectionInfo(this).execute(p2p); } } private void processCommandApdu(byte[] cmd) { final long stampCmd = System.currentTimeMillis(); if (cmd != null && cmd.length > 0) { byte[] rsp = NfcManager.transceiveApdu(isodep, cmd); if (rsp == null) rsp = NfcManager.transceiveApdu(isodep, 20000, cmd); final long stampRsp = System.currentTimeMillis(); final boolean valid = (rsp != null && rsp.length > 0); boolean sent = false; if (valid) sent = sendBinary2Peer(MSG_HCE_APDU_RSP, rsp); final long delayCmd = Logger.logApdu(stampCmd, false, true, cmd); final long delayRsp = Logger.logApdu(stampRsp, false, false, rsp); if (!highSpeed) { sendBinary2Activity(MSG_HCE_APDU_CMD, (int) delayCmd, cmd); if (valid) sendBinary2Activity(MSG_HCE_APDU_RSP, (int) delayRsp, rsp); } if (!valid) sendStatus2Activity(MSG_HCE_APDU_RSP, STA_ERROR, ERR_APDU_RSP); if (!sent) sendStatus2Activity(MSG_HCE_APDU_RSP, STA_ERROR, ERR_P2P); } else { Logger.logApdu(stampCmd, false, true, null); sendStatus2Activity(MSG_HCE_APDU_CMD, STA_ERROR, ERR_APDU_CMD); } } private void processResponseApdu(byte[] rsp) { ((ServiceFactory.SpyService) service).processResponseApdu(rsp); Logger.logApdu(System.currentTimeMillis(), true, false, rsp); } private void onCardAttaching(Intent intent) { isodep = NfcManager.attachCard(intent); if (isodep != null) { String id = NfcManager.getCardId(isodep); Logger.logNfcAttach(id); byte[] raw = id.getBytes(); sendBinary2Peer(MSG_HCE_ATTACH, raw); sendBinary2Activity(MSG_HCE_ATTACH, raw); } } private void onSetCommand(Intent intent) { highSpeed = ServiceFactory.getHighSpeedSettingExtra(intent); } private void onSendChatMessage(Intent intent) { byte[] msg = ServiceFactory.getChatMessageExtra(intent).getBytes(); if (sendBinary2Peer(MSG_CHAT_SEND, msg)) sendBinary2Activity(MSG_CHAT_SEND, msg); } private void onStopCommand(Intent intent) { stopSelf(true); } private void onCardDettached(Intent intent) { isodep = null; } void onDeactivated(int reason) { sendBinary2Peer(MSG_HCE_DEACTIVATED, new byte[1]); Logger.logHceDeactive(); if (!highSpeed) sendStatus2Activity(MSG_HCE_DEACTIVATED, STA_NOTCARE, 0); } byte[] processCommandApdu(byte[] apdu, Bundle ignore) { sendBinary2Peer(MSG_HCE_APDU_CMD, apdu); Logger.logApdu(System.currentTimeMillis(), true, true, apdu); return null; } void onDestroy() { service.unregisterReceiver(this); onCardDettached(null); disconnect(); } private void stopSelf(boolean force) { if (force || !p2p.isConnected()) service.stopSelf(); } @Override public void onChannelDisconnected() { disconnect(); } private void disconnect() { p2p.reset(); } private void sendVersion2Peer() { // random delay between a few seconds int delay = (int) (SystemClock.uptimeMillis() & 0x3FF); delayAction(MSG_SERVER_VER, delay + 1000); } private boolean sendBinary2Peer(int type, byte[] raw) { return p2p.sendData(type, raw); } private void sendBinary2Activity(int type, byte[] raw) { sendBinary2Activity(type, STA_NOTCARE, raw); } private void sendBinary2Activity(int type, int arg, byte[] raw) { try { Message msg = Message.obtain(null, type, raw.length, arg); ServiceFactory.setDataToMessage(msg, raw); outbox.send(msg); } catch (Exception e) { } } private void sendStatus2Activity(int type, int status, int detail) { try { outbox.send(Message.obtain(null, type, status, detail)); } catch (Exception e) { } } private void delayAction(int type, long millis) { handler.postDelayed(new Action(this, type, STA_NOTCARE), millis); } ServiceAgent(Service service) { this.service = service; this.handler = new Handler(); this.p2p = new WiFiP2PManager(); outbox = null; Logger.open(); } synchronized boolean lock() { if (!lock) { lock = true; return true; } return false; } synchronized void unlock() { lock = false; } private final static class Action implements Runnable { private final ServiceFactory.SpyCallback callback; private final int type, status; @Override public void run() { callback.handleMessage(type, status, null); } Action(ServiceFactory.SpyCallback cback, int type, int status) { this.callback = cback; this.type = type; this.status = status; } } private final Service service; private final WiFiP2PManager p2p; private final Handler handler; private IsoDep isodep; private Messenger outbox; private boolean lock; private static boolean highSpeed; private final static IntentFilter P2PFILTER; static { P2PFILTER = new IntentFilter(); P2PFILTER.addAction(WIFI_P2P_STATE_CHANGED_ACTION); P2PFILTER.addAction(WIFI_P2P_CONNECTION_CHANGED_ACTION); } }
0antwei-nfcsop
src/com/sinpo/nfcspy/ServiceAgent.java
Java
gpl3
11,091
/* NFC Spy is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. NFC Spy is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Wget. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 */ package com.sinpo.nfcspy; import android.app.Activity; import android.os.Handler; abstract class ActivityBase extends Activity { @Override public void onBackPressed() { if (!safeExit.isLocked()) super.onBackPressed(); } @Override public void onWindowFocusChanged(boolean hasFocus) { if (hasFocus) safeExit.unlockDelayed(800); else safeExit.setLock(true); } private final SafeExitLock safeExit = new SafeExitLock(); private final static class SafeExitLock extends Handler implements Runnable { private boolean lock; @Override public void run() { setLock(false); } boolean isLocked() { return lock; } void setLock(boolean lock) { this.lock = lock; } void unlockDelayed(long delayMillis) { postDelayed(this, delayMillis); } SafeExitLock() { setLock(true); } } }
0antwei-nfcsop
src/com/sinpo/nfcspy/ActivityBase.java
Java
gpl3
1,491
/* NFC Spy is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. NFC Spy is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Wget. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 */ package com.sinpo.nfcspy; import android.app.Service; import android.content.Intent; import android.os.Bundle; import android.os.IBinder; public final class ServiceLite extends Service implements ServiceFactory.SpyService { private ServiceAgent agent; @Override public void onCreate() { super.onCreate(); agent = new ServiceAgent(this); } @Override public int onStartCommand(Intent intent, int flags, int startId) { agent.handleIntent(intent); return START_NOT_STICKY; } @Override public void onDestroy() { agent.onDestroy(); agent = null; super.onDestroy(); } @Override public IBinder onBind(Intent intent) { return null; } @Override public void processResponseApdu(byte[] apdu) { } @Override public byte[] processCommandApdu(byte[] commandApdu, Bundle extras) { return null; } }
0antwei-nfcsop
src/com/sinpo/nfcspy/ServiceLite.java
Java
gpl3
1,486
/* NFC Spy is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. NFC Spy is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Wget. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 */ package com.sinpo.nfcspy; import android.annotation.SuppressLint; import android.content.Intent; import android.nfc.cardemulation.HostApduService; import android.os.Bundle; @SuppressLint("NewApi") public final class ServiceFull extends HostApduService implements ServiceFactory.SpyService { private ServiceAgent agent; @Override public void onCreate() { super.onCreate(); agent = new ServiceAgent(this); } @Override public int onStartCommand(Intent intent, int flags, int startId) { agent.handleIntent(intent); return START_NOT_STICKY; } @Override public void onDestroy() { agent.onDestroy(); agent = null; super.onDestroy(); } @Override public void onDeactivated(int reason) { if (DEACTIVATION_LINK_LOSS == reason) agent.onDeactivated(reason); } @Override public byte[] processCommandApdu(byte[] commandApdu, Bundle extras) { return agent.processCommandApdu(commandApdu, extras); } @Override public void processResponseApdu(byte[] apdu) { sendResponseApdu(apdu); } }
0antwei-nfcsop
src/com/sinpo/nfcspy/ServiceFull.java
Java
gpl3
1,678
/* NFC Spy is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. NFC Spy is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Wget. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 */ package com.sinpo.nfcspy; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.os.Message; import android.os.Messenger; final class ServiceFactory { final static String ACTION_SERVER_START = "ACTION_SERVER_START"; final static String ACTION_SERVER_STOP = "ACTION_SERVER_STOP"; final static String ACTION_SERVER_SET = "ACTION_SERVER_SET"; final static String ACTION_SERVER_CHAT = "ACTION_SERVER_CHAT"; final static String ACTION_NFC_ATTACH = "ACTION_NFC_ATTACH"; final static String ACTION_NFC_DETTACH = "ACTION_NFC_DETTACH"; final static int MSG_P2P_INIT = 0x11; final static int MSG_P2P_SOCKET = 0x12; final static int MSG_P2P_CONNECT = 0x13; final static int MSG_P2P_DISCONN = 0x14; final static int MSG_SERVER_KILL = 0x21; final static int MSG_SERVER_START = 0x22; final static int MSG_SERVER_STOP = 0x23; final static int MSG_SERVER_VER = 0x24; final static int MSG_HCE_ATTACH = 0x31; final static int MSG_HCE_DETTACH = 0x32; final static int MSG_HCE_DEACTIVATED = 0x33; final static int MSG_HCE_APDU_CMD = 0x34; final static int MSG_HCE_APDU_RSP = 0x35; final static int MSG_CHAT_SEND = 0x41; final static int MSG_CHAT_RECV = 0x42; final static int STA_NOTCARE = 0xFFFFFFFF; final static int STA_UNKNOWN = 0x00; final static int STA_SUCCESS = 0x01; final static int STA_FAIL = 0x02; final static int STA_ERROR = 0x03; final static int STA_P2P_UNINIT = 0x00; final static int STA_P2P_INITED = 0x10; final static int STA_P2P_WATING = 0x11; final static int STA_P2P_ACCEPT = 0x12; final static int STA_P2P_CLIENT = 0x13; final static int ERR_APDU_RSP = 0x21; final static int ERR_APDU_CMD = 0x22; final static int ERR_P2P = 0x23; interface SpyService { void processResponseApdu(byte[] apdu); byte[] processCommandApdu(byte[] commandApdu, Bundle extras); } interface SpyCallback { void handleMessage(int type, int status, Object obj); } static void startServer(Context ctx, Messenger reply) { final Intent i = newServerIntent(ctx, ACTION_SERVER_START); ctx.startService(i.putExtra(KEY_REPLY, reply)); } static void setTag2Server(Context ctx, Intent nfc) { final Intent i = newServerIntent(ctx, ACTION_NFC_ATTACH); ctx.startService(i.replaceExtras(nfc)); } static void resetTag2Server(Context ctx) { ctx.startService(newServerIntent(ctx, ACTION_NFC_DETTACH)); } static void setHighSpeed2Server(Context ctx, boolean set) { final Intent i = newServerIntent(ctx, ACTION_SERVER_SET); ctx.startService(i.putExtra(KEY_HISPD, set)); } static void sendChatMessage2Server(Context ctx, String msg) { final Intent i = newServerIntent(ctx, ACTION_SERVER_CHAT); ctx.startService(i.putExtra(KEY_CHAT, msg)); } static void stopServer(Context ctx) { ctx.stopService(newServerIntent(ctx, ACTION_SERVER_STOP)); } static Messenger getReplyMessengerExtra(Intent intent) { return (Messenger) intent.getParcelableExtra(KEY_REPLY); } static String getChatMessageExtra(Intent intent) { return intent.getStringExtra(KEY_CHAT); } static boolean getHighSpeedSettingExtra(Intent intent) { return intent.getBooleanExtra(KEY_HISPD, false); } static byte[] extractDataFromMessage(Message msg) { Bundle data = msg.getData(); return (data != null) ? data.getByteArray(KEY_BLOB) : null; } static void setDataToMessage(Message msg, byte[] raw) { Bundle data = new Bundle(); data.putByteArray(KEY_BLOB, raw); msg.setData(data); } private static Intent newServerIntent(Context ctx, String action) { Class<?> clazz = ServiceLite.class; if (NfcManager.hasHCE()) { try { clazz = Class.forName("com.sinpo.nfcspy.ServiceFull"); } catch (Exception e) { clazz = ServiceLite.class; } } return new Intent(action, null, ctx, clazz); } private final static String KEY_REPLY = "KEY_REPLY"; private final static String KEY_HISPD = "KEY_HISPD"; private final static String KEY_CHAT = "KEY_CHAT"; private final static String KEY_BLOB = "KEY_BLOB"; }
0antwei-nfcsop
src/com/sinpo/nfcspy/ServiceFactory.java
Java
gpl3
4,671
/* NFC Spy is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. NFC Spy is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Wget. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 */ package com.sinpo.nfcspy; import static android.net.wifi.p2p.WifiP2pManager.EXTRA_WIFI_P2P_DEVICE; import static android.net.wifi.p2p.WifiP2pManager.EXTRA_WIFI_STATE; import static android.net.wifi.p2p.WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION; import static android.net.wifi.p2p.WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION; import static android.net.wifi.p2p.WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION; import static android.net.wifi.p2p.WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION; import java.util.ArrayList; import java.util.Collection; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.content.Intent; import android.content.IntentFilter; import android.net.wifi.p2p.WifiP2pDevice; import android.net.wifi.p2p.WifiP2pManager; import android.net.wifi.p2p.WifiP2pManager.ChannelListener; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; public class ActivityManageP2P extends ActivityBase { public void startDiscover(View v) { resetPeers(); if (!WiFiP2PManager.isWiFiEnabled(this)) { showMessage(R.string.status_no_wifi); return; } new CommandHelper(new Wifip2pDiscoverPeers(eventHelper), p2p, getString(R.string.info_discovering)).execute(); } public void disconnectPeer(View v) { new Wifip2pCancelConnect(eventHelper).execute(p2p); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_manage_p2p); peerdevs = new ArrayList<WifiP2pDevice>(); peers = new ArrayAdapter<CharSequence>(this, R.layout.listitem_peer); eventHelper = new EventHelper(); ListView lv = ((ListView) findViewById(R.id.list)); lv.setAdapter(peers); lv.setOnItemClickListener(eventHelper); thisDevice = (TextView) findViewById(R.id.txtThisdevice); } @Override protected void onResume() { p2p = new WiFiP2PManager(); p2p.init(this, eventHelper); registerReceiver(eventHelper, getWiFiP2PIntentFilter()); super.onResume(); } @Override protected void onPause() { closeProgressDialog(); new Wifip2pStopPeerDiscovery(null).execute(p2p); unregisterReceiver(eventHelper); p2p.reset(); p2p = null; resetPeers(); super.onPause(); } @SuppressWarnings("unchecked") boolean handleMessage(int type, int status, Object obj) { if (type == WiFiP2PCommand.CMD_RequestPeers) { resetPeers(); if (obj != null) { for (WifiP2pDevice dev : (Collection<WifiP2pDevice>) obj) { peerdevs.add(dev); peers.add(getWifiP2pDeviceInfo(dev)); } } return true; } if (type == WiFiP2PCommand.CMD_CancelConnect) { new Wifip2pRemoveGroup(eventHelper).execute(p2p); return true; } if (type == WiFiP2PCommand.CMD_RemoveGroup) { new Wifip2pDiscoverPeers(eventHelper).execute(p2p); return true; } return true; } void handlePeerListClick(int index) { WifiP2pDevice dev = peerdevs.get(index); if (dev.status == WifiP2pDevice.CONNECTED || dev.status == WifiP2pDevice.INVITED) { disconnectPeer(dev); } else if (dev.status != WifiP2pDevice.UNAVAILABLE) { connectPeer(dev); } } void handleBroadcast(Intent intent) { closeProgressDialog(); final String action = intent.getAction(); if (WIFI_P2P_STATE_CHANGED_ACTION.equals(action)) { int state = intent.getIntExtra(EXTRA_WIFI_STATE, -1); if (state == WifiP2pManager.WIFI_P2P_STATE_ENABLED) { p2p.isWifiP2pEnabled = true; } else { showMessage(R.string.event_p2p_disable); resetData(); } } else if (WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)) { new Wifip2pRequestPeers(eventHelper).execute(p2p); } else if (WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action)) { WifiP2pDevice me = (WifiP2pDevice) intent .getParcelableExtra(EXTRA_WIFI_P2P_DEVICE); thisDevice.setText(getWifiP2pDeviceInfo(me)); } } void showMessage(int resId) { showMessage(getString(resId)); } void showMessage(CharSequence msg) { Toast.makeText(this, msg, Toast.LENGTH_LONG).show(); } void showProgressDialog(CharSequence msg) { closeProgressDialog(); ProgressDialog pd = new ProgressDialog(this, ProgressDialog.THEME_HOLO_LIGHT); progressDialog = pd; pd.setMessage(msg); pd.setProgressStyle(ProgressDialog.STYLE_SPINNER); pd.setIndeterminate(true); pd.setCancelable(true); pd.setCanceledOnTouchOutside(false); pd.show(); } void closeProgressDialog() { if (progressDialog != null) { progressDialog.dismiss(); progressDialog = null; } } void onChannelDisconnected() { showMessage(R.string.event_p2p_disable); resetData(); p2p.reset(); } private void connectPeer(WifiP2pDevice peer) { CharSequence dev = getWifiP2pDeviceInfo2(peer); CharSequence msg = Logger.fmt(getString(R.string.info_connect), dev); CharSequence msg2 = Logger .fmt(getString(R.string.info_connecting), dev); CommandHelper cmd = new CommandHelper(new Wifip2pConnectPeer(peer, eventHelper), p2p, msg2); new AlertDialog.Builder(this, AlertDialog.THEME_HOLO_LIGHT) .setTitle(R.string.lab_p2p_connect).setMessage(msg) .setNegativeButton(R.string.action_cancel, cmd) .setPositiveButton(R.string.action_ok, cmd).show(); } private void disconnectPeer(WifiP2pDevice peer) { CharSequence dev = getWifiP2pDeviceInfo2(peer); CharSequence msg = Logger.fmt(getString(R.string.info_disconnect), dev); CommandHelper cmd = new CommandHelper(new Wifip2pCancelConnect( eventHelper), p2p, null); new AlertDialog.Builder(this, AlertDialog.THEME_HOLO_LIGHT) .setTitle(R.string.lab_p2p_disconnect).setMessage(msg) .setNegativeButton(R.string.action_cancel, cmd) .setPositiveButton(R.string.action_ok, cmd).show(); } private void resetPeers() { peerdevs.clear(); peers.clear(); } private void resetData() { p2p.isWifiP2pEnabled = false; thisDevice.setText(null); resetPeers(); } private CharSequence getWifiP2pDeviceInfo(WifiP2pDevice dev) { CharSequence sta = getWifiP2pDeviceStatus(dev); return Logger.fmt("%s [%s] [%s]", dev.deviceName, dev.deviceAddress, sta); } private CharSequence getWifiP2pDeviceInfo2(WifiP2pDevice dev) { return Logger.fmt("%s [%s]", dev.deviceName, dev.deviceAddress); } private CharSequence getWifiP2pDeviceStatus(WifiP2pDevice dev) { switch (dev.status) { case WifiP2pDevice.CONNECTED: return getString(R.string.status_p2p_connected); case WifiP2pDevice.INVITED: return getString(R.string.status_p2p_invited); case WifiP2pDevice.FAILED: return getString(R.string.status_p2p_failed); case WifiP2pDevice.AVAILABLE: return getString(R.string.status_p2p_available); case WifiP2pDevice.UNAVAILABLE: default: return getString(R.string.status_p2p_unavailable); } } private ArrayAdapter<CharSequence> peers; private ArrayList<WifiP2pDevice> peerdevs; private TextView thisDevice; private ProgressDialog progressDialog; private EventHelper eventHelper; private WiFiP2PManager p2p; private final class CommandHelper implements OnClickListener { private final WiFiP2PCommand command; private final WiFiP2PManager ctx; private final CharSequence message; CommandHelper(WiFiP2PCommand cmd, WiFiP2PManager p2p, CharSequence msg) { ctx = p2p; command = cmd; message = msg; } void execute() { command.execute(ctx); if (message != null) showProgressDialog(message); } @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); if (which == DialogInterface.BUTTON_POSITIVE) execute(); } } private final class EventHelper extends BroadcastReceiver implements ServiceFactory.SpyCallback, ChannelListener, OnItemClickListener { @Override public void handleMessage(int type, int status, Object obj) { ActivityManageP2P.this.handleMessage(type, status, obj); } @Override public void onReceive(Context context, Intent intent) { ActivityManageP2P.this.handleBroadcast(intent); } @Override public void onChannelDisconnected() { ActivityManageP2P.this.onChannelDisconnected(); } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { ActivityManageP2P.this.handlePeerListClick(position); } } private final IntentFilter getWiFiP2PIntentFilter() { final IntentFilter ret = new IntentFilter(); ret.addAction(WIFI_P2P_STATE_CHANGED_ACTION); ret.addAction(WIFI_P2P_CONNECTION_CHANGED_ACTION); ret.addAction(WIFI_P2P_PEERS_CHANGED_ACTION); ret.addAction(WIFI_P2P_THIS_DEVICE_CHANGED_ACTION); return ret; } }
0antwei-nfcsop
src/com/sinpo/nfcspy/ActivityManageP2P.java
Java
gpl3
9,589
/* NFC Spy is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. NFC Spy is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Wget. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 */ package com.sinpo.nfcspy; import java.lang.Thread.UncaughtExceptionHandler; import android.app.Application; import android.content.res.XmlResourceParser; public final class ThisApplication extends Application implements UncaughtExceptionHandler { final static int PRIORITY_HIGH = android.os.Process.THREAD_PRIORITY_URGENT_AUDIO; final static int PRIORITY_NORMAL = android.os.Process.THREAD_PRIORITY_FOREGROUND; final static int PRIORITY_LOW = android.os.Process.THREAD_PRIORITY_DEFAULT; @Override public void uncaughtException(Thread thread, Throwable ex) { System.exit(0); } @Override public void onCreate() { super.onCreate(); //Thread.setDefaultUncaughtExceptionHandler(this); if (getCurrentThreadPriority() > PRIORITY_NORMAL) setCurrentThreadPriority(PRIORITY_NORMAL); instance = this; } static int getCurrentThreadPriority() { try { int tid = android.os.Process.myTid(); return android.os.Process.getThreadPriority(tid); } catch (Exception e) { return PRIORITY_LOW; } } static void setCurrentThreadPriority(int priority) { try { int tid = android.os.Process.myTid(); android.os.Process.setThreadPriority(tid, priority); } catch (Exception e) { } } static String name() { return getStringResource(R.string.app_name); } static String version() { try { return instance.getPackageManager().getPackageInfo( instance.getPackageName(), 0).versionName; } catch (Exception e) { return "1.0"; } } static int getColorResource(int resId) { return instance.getResources().getColor(resId); } static String getStringResource(int resId) { return instance.getString(resId); } static XmlResourceParser getXmlResource(int resId) { return instance.getResources().getXml(resId); } private static ThisApplication instance; }
0antwei-nfcsop
src/com/sinpo/nfcspy/ThisApplication.java
Java
gpl3
2,480
/* NFC Spy is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. NFC Spy is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Wget. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 */ package com.sinpo.nfcspy; import static com.sinpo.nfcspy.ServiceFactory.MSG_P2P_CONNECT; import static com.sinpo.nfcspy.ServiceFactory.MSG_P2P_DISCONN; import static com.sinpo.nfcspy.ServiceFactory.STA_FAIL; import static com.sinpo.nfcspy.ServiceFactory.STA_P2P_ACCEPT; import static com.sinpo.nfcspy.ServiceFactory.STA_P2P_CLIENT; import static com.sinpo.nfcspy.ServiceFactory.STA_SUCCESS; import static com.sinpo.nfcspy.ThisApplication.PRIORITY_HIGH; import static com.sinpo.nfcspy.ThisApplication.setCurrentThreadPriority; import java.io.BufferedOutputStream; import java.io.Closeable; import java.io.DataInputStream; import java.io.DataOutputStream; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException; final class WiFiP2PSocket extends Thread { static final int BUF_SIZE = 512; ServerSocket server; Socket client; private ServiceFactory.SpyCallback callback; private DataInputStream iStream; private DataOutputStream oStream; WiFiP2PSocket(ServiceFactory.SpyCallback callback) { this.callback = callback; } synchronized boolean isConnected() { if (client == null) return false; return (server != null) ? server.isBound() : client.isConnected(); } boolean sendData(int type, byte[] data) { if (data != null && data.length > 0 && oStream != null) { try { oStream.writeInt(type); oStream.writeInt(data.length); oStream.write(data); oStream.flush(); return true; } catch (Exception e) { return false; } } return false; } synchronized void close() { iStream = null; oStream = null; try { if (client != null && !client.isClosed()) client.close(); } catch (Throwable e) { } client = null; try { if (server != null && !server.isClosed()) server.close(); } catch (Throwable e) { } server = null; } @Override public void run() { synchronized (this) { notifyAll(); } setCurrentThreadPriority(PRIORITY_HIGH); try { iStream = new DataInputStream(client.getInputStream()); oStream = new DataOutputStream(new BufferedOutputStream( client.getOutputStream(), BUF_SIZE)); while (true) { int type = iStream.readInt(); int len = iStream.readInt(); byte[] data = new byte[len]; iStream.readFully(data); callback.handleMessage(type, STA_SUCCESS, data); } } catch (Exception e) { } finally { close(); callback.handleMessage(MSG_P2P_DISCONN, STA_SUCCESS, null); } } } final class SocketConnector extends Thread { private final ServiceFactory.SpyCallback callback; final WiFiP2PManager context; SocketConnector(WiFiP2PManager ctx, ServiceFactory.SpyCallback cb) { callback = cb; context = ctx; } @Override public void run() { final WiFiP2PManager ctx = context; ctx.closeSocket(); WiFiP2PSocket p2p = new WiFiP2PSocket(callback); ctx.p2pSocket = p2p; Socket client = null; ServerSocket server = null; try { if (ctx.isGroupOwner) { fireCallback(STA_P2P_ACCEPT); server = new ServerSocket(WiFiP2PManager.PORT); p2p.server = server; client = server.accept(); p2p.client = client; } else { fireCallback(STA_P2P_CLIENT); server = null; p2p.server = server; client = new Socket(); p2p.client = client; client.bind(null); client.connect(new InetSocketAddress(ctx.groupOwnerAddress, WiFiP2PManager.PORT), 8000); } } catch (Exception e) { safeClose(client); client = null; p2p.client = null; safeClose(server); p2p.server = null; ctx.p2pSocket = null; } if (client != null && client.isConnected()) { try { tuneupSocket(client); p2p.start(); synchronized (p2p) { p2p.wait(); } fireCallback(STA_SUCCESS); } catch (Exception e) { fireCallback(STA_FAIL); } } else { fireCallback(STA_FAIL); } } protected void fireCallback(int sta) { callback.handleMessage(MSG_P2P_CONNECT, sta, null); } private static void tuneupSocket(Socket skt) throws SocketException { skt.setTcpNoDelay(true); skt.setTrafficClass(0x04 | 0x10); if (skt.getSendBufferSize() < WiFiP2PSocket.BUF_SIZE) skt.setSendBufferSize(WiFiP2PSocket.BUF_SIZE); if (skt.getReceiveBufferSize() < WiFiP2PSocket.BUF_SIZE) skt.setReceiveBufferSize(WiFiP2PSocket.BUF_SIZE); } private static void safeClose(Closeable obj) { try { if (obj != null) obj.close(); } catch (Throwable e) { } } }
0antwei-nfcsop
src/com/sinpo/nfcspy/WiFiP2PSocket.java
Java
gpl3
5,134
/* NFC Spy is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. NFC Spy is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Wget. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 */ package com.sinpo.nfcspy; import static de.robv.android.xposed.XposedHelpers.findAndHookMethod; import static de.robv.android.xposed.XposedHelpers.findField; import de.robv.android.xposed.IXposedHookLoadPackage; import de.robv.android.xposed.XC_MethodHook; import de.robv.android.xposed.callbacks.XC_LoadPackage.LoadPackageParam; public final class XposedModApduRouting implements IXposedHookLoadPackage { @Override public void handleLoadPackage(LoadPackageParam pkg) throws Throwable { if ("com.android.nfc".equals(pkg.packageName)) { final String CLASS = "com.android.nfc.cardemulation.HostEmulationManager"; final String METHOD = "findSelectAid"; try { findAndHookMethod(CLASS, pkg.classLoader, METHOD, byte[].class, findSelectAidHook); } catch (Exception e) { } } } private final static String AID_NFCSPY = "F04E4643535059"; private final XC_MethodHook findSelectAidHook = new XC_MethodHook() { @Override protected void beforeHookedMethod(MethodHookParam param) throws Throwable { final byte[] data = (byte[]) param.args[0]; final int len = data.length; if (data != null && len > 0) { try { final Object THIS = param.thisObject; // static final int STATE_W4_SELECT = 1; if (findField(THIS.getClass(), "mState").getInt(THIS) == 1) param.setResult(AID_NFCSPY); else // just bypass orgin call; param.setResult(null); } catch (Exception e) { } } } }; }
0antwei-nfcsop
src/com/sinpo/nfcspy/XposedModApduRouting.java
Java
gpl3
2,130
/* NFC Spy is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. NFC Spy is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Wget. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 */ package com.sinpo.nfcspy; import java.util.ArrayList; import android.os.Build; import android.text.Spannable; import android.text.SpannableString; import android.text.TextUtils; import android.text.format.Time; import android.text.style.ForegroundColorSpan; final class Logger { static CharSequence fmtHeader(CharSequence notes) { final StringBuilder header = new StringBuilder(); final String CMT = "## "; final Time time = new Time(); time.setToNow(); header.append(CMT).append(ThisApplication.name()).append(" Log File v") .append(ThisApplication.version()).append('\n'); header.append(CMT).append("System: Android ") .append(Build.VERSION.RELEASE).append(", ").append(Build.BRAND) .append(' ').append(Build.MODEL).append('\n'); header.append(CMT).append("DateTime: ").append(fmtDate(time)) .append(' ').append(fmtTime(time)).append('\n'); header.append(CMT).append('\n'); if (!TextUtils.isEmpty(notes)) { String[] lines = notes.toString().split("\\n"); for (String line : lines) header.append(CMT).append(line).append('\n'); header.append(CMT).append('\n'); } header.append('\n'); return header; } static CharSequence fmtChatIn(CharSequence msg) { return fmt(R.color.sta_chat_in, fmt(">> %s %s", now(), msg)); } static CharSequence fmtChatOut(CharSequence msg) { return fmt(R.color.sta_chat_out, fmt("<< %s %s", now(), msg)); } static CharSequence fmtMsg(String fm, Object... args) { return fmt(R.color.sta_msg, fmt("!!!! %s %s", now(), fmt(fm, args))); } static CharSequence fmtInfo(String fm, Object... args) { return fmt(R.color.sta_info, fmt("## %s %s", now(), fmt(fm, args))); } static CharSequence fmtWarn(String fm, Object... args) { return fmt(R.color.sta_warn, fmt("!!!! %s %s", now(), fmt(fm, args))); } static CharSequence fmtError(String fm, Object... args) { return fmt(R.color.sta_error, fmt("!!!! %s %s", now(), fmt(fm, args))); } static CharSequence fmtApdu(int delay, boolean isCmd, byte[] apdu) { long stamp = System.currentTimeMillis(); return fmtApdu(currentCardId, stamp, delay, false, isCmd, apdu); } static CharSequence fmtApdu(String id, long stamp, long delay, boolean isHCE, boolean isCmd, byte[] raw) { final StringBuilder info = apduFormatter; info.setLength(0); final CharSequence hex, cmt; if (raw == null || raw.length == 0) { if (raw == ATTACH_MARKER) return fmtNfcAttachMessage(id, stamp); if (raw == DEACTIVE_MARKER) return fmtHceDeactivatedMessage(stamp); hex = "<NULL>"; cmt = "No Data"; } else { hex = toHexString(raw, 0, raw.length); cmt = ApduParser.parse(isCmd, raw); } final Time tm = new Time(); tm.set(stamp); info.append('[').append(isCmd ? 'C' : 'R').append(' '); info.append(id).append(']').append(' '); info.append(fmtTime(tm)).append(' ').append(hex).append(' '); info.append(cmt).append(' ').append(isHCE ? '+' : '~'); if (delay < 0 || delay > MAX_APDUDELAY_MS) info.append('?'); else info.append(delay); info.append('m').append('s'); return fmt(isCmd ? R.color.sta_apdu_in : R.color.sta_apdu_out, info); } static CharSequence fmtNfcAttachMessage(String cardId, long stamp) { Time time = new Time(); time.set(stamp); return fmt( R.color.sta_msg, fmt(ThisApplication .getStringResource(R.string.event_nfc_attach), fmtTime(time), cardId, fmtDate(time))); } static CharSequence fmtHceDeactivatedMessage(long stamp) { Time time = new Time(); time.set(stamp); return fmt( ThisApplication.getStringResource(R.string.status_deactivated), fmtTime(time), fmtDate(time)); } static CharSequence fmt(int colorResId, CharSequence msg) { final int color = ThisApplication.getColorResource(colorResId); final SpannableString ret = new SpannableString(msg); final ForegroundColorSpan span = new ForegroundColorSpan(color); ret.setSpan(span, 0, msg.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE); return ret; } static CharSequence fmt(String fm, Object... args) { return String.format(fm, args); } static String now() { Time time = new Time(); time.setToNow(); return fmtTime(time); } static String fmtDate(Time tm) { return String.format("%04d-%02d-%02d", tm.year, tm.month + 1, tm.monthDay); } static String fmtTime(Time tm) { return String.format("%02d:%02d:%02d", tm.hour, tm.minute, tm.second); } static String toHexString(byte[] d, int s, int n) { final char[] ret = new char[n * 2]; final int e = s + n; int x = 0; for (int i = s; i < e; ++i) { final byte v = d[i]; ret[x++] = HEX[0x0F & (v >> 4)]; ret[x++] = HEX[0x0F & v]; } return new String(ret); } private final static byte[] ATTACH_MARKER = new byte[0]; private final static byte[] DEACTIVE_MARKER = new byte[0]; private final static char[] HEX = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; static void logNfcAttach(String cardId) { currentCardId = cardId; logApdu(System.currentTimeMillis(), true, true, ATTACH_MARKER); } static void logHceDeactive() { logApdu(System.currentTimeMillis(), true, true, DEACTIVE_MARKER); } static long logApdu(long stamp, boolean isHCE, boolean isCmd, byte[] apdu) { ApduItem it = new ApduItem(currentCardId, stamp, isHCE, isCmd, apdu); if (isFull()) apduLogs.set(cursor, it); else apduLogs.add(it); if (++cursor == MAX_LOGS) cursor = 0; return it.delay; } static void clearCachedLogs() { apduLogs.clear(); cursor = 0; } static int getCachedLogsCount() { return apduLogs.size(); } static CharSequence getCachedLog(int index) { if (isFull()) index = (index + cursor - 1) % MAX_LOGS; ApduItem i = apduLogs.get(index); return fmtApdu(i.cardId, i.timestamp, i.delay, i.isHCE, i.isCmd, i.apdu); } static String getCurrentLogFileName() { Time t = new Time(); t.setToNow(); return String.format("nfcspy_%04d%02d%02d_%02d%02d%02d.log", t.year, t.month + 1, t.monthDay, t.hour, t.minute, t.second); } static void setCurrentCardId(String id) { currentCardId = id; } static void open() { ApduParser.init(); } private static boolean isFull() { return apduLogs.size() == MAX_LOGS; } private static final long MAX_APDUDELAY_MS = 1999; private static final int MAX_LOGS = 512; private static int cursor = 0; private static String currentCardId = ""; private static final StringBuilder apduFormatter = new StringBuilder(); private static final ArrayList<ApduItem> apduLogs = new ArrayList<ApduItem>( MAX_LOGS); private static final class ApduItem { private static long lastApduStamp = 0; ApduItem(String id, long stamp, boolean isHCE, boolean isCmd, byte[] raw) { this.cardId = id; this.isHCE = isHCE; this.isCmd = isCmd; this.apdu = raw; this.timestamp = stamp; this.delay = stamp - lastApduStamp; lastApduStamp = stamp; } final byte[] apdu; final String cardId; final boolean isHCE; final boolean isCmd; final long timestamp; final long delay; } }
0antwei-nfcsop
src/com/sinpo/nfcspy/Logger.java
Java
gpl3
7,719
/* NFC Spy is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. NFC Spy is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Wget. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 */ package com.sinpo.nfcspy; import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT; import static org.xmlpull.v1.XmlPullParser.END_TAG; import static org.xmlpull.v1.XmlPullParser.START_TAG; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import android.content.res.XmlResourceParser; final class ApduParser { static String parse(boolean isCmd, byte[] apdu) { if (isCmd) { return CMDS.search(0, apdu).name(); } else { final int len = apdu.length; if (len > 1) return SWS.search(0, apdu[len - 2], apdu[len - 1]).name(); } return ""; } static void init() { if (CMDS != null && SWS != null) return; final XmlResourceParser xml = ThisApplication .getXmlResource(R.xml.apdu7816); try { // START__DOCUMENT xml.next(); if (xml.next() == START_TAG && "apdu".equalsIgnoreCase(xml.getName())) { while (xml.next() != END_DOCUMENT) { Apdu7816 cmds = readTag(Apdu7816.CMDS.class, xml); if (cmds != null) { CMDS = cmds; continue; } Apdu7816 sws = readTag(Apdu7816.SWS.class, xml); if (sws != null) { SWS = sws; continue; } break; } } } catch (Exception e) { } finally { if (xml != null) xml.close(); } if (CMDS == null) CMDS = new Apdu7816.CMDS(); if (SWS == null) SWS = new Apdu7816.SWS(); } @SuppressWarnings("unchecked") static Apdu7816 readTag(Class<? extends Apdu7816> clazz, XmlResourceParser xml) throws Exception { if (xml.getEventType() != START_TAG) return null; final String thisTag = xml.getName(); final String testTag = (String) clazz.getDeclaredField("TAG").get(null); if (!thisTag.equalsIgnoreCase(testTag)) return null; final String apduName = xml.getAttributeValue(null, "name"); final String apduVal = xml.getAttributeValue(null, "val"); final ArrayList<Apdu7816> list = new ArrayList<Apdu7816>(); final Object child = clazz.getDeclaredField("SUB").get(null); while (true) { int event = xml.next(); if (event == END_DOCUMENT) break; if (event == END_TAG && thisTag.equalsIgnoreCase(xml.getName())) break; if (child != null) { Apdu7816 apdu = readTag((Class<? extends Apdu7816>) child, xml); if (apdu != null) list.add(apdu); } } final Apdu7816[] sub; if (list.isEmpty()) sub = null; else sub = list.toArray(new Apdu7816[list.size()]); final Apdu7816 ret = clazz.newInstance(); ret.init(parseValue(apduVal), apduName, sub); return ret; } private static byte parseValue(String strVal) { if (strVal != null && strVal.length() > 0) { try { return (byte) (Integer.parseInt(strVal, 16) & 0xFF); } catch (Exception e) { } } return (byte) 0; } private static Apdu7816 CMDS; private static Apdu7816 SWS; @SuppressWarnings("unused") private static class Apdu7816 implements Comparator<Apdu7816> { final static class CMDS extends Apdu7816 { final static String TAG = "cmds"; final static Object SUB = CLS.class; } final static class SWS extends Apdu7816 { final static String TAG = "sws"; final static Object SUB = SW1.class; } final static class CLS extends Apdu7816 { final static String TAG = "class"; final static Object SUB = INS.class; int compare(Apdu7816 apdu) { if (apdu.getClass() != CLS.class) { final byte val = this.val; final byte oth = apdu.val; if (val == 0) { // class 0XXX XXXXb if ((oth | 0x7F) == 0x7F) return 0; } else if (val == 1) { // class 1XXX XXXXb if ((oth & 0x80) == 0x80) return 0; } else { // class as val if (val == oth) return 0; } } return super.compare(apdu); } } final static class INS extends Apdu7816 { final static String TAG = "ins"; final static Object SUB = P1.class; } final static class P1 extends Apdu7816 { final static String TAG = "p1"; final static Object SUB = P2.class; } final static class P2 extends Apdu7816 { final static String TAG = "p2"; final static Object SUB = null; } final static class SW1 extends Apdu7816 { final static String TAG = "sw1"; final static Object SUB = SW2.class; } final static class SW2 extends Apdu7816 { final static String TAG = "sw2"; final static Object SUB = null; } int compare(Apdu7816 apdu) { return (this.val & 0xFF) - (apdu.val & 0xFF); } String name() { return name == null ? "" : name; } Apdu7816 search(int start, byte... val) { final Apdu7816[] sub = this.sub; if (sub != null && start < val.length) { Apdu7816 cp = comparator; cp.val = val[start]; int i = Arrays.binarySearch(sub, cp, cp); if (i >= 0) return sub[i].search(++start, val); } return this; } @Override public int compare(Apdu7816 lhs, Apdu7816 rhs) { return lhs.compare(rhs); } void init(byte val, String name, Apdu7816[] sub) { this.val = val; this.name = name; this.sub = sub; if (sub != null) Arrays.sort(sub, comparator); } protected Apdu7816[] sub; protected byte val; protected String name; protected static Apdu7816 comparator = new Apdu7816(); } }
0antwei-nfcsop
src/com/sinpo/nfcspy/ApduParser.java
Java
gpl3
5,878
/* NFC Spy is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. NFC Spy is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Wget. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 */ package com.sinpo.nfcspy; import static com.sinpo.nfcspy.ServiceFactory.ERR_APDU_CMD; import static com.sinpo.nfcspy.ServiceFactory.ERR_APDU_RSP; import static com.sinpo.nfcspy.ServiceFactory.MSG_CHAT_RECV; import static com.sinpo.nfcspy.ServiceFactory.MSG_CHAT_SEND; import static com.sinpo.nfcspy.ServiceFactory.MSG_HCE_APDU_CMD; import static com.sinpo.nfcspy.ServiceFactory.MSG_HCE_APDU_RSP; import static com.sinpo.nfcspy.ServiceFactory.MSG_HCE_ATTACH; import static com.sinpo.nfcspy.ServiceFactory.MSG_HCE_DEACTIVATED; import static com.sinpo.nfcspy.ServiceFactory.MSG_HCE_DETTACH; import static com.sinpo.nfcspy.ServiceFactory.MSG_P2P_CONNECT; import static com.sinpo.nfcspy.ServiceFactory.MSG_P2P_DISCONN; import static com.sinpo.nfcspy.ServiceFactory.MSG_P2P_INIT; import static com.sinpo.nfcspy.ServiceFactory.MSG_P2P_SOCKET; import static com.sinpo.nfcspy.ServiceFactory.MSG_SERVER_VER; import static com.sinpo.nfcspy.ServiceFactory.STA_ERROR; import static com.sinpo.nfcspy.ServiceFactory.STA_FAIL; import static com.sinpo.nfcspy.ServiceFactory.STA_NOTCARE; import static com.sinpo.nfcspy.ServiceFactory.STA_P2P_ACCEPT; import static com.sinpo.nfcspy.ServiceFactory.STA_P2P_CLIENT; import static com.sinpo.nfcspy.ServiceFactory.STA_SUCCESS; import java.io.File; import java.io.FileOutputStream; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.os.Messenger; import android.text.ClipboardManager; import android.text.Html; import android.text.TextUtils; import android.text.method.LinkMovementMethod; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ArrayAdapter; import android.widget.CheckBox; import android.widget.EditText; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; public class ActivityMain extends ActivityBase implements Handler.Callback { public ActivityMain() { inbox = new Messenger(new Handler(this)); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); messages = new ArrayAdapter<CharSequence>(this, R.layout.listitem_message); ((ListView) findViewById(R.id.list)).setAdapter(messages); messageView = (TextView) findViewById(R.id.txtChatLine); nfc = new NfcManager(this); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_copy: copyLogs(); return true; case R.id.action_save: saveLogs(); return true; case R.id.action_share: shareLogs(); return true; case R.id.action_settings: startActivity(new Intent(this, ActivityManageP2P.class)); return true; case R.id.action_viewlogs: showHCELogs(); return true; case R.id.action_clearlogs: clearHCELogs(); return true; case R.id.action_about: showHelp(); return true; default: return super.onOptionsItemSelected(item); } } public void startServer(View ignore) { if (!nfc.isEnabled()) { messages.add(Logger.fmtError(getString(R.string.status_no_nfc))); return; } if (!WiFiP2PManager.isWiFiEnabled(this)) { messages.add(Logger.fmtError(getString(R.string.status_no_wifi))); return; } if (!NfcManager.hasHCE()) messages.add(Logger.fmtWarn(getString(R.string.status_no_hce))); ServiceFactory.startServer(this, inbox); } public void stopServer(View ignore) { ServiceFactory.stopServer(this); } public void clearList(View ignore) { messages.clear(); } public void enableHighSpeed(View v) { ServiceFactory.setHighSpeed2Server(this, ((CheckBox) v).isChecked()); } public void sendChatMessage(View ignore) { final String msg = messageView.getText().toString(); if (!TextUtils.isEmpty(msg)) ServiceFactory.sendChatMessage2Server(this, msg); } @Override protected void onResume() { super.onResume(); nfc.onResume(); } @Override protected void onPause() { nfc.onPause(); super.onPause(); } @Override protected void onDestroy() { nfc = null; super.onDestroy(); } @Override protected void onNewIntent(Intent intent) { ServiceFactory.setTag2Server(this, intent); } @Override public boolean handleMessage(Message msg) { switch (msg.what) { case MSG_HCE_APDU_CMD: case MSG_HCE_APDU_RSP: printHceApdu(msg); break; case MSG_HCE_ATTACH: printNfcAttachMessage(msg); break; case MSG_HCE_DEACTIVATED: printHceDeactivatedMessage(); break; case MSG_HCE_DETTACH: printStatusMessage(R.string.event_nfc_lost, STA_ERROR, 0); break; case MSG_CHAT_SEND: case MSG_CHAT_RECV: printChatMessage(msg); break; case MSG_P2P_SOCKET: printStatusMessage(R.string.status_getaddr, msg.arg1, msg.arg2); break; case MSG_P2P_CONNECT: printStatusMessage(R.string.status_connect, msg.arg1, msg.arg2); break; case MSG_P2P_DISCONN: printStatusMessage(R.string.status_disconn, msg.arg1, msg.arg2); break; case MSG_P2P_INIT: printStatusMessage(R.string.status_init, msg.arg1, msg.arg2); break; case MSG_SERVER_VER: printVersionInfo(msg); break; default: return false; } return true; } private void printStatusMessage(int descId, int status, int error) { final CharSequence desc; if (status == STA_NOTCARE) { desc = Logger.fmtInfo(getString(descId)); } else if (status == STA_SUCCESS) { String sta = getString(R.string.status_success); desc = Logger.fmtInfo("%s%s", getString(descId), sta); } else if (status == STA_FAIL) { String sta = getString(R.string.status_failure); desc = Logger.fmtError("%s%s", getString(descId), sta); } else if (status == STA_ERROR) { desc = Logger.fmtError(getString(descId)); } else { if (status == STA_P2P_ACCEPT) descId = R.string.status_p2p_accept; else if (status == STA_P2P_CLIENT) descId = R.string.status_p2p_client; String sta = getString(R.string.status_waitting); desc = Logger.fmtWarn("%s %s", getString(descId), sta); } messages.add(desc); } private void printChatMessage(Message msg) { byte[] raw = ServiceFactory.extractDataFromMessage(msg); if (raw != null && raw.length > 0) { String txt = new String(raw); if (MSG_CHAT_SEND == msg.what) { messages.add(Logger.fmtChatOut(txt)); messageView.setText(null); } else { messages.add(Logger.fmtChatIn(txt)); } } } private void printVersionInfo(Message msg) { byte[] raw = ServiceFactory.extractDataFromMessage(msg); if (raw != null && raw.length > 0) { String peer = new String(raw); String me = ThisApplication.version(); if (me.equals(peer)) { String fmt = getString(R.string.event_p2p_version); messages.add(Logger.fmtInfo(fmt, me)); } else { String fmt = getString(R.string.event_p2p_version2); messages.add(Logger.fmtWarn(fmt, peer, me)); } } } private void printNfcAttachMessage(Message msg) { byte[] raw = ServiceFactory.extractDataFromMessage(msg); if (raw != null && raw.length > 0) { long stamp = System.currentTimeMillis(); messages.add(Logger.fmtNfcAttachMessage(new String(raw), stamp)); } } private void printHceDeactivatedMessage() { long stamp = System.currentTimeMillis(); messages.add(Logger.fmtHceDeactivatedMessage(stamp)); } private void printHceApdu(Message msg) { byte[] apdu = ServiceFactory.extractDataFromMessage(msg); if (apdu != null && apdu.length > 0) { boolean isCmd = (MSG_HCE_APDU_CMD == msg.what); messages.add(Logger.fmtApdu(msg.arg2, isCmd, apdu)); } else { String hint; if (STA_ERROR == msg.arg1) { if (ERR_APDU_CMD == msg.arg2) hint = getString(R.string.event_p2p_connect); else if (ERR_APDU_RSP == msg.arg2) hint = getString(R.string.event_nfc_rsp); else hint = getString(R.string.event_p2p_connect); } else { hint = getString(R.string.event_nfc_lost); } messages.add(Logger.fmtError(hint)); } } private void shareLogs() { CharSequence logs = getAllLogs(); if (!TextUtils.isEmpty(logs)) { Intent intent = new Intent(); intent.setAction(Intent.ACTION_SEND); intent.putExtra(Intent.EXTRA_TEXT, logs); intent.setType("text/plain"); startActivity(intent); } } private void copyLogs() { CharSequence logs = getAllLogs(); if (!TextUtils.isEmpty(logs)) { ((ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE)) .setText(logs); Toast.makeText(this, R.string.event_log_copy, Toast.LENGTH_LONG) .show(); } } private void showHCELogs() { int n = Logger.getCachedLogsCount(); for (int i = 0; i < n; ++i) messages.add(Logger.getCachedLog(i)); } private void clearHCELogs() { Logger.clearCachedLogs(); } private void showHelp() { CharSequence title = Logger.fmt("%s v%s", ThisApplication.name(), ThisApplication.version()); CharSequence info = Html.fromHtml(getString(R.string.info_about)); TextView tv = (TextView) getLayoutInflater().inflate( R.layout.dialog_message, null); tv.setLinksClickable(true); tv.setMovementMethod(LinkMovementMethod.getInstance()); tv.setText(info); new AlertDialog.Builder(this, AlertDialog.THEME_HOLO_LIGHT) .setTitle(title).setView(tv) .setNeutralButton(R.string.action_ok, null).show(); } private void saveLogs() { CharSequence logs = getAllLogs(); if (!TextUtils.isEmpty(logs)) { View root = getLayoutInflater().inflate(R.layout.dialog_savelog, null); EditText name = (EditText) root.findViewById(R.id.file); name.setText(Logger.getCurrentLogFileName()); EditText note = (EditText) root.findViewById(R.id.note); SaveLogHelper helper = new SaveLogHelper(logs, name, note); new AlertDialog.Builder(this, AlertDialog.THEME_HOLO_LIGHT) .setTitle(R.string.action_save).setView(root) .setNegativeButton(R.string.action_cancel, helper) .setPositiveButton(R.string.action_ok, helper).show(); } } private CharSequence getAllLogs() { StringBuilder ret = new StringBuilder(); final ArrayAdapter<CharSequence> messages = this.messages; final int count = messages.getCount(); for (int i = 0; i < count; ++i) { if (i > 0) ret.append("\n\n"); ret.append(messages.getItem(i)); } return ret; } private static final class SaveLogHelper implements DialogInterface.OnClickListener { CharSequence logs; EditText nameView, noteView; SaveLogHelper(CharSequence logs, EditText name, EditText note) { this.logs = logs; this.nameView = name; this.noteView = note; } @Override public void onClick(DialogInterface dialog, int which) { if (which == DialogInterface.BUTTON_POSITIVE) saveLogs(); dialog.dismiss(); nameView = null; noteView = null; logs = null; } private void saveLogs() { String file = nameView.getText().toString(); if (TextUtils.isEmpty(file)) return; Context ctx = nameView.getContext(); String msg; try { File root = Environment.getExternalStorageDirectory(); File path = new File(root, "/nfcspy/logs"); File logf = new File(path, file); file = logf.getAbsolutePath(); path.mkdirs(); FileOutputStream os = new FileOutputStream(file); CharSequence note = Logger.fmtHeader(noteView.getText()); if (!TextUtils.isEmpty(note)) os.write(note.toString().getBytes()); os.write(logs.toString().getBytes()); os.close(); msg = ctx.getString(R.string.event_log_save); } catch (Exception e) { msg = ctx.getString(R.string.event_log_notsave); } Toast.makeText(ctx, Logger.fmt(msg, file), Toast.LENGTH_LONG) .show(); } } private NfcManager nfc; private Messenger inbox; private ArrayAdapter<CharSequence> messages; private TextView messageView; }
0antwei-nfcsop
src/com/sinpo/nfcspy/ActivityMain.java
Java
gpl3
12,696
/* NFC Spy is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. NFC Spy is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Wget. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 */ package com.sinpo.nfcspy; import static android.content.Context.WIFI_P2P_SERVICE; import static com.sinpo.nfcspy.ServiceFactory.STA_P2P_INITED; import static com.sinpo.nfcspy.ServiceFactory.STA_P2P_UNINIT; import java.net.InetAddress; import android.content.Context; import android.net.wifi.WifiManager; import android.net.wifi.p2p.WifiP2pManager; import android.net.wifi.p2p.WifiP2pManager.Channel; import android.net.wifi.p2p.WifiP2pManager.ChannelListener; final class WiFiP2PManager { // TODO maybe choooooose by setting panel final static int PORT = 2013; static boolean isWiFiEnabled(Context ctx) { return ((WifiManager) ctx.getSystemService(Context.WIFI_SERVICE)) .isWifiEnabled(); } WiFiP2PManager() { reset(); } void init(Context ctx, ChannelListener lsn) { wifip2p = (WifiP2pManager) ctx.getSystemService(WIFI_P2P_SERVICE); channel = wifip2p.initialize(ctx, ctx.getMainLooper(), lsn); if (wifip2p != null && channel != null) { isWifiP2pEnabled = true; status = STA_P2P_INITED; } else { isWifiP2pEnabled = false; status = STA_P2P_UNINIT; } } boolean isInited() { return status != STA_P2P_UNINIT; } boolean isConnected() { return (p2pSocket != null) && p2pSocket.isConnected(); } boolean sendData(int type, byte[] data) { return isConnected() ? p2pSocket.sendData(type, data) : false; } void closeSocket() { if (p2pSocket != null) { p2pSocket.close(); p2pSocket = null; } } void reset() { closeSocket(); peerName = null; groupOwnerAddress = null; isGroupOwner = false; isWifiP2pConnected = false; channel = null; status = STA_P2P_UNINIT; } String peerName; InetAddress groupOwnerAddress; boolean isGroupOwner; boolean isWifiP2pConnected; boolean isWifiP2pEnabled; WiFiP2PSocket p2pSocket = null; private int status; WifiP2pManager wifip2p; Channel channel; }
0antwei-nfcsop
src/com/sinpo/nfcspy/WiFiP2PManager.java
Java
gpl3
2,530
<?xml version='1.0' encoding='UTF-8' ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:p="http://primefaces.org/ui" xmlns:c="http://java.sun.com/jsp/jstl/core"> <ui:include src="elementos/contenidos/index.xhtml" /> Error 404 </html>
09012143a
trunk/jv3/web/error404.xhtml
HTML
gpl2
543
<ui:composition xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:h="http://java.sun.com/jsf/html"> <h:head> <title><h:outputText value="#{msg['sistema.nombre']}" /></title> <link type="text/css" href="recursos/estilos/acd.main.css" rel="stylesheet" /> <script type="text/javascript" src="recursos/scripts/jquery-1.8.2.js" ></script> <script type="text/javascript" src="recursos/scripts/acd.main.js" ></script> </h:head> <h:body> <ui:include src="../header.xhtml" /> <div class="body"> <center> <div class="inBody"> <div id="introImg" class="shadowBlue"> <ui:include src="login.xhtml" /> </div> </div> </center> </div> <ui:include src="../footer.xhtml" /> </h:body> </ui:composition>
09012143a
trunk/jv3/web/elementos/contenidos/index.xhtml
HTML
gpl2
890
<ui:composition xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:h="http://java.sun.com/jsf/html" xmlns:c="http://java.sun.com/jsp/jstl/core"> <c:if test="#{!sessionScope['usuario'].valid}"> <div id="divLogin"> <div> <h:outputText value="#{msg['lbl.login']}" />: </div> <form id="formLogin"><br/> <h:outputText value="#{msg['lbl.username']}:" /><br/> <input type="text" placeholder="" id="username" /><br/> <h:outputText value="#{msg['lbl.pass']}:" /> <input type="password" placeholder="" id="pass"/><br/> <h:outputText value="#{msg['lbl.loginError']}" id="msgErrorLogin" /> <br/> <button class="blanco"> <h:outputText value="#{msg['lbl.ingreso']}" /> </button><br/><br/> </form> <h:outputLink value="#{modulo['login']}" class="linkBlanco" > <h:outputText value="Crear una cuenta" /> </h:outputLink> </div> </c:if> </ui:composition>
09012143a
trunk/jv3/web/elementos/contenidos/login.xhtml
HTML
gpl2
1,187
<ui:composition xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:h="http://java.sun.com/jsf/html" xmlns:c="http://java.sun.com/jsp/jstl/core" xmlns:f="http://java.sun.com/jsf/core"> <div class="footer"> <div style="width:977px; margin: auto;"> <hr style="height:3px; background-color:#444; border: solid 0px #444;"/> <span style="color:#444; font-size:12px;"> <h:outputText value="#{msg['sistema.nombre']}" /> &#169; <h:outputText value="#{sistema.year}" /> <h:outputText value=" by #{msg['autor']}" /></span> </div> </div> </ui:composition>
09012143a
trunk/jv3/web/elementos/footer.xhtml
HTML
gpl2
716
<ui:composition xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:h="http://java.sun.com/jsf/html" xmlns:c="http://java.sun.com/jsp/jstl/core" xmlns:f="http://java.sun.com/jsf/core" xmlns:p="http://primefaces.org/ui"> <h:head> <title><h:outputText value="#{msg['sistema.nombre']}" /></title> <link type="text/css" href="recursos/estilos/acd.main.css" rel="stylesheet" /> <script type="text/javascript" src="recursos/scripts/acd.main.js" ></script> <style> .tdClass1{width:150px; padding:5px; vertical-align: middle; } .tdClass2{width:180px; padding:5px; vertical-align: middle; } .tdClass3{ padding:5px; vertical-align: middle;} .tdClassA{} .tdClassB{width:100%} </style> </h:head> <h:body> <ui:include src="../header.xhtml" /> <div class="body"> <center> <div class="inBody" style="font-size: 12px;"> <h:form id="form"> <p:panel header="#{msg['usuario.nuevoUsuario']}" id="panel" style="text-align:left;"> <p:messages id="messages" /> <h:panelGrid columns="2" style="width:100%;" columnClasses="tdClassA, tdClassB" > <img src="recursos/imagenes/usuario.jpg" style="width:250px;" /> <h:panelGrid columns="4" id="matchGrid" style="width:100%; border:solid 1px silver; border-radius: 10px;" columnClasses="tdClass1,tdClass2,tdClass3"> <h:outputLabel for="nombre" id="nombreLbl" value="#{msg['usuario.nombre']} *" /> <p:inputText id="nombre" value="#{usuariosBean.nombre}" required="false" validatorMessage="nada" /> <h:outputText value="#{usuariosBean.msgNombre}" style="color:red;" /> <p:tooltip for="nombreLbl" value="Ejemplo: Juan Perez" showEffect="clip" hideEffect="clip" /> <h:outputLabel for="username" id="usernameLbl" value="Correo electrónico: *" /> <p:inputText id="username" value="#{usuariosBean.username}" required="false" /> <h:outputText value="#{usuariosBean.msgUsername}" style="color:red;" /> <p:tooltip for="usernameLbl" value="Ejemplo: jperez@kmail.com" showEffect="clip" hideEffect="clip" /> <h:outputLabel for="tipo" id="tipoLbl" value="Tipo de usuario" /> <p:selectOneMenu id="tipo" value="#{usuariosBean.tipo}" > <f:selectItems value="#{usuariosBean.tipos}" /> </p:selectOneMenu> <p:tooltip for="tipoLbl" value="Modalidad de participación en concursos" showEffect="clip" hideEffect="clip" /> <h:outputText /> <h:outputLabel for="pass1" id="pass1Lbl" value="#{msg['usuario.pass']} *" /> <p:password id="pass1" value="#{usuariosBean.pass1}" promptLabel="#{msg['usuario.ingresePass']}" weakLabel="#{msg['usuario.passInseguro']}" goodLabel="#{msg['usuario.passAceptable']}" strongLabel="#{msg['usuario.passRobusto']}" feedback="true" inline="true" /> <h:outputText value="#{usuariosBean.msgPass1}" style="color:red;" /> <p:tooltip for="pass1Lbl" value="Puede incluir letras, numeros y caracteres" showEffect="clip" hideEffect="clip" /> <h:outputLabel for="pass2" id="pass2Lbl" value="#{msg['usuario.confirmPass']} *" /> <p:password id="pass2" value="#{usuariosBean.pass2}" /> <h:outputText value="#{usuariosBean.msgPass2}" style="color:red;" /> <p:tooltip for="pass2Lbl" value="Confirme su contraseña" showEffect="clip" hideEffect="clip" /> </h:panelGrid> <h:outputText /> <p:commandButton value="Crear nueva cuenta de usuario" update="panel" id="ajax" icon="ui-icon-disk" actionListener="#{usuariosBean.guardarUsuario}" action="#{usuariosBean.guardarUsuario}" /> </h:panelGrid> </p:panel> </h:form> <br/> <div style="text-align:right;"> <form action="#{modulo.login}" method="GET"> <input type="hidden" name="modulo" value="usuarios" /> <input type="hidden" name="action" value="nuevo" /> <p:commandButton value="Regresar a la página principal" icon="ui-icon-arrowreturnthick-1-w" action="jv" /> </form> </div> <h:form> Opciones: <h:selectOneMenu value="#{usuariosBean.tipo}"> <f:selectItems value="#{usuariosBean.tipos}" /> <f:ajax render="opcionActual" /> </h:selectOneMenu><br/> <h:commandButton value="Mostrar" /> <br/> Opción seleccionada: <h:outputText id="opcionActual" value="#{usuariosBean.tipo}" /> </h:form> </div> </center> </div> <ui:include src="../footer.xhtml" /> </h:body> </ui:composition>
09012143a
trunk/jv3/web/elementos/usuarios/nuevoUsuario.xhtml
HTML
gpl2
6,051
<ui:composition xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:h="http://java.sun.com/jsf/html" xmlns:c="http://java.sun.com/jsp/jstl/core" xmlns:f="http://java.sun.com/jsf/core" xmlns:p="http://primefaces.org/ui"> <h:form id="test"> <p:dataTable id="dataTable" var="car" value="#{tableBean.carsSmall}" widgetVar="carsTable" emptyMessage="No cars found with given criteria" filteredValue="#{tableBean.filteredCars}"> <f:facet name="header"> <p:outputPanel> <h:outputText value="Search all fields:" /> <p:inputText id="globalFilter" onkeyup="carsTable.filter()" style="width:150px" /> </p:outputPanel> </f:facet> <p:column id="modelColumn" filterBy="#{car.model}" headerText="Model" footerText="contains" filterMatchMode="contains"> <h:outputText value="#{car.model}" /> </p:column> <p:column id="yearColumn" filterBy="#{car.year}" headerText="Year" footerText="startsWith"> <h:outputText value="#{car.year}" /> </p:column> <p:column id="colorColumn" filterBy="#{car.color}" headerText="Color" footerText="endsWith" filterMatchMode="endsWith"> <h:outputText value="#{car.color}" /> </p:column> </p:dataTable> </h:form> </ui:composition>
09012143a
trunk/jv3/web/elementos/concursos/default.xhtml
HTML
gpl2
1,584
<ui:composition xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:h="http://java.sun.com/jsf/html" xmlns:c="http://java.sun.com/jsp/jstl/core" xmlns:f="http://java.sun.com/jsf/core" xmlns:p="http://primefaces.org/ui"> <c:if test="#{!concursosBean.esNuevo}" > <h:form id="concursosUsuarios"> <p:tabView effect="fade" effectDuration="normal"> <p:tab title="Administradores"> <h:panelGrid columns="2" cellpadding="10"> <h:outputText value="The story begins as Don Vito Corleone, the head of a New York Mafia family, oversees his daughter's wedding. His beloved son Michael has just come home from the war, but does not intend to become part of his father's business. T hrough Michael's life the nature of the family business becomes clear. The business of the family is just like the head of the family, kind and benevolent to those who give respect, but given to ruthless violence whenever anything stands against the good of the family." /> </h:panelGrid> </p:tab> <p:tab title="Jueces"> <h:panelGrid columns="2" cellpadding="10"> <h:outputText value="Francis Ford Coppola's legendary continuation and sequel to his landmark 1972 film, The_Godfather, parallels the young Vito Corleone's rise with his son Michael's spiritual fall, deepening The_Godfather's depiction of the dark side of the American dream. In the early 1900s, the child Vito flees his Sicilian village for America after the local Mafia kills his family. Vito struggles to make a living, legally or illegally, for his wife and growing brood in Little Italy, killing the local Black Hand Fanucci after he demands his customary cut of the tyro's business. With Fanucci gone, Vito's communal stature grows."></h:outputText> </h:panelGrid> </p:tab> <p:tab title="Participantes"> <h:panelGrid columns="2" cellpadding="10"> <h:outputText value="Francis Ford Coppola's legendary continuation and sequel to his landmark 1972 film, The_Godfather, parallels the young Vito Corleone's rise with his son Michael's spiritual fall, deepening The_Godfather's depiction of the dark side of the American dream. In the early 1900s, the child Vito flees his Sicilian village for America after the local Mafia kills his family. Vito struggles to make a living, legally or illegally, for his wife and growing brood in Little Italy, killing the local Black Hand Fanucci after he demands his customary cut of the tyro's business. With Fanucci gone, Vito's communal stature grows."></h:outputText> </h:panelGrid> </p:tab> <p:tab title="Otros"> <h:panelGrid columns="2" cellpadding="10"> <h:outputText value="After a break of more than 15 years, director Francis Ford Coppola and writer Mario Puzo returned to the well for this third and final story of the fictional Corleone crime family. Two decades have passed, and crime kingpin Michael Corleone, now divorced from his wife Kay has nearly succeeded in keeping his promise that his family would one day be completely legitimate."></h:outputText> </h:panelGrid> </p:tab> </p:tabView> </h:form> </c:if> </ui:composition>
09012143a
trunk/jv3/web/elementos/concursos/usuarios.xhtml
HTML
gpl2
3,704
<ui:composition xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:h="http://java.sun.com/jsf/html" xmlns:c="http://java.sun.com/jsp/jstl/core" xmlns:f="http://java.sun.com/jsf/core" xmlns:p="http://primefaces.org/ui"> <c:if test="#{concursosBean.esNuevo}" > <h:form id="form"> <p:panel header="Nuevo concurso" id="panelCrear" style="text-align:left;"> <p:messages id="messages" /> <p:inputText id="idx" value="#{concursosBean.id}" style="display:none;" /> <h:panelGrid columns="2" style="width:100%;" columnClasses="tdClassA, tdClassB" > <img src="recursos/imagenes/usuario.jpg" style="width:250px;" /> <h:panelGrid columns="4" id="matchGrid" style="width:100%; border:solid 1px silver; border-radius: 10px;" columnClasses="tdClass1,tdClass2,tdClass3"> <h:outputLabel for="nombre" id="nombreLbl" value="Nombre del concurso *" /> <p:inputText id="nombre" value="#{concursosBean.nombre}" /> <h:outputText value="#{concursosBean.nombre}" style="color:red;" /> <p:tooltip for="nombreLbl" value="pendiente" showEffect="clip" hideEffect="clip" /> <h:outputLabel for="inicia" id="iniciaLbl" value="Fecha de inicio *" /> <p:calendar value="#{concursosBean.inicia}" pattern="MM/dd/yyyy HH:mm" locale="es" navigator="true" /> <h:outputText value="#{concursosBean.inicia}" style="color:red;" /> <p:tooltip for="iniciaLbl" value="pendiente" showEffect="clip" hideEffect="clip" /> <h:outputLabel for="finaliza" id="finalizaLbl" value="Fecha de fin *" /> <p:calendar value="#{concursosBean.finaliza}" pattern="MM/dd/yyyy HH:mm" /> <h:outputText value="#{concursosBean.finaliza}" style="color:red;" /> <p:tooltip for="finalizaLbl" value="pendiente" showEffect="clip" hideEffect="clip" /> <h:outputLabel for="publicidadInicia" id="publicidadIniciaLbl" value="Mostrar publicidad desde " /> <p:calendar value="#{concursosBean.publicidadInicio}" pattern="MM/dd/yyyy HH:mm" locale="es" navigator="true" /> <h:outputText value="#{concursosBean.inicia}" style="color:red;" /> <p:tooltip for="publicidadIniciaLbl" value="pendiente" showEffect="clip" hideEffect="clip" /> <h:outputLabel for="publicidadFin" id="publicidadFinLbl" value="Mostrar publicidad hasta*" /> <p:calendar value="#{concursosBean.publicidadFin}" pattern="MM/dd/yyyy HH:mm" /> <h:outputText value="#{concursosBean.publicidadFin}" style="color:red;" /> <p:tooltip for="publicidadFinLbl" value="pendiente" showEffect="clip" hideEffect="clip" /> </h:panelGrid> <h:outputText value=""/> <h1>Bases del concurso</h1> <h:outputText value=""/> <p:editor id="editor" value="#{concursosBean.convocatoria}" width="600"/> <h:outputText value="" style="color:red;" /> <p:commandButton value="Crear concurso de programación" update="panelCrear" id="ajax" icon="ui-icon-disk" action="#{concursosBean.guardar}" /> </h:panelGrid> <h:outputText value="" /> <div style="border:solid 0px red; height:20px;"></div> </p:panel> </h:form> </c:if> </ui:composition>
09012143a
trunk/jv3/web/elementos/concursos/nuevo.xhtml
HTML
gpl2
3,887
<ui:composition xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:h="http://java.sun.com/jsf/html" xmlns:c="http://java.sun.com/jsp/jstl/core" xmlns:f="http://java.sun.com/jsf/core" xmlns:p="http://primefaces.org/ui"> <c:if test="#{!concursosBean.esNuevo}" > <h:form> <p:tabView effect="fade" effectDuration="normal"> <p:tab title="Datos generales"> <h:panelGrid columns="2" cellpadding="10"> <!--<p:graphicImage value="/images/godfather/godfather1.jpg" /> --> <h:outputText value="The story begins as Don Vito Corleone, the head of a New York Mafia family, oversees his daughter's wedding. His beloved son Michael has just come home from the war, but does not intend to become part of his father's business. T hrough Michael's life the nature of the family business becomes clear. The business of the family is just like the head of the family, kind and benevolent to those who give respect, but given to ruthless violence whenever anything stands against the good of the family." /> </h:panelGrid> </p:tab> <p:tab title="Bases del concursos"> <h:panelGrid columns="2" cellpadding="10"> <!--<p:graphicImage value="/images/godfather/godfather2.jpg" /> --> <h:outputText value="Francis Ford Coppola's legendary continuation and sequel to his landmark 1972 film, The_Godfather, parallels the young Vito Corleone's rise with his son Michael's spiritual fall, deepening The_Godfather's depiction of the dark side of the American dream. In the early 1900s, the child Vito flees his Sicilian village for America after the local Mafia kills his family. Vito struggles to make a living, legally or illegally, for his wife and growing brood in Little Italy, killing the local Black Hand Fanucci after he demands his customary cut of the tyro's business. With Fanucci gone, Vito's communal stature grows."></h:outputText> </h:panelGrid> </p:tab> <p:tab title="Reactivos"> <h:panelGrid columns="2" cellpadding="10"> <!--<p:graphicImage value="/images/godfather/godfather2.jpg" /> --> <h:outputText value="Francis Ford Coppola's legendary continuation and sequel to his landmark 1972 film, The_Godfather, parallels the young Vito Corleone's rise with his son Michael's spiritual fall, deepening The_Godfather's depiction of the dark side of the American dream. In the early 1900s, the child Vito flees his Sicilian village for America after the local Mafia kills his family. Vito struggles to make a living, legally or illegally, for his wife and growing brood in Little Italy, killing the local Black Hand Fanucci after he demands his customary cut of the tyro's business. With Fanucci gone, Vito's communal stature grows."></h:outputText> </h:panelGrid> </p:tab> <p:tab title="Lenguajes y Compiladores"> <h:panelGrid columns="2" cellpadding="10"> <!--<p:graphicImage value="/images/godfather/godfather3.jpg" /> --> <h:outputText value="After a break of more than 15 years, director Francis Ford Coppola and writer Mario Puzo returned to the well for this third and final story of the fictional Corleone crime family. Two decades have passed, and crime kingpin Michael Corleone, now divorced from his wife Kay has nearly succeeded in keeping his promise that his family would one day be completely legitimate."></h:outputText> </h:panelGrid> </p:tab> <p:tab title="Publicidad"> <h:panelGrid columns="2" cellpadding="10"> <!--<p:graphicImage value="/images/godfather/godfather3.jpg" /> --> <h:outputText value="After a break of more than 15 years, director Francis Ford Coppola and writer Mario Puzo returned to the well for this third and final story of the fictional Corleone crime family. Two decades have passed, and crime kingpin Michael Corleone, now divorced from his wife Kay has nearly succeeded in keeping his promise that his family would one day be completely legitimate."></h:outputText> </h:panelGrid> </p:tab> </p:tabView> </h:form> <br/><br/> </c:if> </ui:composition>
09012143a
trunk/jv3/web/elementos/concursos/editar.xhtml
HTML
gpl2
4,715
<ui:composition xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:h="http://java.sun.com/jsf/html" xmlns:c="http://java.sun.com/jsp/jstl/core" xmlns:f="http://java.sun.com/jsf/core"> <div class="header"> <h:outputText value="#{msg['sistema.nombre']}" /> <c:if test="#{sessionScope['usuario'].valid}"> <div class="notificaciones"> <!--<i class="icon-user icon-white clickeable"></i>--> <div class="buttonClass clickeable" > <i class="icon-info-sign icon-white"></i> </div> <div class="buttonClass blinking clickeable"> <i class="icon-comment icon-white clickeable"></i> 7 </div> <div class="buttonClass blinking clickeable"> <i class="icon-ok icon-white clickeable"></i> 1 </div> <div class="buttonClass blinking clickeable"> <i class="icon-remove icon-white clickeable"></i> 2 </div> <div class="buttonClass clickeable"> <i class="icon-star icon-white clickeable"></i>3 </div> <div class="buttonClass clickeable"> <i class="icon-file icon-white clickeable"></i> 1 </div> <!-- <div class="buttonClass clickeable"> <i class="icon-time icon-white clickeable"></i> 27 minutos restantes </div> --> <div class="buttonClass userMenuBox"> <span class="clickeable"> <h:outputText value="#{sessionScope['usuario'].nombre}" /> </span> <i class="icon-chevron-down icon-white clickeable"></i> </div> </div> <div class="menuUser"> <span class="clickeable"> <i class="icon-off icon-white"></i> <span id="btnLogout"><h:outputText value="#{msg['sistema.logout']}" /></span> </span> </div> </c:if> </div> </ui:composition>
09012143a
trunk/jv3/web/elementos/header.xhtml
HTML
gpl2
2,192
<ui:composition xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" > <span style="color:red;"> Usted no tiene permiso para ver esta página<br/> Redireccionando en: <span id="segundos" ></span> segundos... </span> <script> /* <![CDATA[ */ var segundos = 5; setInterval(function(){ $("#segundos").text(segundos--); if(segundos <= 0){ location.href="index.xhtml"; } }, 1000); /* ]]> */ </script> </ui:composition>
09012143a
trunk/jv3/web/elementos/redireccionar.xhtml
HTML
gpl2
595
<%-- Document : requestController Created on : 3/12/2012, 12:03:46 PM Author : acazares --%> <%@page contentType="text/plain" pageEncoding="UTF-8"%> <%@taglib prefix="f" uri="http://java.sun.com/jsf/core"%> <%@taglib prefix="h" uri="http://java.sun.com/jsf/html"%> <f:view> <h:outputText value="#{UsuariosBean.actionLogin('a@b.com', 'acceso123')}"/> </f:view>
09012143a
trunk/jv3/web/requestController.jsp
Java Server Pages
gpl2
402
<?xml version='1.0' encoding='UTF-8' ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:p="http://primefaces.org/ui" xmlns:c="http://java.sun.com/jsp/jstl/core"> <ui:include src="elementos/contenidos/index.xhtml" /> </html>
09012143a
trunk/jv3/web/index.xhtml
HTML
gpl2
531
<?xml version="1.0" encoding="UTF-8"?> <!-- To change this template, choose Tools | Templates and open the template in the editor. --> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>TODO supply a title</title> </head> <body> <div>Error</div> </body> </html>
09012143a
trunk/jv3/web/error.xhtml
HTML
gpl2
317
<?xml version='1.0' encoding='UTF-8' ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:p="http://primefaces.org/ui" xmlns:c="http://java.sun.com/jsp/jstl/core"> <h:head> <title><h:outputText value="#{msg['sistema.nombre']}" /></title> <link type="text/css" href="recursos/estilos/acd.main.css" rel="stylesheet" /> <c:if test="#{!sessionScope['usuario'].valid}" > <script type="text/javascript" src="recursos/scripts/jquery-1.8.2.js" ></script> </c:if> <script type="text/javascript" src="recursos/scripts/acd.main.js" ></script> <style> .tdClass1{width:150px; padding:5px; vertical-align: middle; } .tdClass2{width:180px; padding:5px; vertical-align: middle; } .tdClass3{ padding:5px; vertical-align: middle;} .tdClassA{} .tdClassB{width:100%} </style> </h:head> <h:body> <ui:include src="elementos/header.xhtml" /> <div class="body"> <center> <div class="inBody" style="font-size: 12px;"> <c:choose> <c:when test="#{sessionScope['usuario'].admin}"> <!-- <ui:include src="elementos/concursos/nuevo.xhtml" /> <ui:include src="elementos/concursos/editar.xhtml" /> <ui:include src="elementos/concursos/usuarios.xhtml" /> --> <ui:include src="elementos/concursos/default.xhtml" /> <br/> <div style="text-align:right;"> <h:form> <p:commandButton value="Regresar a la página principal" icon="ui-icon-arrowreturnthick-1-w" action="index" /> </h:form> </div> </c:when> <c:otherwise> <ui:include src="elementos/redireccionar.xhtml" /> </c:otherwise> </c:choose> </div> </center> </div> <ui:include src="elementos/footer.xhtml" /> </h:body> </html>
09012143a
trunk/jv3/web/concursosEdicion.xhtml
HTML
gpl2
2,802
<?xml version='1.0' encoding='UTF-8' ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core" xmlns:p="http://primefaces.org/ui"> <h:head> <title><h:outputText value="#{msg['sistema.nombre']}" /></title> <link type="text/css" href="recursos/estilos/acd.main.css" rel="stylesheet" /> <script type="text/javascript" src="recursos/scripts/acd.main.js" ></script> <style> .tdClass1{width:150px; padding:5px; vertical-align: middle; } .tdClass2{width:180px; padding:5px; vertical-align: middle; } .tdClass3{ padding:5px; vertical-align: middle;} .tdClassA{} .tdClassB{width:100%} </style> </h:head> <h:body> <ui:include src="elementos/header.xhtml" /> <div class="body"> <center> <div class="inBody" style="font-size: 12px;"> <h:form id="form"> <p:panel header="#{msg['usuario.nuevoUsuario']}" id="panel" style="text-align:left;"> <p:messages id="messages" /> <h:panelGrid columns="2" style="width:100%;" columnClasses="tdClassA, tdClassB" > <img src="recursos/imagenes/usuario.jpg" style="width:250px;" /> <h:panelGrid columns="4" id="matchGrid" style="width:100%; border:solid 1px silver; border-radius: 10px;" columnClasses="tdClass1,tdClass2,tdClass3"> <h:outputLabel for="nombre" id="nombreLbl" value="#{msg['usuario.nombre']} *" /> <p:inputText id="nombre" value="#{usuariosBean.nombre}" required="false" validatorMessage="nada" /> <h:outputText value="#{usuariosBean.msgNombre}" style="color:red;" /> <p:tooltip for="nombreLbl" value="Ejemplo: Juan Perez" showEffect="clip" hideEffect="clip" /> <h:outputLabel for="username" id="usernameLbl" value="Correo electrónico: *" /> <p:inputText id="username" value="#{usuariosBean.username}" required="false" /> <h:outputText value="#{usuariosBean.msgUsername}" style="color:red;" /> <p:tooltip for="usernameLbl" value="Ejemplo: jperez@kmail.com" showEffect="clip" hideEffect="clip" /> <h:outputLabel for="tipo" id="tipoLbl" value="Tipo de usuario" /> <p:selectOneMenu id="tipo" value="#{usuariosBean.tipo}" > <f:selectItems value="#{usuariosBean.tipos}" /> </p:selectOneMenu> <h:outputText /> <p:tooltip for="tipoLbl" value="Modalidad de participación en concursos" showEffect="clip" hideEffect="clip" /> <h:outputLabel for="pass1" id="pass1Lbl" value="#{msg['usuario.pass']} *" /> <p:password id="pass1" value="#{usuariosBean.pass1}" promptLabel="#{msg['usuario.ingresePass']}" weakLabel="#{msg['usuario.passInseguro']}" goodLabel="#{msg['usuario.passAceptable']}" strongLabel="#{msg['usuario.passRobusto']}" feedback="true" inline="true" /> <h:outputText value="#{usuariosBean.msgPass1}" style="color:red;" /> <p:tooltip for="pass1Lbl" value="Puede incluir letras, numeros y caracteres" showEffect="clip" hideEffect="clip" /> <h:outputLabel for="pass2" id="pass2Lbl" value="#{msg['usuario.confirmPass']} *" /> <p:password id="pass2" value="#{usuariosBean.pass2}" /> <h:outputText value="#{usuariosBean.msgPass2}" style="color:red;" /> <p:tooltip for="pass2Lbl" value="Confirme su contraseña" showEffect="clip" hideEffect="clip" /> </h:panelGrid> <h:outputText /> <p:commandButton value="Crear nueva cuenta de usuario" update="panel" id="ajax" icon="ui-icon-disk" actionListener="#{usuariosBean.guardarUsuario}" action="#{usuariosBean.guardarUsuario}" /> </h:panelGrid> </p:panel> </h:form> <br/> <div style="text-align:right;"> <form action="#{modulo.login}" method="GET"> <input type="hidden" name="modulo" value="usuarios" /> <input type="hidden" name="action" value="nuevo" /> <p:commandButton value="Regresar a la página principal" icon="ui-icon-arrowreturnthick-1-w" action="index" /> </form> </div> </div> </center> </div> <ui:include src="elementos/footer.xhtml" /> </h:body> </html>
09012143a
trunk/jv3/web/nuevoUsuario.xhtml
HTML
gpl2
5,754
/* Document : acd.main Created on : 14/11/2012, 09:55:31 AM Author : acazares Description: Hoja de estilos base */ .ui-messages-error-icon{display:none;} body{ margin:0px; padding:0px; padding-top:76px; font-family:Arial; Xbackground-color: #222; Xcolor:#fff; } .body{ background-color: #fff; } .inBody{ background-color: #fff; border:solid 1px #fff; width:977px; padding-bottom:40px; padding-top:40px; } .footer{ Xbackground-image: url('../../recursos/imagenes/footer.png'); background-repeat: repeat-x; padding-top:20px; width:100%; text-align:center; } .menuUser{ background-color:#333; width:110px; position:fixed; right:1px; top:30px; border:solid 1px #fff; z-index:10; color:#fff; font-size:12px; display:none; padding:10px; -webkit-box-shadow: 0 5px 2px rgba(0,0,0,.2); -moz-box-shadow: 0 5px 2px rgba(0,0,0,.2); box-shadow: 0 5px 2px rgba(0,0,0,.2); } .header{ background-image: url('../../recursos/imagenes/azulTop.png'); background-repeat: repeat-x; width:100%; Xheight:41px; height:29px; position:fixed; top:0px; left:0px; color:#fff; font-size:12px; padding-top:12px; padding-left:12px; padding-right:12px; z-index:9; -moz-box-shadow: -12px 10px 35px -10px #556; -webkit-box-shadow: -12px 10px 35px -10px #556; box-shadow: -12px 10px 35px -10px #556; } .notificaciones{ float:right; margin-right:30px; } .buttonClass{ float:left; border:solid 1px #357; font-size:10px; padding:1px 5px 1px 5px; margin:-2px; margin-left:10px; -webkit-border-radius: .3em; -moz-border-radius: .3em; border-radius: .3em; cursor:pointer; } #introImg{ Xpadding-top:20px; -webkit-border-radius: 10px; -moz-border-radius: 10px; border-radius: 10px; border:solid 1px darkblue; background-image: url('../../recursos/imagenes/lib/Blue_Binary_Code_Jigsaw_Puzzle1.jpg'); background-size: 977px 522px; width:977px; height:522px; overflow:hidden; position: relative; } .shadowBlue{ -moz-box-shadow: 0px 30px 40px -15px #556; -webkit-box-shadow: 0px 30px 40px -15px #556; box-shadow: 0px 30px 40px -15px #556; } #formLogin{ display: inherit; background-image: url('../../recursos/imagenes/lib/Blue_Binary_Code_Jigsaw_Puzzle1.jpg'); border-top:solid 1px #fff; border-bottom:solid 1px #fff; margin-top:5px; margin-bottom:5px; padding-top:5px; padding-bottom:5px; } #formLogin input{ font-size:14px; height:25px; width:160px; margin:5px; text-align:center; font-weight:bold; color:#333; -webkit-border-radius: 5px; -moz-border-radius: 5px; border-radius: 5px; border: solid 1px black; } #formLogin button{ font-size:14px; height:25px; width:160px; margin:5px; -webkit-border-radius: 5px; -moz-border-radius: 5px; border-radius: 5px; } #divLogin{ position:absolute; top:100px; right:20px; width:200px; Xheight:200px; Xpadding:10px; text-align:center; border:solid 1px #fff; -webkit-border-radius: 10px; -moz-border-radius: 10px; border-radius: 10px; font-size: 12px; Zbackground-image: url('../../recursos/imagenes/lib/Metal-Grip.jpg'); Xbackground-image: url('../../recursos/imagenes/lib/1105361_73037873.jpg'); Ybackground-image: url('../../recursos/imagenes/lib/Blue_Binary_Code_Jigsaw_Puzzle1.jpg'); background-size: 220px 220px; background-color: #333; padding-bottom:10px; color:#fff; } #divLogin div{ font-size:16px; letter-spacing: 2px; margin-top:10px; font-weight: bold; } #lblRegistro{ letter-spacing: 2px; text-decoration: underline; cursor: pointer; } .linkBlanco{ letter-spacing: 2px; color:#fff; } #msgErrorLogin{ color:#fff; display:none; } .hidden{ display:none; } .clickeable{ cursor: pointer; } [class^="icon-"], [class*=" icon-"] { display: inline-block; width: 14px; height: 14px; line-height: 14px; vertical-align: text-top; background-image: url("../../recursos/imagenes/glyphicons-halflings.png"); background-position: 14px 14px; background-repeat: no-repeat; margin-top: 1px; } .icon-white{ background-image: url("../../recursos/imagenes/glyphicons-halflings-white.png"); } .icon-glass { background-position: 0 0; } .icon-music { background-position: -24px 0; } .icon-search { background-position: -48px 0; } .icon-envelope { background-position: -72px 0; } .icon-heart { background-position: -96px 0; } .icon-star { background-position: -120px 0; } .icon-star-empty { background-position: -144px 0; } .icon-user { background-position: -168px 0; } .icon-film { background-position: -192px 0; } .icon-th-large { background-position: -216px 0; } .icon-th { background-position: -240px 0; } .icon-th-list { background-position: -264px 0; } .icon-ok { background-position: -288px 0; } .icon-remove { background-position: -312px 0; } .icon-zoom-in { background-position: -336px 0; } .icon-zoom-out { background-position: -360px 0; } .icon-off { background-position: -384px 0; } .icon-signal { background-position: -408px 0; } .icon-cog { background-position: -432px 0; } .icon-trash { background-position: -456px 0; } .icon-home { background-position: 0 -24px; } .icon-file { background-position: -24px -24px; } .icon-time { background-position: -48px -24px; } .icon-road { background-position: -72px -24px; } .icon-download-alt { background-position: -96px -24px; } .icon-download { background-position: -120px -24px; } .icon-upload { background-position: -144px -24px; } .icon-inbox { background-position: -168px -24px; } .icon-play-circle { background-position: -192px -24px; } .icon-repeat { background-position: -216px -24px; } .icon-refresh { background-position: -240px -24px; } .icon-list-alt { background-position: -264px -24px; } .icon-lock { background-position: -287px -24px; } .icon-flag { background-position: -312px -24px; } .icon-headphones { background-position: -336px -24px; } .icon-volume-off { background-position: -360px -24px; } .icon-volume-down { background-position: -384px -24px; } .icon-volume-up { background-position: -408px -24px; } .icon-qrcode { background-position: -432px -24px; } .icon-barcode { background-position: -456px -24px; } .icon-tag { background-position: 0 -48px; } .icon-tags { background-position: -25px -48px; } .icon-book { background-position: -48px -48px; } .icon-bookmark { background-position: -72px -48px; } .icon-print { background-position: -96px -48px; } .icon-camera { background-position: -120px -48px; } .icon-font { background-position: -144px -48px; } .icon-bold { background-position: -167px -48px; } .icon-italic { background-position: -192px -48px; } .icon-text-height { background-position: -216px -48px; } .icon-text-width { background-position: -240px -48px; } .icon-align-left { background-position: -264px -48px; } .icon-align-center { background-position: -288px -48px; } .icon-align-right { background-position: -312px -48px; } .icon-align-justify { background-position: -336px -48px; } .icon-list { background-position: -360px -48px; } .icon-indent-left { background-position: -384px -48px; } .icon-indent-right { background-position: -408px -48px; } .icon-facetime-video { background-position: -432px -48px; } .icon-picture { background-position: -456px -48px; } .icon-pencil { background-position: 0 -72px; } .icon-map-marker { background-position: -24px -72px; } .icon-adjust { background-position: -48px -72px; } .icon-tint { background-position: -72px -72px; } .icon-edit { background-position: -96px -72px; } .icon-share { background-position: -120px -72px; } .icon-check { background-position: -144px -72px; } .icon-move { background-position: -168px -72px; } .icon-step-backward { background-position: -192px -72px; } .icon-fast-backward { background-position: -216px -72px; } .icon-backward { background-position: -240px -72px; } .icon-play { background-position: -264px -72px; } .icon-pause { background-position: -288px -72px; } .icon-stop { background-position: -312px -72px; } .icon-forward { background-position: -336px -72px; } .icon-fast-forward { background-position: -360px -72px; } .icon-step-forward { background-position: -384px -72px; } .icon-eject { background-position: -408px -72px; } .icon-chevron-left { background-position: -432px -72px; } .icon-chevron-right { background-position: -456px -72px; } .icon-plus-sign { background-position: 0 -96px; } .icon-minus-sign { background-position: -24px -96px; } .icon-remove-sign { background-position: -48px -96px; } .icon-ok-sign { background-position: -72px -96px; } .icon-question-sign { background-position: -96px -96px; } .icon-info-sign { background-position: -120px -96px; } .icon-screenshot { background-position: -144px -96px; } .icon-remove-circle { background-position: -168px -96px; } .icon-ok-circle { background-position: -192px -96px; } .icon-ban-circle { background-position: -216px -96px; } .icon-arrow-left { background-position: -240px -96px; } .icon-arrow-right { background-position: -264px -96px; } .icon-arrow-up { background-position: -289px -96px; } .icon-arrow-down { background-position: -312px -96px; } .icon-share-alt { background-position: -336px -96px; } .icon-resize-full { background-position: -360px -96px; } .icon-resize-small { background-position: -384px -96px; } .icon-plus { background-position: -408px -96px; } .icon-minus { background-position: -433px -96px; } .icon-asterisk { background-position: -456px -96px; } .icon-exclamation-sign { background-position: 0 -120px; } .icon-gift { background-position: -24px -120px; } .icon-leaf { background-position: -48px -120px; } .icon-fire { background-position: -72px -120px; } .icon-eye-open { background-position: -96px -120px; } .icon-eye-close { background-position: -120px -120px; } .icon-warning-sign { background-position: -144px -120px; } .icon-plane { background-position: -168px -120px; } .icon-calendar { background-position: -192px -120px; } .icon-random { background-position: -216px -120px; width: 16px; } .icon-comment { background-position: -240px -120px; } .icon-magnet { background-position: -264px -120px; } .icon-chevron-up { background-position: -288px -120px; } .icon-chevron-down { background-position: -313px -119px; } .icon-retweet { background-position: -336px -120px; } .icon-shopping-cart { background-position: -360px -120px; } .icon-folder-close { background-position: -384px -120px; } .icon-folder-open { background-position: -408px -120px; width: 16px; } .icon-resize-vertical { background-position: -432px -119px; } .icon-resize-horizontal { background-position: -456px -118px; } .icon-hdd { background-position: 0 -144px; } .icon-bullhorn { background-position: -24px -144px; } .icon-bell { background-position: -48px -144px; } .icon-certificate { background-position: -72px -144px; } .icon-thumbs-up { background-position: -96px -144px; } .icon-thumbs-down { background-position: -120px -144px; } .icon-hand-right { background-position: -144px -144px; } .icon-hand-left { background-position: -168px -144px; } .icon-hand-up { background-position: -192px -144px; } .icon-hand-down { background-position: -216px -144px; } .icon-circle-arrow-right { background-position: -240px -144px; } .icon-circle-arrow-left { background-position: -264px -144px; } .icon-circle-arrow-up { background-position: -288px -144px; } .icon-circle-arrow-down { background-position: -312px -144px; } .icon-globe { background-position: -336px -144px; } .icon-wrench { background-position: -360px -144px; } .icon-tasks { background-position: -384px -144px; } .icon-filter { background-position: -408px -144px; } .icon-briefcase { background-position: -432px -144px; } .icon-fullscreen { background-position: -456px -144px; } .blanco{ margin: 3px 0 3px 0; color: #444; border: solid 1px #cccccc; background: #fefdfd; background: -webkit-gradient(linear, left top, left bottom, from(#fefdfd), to(#dddddd)); background: -moz-linear-gradient(top, #fefdfd, #dddddd); filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fefdfd', endColorstr='#dddddd'); -webkit-border-radius: .2em; -moz-border-radius: .2em; border-radius: .2em; -webkit-box-shadow: 0 5px 2px rgba(0,0,0,.2); -moz-box-shadow: 0 5px 2px rgba(0,0,0,.2); box-shadow: 0 5px 2px rgba(0,0,0,.2); padding:2px 15px 2px 15px; } .blanco:hover { background: #dddddd; background: -webkit-gradient(linear, left top, left bottom, from(#dddddd), to(#fefdfd)); background: -moz-linear-gradient(top, #dddddd, #fefdfd); filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#dddddd', endColorstr='#fefdfd'); } .blanco:active { color: #000; background: -webkit-gradient(linear, left top, left bottom, from(#dddddd), to(#fefdfd)); background: -moz-linear-gradient(top, #dddddd, #fefdfd); filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#dddddd', endColorstr='#fefdfd'); }
09012143a
trunk/jv3/web/recursos/estilos/acd.main.css
CSS
gpl2
13,440
/* Document : acd.main Created on : 14/11/2012, 03:16:31 PM Author : acazares Description: script base */ var servlet = 'requestController.jsf'; $(function(){ $(".userMenuBox").bind('click', function(){ $('.menuUser').fadeIn('slow', function() { setTimeout(function(){$('.menuUser').fadeOut('slow')}, 3000); }); }); setInterval(function(){ $(".blinking").fadeToggle("slow"); }, 300); $("#lblRegistro").bind("click", function(){ location.href="faces/usuario.xhtml?action=nuevo"; }); $("#formLogin").submit(function(e){ if($('#username').val().length==0){ $('#username').css("background-color","yellow"); $('#username').focus(); }else{ $('#username').css("background-color","#fff"); } if($('#pass').val().length==0){ $('#pass').css("background-color","yellow"); $('#pass').focus(); return false; }else{ $('#pass').css("background-color","#fff"); } if($('#username').val().length==0){ return false; } extras = 'user='+$('#username').val()+'&pass='+$('#pass').val() $.ajax({ dataType : "json", url : servlet+'?action=login&'+extras, //url : 'requestController.jsp?action=logout', success: function(data) {//alert(data); JSONdata = eval(data) if(JSONdata.id !=null){ location.href='?'; }else{ $("#msgErrorLogin").css("display","inline") $("#username").val(""); $("#pass").val(""); } } }); return false; }); $("#btnLogout").bind('click', function(){ $.ajax({ dataType : "json", url : servlet+'?action=logout', //url : 'requestController.jsp?action=logout', //url : 'http://localhost:8080/jv3/faces/index.xhtml', success: function(data) {//alert(data); location.href='?'; } }); }); });
09012143a
trunk/jv3/web/recursos/scripts/acd.main.js
JavaScript
gpl2
2,379
body { background-color: #ffffff; font-size: 12px; font-family: Verdana, "Verdana CE", Arial, "Arial CE", "Lucida Grande CE", lucida, "Helvetica CE", sans-serif; color: #000000; margin: 10px; } h1 { font-family: Arial, "Arial CE", "Lucida Grande CE", lucida, "Helvetica CE", sans-serif; border-bottom: 1px solid #AFAFAF; font-size: 16px; font-weight: bold; margin: 0px; padding: 0px; color: #D20005; } a:link, a:visited { color: #045491; font-weight : bold; text-decoration: none; } a:link:hover, a:visited:hover { color: #045491; font-weight : bold; text-decoration : underline; }
09012143a
trunk/jv3/web/resources/css/default.css
CSS
gpl2
680
#top { position: relative; background-color: #036fab; color: white; padding: 5px; margin: 0px 0px 10px 0px; } #bottom { position: relative; background-color: #c2dfef; padding: 5px; margin: 10px 0px 0px 0px; } #left { float: left; background-color: #ece3a5; padding: 5px; width: 150px; } #right { float: right; background-color: #ece3a5; padding: 5px; width: 150px; } .center_content { position: relative; background-color: #dddddd; padding: 5px; } .left_content { background-color: #dddddd; padding: 5px; margin-left: 170px; } .right_content { background-color: #dddddd; padding: 5px; margin: 0px 170px 0px 170px; } #top a:link, #top a:visited { color: white; font-weight : bold; text-decoration: none; } #top a:link:hover, #top a:visited:hover { color: black; font-weight : bold; text-decoration : underline; }
09012143a
trunk/jv3/web/resources/css/cssLayout.css
CSS
gpl2
1,001
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package componentes; import java.io.Serializable; import java.util.*; import javax.faces.bean.ManagedBean; import javax.faces.bean.ViewScoped; /** * * @author acazares * consulta [scope]: http://anadreamy.wordpress.com/2011/10/25/jsf-2-0-managed-beans-iii/ * consulta [efectos]: http://icefaces-showcase.icesoft.org/showcase.jsf?grp=aceMenu&exp=autoCompleteEntryBean */ @ManagedBean @ViewScoped public class Sistema implements Serializable{ private static final long serialVersionUID = 1L; private String year;// ="2012"; /** * Creates a new instance of Sistema */ public Sistema() throws Exception { Calendar toDay = Calendar.getInstance(); year = toDay.get(Calendar.YEAR)+""; } public String getYear(){ return year; } }
09012143a
trunk/jv3/src/java/componentes/Sistema.java
Java
gpl2
962
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package componentes; import DTO.Usuario; import com.google.gson.Gson; import java.util.Date; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.faces.application.FacesMessage; import javax.faces.bean.ManagedBean; import javax.faces.bean.RequestScoped; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.model.SelectItem; import javax.faces.validator.ValidatorException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import tipos.UsuarioStatus; import tipos.UsuarioTipo; import utilidades.Hash; /** * * @author acazares * http://www.primefaces.org/ * http://www.roseindia.net/jsf/validator.shtml * http://jqueryui.com/themeroller/#themeGallery */ @ManagedBean @RequestScoped public class UsuariosBean { private static final long serialVersionUID = 1L; private DAO.UsuarioDAO usuarioDao; //@Size(min=3, max=32) //@NotNull private String username; private String msgUsername; //@Size(min=4, max=32) //@NotNull private String pass1; private String msgPass1; //@NotNull private String pass2; private String msgPass2; //@Size(min=3, max=32) //@NotNull private String nombre; private String msgNombre; private tipos.UsuarioTipo tipo; private SelectItem[] usuariosTipo = new SelectItem[]{ new SelectItem( tipos.UsuarioTipo.usuario, tipos.UsuarioTipo.usuario.toString() ), new SelectItem( tipos.UsuarioTipo.equipo, tipos.UsuarioTipo.equipo.toString() )/*, new SelectItem( tipos.UsuarioTipo.administrador, tipos.UsuarioTipo.administrador.toString() )*/ }; public UsuariosBean() { usuarioDao = new DAO.UsuarioDAO(); } public SelectItem[] getUsuariosStatus() { return usuariosTipo; } public String guardarUsuario(){ System.out.println("Iniciando validacion de elementos"); boolean validacion = nombreValido() & usuarioValido() & passValido(); System.out.println("Resultado: "+validacion); if(!validacion){ return "nuevoUsuario"; } Usuario usr = new Usuario(); usr.setNombre(nombre); usr.setUser(username); usr.setPass( utilidades.Hash.md5(pass1) ); usr.setStatus(UsuarioStatus.nuevo); usr.setTipo(tipo); usr.setCreacion(new Date()); usr.setUltimoAcceso(new Date()); try{ usuarioDao.guardar(usr); System.out.println("usuario id: "+usr.getId() ); login(usr); }catch(Exception e){ System.out.println( "Se presento un problema: "+e ); }finally{ return "index"; } } public void login(Usuario usr){ FacesContext context = FacesContext.getCurrentInstance(); HttpServletRequest request = (HttpServletRequest)context. getExternalContext().getRequest(); HttpSession httpSession = request.getSession(false); System.out.println("usuario: "+usr.getNombre()); if(usr.isValid()){ httpSession.setAttribute("usuario", usr); System.out.println("Se ha establecido login"); }else{ System.out.println("No se completo login, usuario no valido"); } } public void logout(){ FacesContext context = FacesContext.getCurrentInstance(); HttpServletRequest request = (HttpServletRequest)context. getExternalContext().getRequest(); HttpSession httpSession = request.getSession(false); httpSession.invalidate(); System.out.println("logout"); } /* public String actionLogout(){ logout(); Gson gson = new Gson(); return gson.toJson( new Usuario() ); } public String actionLogin(String user, String pass){ Gson gson = new Gson(); Usuario usuario = usuarioDao.getUsuarioByUserPass(user, Hash.md5(pass)); System.out.println("Preparando login: "+user+","+pass); login(usuario); System.out.println("Finalizando login: "+gson.toJson( usuario )); return gson.toJson( usuario ); } */ public boolean nombreValido(){ if(nombre == null || nombre.length() == 0){ msgNombre = "Campo requerido"; return false; } if(nombre.length() <3){ msgNombre = "Al menos debe contener 3 caracteres"; return false; } if(nombre.length() >32){ msgNombre = "Máximo 32 caracteres"; return false; } return true; } public boolean usuarioValido(){ if(username == null || username.length() == 0){ msgUsername = "Campo requerido"; return false; } String regex = "^\\w+([\\.-]?\\w+)*@\\w+([\\.-]?\\w+)*(\\.\\w{2,3})+$"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(username); if( !matcher.matches() ){ msgUsername = "formato de correo electrónico no válido"; return false; } if( usuarioDao.countByUsername(username) >0 ){ msgUsername ="Alguien mas ya ha usado ["+username +"] como nombre de usuario"; return false; } return true; } public boolean passValido(){ if(pass2 == null || pass2.length() == 0){ msgPass2 = "Campo requerido"; } if(pass1 == null || pass1.length() == 0){ msgPass1 = "Campo requerido"; return false; } String regex = ""; regex += "^(?=.*[A-Z]).{6,}$|^(?=.*[.]).{6,}$";//M6,e6, regex += "|^(?=.*[0-9]).{7,}$|^(?=.*[a-z]).{12,}$";//n7,m12 regex += "|^(?=.*[0-9])(?=.*[A-Z]).{4,}$";//nM4 regex += "|^(?=.*[.])(?=.*[A-Z]).{4,}$";//eM4 regex += "|^(?=.*[.])(?=.*[0-9]).{4,}$";//en4 regex += "|^(?=.*[.])(?=.*[a-z]).{5,}$";//en5 regex += "|^(?=.*[A-Z])(?=.*[a-z]).{6,}$";//Mm6 regex += "|^(?=.*[0-9])(?=.*[a-z]).{7,}$";//nm7 regex += "|^(?=.*[.])(?=.*[a-z])(?=.*[A-Z]).{4,}$";//emM4// regex += "|^(?=.*[.])(?=.*[a-z])(?=.*[0-9]).{4,}$";//emn4// regex += "|^(?=.*[.])(?=.*[A-Z])(?=.*[0-9]).{3,}$";//enM3// regex += "|^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9]).{4,}$";//mMn// regex += "|^(?=.*[.])(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9]).{4,}$";//emMn4// Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(pass1); if( !matcher.matches() ){ //if( !matcher.matches() ){ msgPass1 = "El password no es seguro"; msgPass2 = "Utilice numeros, letras minusculas, letras mayusculas y opcionalmente caracteres especiales."; return false; } if(!pass1.equals(pass2)){ msgPass1 = "Falló la confirmación del password"; return false; } return true; } /////////////////////////////////////////////////////////////////////// public String getMsgUsername() { return msgUsername; } public String getMsgPass1() { return msgPass1; } public String getMsgPass2() { return msgPass2; } public String getMsgNombre() { return msgNombre; } /////////////////////////////////////////////////////////////////////// public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPass1() { return pass1; } public void setPass1(String pass) { this.pass1 = pass; } public String getPass2() { return pass1; } public void setPass2(String pass) { this.pass2 = pass; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public UsuarioTipo getTipo() { return tipo; } public void setTipo(UsuarioTipo tipo) { this.tipo = tipo; } public SelectItem[] getTipos(){ return usuariosTipo; } }
09012143a
trunk/jv3/src/java/componentes/UsuariosBean.java
Java
gpl2
8,923
package componentes; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import java.util.UUID; import javax.faces.model.SelectItem; import componentes.Car;//<---------------- public class TableBean implements Serializable { private final static String[] colors; private final static String[] manufacturers; static { colors = new String[10]; colors[0] = "Black"; colors[1] = "White"; colors[2] = "Green"; colors[3] = "Red"; colors[4] = "Blue"; colors[5] = "Orange"; colors[6] = "Silver"; colors[7] = "Yellow"; colors[8] = "Brown"; colors[9] = "Maroon"; manufacturers = new String[10]; manufacturers[0] = "Mercedes"; manufacturers[1] = "BMW"; manufacturers[2] = "Volvo"; manufacturers[3] = "Audi"; manufacturers[4] = "Renault"; manufacturers[5] = "Opel"; manufacturers[6] = "Volkswagen"; manufacturers[7] = "Chrysler"; manufacturers[8] = "Ferrari"; manufacturers[9] = "Ford"; } private SelectItem[] manufacturerOptions; private List<Car> filteredCars; private List<Car> carsSmall; public TableBean() { carsSmall = new ArrayList<Car>(); populateRandomCars(carsSmall, 9); manufacturerOptions = createFilterOptions(manufacturers); } private void populateRandomCars(List<Car> list, int size) { for(int i = 0 ; i < size ; i++) list.add(new Car(getRandomModel(), getRandomYear(), getRandomManufacturer(), getRandomColor())); } public List<Car> getFilteredCars() { return filteredCars; } public void setFilteredCars(List<Car> filteredCars) { this.filteredCars = filteredCars; } public List<Car> getCarsSmall() { return carsSmall; } private int getRandomYear() { return (int) (Math.random() * 50 + 1960); } private String getRandomColor() { return colors[(int) (Math.random() * 10)]; } private String getRandomManufacturer() { return manufacturers[(int) (Math.random() * 10)]; } private String getRandomModel() { return UUID.randomUUID().toString().substring(0, 8); } private SelectItem[] createFilterOptions(String[] data) { SelectItem[] options = new SelectItem[data.length + 1]; options[0] = new SelectItem("", "Select"); for(int i = 0; i < data.length; i++) { options[i + 1] = new SelectItem(data[i], data[i]); } return options; } public SelectItem[] getManufacturerOptions() { return manufacturerOptions; } }
09012143a
trunk/jv3/src/java/componentes/TableBean.java
Java
gpl2
3,011
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package componentes; import DTO.Usuario; import com.google.gson.Gson;//http://blog.pontt.com/json-con-java/introduccion-java-y-json-primera-parte-con-ejemplo/ import java.io.IOException; import java.io.PrintWriter; import java.util.*; import javax.faces.application.Application; import javax.faces.context.FacesContext; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import javax.sound.midi.Soundbank; import tipos.UsuarioStatus; import tipos.UsuarioTipo; import utilidades.Hash; /** * * @author acazares */ @WebServlet(name = "requestController", urlPatterns = {"/requestController.jsf"}) public class RequestController extends HttpServlet { private Gson gson; /** * Processes requests for both HTTP * <code>GET</code> and * <code>POST</code> methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //response.setContentType("text/html;charset=UTF-8"); response.setContentType("text/plain;charset=UTF-8"); gson = new Gson(); PrintWriter out = response.getWriter(); try { String opcion = request.getParameter("action"); if( opcion != null ){ if(opcion.equals("login")){ out.print( login(request) ); } if(opcion.equals("logout")) { logout(request); //out.print("ya"); } } } finally { out.close(); } } private String login(HttpServletRequest request){ try{ String user = request.getParameter("user"); String pass = request.getParameter("pass"); if(user!=null && pass!=null && user.length()>0 && pass.length()>0){ HttpSession sesionActual = request.getSession(); DAO.UsuarioDAO dao = new DAO.UsuarioDAO(); Usuario usuario = dao.getUsuarioByUserPass(user, Hash.md5(pass)); if(usuario.isValid()){ sesionActual.setAttribute("usuario", usuario ); dao.updateLastLogin(usuario); System.out.println("login starting: "+usuario.getId()); } return gson.toJson( usuario ); } return gson.toJson( new Usuario() ); }catch(Exception e){ return "error: "+e; } } private void logout(HttpServletRequest request){ // consulta [invalidate]: http://manglar.uninorte.edu.co/bitstream/10584/2206/1/Frameworks%20de%20desarrollo%20sobre%20p%C3%A1ginas%20JSP.pdf HttpSession sesionActual = request.getSession(); sesionActual.invalidate(); System.out.println("logout"); } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP * <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP * <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
09012143a
trunk/jv3/src/java/componentes/RequestController.java
Java
gpl2
5,047
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package componentes; /** * * @author acazares */ import java.util.Date; public class Car { private String model; private int year; private String manufacturer; private String color; public Car(String model, int year, String manufacturer, String color) { this.model = model; this.year = year; this.manufacturer = manufacturer; this.color = color; } public String getModel() { return model; } public void setModel(String model) { this.model = model; } public int getYear() { return year; } public void setYear(int year) { this.year = year; } public String getManufacturer() { return manufacturer; } public void setManufacturer(String manufacturer) { this.manufacturer = manufacturer; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } }
09012143a
trunk/jv3/src/java/componentes/Car.java
Java
gpl2
1,335
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package componentes; import DTO.Concurso; import DTO.Usuario; import com.sun.xml.registry.uddi.infomodel.ConceptImpl; import java.util.Date; import javax.faces.bean.ManagedBean; import javax.faces.bean.RequestScoped; import javax.faces.context.FacesContext; import javax.faces.model.SelectItem; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import tipos.ConcursoStatus; import tipos.ConcursoTipo; import tipos.UsuarioStatus; /** * * @author acazares */ @ManagedBean @RequestScoped public class ConcursosBean { private DTO.Concurso concurso; private DAO.ConcursoDAO dao; private HttpServletRequest request; private FacesContext context; private HttpSession httpSession; private boolean esNuevo = false; private String vista; public ConcursosBean() { try{ dao = new DAO.ConcursoDAO(); context = FacesContext.getCurrentInstance(); request = (HttpServletRequest) FacesContext.getCurrentInstance(). getExternalContext().getRequest(); httpSession = request.getSession(false); String id = request.getParameter("id"); vista = (String)request.getParameter("vista"); if(id!=null && id.length()>0){ //DAO.UtilDao dao1 = new DAO.UtilDao( tipos.ComponentesNombre.Concurso ); //System.out.println("Solicitando datos..."); //concurso = (Concurso)dao1.getById(id); concurso = dao.getConcursoById(id); System.out.println("Salida: "); System.out.println(concurso.toString()); concurso.setId(id); esNuevo = false; }else{ concurso = new DTO.Concurso(); esNuevo = true; } }catch(Exception e){ System.out.println("Error: "+e); } } public void setVista(String vista){ this.vista = vista; } public String getVista(){ if(vista!=null && vista.equals("crear")){ System.out.println("Set vista"); return this.vista="elementos/concursos/nuevo.xhtml"; } /* * else{ System.out.println("Nada???"+vista); //this.vista=vista; return this.vista="elementos/concursos/nuevo1.xhtml"; } //return vista;*/ return this.vista="elementos/concursos/default.xhtml"; } /* public String getVistaLL(){ if(vista!=null && vista.equals("crear")){ System.out.println("Ingresando"); return "elementos/concursos/nuevo.xhtml"; }else{ System.out.println("Nada???"); } /* if(vista!=null){ if(vista.equals("crear")) return "elementos/concursos/nuevo.xhtml"; } return "elementos/concursos/usuarios.xhtml"; //return "elementos/concursos/nuevo.xhtml"; }*/ public boolean getEsNuevo(){ return esNuevo; //return true; } public String guardar(){ try{ DTO.Concurso concurso = dao.getConcursoById(this.concurso.getId()); System.out.println("Formulario: "+this.concurso.getNombre() + "Objeto: "+concurso.getNombre()); //falta validar los datos if(concurso.getId()==null){ System.out.println("Guardando datos"); dao = new DAO.ConcursoDAO(); this.concurso.setTipoInscripcion(ConcursoTipo.publico); this.concurso.setStatus(ConcursoStatus.nuevo); DTO.Usuario usr = (DTO.Usuario)httpSession.getAttribute("usuario"); this.concurso.setAutor(usr); System.out.println("objeto construido, administrado por "+usr.getNombre()); dao.guardar(this.concurso); System.out.println("Datos almacenados"); return "index"; }else{ //falta validar los datos concurso.setConvocatoria(this.concurso.getConvocatoria()); concurso.setFinaliza(this.concurso.getFinaliza()); concurso.setInicia(this.concurso.getInicia()); concurso.setNombre(this.concurso.getNombre()); concurso.setPublicidadFin(this.concurso.getPublicidadFin()); concurso.setPublicidadInicio(this.concurso.getPublicidadInicio()); //concurso.setStatus(this.concurso.getStatus()); //concurso.setTipoInscripcion(this.concurso.getTipoInscripcion()); dao.update(concurso); System.out.println("objeto actualizado, administrado por "+concurso.getAutor()); System.out.println("Detalles:"+ concurso.getNombre()); return "index"; } }catch(Exception e){ System.out.println("Error: "+e); return "crear"; } } private SelectItem[] concursosTipo = new SelectItem[]{ new SelectItem( tipos.ConcursoTipo.publico, tipos.ConcursoTipo.publico.toString() ), new SelectItem( tipos.ConcursoTipo.privado, tipos.ConcursoTipo.privado.toString() ), new SelectItem( tipos.ConcursoTipo.bloqueado, tipos.ConcursoTipo.bloqueado.toString() ) }; public SelectItem[] getTipos(){ return concursosTipo; } private SelectItem[] concursosStatus = new SelectItem[]{ new SelectItem( tipos.ConcursoStatus.nuevo, tipos.ConcursoStatus.nuevo.toString() ), new SelectItem( tipos.ConcursoStatus.iniciado, tipos.ConcursoStatus.iniciado.toString() ), new SelectItem( tipos.ConcursoStatus.pausado, tipos.ConcursoStatus.pausado.toString() ), new SelectItem( tipos.ConcursoStatus.finalizado, tipos.ConcursoStatus.finalizado.toString() ) }; public SelectItem[] getStatusConcursos(){ return concursosStatus; } public String msgNombre, msgInicio, msgFinaliza, msgAutor, msgStatus, msgTipoInscripcion, msgPublicidadInicio, msgPublicidadFin; public void setId(String id){ concurso.setId(id); } public void setNombre(String nombre){ concurso.setNombre(nombre); } public void setInicia(Date inicia){ concurso.setInicia(inicia); } public void setFinaliza(Date finaliza){ concurso.setFinaliza(finaliza); } public void setAutor(DTO.Usuario autor){ concurso.setAutor(autor); } public void setStatus(tipos.ConcursoStatus status){ concurso.setStatus(status); } public void setTipoInscripcion(tipos.ConcursoTipo tipo){ concurso.setTipoInscripcion(tipo); } public void setConvocatoria(String convocatoria){ concurso.setConvocatoria(convocatoria); } public void setPublicidadInicio(Date publicidadInicio){ concurso.setPublicidadInicio(publicidadInicio); } public void setPublicidadFin(Date publicidadFin){ concurso.setPublicidadFin(publicidadFin); } public String getId(){ return concurso.getId(); } public String getNombre(){ return concurso.getNombre(); } public Date getInicia(){ return concurso.getInicia(); } public Date getFinaliza(){ return concurso.getFinaliza(); } public DTO.Usuario getAutor(){ DAO.UsuarioDAO dao = new DAO.UsuarioDAO(); return dao.getUsuarioById(concurso.getAutor()); //return concurso.getAutor(); } public tipos.ConcursoStatus getStatus(){ return concurso.getStatus(); } public tipos.ConcursoTipo getTipoInscripcion(){ return concurso.getTipoInscripcion(); } public String getConvocatoria(){ return concurso.getConvocatoria(); } public Date getPublicidadInicio(){ return concurso.getPublicidadInicio(); } public Date getPublicidadFin(){ return concurso.getPublicidadFin(); } }
09012143a
trunk/jv3/src/java/componentes/ConcursosBean.java
Java
gpl2
8,736
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package tipos; /** * * @author Windows */ public enum CodigoFuenteError { compilacion, ejecucion, incorrecto, tiempo, ninguno; }
09012143a
trunk/jv3/src/java/tipos/CodigoFuenteError.java
Java
gpl2
250
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package tipos; /** * * @author Windows */ public enum RolTipo { participante, juez, observador, administrador; }
09012143a
trunk/jv3/src/java/tipos/RolTipo.java
Java
gpl2
234
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package tipos; /** * * @author acazares */ public enum ConcursoStatus { nuevo, iniciado, pausado, finalizado; }
09012143a
trunk/jv3/src/java/tipos/ConcursoStatus.java
Java
gpl2
233
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package tipos; /** * * @author Windows */ public enum UsuarioTipo { usuario, equipo, administrador; }
09012143a
trunk/jv3/src/java/tipos/UsuarioTipo.java
Java
gpl2
223
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package tipos; /** * * @author Windows */ public enum UsuarioStatus { nuevo, activo, bloqueado; }
09012143a
trunk/jv3/src/java/tipos/UsuarioStatus.java
Java
gpl2
219
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package tipos; /** * * @author acazares */ public enum ComponentesNombre { Aclaraciones, CodigoFuente, Concurso, Dudas, Lenguaje, LenguajeConcurso, Reactivo, Rol, Servidor, Usuario; }
09012143a
trunk/jv3/src/java/tipos/ComponentesNombre.java
Java
gpl2
311
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package tipos; /** * * @author Windows */ public enum RolStatus { aceptado, bloqueado, rechazado; }
09012143a
trunk/jv3/src/java/tipos/RolStatus.java
Java
gpl2
221
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package tipos; /** * * @author acazares */ public enum ConcursoTipo { publico, privado, bloqueado; }
09012143a
trunk/jv3/src/java/tipos/ConcursoTipo.java
Java
gpl2
222
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package tipos; /** * * @author Windows */ public enum ServidorStatus { activo, pausado, apagado }
09012143a
trunk/jv3/src/java/tipos/ServidorStatus.java
Java
gpl2
219
package DTO; // Generated 16/11/2012 12:38:33 PM by Hibernate Tools 3.2.1.GA import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.Temporal; import org.hibernate.annotations.GenericGenerator; @Entity @Table(name = "concursos") public class Concurso implements java.io.Serializable { @Id @GeneratedValue(generator = "uuid") @GenericGenerator(name = "uuid", strategy = "uuid") @Column(name = "id", length=32) private String id; @Column(name="nombre", length=64, nullable=false) private String nombre; @Column(name="inicia", nullable=false) @Temporal(javax.persistence.TemporalType.TIMESTAMP) private Date inicia; @Column(name="finaliza", nullable=false) @Temporal(javax.persistence.TemporalType.TIMESTAMP) private Date finaliza; @Column(name = "autor", length=32) //@OneToOne(cascade = CascadeType.ALL) private String autor; @Enumerated(EnumType.STRING) @Column(name="status", length=11, nullable=false) private tipos.ConcursoStatus status; @Enumerated(EnumType.STRING) @Column(name="tipo_inscripcion", length=10, nullable=false) private tipos.ConcursoTipo tipoInscripcion; private String convocatoria; @Column(name="publicidad_inicio", nullable=false) @Temporal(javax.persistence.TemporalType.TIMESTAMP) private Date publicidadInicio; @Column(name="publicidad_fin", nullable=false) @Temporal(javax.persistence.TemporalType.TIMESTAMP) private Date publicidadFin; public Concurso() { } public Concurso(String id, String nombre, Date inicia, Date finaliza, String autor, tipos.ConcursoStatus status, tipos.ConcursoTipo tipoInscripcion, String convocatoria, Date publicidadInicio, Date publicidadFin) { this.id = id; this.nombre = nombre; this.inicia = inicia; this.finaliza = finaliza; this.autor = autor; this.status = status; this.tipoInscripcion = tipoInscripcion; this.convocatoria = convocatoria; this.publicidadInicio = publicidadInicio; this.publicidadFin = publicidadFin; } public String getId() { return this.id; } public void setId(String id) { this.id = id; } public String getNombre() { return this.nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public Date getInicia() { return this.inicia; } public void setInicia(Date inicia) { this.inicia = inicia; } public Date getFinaliza() { return this.finaliza; } public void setFinaliza(Date finaliza) { this.finaliza = finaliza; } public String getAutor() { return this.autor; } public void setAutor(Usuario autor) { this.autor = autor.getId(); } public void setAutor(String autor) { this.autor = autor; } public tipos.ConcursoStatus getStatus() { return this.status; } public void setStatus(tipos.ConcursoStatus status) { this.status = status; } public tipos.ConcursoTipo getTipoInscripcion() { return this.tipoInscripcion; } public void setTipoInscripcion(tipos.ConcursoTipo tipoInscripcion) { this.tipoInscripcion = tipoInscripcion; } public String getConvocatoria() { return this.convocatoria; } public void setConvocatoria(String convocatoria) { this.convocatoria = convocatoria; } public Date getPublicidadInicio() { return this.publicidadInicio; } public void setPublicidadInicio(Date publicidadInicio) { this.publicidadInicio = publicidadInicio; } public Date getPublicidadFin() { return this.publicidadFin; } public void setPublicidadFin(Date publicidadFin) { this.publicidadFin = publicidadFin; } }
09012143a
trunk/jv3/src/java/DTO/Concurso.java
Java
gpl2
4,371
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package validadores; import javax.faces.validator.*; import javax.faces.application.*; import javax.faces.component.*; import javax.faces.context.*; import java.util.regex.*; /** * * @author Windows * http://www.roseindia.net/jsf/validator.shtml */ public class PasswordConfirm implements Validator{ public PasswordConfirm(){} @Override public void validate( FacesContext facesContext, UIComponent uIComponent, Object object ) throws ValidatorException { String password = (String)object; if (password.length() <3) { FacesMessage message = new FacesMessage(); message.setSummary("Password muy corto"); throw new ValidatorException(message); } } }
09012143a
trunk/jv3/src/java/validadores/PasswordConfirm.java
Java
gpl2
902
import java.util.Date; import DTO.Usuario; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author Windows */ public class ImplementacionHibernate { public static void main(String...args){ DAO.UsuarioDAO dao = new DAO.UsuarioDAO(); System.out.println(dao.getList().size()); Usuario usuario = new Usuario(); usuario.setCreacion(new Date()); usuario.setPass("1234586"); usuario.setStatus(tipos.UsuarioStatus.nuevo); usuario.setTipo(tipos.UsuarioTipo.administrador); usuario.setUltimoAcceso(new Date()); usuario.setUser("acazares19"); dao.guardar(usuario); /* UsuariosDAO dao = new UsuariosDAO(); System.out.println("Numero de usuarios registrados:"); System.out.println(dao.getUsuarios().size()); Usuarios usuario = new Usuarios(); usuario.setCreacion(new Date()); usuario.setPass("1234586"); usuario.setStatus(tipos.UsuarioStatus.nuevo); usuario.setTipo(tipos.UsuarioTipo.administrador); usuario.setUltimoAcceso(new Date()); usuario.setUser("acazares17"); dao.guardarUsuario(usuario); //*/ } }
09012143a
trunk/jv3/src/java/ImplementacionHibernate.java
Java
gpl2
1,375
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package utilidades; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; /** * * @author acazares * http://www.apuntesdejava.com/2009/03/md5-en-java.html */ public class Hash { private static final char[] HEXADECIMAL = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; public static String md5(String stringToHash) { try { MessageDigest md = MessageDigest.getInstance("MD5"); byte[] bytes = md.digest(stringToHash.getBytes()); StringBuilder sb = new StringBuilder(2 * bytes.length); for (int i = 0; i < bytes.length; i++) { int low = (int)(bytes[i] & 0x0f); int high = (int)((bytes[i] & 0xf0) >> 4); sb.append(HEXADECIMAL[high]); sb.append(HEXADECIMAL[low]); } return sb.toString(); } catch (NoSuchAlgorithmException e) { //exception handling goes here return null; } } }
09012143a
trunk/jv3/src/java/utilidades/Hash.java
Java
gpl2
1,185
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package DAO; import DTO.Aclaraciones; import DTO.CodigoFuente; import DTO.Concurso; import DTO.Dudas; import DTO.LenguajesConcurso; import DTO.Reactivo; import DTO.Rol; import DTO.Servidor; import DTO.Usuario; import java.util.List; import org.hibernate.HibernateException; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.Transaction; /** * * @author acazares */ public class UtilDao{ protected Session sesion; protected Transaction tx; protected String objName;// = "Usuarios"; protected String objAlias;// = "usuario"; protected Object object; public UtilDao(){ sesion = HibernateUtilDAO.getSessionFactory().openSession(); } public UtilDao(tipos.ComponentesNombre tipo){ sesion = HibernateUtilDAO.getSessionFactory().openSession(); System.out.println("UtilDao: Inicializando valores del objeto..."); if(tipo == tipos.ComponentesNombre.Aclaraciones){ objName=tipo.toString(); objAlias="aclaraciones"; object = new Aclaraciones(); } if(tipo == tipos.ComponentesNombre.CodigoFuente ){ objName=tipo.toString(); objAlias="codigo_fuente"; object = new CodigoFuente(); } if(tipo == tipos.ComponentesNombre.Concurso ){ objName=tipo.toString(); objAlias="concurso"; object = new Concurso(); } if(tipo == tipos.ComponentesNombre.Dudas){ objName=tipo.toString(); objAlias="dudas"; object = new Dudas(); } if(tipo == tipos.ComponentesNombre.Lenguaje){ objName=tipo.toString(); objAlias="lenguaje"; object = new DTO.Lenguaje(); } if(tipo == tipos.ComponentesNombre.LenguajeConcurso ){ objName=tipo.toString(); objAlias="lenguajes_concurso"; object = new LenguajesConcurso(); } if(tipo == tipos.ComponentesNombre.Reactivo){ objName=tipo.toString(); objAlias="reactivo"; object = new Reactivo(); } if(tipo == tipos.ComponentesNombre.Rol){ objName=tipo.toString(); objAlias="rol"; object = new Rol(); } if(tipo == tipos.ComponentesNombre.Servidor){ objName=tipo.toString(); objAlias="servidor"; object = new Servidor(); } if(tipo == tipos.ComponentesNombre.Usuario ){ objName=tipo.toString(); objAlias="usuario"; object = new Usuario(); } } public List casting(List list){ if(objName.equals(tipos.ComponentesNombre.Aclaraciones.toString() )){ return (List<Aclaraciones>) list; } if(objName.equals(tipos.ComponentesNombre.CodigoFuente.toString() )){ return (List<CodigoFuente>) list; } if(objName.equals(tipos.ComponentesNombre.Concurso.toString() )) { return (List<Concurso>) list; } if(objName.equals(tipos.ComponentesNombre.Dudas.toString() )) { return (List<Dudas>) list; } if(objName.equals(tipos.ComponentesNombre.Lenguaje.toString() )) { return (List<DTO.Lenguaje>) list; } if(objName.equals(tipos.ComponentesNombre.LenguajeConcurso.toString())){ return (List<LenguajesConcurso>) list; } if(objName.equals(tipos.ComponentesNombre.Reactivo.toString() )) { return (List<Reactivo>) list; } if(objName.equals(tipos.ComponentesNombre.Rol.toString())) { return (List<Rol>) list; } if(objName.equals(tipos.ComponentesNombre.Servidor.toString())) { return (List<Servidor>) list; } if(objName.equals(tipos.ComponentesNombre.Usuario.toString())){ return (List<Usuario>) list; } return (List<Object>) list; } public Object getById(String id){ try { tx = sesion.beginTransaction(); System.out.println("FROM "+objName+" AS "+objAlias+" WHERE id='"+id+"'"); Query q = sesion.createQuery ("FROM "+objName+" AS "+objAlias+" WHERE id='"+id+"'"); //List objectList = (List<Concurso>) q.list(); //objClass = objectList.size()>0?objectList.get(0):concurso; object = casting(q.list()).size()>0?casting(q.list()).get(0):object; } catch (Exception e) { e.printStackTrace(); }finally{ return object; } } //public List getList() { public List getList() { //List<Usuario> usersList = null; List objList = null; try { tx = sesion.beginTransaction(); Query q = sesion.createQuery ("from "+objName+" as "+objAlias); objList = (List) q.list(); } catch (Exception e) { e.printStackTrace(); } return objList; } public String guardar(Object obj) throws HibernateException { String id = ""; try { tx = sesion.beginTransaction(); id = (String) sesion.save(obj); tx.commit(); } catch (Exception e) { System.err.append("insert error: "+e); } finally { sesion.close(); return id; } } //alias [guardar] public String insert(Object obj) throws HibernateException { String id = ""; try { tx = sesion.beginTransaction(); id = (String) sesion.save(obj); tx.commit(); } catch (Exception e) { System.err.append("insert error: "+e); } finally { sesion.close(); return id; } } public void update(Object obj){ try { tx = sesion.beginTransaction(); sesion.update(obj); tx.commit(); }catch (Exception e) { e.printStackTrace(); } } public int count(String from){ try { tx = sesion.beginTransaction(); return sesion.createQuery("from "+from).list().size(); }catch (Exception e) { e.printStackTrace(); return 0; } } }
09012143a
trunk/jv3/src/java/DAO/UtilDao.java
Java
gpl2
6,648
package DAO; import DTO.Usuario; import java.util.Date; import java.util.List; import org.hibernate.HibernateException; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.Transaction; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author Windows */ public class UsuarioDAO extends UtilDao{ /* public List getUsuario(String id) { List<Usuario> usersList = null; try { tx = sesion.beginTransaction(); //Query q = sesion.createQuery ("from Usuarios as usuario where id='"+id+"'"); Query q = sesion.createQuery ("from Usuario as usuario"); usersList = (List<Usuario>) q.list(); } catch (Exception e) { e.printStackTrace(); } return usersList; }*/ public Usuario getUsuarioById(String id){ Usuario user = new Usuario(); try { tx = sesion.beginTransaction(); Query q = sesion.createQuery ("FROM Usuario AS usuario WHERE id='"+id+"'"); List<Usuario> usersList = (List<Usuario>) q.list(); user = usersList.size()>0?usersList.get(0):user; } catch (Exception e) { e.printStackTrace(); }finally{ return user; } } public Usuario getUsuarioByUserPass(String userStr, String passStr){ Usuario user = new Usuario(); try { tx = sesion.beginTransaction(); Query q = sesion.createQuery ("FROM Usuario AS usuario "+ "WHERE username='" + userStr + "' AND pass = '" + passStr + "'"); List<Usuario> usersList = (List<Usuario>) q.list(); user = usersList.size()>0?usersList.get(0):user; } catch (Exception e) { e.printStackTrace(); }finally{ return user; } } public void updateLastLogin(Usuario usuario){ try { tx = sesion.beginTransaction(); usuario.setUltimoAcceso( new Date() ); sesion.update(usuario); tx.commit(); }catch (Exception e) { e.printStackTrace(); } } /* public void update(Usuario usuario){ try { tx = sesion.beginTransaction(); sesion.update(usuario); tx.commit(); }catch (Exception e) { e.printStackTrace(); } } public int count(){ try { tx = sesion.beginTransaction(); return sesion.createQuery("from Usuario").list().size(); }catch (Exception e) { e.printStackTrace(); return 0; } }*/ public int countByStatus(tipos.UsuarioStatus status){ try { tx = sesion.beginTransaction(); return sesion.createQuery("FROM Usuario WHERE status = '" + status.toString() +"'").list().size(); }catch (Exception e) { e.printStackTrace(); return 0; } } public int countByTipo(tipos.UsuarioTipo tipo){ try { tx = sesion.beginTransaction(); return sesion.createQuery("FROM Usuario WHERE tipo = '" + tipo.toString() +"'").list().size(); }catch (Exception e) { e.printStackTrace(); return 0; } } public int countByUsername(String username){ try { tx = sesion.beginTransaction(); return sesion.createQuery("FROM Usuario WHERE username = '" + username +"'").list().size(); }catch (Exception e) { e.printStackTrace(); return 0; } } }
09012143a
trunk/jv3/src/java/DAO/UsuarioDAO.java
Java
gpl2
3,832