Tuesday, April 24, 2012

Look for a Qt library for network topology

Qanava could be my solution for network topology based on Qt4. But, it had been not maintained anymore...

main page:
http://gna.org/projects/qanava

git repository
http://repo.or.cz/w/qanava.git

Document 
Qanava Manual v0.1.0

Monday, April 23, 2012

[How to] Use tcpdump to look at LLDP packet

Here is an example about how to use tcpdump tool to look at LLDP information

> sudo tcpdump -c 1 -lv -v -i eth0 -a -e -s 1514 ether proto 0x88cc

The result:
tcpdump: listening on eth4, link-type EN10MB (Ethernet), capture size 1514 bytes
13:30:46.426056 08:00:27:09:61:e9 (oui Unknown) > 01:80:c2:00:00:0e (oui Unknown), ethertype LLDP (0x88cc), length 156: LLDP, length 142
    Chassis ID TLV (1), length 7
      Subtype MAC address (4): 08:00:27:09:61:e9 (oui Unknown)
      0x0000:  0408 0027 0961 e9
    Port ID TLV (2), length 7
      Subtype MAC address (3): 08:00:27:09:61:e9 (oui Unknown)
      0x0000:  0308 0027 0961 e9
    Time to Live TLV (3), length 2: TTL 120s
      0x0000:  0078
    System Name TLV (5), length 15: Ubuntu-Devstack
      0x0000:  5562 756e 7475 2d44 6576 7374 6163 6b
    System Description TLV (6), length 43
      Ubuntu 11.10\0x0a Linux 3.0.0-14-generic x86_64
      0x0000:  5562 756e 7475 2031 312e 3130 0a20 4c69
      0x0010:  6e75 7820 332e 302e 302d 3134 2d67 656e
      0x0020:  6572 6963 2078 3836 5f36 34
    System Capabilities TLV (7), length 4
      System  Capabilities [Bridge, WLAN AP, Router] (0x001c)
      Enabled Capabilities [Bridge, Router] (0x0014)
      0x0000:  001c 0014
    Management Address TLV (8), length 12
      Management Address length 5, AFI IPv4 (1): Ubuntu-Devstack.local
      Interface Index Interface Numbering (2): 5
      0x0000:  0501 c0a8 7a01 0200 0000 0500
    Port Description TLV (4), length 4: eth4
      0x0000:  6574 6834
    Organization specific TLV (127), length 9: OUI IEEE 802.3 Private (0x00120f)
      Link aggregation Subtype (3)
        aggregation status [supported], aggregation port ID 0
      0x0000:  0012 0f03 0100 0000 00
    Organization specific TLV (127), length 9: OUI IEEE 802.3 Private (0x00120f)
      MAC/PHY configuration/status Subtype (1)
        autonegotiation [supported, enabled] (0x03)
        PMD autoneg capability [10BASE-T hdx, 10BASE-T fdx, 100BASE-TX hdx, 100BASE-TX fdx, 1000BASE-T fdx] (0x6c01)
        MAU type 1000BASET fdx (0x001e)
      0x0000:  0012 0f01 036c 0100 1e
    Organization specific TLV (127), length 6: OUI IEEE 802.3 Private (0x00120f)
      Max frame size Subtype (4)
        MTU size 0
      0x0000:  0012 0f04 0000
    End TLV (0), length 0



The following is the argument list for reference:
 -a    將網絡地址和廣播地址轉變成名字
 -d    將匹配信息包的代碼以人們能夠理解的彙編格式給出
 -dd    將匹配信息包的代碼以c語言程序段的格式給出
 -ddd   將匹配信息包的代碼以十進制的形式給出
 -e    在輸出行打印出數據鏈路層的頭部信息
 -f    將外部的Internet地址以數字的形式打印出來
 -l    使標準輸出變為緩衝行形式( line buffered mode )
 -n    不把網絡地址轉換成名字
 -t    在輸出的每一行不打印時間戳
 -v    輸出一個稍微詳細的信息,例如在ip包中可以包括ttl和服務類型的信息
 -vv    輸出詳細的報文信息
 -c    在收到指定的包的數目後,tcpdump就會停止
 -F    從指定的文件中讀取表達式,忽略其它的表達式
 -i    指定監聽的網絡接口
 -r    從指定的文件中讀取包(這些包一般通過-w選項產生)
 -w    直接將包寫入文件中,並不分析和打印出來
 -T    將監聽到的包直接解釋為指定的類型的報文,常見的類型有rpc (遠程過程調用)和snmp(簡單網絡管理協議;)

