2010年7月28日 星期三

[PERL]-Gtk2Perl on Windows

最近有個案子是用Perl開發Gtk
因為手頭上沒有Unix like環境
所以必須在windows上架構Gtk2Perl的環境

首先要先安裝ActivePerl這樣才能在windows上編譯及執行Perl
下載位置:ActivePerl
注意,這裡建議安裝ActivePerl 5.8.9.827版本比較穩定,
更新的版本在install ppm上會有些不可預期的問題。


再來利用ppm指令載入Gtk相關的模組
ppm install http://gtk2-perl.sourceforge.net/win32/ppm/ExtUtils-Depends.ppd
ppm install http://gtk2-perl.sourceforge.net/win32/ppm/ExtUtils-PkgConfig.ppd
ppm install http://gtk2-perl.sourceforge.net/win32/ppm/Glib-1080.ppd
ppm install http://gtk2-perl.sourceforge.net/win32/ppm/Gtk2-1080.ppd

ppm install http://gtk2-perl.sourceforge.net/win32/ppm/Gtk2-GladeXML-1.005.ppd

接著要安裝GTK+ Development Enviroment
下載位置:Glade/Gtk+ for Windows
這個安裝檔包含glade3,一個Gtk所見即所得的工具

整個Gtk2Perl的開發環境在此已建構完成
接下來實際拉個畫面來試試看
打開glade3拖拉個畫面如下,並另存新檔檔名為GUI.glade:

接著建個文字檔Gtk2Perl.pl,內容如下
use Glib qw/TRUE FALSE/;
use Gtk2 '-init';
use Gtk2::GladeXML;

my $gladexml = Gtk2::GladeXML->new("GUI.glade");
$gladexml->signal_autoconnect_from_package('main');

my $window = $gladexml->get_widget('window1');
$window->signal_connect( 'delete_event' => sub{Gtk2->main_quit();});
$window->show_all();

Gtk2->main();

由上面的程式碼可知我們就是用Gtk2::GladeXML這個模組來載入glade編寫出來的.glade檔,
接著直接點擊Gtk2Perl.pl就可以看到執行畫面:

注意,如果執行期發生如下的error
Can't locate object method "signal_connect" via package "Gtk2::Window"
請找出Gtk2.pm檔案,在開頭加上push @Gtk2::Object::ISA, 'Glib::Object';這行即可

最後簡單介紹兩個元件的使用心得
Gtk2::ComboBox,下面的程式碼(非完整)
利用Gtk2::ListStore來做為combobox model的資料來源,
使用Gtk2::CellRendererText來呈現Combobox的欄位,
$FFComboBox->add_attribute ($fy_renderer, "text", ID_COLUMN);
表示render由model的ID_COLUMN欄位取得"text"文字資料
$fy_model = Gtk2::ListStore->new('Glib::String');
foreach (reverse(keys(%fy_all))) {
$fy_model->set($fy_model->append, ID_COLUMN, $_);
}
$FFComboBox->clear();
$FFComboBox->set_model($fy_model);
$fy_renderer = Gtk2::CellRendererText->new;
$FFComboBox->pack_start ($fy_renderer, false);
$FFComboBox->add_attribute ($fy_renderer, "text", ID_COLUMN);
if ($FFComboBox->get_active() == -1) {
$FFComboBox->set_active(0);
}


Gtk2::Dialog,下面是說明一般是如何接受Dialog(與繼承Dialog的模組)的回傳動作,
$config_dialog->set_response_sensitive (0, FALSE);
是說將0註冊為這個dialog的response_id,
然後$config_dialog->run()時會等待該dialog有所動作,並回傳該動作的response_id,
至於dialog的動作就是由button元件觸發,所以button元件會有一個response_id屬性,
用來註明該button動作時會回傳的response_id值,
最後就是利用if (0 eq $config_dialog->run())來判斷按下的是dialog中的那一個按鈕
my $config_dialog = shift @_;
my $text_view = shift @_;

$config_dialog->set_response_sensitive (0, FALSE);
$config_dialog->show();
if (0 eq $config_dialog->run()){
$config_dialog->hide();
}

參考文件:

2010年7月22日 星期四

