2011年9月20日 星期二

三級憤怒 - jAG301

import java.util.*;
class Test301{
 public static void main(String[]args){
Scanner stdin=new Scanner(System.in);
  int num;
  do{
      System.out.print("How many strings?");
      num=stdin.nextInt();
  }while(num<1);
String x[]=new String[num];
  for(int i=0;i<x.length;++i){
      System.out.print("["+i+"]=");
      x[i]=stdin.nextLine();
  }
 }
}
 
上面程式可以執行, 可是會跳過 x[0]=stdin.nextLine() 輸入 ?

2011年8月16日 星期二

private final 方法可以被覆蓋 (Override)

A 類別程式中, f() 及 g() 這二個方法, 因宣告為 private, 在繼承的關係中是不會被繼承, 所以根本沒覆蓋的討論, 下面程式範例, 編譯會過, 既使 B 類別程式中有相同宣告的 f() 及 g() 這二個方法

class A {

   // Identical to "private" alone:
   private final void f() {
     System.out.println("A.f()");
   }

   // Also automatically "final":
   private void g() {
     System.out.println("A.g()");
   }
}


class B extends A {
   private final void f() {
     System.out.println("B.f()");
   }

   private void g() {
     System.out.println("B.g()");
   }
}

在繼承關係中, 變數是沒有覆蓋 (Override) 的討論, 而是以 shadow 來討論, 以下範例程式, 編譯是會通過, 因沒有覆蓋討論, I 介面中的變數 KEY 既使宣告 final, A 類別一樣可以宣告同名的變數 KEY.

public interface I {
    public final String KEY = "a";
}

public class A implements I {
   public String KEY = "b";

   public String getKey() {
      return KEY;
   }
}

參考文章
1. Why can final constants in Java beoverriden ?
http://stackoverflow.com/questions/205239/why-can-final-constants-in-java-be-overriden

2011年8月6日 星期六

Apache Maven 專案管理平台 - WAR 專案加入 Servlet

初設 AServlet 專案

$ mvn archetype:create -DgroupId=kvm.servlet -DartifactId=AServlet -DarchetypeArtifactId=maven-archetype-webapp

