星期日, 8月 20, 2006

NetBeans Java 6(aka Mustang)備忘記

以下為 Java SE 6 的目標:
提高兼容性及穩定性
增強診斷,監察及管理能力
提高開發效率
Enterprise desktop
XML and web services
Transparency


以下為 Java SE 6 新特性:
‧ JSR 105: XML Digital Signature
‧ JSR 173: Streaming API for XML
‧ JSR 181: Web Services Metadata
‧ JSR 199: Java Compiler API
‧ JSR 202: Java Class File Specification Update
‧ JSR 221: JDBC 4.0
‧ JSR 222: JAXB 2.0
‧ JSR 223: Scripting for the Java Platform
‧ JSR 224: Java API for XML-Based Web Services (JAX-WS) 2.0
‧ JSR 250: Common Annotations
‧ JSR 269: Pluggable Annotation Processing API


官方網 Java SE 6 新特性:
http://java.sun.com/javase/6/webnotes/features.html
http://java.sun.com/javase/6/webnotes/compatibility.html


本備忘記主要介紹使用 NetBeans 實作一些本人感興趣的 Java SE 6 新特性.


開始備忘記:
[1]
安裝 Java SE 6
[2] 測試 Java 6 Scripting
[3] 安裝 NetBeans IDE 5.0
[4] 建立第一個 NetBeans web project
[5] NetBeans 建立 Java 6 project (Scripting and JSR 223)
[6] NetBeans 建立 Java 6 project (Java Compiler API)
[7] NetBeans 建立 Java 6 project (web service)
[8] NetBeans 建立 Java 6 project (XML)
[9] NetBeans 建立 Java 6 project (Other)
[10] NetBeans 常用 Hot-Key


[1] 安裝 Java SE 6:
下載 jdk-6-beta2-windows-i586.exe
http://java.sun.com/javase/downloads/ea.jsp
http://192.18.108.229/ECom/EComTicketServlet/BEGIN8806B36D55D38D5324C7FB81ED8D1453/-2147483648/1629557847/1/737498/737330/1629557847/2ts+/westCoastFSEND/jdk-6-beta2-oth-JPR/jdk-6-beta2-oth-JPR:3/jdk-6-beta2-windows-i586.exe


雙擊 jdk-6-beta2-windows-i586.exe 進行安裝
選擇安裝目錄至 D:\jdk1.6.0\
如下圖所示


以下是官方 Java SE 6 安裝教學:
http://java.sun.com/javase/6/webnotes/install/jdk/install-windows.html
http://java.sun.com/javase/6/webnotes/install/index.html



[2] 測試 Java 6 Scripting:
進入目錄 D:\jdk1.6.0\bin
執行指令 D:\jdk1.6.0\bin>jrunscript -? 顯示指令資料


執行指令 D:\jdk1.6.0\bin>jrunscript -q 顯示 support 的 scripting engine
輸出為
Language ECMAScript 1.6 implemention "Mozilla Rhino" 1.6 release 2


執行指令 D:\jdk1.6.0\bin>jrunscript
輸入 js> var output = "Hello World";
輸入 js> println(output);
輸出為
Hello World


輸出如下圖所示



[3] 安裝 NetBeans IDE 5.0:
下載 netbeans-5_0-windows.exe
http://www.netbeans.info/downloads/download.php
http://us1.mirror.netbeans.org/download/5_0/fcs/200601251500/netbeans-5_0-windows.exe


雙擊 netbeans-5_0-windows.exe 進行安裝
安裝目錄 Directory Name: D:\netbeans-5.0
如下圖所示


J2SE JDK Home Directory: D:\jdk1.6.0
如下圖所示


啟動 NetBeans 後
NetBeans: Tools -> Server Manager
如下圖所示

NetBeans 內置了 tomcat
NetBeans 內置 tomcat 目錄 D:\netbeans-5.0\enterprise2\jakarta-tomcat-5.5.9


亦可以在上圖裡按 "Add Server..." 增加以下 application server
BEA WebLogic Application Server 9.0
JBoss Application Server 4.0.3
Sun Java System Application Server
Tomcat 5.0
Tomcat 5.5