Wednesday, April 18, 2012

[ZeroMQ] The new solution for building up distributed system

    I have used TIBCO Rendezvous (RV Message), ActiveMQ (JMS), and RabbitMQ(AMQP) before. They all have message broker, which means all the messages will be send to broker (centralized control) first, and then the client or node will receives them later. But, ZeroMQ has totally different story. I personally believe that it could be a very good solution for building up distributed system.

http://www.zeromq.org/

    And also, this article gives the short introduction and summarizes the important items including "communication transport", "End Point Implementation", "The Socket Object", and so on about ZeroMQ. This content is very uesful for beginner to get to know and read first.
http://www.coastrd.com/zeromq-messaging


[Python] Make pyc file for your Python source code

It could be a situation when you have to give your Python program to customers, but you don't want to give them Python source code. Here is a solution. Give them Python byte code!

For example, on command line:
  • Compile one file
         > python -c "import compileall; compileall.compile_file('YourPythonFile.py')"
  • Compile one folder
         > python -c "import compileall; compileall.compile_dir('YourFolder/', force=True)"

Or, you can put the compiling action in source code

      import compileall
      compileall.compile_dir('YourFolder/', force=True)

Tuesday, April 17, 2012

[Quantum] An example of OpenStack Quantum's table schema and data

mysql> SELECT * FROM ovs_quantum.networks n LIMIT 0,1000;
+--------------------------------------+-----------+---------+-----------+
| uuid                                 | tenant_id | name    | op_status |
+--------------------------------------+-----------+---------+-----------+
| 5b2c8537-26df-4fdc-9e38-3f3f09797d3f | default   | private | UP        |
+--------------------------------------+-----------+---------+-----------+
1 row in set (0.00 sec)
mysql> SELECT * FROM ovs_quantum.ports p LIMIT 0,1000;
+--------------------------------------+--------------------------------------+--------------------------------------+--------+-----------+
| uuid                                 | network_id                           | interface_id                         | state  | op_status |
+--------------------------------------+--------------------------------------+--------------------------------------+--------+-----------+
| e1b7cec5-1d7c-4bcd-b123-4a97f37ef498 | 5b2c8537-26df-4fdc-9e38-3f3f09797d3f | 0a76a701-ea3b-40d8-a56d-fc26a8db69c2 | ACTIVE | DOWN      |
| fdc3836d-c884-4aeb-b5b2-e354745a2de4 | 5b2c8537-26df-4fdc-9e38-3f3f09797d3f | gw-5b2c8537-26                       | ACTIVE | DOWN      |
| d612ccc3-81cd-489c-8cf6-3e37966cebcb | 5b2c8537-26df-4fdc-9e38-3f3f09797d3f | b91861ff-f90b-435d-b9c2-65eb76f0300d | ACTIVE | DOWN      |
+--------------------------------------+--------------------------------------+--------------------------------------+--------+-----------+
3 rows in set (0.00 sec)
mysql> SELECT * FROM ovs_quantum.vlan_bindings v LIMIT 0,1000;
+---------+--------------------------------------+
| vlan_id | network_id                           |
+---------+--------------------------------------+
|       2 | 5b2c8537-26df-4fdc-9e38-3f3f09797d3f |
+---------+--------------------------------------+
1 row in set (0.00 sec)

Monday, April 16, 2012

[sFlow] sFlow Agent and sFlow Collector

sFlow is a technology for monitoring network, wireless and host devices. Based on the following topology, there is a test about using sFlow Agent and sFlow Collector to observe the sFlow data from Open vSwitch.


  • sFlow agent is from Open vSwitch
          How to setup sFlow on Open vSwitch:
          > sudo ovs-vsctl -- --id=@s create sFlow agent=eth0 target=\"colletor ip:6343\" header=128 sampling=64 polling=10 -- set Bridge br0 sflow=@s 
  • sFlow collector is sFlowTrend
 Now, we can see the results from sFlowTrend:

 When trying to ping PC1 and PC2, the result is below:







[Comparsion] Topology graph in NOX GUI and OpenFlow GUI

Using GNS3 for constructing an emulation network environment, I give a simple topology as follows to try running NOX GUI and OpenFlow GUI.
P.S: for more information in GNS3, please refer to this:
http://www.gns3.net/gns3-virtualbox-edition/


In NOX GUI, the topology graph is created like this:


In OpenFlow GUI, the topology graph is created like this:

Saturday, April 14, 2012

[Trema] Try Trema App: flow_dumper


1. Choose "routing_switch" as my testing app. (any other simple switch app is all available...)
> ./trema run -c ../apps/routing_switch/routing_switch.conf

2. Send packets between these 2 hosts
> ./trema send_packets -s host2 -d host1
> ./trema send_packets -s host1 -d host2

3. Try to run Trema App: "flow_dumper" as follows
> TREMA_HOME=. ../apps/flow_dumper/flow_dumper
[0x000000000000e0] priority = 65535, match = [wildcards = 0, in_port = 1, dl_src = 00:00:00:01:00:02, dl_dst = 00:00:00:01:00:01, dl_vlan = 65535, dl_vlan_pcp = 0, dl_type = 0x800, nw_tos = 0, nw_proto = 17, nw_src = 192.168.0.2/32, nw_dst = 192.168.0.1/32, tp_src = 1, tp_dst = 1], actions = [output: port=2 max_len=65535]
[0x000000000000e0] priority = 65535, match = [wildcards = 0, in_port = 2, dl_src = 00:00:00:01:00:01, dl_dst = 00:00:00:01:00:02, dl_vlan = 65535, dl_vlan_pcp = 0, dl_type = 0x800, nw_tos = 0, nw_proto = 17, nw_src = 192.168.0.1/32, nw_dst = 192.168.0.2/32, tp_src = 1, tp_dst = 1], actions = [output: port=1 max_len=65535]

4. So, we can see all the flows here.

Wednesday, April 11, 2012

[Tutorial] How to setup QoS on Open vSwitch

There are two ways to do that:

1. Interface Rate Limiting ( on Interface )
  • For instance:
         > sudo ovs-vsctl set Interface eth1 ingress_policing_rate=10000
         > sudo ovs-vsctl set Interface eth1 ingress_policing_burst=1000

 2. Port  QoS Policy ( on Port )
  • For instance:
         > sudo ovs-vsctl set port eth1 qos=@newqos \
             -- --id=@newqos create qos type=linux-htb \
             other-config:max-rate=200000000 queues=0=@q0,1=@q1 \
             -- --id=@q0 create queue \
             other-config:min-rate=100000000 \
             other-config:max-rate=100000000 \
              -- --id=@q1 create queue \
             other-config:min-rate=50000000 \
             other-config:max-rate=50000000
  • Qos can have more than 1 queue

Tuesday, April 10, 2012

[Tutorial] Trema Tutorial

http://www.fp7-ofelia.eu/assets/Uploads/201203xx-TremaTutorial.pdf

[Open vSwitch] How to get port statistics from interface in OVS

1. Show the bridge info
> sudo ovs-vsctl show
result:
2909bfce-536e-4184-a5bb-507f0553abee
    Bridge "br0"
        Controller "tcp:10.6.186.244"
        Port "br0"
            Interface "br0"
                type: internal
        Port "eth3"
            Interface "eth3"
        Port "eth2"
            Interface "eth2"
        Port "eth1"


2. Get port statistics from interface
> sudo ovs-vsctl get Interface br0 statistics
result:
{collisions=0,
rx_bytes=0,
rx_crc_err=0,
rx_dropped=0,
rx_errors=0,
rx_frame_err=0,
rx_over_err=0,
rx_packets=0,
tx_bytes=0,
tx_dropped=0,
tx_errors=0,
tx_packets=0}

Monday, April 9, 2012

[Python] How to use Decorators for Functions and Methods


When list_ports() is executed, Class ApiCall will be created for becoming a decorator to examine the arguments as follows:


import sys class ApiCall(object): """A Decorator to add support for format and tenant overriding""" def __init__(self, function): self.function = function def __get__(self, instance, owner): def with_params(*args, **kwargs): """ Temporarily sets the format and tenant for this request """ (format, tenant) = (instance.format, instance.tenant) if 'format' in kwargs: instance.format = kwargs['format'] if 'tenant' in kwargs: instance.tenant = kwargs['tenant'] ret = self.function(instance, *args) (instance.format, instance.tenant) = (format, tenant) return ret return with_params class Client(object): def __init__(self, tenant=None, format="xml"): self.tenant = tenant self.format = format @ApiCall def list_ports(self, network): """ Fetches a list of ports on a given network """ return network def main(): client = Client(tenant="AAA",format="xml") client.list_ports('my network') sys.exit(0) if __name__ == "__main__": main()

[Tutorial][Trema] Show Topology


 Trema有一個很不錯的App, 可以利用toplogy topology_discovery App, 去產生topology graph…如下:


下列為Network emulation的設定檔內容
# virtual switches
vswitch("switch1") { datapath_id "0x1" }
vswitch("switch2") { datapath_id "0x2" }
vswitch("switch3") { datapath_id "0x3" }
vswitch("switch4") { datapath_id "0x4" }
vswitch("switch4") { datapath_id "0x5" }

# virtual hosts
vhost("host1")
vhost("host2")
vhost("host3")
vhost("host4")

# virtual links
link "switch1", "switch2"
link "switch1", "switch3"
link "switch2", "switch3"
link "switch2", "switch4"
link "switch2", "switch5"
link "switch3", "switch4"
link "switch3", "switch5"
link "switch4", "switch5"
link "switch4", "host1"
link "switch4", "host2"
link "switch5", "host3"
link "switch5", "host4"

Wednesday, April 4, 2012

[Tutorial] ovsdbmonitor GUI 設定步驟 (setup procedure)

The following steps are the setup procedure for running ovsdbmonitor GUI
(You have to make sure that your "PYTHONPATH" contains the path of openvswitch source path/python. )
   
1. 增加PYTHONPATH到 .bashrc
for example:
PYTHONPATH="${PYTHONPATH}:/home/liudanny/Source/openvswitch-1.2.2/python/"
Export PYTHONPATH

2. 增加一個symbolic link for ovsdb-client
sudo ln -s /usr/local/bin/ovsdb-client /usr/bin/ovsdb-client

3. 執行ovsdbmonitor
“your openswitch path”/ovsdb/ovsdbmonitor/ovsdbmonitor

4. 設定Host Properties:
Host name or IP: your openvswitch host
SSH Password: ***
Connect target: unix:/usr/local/var/run/openvswitch/db.sock
*     這個connect target 會與 啟動ovsdb-server daemon 的參數有相關 *
          sudo ovsdb-server --remote=punix:/usr/local/var/run/openvswitch/db.sock \
                    --remote=db:Open_vSwitch,manager_options \
                    --private-key=db:SSL,private_key \
                    --certificate=db:SSL,certificate \
                    --bootstrap-ca-cert=db:SSL,ca_cert \
                    --pidfile --detach


5.       相關畫面 (可以看到ovs database 內的table content, 每個頁簽都代表一個table)

[Info] Quantum L3 Model and API

The following link is about adding L3 concept and APIs ( routing between Subnets) into OpenStack Quantum.
http://wiki.openstack.org/quantum-l3

The more information is here:
quantum-l3-service-spec-SumitNaiksatam-5.pdf

Monday, April 2, 2012

如何在Python內使用Singleton方法



# There is an example to do with Singleton in Python def singleton(cls): instances = {} def getinstance(): if cls not in instances: instances[cls] = cls() return instances[cls] return getinstance @singleton class MyClass(): def __init__(self): self.data = "AAA" if __name__ == "__main__": obj_a = MyClass() obj_a.data = "AAAA" print obj_a, obj_a.data obj_b = MyClass() print obj_b, obj_b.data

Big Switch: the SDN Coffee Talks

Big Switch Networks Launches SDN Coffee Talks to Further Educate the
Broader IT Community on Software-Defined Networking (SDN)

the SDN Coffee Talks
http://www.bigswitch.com/sdn-coffee-talks/

如何取得Open vSwitch 上的 datapath id