AServlet 專案目錄結構
$ tree AServlet/
AServlet/
|-- pom.xml
`-- src
`-- main
|-- resources
`-- webapp
|-- WEB-INF
| `-- web.xml
`-- index.jsp

5 directories, 3 files

產生 kvm.servlet 套件目錄

$ mkdir -p AServlet/src/main/java/kvm/servlet

撰寫 SimpleServlet.java 程式

$ nano AServlet/src/main/java/kvm/servlet/SimpleServlet.java
package kvm.servlet;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class SimpleServlet extends HttpServlet {
   public void doGet(HttpServletRequest request, 
                               HttpServletResponse response)
                               throws ServletException, IOException {
      PrintWriter out = response.getWriter();
      out.println( "SimpleServlet Executed" );
      out.flush();
      out.close();
   }
}

修改 AServlet 網站專案設定檔 - web.xml

$ nano AServlet/src/main/webapp/WEB-INF/web.xml

<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
    <display-name>Archetype Created Web Application</display-name>
    <servlet>
       <servlet-name>simple</servlet-name>
       <servlet-class>kvm.servlet.SimpleServlet</servlet-class>
    </servlet>
    <servlet-mapping>
       <servlet-name>simple</servlet-name>
       <url-pattern>/simple</url-pattern>
    </servlet-mapping>
</web-app>


第一次編譯 Servlet 程式
$ cd AServlet/
$ mvn compile
                                  :
[ERROR] /mnt/hda1/AServlet/src/main/java/kvm/servlet/SimpleServlet.java:[5,0] error: package javax.servlet.http does not exist
[ERROR] /mnt/hda1/AServlet/src/main/java/kvm/servlet/SimpleServlet.java:[7,35] error: cannot find symbol
[ERROR] class HttpServlet
[ERROR] /mnt/hda1/AServlet/src/main/java/kvm/servlet/SimpleServlet.java:[8,22] error: cannot find symbol
[ERROR] class SimpleServlet
[ERROR] /mnt/hda1/AServlet/src/main/java/kvm/servlet/SimpleServlet.java:[8,50] error: cannot find symbol
[ERROR] class SimpleServlet
[ERROR] /mnt/hda1/AServlet/src/main/java/kvm/servlet/SimpleServlet.java:[9,41] error: cannot find symbol
[ERROR] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException

修改 pom.xml 設定檔

$ nano pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/maven-v4_0_0.xsd">

   <modelVersion>4.0.0</modelVersion>
   <groupId>kvm.servlet</groupId>
   <artifactId>AServlet</artifactId>
   <packaging>war</packaging>
   <version>1.0-SNAPSHOT</version>
   <name>AServlet Maven Webapp</name>
   <url>http://maven.apache.org</url>
   <dependencies>
      <dependency>
         <groupId>junit</groupId>
         <artifactId>junit</artifactId>
         <version>3.8.1</version>
         <scope>test</scope>
      </dependency>

      <dependency>
         <groupId>javax.servlet</groupId>
         <artifactId>servlet-api</artifactId>
         <version>2.4</version>
         <scope>provided</scope>
      </dependency>

   </dependencies>
   <build>
      <finalName>AServlet</finalName>
    </build>
</project>

再次編譯 servlet 程式
$ mvn compile
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building AServlet Maven Webapp 1.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
Downloading: http://repo1.maven.org/maven2/javax/servlet/servlet-api/2.4/servlet-api-2.4.pom
Downloaded: http://repo1.maven.org/maven2/javax/servlet/servlet-api/2.4/servlet-api-2.4.pom (156 B at 0.0 KB/sec)
Downloading: http://repo1.maven.org/maven2/javax/servlet/servlet-api/2.4/servlet-api-2.4.jar
Downloaded: http://repo1.maven.org/maven2/javax/servlet/servlet-api/2.4/servlet-api-2.4.jar (96 KB at 36.1 KB/sec)
[INFO]
[INFO] --- maven-resources-plugin:2.4.3:resources (default-resources) @ AServlet ---
[WARNING] Using platform encoding (ANSI_X3.4-1968 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] Copying 0 resource
[INFO]
[INFO] --- maven-compiler-plugin:2.3.2:compile (default-compile) @ AServlet ---
[WARNING] File encoding has not been set, using platform encoding ANSI_X3.4-1968, i.e. build is platform dependent!
[INFO] Compiling 1 source file to /mnt/hda1/AServlet/target/classes
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 8.557s
[INFO] Finished at: Sun Aug 07 09:25:48 UTC 2011
[INFO] Final Memory: 6M/17M
[INFO] ------------------------------------------------------------------------

製作 AServlet 專案檔

$ mvn package

上載 AServlet 專案檔至 Tomcat
$ cp target/AServlet.war /mnt/hda1/apache-tomcat-7.0.19/webapps/

SimpleServlet 程式測試
$ curl http://localhost:8080/AServlet/simple
SimpleServlet Executed

Apache Maven 專案管理平台 - WAR 專案加入 JSP

初設 AJSP 專案

$ mvn archetype:create -DgroupId=kvm.jsp -DartifactId=AJSP
 -DarchetypeArtifactId=maven-archetype-webapp


Counter.java 資料物件設計

1.  建立 foo 套件目錄
$ mkdir -p AJSP/src/main/java/foo

2. 撰寫 Counter.java 程式

$ nano AJSP/src/main/java/foo/Counter.java
package foo;
public class Counter {
  private static int count;
  public static synchronized int getCount() {
     count++;
     return count;
  }
}


撰寫 MyJSP01.jsp 
$ nano AJSP/src/main/webapp/MyJSP01.jsp
<html>
<body>
The Page count is :
<%
  out.println(foo.Counter.getCount());
%>
</body>
</html>

製作 AJSP 專案檔 (AJSP.war)
$ cd AJSP
$ mvn package
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building AJSP Maven Webapp 1.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-resources-plugin:2.4.3:resources (default-resources) @ AJSP ---
[WARNING] Using platform encoding (ANSI_X3.4-1968 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] Copying 0 resource
[INFO]
[INFO] --- maven-compiler-plugin:2.3.2:compile (default-compile) @ AJSP ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-resources-plugin:2.4.3:testResources (default-testResources) @ AJSP ---
[WARNING] Using platform encoding (ANSI_X3.4-1968 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] skip non existing resourceDirectory /mnt/hda1/AJSP/src/test/resources
[INFO]
[INFO] --- maven-compiler-plugin:2.3.2:testCompile (default-testCompile) @ AJSP ---
[INFO] No sources to compile
[INFO]
[INFO] --- maven-surefire-plugin:2.7.2:test (default-test) @ AJSP ---
[INFO] No tests to run.
[INFO] Surefire report directory: /mnt/hda1/AJSP/target/surefire-reports

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
There are no tests to run.

Results :

Tests run: 0, Failures: 0, Errors: 0, Skipped: 0

[INFO]
[INFO] --- maven-war-plugin:2.1.1:war (default-war) @ AJSP ---
[INFO] Packaging webapp
[INFO] Assembling webapp [AJSP] in [/mnt/hda1/AJSP/target/AJSP]
[INFO] Processing war project
[INFO] Copying webapp resources [/mnt/hda1/AJSP/src/main/webapp]
[INFO] Webapp assembled in [78 msecs]
[INFO] Building war: /mnt/hda1/AJSP/target/AJSP.war
[INFO] WEB-INF/web.xml already added, skipping
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 3.804s
[INFO] Finished at: Sun Aug 07 10:00:12 UTC 2011
[INFO] Final Memory: 5M/13M
[INFO] ------------------------------------------------------------------------

檢視 AJSP 專案檔製作後, AJSP 的目錄結構
$ tree .
.
|-- pom.xml
|-- src
|   `-- main
|       |-- java
|       |   `-- foo
|       |       `-- Counter.java
|       |-- resources
|       `-- webapp
|           |-- MyJSP01.jsp
|           |-- WEB-INF
|           |   `-- web.xml
|           `-- index.jsp
`-- target
    |-- AJSP
    |   |-- META-INF
    |   |-- MyJSP01.jsp
    |   |-- WEB-INF
    |   |   |-- classes
    |   |   |   `-- foo
    |   |   |       `-- Counter.class
    |   |   `-- web.xml
    |   `-- index.jsp
    |-- AJSP.war
    |-- classes
    |   `-- foo
    |       `-- Counter.class
    |-- maven-archiver
    |   `-- pom.properties
    `-- surefire

17 directories, 12 files

佈署 AJSP 專案至 Tomcat

$ cp target/AJSP.war /mnt/hda1/apache-tomcat-7.0.19/webapps/