[4] 建立第一個 NetBeans web project:
NetBeans: File -> New Project
Choose Project 如下圖所示

Project Name 為 MyFirstWebApplication
Name and Location 如下圖所示

Frameworks 如下圖所示


項目目錄結構如下所示


右鍵點選 MyFirstWebApplication -> Run Project
NetBeans 會自動啟動 tomcat 及 deploy project, 並自動開啟預設的 browser
啟動後 tomcat console 如下圖所示

browser 如下圖所示


在 NetBeans 裡其中幾種功能本人覺得不錯.
當把 panel 縮成最小時, MouseOver 會自動跳出.


NetBeans: Views -> Toolbars -> Memory
這功能可以看到 Memory 使用的情況, 點擊它就會強迫 garbage collection


NetBeans: Window -> HTTP Monitor
這功能可以檢視 HTTP 相關資料


這些功能如下圖所示



[5] NetBeans 建立 Java 6 project (Scripting and JSR 223):
NetBeans: File -> New Project -> General -> Java Application
Project Name: ScriptingTest
然後按 "Finish"


建立 JavascriptTest.java
/*----------------- JavascriptTest.java -----------------------------*/
package scriptingtest;


import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;


public class JavascriptTest {
public JavascriptTest() {
}


public static void main(String args[]) {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("javascript");
// 取得 javascript engine
try {
engine.put("hello", "Hello"); // 定義 javascript hello variable
engine.eval(
"var world = 'World';" +
"function sayHello(){" +
" return hello + ' ' + world;" +
"}");
String world = (String)engine.get("world"); // 取得 javascript world variable
System.out.printf("print world: %s%n", world);

Invocable invokeEngine = (Invocable)engine;
Object o = invokeEngine.invoke("sayHello"); // 呼叫 javascript sayHello function
System.out.printf("print sayHello() output: %s%n", o);

} catch (NoSuchMethodException e){
System.err.println(e);
} catch (ScriptException e) {
System.err.println(e);
}
}

}
/*----------------- JavascriptTest.java -----------------------------*/


右鍵點選 JavascriptTest.java -> Run File 或按 Shift + F6
Console 輸出結果為
init:
deps-jar:
compile-single:
run-single:
print world: World
print sayHello() output: Hello World
BUILD SUCCESSFUL (total time: 0 seconds)


項目結構及 Console 輸出如下所示



[6] NetBeans 建立 Java 6 project (Java Compiler API):
NetBeans: File -> New Project -> General -> Java Application
Project Name: CompilerAPITest
然後按 "Finish"


建立 CompilerAPITest.java
/*----------------- CompilerAPITest.java -----------------------------*/
package compilerapitest;


import javax.tools.JavaCompilerTool;
import javax.tools.ToolProvider;


public class CompilerAPITest {
public static void main(String[] args) {
JavaCompilerTool compiler = ToolProvider.getSystemJavaCompilerTool();
// 取得編譯器
int results = compiler.run(null, null, null, "src/compilerapitest/Test.java");
// 編譯 src/compilerapitest/Test.java
System.out.println("Result: " + (results == 0));
// results 為 0 即表示編譯成功
}
}
/*----------------- CompilerAPITest.java -----------------------------*/


建立 Test.java
/*----------------- Test.java -----------------------------*/
package compilerapitest;
public class Test {
public static void main(String args[]){
System.out.println("Hello World, Joeyta");
}
}
/*----------------- Test.java -----------------------------*/


右鍵點選 JavascriptTest.java -> Run File 或按 Shift + F6
Console 輸出結果為
init:
deps-jar:
Compiling 1 source file to C:\Documents and Settings\joey.chan\CompilerAPITest\build\classes
compile-single:
run-single:
Result: true
BUILD SUCCESSFUL (total time: 1 second)


項目結構及 Console 輸出如下所示



[7] NetBeans 建立 Java 6 project (web service):
NetBeans: File -> New Project -> General -> Java Application
Project Name: WebServiceTest
然後按 "Finish"