GTK+ with Dev-C++ on Windows

前言:
        說到C/C++開發環境,就不能不提到GCC。GCC是GNU Compiler Collection (GNU編譯器總集)的縮寫,為GNU計畫中一套多種程式語言編譯器的集合,在諸多Unix-like與Mac OS X中
都成為其內建的程式開發環境。

        其實,GCC最初的名稱為GNU C Compiler (GNU C 語言編譯器)。在當時,GCC還只是一個專門處理 C 語言的編譯器。而在後來 GCC 擴展之後,慢慢的也可以處理C++、Fortran、
Ada、Java、Objective-C 等語言。發展至今,就是現在我們所看到的編譯器總集了。

        雖然在Unix-like與Mac OS X系統中都已經內建了GCC的環境,但是若要在Windows系統下擁有相同的環境,你可能就需要安裝MinGW了。

        MinGW(Minimalist GNU for Windows),又稱Mingw32,為包含了GCC、GDB(GNU Debugger)、binutils等工具的GNU工具組(toolchain)移植到windows平台上的版本。包括一系列表頭檔(Win32API)、函式庫和可執行檔案。 MinGW是從Cygwin(1.3.3版)基礎上發展而來,但是用MinGW開發的程式不需要額外的第三方DLL支援就可以直接在Windows下執行,而且也不一定必須遵從GPL許可證。

進入正題:
下載Dev-C++ 並安裝
Bloodshed Dev-C++ 4.9.9.2 with MinGW for Windows
下載GTK+ Development Enviroment 並安裝
GTK+ Development Enviroment 2.12.9-2 for Windows

接下來檢查GTK+ Path 是否有正確設定於Dev-C++

執行Dev-C++
點選工具列的「Tools -> Compiler Options」,開啟Compiler Options視窗,
點選「Directories」頁籤,點選「Libraries」頁籤,檢查是否含有以下路徑:C:\GTK\LIB

點選「C Includes」「C++ Includes」頁籤,檢查是否含有以下路徑:
C:\GTK\INCLUDE
C:\GTK\INCLUDE\GTK-2.0
C:\GTK\INCLUDE\GLIB-2.0
C:\GTK\INCLUDE\PANGO-1.0
C:\GTK\INCLUDE\CAIRO
C:\GTK\INCLUDE\ATK-1.0
C:\GTK\INCLUDE\GTKGLEXT-1.0
C:\GTK\LIB\GTK-2.0\INCLUDE
C:\GTK\LIB\GLIB-2.0\INCLUDE
C:\GTK\LIB\GTKGLEXT-1.0\INCLUDE
C:\GTK\INCLUDE\LIBGLADE-2.0
C:\GTK\INCLUDE\LIBXML2
 
建立新專案,在新產生的檔案內輸入第一個GTK+的程式碼:
#include 

int main(int argc, char *argv[])
{
GtkWidget *window;
gtk_init(&argc, &argv);
window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
gtk_window_set_title(GTK_WINDOW(window), "Hello! GTK+!");
gtk_widget_show(window);
gtk_main();
return 0;
}
在Project頁籤內的專案圖示上按右鍵點選「Project Options」點選「Parameters」頁籤
在欄位「Compiler」,輸入以下參數:
-mms-bitfields -IC:\GTK\include\gtk-2.0 -IC:\GTK\lib\gtk-2.0\include -IC:\GTK\include\atk-1.0 -IC:\GTK\include\cairo -IC:\GTK\include\pango-1.0 -IC:\GTK\include\glib-2.0 -IC:\GTK\lib\glib-2.0\include -IC:\GTK\include\libpng12
 
在欄位「Linker」,輸入以下參數:
-LC:\GTK\lib -lgtk-win32-2.0 -lgdk-win32-2.0 -latk-1.0 -lgdk_pixbuf-2.0 -lpangowin32-1.0 -lgdi32 -lpangocairo-1.0 -lpango-1.0 -lcairo -lgobject-2.0 -lgmodule-2.0 -lglib-2.0 -lintl
 
 
compile後執行:
 
compiler參數需要加入-mms-bitfields 的原因:
For reference, here is what the gcc info file has to say about -mms-bitfields:

5.34.3 i386 Variable Attributes
-------------------------------
Two attributes are currently defined for i386 configurations:`ms_struct' and `gcc_struct'
`ms_struct'
`gcc_struct'
If `packed' is used on a structure, or if bit-fields are used it
may be that the Microsoft ABI packs them differently than GCC
would normally pack them. Particularly when moving packed data
between functions compiled with GCC and the native Microsoft
compiler (either via function call or as data in a file), it may
be necessary to access either format.
Currently `-m[no-]ms-bitfields' is provided for the Microsoft
Windows X86 compilers to match the native Microsoft compiler.

2010年7月21日 星期三

[MS-Server]-JDBC連接SQL Server 2005

首先下載三個元件
1.Microsoft SQL Server 2005 Express Edition SP3
    安裝時要選混合認証,並為管理者帳號sa設立一組密碼。
2.SQL Server Management Studio 2005 SP3
3.SQL Server 2005 driver for JDBC
    解壓縮後得到的sqljdbc.jar置於jre/lib/ext下
    筆者實際安裝目錄:C:\Program Files\Java\jre6\lib\ext
    並在classpath下加入這行:C:\Program Files\Java\jre6\lib\ext\sqljdbc.jar
    這樣Class.forName時才找的到driver(後面程式碼會說明)。

接下來為了能夠透過TCP/IP來連接sql server還必需多做下列這個動作
   a.打開SQL Server Configuration Manager -> SQLEXPRESS的協議 -> TCP/IP
   b.右鍵單擊啟動TCP/IP
   c.雙擊進入內容,把IP地址中的IP all中的TCP端口設置為1433
   d.重新啟動SQL Server 2005服務中的SQLEXPRESS服務器
   e.關閉SQL Server Configuration Manager

開下來利用SQL Server Management Studio工具新增一個資料庫"Test"
新增兩個欄位及增加一筆值組如下:
field1   field2
----------------
data1   data2

接下來就是實際的存取範利程式碼
public static void main(String[] args) {
  Connection conn = null;
    try {
      Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
      String url = "jdbc:sqlserver://localhost:1433;DatabaseName=Test";
            
      String user = "sa";
      String password = "50321177";
      conn = DriverManager.getConnection(url, user, password);
      PreparedStatement ps = null;
      ResultSet rs = null;
      String sql = "SELECT * FROM table1";
      ps = conn.prepareStatement(sql);
      rs = ps.executeQuery();
      while (rs.next()) {
        System.out.println(rs.getString("field1"));
        System.out.println(rs.getString("field2"));
      }
      conn.close();
    } catch (Exception e) {
      e.printStackTrace();
  }
}

接下來是額外的補充
在SQL Server 2000 中加載driver和URL路徑的語法是
String driverName = "com.microsoft.jdbc.sqlserver.SQLServerDriver ";
String dbURL = "jdbc:microsoft:sqlserver://localhost:1433; DatabaseName=sample ";
而SQL Server 2005 中加載driver和URL路徑的語法是
String driverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver ";
String dbURL = "jdbc:sqlserver://localhost:1433; DatabaseName=sample ";

2010年7月10日 星期六