啟動 Tomcat
$ /mnt/hda1/apache-tomcat-7.0.19/bin/startup.sh &
[1] 1321
Using CATALINA_BASE: /mnt/hda1/apache-tomcat-7.0.19
Using CATALINA_HOME: /mnt/hda1/apache-tomcat-7.0.19
Using CATALINA_TMPDIR: /mnt/hda1/apache-tomcat-7.0.19/temp
Using JRE_HOME: /mnt/hda1/jdk1.7.0
Using CLASSPATH: /mnt/hda1/apache-tomcat-7.0.19/bin/bootstrap.jar:/mnt/hda1/apache-tomcat-7.0.19/bin/tomcat-juli.jar

執行 MyJSP01.jsp
$ curl http://localhost:8080/AJSP/MyJSP01.jsp
<html>
<body>
The Page count is :
1
</body>
</html>

Apache Maven 專案管理平台 - WAR 專案建立與執行

1. 初設 AAAWebapp 專案

$ mvn  archetype:create  -DgroupId=kvm.aaa  -DartifactId=AAAWebapp  -DarchetypeArtifactId=maven-archetype-webapp
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building Maven Stub Project (No POM) 1
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-archetype-plugin:2.0:create (default-cli) @ standalone-pom ---
[WARNING] This goal is deprecated. Please use mvn archetype:generate instead
[INFO] Defaulting package to group ID: kvm.aaa
Downloading: http://repo1.maven.org/maven2/org/apache/maven/archetypes/maven-archetype-webapp/maven-metadata.xml
Downloaded: http://repo1.maven.org/maven2/org/apache/maven/archetypes/maven-archetype-webapp/maven-metadata.xml (498 B at 0.3 KB/sec)
[INFO] ----------------------------------------------------------------------------
[INFO] Using following parameters for creating project from Old (1.x) Archetype: maven-archetype-webapp:RELEASE
[INFO] ----------------------------------------------------------------------------
[INFO] Parameter: groupId, Value: kvm.aaa
[INFO] Parameter: packageName, Value: kvm.aaa
[INFO] Parameter: package, Value: kvm.aaa
[INFO] Parameter: artifactId, Value: AAAWebapp
[INFO] Parameter: basedir, Value: /mnt/hda1
[INFO] Parameter: version, Value: 1.0-SNAPSHOT
[INFO] ********************* End of debug info from resources from generated POM ***********************
[INFO] project created from Old (1.x) Archetype in dir: /mnt/hda1/AAAWebapp
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 6.480s
[INFO] Finished at: Sat Aug 06 18:06:32 UTC 2011
[INFO] Final Memory: 7M/18M
[INFO] ------------------------------------------------------------------------

2. AAAWebapp 專案目錄結構