建立 GoogleSearchTest.java
/*----------------- GoogleSearchTest.java -----------------------------*/
package webservicetest;


import java.io.*;
import java.net.*;
import javax.xml.ws.*;
import javax.xml.namespace.*;
import javax.xml.soap.*;
public class GoogleSearchTest {
public static void main(String args[]) throws Exception {
URL url = new URL("
http://api.google.com/GoogleSearch.wsdl");
QName serviceName = new QName("urn:GoogleSearch", "GoogleSearchService");
QName portName = new QName("urn:GoogleSearch", "GoogleSearchPort");
Service service = Service.create(url, serviceName);
Dispatch<SOAPMessage> dispatch = service.createDispatch(portName,
SOAPMessage.class, Service.Mode.MESSAGE);

InputStream soapRequestIS = new ByteArrayInputStream("blah blah".getBytes());
SOAPMessage request = MessageFactory.newInstance().createMessage(
null, soapRequestIS);
SOAPMessage response = dispatch.invoke(request);
response.writeTo(System.out);
}
}
/*----------------- GoogleSearchTest.java -----------------------------*/


右鍵點選 GoogleSearchTest.java -> Run File 或按 Shift + F6
由於只是測試, 能夠取回 Soap response message 即代表測試成功.
因此 soapRequestIS 的內容隨便輸入為 "blah blah"
如果真的要實作, 這裡的 soapRequestIS 應該是 Soap request message
因此取得的 Soap response message 會出現 org.xml.sax.SAXParseException


Console 輸出為
init:
deps-jar:
Compiling 1 source file to C:\Documents and Settings\joey.chan\WebServiceTest\build\classes
compile-single:
run-single:
<?xml version='1.0' encoding='UTF-8'?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="
http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/1999/XMLSchema-instance" xmlns:xsd="http://www.w3.org/1999/XMLSchema">
<SOAP-ENV:Body>
<SOAP-ENV:Fault>
<faultcode>SOAP-ENV:Client</faultcode>
<faultstring>parsing error: org.xml.sax.SAXParseException: Content is not allowed in prolog.</faultstring>
<faultactor>/search/beta2</faultactor>
</SOAP-ENV:Fault>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
BUILD SUCCESSFUL (total time: 1 second)


項目結構及 Console 輸出如下所示



[8] NetBeans 建立 Java 6 project (XML):
NetBeans: File -> New Project -> General -> Java Application
Project Name: XMLTest
然後按 "Finish"


建立 AccountXMLTest.java
/*----------------- AccountXMLTest.java -----------------------------*/
package xmltest;


import javax.xml.bind.*;
import javax.xml.bind.annotation.*;
public class AccountXMLTest {
public static void main(String[] args) {
try {
JAXBContext context = JAXBContext.newInstance(Account.class);
Marshaller m = context.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
Account p = new Account("joeyta", 18);
m.marshal(p, System.out);
} catch (JAXBException jex) {
System.out.println("JAXB Binding Exception");
jex.printStackTrace();
}
}
@XmlRootElement // 標記 Account class 為 root element
private static class Account {
String name;
int age;
public Account() {
}
public Account(String name, int age) {
this.name = name;
this.age = age;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
}
/*----------------- AccountXMLTest.java -----------------------------*/


右鍵點選 AccountXMLTest.java -> Run File 或按 Shift + F6
Console 輸出為
init:
deps-jar:
Compiling 1 source file to C:\Documents and Settings\joey.chan\XMLTest\build\classes
compile-single:
run-single:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<account>
<age>18</age>
<name>joeyta</name>
</account>

BUILD SUCCESSFUL (total time: 1 second)


項目結構及 Console 輸出如下所示



[9] NetBeans 建立 Java 6 project (Other):
NetBeans: File -> New Project -> General -> Java Application
Project Name: OtherTest
然後按 "Finish"


建立 VolumeTest.java
/*----------------- VolumeTest.java -----------------------------*/
package othertest;


import java.io.*;
import java.net.URL;
public class VolumeTest {
public static void main(String args[]) throws Exception {
File roots[] = File.listRoots();
for (File root: roots) {
System.out.printf("%s has %,d of %,d free%n", root.getPath(),
root.getUsableSpace(), root.getTotalSpace());
}

File file = new File("test");
URL url1 = file.toURL();
URL url2 = file.toURI().toURL();
System.out.printf("Old url %s%n", url1);
System.out.printf("New url %s%n", url2);
}
}
/*----------------- VolumeTest.java -----------------------------*/


右鍵點選 VolumeTest.java -> Run File 或按 Shift + F6
Console 輸出為
init:
deps-jar:
Compiling 1 source file to C:\Documents and Settings\joeyta\OtherTest\build\classes
Note: C:\Documents and Settings\joeyta\OtherTest\src\othertest\VolumeTest.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
compile-single:
run-single:
A:\ has 0 of 0 free
C:\ has 739,835,904 of 10,487,197,696 free
D:\ has 244,649,984 of 29,504,077,824 free
E:\ has 0 of 37,828,608 free
F:\ has 167,845,888 of 8,391,688,192 free
G:\ has 167,845,888 of 8,391,688,192 free
H:\ has 167,845,888 of 8,391,688,192 free
K:\ has 792,875,008 of 838,860,800 free
S:\ has 792,875,008 of 838,860,800 free
U:\ has 245,153,792 of 838,860,800 free
X:\ has 60,586,983,424 of 146,804,764,672 free
Old url file:/C:/Documents and Settings/joeyta/OtherTest/test/
New url file:/C:/Documents%20and%20Settings/joeyta/OtherTest/test/
BUILD SUCCESSFUL (total time: 1 second)



建立 VolumeTest.java
/*----------------- DesktopTest.java -----------------------------*/
package othertest;


import java.awt.*;
import java.io.*;
public class DesktopTest {
public static void main(String args[]) {
if (Desktop.isDesktopSupported()) {
Desktop desktop = Desktop.getDesktop();
File dir = new File("."); // 開啟 project 下的所有檔案
File files[] = dir.listFiles();
for (File file: files) {
if (desktop.isSupported(Desktop.Action.OPEN)) {
System.out.println("Opening... " + file.getName());
try {
desktop.open(file);
} catch (IOException ioe) {
System.err.println("Unable to open: " + file.getName());
}
}
}
}
}
}
/*----------------- DesktopTest.java -----------------------------*/


右鍵點選 DesktopTest.java -> Run File 或按 Shift + F6
桌面上便會開啟所有在項目目錄下的檔案.


[10] NetBeans 常用 Hot-Key:
Ctrl + Shift + F
 : Reformat Code (與 eclipse 一樣)
Ctrl + G : Go to Line (與 eclipse 一樣)
Alt + Shift + R : rename (與 eclipse 一樣)
Alt + Shift + F : Fix Imports
Alt + Shift + O : Go to Class
Alt + Shift + W : Surround With try-catch
Alt + O : Go to Source
Ctrl + B : Go to Super Implementation
Alt + F7 : Find Usages
Ctrl + F : Find
Ctrl + H : Replace
Ctrl + Shift + P : Find in projects
Ctrl + Shift + T : Comment
Ctrl + Shift + D : Uncomment
Ctrl + Shift + 1 : Select in project
Ctrl + F3 : Find Selection
Shift + F3 : Find Previous
F3 : Find Next


Java 6 官方文檔:
http://java.sun.com/javase/6/docs/
http://java.sun.com/javase/6/docs/api/index.html


NetBeans j2ee 教學:
http://www.netbeans.org/download/docs/41/j2ee-tutorial/index.html


這裡測試了 NetBeans 5.0
http://www.netbeans.org/community/releases/50/
可選擇測試 NetBeans 5.5 Beta 2
http://www.netbeans.org/community/releases/55/
http://www.netbeans.org/community/releases/55/install.html

JDK 7 Project
https://jdk7.dev.java.net/


沒有留言: