Tuesday, December 8, 2015

Java – Simple TextEditor

Using java to building a simple text editor application

  1. – Create menu, contextual menu
  2. – Using toolbox component
  3. – Using JTextPane
  4. – Understand JFileChooser, JColorChooser


You can down load source =>> here <<==

Some app’s interface

Công cụ chuyển ngôn ngữ miễn phí

Convert .NET (Based on .NET 4.5)
Convert .NET phát triển một công cụ tích hợp, mạnh mẽ, đa mục đích chuyển đổi. Các tính năng: C # sang VB và ngược lại, LINQ tester, mã hóa / giải mã, Regular Expression tester, Base64 Encoding / Decoding và dịch văn bản đầy đủ.

Chi tiet tai day


Voi cong cu nay viet chuyen doi qua lai giua cac ngon ngu tro nen vo cung nhanh chong va chinh xac.

Tác giả

Đôi điều về tôi
Birthday: September 20
Address: Vietnam
Personal email: ntdan@live.com
Gender: Male
Location: Viet Nam
Occupation: Can Tho
More : Lecturer of Can Tho University
Interests: Computer; Travel; sport
Job title: Lecturer
Sở thích: Trao đổi kiến thức với mọi người, cafe một mình (enjoy coffee –> just alone). Mục tiêu: Hoàn thiện bản thần và cải thiện môi trường sống. Triết lý sống: Cuộc sống thật công bằng.


Experiment

Aptech Faculty and Lecturer of Infomation Technilogy and MultiMedia – Can Tho University from 2009 until now

  • .Net Technics: c#, asp.net, asp.net MVC, winform app.
  • Database: SQL Server, MySQL, Oracle.
  • Java: java language, jsp, ejb, struts, JSF, Android.
  • Network: MCITP
  • Cloud computing
  • PHP: ecommerce website – development trainer
  • Mobile Application Development (Android platform)
Lecturer of Đồng Tháp University – Vietnam (2006)
ECG data format translator – Desktop App – Coding (JP)
Hopital Information System – Desktop App – Design, Coding (4 start – Vinasa) (VN)
Human Resource Management – Desktop App – Design, Coding, Leader (VN)

Publish

Simulating flooding situation in Mekong Delta region by the influence of rainfall – 16th National IT Conference – Duy Tan University – VietNam(2013)

