Wednesday, September 16, 2015

Bài tập IXJ (JAXB)

JAXB, stands for Java Architecture for XML Binding, using JAXB annotation to convert Java object to / from XML file.
In this tutorial, we show you how to use JAXB to do following stuffs

  1. Marshalling – Convert a Java object into a XML file.

  2. Unmarshalling – Convert XML content into a Java Object.


Working with JAXB is easy, just annotate object with JAXB annotation, later use jaxbMarshaller.marshal() or jaxbMarshaller.unmarshal() to do the object / XML conversion.

Create Java class
[sourcecode language="java"]
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

// Customer will become root node in XML file
@XmlRootElement
public class Customer {
String name;
int age;
int id;
public String getName() {
return name;
}
//Name as tag
@XmlElement
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
// Age as tag
@XmlElement
public void setAge(int age) {
this.age = age;
}
public int getId() {
return id;
}
// id as attribute of customer tag
@XmlAttribute
public void setId(int id) {
this.id = id;
}
}
[/sourcecode]

Convert Object to XML: JAXB marshalling example, convert customer object into a XML file. The jaxbMarshaller.marshal() contains a lot of overloaded methods, find one that suit your output.
[sourcecode language="java"]
import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

public class JAXBExample {
public static void main(String[] args) {
// create customer object
Customer customer = new Customer();
customer.setId(100);
customer.setName("nvmit");
customer.setAge(29);
try {
File file = new File("C:\\file.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
// output pretty printed
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
// convert to XML and write to file
jaxbMarshaller.marshal(customer, file);
jaxbMarshaller.marshal(customer, System.out);
} catch (JAXBException e) {
e.printStackTrace();
}
}
}
[/sourcecode]
Run this code, we have XML as
[sourcecode language="xml"]
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<customer id="100">
<age>29</age>
<name>nvmit</name>
</customer>
[/sourcecode]

Convert XML to Object: JAXB unmarshalling example, convert a XML file content into a customer object. The jaxbMarshaller.unmarshal() contains a lot of overloaded methods
[sourcecode language="java"]
import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

public class JAXBExample {
public static void main(String[] args) {
try {
File file = new File("C:\\file.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Customer customer = (Customer) jaxbUnmarshaller.unmarshal(file);
System.out.println(customer);
} catch (JAXBException e) {
e.printStackTrace();
}
}
}
[/sourcecode]

Run this code
Customer [name=nvmit, age=29, id=100]

OK, very simple.

Friday, September 11, 2015

SAX căn bản - phân tích XML (dữ liệu thời tiết trực tuyến)

Ví dụ sử dụng SAX phân tích nội dung XML trực tuyến (thông tin dự báo thời tiết)
Nội dung XML
Snap 2015-09-11 at 16.27.57
Nội dung hiện thị sau phân tích
Snap 2015-09-11 at 16.28.14
Mã nguồn ví dụ
[sourcecode language="java"]
package codes;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
/**
* @author ntdan
*/
public class SAXParser_RSS extends DefaultHandler {
String urlPath = "http://api.openweathermap.org/data/2.5/forecast?q=can+tho,vn&mode=xml";
String strresult = "";
int count = 1;
boolean namefound = false;
boolean itemfound = false;

public String parse() {
try {
SAXParserFactory fac = SAXParserFactory.newInstance();
SAXParser sax = fac.newSAXParser();
// ket noi truc tiep
URL url = new URL(urlPath);
URLConnection conn = url.openConnection();
InputSource in = new InputSource(conn.getInputStream());
// phan tich tu luon truc tuyen
sax.parse(in, this);
return strresult;
} catch (ParserConfigurationException ex) {
Logger.getLogger(SAXParser_RSS.class.getName()).log(Level.SEVERE, null, ex);
} catch (SAXException ex) {
Logger.getLogger(SAXParser_RSS.class.getName()).log(Level.SEVERE, null, ex);
} catch (MalformedURLException ex) {
Logger.getLogger(SAXParser_RSS.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(SAXParser_RSS.class.getName()).log(Level.SEVERE, null, ex);
}
return strresult;
}

@Override
public void characters(char[] ch, int start, int length) throws SAXException {
super.characters(ch, start, length); //To change body of generated methods, choose Tools | Templates.

if (namefound) {
strresult += "<b>Location</b>: " + new String(ch, start, length) + "!<br/>";
namefound = false;
}
}

@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
super.endElement(uri, localName, qName); //To change body of generated methods, choose Tools | Templates.

if (qName.equalsIgnoreCase("item")) {
strresult += "<br/>";
itemfound = false;
}
}

@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
super.startElement(uri, localName, qName, attributes); //To change body of generated methods, choose Tools | Templates.
if (qName.equalsIgnoreCase("name")) {
namefound = true;
}

if (qName.equalsIgnoreCase("item")) {
itemfound = true;
}

if (qName.equalsIgnoreCase("time")) {
strresult += count++ + ". <i>Time<i> <b>From</b>: " + attributes.getValue("from")
+ " <b>To</b>: " + attributes.getValue("to");
}

if (qName.equalsIgnoreCase("humidity")) {
strresult += " <i>Humidity</i>: " + attributes.getValue("value")
+ attributes.getValue("unit") + "<br/>";
}

if (qName.equalsIgnoreCase("temperature")) {
strresult += " <b>Temperature</b>: <b>from</b> "
+ attributes.getValue("min") + " <b>to</b> "
+ attributes.getValue("max") + "-"
+ attributes.getValue("unit");
}
}

@Override
public void endDocument() throws SAXException {
super.endDocument(); //To change body of generated methods, choose Tools | Templates.
strresult += "<br/>End parsing ...";
}

@Override
public void startDocument() throws SAXException {
super.startDocument(); //To change body of generated methods, choose Tools | Templates.
strresult += "Start parsing ... <br/>";
}
}
[/sourcecode]

goodluck!!!

Parsing XML using DOM (Basic)

Objectives

  1. Overview XML parse using DOM

  2. Create DOM with content loaded from SQL Server

  3. Save DOM to XML file

  4. Find information in XML file

  5. Update content in XML file




    1. Load Data form XML
      Create java class JavaApplication1 and declare 02 variable
      static ResultSet rs;
      static Document doc;

      Load Data from Employees table
      [sourcecode language="java"]
      Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
      Connection conn = DriverManager.getConnection("jdbc:sqlserver://"
      + "172.16.160.81\\sql2008;database=northwind;user=sa;password=sa;");
      PreparedStatement comm = conn.prepareStatement(""
      + "Select EmployeeID, FirstName,LastName From Employees");
      rs = comm.executeQuery();
      [/sourcecode]
      Create createDom method to transform RS to DOM
      [sourcecode language="java"]
      void createDom() {
      try {
      DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance();
      DocumentBuilder db = fac.newDocumentBuilder();
      doc = db.newDocument();

      Element root = doc.createElement("emplist");
      // tao nut goc
      doc.appendChild(root);

      Comment comment = doc.createComment("danh sach nhan vien");
      // tao nut goc
      root.appendChild(comment);

      // doc du lieu va tao lai voi xml
      while (rs.next()) {
      // tao the emp
      Element emp = doc.createElement("emp");
      emp.setAttribute("status", "on");
      // the id
      Element id = doc.createElement("id");
      id.setTextContent(rs.getString("EmployeeID"));
      emp.appendChild(id);

      // the name
      Element name = doc.createElement("name");
      name.setTextContent(rs.getString("FirstName") + " " + rs.getString("LastName"));
      emp.appendChild(name);

      // gan vao root
      root.appendChild(emp);
      }
      Comment comment1 = doc.createComment("Nhan vien cuoi cung");
      // gan ghi chu vao phan tu cuoi cung
      root.insertBefore(comment1, root.getLastChild());
      } catch (Exception ex) {
      Logger.getLogger(JavaApplication1.class.getName()).log(Level.SEVERE, null, ex);
      }
      }
      [/sourcecode]
      Write DOM to XML file
      [sourcecode language="java"]
      void writeToXML(String filename) {
      try {

      if(new File(filename).exists())
      {
      if(JOptionPane.showConfirmDialog(
      null, filename + " đ? t?n t?i ! \nB?n có mu?n ghi đè không?",
      "Xác nh?n!", JOptionPane.YES_NO_OPTION) == JOptionPane.NO_OPTION)
      return;
      }

      // Create a DOM document for writing
      Source source = new DOMSource(doc);
      // Prepare the output file
      Result result = new StreamResult(filename);
      // Create an instance of Transformer
      Transformer xformer = TransformerFactory.newInstance().newTransformer();
      xformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
      xformer.setOutputProperty(OutputKeys.INDENT, "yes");
      xformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
      // Write the DOM document to the file
      xformer.transform(source, result);
      } catch (TransformerException ex) {
      System.out.println(ex.toString());
      }
      }
      [/sourcecode]
      Update status attribute of emp tag with content of id tag equal id
      [sourcecode language="java"]
      void deactive(int id) {
      // lay danh sach cac the con
      NodeList list = doc.getElementsByTagName("emp");
      // duyet qua ca the con
      for (int i = 0; i < list.getLength(); i++) {
      // tim con dau tien (the id) va kiem tra gia tri
      // neu bang voi id thi thuc hien
      if (Integer.parseInt(list.item(i).getFirstChild().getTextContent()) == id) {
      // cap nhat gia tri thuoc tinh status cua the emp
      list.item(i).getAttributes().getNamedItem("status").setNodeValue("off");
      break;
      }
      }
      }
      [/sourcecode]
      Find an employee in XML file with id tag content equal id
      [sourcecode language="java"]
      boolean exist(int id) {
      try {
      DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance();
      DocumentBuilder db = fac.newDocumentBuilder();
      doc = db.parse(new File("src/emp.xml"));
      // lay danh sach cac the con
      NodeList list = doc.getElementsByTagName("id");
      // duyet qua ca the con
      for (int i = 0; i < list.getLength(); i++) {
      // tim con dau tien (the id) va kiem tra gia tri
      // neu bang voi id thi thuc hien
      if (Integer.parseInt(list.item(i).getTextContent()) == id) {
      return true;
      }
      }
      } catch (ParserConfigurationException ex) {
      Logger.getLogger(JavaApplication1.class.getName()).log(Level.SEVERE, null, ex);
      } catch (SAXException ex) {
      Logger.getLogger(JavaApplication1.class.getName()).log(Level.SEVERE, null, ex);
      } catch (IOException ex) {
      Logger.getLogger(JavaApplication1.class.getName()).log(Level.SEVERE, null, ex);
      }

      return false;
      }
      [/sourcecode]
      Add new emp tag to existing XML file if emp id tag do not exist in XML file
      [sourcecode language="java"]
      void add(int newId, String newName) {
      try {
      DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance();
      DocumentBuilder db = fac.newDocumentBuilder();
      doc = db.parse(new File("src/emp.xml"));

      if (exist(newId)) {
      JOptionPane.showMessageDialog(null, newId + " đ? t?n t?i !");
      return;
      }

      // lay the emplist
      Node root = doc.getDocumentElement();

      // tao the emp
      Element emp = doc.createElement("emp");
      emp.setAttribute("status", "on");
      // the id
      Element id = doc.createElement("id");
      id.setTextContent(newId + "");
      emp.appendChild(id);

      // the name
      Element name = doc.createElement("name");
      name.setTextContent(newName);
      emp.appendChild(name);

      // gan vao root
      root.appendChild(emp);

      } catch (ParserConfigurationException ex) {
      Logger.getLogger(JavaApplication1.class.getName()).log(Level.SEVERE, null, ex);
      } catch (SAXException ex) {
      Logger.getLogger(JavaApplication1.class.getName()).log(Level.SEVERE, null, ex);
      } catch (IOException ex) {
      Logger.getLogger(JavaApplication1.class.getName()).log(Level.SEVERE, null, ex);
      }
      }
      [/sourcecode]
      Test app
      [sourcecode language="java"]
      public class JavaApplication1 {