$  tree AAAWebapp/
AAAWebapp/
|-- pom.xml
`-- src
    `-- main
        |-- resources
        `-- webapp
            |-- WEB-INF
            |   `-- web.xml
            `-- index.jsp

5 directories, 3 files

3. 產生 WAR 專案檔

$ cd AAAWebapp/

$ mvn package
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building AAAWebapp Maven Webapp 1.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-resources-plugin:2.4.3:resources (default-resources) @ AAAWebapp ---
[WARNING] Using platform encoding (ANSI_X3.4-1968 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] Copying 0 resource
[INFO]
[INFO] --- maven-compiler-plugin:2.3.2:compile (default-compile) @ AAAWebapp ---
[INFO] No sources to compile
[INFO]
[INFO] --- maven-resources-plugin:2.4.3:testResources (default-testResources) @ AAAWebapp ---
[WARNING] Using platform encoding (ANSI_X3.4-1968 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] skip non existing resourceDirectory /mnt/hda1/AAAWebapp/src/test/resources
[INFO]
[INFO] --- maven-compiler-plugin:2.3.2:testCompile (default-testCompile) @ AAAWebapp ---
[INFO] No sources to compile
[INFO]
[INFO] --- maven-surefire-plugin:2.7.2:test (default-test) @ AAAWebapp ---
[INFO] No tests to run.
[INFO] Surefire report directory: /mnt/hda1/AAAWebapp/target/surefire-reports

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
There are no tests to run.

Results :

Tests run: 0, Failures: 0, Errors: 0, Skipped: 0

[INFO]
[INFO] --- maven-war-plugin:2.1.1:war (default-war) @ AAAWebapp ---
[INFO] Packaging webapp
[INFO] Assembling webapp [AAAWebapp] in [/mnt/hda1/AAAWebapp/target/AAAWebapp]
[INFO] Processing war project
[INFO] Copying webapp resources [/mnt/hda1/AAAWebapp/src/main/webapp]
[INFO] Webapp assembled in [75 msecs]
[INFO] Building war: /mnt/hda1/AAAWebapp/target/AAAWebapp.war
[INFO] WEB-INF/web.xml already added, skipping
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 5.140s
[INFO] Finished at: Sat Aug 06 18:12:20 UTC 2011
[INFO] Final Memory: 5M/12M
[INFO] ------------------------------------------------------------------------

4. 佈署 AAAWebapp 專案

$ cp target/AAAWebapp.war /mnt/hda1/apache-tomcat-7.0.19/webapps/

5. 啟動 Tomcat
$ /mnt/hda1/apache-tomcat-7.0.19/bin/startup.sh &
[1] 1321
Using CATALINA_BASE:   /mnt/hda1/apache-tomcat-7.0.19
Using CATALINA_HOME:   /mnt/hda1/apache-tomcat-7.0.19
Using CATALINA_TMPDIR: /mnt/hda1/apache-tomcat-7.0.19/temp
Using JRE_HOME:        /mnt/hda1/jdk1.7.0
Using CLASSPATH:       /mnt/hda1/apache-tomcat-7.0.19/bin/bootstrap.jar:/mnt/hda1/apache-tomcat-7.0.19/bin/tomcat-juli.jar

6. 執行 AAAWebapp 專案

$ curl http://localhost:8080/AAAWebapp/
<html>
<body>
<h2>Hello World!</h2>
</body>
</html>

2011年8月5日 星期五

Apache Maven 專案管理平台 - Java 專案建立與執行

初設專案

Maven 專案命令是 mvn, mvn 主命令參數 archetype:generate 會根據 archetypeArtifactId 這參數, 來決定要初設何種專案.

Maven 小組提供一個專案模版網站, 網址 : http://www.mvnbrowser.com/index.html

初設 maven-archetype-quickstart 專案, 命令如下 :

$ mvn archetype:generate -DgroupId=com.mycompany.app -DartifactId=my-app -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
: 
Downloaded: http://repo1.maven.org/maven2/org/codehaus/plexus/plexus-interactivity-api/1.0-alpha-5/plexus-interactivity-api-1.0-alpha-5.jar (14 KB at 6.6 KB/sec)
Downloaded: http://repo1.maven.org/maven2/org/apache/maven/shared/maven-invoker/2.0.10/maven-invoker-2.0.10.jar (28 KB at 12.8 KB/sec)
Downloaded: http://repo1.maven.org/maven2/commons-collections/commons-collections/3.2.1/commons-collections-3.2.1.jar (562 KB at 97.0 KB/sec)
[INFO] Generating project in Batch mode
Downloading: http://repo1.maven.org/maven2/org/apache/maven/archetypes/maven-archetype-quickstart/1.0/maven-archetype-quickstart-1.0.jar
Downloaded: http://repo1.maven.org/maven2/org/apache/maven/archetypes/maven-archetype-quickstart/1.0/maven-archetype-quickstart-1.0.jar (5 KB at 7.4 KB/sec)
Downloading: http://repo1.maven.org/maven2/org/apache/maven/archetypes/maven-archetype-quickstart/1.0/maven-archetype-quickstart-1.0.pom
Downloaded: http://repo1.maven.org/maven2/org/apache/maven/archetypes/maven-archetype-quickstart/1.0/maven-archetype-quickstart-1.0.pom (703 B at 1.2 KB/sec)
[INFO] ----------------------------------------------------------------------------
[INFO] Using following parameters for creating project from Old (1.x) Archetype: maven-archetype-quickstart:1.0
[INFO] ----------------------------------------------------------------------------
[INFO] Parameter: groupId, Value: com.mycompany.app
[INFO] Parameter: packageName, Value: com.mycompany.app
[INFO] Parameter: package, Value: com.mycompany.app
[INFO] Parameter: artifactId, Value: my-app
[INFO] Parameter: basedir, Value: /mnt/hda1/apache-maven-3.0.3
[INFO] Parameter: version, Value: 1.0-SNAPSHOT
[INFO] ********************* End of debug info from resources from generated POM ***********************
[INFO] project created from Old (1.x) Archetype in dir: /mnt/hda1/apache-maven-3.0.3/my-app
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 1:35.260s
[INFO] Finished at: Sat Aug 06 09:14:53 UTC 2011
[INFO] Final Memory: 7M/18M
[INFO] ------------------------------------------------------------------------

上述命令, 會下載 archetypeArtifactId 參數所指 maven-archetype-quickstart 專案, 所需的所有檔案 (*.jar, *.pom) 至指定的儲存目錄, 並且會根據 artifactId 參數, 產生  my-app 目錄

檢視儲存目錄內容, 如下 :

drwxr-xr-x 14 root root 4096 Aug  6 09:14 .
drwxr-xr-x 10 root root 4096 Aug  6 07:43 ..
drwxr-xr-x  3 root root 4096 Aug  6 09:14 classworlds
drwxr-xr-x  3 root root 4096 Aug  6 09:14 commons-cli
drwxr-xr-x  3 root root 4096 Aug  6 09:14 commons-collections
drwxr-xr-x  3 root root 4096 Aug  6 09:14 commons-io
drwxr-xr-x  3 root root 4096 Aug  6 09:14 commons-lang
drwxr-xr-x  3 root root 4096 Aug  6 09:14 dom4j
drwxr-xr-x  3 root root 4096 Aug  6 09:14 jdom
drwxr-xr-x  3 root root 4096 Aug  6 09:14 junit
drwxr-xr-x  3 root root 4096 Aug  6 09:14 net
drwxr-xr-x  4 root root 4096 Aug  6 09:13 org
drwxr-xr-x  3 root root 4096 Aug  6 09:14 oro
drwxr-xr-x  3 root root 4096 Aug  6 09:14 xml-apis

my-app 目錄結構, 如下 :

my-app
|-- pom.xml
`-- src
    |-- main
    |   `-- java
    |       `-- com
    |           `-- mycompany
    |               `-- app
    |                   `-- App.java
    `-- test
        `-- java
            `-- com
                `-- mycompany
                    `-- app
                        `-- AppTest.java

在 my-app 目錄中的 pom.xml 設定檔, 是這個專案的核心, 內容如下 :

<project xmlns="http://maven.apache.org/POM/4.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
  http://maven.apache.org/maven-v4_0_0.xsd">

  <modelVersion>4.0.0</modelVersion>
  <groupId>com.mycompany.app</groupId>
  <artifactId>my-app</artifactId>
  <packaging>jar</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>my-app</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
</project>

專案建立

$ cd my-app          # 一定要執行此命令
$ mvn package
            :
            :
xus-io-1.0.pom
Downloaded: http://repo1.maven.org/maven2/org/codehaus/plexus/plexus-io/1.0/plexus-io-1.0.pom (2 KB at 2.1 KB/sec)
Downloading: http://repo1.maven.org/maven2/org/apache/maven/maven-archiver/2.4.1/maven-archiver-2.4.1.jar
Downloading: http://repo1.maven.org/maven2/org/codehaus/plexus/plexus-archiver/1.0/plexus-archiver-1.0.jar
Downloading: http://repo1.maven.org/maven2/org/codehaus/plexus/plexus-io/1.0/plexus-io-1.0.jar
Downloaded: http://repo1.maven.org/maven2/org/apache/maven/maven-archiver/2.4.1/maven-archiver-2.4.1.jar (20 KB at 16.3 KB/sec)
Downloaded: http://repo1.maven.org/maven2/org/codehaus/plexus/plexus-io/1.0/plexus-io-1.0.jar (50 KB at 19.8 KB/sec)
Downloaded: http://repo1.maven.org/maven2/org/codehaus/plexus/plexus-archiver/1.0/plexus-archiver-1.0.jar (174 KB at 46.9 KB/sec)
[INFO] Building jar: /mnt/hda1/my-app/target/my-app-1.0-SNAPSHOT.jar
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 1:20.944s
[INFO] Finished at: Sat Aug 06 10:20:02 UTC 2011
[INFO] Final Memory: 10M/25M
[INFO] ------------------------------------------------------------------------

執行專案

$ java -cp target/my-app-1.0-SNAPSHOT.jar com.mycompany.app.App
Hello World!

參考文章
1. Maven in 5 Minutes
http://maven.apache.org/guides/getting-started/maven-in-five-minutes.html

Apache Maven 專案管理平台 - 安裝

Apache Maven 是一個 Java 的專案管理平台,就好像 C 語言中的 make 與 Java 的 Ant 等專案產生器一樣。

Apache Maven 官方網址 :  http://maven.apache.org/

本系列文章的實作, 均使用 TinyCore 這個發行套件, 為使實作順利,
還需事先安裝以下套件 :

$ tce-load -wi tree.tcz     # 列出目錄架構
$ tce-load -wi curl.tcz      # 文字模式 WWW 瀏覽器

如需更多 TinyCore 操作與設定, 請參考 : http://linuxkvm.blogspot.com/

安裝 Apache Maven
1. 下載 maven


2. 解壓縮 apache-maven-3.0.x-bin.zip

3. 設定 M2_HOME 環境變數

     Linux Operating Systems 
           export M2_HOME=/usr/local/apache-maven-3.0.x

     Windows 2000/XP 
           set M2_HOME="c:\program files\apache-maven-3.0.x

4. 設定 PATH 環境變數 

    Linux Operating Systems 
        export PATH=$M2_HOME/bin:$PATH

    Windows 2000/XP 
         set PATH="%M2_HOME%\bin";%PATH% 

5. 測試

    $ mvn -version
    Apache Maven 3.0.3 (r1075438; 2011-02-28 17:31:09+0000)
    Maven home: /mnt/hda1/apache-maven-3.0.3
    Java version: 1.7.0, vendor: Oracle Corporation
    Java home: /mnt/hda1/jdk1.7.0/jre
                                                   :

6. 設定下載套件 (*.jar) 的儲存位址

    修改 %M2_HOME%\conf\settings.xml 檔案中的 <localRepository>
    標籤內容, 內定儲存位址 ${user.home}/.m2

    $ nano %M2_HOME%/conf/settings

   <settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 
          http://maven.apache.org/xsd/settings-1.0.0.xsd">
    <!-- localRepository
     | The path to the local repository maven will use to store artifacts.
     |
     | Default: ~/.m2/repository  -->
    <localRepository>${env.M2_HOME}\mavenrepo</localRepository>
 

2011年7月20日 星期三

Java 資料物件首部曲 - POJO

在 Java 物件導向程式設計中, 一直存在一個很重要的主角, 那就是 Java 資料物件, 這類物件主要是作為資料的容器 (PO : Persistent Object) 或載具 (DTO : Data transfer object ).

在本文中, 先來認識 POJO (Plain Old Java Object) 這簡易資料物件規範, POJO 資料物件只有變數 (Field) 及 getter、setter 這二個方法, 不具有永久儲存性.

如下程式範例中, 共宣告二個變數 (Field), 每一個變數均擁有 getter、setter 這二個方法. 變數均必須宣告 private, getter、setter 這二個方法一定要宣告 public, 這樣的程式設計又稱為 Information hiding

Mongo.java
public class Mongo {

    private String type;
    private String company;

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getCompany() {
        return company;
    }

    public void setCompany(String company) {
        this.company = company;
    }
   
}

Mongo 資料物件的使用, 程式範例如下 :

MongoTest.java
public class MongoTest {

    public static void main(String[] args) {

        Mongo x = new Mongo();
        x.setCompany("Donzai");
        x.setType("Trolling");
       
        System.out.println(x.getCompany());
        System.out.println(x.getType());

    }

}
先產生 Mongo 資料物件, 然後呼叫 setCompany() 及 setType() 這二個方法, 去設定 Mongo 資料物件內容. 然後再呼叫 getCompany() 及 getType() 這二個方法, 去顯示 Mongo 資料物件內容

2011年7月18日 星期一

Java Bean 的 XML 資訊檔

使用 java.beans 套件中的 XMLEncoder 及 XMLDecoder 這二個類別程式, 轉換 Java 物件資料 (Field) 與 XML 資訊檔

1. 程式撰寫
BeanEncoder.java
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

public class BeanEncoder {

    public static void main(String[] args) {
        Address address = new Address("123 Main Street", "San Jose", "CA", "95000-0000");
        Contact contact = new Contact("Doe", "Joe", address);
      
        try {
            FileOutputStream fos = new java.io.FileOutputStream(args[0]);
            java.beans.XMLEncoder encoder = new java.beans.XMLEncoder(fos);
            encoder.writeObject(contact);
            encoder.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}
BeanDecoder.java
public class BeanDecoder {

    public static void main(String[] args) {

        java.io.FileInputStream fis;
        try {
            fis = new java.io.FileInputStream(args[0]);
            java.beans.XMLDecoder decoder = new java.beans.XMLDecoder(fis);
            Contact contact = (Contact) decoder.readObject();
            decoder.close();
            (new XMLWriter()).write(contact, null);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

2. 執行程式
> java BeanEncoder d:\temp\abc.xml
執行後會在 d:\temp 目錄產生 abc.xml 資訊檔

> java BeanDecoder d:\temp\abc.xml
<?xml version = "1.0" encoding = "UTF-8"?><contact><name><fname>Doe</fname><lname>Joe</lname></name><address><street>123 Main Street</street><city>San Jose</city><state>CA</state><zip>95000-0000</zip></address></contact>

2011年7月17日 星期日

認識 JSF 網站開發架構

JavaServer Faces 於 2004 年三月 1.0 版正式提出,清楚的將 Web 2.0 網站的開發者劃分了三個角色:

1. 網頁設計人員
2. 應用程式設計人員
3. 網頁互動元件開發人員

從使用的角度 來看,網頁設計人員與應用程式設計人員可以他們所熟悉的方式開發程式,而不用侵入彼此的工作範圍,而網頁互動元件開發人員可以獨立的開發個別元件,細節的部份 留給了他們來處理。

總而言之,JavaServer Faces 協助了職責的分別,讓不同屬性的開發人員可以彼此合作,而又互不侵擾,網頁互動 (UI) 元件的開發搭配整合開發環境(IDE)或是所視即可得的網頁編輯程式,讓 Web 2.0 網站的開發得以簡單且迅速,藉此提高應用程式開發效率。

JavaServer Faces 2 (JSF 2) 是以 Java EE 為基礎的網頁互動 (UI) 應用架構技術,符合 MVC 架構,設定上跟其他架構相比算是較簡單些,也改進了第一代 JSF 的一些不足,Annotation 取代了原本的 xml 設定檔,使得設定相當容易,同時也提供彈性不錯的 Ajax 標籤。

參考文章
1.JSF 學習筆記
http://caterpillar.onlyfun.net/Gossip/JSF/JavaServerFaces.htm
2.Rational Application Developer for WebSphere Software V8 Programming Guide
http://my.safaribooksonline.com/book/-/0738435597/firstchapter

3.Apache MyFaces
http://myfaces.apache.org/
4. Why can't I get a larger heap with the 32-bit JVM?
http://www.oracle.com/technetwork/java/hotspotfaq-138619.html
5. How do you merge multiple VMware 2GB disk files to single monolithic vmdk file?

JSF 官方網址 : http://www.oracle.com/technetwork/java/javaee/javaserverfaces-139869.html

2011年7月13日 星期三

Java 文字終端機 - 密碼輸入 (會出現 *)

Java 對於文字終端機的支援是非常貧乏,  例如 : 密碼輸入螢幕上只出現 '*', 這樣的功能, JDK 並沒有支援, 如需這樣的功能, 你必須使用第三方套件來完成.

在此為你介紹 Jline 這套件, 如何完成 密碼輸入螢幕上只會出現 '*',
實作步驟如下 :

1. 下載 JLine 套件
http://sourceforge.net/projects/jline/files/

2. 撰寫程式
import jline.*;
import java.io.*;

public class PasswordReader {

    public static void main(String[] args) throws IOException {
        ConsoleReader reader = new ConsoleReader();

        String line = null;
        do {
            line = reader.readLine("enter password> ", '*');
            System.out.println("Got password: " + line);
        } while(line != null && line.length() > 0);
    }
}

3.編譯程式
> javac -cp jline-1.0.jar PasswordReader

4. 執行程式
> java -cp .;jline-1.0.jar PasswordReader
enter password> **********
Got password: qqqqqqqqqq
enter password>
Got password:

JLine 官方網址 : http://jline.sourceforge.net/

2011年7月10日 星期日

Java 與 費式數列 (Fibonacci)

Fibonacci 為1200年代的歐洲數學家,在他的著作中曾經提到:「若有一隻免子每個月生一隻小免子,一個月後小免子也開始生產。起初只有一隻免 子,一個月後就有兩隻免子,二個月後有三隻免子,三個月後有五隻免子(小免子投入生產)......」。 


範例程式
public class Fibonacci {
    public static void main(String[] args) {
        int[] fib = new int[20]; 
        fib[1] = 1; 
        for(int i = 2; i < fib.length; i++) 
            fib[i] = fib[i-1] + fib[i-2]; 
        for(int number : fib) 
            System.out.print(number + " ");  
        System.out.println();
    }
}

參考網站 :  http://caterpillar.onlyfun.net/Gossip/AlgorithmGossip/FibonacciNumber.htm

2011年7月9日 星期六

Java 浮點數內部格式

Java 浮點數內部格式採用 IEEE 754 二進位浮點數算術標準

浮點數而又分為單精度 (float) 與倍精度 (double) :單精度為 32bits,倍精度為 64bits

float 變數內部格式




double 變數內部格式




例如 :  -12.625 使用 IEEE 754 單精度 表示浮點數

第一步驟:不管正負號直接將數值轉為二進制
12.625 => 1100.101 = 1.100101 × 2^3

第二步驟:計算指數
127+3=130 => 10000010

第三步驟:填入數值置於浮點數規格中
S E      M
1 10000010 100101 0000 0000 0000 0000 0


撰寫研究程式 1 - MyIEEE754.java

public class MyIEEE754 {
    public static void main(String[] args) { 
        System.out.println(Integer.toHexString(Float.floatToRawIntBits(2.25f)));
        System.out.println(Integer.toHexString(Float.floatToRawIntBits(5.625f))) 
    }
}

程式中 Float.floatToRawIntBits(2.25f) 會將 float 浮點數內部格式, 以 int 傳回, 然後以十六進位格式顯示, 以下為執行結果 :

40100000
40b40000

執行結果, 使用下圖為你解釋 :


1. 先計算指數部份 : 128-127=1 (如是 double, 則減去 1023)
2. 移動小數點 : 指數為正數 1, 所以向右移動一位
3. 計算整數 : 小數點左邊為 10 (二進位), 2*1+2*0 = 2
4. 計算小數 : 查表得知 小數點右邊  01 (二進位) 為 0.25
5. 將整數加上小數得到結果 : 2 + 0.25 = 2.25

撰寫研究程式 2 - MyIEEE754_2.java
public class MyIEEE754_2 {
    public static void main(String[] args) {
        System.out.println(Float.toHexString(1.0f));
        System.out.println(Float.toHexString(5.25f));
        System.out.println(Float.toHexString(0.625f));
        System.out.println(Float.toHexString(5.3f));
        System.out.println(Float.toHexString(-5.25f));           
    }
}

以下為執行結果 :

0x1.0p0
0x1.5p2
0x1.4p-1
0x1.533334p2
-0x1.5p2

2011年7月6日 星期三

一級憤怒 - jAG105

class MyBug06 {
  public static void main(String[] arg) {
   
     for(int i=0; true ; ++i)
        System.out.println(i);

     System.out.print('end');
  }
}

這簡單程式, 幾個 "編譯憤怒" ?

一級憤怒 - jAG104

public class MyBug09 {

   public static void main(String[] args){
  
       byte o = 200;
       for(int x=2;x<7;x++){
         if(x==5) break v;
         o=o+x;
       }
       v:
       System.out.println(o);
  }
}

這簡單程式, 幾個 "編譯憤怒" ?

2011年6月29日 星期三

第一支 Java 大芒果資料庫程式

1. 下載  Java mongodb Driver
https://github.com/mongodb/mongo-java-driver/downloads

2. 設定 classpath 指到  Java mongodb Driver 的 jar 檔

3. 啟動 mongodb 服務 (Windows 7)
> cd  mongodb182\bin
> start mongod --rest -dbpath ..\db

4.撰寫 MyMGDB.java 
import com.mongodb.Mongo;

class MyMGDB1 {
  public static void main(String[] argv) throws Exception{
        Mongo m = new Mongo( "localhost" , 27017 );

        for (String s : m.getDatabaseNames()) {
            System.out.println(s);
        }
  }
}

5.編譯程式
> javac MyMGDB.java

6. 執行程式
> java MyMGDB
admin
local

參考網站
1. Java & MongoDB Tutorial

2011年6月28日 星期二

大芒果資料庫 - MongoDB 基礎操作

1. 啟動 mongodb 服務 (Windows 7)
c:\mongodb182\bin> start mongod --rest -dbpath ..\db

2. 啟動 mongo shell
c:\mongodb182\bin> mongo

3. 建立 MyDB 文件資料庫
> use MyDB
switched to db MyDB

4. 顯示目前開啟的文件資料庫
> db
MyDB

5.建立 Collection 並同時寫入文件
> db.aaa.insert( {a:1} )

6. 顯示文件
> db.aaa.find()
{ "_id" : ObjectId("4e0984538178ec62807d4feb"), "a" : 1 }

7. 顯示所有文件資料庫
> show dbs
MyDB    0.03125GB
admin   (empty)
local   (empty)

8. 顯示所有 Collections
> show collections
aaa
system.indexes

9. 離開 mongo shell
> exit

你可以直接使用瀏覽器, 查詢文件資訊, URL  如下 :

http://localhost:28017/MyDB/aaa/?filter_a=1

查詢結果如下 :
{
  "offset" : 0,
  "rows": [
    { "_id" : { "$oid" : "4e0984538178ec62807d4feb" }, "a" : 1 }
  ],

  "total_rows" : 1 ,
  "query" : { "a" : 1 } ,
  "millis" : 0
}

2011年6月26日 星期日

一級憤怒 - jAG103

class MyTest03 {
   public static void manin(String[] args) {
   
     int i=0;
     do {
    
       i=i+1;
       System.out.print("*");
    
     }; while (i>3)
 
   }

這簡單程式, 幾個 "編譯憤怒" ?

一級憤怒 - jAG102

class MyTes02 }{
   public static void main(String[] argv){
     for(int i=0; i<6 ; ++i){
       System.out.print( (i%2)==0 ? '*' : '' );
     }
     System.out.println(i);
   }
}

這麼簡單程式, 竟有二個 "編譯憤怒", 有看到嗎 ?

2011年6月21日 星期二

大芒果資料庫 - MongoDB

MongoDb 是一套用 C++ 寫成的,高擴充性,高效能,文件導向 (JSON) 的資料庫系統,而且它還是 開放源軟體 (Open Source) 

基本上它支援多數的作業系統:OSX / Linux / Windows / Solaris 等等, 而且也提供了多種程式語言的 連接驅動程式 :Java / Python / PHP / Ruby / Perl / C++ 等等

MongoDB 中的 mongo 是由 "humongous" 這單字而來, 代表它是能處理巨大資訊, 之所以稱它為芒果, 完全是根據它的讀音

不需安裝, 立即使用 (Ubuntu 為例)

1. 下載 MongoDB 壓縮檔,然後解壓縮至家目錄
網址 : http://www.mongodb.org/downloads

2.先建立資料庫存放目錄,預設會在 /data/db 底下
$ sudo mkdir -p /data/db

3. 下載後解壓縮
$ wget http://fastdl.mongodb.org/linux/mongodb-linux-i686-1.8.2.tgz
$ tar xvfz mongodb-linux-i686-1.8.2.tgz
mongodb-linux-i686-1.8.2/
mongodb-linux-i686-1.8.2/THIRD-PARTY-NOTICES
mongodb-linux-i686-1.8.2/GNU-AGPL-3.0
mongodb-linux-i686-1.8.2/README
mongodb-linux-i686-1.8.2/bin/
mongodb-linux-i686-1.8.2/bin/mongofiles
mongodb-linux-i686-1.8.2/bin/mongostat
mongodb-linux-i686-1.8.2/bin/bsondump
mongodb-linux-i686-1.8.2/bin/mongos
mongodb-linux-i686-1.8.2/bin/mongodump
mongodb-linux-i686-1.8.2/bin/mongoimport
mongodb-linux-i686-1.8.2/bin/mongosniff
mongodb-linux-i686-1.8.2/bin/mongo
mongodb-linux-i686-1.8.2/bin/mongod
mongodb-linux-i686-1.8.2/bin/mongoexport
mongodb-linux-i686-1.8.2/bin/mongorestore

4. 啟動 mongodb 服務
$ cd mongodb-linux-i686-1.8.2/
$ cd bin
$ sudo ./mongod -dbpath /data/db &

[註] MongoDB 啟動之後預設會佔用兩個 TCP Port, 如下 :

  27017 ﹣用來等待連線
  28017 ﹣提供 web admin interface(可以用瀏覽器來看MongoDB目前的狀態)

5. 執行 MongDB Shell
$ ./mongo
MongoDB shell version: 1.8.2
connecting to: test
Wed Jun 22 12:18:56 [initandlisten] connection accepted from 127.0.0.1:60485 #1
> help
    db.help()                    help on db methods
    db.mycoll.help()             help on collection methods
    rs.help()                    help on replica set methods
    help connect                 connecting to a db help
    help admin                   administrative help
    help misc                    misc things to know
    help mr                      mapreduce help

    show dbs                     show database names
    show collections             show collections in current database
    show users                   show users in current database
    show profile                 show most recent system.profile entries with time >= 1ms
    use <db_name>                set current database
    db.foo.find()                list objects in collection foo
    db.foo.find( { a : 1 } )     list objects in foo where a == 1
    it                           result of the last line evaluated; use to further iterate
    DBQuery.shellBatchSize = x   set default number of items to display on shell
    exit                         quit the mongo shell
>

6.停止 mongodb 服務
> use admin
switched to db admin
> db.shutdownServer()
Tue Jun 28 14:23:31 [conn2] terminating, shutdown command received
Tue Jun 28 14:23:31 dbexit: shutdown called
Tue Jun 28 14:23:31 [conn2] shutdown: going to close listening sockets...
Tue Jun 28 14:23:31 [conn2] closing listening socket: 5
Tue Jun 28 14:23:31 [conn2] closing listening socket: 6
Tue Jun 28 14:23:31 [conn2] closing listening socket: 7
Tue Jun 28 14:23:31 [conn2] closing listening socket: 8

MongoDB官網 : http://www.mongodb.org/

2011年6月18日 星期六

一級憤怒 - jAG101

class MyAG101 {
    public static viod main(Stringargv[]) {    
       System.out.printf("Hello World")
    }
}

這麼簡單程式, 竟有三個 "編譯憤怒", 妳感受到嗎 ?