|
|
| 高可靠性移动应用程序-移动数据库和J2ME工具(二) |
作者:
文章来源:
访问次数:43次
加入时间:2007年03月21日
|
|
<FONT size=2>翻译作者:jungleguo 2003-11-15<BR>原文: <IMG src="http://www.matrix.org.cn/images/small/url.gif" align=absMiddle></FONT><A href="http://www.javaworld.com/javaworld/jw-06-2003/jw-0606-wireless-p2.html" target=_blank><FONT size=2>http://www.javaworld.com/javaworld/jw-06-2003/jw-0606-wireless-p2.html</FONT></A><BR><FONT size=2><STRONG>一个应用程序例子</STRONG><BR>现在通过一个简单的例子,我们检测一下移动数据库应用程序的典型用法和关键组件。<BR></FONT><FONT size=2><STRONG>移动联系管理器<BR></STRONG>这是一个由PointBase提供的移动联系管理器的例子。联系管理器 contact manager包括在PointBase 4.x中。为了读者方便,我已经把源代码打包成zip文件放在Resource中。如果你想编译和运行例子,你必须先从PointBase处下载适当的jar文件。<BR>这个应用程序本身比较简单。它主要沿用了高级地址本应用程序的通用特性。例如,它允许用户存储联系人名字,地址和电话号码;提供自觉浏览和搜索接口;和后台数据库服务器同步。图1和图2分别显示了该应用程序在标准模式和同步模式下的操作。这些屏幕快照来自一个由Insignia’s Jeode PersonalJava VM驱动的Pocket PC 和一个由J2SE驱动的Mac OS X 膝上型电脑。相同字节代码的应用程序没有经过修改运行在许多平台上,证明了Java的威力。<BR></FONT><A href="http://www.javaworld.com/javaworld/jw-06-2003/images/jw-0606-wireless1.gif" target=_blank><FONT size=2><IMG style="WIDTH: 267px; HEIGHT: 263px" height=200 alt="" hspace=0 src="http://www.javaworld.com/javaworld/jw-06-2003/images/jw-0606-wireless1.gif" width=200 border=0></FONT></A><BR><FONT size=2>图1 在袖珍PC Jeode PersonalJava上的标准联系管理器<BR> </FONT><A href="http://www.javaworld.com/javaworld/jw-06-2003/images/jw-0606-wireless2-thumb.gif" target=_blank><FONT size=2><IMG style="WIDTH: 319px; HEIGHT: 271px" height=200 alt="" hspace=0 src="http://www.javaworld.com/javaworld/jw-06-2003/images/jw-0606-wireless2-thumb.gif" width=200 border=0></FONT></A><BR><FONT size=2>图2 在Mac OS X上的两个同步的联系管理器spoke<BR>客户端应用程序UI(用户界面)是用AWT写的。这是被PersonalJava或J2ME/FP/PP设备所支持的唯一标准UI库。除了这些UI驱动,我们还有另一个代码层,它提供访问一般的设备上JDBC数据库。这个数据库访问层也提供了与后台服务器同步移动数据的逻辑,它是通过PointBase专有UniSync同步服务器来实现的。现在我们来看看数据访问层的代码,它包括在一个单独的类:DBManager.<BR></FONT><STRONG><BR><FONT size=2>设备上的数据访问</FONT></STRONG><BR><FONT size=2>类DBManager是一个单独的类,它提供从应用程序单点访问数据。这个单独模式避免了嵌入式数据库的线程复杂性。下面的代码片断显示了DBManager的构造器和初始化的代码。它连接数据库,定义表,将测试数据导入表中,创建为以后时候的SQL状态模版(PreparedStatement)。正如我们所看到的,这里用到的都是标准JDBC。对于企业Java 开发者下面的代码应该很容易明白:<BR>例1 连接移动数据库和初始化访问对象<BR></FONT> <TABLE style="TABLE-LAYOUT: fixed" cellSpacing=0 borderColorDark=#ffffff cellPadding=4 width="98%" align=center bgColor=#e6e6e6 borderColorLight=#009ace border=1> <TBODY> <TR> <TD style="WORD-WRAP: break-word"><FONT size=2>class DBManager {<BR> // DBManager is a singleton class.<BR> private static DBManager instance;<BR> private String driver;<BR> private String url;<BR> private String user;<BR> private String password;<BR> private boolean delay;<BR> private Connection connection;<BR> private Statement statement;<BR> private PreparedStatement insert;<BR> private PreparedStatement find;<BR> private PreparedStatement delete;<BR> private PreparedStatement update;<BR> private PreparedStatement all;<BR><BR> static DBManager getInstance() {<BR> if (instance == null) {<BR> instance = new DBManager();<BR> }<BR> return instance;<BR> }<BR><BR> private DBManager() {<BR> // Get parameters from runtime properties.<BR> // This allows us to switch to different JDBC databases<BR> // without changing the application code.<BR> Properties properties = ContactManager.getProperties();<BR> driver =<BR> properties.getProperty("driver", "com.pointbase.me.jdbc.jdbcDriver");<BR> url =<BR> properties.getProperty("url", "jdbc:pointbase:micro:pbdemo");<BR> user =<BR> properties.getProperty("user", "PBPUBLIC");<BR> password =<BR> properties.getProperty("password", "PBPUBLIC");<BR> delay =<BR> properties.getProperty("delayread","true").equals("true");<BR> connect();<BR> }<BR><BR> private void connect() {<BR> try {<BR> // Load the driver class.<BR> Class.forName(driver);<BR><BR> // If the database doesn't exist, create a new database.<BR> connection = DriverManager.getConnection(url, user, password);<BR><BR> // Create template statement objects.<BR> statement = connection.createStatement();<BR> createStatement();<BR><BR> // If the database is newly created, load the schema.<BR> boolean newdb=initDatabase();<BR> // Load sample data for the new tables.<BR> if(newdb) {<BR> SampleDataCreator.insert(connection);<BR> }<BR><BR> } catch (Exception e) {<BR> e.printStackTrace();<BR> System.exit(1);<BR> }<BR> }<BR><BR> void disconnect() {<BR> try {<BR> connection.commit();<BR> statement.close();<BR> insert.close();<BR> find.close();<BR> delete.close();<BR> update.close();<BR> all.close();<BR> connection.close();<BR> System.exit(0);<BR> } catch (Exception e) {<BR> e.printStackTrace();<BR> System.exit(1);<BR> }<BR> }<BR><BR> // Create the table and load the schema.<BR> private boolean initDatabase() {<BR> try {<BR> String sql = "CREATE TABLE NameCard (ID INT PRIMARY KEY, "+<BR> "Name VARCHAR(254), Company VARCHAR(254), Title VARCHAR(254), "+<BR> "Address1 VARCHAR(254), Address2 VARCHAR(254), "+<BR> "Phone VARCHAR(254), Email VARCHAR(254), "+<BR> "Picture Binary(1000000))";<BR> // If the table already exists, this will throw an exception.<BR> statement.executeUpdate(sql);<BR> // This means the database already exists.<BR> return true;<BR> } catch (SQLException e) {<BR> // Ignore the error - the table already exists, which is good<BR> // so we don't need to add demo data later on.<BR> return false;<BR> }<BR> }<BR><BR> // Create statement templates.<BR> private void createStatement() {<BR> try {<BR> insert = connection.prepareStatement(<BR> "INSERT INTO NameCard (ID, Name, Company, Title, Address1, "+<BR> "Address2, Phone, Email, Picture) "+<BR> "valueS (?, ?, ?, ?, ?, ?, ?, ?, ?)");<BR> find = connection.prepareStatement(<BR> "SELECT * FROM NameCard WHERE (Name LIKE ?) "+<BR> "AND (Company LIKE ?) AND (Title LIKE ?) "+<BR> "AND ((Address1 LIKE ?) OR (Address2 LIKE ?)) "+<BR> "AND (Phone LIKE ?) AND (Email LIKE ?)");<BR> delete = connection.prepareStatement(<BR> "DELETE FROM NameCard WHERE ID = ?");<BR> update = connection.prepareStatement(<BR> "UPDATE NameCard SET ID=?, Name=?, Company=?, Title=?, "+<BR> "Address1=?, Address2=?, Phone=?, Email=?, Picture=? "+<BR> "WHERE ID = ?");<BR> all = connection.prepareStatement(<BR> "SELECT ID, Name, Company, Title, Address1, Address2, "+<BR> "Phone, Email FROM NameCard");<BR> } catch (SQLException e) {<BR> e.printStackTrace();<BR> }<BR> }<BR> <BR> // Other methods.<BR><BR>}</FONT></TD></TR></TBODY></TABLE><FONT size=2>在DBManager中的其他方法通过简单JDBC API调用进行访问数据库。如下的代码片断展示了搜索和操纵名称卡片记录的方法。这些方法使用了我们之前定义的SQL模版。<BR>例2 数据访问方法<BR></FONT> <TABLE style="TABLE-LAYOUT: fixed" cellSpacing=0 borderColorDark=#ffffff cellPadding=4 width="98%" align=center bgColor=#e6e6e6 borderColorLight=#009ace border=1> <TBODY> <TR> <TD style="WORD-WRAP: break-word"><FONT size=2>Vector findNameCardsByKeyword(String name, String company,<BR> String title, String address1, String address2,<BR> String phone, String email) {<BR> Vector NameCards = new Vector();<BR> String[] keywords = {name, company, title, address1, address2,<BR> phone, email};<BR> try {<BR> for (int i = 0; i < keywords.length; i++) {<BR> String criteria = (keywords[i].equals("")) ? "%" :<BR> "%" + keywords[i] + "%";<BR> find.setString(i + 1, criteria);<BR> }<BR> ResultSet resultSet = find.executeQuery();<BR> while (resultSet.next()) {<BR> NameCard nameCard = new NameCard(resultSet.getInt(1),<BR> resultSet.getString(2), resultSet.getString(3),<BR> resultSet.getString(4), resultSet.getString(5),<BR> resultSet.getString(6),<BR> resultSet.getString(7), resultSet.getString(8));<BR> if (!delay)<BR> loadPicture(nameCard);<BR> NameCards.addElement(nameCard);<BR> }<BR> } catch (SQLException e) {<BR> e.printStackTrace();<BR> }<BR> return NameCards;<BR>}<BR><BR>void addNameCard(NameCard nameCard) {<BR> nameCard.setID(getNewID());<BR> try {<BR> insert.setInt(1, nameCard.getID());<BR> insert.setString(2, nameCard.getName());<BR> insert.setString(3, nameCard.getCompany());<BR> insert.setString(4, nameCard.getTitle());<BR> insert.setString(5, nameCard.getAddress1());<BR> insert.setString(6, nameCard.getAddress2());<BR> insert.setString(7, nameCard.getPhone());<BR> insert.setString(8, nameCard.getEmail());<BR> insert.setBytes(9, nameCard.getPicture().getBytes());<BR> insert.executeUpdate();<BR> } catch (SQLException e) {<BR> e.printStackTrace();<BR> }<BR>}<BR><BR>void updateNameCard(NameCard nameCard) {<BR> try {<BR> update.setInt(1, nameCard.getID());<BR> update.setString(2, nameCard.getName());<BR> update.setString(3, nameCard.getCompany());<BR> update.setString(4, nameCard.getTitle());<BR> update.setString(5, nameCard.getAddress1());<BR> update.setString(6, nameCard.getAddress2());<BR> update.setString(7, nameCard.getPhone());<BR> update.setString(8, nameCard.getEmail());<BR> update.setBytes(9, nameCard.getPicture().getBytes());<BR> update.setInt(10, nameCard.getID());<BR> update.executeUpdate();<BR> } catch (SQLException e) {<BR> e.printStackTrace();<BR> }<BR>}<BR><BR>void deleteNameCard(NameCard nameCard) {<BR> try {<BR> delete.setInt(1, nameCard.getID());<BR> delete.executeUpdate();<BR> } catch (SQLException e) {<BR> e.printStackTrace();<BR> }<BR>}<BR><BR>void loadPicture(NameCard nameCard) {<BR> try {<BR> ResultSet resultSet =<BR> statement.executeQuery(<BR> "SELECT Picture FROM NameCard WHERE ID = " +<BR> nameCard.getID());<BR> resultSet.next();<BR> Picture picture = new Picture();<BR> picture.setBytes(resultSet.getBytes(1));<BR> nameCard.setPicture(picture);<BR> } catch (SQLException e) {<BR> e.printStackTrace();<BR> }<BR>}<BR><BR>private int getNewID() {<BR> try {<BR> ResultSet resultSet = statement.executeQuery(<BR> "SELECT MAX(ID)+1 FROM NameCard");<BR> if (resultSet.next()) {<BR> return resultSet.getInt(1);<BR> } else {<BR> return 0;<BR> }<BR> } catch (Exception e) {<BR> e.printStackTrace();<BR> }<BR> return 0;<BR>}</FONT></TD></TR></TBODY></TABLE><FONT size=2><STRONG>与后台数据库同步</STRONG><BR>类DBManager也允许应用程序开发者用PointBase 专有UniSync引擎与后台数据库同步移动数据。不同的厂商使用不同的同步引擎,但他们的概念都是相类似的。同步过程按照如下这些步骤进行:<BR>1. 在后台服务器和移动设备上创建相应的数据库和表<BR>2. 在同步服务器上创建一个hub。这个hub包含发布信息。它指定和标识用于同步(发布)的后台表(或部分表)。<BR>3. 使用hub来创建spoke。spoke是在同步服务器上表示移动设备的对象。每个spoke都有一个ID。它能通过在同一个hub里的订阅对象来订阅发布。通过使用一个spokeID,移动设备匹配spoke并对订阅的后台表进行同步。<BR>4. 启动同步服务器。基本上通过com.pointbase.me.sync.Server 类的main()方法来执行。这个服务器类用于PointBase 发布包。还有其他几个方法在不同环境中运行服务器。您可以参考PointBase文档来得到更多的细节和例子。默认情况下,服务器监听端口8124。<BR>5. 使用一个spokeID和在移动设备上的类 spoke stub 来初始化同步过程。<BR> </FONT><A href="http://www.javaworld.com/javaworld/jw-06-2003/images/jw-0606-wireless3.gif" target=_blank><FONT size=2><IMG style="WIDTH: 341px; HEIGHT: 221px" height=200 alt="" hspace=0 src="http://www.javaworld.com/javaworld/jw-06-2003/images/jw-0606-wireless3.gif" width=200 border=0></FONT></A><BR><FONT size=2>图3 UniSync同步服务器框架图解<BR>例3 中的类ResetServer显示了在UniSync服务器上如何创建hub和spoke:<BR>例3 安装同步服务器<BR></FONT> <TABLE style="TABLE-LAYOUT: fixed" cellSpacing=0 borderColorDark=#ffffff cellPadding=4 width="98%" align=center bgColor=#e6e6e6 borderColorLight=#009ace border=1> <TBODY> <TR> <TD style="WORD-WRAP: break-word"><FONT size=2>manager=SyncManager.getInstance(caturl,catdriver,catuser,catpassword);<BR>String dsname;<BR>dsname=SyncDataSource.DEFAULT;<BR><BR>String hubname="Hub";<BR>Hub hub=manager.createHub(hubname);<BR><BR>Publication pub;<BR>String pubname;<BR>SpokeConfig spoke;<BR>Subscription sub;<BR>String subname="SubNameCard";<BR>String tablename="NAMECARD";<BR>String[] tables=new String[]{tablename};<BR><BR>// Publish the complete name-card table<BR>pubname="PubNameCard";<BR>pub=hub.newPublication(pubname,dsname,tables);<BR>hub.publish(pub);<BR><BR>// Create two spokes and subscribe to this publication<BR>for(int i=1;i<=2;i++) {<BR> String name="Spoke"+i;<BR> spoke=hub.createSpokeConfig(name);<BR> spoke.savePassword("pass"+i);<BR> sub=spoke.newSubscription(subname,SyncDataSource.DEFAULT,pubname);<BR> spoke.subscribe(sub);<BR>}<BR><BR>// Publish the name-card table without the picture column<BR><BR>pubname="PubNameCardNoPicture";<BR>pub=hub.newPublication(pubname,dsname,tables);<BR>SyncTable table=pub.getSyncTable(tablename);<BR>table.dropSyncColumns(new String[]{"PICTURE"});<BR>hub.publish(pub);<BR> <BR>// Create two spokes and subscribe to this publication<BR>for(int i=3;i<=4;i++) {<BR> String name="Spoke"+i;<BR> spoke=hub.createSpokeConfig(name);<BR> spoke.savePassword("pass"+i);<BR> sub=spoke.newSubscription(subname,SyncDataSource.DEFAULT,pubname);<BR> spoke.subscribe(sub);<BR>}<BR>manager.close();</FONT></TD></TR></TBODY></TABLE><FONT size=2>下面的DBManager代码片断显示了如何获得spoke stub 和如何在设备上处理同步。代码中的注释解释了应用程序的同步和独立版本的不同:<BR>例4 通过同步服务器访问数据<BR></FONT> <TABLE style="TABLE-LAYOUT: fixed" cellSpacing=0 borderColorDark=#ffffff cellPadding=4 width="98%" align=center bgColor=#e6e6e6 borderColorLight=#009ace border=1> <TBODY> <TR> <TD style="WORD-WRAP: break-word"><FONT size=2>// Import proprietary classes for sync<BR>import com.pointbase.me.jdbc.*;<BR><BR>class DBManager {<BR><BR> // In addition to JDBC connection variables,<BR> // we also need to define variables for sync<BR> // ... ...<BR> private Spoke spoke;<BR> private String spokename;<BR> private int spoke_id;<BR> private int spoke_range_start,spoke_range_end;<BR> final static int ROWS_PER_SPOKE=1<<16;<BR> private String syncurl;<BR> private String syncpassword;<BR><BR><BR> private DBManager() {<BR> <BR> // Get DB connection parameters<BR> // ... ...<BR> <BR> // Get sync parameters<BR> syncurl =<BR> properties.getProperty("syncurl", "<IMG src="http://www.matrix.org.cn/images/small/url.gif" align=absMiddle></FONT><A href='http://localhost:8124"/' target=_blank><FONT size=2>http://localhost:8124"</FONT></A><FONT size=2>;);<BR> String spokeid =<BR> properties.getProperty("spokeid", "1");<BR> spokename =<BR> properties.getProperty("spoke", "Spoke"+spokeid);<BR> syncpassword =<BR> properties.getProperty("syncpassword", "pass"+spokeid);<BR> url =<BR> properties.getProperty("url",<BR> "jdbc:pointbase:micro:pbdemo"+spokeid);<BR><BR> connect();<BR> }<BR><BR> // The complete connect method using synchronization server<BR> private void connect() {<BR> try {<BR> System.out.println("Connecting to the database...");<BR><BR> Class.forName(driver);<BR><BR> // If the database doesn't exist, create a new database<BR> connection = DriverManager.getConnection(url, user, password);<BR> statement = connection.createStatement();<BR><BR><BR> // Check sync metadata and create tables<BR> loadMeta();<BR><BR> // Create prepared statements<BR> createStatement();<BR><BR> } catch (Exception e) {<BR> e.printStackTrace();<BR> System.exit(1);<BR> }<BR> }<BR><BR> // The complete newID method using the sync server<BR> private int getNewID() {<BR> try {<BR> ResultSet rs = statement.executeQuery(<BR> "SELECT MAX(ID)+1 FROM NameCard WHERE "+<BR> "ID>="+spoke_range_start+" AND ID<"+spoke_range_end);<BR> rs.next();<BR> int id=rs.getInt(1);<BR> if(rs.wasNull()) {<BR> return spoke_range_start;<BR> } else {<BR> return id;<BR> }<BR><BR> } catch (Exception e) {<BR> e.printStackTrace();<BR> }<BR> return 0;<BR> }<BR><BR> // Create table and load metadata from the sync hub<BR> void loadMeta() {<BR> try {<BR> SyncManager manager=SyncManager.getInstance(connection);<BR> spoke=manager.getSpoke(spokename);<BR> if(spoke==null) {<BR> System.out.println(<BR> "Loading MetaData from url "+syncurl+<BR> " for spoke "+spokename+<BR> " using password "+syncpassword);<BR> spoke=manager.createSpoke(spokename);<BR> spoke.savePassword(syncpassword);<BR> spoke.saveHubURL(syncurl);<BR> spoke.loadConfig();<BR> spoke.getSnapshot();<BR> }<BR> spoke_id = spoke.getSpokeId();<BR> System.out.println("SpokeID is "+spoke_id);<BR> spoke_range_start = ROWS_PER_SPOKE * spoke_id;<BR> spoke_range_end = spoke_range_start + ROWS_PER_SPOKE - 1;<BR> } catch (SyncException e) {<BR> e.printStackTrace();<BR> }<BR> }<BR> <BR> // Synchronize spoke databases (mobile databases) with the hub<BR> // and backend databases<BR> void sync() {<BR> try {<BR> spoke.sync();<BR> } catch (SyncException e) {<BR> e.printStackTrace();<BR> }<BR> }<BR> <BR> // Other data access methods are the same as the non-synced version.<BR>}</FONT></TD></TR></TBODY></TABLE>
|
|
|