ovs-vsctl -- get bridge br-int datapath_id

[HowTo] Build up GRE Tunneling on Open vSwitch

// Create a bridge
ovs-vsctl add-br br0

// Build up GRE Tunnel on remote host's ip = x.x.x.x
ovs-vsctl add-port br0 gre0 -- set interface gre0 type=gre options:remote_ip=x.x.x.x

In this article, the author explains more info about GRE Tunneling in details.
http://d.hatena.ne.jp/kazuya_ax/20120420/1334928361
The way for him to build GRE Tunneling is as follows:
ovs-vsctl set interface gre0 type=gre options:remote_ip=x.x.x.x options:pmtud=false

Friday, April 11, 2008

Iron Speed Designer

Iron Speed Designer is a .NET web application development tool that can generate your web application straight from your database. You just simply point to an existing database and let the Iron Speed Designer wizards build a sophisticated, database-driven application that's easy to customize and ready to deploy.

If you are a web developer and dedicated in ASP .NET programming, you maybe feel uncomfortable about the information as follows. What I mean is that you probably could not build a .NET web application more better than it if you already have several years work experience with ASP .NET.

Check out these links.

Iron-Speed Designer Web Site:
http://www.ironspeed.com/products/Landing.aspx?c=CP02

Demo Video:
http://www.ironspeed.com/Designer/5.1.0/Videos/5MinuteVideo/5minutevideo.html

Friday, March 21, 2008

SoftRock FM 102.1

After several days in studying hard for the midterm, I finally can take a break and relax a little bit. Meanwhile I feel that this blog is full of too much stuffs about IT field. It should be balanced with other topics.
In Cleveland, SoftRock FM 102.1 is the radio channel I listen to it so often. The songs it plays are almost very popular and favorite for people. It also has web site on the Internet for listening. Click "Listen Live" and enjoy it. Here you go. http://www.wdok.com/

Thursday, March 6, 2008

Google Web Toolkit

If you are familiar with Java programming but not familiar Ajax (Asynchronous JavaScript + XML) , Google Web Toolkit (GWT) is a good choice to deal with Ajax web application.
GWT provides its APIs for developers to write Java code in the program, and then compiles to JavaScript. In the web site of GWT, it gives a lot of features about GWT, and explains how to translate Java code to JavaScript.
Some people may have an question why I need to write Java code instead of JavaScript directly? In my opinion, it is about "software engineering". It may be easy if you only have a small or not so big Ajax application. Once you have more and more projects that need to do, you probably will find that your debugging time is longer than you think and your source code is hard to be reused. Due to these issues above, Google develops this way to deal with Ajax. Using GWT, we can leverage Java's ability and Java IDE tool to build application logic through well-designed object-oriented techniques.

Saturday, March 1, 2008

To promote reusability

To reuse our source code or classes is a hard task specially when we don't think about this in the beginning of analysis or design. Even though we have already done our projects or programs that is not well-designed, we can use some refactoring function inside the IDE tool for us to adjust or arrange our source code, for instance, to extract the interface from classes. But, it is still much better if we know how to promote reusability and do it in the analysis/design phase. In the book, Pro Java Programming 2nd Edition, it provides 2 good principles (Loose Coupling and Strong Cohesion) for reference.

1. Loose Coupling
Coupling means that it refers to the degree to which classes depend upon one another, and two classes that are highly dependent upon each other are considered tightly (or highly) coupled. In other words, they cannot be used alone and also not be used for other classes. There are some examples from this book and I draw the class diagrams to explain the idea.

a.) This diagram shows that these two classes have strong coupling. They refer each other and are Bad-designed.

b.) This diagram shows that it uses an interface "FontListener" to reduce the coupling. "FontProperitesPanel" doesn't need to know who implements the interface "FontListener". It just calls the method "fontChanged()" in the interface, and "SampleTextFrame" that implements the interface will response.

c.) This diagram shows we create a "FontPropertiesFrame" class that extends "SampleTextFrame" that can eliminate "SampleTextFrame"’s references to the "FontPropertiesPanel" class and move them into a subclass of SampleTextFrame.
2. Strong Cohesion
If a class is highly cohesive, it means its responsibilities are closely related and that it’s complete. In other words, the class isn’t cohesive if it contains methods that perform unrelated functions or if some set of closely related functions is split across that class and one or more others.
So, I think that these 2 principles are quite useful when we design our classes structure.