[C#]-讀取excel檔案寫入MS SQL Server

最近寫案子有用到C#去讀取excel檔案再寫入MS SQL Server,
這是滿常用到的功能所以在這裡記錄一下。

首先是利用oledb讀取excel檔,再利用OleDbDataAdapter將資料填入DataSet。
OleDbDataAdapter 是 DataSet 和資料來源之間的橋接器,用來擷取和儲存資料。OleDbDataAdapter 會提供這個橋接器,方法是使用 Fill 從資料來源將資料載入 DataSet,並使用 Update 將 DataSet 中所做的變更傳送至資料來源。

OLE DB簡介
OLE DB 是一種以 COM 為基礎、用來存取資料的應用程式發展介面 (Application Programming Interface,API)。OLE DB 可存取以任何格式所儲存的資料 (資料庫、試算表、文字檔等等),只要該格式能夠使用 OLE DB 提供者 (Provider)。每個 OLE DB 提供者都會公開特定資料來源類型 (例如 SQL Server 資料庫、Microsoft Access 資料庫或 Microsoft Excel 試算表) 的資料。

常用的Provider列表
Database                Provider
----------------------------------------------------
Ms SQL server       Provider=SQLOLEDB
Oracle                   Provider=MSDAORA
Ms Access 2003    Provider=Microsoft.jet.OLEDB.4.0
Ms Access 2007    Provider=Microsoft.ACE.OLEDB.12.0
Ms Excel 2003       Provider=Microsoft.jet.OLEDB.4.0
Ms Excel 2007       Provider=Microsoft.ACE.OLEDB.12.0
IBM DB2                Provider=DB2OLEDB

private void button1_Click(object sender, EventArgs e)
{
  // Show the dialog and get result.
  DialogResult result = openFileDialog1.ShowDialog(); 
  if (result == DialogResult.OK) // Test result.
  {
    // get excel file name
    string fileName = openFileDialog1.FileName;
    textBox1.Text = fileName;
    button2.Enabled = true;
    // import excel into datagridview
    string excelConn = "Provider = Microsoft.Jet.OLEDB.4.0 ; 
           Data Source = " + textBox1.Text + ";
           Extended Properties = 'Excel 8.0;HDR=YES'";
    string strExcelSelect = "SELECT * FROM [Sheet1$]";
    OleDbDataAdapter adapter = 
          new OleDbDataAdapter(strExcelSelect, excelConn);
    DataSet dataSet = new DataSet();
    adapter.Fill(dataSet, "ExcelInfo");
    dataGridView1.DataSource = dataSet.Tables["ExcelInfo"].DefaultView;
  }
}
再來是將資料從datagridview中匯入MS SQL Server
雖然 .NET沒有類似JAVA的preparedstatement,但有類似的應用IDbDataParameter。
private void button2_Click(object sender, EventArgs e)
{
  string strDBInsert = "INSERT INTO customers VALUES
       (@name,@hPhone,@oPhone,@addr,@delivery,@midwife,@source)";
  string strConn = "Data Source = 6A-783500-NB\\SQLEXPRESS;
                   Integrated Security = True";
  SqlConnection sqlConn = new SqlConnection(strConn);
  sqlConn.Open();
  SqlCommand sqlCmd = new SqlCommand(strDBInsert,sqlConn);
  progressBar1.Step = 100/dataGridView1.Rows.Count;
  for (int i = 0; i < dataGridView1.Rows.Count; i++)
  {
    try
    {
      sqlCmd.Parameters.Clear();
      sqlCmd.Parameters.AddWithValue
          ("@name", Convert.ToString(dataGridView1[0, i].Value));
      sqlCmd.Parameters.AddWithValue
          ("@hPhone", Convert.ToString(dataGridView1[1, i].Value));
      sqlCmd.Parameters.AddWithValue
          ("@oPhone", Convert.ToString(dataGridView1[2, i].Value));
      sqlCmd.Parameters.AddWithValue
          ("@addr", Convert.ToString(dataGridView1[3, i].Value));
      sqlCmd.Parameters.AddWithValue
          ("@delivery", Convert.ToString(dataGridView1[4, i].Value));
      sqlCmd.Parameters.AddWithValue
          ("@midwife", Convert.ToString(dataGridView1[5, i].Value));
      sqlCmd.Parameters.AddWithValue
          ("@source", Convert.ToString(dataGridView1[6, i].Value));
      sqlCmd.ExecuteNonQuery();
      progressBar1.PerformStep();
      }
    catch (Exception e1)
    {
      continue;
    }
    dataGridView1.Rows[i].DefaultCellStyle.BackColor =
                                          Color.CornflowerBlue;  
  }
  progressBar1.Value = progressBar1.Maximum;
  sqlConn.Close();
}

2010年6月22日 星期二

巴里島蜜月之旅-第4天~第5天

第四天:
早上一大早就被我家那口子走動的聲音吵醒了
果不其然的是按奈不住一大早就起來狂拍照
(我懷疑她是個拍照狂~)

淋浴間就在馬桶的旁邊,連門都是透明的

這就是以往只能對著電視流口水發夢的私人遊泳池
還有游泳池旁邊一定要的懶人躺椅

還有小廚房可以煮東西吃,別以為這個廚房你會用不到
吃壞肚子的時候還可以自已煮些東西來吃(本人悲慘遭遇~~)

主臥房旁邊有一個小客廳可以用來招待客人,外面的桌椅就是平常吃飯的地方

初體驗是一定要的啦,享受當富豪般的快感
其實我比較想躺在氣墊上漂在游泳池上喝果汁
不過我沒有臉去問有沒有這種東西~

附贈的早餐,很好食,這裡忍不住再大推一下,峇里島的果汁真的很好喝

吃完早餐我們步行往厙塔街上走去,本來是想看看有沒有什麼可以shopping的地方
結果發現九點出門太早了,大部份的店家還沒開始營業
而且庫塔街上的商店裡面賣的商品大多大同小異,
路旁有很多怪怪的人會向觀光客推銷商品
街道又滿髒亂的,不是很好逛,我們大概逛了一個小時就回葉子了
向櫃台叫了計程車,下一站往神鷹廣場出發

就是這頭鷹

這座神像是騎在鷹上的,但是每個部位目前都還是分開的
據說是材料銅收集不易,組裝進度緩慢

組合起來的完整體就像這樣,非常帥氣的感覺

其實神鷹廣場行覺得滿普通的
不太值得千里沼沼從厙塔坐計程車過去
車程大概花了快四十分鐘,而且神像也還沒組裝完成
如果整個組裝好應該是滿壯觀的
由於中午太熱了,我們又從神鷹廣場回到了葉子休息一翻
大約三四點才又從葉子出發準備到太陽百貨shopping

路口招的計程車,在峇里島叫"藍鳥"計程是一定要的啦
比較有保障,也不會被隨地亂起價

太陽百貨一帶真的還滿熱鬧的
我還是比較習慣逛這種比較先進的shopping mall

在這裡買了一些吊飾
(峇里島的吊飾真的很不耐用,超容易壞的,回來用不到一個禮拜吊線就斷了,
因為他們吊線用的不是鐵環,是尼龍繩…)
也買了一堆RURU霜,太座要拿來送朋友的…

回到葉子,他們已經幫我們佈置好我們加訂的蜜月套餐了

還有整池的玫瑰花瓣

第五天:
早上一起來看到那整池的玫瑰花瓣真的是有嚇到
昨天晚上光線不足比較看不清楚,早上看真是一整個有fu呀,非常壯觀~


今天的早餐內容跟昨天差不多,吃完休息一下就收拾一翻要準備離開葉子了
來接我們的一樣是旅行社第三天派給我們的隨車導遊"小林"
不過他實在太低調了,導致我們完全忘了跟他一起合照…

午餐前還有時間,小林先帶我們到賣黃金咖啡的工廠
這也是太座指明要來買伴手禮的地方

負責介紹的小姐講的口沫橫飛,我們也學到了一些咖啡豆的相關知識
當然最後雖然昂貴的射香貓咖啡買不起
(射香貓>公豆>母豆)
也買六包的公豆咖啡,一包要台幣八百@@
(家裡沒磨咖啡豆機的最好別買…因為就算請店家先
幫你磨成粉,還是不能夠直接泡來喝,泡完還得先濾過才行,
我們自己留了一包,喝的時候才發現泡完裡面還是很多咖啡渣,
還要買濾紙濾過才能喝,不方便呀~)

左邊跟貓大便混在一起的就是射香貓咖啡

買完了咖啡下一站就是峇里島名產專賣店,庫塔應該有一兩間,這間店依然是小林推薦的
其實第三天小林當我們隨車導遊時就力薦我們好吃的尤魚絲片
(真的是好吃呀~吃起來脆脆有點辣辣的,跟在台灣吃到的尤魚絲很不一樣)
聽說每天都有限量,一般名產店買不到所以早先就跟小林訂了六盒了
等第五天要回程時再到這家名產店來拿

除了跟小林訂的尤魚片外我們也在這裡買了一些有的沒的
像月亮蝦餅、椰子糖之類的,峇里島的糖果都滿特別好吃的~
最後打包也是滿滿的一箱

最後一站就是今天的午餐,這也是網路上大推的
好吃的酥骨雞,不只皮,連肉也是酥酥脆脆的,炒青菜跟椰奶也是一級棒
它的椰奶跟台灣的不一樣,奶味比較重也比較甜一點,好喝!
(覺得來峇里島吃過特好吃的就第一天金巴蘭的海鮮、
第三天烏布的豬肋排、還有就是第五天庫塔的酥骨雞了)



吃完好吃的酥骨雞就心滿意足的出發到機場準備回家囉
這次準備了三萬台幣全都花光光了,最後到機場還多塞了一些小費給小林
果然出國都容易亂花錢呀@@~回到家後攤開戰利品才發現買了還真不少捏


心得:
其實這次的峇里島有些行程還可以再改進一下
第三天烏布的行程太密集了應該要悠閒一點
出國的迷思就是會想多踩一些點
但是其實出國就是要放鬆的咩~行程沒必要排太滿

另外就是號稱米其林三星的mozaic有點被唬弄的感覺
一人份要二千多台幣,但是其實應該沒那個價值
還有SPA的部份應該盡量找些市區獨立經營俗又大碗的
飯店內的SPA都貴森森呀~
感覺在整體費用上還可以在省一點的~
基本上五天四夜的行程,一個人三萬五就很剛好囉了~

2010年5月30日 星期日

[Web Service]-NetBeans開發Web Service

Getting Started with JAX-WS Web Services
                                                          from NetBeans Web Service tutorials
Java API for XML Web Services (JAX-WS) 2.0/2.1, JSR 224, is an important part of the Java EE 5 platform. A follow-up to the release of Java API for XML-based RPC 1.1(JAX-RPC), JAX-WS simplifies the task of developing web services using Java technology. It addresses some of the issues in JAX-RPC 1.1 by providing support for multiple protocols such as SOAP 1.1, SOAP 1.2, XML, and by providing a facility for supporting additional protocols along with HTTP. JAX-WS uses JAXB 2.0 for data binding and supports customizations to control generated service endpoint interfaces. With its support for annotations, JAX-WS simplifies web service development and reduces the size of runtime JAR files.

Creating a Web Service
Choosing a Container
You can either deploy your web service in a web container or in an EJB container. This depends on your choice of implementation. If you are creating a Java EE 6 application, use a web container in any case, because you can put EJBs directly in a web application. For example, if you plan to deploy to the Tomcat Web Server, which only has a web container, create a web application, not an EJB module.
  1. Choose File > New Project (Ctrl-Shift-N). Select Web Application from the Java Web category or EJB Module from the Java EE category.
  2. Name the project CalculatorWSApplication.
  3. Click through the remaining pages and click Finish.
Creating a Web Service from a Java Class
  1. Right-click the CalculatorWSApplication node and choose New > Web Service.
  2. Name the web service CalculatorWS and type org.me.calculator in Package.
  3. If you are creating a Java EE 6 project, leave Create Web Service from Scratch selected, and select Implement Web Service as a Stateless Session Bean.
  4. Click Finish. The Projects window displays the structure of the new web service and the source code is shown in the editor area.
Designing the Web Service
Adding an Operation to the Web Service
  1. Change to the Design view. (Note: The Preview view in NetBeans 6.5.1 is disabled.)
  2. Click Add Operation in the visual designer. A dialog box appears where you can define the new operation.
  3. In the upper part of the Add Operation dialog box, type add in Name and type int in the Return Type drop-down list. In the lower part of the Add Operation dialog box, click Add and create a parameter of type int named i. Then click Add again and create a parameter of type int called j. You now see the following:
  4. Click OK at the bottom of the Add Operation dialog box. The visual designer now displays the following:
  5. Click Source and view the code that you generated in the previous steps. It differs whether you created the service as an EE6 stateless bean or not. Can you see the difference in the screenshots below?
  6. In the editor, extend the skeleton add operation to the following (changes are in bold):
@WebMethod
public int add(@WebParam(name = "i") int i, 
@WebParam(name = "j") int j) {
int k = i + j;
return k;
} 
Deploying and Testing the Web Service
To test successful deployment to a web container:
  1. Right-click the project and choose Deploy. The IDE starts the application server, builds the application, and deploys the application to the server. You can follow the progress of these operations in the CalculatorWSApplication (run-deploy) and GlassFish or Tomcat tabs in the Output view.
  2. If you deployed to the Tomcat Web Server, you will see the following instead, which indicates that you have successfully deployed your web service:

Consuming the Web Service
Client : Java Class in Java SE Application
  1. Choose File > New Project (Ctrl-Shift-N). Select Java Application from the Java category. Name the project CalculatorWS_Client_Application. Leave Create Main Class selected and accept all other default settings. Click Finish.
  2. Right-click the CalculatorWS_Client_Application node and choose New > Web Service Client.
  3. In Project, click Browse. Browse to the web service that you want to consume. When you have selected the web service, click OK.
  4. Leave the other settings at default and click Finish. The Projects window displays the new web service client, with a node for the add method that you created:
  5. Double-click Main.java so that it opens in the Source Editor. Delete the TODO comment and then drag the add node above into the empty line. You now see the following:
public static void main(String[] args) {
try {
// Call Web Service Operation
org.me.calculator.CalculatorWSService service = 
new org.me.calculator.CalculatorWSService();
org.me.calculator.CalculatorWS port = 
service.getCalculatorWSPort();
// TODO initialize WS operation arguments here
int i = 0;
int j = 0;
// TODO process result here
int result = port.add(i, j);
System.out.println("Result = "+result);
} catch (Exception ex) {
// TODO handle custom exceptions here
}
}

2010年5月29日 星期六

[Web Service]-淺談Web Service

Introduction to Web Services
                                                                      from NetBeans Web Service tutorials
Web services are distributed application components that are externally available. You can use them to integrate computer applications that are written in different languages and run on different platforms. Web services are language and platform independent because vendors have agreed on common web service standards.
Several programing models are available to web service developers. These models fall into two categories, both supported by the IDE:
  • REST-based. REpresentational State Transfer is a new way to create and communicate with web services. In REST, resources have URIs and are manipulated through HTTP header operations.
  • SOAP/WSDL-based. In traditional web service models, web service interfaces are exposed through WSDL documents (a type of XML), which have URLs. Subsequent message exchange is in SOAP, another type of XML document.
RESTful Web Services
REST-based ("RESTful") web services are collections of web resources identified by URIs. Every document and every process is modeled as a web resource with a unique URI. These web resources are manipulated by the actions that can be specified in an HTTP header. Neither SOAP, nor WSDL, nor WS-* standards are used. Instead, message exchange can be conducted in any format—XML, JSON, HTML, etc. In many cases a web browser can serve as the client.

HTTP is the protocol in REST. Only four methods are available: GET, PUT, POST, and DELETE. Requests can be bookmarked and responses can be cached. A network administrator can easily follow what is going on with a RESTful service just by looking at the HTTP headers.

REST is a suitable technology for applications that do not require security beyond what is available in the HTTP infrastructure and where HTTP is the appropriate protocol. REST services can still deliver sophisticated functionality. Flickr, Google Maps and Amazon all provide RESTful web services. NetBeans IDE Software as a Service (SaaS) functionality lets you use Facebook, Zillow, and other third-party-provided services in your own applications.

SOAP-based Web Services
In SOAP-based web services, Java utilites create a WSDL file based on the Java code in the web service. The WSDL is exposed on the net. Parties interested in using the web service create a Java client based on the WSDL. Messages are exchanged in SOAP format. The range of operations that can be passed in SOAP is much broader than what is available in REST, especially in security.

SOAP-based web services are suitable for heavyweight applications using complicated operations and for applications requiring sophisticated security, reliability or other WS-* standards-supported features. They are also suitable when a transport protocol other than HTTP has to be used. Many of Amazon's web services, particularly those involving commercial transactions, and the web services used by banks and government agencies are SOAP-based.

The Java API for XML Web Services (JAX-WS) is the current model for SOAP-based web services in Metro. JAX-WS is built on the earlier JAX-RPC model but uses specific Java EE 5 features, such as annotations, to simplify the task of developing web services. Because it uses SOAP for messaging, JAX-WS is transport neutral. It also supports a wide range of modular WS-* specifications, such as WS-Security and WS-ReliableMessaging.