      static ResultSet rs;
      static Document doc;

      /**
      * @param args the command line arguments
      */
      public static void main(String[] args) {
      try {
      Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
      Connection conn = DriverManager.getConnection("jdbc:sqlserver://"
      + "172.16.160.81\\sql2008;database=northwind;user=sa;password=sa;");
      PreparedStatement comm = conn.prepareStatement(""
      + "Select EmployeeID, FirstName,LastName From Employees");

      rs = comm.executeQuery();

      JavaApplication1 xmlDOM = new JavaApplication1();
      // tao doi tuong t? SQL Server
      xmlDOM.createDom();
      // ghi ra file
      xmlDOM.writeToXML("src/emp.xml");
      // cap nhat
      xmlDOM.deactive(5);
      // luu thay doi
      xmlDOM.writeToXML("src/emp.xml");
      // them node
      xmlDOM.add(100, "Nguyen Van Mit");
      // luu thay doi
      xmlDOM.writeToXML("src/emp.xml");

      } catch (Exception ex) {
      System.out.println(ex.toString());
      }
      }

      }
      [/sourcecode]

      }
      }

      Shifl + F6 to run
  • Android Notification (căn bản về thông báo trong Android)

    Notification là dạng thông báo xuất hiện ở phần trên cùng của màn hình, dạng thông báo này hiện giời được hỗ trợ trên cả 3 nền tảng phổ biến hiện này: Android, iOS và WindowPhone.



    Android cung cấp thư viện NotificationCompat.Builder, Notification để tạo các thông báo này.

    1. NotificationCompat.Builder.build(): để tạo một thông báo

    2. Phương thức notify() của Notification: để cập nhật thông báo

    3. setSmalIcon: chỉ định icon của thông báo

    4. setContentTitle: Tiêu đề thông báo

    5. setContentText: Nội dung thông báo



    Ví dụ tạo một thông báo:
    [sourcecode language="java"]
    Notification.Builder mBuilder = new Notification.Builder(this);
    mBuilder.setContentTitle("Tin nhắn mới");
    mBuilder.setContentText("Có điểm thực hành môn Android.");
    mBuilder.setTicker("Thông báo!"); mBuilder.setSmallIcon(R.drawable.ic_launcher);
    [/sourcecode]

    Cập nhật thông báo
    [sourcecode language="java"]
    mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    /* cập nhật thông báo */
    mNotificationManager.notify(notificationID, mBuilder.build());
    [/sourcecode]

    Thông thường các ứng dụng cấu hình khi người dùng chạm lên thông báo thì hệ thống sẽ mở lại ứng dụng đã phát sinh thông báo. Để Android có thể mở lại một ứng dụng đã thông báo (có thể là bất kỳ ứng dụng nào) hợp lệ thì chúng ta cần phải thông qua đối tượng hỗ trợ là PendingIntent

    Ví dụ sau đây thực hiện theo mô tả bên trên.

    [sourcecode language="java"]
    /* Tạo đối tượng chỉ đến activity sẽ mở khi chọn thông báo */
    Intent resultIntent = new Intent(this, NotificationView.class);
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
    stackBuilder.addParentStack(NotificationView.class);
    // kèm dữ liệu theo activity để xử lý
    resultIntent.putExtra("events",new String[] { "Có điểm thực hành môn Android" });
    resultIntent.putExtra("id",notificationID);
    /* Đăng ký activity được gọi khi chọn thông báo */
    stackBuilder.addNextIntent(resultIntent);
    PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,
    PendingIntent.FLAG_UPDATE_CURRENT);
    mBuilder.setContentIntent(resultPendingIntent);
    [/sourcecode]

    Sau khi mở ứng dụng (NotificationView) đã phát sinh thông báo qua hỗ trợ của PendingIntent chúng ta có thể xóa thông báo báo với phương thức cancel từ NotificartioManager

    Ví dụ như sau:
    [sourcecode language="java"]
    NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    mNotificationManager.cancel(i.getIntExtra("id", 0));
    [/sourcecode]

    Notification có 2 dạng cơ bản là dạng đơn và dạng danh sách.
    Ví dụ:
    Snap 2015-09-10 at 16.57.29
    Mã nguồn ở
    đây

    Thursday, September 10, 2015

    Direct access to SQL Server From Android

    Sử dụng thư viện JTDS --> http://sourceforge.net/projects/jtds/  để truy cập SQL Server từ Android

    [embed]https://youtu.be/8cp8ykUNmL4[/embed]

    Download thư viện từ đây

    Kết nối với SQL Server như sau:
    [sourcecode language="java"]
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);
    Class.forName("net.sourceforge.jtds.jdbc.Driver").newInstance();
    conn = DriverManager
    .getConnection(""
    + "jdbc:jtds:sqlserver://172.16.160.81/northwind;instance=SQL2008;"
    + "user=sa;password=sa;");
    [/sourcecode]

    net.sourceforge.jtds.jdbc.Driver là dạng Drive truy cập SQL Server.

    Thêm dữ liệu

    [sourcecode language="java"]
    comm = conn.prepareStatement("insert into Employees("
    + "firstname, lastname) values(?,?)");
    comm.setString(1, etFirst.getText().toString());
    comm.setString(2, etLast.getText().toString());
    comm.executeUpdate();
    [/sourcecode]

    Đọc dữ liệu

    [sourcecode language="java"]
    comm = conn.createStatement();
    ResultSet rs = comm.executeQuery("Select EmployeeID, Firstname From Employees");
    String msg = "";
    while (rs.next()) {
    msg += "\nID: " + rs.getInt("EmployeeID") + " Name: "
    + rs.getString("Firstname");
    [/sourcecode]

    Giao diện

    [sourcecode language="html"]
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="${relativePackage}.${activityClass}" >

    <EditText
    android:id="@+id/etFirstName"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="4dp"
    android:background="#eeeeee"
    android:hint="Firstname"
    android:textColor="#000000"
    android:textSize="24dp" >

    <requestFocus />
    </EditText>

    <EditText
    android:id="@+id/etLastName"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#eeeeee"
    android:hint="Lastname"
    android:padding="4dp"
    android:textColor="#000000"
    android:textSize="24dp" />

    <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="4dp" >

    <Button
    android:id="@+id/btnConnect"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:text="Connect" />

    <Button
    android:id="@+id/btnAdd"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:text="Add new" />
    </LinearLayout>

    <TextView
    android:id="@+id/tvDs"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ffffff"
    android:padding="8dp"
    android:text=""
    android:textAppearance="?android:attr/textAppearanceMedium" />
    </LinearLayout>
    [/sourcecode]

    Mã nguồn tham khảo https://drive.google.com/file/d/0B2F9IAasWwaNYVZSc2tiZDNlNTA/view?usp=sharing

    Wednesday, September 9, 2015

    kiểm tra tính tương thích của ứng Android trên các thiết bị chạy chip intel

    http://testdroid.com/news/free-android-app-game-and-web-testing-on-intel-devices

    một bài hướng dẫn kiểm tra tương thích rất chi tiết

    Tuesday, September 8, 2015

    Translate