Thursday, February 28, 2008

A glimpse of Flex

This term "Rich Internet Applications (RIAs) is popular in a coupe of years recently. Adobe is one of company that provides a very good software and development kit that is based on Flash to build your Flash-based applications which belongs to RIA. The product, Flex, is the key software to achieve this goal. Currently Adobe is released Flex 3 builder that is a tool using Eclipse IDE and plug-ins to develop Flex web application. Because I download the trail version of Flex 2, the information of display as follows is about Flex 2.
There is a point that I need to clarify. Flash and Flex is not standard Ajax-based. because both of them need to download Flash plug-in and the SWF file is executed on the plug-in player.

(Data Source from Adobe)
A typical Flex application consists of the following elements.

Flex framewor

The Adobe® Flex 2 framework contains all the components you need to build rich Internet applications, which include:

Containers that you use to layout the application

Controls you use to gather data from users and to manage the user interface (Text and Button, for example)

Extensive data binding, formatting, and validation features

An event-driven development model that provides rich user interface transformation features such as effects and transitions.

The Flex framework is contained within a shared component library (SWC) file.

MXML

Every Flex application contains at least one MXML file, known as the main application file. MXML is a markup language, an implementation of XML that was designed specifically for creating Flex applications, and you use it to declaratively define the structure of your application using tags.

ActionScript 3.0

You add dynamic behavior to your applications using ActionScript 3.0, which is an implementation of ECMAScript and is similar to JavaScript. You can add ActionScript to Flex applications directly in the MXML file as script blocks or you can create separate files of ActionScript functions and import them into your MXML files.

CSS

Style attributes in visual components (buttons, list boxes, and so on) are controlled by component properties. For example, a button component has a fontFamily property that you use to set the font. Style properties are controlled by a theme, by styles defined in a CSS file, by styles defined in style blocks in an MXML file, or by setting individual style properties in the component instance itself.

Graphic assets

Like most applications, Flex applications contain a variety of graphic assets such as icons and other images.

Data

Some components are used to display data (a combo box or data grid for example) and you can populate these components with data by using arrays, collection objects, data models, external XML data sources, and so on.

(Data Source from Adobe)
Generating the data:
Since Flex applications do not directly connect to a database, you need to interact with data using some kind of service. In the following examples, the Flex HTTPService component is used to retrieve data from an XML file that is generated by PHP.

The first step in connecting to data is to generate the data that will be used in the Flex application. On the PHP side, you would follow these steps:

a. Create a database (MySQL for example) if one does not already exist.

b. Write a PHP script to both connect to the MySQL database and generate the XML-formatted data.

P.S: These steps also apply to any other tools you might use to generate the data (ColdFusion, ASP.NET, JSP, JavaEE server, and so on).

The screen shot of Flex 2 Builder:






Thursday, February 21, 2008

A small problem in programming with Java ME

Recently I feel weird by dealing with threads and alerts in programming with Java ME. One of the problems is that my program will occur NullPointException in the console.

java.lang.NullPointerException
at javax.microedition.lcdui.Alert$1.commandAction(Alert.java:663)
at javax.microedition.lcdui.Alert$timeoutTask.run(Alert.java:1110)
at java.util.TimerThread.mainLoop(+237)
at java.util.TimerThread.run(Timer.java:462)


Based on this Exception message, I checked the source code of Java SE 1.6 version ( Thanks for Sun Microsystems to open the Java source ) of Timer and TimerThread because I cannot see the source in Java ME, so I use JavaSE to guess the structure of JavaME. P.S: The core APIs are still different even the package name are the same. And also, I drew a diagram as follows for myself to figure out the whole situation about my threads, alert, and timertask. This problem I guess is in "Alert" class.

Alert class allows to setup the timing for showing on the screen during it appears, and it still has a TimerThread to control seconds. TimerThread only can do one task at the same time. So there is a situation: If I let my "AlertThread" setup the alert before the alert disappear ( done its work) and it happens more than 1 task needed to do. Then it will occur the problem. After I changed the timeout of the Alert, it didn't happen the problem again.