Graduated


  1. Master (Data mining) – 2013 – Nantes PolyTech University.
  2. Bachelor – 1999 to 2004  – Can Tho University.

    Training


    1. Android app development certificate
    2. Chứng chỉ nghiệp vụ sử phạm – Can Tho University(2011)
    3. Triết học – Can Tho University(2011)
    4. Vietnam – Japan bridge engineer – Yokohama Japanese (2009)
    5. Linux – Khoa công nghệ thông tin ĐHCT (2006)

      MICROSOFT CERTIFICATIONS:

      • MICROSOFT CERTIFICATION EXAMS COMPLETED SUCCESSFULLY:
      • 640 TS:Windows Server 2008 Active Directory, Configuring August 06, 2010
      • 536 TS: Microsoft .NET Framework – Application Development Foundation January 09, 2009
      • 526 TS: Microsoft® .NET Framework 2.0 – Windows®-based Client Development September 26, 2008

      Monday, December 7, 2015

      Xây dựng ứng dụng MDI với Java (netbean, ứng dụng form cha-con)

      MDI application là loại giao diện ứng dụng rất phổ biến trên nền hệ điều hành window. Java hỗ trợ 02 đối tượng jDesktopPaneJInternalFrame cho phép lập trình viên tạo ra loại giao diện ứng dụng này đơn gian và nhanh chóng.

      Trong bài này tôi hướng dẫn căn bản cho các bạn sinh viên (lập trình viên) từng bước tạo ứng dụng có kiểu giao diện này.
      1. Tạo form chính (FrmMain)
      2. Định nghĩa form con (Children form)
      3. Chỉ đinh form cha-con.
      4. Ràng buộc form con chỉ được mở 1 lần trong form cha.

      Bước 1: Tạo ứng dụng Java destop với netbean.
      + File -> New Project -> chọn kiểu java application
      Bước 2: Tạo đối tượng form cha
      + File -> New File -> chọn Swing GUI Forms -> chọn JFrame Form phía bên phải
      + Thiết kế menu chính của chương trình: Kéo thả Menu Bar và jDesktopPane vào form chính như hình dưới

      [caption id="attachment_1086" align="aligncenter" width="300"]Giao diện tạo form chính Giao diện tạo form chính[/caption]

      Bước 3: Xây dựng các form con, trong ví dụ này tôi tạo form Login
      + File -> New File chọn tiếp loại JInternalFrame

      Các bạn thiết kế lại giao diện form con cho phù hợp

      Bước 4: Gán form con và form cha
      + Chọn menu login trong form cha: Click chuột phải và chọn event => action performed
      [sourcecode language="java"]
      for (JInternalFrame frmChild : jDesktopPane1.getAllFrames()) {
      frmChild.dispose();
      }

      FrmLogin frmLogin = new FrmLogin();
      frmLogin.setTitle("Login to system");
      frmLogin.setLocation(this.getWidth()/2 - frmLogin.getWidth()/2,(this.getHeight()-20)/2 - frmLogin.getHeight()/2 - 20);
      jDesktopPane1.add(frmLogin);
      frmLogin.setVisible(true);
      [/sourcecode]

      Dòng lệnh for đóng tất cả các form con đang mở.
      [sourcecode language="java"]
      jDesktopPane1.add(frmLogin);
      frmLogin.setVisible(true);
      [/sourcecode]
      Đoạn gán form login vào form main.

      OK, bây giờ chạy form cha và chọn menu login ta sẽ có kết quả

      [caption id="attachment_1087" align="aligncenter" width="300"]Form con Form con[/caption]

      Bước 5: Qui định form chỉ được mở 1 lần, nếu trước đó đã mở và hiện đang bị che khuất thì chỉ hiển thị form con lên trên (active). Trong ví dụ này tôi chọn form About để làm demo
      + Định nghĩa biên frmAbout có kiểu là FrmAbout
      + Trong sự kiện Action Performed của menu About ta cung cấp code như sau
      [sourcecode language="java"]
      private void jMenuItem3ActionPerformed(java.awt.event.ActionEvent evt) {
      // TODO add your handling code here:
      if(frmAbout == null || frmAbout.isClosed())
      {
      frmAbout = new FrmAbout();
      jDesktopPane1.add(frmAbout);
      frmAbout.setLocation(this.getWidth()/2 - frmAbout.getWidth()/2,(this.getHeight()-20)/2 - frmAbout.getHeight()/2 - 20);
      frmAbout.setVisible(true);
      }
      else
      {
      frmAbout.setLocation(this.getWidth()/2 - frmAbout.getWidth()/2,(this.getHeight()-20)/2 - frmAbout.getHeight()/2 - 20);
      frmAbout.setVisible(true);
      }
      }
      [/sourcecode]

      Như vậy là chúng ta vừa sủ dụng jDesktopPane và jInternalFrame để xây dựng ứng dụng MDI rất đơn gian. Hi vọng nó sẽ cho các bạn một các nhìn ban đầu về các xây dựng MDI application trên java với sự hỗ trợ của netbean.

      Video từng bước tại đây

      Thursday, December 3, 2015

      Java - Simple TextEditor

      Using java to building a simple text editor application


      - Create menu, contextual menu
      - Using toolbox component
      - Using JTextPane
      - Understand JFileChooser, JColorChooser

      You can down load source =>> here <<==

      Video step by step ==>> at here <<==

      Some app's interface


      [gallery ids="1961,1963,1964,1962" type="rectangular"]


      Load all system font on font combobox



      private void loadFont() {
      GraphicsEnvironment gEnv = GraphicsEnvironment.getLocalGraphicsEnvironment();
      // get all font name&amp;amp;amp;amp;amp;amp;amp;nbsp;
      String[] fontNames = gEnv.getAvailableFontFamilyNames();
      // load to combobox
      ComboBoxModel model = new DefaultComboBoxModel(fontNames);
      jcbFont.setModel(model);
      }

      When user select font and size, we will setting font and size for textpane component

      private void jcbFontActionPerformed(java.awt.event.ActionEvent evt) {
      // Change font of text
      jTextPane1.setFont(new Font(jcbFont.getSelectedItem().toString(),
      Font.PLAIN, Integer.parseInt(jcbSelectSize.getSelectedItem().toString())));
      }

      private void jcbSelectSizeActionPerformed(java.awt.event.ActionEvent evt) {
      // Select size of text
      String getSize = jcbSelectSize.getSelectedItem().toString();
      Font f = jTextPane1.getFont();
      // setting new size
      jTextPane1.setFont(new Font(f.getFontName(),
      f.getStyle(), Integer.parseInt(getSize)));
      }

      JColorChooser API of Java swing help our get a color from system color dialog, using code below for ActionPerformed event of color button.

      private void btnSelectColorActionPerformed(java.awt.event.ActionEvent evt) {
      Color jColor = selectColor;
      // open color dialog and select Color
      if ((jColor = JColorChooser.showDialog(this, "Select color", jColor)) != null) {
      selectColor = jColor;
      // set text color
      jTextPane1.setForeground(selectColor);
      }
      }

      RTFEditorKit can help reading formatted text on JTextPane and write down file system with rich text format


      When user click on Save button or save as menu

      private void save() {
      JFileChooser file = new JFileChooser();
      TextFilter filter = new TextFilter();
      file.setFileFilter(filter);
      String fileName = "";
      // show save file dialog
      if (file.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
      // get full path of selected file
      fileName = file.getSelectedFile().getAbsolutePath();
      // get meta of text
      StyledDocument doc = (StyledDocument) jTextPane1.getDocument();
      // convert to richtext format
      RTFEditorKit kit = new RTFEditorKit();
      BufferedOutputStream out;
      try {
      out = new BufferedOutputStream(new FileOutputStream(fileName));
      // save content to file
      kit.write(out, doc, doc.getStartPosition().getOffset(), doc.getLength());
      out.flush();
      out.close();
      } catch (Exception e) {
      System.out.println("Err:" + e.toString());
      }

      } else {
      return;
      }
      }

      Handing button Open file or menu Open file as

      private void open() {
      JFileChooser file = new JFileChooser();
      TextFilter filter = new TextFilter();
      file.setFileFilter(filter);
      String fileName = "";
      // show open file dialog
      if (file.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
      fileName = file.getSelectedFile().getAbsolutePath();
      } else {
      return;
      }
      // using richtext format
      RTFEditorKit rtf = new RTFEditorKit();
      try {
      // load file into jTextPane
      FileInputStream fi = new FileInputStream(fileName);
      rtf.read(fi, jTextPane1.getDocument(), 0);
      fi.close();
      } catch (Exception e) {
      System.out.println("err:" + e.toString());
      }
      }

      This is just demo java beginner.
      I hope that, it is useful for you.

      Thursday, November 5, 2015

      jax-rs (sử dụng jersey) (P1)

      jax-rs (sử dụng jersey) (P1)

      1. Tạo Rest service trên java sử dụng gói jersey

      2. Gọi Rest service từ trang html với java script


      Trong bài này chúng ta sẽ tìm hiểu các tạo dich vụ vụ web theo kiến trúc Rest. Bài này chúng ta sẽ cài đặt cách giao tiếp qua phương thức GET.
      B1: Tạo java web project
      B2: Tạo rest service
      rest1
      rest2
      rest3
      Sau khi xong, mở file web.xml chúng ta sẽ thấy xuất hiện thêm đoạn xml sau:
      [sourcecode language="xml"]
      <servlet>
      <servlet-name>ServletAdaptor</servlet-name>
      <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
      <load-on-startup>1</load-on-startup>
      </servlet>
      <servlet-mapping>
      <servlet-name>ServletAdaptor</servlet-name>
      <url-pattern>/rest/*</url-pattern>
      </servlet-mapping>
      [/sourcecode]

      Hiệu chỉnh lại nội dung của lớp Student như sau:
      [sourcecode language="java"]
      package codes;
      import javax.ws.rs.PathParam;
      import javax.ws.rs.Path;
      import javax.ws.rs.GET;
      import javax.ws.rs.Produces;
      import javax.ws.rs.QueryParam;

      @Path("student")
      public class Student {
      public Student() {
      }
      /**
      * Phuong thuc se duoc kich hoat khi nhan duoc
      * yeu cau tu phia client theo phuong phap get
      * Ket qua tra ve chuyen thanh chuoi
      */
      @GET
      @Produces("text/plain")
      public String getText() {
      return "hello moto";
      }

      /**
      * Phuong thuc se duoc kich hoat khi nhan duoc
      * yeu cau tu phia client theo phuong phap get
      * Ket qua tra ve chuyen thanh chuoi XML
      */
      @Path("/xml")
      @GET
      @Produces("text/xml")
      public String getXML(@QueryParam("id") int id) {
      try {
      JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
      Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
      jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
      Customer customer = new Customer(id, "Nguyen Van Mit", "Can Tho");
      StringWriter sw = new StringWriter();
      jaxbMarshaller.marshal(customer, sw);
      String xmlString = sw.toString();
      return xmlString;
      } catch (JAXBException ex) {
      return ex.toString();
      }
      }

      /**
      * Phuong thuc se duoc kich hoat khi nhan duoc
      * yeu cau tu phia client theo phuong phap get
      * nhan tham so id theo cach gan them vao URL
      * Ket qua tra ve chuyen thanh chuoi xml
      */
      @Path("/xml/{id}")
      @GET
      @Produces("text/xml")
      // @PathParam("id") tim phan id tren URL
      public String getXMLID(@PathParam("id") int id) {
      return "<rs><id>"+id+"</id>"
      + "<name>hello moto</name>"
      + "</rs>";
      }

      /**
      * Phuong thuc se duoc kich hoat khi nhan duoc
      * yeu cau tu phia client theo phuong phap get
      * Ket qua tra ve chuyen thanh chuoi JSON
      */
      @Path("/json")
      @GET
      @Produces("text/json")
      public String getJSON() {
      return "{'id':1, "
      + "'name':'Nguyen Van Mit'}";
      }
      }
      [/sourcecode]

      Biên dịch và deploy website.
      Mở trình duyệt và gõ địa chỉ như sau để test:
      rest4

      rest5

      Như vậy là chúng ta đã có được dịch vụ web theo kiến trúc Rest
      Các bước thực hiện chi tiết và tạo client để gọi dịch vụ với ajax tham khảo video này:

      [embed]https://youtu.be/BOhU3gKGpKo[/embed]

      Thử xem sao !

      Friday, October 30, 2015

      HTML5 Lưu trữ dữ liệu web

      Bài trước, chúng ta đã tìm hiểu một đặc điểm thú vị của HTML5: hỗ trợ vẽ các đối tượng 2D thông qua thẻ canvas. Hôm nay, chúng ta lại tiếp cận một API mới của HTML5, lưu trữ dữ liệu web ở phía máy khách.

      Lưu trữ web là một đặc điểm kỹ thuật được đưa ra bởi W3C, hỗ trợ việc lưu trữ dữ liệu tại phiên làm việc của người dùng hoặc lưu trữ trong thời gian lâu dài. Nó cho phép lưu trữ 5 MB thông tin cho mỗi tên miền.

      Có 2 loại:

      • sesionStorage: lưu trữ dữ liệu trong một phiên làm việc (sẽ bị xóa khi đóng cửa sổ trình duyệt)


      Ví dụ: xây dựng phiên làm việc của người dùng sau khi đăng nhập, …

      • localStorage: lưu trữ cục bộ (thông tin được lưu trữ lâu dài, không giới hạn thời gian)


      Ví dụ: đếm số lần người dùng đã truy cập trang; ghi nhớ thông tin tài khoản, mật khẩu cho lần đăng nhập sau, …

      Trước khi sử dụng sessionStorage và localStorage, chúng ta phải kiểm tra trình duyệt hiện tại có hỗ trợ 2 dạng lưu trữ này không?
      Code tham khảo kiểm tra trình duyệt:

      [sourcecode language="html"]
      <!DOCTYPE HTML>
      <html>
      <head>
      <meta charset="utf-8">
      <title>Kiểm tra lưu trữ phiên</title>
      <script>
      function checkSupport()
      {
      if (('sessionStorage' in window) && window['sessionStorage'] !== null)
      {
      alert("Trình duyệt hỗ trợ lưu trữ web");
      return;
      }
      alert("Trình duyệt không hỗ trợ lưu trữ web");
      }
      </script>
      </head>

      <body onLoad="checkSupport()">
      </body>
      </html>
      [/sourcecode]

      Để kiểm tra localStorage trong trình duyệt: thay đổi dòng code:

      [sourcecode language="html"]
      if (('sessionStorage' in window) &amp;amp;&amp;amp; window['sessionStorage'] !== null)
      [/sourcecode]

      thành

      [sourcecode language="html"]
      if (('localStorage' in window) &amp;amp;&amp;amp; window['localStorage'] !== null)
      [/sourcecode]

      1. Cách lưu trữ dữ liệu:

      Có 3 cách để lưu trữ:

      • Thông qua các hàm hỗ trợ sẵn: lưu trữ dạng key/value (biến/giá trị)
        + Gán giá trị cho biến: sessionStorage.setItem(“key”) = value (key,value có thể là chuỗi hoặc số)
        sessionStorage.setItem('name', 'user')
        + Lấy giá trị của biến: sessionStorage.getItem(“key”)
        sessionStorage.getItem('name')
        + Xóa một giá trị biến đã tạo: sessionStorage.removeItem(“key”)
        sessionStorage.removeItem('name')
        + Xóa tất cả các biến đã tạo: sessionStorage.clear()

      • Thông qua cú pháp mảng: sessionStorage[“key”] = value
        sessionStorage['name'] = 'user'

      • Thông qua toán tử dấu chấm: sessionStorage.key = value
        sessionStorage.name = “user”


      Ghi chú: 3 cách lưu trữ này cũng áp dụng cho localStorage

      Ví dụ đơn giản để lưu trữ dữ liệu:

      [sourcecode language="html"]
      <!DOCTYPE HTML>
      <html>
      <head>
      <meta charset="utf-8">
      <title>Working with Session Storage</title>
      <script>
      function testStorage()
      {
      if(('sessionStorage' in window) && window['sessionStorage'] != null){
      sessionStorage.setItem('name', 'Sarah');
      document.write("The name is:" + sessionStorage.getItem('name') + "
      ");
      sessionStorage.setItem(6, 'Six');
      document.write("The number 6 is : " + sessionStorage.getItem(6) + "
      ");
      sessionStorage["age"] = 20;
      document.write("The age is : " + sessionStorage.age);
      }
      }
      </script>
      </head>

      <body onLoad="testStorage()">
      </body>
      </html>
      [/sourcecode]

      Kết quả:

      1

      2. Ví dụ: Sử dụng sessionStorage để tạo phiên làm việc khi người dùng đăng nhập:

      Kịch bản xử lý như sau:

      • Tạo form đăng nhập.

      • Tạo một trang thanhcong.html để hiển thị thông báo đăng nhập thành công.

      • Nếu người dùng chưa đăng nhập -> hiển thị trang thanhcong.html thì có thông báo “Bạn chưa đăng nhập”

      • Nếu người dùng vào trang đăng nhập rồi tiến hành đăng nhập -> sau khi đăng nhập thành công, qua trang thanhcong.html và hiển thị “Chúc mừng bạn tên đăng nhập đã đăng nhập thành công”.


      Code:

      Trang đăng nhập (dangnhap.html)

      [sourcecode language="html"]
      <!DOCTYPE HTML>
      <html>
      <head>
      <meta charset="utf-8">
      <title>Phiên làm việc người dùng</title>
      <script>
      function kiemTra()
      {
      //kiem tra du lieu
      if(('sessionStorage' in window) && window['sessionStorage'] !== null){
      // bỏ qua bước bắt lỗi tài khoản, mật khẩu

      // tạo sessionStorage với key là user lưu tài khoản người dùng
      sessionStorage.setItem('user', document.frm.txtTK.value);
      // tạo sessionStorage với key là pass lưu mật khẩu người dùng
      sessionStorage.setItem('pass', document.frm.txtMK.value);
      return true;
      }else alert("Không hỗ trợ");
      }
      </script>
      </head>
      <body >

      <form name="frm" onSubmit="return kiemTra()" action="thanhcong.html">

      <table>

      <tr>

      <td>Tài khoản:</td>


      <td><input name="txtTK" /></td>

      </tr>


      <tr>

      <td>Mật khẩu:</td>


      <td><input name="txtMK" type="password"/></td>

      </tr>


      <tr align="center">

      <td colspan="2"><input type="submit" value="Đăng nhập" /></td>

      </tr>

      </table>

      </form>

      </body>
      </html>
      [/sourcecode]

      Trang thông báo thành công (thanhcong.html):

      [sourcecode language="html"]
      <!doctype html>
      <html>
      <head>
      <meta charset="utf-8">
      <title>Thanh cong</title>
      <script>
      if(sessionStorage.getItem('user') != null)
      document.write("Chúc mừng bạn "
      + sessionStorage.getItem('user')
      + " đã đăng nhập thành công");
      else document.write('Bạn chưa đăng nhập');
      /* Xử lý nút thoát : xóa biến lưu trữ user*/
      function thoat(){
      sessionStorage.removeItem('user');
      location.href="thanhcong.html";
      }
      </script>
      </head>

      <body>

      <form>
      <input value="Thoát" type="button" onClick="thoat()" />
      </form>

      </body>
      </html>
      [/sourcecode]

      Video:
      [embed]https://youtu.be/ee7G5Y3A8WE[/embed]

      3. Ví dụ: Sử dụng localStorage để đếm số lần người dùng truy cập vào trang web:

      Mỗi lần người dùng vào trang web:

      • Nếu là lần đầu tiên: khởi tạo biến localStorage[‘truy cập’] là 1.

      • Nếu là lần thứ 2 về sau: cộng thêm 1 vào biến localStorage[‘truy cập’]


      Chú ý: Tắt trình duyệt và mở lên lại thì biến localStorage[‘truy cập’] vẫn cập nhật từ giá trị cũ.

      Code:

      [sourcecode languange="html"]
      <!DOCTYPE HTML>
      <html>
      <head>
      <meta charset="utf-8">
      <title>Lưu trữ cực bộ</title>
      <script>
      function store()
      {
      if(('localStorage' in window) && window['localStorage'] != null){
      if(localStorage.getItem('truycap') == null)
      localStorage.setItem('truycap', 1);
      else
      localStorage.setItem('truycap', parseInt(localStorage.getItem('truycap')) + 1);
      document.write("Số lần đăng nhập = " + localStorage.getItem('truycap'));

      }
      else{
      alert("Trình duyệt không hỗ trợ LocalStorage");
      }
      }
      </script>
      </head>
      <body onLoad="store()">
      </body>
      </html>
      [/sourcecode]

      Kết quả:
      Lần chạy đầu tiên:
                Số lần đăng nhập = 1
      Reload lại trang:
                Số lần đăng nhập = 2
      Các lần chạy tiếp theo -> mỗi lần tăng lên 1.
      Tắt trình duyệt và chạy lại trình duyệt vừa rồi:
                Số lần đăng nhập = 3
      Các bạn có thể tham khảo thêm:
      4. Ví dụ sử dụng localStorage để ghi nhớ thông tin đăng nhập:




      [sourcecode language="html"]
      <!DOCTYPE HTML>
      <html>
      <head>
      <meta charset="utf-8">
      <title>Lưu trữ cực bộ</title>
      <script>
      function loadData(){
      if(('localStorage' in window)
      && window['localStorage'] != null
      && localStorage.getItem('ghinho')
      ){
      document.frmDangNhap.txtDN.value = localStorage.getItem('tendangnhap');
      document.frmDangNhap.txtMK.value = localStorage.getItem('matkhau');
      }
      }
      function store()
      {
      var tendangnhap = document.getElementById("txtDN").value;
      var matkhau = document.getElementById("txtMK").value;
      var ghinho = document.getElementById("chkGhiNho");
      if(('localStorage' in window) && window['localStorage'] != null){
      localStorage.setItem('tendangnhap', tendangnhap);
      localStorage.setItem('matkhau', matkhau);
      alert("Tên người dùng : " + localStorage.getItem('tendangnhap') + ", Mật khẩu : " + localStorage.getItem('matkhau'));
      }
      else{
      alert("Trình duyệt không hỗ trợ LocalStorage");
      }

      //ghi nho thong tin
      if(ghinho.checked)
      {
      localStorage.setItem('ghinho', 1);
      }
      }
      </script>
      </head>
      <body onLoad="loadData()" >

      <form method="get" name="frmDangNhap" >

      <table width="50%" border="1" align="center">

      <tr>

      <th colspan="2" scope="col">Đăng nhập </th>

      </tr>


      <tr>

      <td>Tên đăng nhập: </td>


      <td><input type="text" id="txtDN" name="txtDN" /></td>

      </tr>


      <tr>

      <td>Mật khẩu:</td>


      <td><input type="text" id="txtMK" name="txtMK" /></td>

      </tr>


      <tr>

      <td></td>


      <td><input type="button" value="Đăng nhập" onClick="store();"/>
      <input type="checkbox" id="chkGhiNho" />Ghi nhớ thông tin</td>

      </tr>

      </table>

      </form>

      </body>
      </html>
      [/sourcecode]

      Video tham khảo
      [embed]https://youtu.be/LcLLxot5bmw[/embed]

      Chúc các bạn hiểu được cơ bản về lưu trữ web trong HTML5

      Wednesday, October 28, 2015

      Android - List and kill background process

      Android OS is a multitasking operating, there are a lot of running background process, these process make your device will be slower. Android SDK provides set of API allow developer can list all background process and kill (stop) them.
      In this post, we will discussing about how listing and kill background process in Android device.

      [caption id="attachment_1855" align="alignnone" width="168"]List all android background processes List all android background processes[/caption]

      We need two permission are KILL_BACKGROUND_PROCESSES and to GET_TASKS.
      Declare two permission as
      [sourcecode language="xml"]
      <uses-permission android:name="android.permission.KILL_BACKGROUND_PROCESSES" />
      <uses-permission android:name="android.permission.GET_TASKS" />
      [/sourcecode]

      Declare 2 variable
      [sourcecode language="java"]
      List<ActivityManager.RunningAppProcessInfo> processes;
      ActivityManager amg;
      [/sourcecode]

      Register service with Android get all running processes
      [sourcecode language="java"]
      // using Activity service to list all process
      amg = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
      // list all running process
      processes = amg.getRunningAppProcesses();
      [/sourcecode]

      Create MyAdapter class extend BaseAdapter class to populate process's information on ListView as
      [sourcecode language="java"]
      public class MyAdapter extends BaseAdapter {

      List<ActivityManager.RunningAppProcessInfo> processes;
      Context context;

      public MyAdapter(List<ActivityManager.RunningAppProcessInfo> processes, Context context) {
      this.context = context;
      this.processes = processes;
      }

      @Override
      public int getCount() {
      return processes.size();
      }

      @Override
      public Object getItem(int position) {
      return processes.get(position);
      }

      @Override
      public long getItemId(int position) {
      return processes.get(position).pid;
      }

      @Override
      public View getView(int position, View convertView, ViewGroup parent) {

      Process pro;

      if(convertView == null)
      {
      convertView = new TextView(context);
      pro = new Process();
      pro.name = (TextView)convertView;

      convertView.setTag(pro);
      }else
      {
      pro = (Process)convertView.getTag();
      }

      pro.name.setText(processes.get(position).processName);

      return convertView;
      }

      class Process
      {
      public TextView name;
      }
      }
      [/sourcecode]
      Display list of process on listview, display name only (just demo).
      [sourcecode language="java"]
      adp = new MyAdapter(processes, MainActivity.this);
      lst.setAdapter(adp);
      [/sourcecode]

      When user longclick on process name, this process will be kill
      [sourcecode language="java"]
      lst.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
      @Override
      public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
      if (load == 1) {
      for (ActivityManager.RunningAppProcessInfo info : processes) {
      if (info.processName.equalsIgnoreCase(
      ((ActivityManager.RunningAppProcessInfo)parent.getItemAtPosition(position)).processName)) {
      // kill selected process
      android.os.Process.killProcess(info.pid);
      android.os.Process.sendSignal(info.pid, android.os.Process.SIGNAL_KILL);
      amg.killBackgroundProcesses(info.processName);
      }
      }
      load = 0;
      // refresh list of process
      skill_Load_Process();
      }
      return true;
      }
      });
      [/sourcecode]

      You only kill user process, with system process you need a rooted device.

      Ok, download sourcecode Here

      Monday, October 26, 2015

      HTML5 - Xây dựng hình ảnh động đơn giản thông qua đối tượng canvas

      Một tiện ích thú vị nhất của HTML5 là hỗ trợ vẽ các đối tượng 2D. Chúng ta có thể vẽ hình tròn, hình chữ nhật, đoạn thẳng, một tấm hình, text, ... lên trang web thông qua các phương thức được hỗ trợ sẵn trong Canvas API của HTML5. Nâng cao hơn nữa, xây dựng một giao diện hoạt hình lên web.

      Hôm nay, chúng ta sẽ tìm hiểu một ví dụ đơn giản nhất để có được một hình ảnh động.

      Vẽ nhiều đối tượng lên một canvas
      1


      Để tạo được hoạt hình, chúng ta phải vẽ lại các đối tượng ở các vị trí khác nhau và lặp đi lặp lại việc vẽ này thông qua hàm setInterval trong Javascript.


      Các bước thực hiện:

      • Tạo đối tượng canvas trong tài liệu để vẽ các hình.

      • Tạo hàm draw() để vẽ các đối tượng (mỗi lần vẽ một hình là một trạng thái -> thiết lập một biến có giá trị thay đổi để gán cho vị trí thay đổi).

      • Cứ mỗi 30/1000 giây sẽ gọi lại hàm draw() một lần để vẽ lại hình ảnh.


      Code tham khảo:

      [sourcecode language="html"]
      <!DOCTYPE html>
      <html>
      <head>
      <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
      <title>HTML5 Animation</title>

      <style>
      #mySwimmerCanvas{
      /*Hiển thị border của canvas*/
      border: 2px solid #FF0000
      }
      </style>

      <script>
      var positionX = 0;
      var positionY = 0;
      // Gọi lại hàm draw sau mỗi thời gian 30/1000 giây
      setInterval(draw, 30);

      //Hàm vẽ người
      function draw(){
      var centerX = 200; // tọa độ x cho tâm của hình tròn thể hiện cái đầu
      var centerY = 50; // tọa độ y cho tâm của hình tròn thể hiện cái đầu
      var radius = 20;
      // thay đổi tọa độ x, y để thiết lập chuyển động hoạt hình
      if (positionX < 30) { positionX += 1; positionY += 1; } else { positionX = 0; positionY = 0; } // khai báo để vẽ các đối tượng 2d lên canvas var canvasSwimmer = document.getElementById("mySwimmerCanvas"); var contextSwimmer = canvasSwimmer.getContext("2d"); //xóa vị trí cũ để vẽ vị trí mới contextSwimmer.clearRect(0,0,400,400); //bắt đầu vẽ contextSwimmer.beginPath(); /*Vẽ đầu (hình tròn) centerX, centerY: tâm đường tròn radius: kích thước bán kính false: vẽ theo chiều kim đồng hồ */ contextSwimmer.arc(centerX, centerY+positionY, radius, 0, 2 * Math.PI, false); contextSwimmer.fillStyle = "#000000"; contextSwimmer.fill(); /* vẽ thân (đoạn thẳng) vẽ nhiều đối tượng lên một canvas -> mỗi đối tượng phải gọi beginPath() lại
      */
      contextSwimmer.beginPath();
      contextSwimmer.moveTo(200,70+positionY); // điểm thứ nhất để vẽ
      contextSwimmer.lineTo(200,175); // điểm thứ hai để vẽ
      contextSwimmer.lineWidth = 10; // độ rộng đoạn thẳng
      contextSwimmer.strokeStyle = "#000000"; // màu đoạn thẳng
      contextSwimmer.lineCap = "round"; // bo tròn hai đầu đoạn thẳng
      contextSwimmer.stroke(); // vẽ đoạn thẳng

      // vẽ cánh tay bên phải (đoạn thẳng)
      contextSwimmer.beginPath();
      contextSwimmer.moveTo(200, 100);
      contextSwimmer.lineTo(175-positionX,140-positionY);
      contextSwimmer.lineWidth = 10;
      contextSwimmer.strokeStyle = "#000000";
      contextSwimmer.lineCap = "round";
      contextSwimmer.stroke();

      // vẽ cánh tay bên trái (đoạn thẳng)
      contextSwimmer.beginPath();
      contextSwimmer.moveTo(200, 100);
      contextSwimmer.lineTo(225+positionX,140-positionY);
      contextSwimmer.lineWidth = 10;
      contextSwimmer.strokeStyle = "#000000";
      contextSwimmer.lineCap = "round";
      contextSwimmer.stroke();

      // vẽ chân bên phải (đoạn thẳng)
      contextSwimmer.beginPath();
      contextSwimmer.moveTo(200, 175);
      contextSwimmer.lineTo(190-positionX,250-positionY);
      contextSwimmer.lineWidth = 10;
      contextSwimmer.strokeStyle = "#000000";
      contextSwimmer.lineCap = "round";
      contextSwimmer.stroke();


      // vẽ chân bên trái (đoạn thẳng)
      contextSwimmer.beginPath();
      contextSwimmer.moveTo(200, 175);
      contextSwimmer.lineTo(210+positionX,250-positionY);
      contextSwimmer.lineWidth = 10;
      contextSwimmer.strokeStyle = "#000000";
      contextSwimmer.lineCap = "round";
      contextSwimmer.stroke();

      }
      </script>
      </head>

      <body onload="draw();">
      <canvas id="mySwimmerCanvas" width="400" height="400" >
      </canvas>
      </body>
      </html>

      [/sourcecode]

      Sau khi hoàn thành (nhấp vào hình để xem kết quả hoàn chỉnh):
      animation
      Chúc các bạn thành công.

      Monday, October 19, 2015

      Máy bay lá dừa - Airplane Toy by coconut leaf

      Cuối tuần làm máy bay lá dừa cho con chơi.
      Snap 2015-10-19 at 13.50.43
      Vật liệu và dụng cụ:

      1. 06 lá dừa

      2. Dao để cắt lá

      Do cách làm khá dài dòng nên upload video


      Vui thôi nhe, ai biết làm con công chỉ tui với nhe.

      Friday, October 9, 2015

      Hai cách quản lý một tập hợp trong Java

      Trong java, bạn có thể quản lý tập hợp các phần tử theo 2 cách:

      • Sử dụng mảng

      • Sử dụng danh sách


      Trong khuôn khổ bài này, chúng ta cùng tìm hiểu ArrayList – một lớp đơn giản để quản lý tập hợp.
      Yêu cầu:
      Tạo một chương trình để người dùng quản lý 5 phần tử kiểu int và lưu vào một mảng.

      • In giá trị các phần tử trong mảng.

      • In các phần tử theo thứ tự giảm dần.

      • In các phần tử trong mảng mà chia hết cho 5.

      • Cho người dùng nhập vào một số, hiển thị số lần xuất hiện của số vừa nhập có trong mảng ban đầu.


      Output:
      1

      1. Cách 1: Khởi tạo mảng int theo cách thông thường:

      int[] array = new int[5];


      Nếu khởi tạo mảng dạng này, khi chúng ta gán mảng 5 phần tử thì số phần tử đó là cố định. Chúng ta muốn tăng số phần tử lên để quản lý nhiều hơn thì phải tốn nhiều công sức cho bước tăng trưởng. Đây cũng là sự bất tiện của cách quản lý này.

      Code tham khảo:

      [sourcecode language="java"]
      public class Array_PrimitiveDataType {

      int[] array;

      public Array_PrimitiveDataType() {
      array = new int[5];
      }

      /**
      * input array
      */
      void inputArray(){
      System.out.println("-----Nhap mang-----");
      Scanner input = new Scanner(System.in);
      for (int i = 0; i &amp;lt; array.length; i++) {
      System.out.print("Nhap phan tu thu " + (i+1) + ":");
      array[i] = input.nextInt();
      }
      System.out.println("");
      }

      void printArray(){
      System.out.println("-----In----");
      for (int i = 0; i &amp;lt; array.length; i++) {
      System.out.print(array[i] + "\t");
      }
      System.out.println("");
      }

      void sortDescArray(){
      System.out.println("-----Sap xep-----");
      for (int i = 0; i &amp;lt;= array.length - 2; i++) {
      for (int j = i+1; j &amp;lt;= array.length -1; j++) {
      if(array[i] &amp;lt; array[j]){
      int temp = array[i];
      array[i] = array[j];
      array[j] = temp;
      }
      }
      }
      }

      void searchNumber(){
      System.out.println("----Tim mot so-----");
      Scanner input = new Scanner(System.in);
      System.out.print("Nhap mot so can tim:");
      int so = input.nextInt();
      int dem = 0;
      for (int i = 0; i &amp;lt; array.length; i++) {
      if(array[i] == so) dem++;
      }
      System.out.println("Co " + dem + " phan tu trong mang co gia tri " + so);
      }

      /**
      * @param args the command line arguments
      */
      public static void main(String[] args) {
      Array_PrimitiveDataType demo = new Array_PrimitiveDataType();
      demo.inputArray();
      demo.printArray();
      demo.sortDescArray();
      demo.printArray();
      }
      }
      [/sourcecode]

      Video:

      [embed]https://www.youtube.com/watch?v=3-Vu-y7SoTk[/embed]

      2. Cách 2: Khởi tạo một đối tượng của lớp ArrayList được hỗ trợ sẵn trong API của Java.

      Với việc quản lý này, người dùng tự do thêm bớt phần tử nếu muốn thông qua các phương thức của nó. Vì nó không giới hạn số phần tử được quản lý. Đây là sự thuận tiện khi sử dụng lớp ArrayList so với cách khai báo thông thường.

      ArrayList array = new ArrayList();


      Đặc biệt: đối tượng trong tập hợp trên chỉ quản lý các đối tượng mà không quản lý các biến kiểu dữ liệu nguyên thủy. Vì vậy, khi thêm dữ liệu mới hoặc lấy ra một phần tử trong tập hợp, chúng ta luôn thao tác với đối tượng (Có thể sử dụng Wrapper Class để quản lý các kiểu dữ liệu nguyên thủy khi cần thiết).

      Code tham khảo:

      [sourcecode language="java"]
      import java.util.ArrayList;
      import java.util.Collection;
      import java.util.Collections;
      import java.util.Iterator;
      import java.util.Scanner;

      /**
      *
      * @author maithicamnhung
      */
      public class Bai1_ArrayList {
      ArrayList arr = new ArrayList();

      // Nhap du lieu
      public void inputList(){
      System.out.println("Enter elements:");
      Scanner input = new Scanner(System.in);
      for(int i = 0 ; i < 4 ; i++){
      System.out.println("Element " + (i+1) + ":");
      int value = input.nextInt();
      arr.add(value);
      }
      }

      // In du lieu mang
      public void printList(){
      System.out.println("======List=====");
      Iterator iarr = arr.iterator();
      while(iarr.hasNext()){
      System.out.println(iarr.next());
      }
      }

      // Sap xep mang tang dan
      public void printListOrderAsc(){
      Collections.sort(arr);
      System.out.println("======List Order Asc=====");
      Iterator iarr = arr.iterator();
      while(iarr.hasNext()){
      System.out.println(iarr.next());
      }
      }

      // Sap xep mang giam dan
      public void printListOrderDes(){
      Collections.sort(arr, Collections.reverseOrder());
      System.out.println("======List Order Des=====");
      Iterator iarr = arr.iterator();
      while(iarr.hasNext()){
      System.out.println(iarr.next());
      }
      }

      // Chia het cho 5
      public void divideFive(){
      System.out.println("Element divide 5:");
      Iterator iarr = arr.iterator();
      while(iarr.hasNext()){
      Integer value = (Integer) iarr.next();
      if(value.intValue() % 5 == 0){
      System.out.println(value);
      }
      }
      }

      public void searchNumber(){
      Scanner input = new Scanner(System.in);
      System.out.println("Enter number to search:");
      int count = 0;
      int number = input.nextInt();
      Iterator iarr = arr.iterator();
      while(iarr.hasNext()){
      Integer value = (Integer)iarr.next();
      if(value.intValue() == number){
      count++;
      }
      }
      System.out.println("Count: " + count);
      }

      public static void main(String[] args) {
      Bai1_ArrayList arrList = new Bai1_ArrayList();
      arrList.inputList();
      arrList.printList();
      arrList.printListOrderAsc();
      arrList.printListOrderDes();
      arrList.divideFive();
      arrList.searchNumber();
      }
      }
      [/sourcecode]

      Video:

      [embed]https://www.youtube.com/watch?v=lHJ0r_SHDMA[/embed]

      Chúc các bạn thành công.

      Thursday, October 8, 2015

      Hiệu chỉnh lỗi Genymotion không load VirtualBox trên window 10

      Bài này chúng ta cùng fix lỗi "Virtualization engine not found" trên Genymotion
      Tham khảo bài hướng dẫn cài đặt genymotion chi tiết
      Khi chạy VirtualBox 5x trên window 10 thi mặc nhiên Genymotion không còn gọi được VirtualBox nữa dẫn đến lỗi "Virtualization engine not found". Chỉ cần hiệu chỉnh lại một trong các card mạng ảo của VirtualBox về dãy địa chỉ cục bộ 192.168.x.x (lớp C) là giải quyết được lỗi này.

      • Mở VirtualBox -> File -> Preferences

      • Chọn NetWork -> Host only Networks ->chọn một card mạng bất ky

      • Hiệu chỉnh lại như sau:


      Bước 1:
      GenyCanLoad
      Bước 2:
      GenyCanLoad_1
      Bước 3:
      GenyCanLoad_2
      Bước 4:
      GenyCanLoad_3

      Cài đặt plugin Genymotion vào AndroidStudio
      [embed]https://youtu.be/alHc903yA94[/embed]

      Vậy là xong !

      Friday, September 25, 2015

      Upload file đơn giản với JSF 2.2

      JSF (Java Server Face) 2.2 bổ sung thêm thẻ inputFile cho phép upload file lên server web trở nên đơn giản hơn bao giờ hết.
      [embed]https://youtu.be/caDsv_-EHPY[/embed]

      1. Tạo Website sử dụng JSF 2.2
      2. Tạo managebean như sau:
      [sourcecode language="java"]
      package codes;
      import java.io.IOException;
      import java.util.logging.Level;
      import java.util.logging.Logger;
      import javax.faces.bean.ManagedBean;
      import javax.faces.bean.RequestScoped;
      import javax.faces.context.FacesContext;
      import javax.servlet.http.Part;
      /**
      *
      * @author ntdan
      */
      @ManagedBean
      @RequestScoped
      public class Upload_File {

      private Part file;
      private String fileName;
      private long fileSize;

      /**
      * Creates a new instance of Upload_File
      */
      public Upload_File() {
      }

      public Part getFile() {
      return file;
      }

      public void setFile(Part file) {
      this.file = file;
      }

      public String getFileName() {
      return fileName;
      }

      public void setFileName(String fileName) {
      this.fileName = fileName;
      }

      public String upload()
      {
      try {
      // get name of selected file
      fileName = file.getSubmittedFileName();
      // get file's size
      fileSize = file.getSize();
      // get fullpath of opload folder in web root
      String dirPath= FacesContext.getCurrentInstance().getExternalContext().getRealPath("/upload");
      // write file to upload folder
      file.write(dirPath + "/" + fileName);

      } catch (IOException ex) {
      Logger.getLogger(Upload_File.class.getName()).log(Level.SEVERE, null, ex);
      }

      return "view";
      }

      public long getFileSize() {
      return fileSize;
      }

      public void setFileSize(long fileSize) {
      this.fileSize = fileSize;
      }
      }
      [/sourcecode]
      3. Tạo trang index.xhtml để upload file như sau:
      [sourcecode language="html"]
      <?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://xmlns.jcp.org/jsf/html"
      xmlns:f="http://xmlns.jcp.org/jsf/core">
      <h:head>
      <title>Facelet Title</title>
      </h:head>
      <h:body>
      Demo for upload file
      <f:view>
      <h:form enctype="multipart/form-data">
      File:<br/>
      <h:inputFile value="#{upload_File.file}"/>
      <br/>
      <h:commandButton value="Upload" action="#{upload_File.upload()}"/>
      <br/>
      File:${upload_File.fileName} - #{upload_File.fileSize} bytes !
      </h:form>

      </f:view>

      </h:body>
      </html>
      [/sourcecode]

      4. Tạo trang xem ảnh vừa upload và thông tin về hình
      [sourcecode language="html"]
      <?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://xmlns.jcp.org/jsf/html"
      xmlns:f="http://xmlns.jcp.org/jsf/core">
      <h:head>
      <title>Facelet Title</title>
      </h:head>
      <h:body>
      <f:view>
      <br/>
      File:${upload_File.fileName} - #{upload_File.fileSize} bytes !
      <br/>
      <h:graphicImage url="/upload/#{upload_File.fileName}" width="400px"/>
      </f:view>

      </h:body>
      </html>
      [/sourcecode]

      OK, chạy trang index.xhtml --> chonj file upload hệ thống sẽ chuyển qua trang view.xhtml để xem ảnh vừa upload.

      Thursday, September 24, 2015

      Hướng dẫn cài đặt, cấu hình và chạy chương trình Java đơn giản đầu tiên


      1. Download JDK


      Các bạn vào địa chỉ sau để download JDK (hỗ trợ nhiều phiên bản):
      http://www.oracle.com/technetwork/java/javase/downloads/index.html
      JDK
      Chọn Accept License Agreement -> Chọn hệ điều hành đúng để tiến hành tải về.
      JDK2
      Sau khi tải về, cài đặt như các ứng dụng bình thường.
      JDK3
      2. Cài đặt JDK
      caidat1
      Các bạn có thể để đường dẫn mặc định khi cài đặt (C:\) hoặc chọn nơi cài đặt tùy chọn.
      Sau khi cài đặt, chúng ta sẽ có 2 thư mục để có thể biên dịch và thông dịch một chương trình java:
      caidat2
      3. Cấu hình biến môi trường cho java
      Cấu hình trên CMD mỗi lần chạy 1 chương trình java bằng dòng lệnh:

      - Copy thư mục JDK đã cài đặt : C:\Program Files\Java\jdk1.8.0_20\bin
      Thiết lập 2 biến PATH và CLASSPATH mỗi lần thực thi chương trình:
      Giả sử, chương trình nằm trong ổ đĩa D:\
      path
      Cấu hình trên biến môi trường của Window:
      path2
      Đi đến Advanced system settings, chọn Enviroment Variables:
      path3
      Tìm đến 2 biến Path và CLASSPATH để thiết lập các giá trị cho 2 biến này.
      path4
      4. Chạy chương trình đơn giản đầu tiên
      Viết một chương trình đầu tiên với lớp Hello trong Notepad và lưu lại với tên Hello.java:
      code1Biên dịch Hello.java thành file Hello.class bằng chương trình javac.exe trong bộ JDK vừa cài đặt ở trên:
      code2- Vào thư mục chứa tập tin Hello.java, chúng ta sẽ thấy có tập tin Hello.class -> chính là tập tin sau khi biên dịch ra mã byte code.
      - Tiến hành thông dịch tập tin Hello.class để thực thi bằng chương trình java.exe:
      code3Vậy là, chúng ta đã thực thi được một chương trình java đơn giản.
      Chúc các bạn thành công.

      Code tham khảo Hello.java

      [source language="java"]
      public class Hello {

      /**
      * @param args the command line arguments
      */
      public static void main(String[] args) {
      System.out.println("Hello you");
      }
      }
      [/source]

      Tham khảo video:
      [embed]https://youtu.be/rT0cldaEf0w[/embed]

      Tuesday, September 22, 2015

      Bài tập IXJ - Object/ Object List to XML File and XML File to Object/ Object List

      Trong bài tập này chúng ta sẽ chuyển đổi qua lại giữa XML và List<Object>. Bài tập chuyển từ Object <-> XML

      Ví dụ danh sách chứa các Emp như sau:

      [sourcecode language="java"]
      Emp emp = new Emp();
      emp.setCode("A001");
      emp.setName("Nguyen Van Mit");
      emp.setAddress("Can Tho");
      emp.setTel("+8499999999");

      Emp emp1 = new Emp();
      emp1.setCode("A002");
      emp1.setName("Tran Van Cam");
      emp1.setAddress("Can Tho");
      emp1.setTel("+848888888");

      List<Emp> emplist = new ArrayList<Emp>();
      emplist.add(emp);
      emplist.add(emp1);
      [/sourcecode]
      Sẽ được chuyển thành file XML có nội dung như sau:
      [sourcecode language="xml"]
      <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
      <emplist>
      <emp code="A001">
      <address>Can Tho</address>
      <name>Nguyen Van Mit</name>
      <tel>+8499999999</tel>
      </emp>
      <emp code="A002">
      <address>Can Tho</address>
      <name>Tran Van Cam</name>
      <tel>+848888888</tel>
      </emp>
      </emplist>
      [/sourcecode]

      Để thực thực việc chuyển đổi này chúng ta sử dụng thư viện JAXB của Java.
      1. Tạo lớp Emp
      [sourcecode language="java"]
      package jaxb_object_list;
      import javax.xml.bind.annotation.XmlAttribute;
      import javax.xml.bind.annotation.XmlRootElement;
      //the goc
      @XmlRootElement(name = "emp")
      public class Emp {
      private String code;
      private String name;
      private String address;
      private String tel;
      public String getAddress() {
      return address;
      }
      public void setAddress(String address) {
      this.address = address;
      }
      public String getCode() {
      return code;
      }
      @XmlAttribute
      public void setCode(String code) {
      this.code = code;
      }
      public String getName() {
      return name;
      }
      public void setName(String name) {
      this.name = name;
      }
      public String getTel() {
      return tel;
      }
      public void setTel(String tel) {
      this.tel = tel;
      }

      @Override
      public String toString() {
      return "Emp [code:" + code + ", name:" + name + ", address:"
      + address + ", tel:" + tel + "]";
      }
      }
      [/sourcecode]
      2. EmpList
      [sourcecode language="java"]
      package jaxb_object_list;
      import java.util.ArrayList;
      import java.util.List;
      import javax.xml.bind.annotation.XmlAccessType;
      import javax.xml.bind.annotation.XmlAccessorType;
      import javax.xml.bind.annotation.XmlElement;
      import javax.xml.bind.annotation.XmlRootElement;
      // cac thuoc tinh duoc luu duoi dang the
      @XmlAccessorType(XmlAccessType.FIELD)
      // the goc
      @XmlRootElement(name = "emplist")
      public class EmpList {
      // moi phan tu trong danh sach luu thanh the emp
      // cau truc the emp mo ta qua lop Emp
      @XmlElement(name = "emp", type = Emp.class)
      private List<Emp> emplist = new ArrayList<Emp>();
      public EmpList() {}
      public EmpList(List<Emp> emplist) {
      this.emplist = emplist;
      }
      public List<Emp> getEmpList() {
      return emplist;
      }
      public void setEmpList(List<Emp> emplist) {
      this.emplist = emplist;
      }
      }
      [/sourcecode]

      3. Tạo 2 phương thức để chuyển đổi
      [sourcecode language="java"]
      // chuyen ds doi tuong thanh xml
      public static void marshal(List<Emp> emplist, File selectedFile)
      throws IOException, JAXBException {
      JAXBContext context;
      BufferedWriter writer = null;
      writer = new BufferedWriter(new FileWriter(selectedFile));
      context = JAXBContext.newInstance(EmpList.class);
      Marshaller m = context.createMarshaller();
      m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
      m.marshal(new EmpList(emplist), writer);
      writer.close();
      }

      // chuyen XML thanh danh sach doi tuong
      public static List<Emp> unmarshal(File importFile) throws JAXBException {
      EmpList empList = new EmpList();
      JAXBContext context = JAXBContext.newInstance(EmpList.class);
      Unmarshaller um = context.createUnmarshaller();
      empList = (EmpList) um.unmarshal(importFile);
      return empList.getEmpList();
      }
      [/sourcecode]

      4. Test
      [sourcecode language="java"]
      public static void main(String[] args) {
      Emp emp = new Emp();
      emp.setCode("A001");
      emp.setName("Nguyen Van Mit");
      emp.setAddress("Can Tho");
      emp.setTel("+8499999999");

      Emp emp1 = new Emp();
      emp1.setCode("A002");
      emp1.setName("Tran Van Cam");
      emp1.setAddress("Can Tho");
      emp1.setTel("+848888888");

      List<Emp> emplist = new ArrayList<Emp>();
      emplist.add(emp);
      emplist.add(emp1);
      //Marshalling: ghi ds doi tuong ra file xml
      try {
      JAXBXMLHandler.marshal(emplist, new File("src/jaxb_object_list/EmpList.xml"));
      } catch (IOException e) {
      e.printStackTrace();
      } catch (JAXBException e) {
      e.printStackTrace();
      }

      try {
      // khoi tao ds tu XML
      emplist = JAXBXMLHandler.unmarshal(new File("src/jaxb_object_list/EmpList.xml"));
      } catch (JAXBException e) {
      e.printStackTrace();
      }
      System.out.println(emplist);
      }
      [/sourcecode]

      Tới đây chạy ứng dụng chúng ta sẽ có file xml sinh ra và mẫu in ra của sổ output
      [sourcecode language="text"]
      [Emp [code:A001, name:Nguyen Van Mit, address:Can Tho, tel:+8499999999], Emp [code:A002, name:Tran Van Cam, address:Can Tho, tel:+848888888]]
      [/sourcecode]

      Mã nguồn tham khảo tại đây

      Monday, September 21, 2015

      Bài tập IXJ - Import XML to WebApplication

      Trong bài này chúng ta sẽ upload file XML có mẫu qui định trước lên web server và rút trích dữ liệu đề đưa vào SQL server.
      Nội dung mẫu XML
      [sourcecode language="xml"]
      <emplist>
      <emp status="off">
      <id>1</id>
      <name>Been</name>
      </emp>
      <emp status="on">
      <id>2</id>
      <name>Andrew</name>
      </emp>
      </emplist>
      [/sourcecode]

      Tạo một web site, sử dụng JSF 2.2
      Tạo managebean như sau:
      [sourcecode language="java"]
      package codes;
      import java.io.File;
      import java.io.IOException;
      import java.sql.Connection;
      import java.sql.DriverManager;
      import java.sql.PreparedStatement;
      import java.sql.SQLException;
      import java.util.logging.Level;
      import java.util.logging.Logger;
      import javax.faces.bean.ManagedBean;
      import javax.faces.bean.RequestScoped;
      import javax.faces.context.FacesContext;
      import javax.servlet.http.Part;
      import javax.xml.parsers.DocumentBuilder;
      import javax.xml.parsers.DocumentBuilderFactory;
      import javax.xml.parsers.ParserConfigurationException;
      import org.w3c.dom.Document;
      import org.w3c.dom.NodeList;
      import org.xml.sax.SAXException;
      /**
      *
      * @author ntdan
      */
      @ManagedBean
      @RequestScoped
      public class FileUploadBean {

      private Part file;
      private String fileName = "";

      /**
      * Creates a new instance of FileUploadBean
      */
      public FileUploadBean() {
      }

      public Part getFile() {
      return file;
      }

      public void setFile(Part file) {
      this.file = file;
      }

      public String upload() {
      try {
      fileName = file.getSubmittedFileName() + " "
      + file.getSize() + " bytes";
      String filePath = FacesContext.getCurrentInstance().getExternalContext()
      .getRealPath("/upload") + "/" + file.getSubmittedFileName();
      // luu file
      file.write(filePath);
      // luu du lieu
      importXML(filePath);
      } catch (Exception ex) {
      System.out.println(ex.toString());
      }
      return "index";
      }

      public String getFileName() {
      return fileName;
      }

      public void setFileName(String fileName) {
      this.fileName = fileName;
      }

      private void importXML(String filename) {
      try {
      Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
      Connection conn = DriverManager.getConnection("jdbc:sqlserver://172.16.160.54\\sql2008;database=northwind;user=sa;password=sa;");
      PreparedStatement comm = conn.prepareStatement("insert into Employees(FirstName,LastName) values(?,?)");

      DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance();
      DocumentBuilder db = fac.newDocumentBuilder();
      Document doc = db.parse(new File(filename));

      NodeList list = doc.getElementsByTagName("emp");
      int pos = 0;
      while (pos < list.getLength()) {
      NodeList emp = list.item(pos).getChildNodes();
      comm.setString(1, emp.item(3).getTextContent());
      comm.setString(2, "L_" + emp.item(3).getTextContent());
      // them du lieu
      comm.executeUpdate();
      pos++;
      }

      fileName += "\n" + pos +" rows added!";
      } catch (ClassNotFoundException ex) {
      Logger.getLogger(FileUploadBean.class.getName()).log(Level.SEVERE, null, ex);
      } catch (SQLException ex) {
      Logger.getLogger(FileUploadBean.class.getName()).log(Level.SEVERE, null, ex);
      } catch (ParserConfigurationException ex) {
      Logger.getLogger(FileUploadBean.class.getName()).log(Level.SEVERE, null, ex);
      } catch (SAXException ex) {
      Logger.getLogger(FileUploadBean.class.getName()).log(Level.SEVERE, null, ex);
      } catch (IOException ex) {
      Logger.getLogger(FileUploadBean.class.getName()).log(Level.SEVERE, null, ex);
      }
      }
      }
      [/sourcecode]

      Hiệu chỉnh lại trang index.xhtml
      [sourcecode language="html"]
      <?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://xmlns.jcp.org/jsf/html"
      xmlns:f="http://xmlns.jcp.org/jsf/core">
      <h:head>
      <title>Upload</title>
      </h:head>
      <h:body>
      <f:view>
      <h:form enctype="multipart/form-data">
      <h:inputFile value="#{fileUploadBean.file}"/>
      <h:commandButton value="Upload"
      action="#{fileUploadBean.upload()}"/><br/>
      File: <h:outputText value="#{fileUploadBean.fileName}"/>
      </h:form>
      </f:view>
      </h:body>
      </html>
      [/sourcecode]

      Chạy trang index.xhtml --> chọn file emp.xml chứa nội dung và nhấn Upload chúng ta có giao diện như sau:
      Snap 2015-09-21 at 15.16.34

      Mã nguồn tham khảo -->> ở đây

      OK vậy là chúng ta đã import nội dung XML vào csdl.

      Bài tập IXJ - FO sử dụng Apache FOP chuyển XML sang PDF

      XSL-FO (XSL Formatting Objects) chuyển đổi dữ liệu XML sang các định dạng khác.
      XSL - FO
      Trong bài thực hành này chúng ta sẽ sử dụng thư viện FOP của Apache tích hợp vào chương trình Java để chuyển tài liệu XML chứa CustomerOrders mua sản phẩm sang biểu mẩu PDF.

      CustomerOrders

      Snap 2015-09-21 at 13.34.42

      Các thư viện hỗ trợ -->> đây

      Mã nguồn tham khảo như sau:
      [sourcecode language="java"]
      package fop_ex;
      import java.io.File;
      import java.io.OutputStream;
      import javax.xml.transform.Result;
      import javax.xml.transform.Source;
      import javax.xml.transform.Transformer;
      import javax.xml.transform.TransformerFactory;
      import javax.xml.transform.sax.SAXResult;
      import javax.xml.transform.stream.StreamSource;
      import org.apache.fop.apps.FOUserAgent;
      import org.apache.fop.apps.Fop;
      import org.apache.fop.apps.FopFactory;
      import org.apache.fop.apps.MimeConstants;
      public class FOP_EX {
      public static void main(String[] args) {
      try {
      // Setup directories
      File baseDir = new File(".");
      File outDir = new File(baseDir, "src/out");
      outDir.mkdirs();
      // Setup input and output files
      File xmlfile = new File(baseDir, "src/xml/CustomerOrders.xml");
      File xsltfile = new File(baseDir, "src/xslt/Customer_fo.xsl");
      File pdffile = new File(outDir, "CustomerOrders.pdf");
      // configure fopFactory as desired
      final FopFactory fopFactory = FopFactory.newInstance(new File(".").toURI());
      // configure foUserAgent as desired
      FOUserAgent foUserAgent = fopFactory.newFOUserAgent();
      // Setup output
      OutputStream out = new java.io.FileOutputStream(pdffile);
      out = new java.io.BufferedOutputStream(out);
      try {
      // Construct fop with desired output format
      Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, out);
      // Setup XSLT
      TransformerFactory factory = TransformerFactory.newInstance();
      Transformer transformer = factory.newTransformer(new StreamSource(xsltfile));
      // Set the value of a <param> in the stylesheet
      transformer.setParameter("author", "Nguyen Van Mit");
      // Setup input for XSLT transformation
      Source src = new StreamSource(xmlfile);
      // Resulting SAX events (the generated FO) must be piped through to FOP
      Result res = new SAXResult(fop.getDefaultHandler());
      // Start XSLT transformation and FOP processing
      transformer.transform(src, res);
      } finally {
      out.close();
      }
      } catch (Exception e) {
      e.printStackTrace(System.err);
      System.exit(-1);
      }
      }
      }
      [/sourcecode]
      File XSL-FO như sau:
      [sourcecode language="xml"]
      <?xml version="1.0" encoding="UTF-8"?>
      <xsl:stylesheet version="1.1" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:fo="http://www.w3.org/1999/XSL/Format" exclude-result-prefixes="fo">
      <xsl:output method="xml" version="1.0" omit-xml-declaration="no" indent="yes"/>
      <xsl:param name="author" select="'Tran Van Cam'"/>
      <xsl:template match="customers">
      <fo:root xmlns:fo="http://www.w3.org/1999/XSL/Format">
      <fo:layout-master-set>
      <fo:simple-page-master master-name="simpleA4" page-height="29.7cm" page-width="21cm" margin-top="2cm" margin-bottom="2cm" margin-left="2cm" margin-right="2cm">
      <fo:region-body/>
      </fo:simple-page-master>
      </fo:layout-master-set>
      <fo:page-sequence master-reference="simpleA4">
      <fo:flow flow-name="xsl-region-body">
      <fo:block font-size="16pt" text-align="center" font-weight="bold" space-after="5mm">CUSTOMER ORDER LIST<xsl:value-of select="customers"/>
      </fo:block>
      <fo:block font-size="12pt" text-align="center" space-after="5mm">----oOo----</fo:block>
      <fo:block font-size="10pt">
      <fo:table table-layout="fixed" width="100%"
      border-collapse="separate" border="solid"
      border-separation="3pt">
      <xsl:attribute-set name="table.cell.padding">
      <xsl:attribute name="padding-left">2pt</xsl:attribute>
      <xsl:attribute name="padding-right">2pt</xsl:attribute>
      <xsl:attribute name="padding-top">2pt</xsl:attribute>
      <xsl:attribute name="padding-bottom">2pt</xsl:attribute>
      </xsl:attribute-set>
      <fo:table-column column-width="2cm"/>
      <fo:table-column column-width="5cm"/>
      <fo:table-column column-width="5cm"/>
      <fo:table-column column-width="2cm"/>
      <fo:table-column column-width="3cm"/>
      <fo:table-header>
      <fo:table-row background-color="#0000FF" color="#FFFFFF">
      <fo:table-cell text-align="center">
      <fo:block>Order.</fo:block>
      </fo:table-cell>
      <fo:table-cell>
      <fo:block>Customer name</fo:block>
      </fo:table-cell>
      <fo:table-cell>
      <fo:block>Product name</fo:block>
      </fo:table-cell>
      <fo:table-cell text-align="right">
      <fo:block>Quantity</fo:block>
      </fo:table-cell>
      <fo:table-cell text-align="right">
      <fo:block>Price</fo:block>
      </fo:table-cell>
      </fo:table-row>
      </fo:table-header>
      <fo:table-body>
      <xsl:apply-templates select="customer"/>
      </fo:table-body>
      </fo:table>
      </fo:block>
      <fo:block font-size="12pt" text-align="right" space-before="1cm">Signature</fo:block>
      <fo:block font-size="12pt" text-align="right" space-before="2cm" space-after="5mm"> <xsl:value-of select="$author"/> </fo:block>
      </fo:flow>
      </fo:page-sequence>
      </fo:root>
      </xsl:template>
      <xsl:template match="customer">
      <xsl:variable name="bgclr">
      <xsl:choose>
      <xsl:when test="position() mod 2">#A7BFDE</xsl:when>
      <xsl:otherwise>#EDF2F8</xsl:otherwise>
      </xsl:choose>
      </xsl:variable>
      <fo:table-row background-color="{$bgclr}">
      <xsl:if test="item='Laptop'">
      <xsl:attribute name="font-weight">bold</xsl:attribute>
      </xsl:if>
      <fo:table-cell text-align="center">
      <fo:block>
      <xsl:value-of select="position()" format="1."/>
      </fo:block>
      </fo:table-cell>
      <fo:table-cell>
      <fo:block>
      <xsl:value-of select="name"/>
      </fo:block>
      </fo:table-cell>
      <fo:table-cell>
      <fo:block>
      <xsl:value-of select="item"/>
      </fo:block>
      </fo:table-cell>
      <fo:table-cell text-align="right">
      <fo:block>
      <xsl:value-of select="quantity"/>
      </fo:block>
      </fo:table-cell>
      <fo:table-cell text-align="right">
      <xsl:attribute name="font-weight">bold</xsl:attribute>
      <fo:block>
      <xsl:value-of select="price"/>
      </fo:block>
      </fo:table-cell>
      </fo:table-row>
      </xsl:template>
      </xsl:stylesheet>
      [/sourcecode]
      Căn bản là vậy !!!

      Translate