Using the emulator of Wireless Tool kit 2.5.2 to run TimerMIDlet:




Friday, February 15, 2008

New Android SDK is released!

If you saw the screen of the previous Android SDK before, you will quickly find out that this new Android SDK released is so different from looking and operating now. I learned some information about the previous SDK that had some bugs found by the community. So I think Android this time provides new SDK version for fixing the bugs, update APIs, and also enhances some basic functions, for instance maps application as following pictures:

The new desktop of Android platform

Maps application's new feature (zoom in)


I find my home in Taiwan...

Thursday, February 14, 2008

A simple Google Android application Part II

In Android framework, Activity class just like MIDlet in Java ME, it provides a frame to display the UI or perform a task. To layout the widgets on Activity, we can use xml file to achieve that. This example has 2 Activity classes, MainActivity.java and Queen.java, each has xml file to define the widgets and layout. In Queen.java, it uses recursive method to solve the N x N Queen problem. Due to the algorithm is not relevant to Android platform, so I emit the most source code with the algorithm and only put the method putQtoArray() to show recursive way.as follows:

main.xml


<Button android:id="@+id/MainButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="OK"
android:layout_x="10px" android:layout_y="102px">
</Button>


<Button android:id="@+id/MainButton2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="Cancel"
android:layout_x="80px" android:layout_y="102px">
</Button>




queen.xml:




<Button android:id="@+id/QueenButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="OK"
android:layout_gravity="right">
</Button>


MainActivity.java

package csu.android.applications;

import android.app.Activity;

import android.content.Intent;

import android.os.Bundle;

import android.view.View;

import android.widget.EditText;

import android.text.method.*;

import android.view.View.OnClickListener;

import android.widget.Button;

public class MainActivity extends Activity {

private EditText myEText;

/** Called when the activity is first created. */

@Override

public void onCreate(Bundle icicle) {

super.onCreate(icicle);

setContentView(R.layout.main);

myEText = (EditText) findViewById(R.id.MainEditText1);

myEText.setInputMethod(DigitsInputMethod.getInstance());

Button okButton = (Button) findViewById(R.id.MainButton1);

Button cancelButton = (Button) findViewById(R.id.MainButton2);

okButton.setOnClickListener(mOKListener);

cancelButton.setOnClickListener(mCancelListener);

}

private OnClickListener mOKListener = new OnClickListener() {

public void onClick(View v) {

String tmp = myEText.getText().toString();

if (!myEText.getText().toString().equals("")) {

int Qnum = Integer.parseInt(tmp);

if (Qnum <= 9) {

// Here we start up the main entry point

Intent intent = new Intent(MainActivity.this, Queen.class);

intent.putExtra("NumKey", tmp);

startActivity(intent);

finish();

} else {

showAlert("The number is bigger than 9!", 0, "Try again!",

"OK", true);

myEText.setText("");

return;

}

}

}

};

private OnClickListener mCancelListener = new OnClickListener() {

public void onClick(View v) {

myEText.setText("");

}

};

}



Queen.java

package csu.android.applications;

import android.app.Activity;

import android.content.Intent;

import android.os.Bundle;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.Button;

import android.widget.EditText;

import java.util.*;

public class Queen extends Activity {

EditText myEText;

int QueenNum;

int totalcount = 0; // the total number of distinct results.

int uniquecount = 0; // the total number of unique results.

boolean[][] arr;

// Record the scores for mapping

ArrayList al;

// For check the duplicate solutions

int[][] arrRotation0;

int[][] arrRotation90;

int[][] arrRotation180;

int[][] arrRotation270;

int[][] arrMirror;

private StringBuilder sb;

/** Called when the activity is first created. */

@Override

public void onCreate(Bundle icicle) {

super.onCreate(icicle);

setContentView(R.layout.queen);

myEText = (EditText) findViewById(R.id.QueenEditText1);

Button backButton = (Button) findViewById(R.id.QueenButton1);

backButton.setOnClickListener(this.mBackListener);

Bundle extras = getIntent().getExtras();

if (extras != null) {

QueenNum = Integer.parseInt(extras.getString("NumKey"));

startCalculation();

myEText.setText(sb.toString());

} else {

showAlert("There is no input!", 0, "Click me", "OK", true);

Intent intent = new Intent(Queen.this, MainActivity.class);

startActivity(intent);

finish();

}

}

private OnClickListener mBackListener = new OnClickListener() {

public void onClick(View v) {

Intent intent = new Intent(Queen.this, MainActivity.class);

startActivity(intent);

finish();

}

};

/*

* startCalculation This method implements recursion for N*N Queen problem.

*/

public void startCalculation() {

sb = new StringBuilder();

// Array for N*N Queens problem

arr = new boolean[QueenNum][QueenNum];

// Array for calculating the duplicate result.

arrRotation0 = new int[QueenNum][QueenNum];

arrRotation90 = new int[QueenNum][QueenNum];

arrRotation180 = new int[QueenNum][QueenNum];

arrRotation270 = new int[QueenNum][QueenNum];

arrMirror = new int[QueenNum][QueenNum];

al = new ArrayList();

// Prepare random numbers inserted into arrays

// for the calculation of the duplication .

prepareRotationData();

// Do recursions

putQtoArray(QueenNum - 1);

}

/*

* putQtoArray This method implements recursion for N*N Queen problem.

* @param: QueenNum

*/

public void putQtoArray(int myNum) {

if (myNum == -1) {

// Find a distinct result.

totalcount++;

// Display the result.

showMe();

return;

}

for (int i = 0; i <>

if (!checkRule(i, myNum)) {

arr[i][myNum] = true;

// Recursion

putQtoArray(myNum - 1);

arr[i][myNum] = false;

}

}

}

... ... rest of part is omitted ... ...

}

Because Activity "Queen" will be started by Activity "MainActivity" using Intent, we also need to add a line into AndroidManifest.xml as below, then that is all set. <activity android:name="Queen" android:label="@string/app_name">

A simple Google Android application Part I

What is Google Android? I don't need to babble that... because I think that it will be very clear if you see this : http://code.google.com/android/what-is-android.html


Basically, Android includes Linux kernel as operating system, libraries ( C language), Android runtime ( Dalvik virtual machine for Java byte code), and application framework (APIs for Java) . The applications we wanna develop are based on this application framework and Java 1.5 language specification, and will run on Android runtime.

Until now, Google only has prototype cell phone for running Android platform. Due to this reason, all the applications need to execute on the emulator which emulates the same environment just like you really have the hardware. There is a simple example that can give an idea about developing a Android application.

This example will ask you a number for defining N x N Queen problem.
Then it will calculate the possibility of results showing as a simple checker.

P.S: It runs on the Android emulator.

Tuesday, February 12, 2008

JavaFX Scripting Language

As we know that scripting language for an operating system is called a shell script such as C shell.
In January 2007, IronPython was released. It is a new implementation of the Python programming language running on .NET. This year also in January, Sun was released The JavaFX Script Programming Language.
These two scripting language are amazing for developers to control the applications dynamically during the run-time. For example, you can create a Frame in the command line like : var jframe= new JFrame("This is a Frame"); or use JavaFX code to define it. Then, you can modify the attributes and see the change immediately. I think that it is useful when developers wanna design GUI applications because arranging UI components and layouts are tedious jobs. More details about Java FX Scripting Language as link: https://openjfx.dev.java.net/JavaFX_Programming_Language.html
http://java.sun.com/developer/technicalArticles/scripting/javafx/ria_1/

Friday, February 8, 2008

[Android] DroidDraw

Dealing with the widgets and layouts in the Android project is a tedious work, especially Eclipse plug-in Android right now doesn't have visual tool for developers to construct the interfaces.
All the things need to do with XML. Fortunately, there is a tool that is very useful to it.
It also provides tutorials that developers can quickly understand how to use it.

http://www.droiddraw.org/

Tuesday, February 5, 2008

[Flickr] Schmap: San Francisco Photo Short-list

Today I got a email from Flickr about my one photo that has been short-listed for inclusion in the fourth edition of our Schmap San Francisco Guide, to be published mid-February 2008.
Schmap: San Francisco Photo Short-list
http://www.schmap.com/shortlist/p=61565007N00/c=SF20012284

That photo was taken from Hyatt Hotel in San Francisco.
I don't know that my old digital camera (Nikon 995) was still able to take good photos.