顯示具有 Maven2 標籤的文章。 顯示所有文章
顯示具有 Maven2 標籤的文章。 顯示所有文章

27 4月 2011

Maven Android Plugin

 

主要是參考 sonatype的reference - Android Application Development with Maven

1. Maven android sdk deployer
Android SDK的安裝就不在這篇記錄了,直接跳到maven android sdk deployer安裝,先連到https://github.com/mosabua/maven-android-sdk-deployer/,按下Download後自行解壓縮。

Github - Maven android sdk deployer

 

進入解壓縮後的目錄執行

mvn install

正常的話可以看到類似下列的結果
[INFO] ------------------------------------------------------------------------
[INFO] Reactor Summary:
[INFO] 
[INFO] Maven Android SDK Deployer ........................ SUCCESS [0.598s]
[INFO] Android Platforms ................................. SUCCESS [0.007s]
[INFO] Android Platform 1.5 API 3 ........................ SUCCESS [0.336s]
[INFO] Android Platform 1.6 API 4 ........................ SUCCESS [0.034s]
[INFO] Android Platform 2.1 API 7 ........................ SUCCESS [0.022s]
[INFO] Android Platform 2.2 API 8 ........................ SUCCESS [0.016s]
[INFO] Android Platform 2.3 API 9 ........................ SUCCESS [0.033s]
[INFO] Android Platform 2.3.3 API 10 ..................... SUCCESS [0.019s]
[INFO] Android Platform 3.0 API 11 ....................... SUCCESS [0.037s]
[INFO] Android Add-Ons ................................... SUCCESS [0.011s]
[INFO] Android Add-On Google Platform 1.5 API 3 .......... SUCCESS [0.075s]
[INFO] Android Add-On Google Platform 1.6 API 4 .......... SUCCESS [0.034s]
[INFO] Android Add-On Google Platform 2.1 API 7 .......... SUCCESS [0.021s]
[INFO] Android Add-On Google Platform 2.2 API 8 .......... SUCCESS [0.027s]
[INFO] Android Add-On Google Platform 2.3 API 9 .......... SUCCESS [0.032s]
[INFO] Android Add-On Google Platform 2.3.3 API 10 ....... SUCCESS [0.028s]
[INFO] Android Add-On Google Platform 3.0 API 11 ......... SUCCESS [0.022s]
[INFO] Android Extras .................................... SUCCESS [0.012s]
[INFO] Android Compatibility Extra V4 .................... SUCCESS [0.016s]
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 1.922s
[INFO] Finished at: Wed Apr 27 17:28:29 CST 2011
[INFO] Final Memory: 4M/528M
[INFO] ------------------------------------------------------------------------
如果有特定的Platform或Add-On失敗的話,請確認在安裝AVD時是否有把所有的platform與add-on裝上。
其實全裝才有點不正常吧....
所以也可以改用指定profile的方式安裝
mvn install -P 2.3.3
 
可用的profile有1.5, 1.6, 2.1, 2.2, 2.3, 2.3.3, 3.0,就看本身AVD有裝哪些囉

2. 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/xsd/maven-4.0.0.xsd">
 <modelVersion>4.0.0</modelVersion>
 <groupId>Best1</groupId>
 <artifactId>Best1</artifactId>
 <version>0.0.1-SNAPSHOT</version>
 <packaging>apk</packaging>
 <properties>
  <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
 </properties>

 

<build> <finalName>best</finalName> <sourceDirectory>src</sourceDirectory> <plugins> <plugin> <groupId>com.jayway.maven.plugins.android.generation2</groupId> <artifactId>maven-android-plugin</artifactId> <version>2.9.0-beta-4</version> <configuration> <sdk> <platform>10</platform> </sdk> <emulator> <avd>Android233</avd> <wait>10000</wait> <!--<options>-no-skin</options>--> </emulator> <deleteConflictingFiles>true</deleteConflictingFiles> </configuration> <extensions>true</extensions> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>2.3.2</version> <configuration> <source>1.6</source> <target>1.6</target> </configuration> </plugin> </plugins> </build> <dependencies> <dependency> <groupId>com.google.android</groupId> <artifactId>android</artifactId> <version>2.3.3</version> <scope>provided</scope> </dependency> </dependencies> </project>

再來就可以執行mvn android:emulator-start, mvn android:deploy來測試程式囉

 

17 3月 2011

Maven 同時使用Emma 與Surefire會執行兩次Unit test的解決方式

emma-maven-plugin的開發人員認為,被instrumented過的test class不等同於原來的test class,可能會造成原來test不會通過,但在emma處理後而可以通過,或是反過來的情形發生。所以在pom中如果同時加上emma-maven-plugin與maven-surefire-plugin,就會跑兩次的unit test。

如果可以接受被emma instrumented過的test class可以代表原來的test class,那解決的方式就還蠻容易的,簡單說, 就是讓surefire執行被instrumented過的test class,但是要求emma在test或site之類的phase不做事。
設定如下



	org.sonatype.maven.plugin
	emma-maven-plugin
	1.2
	
		
			instrument
			process-classes
			
				instrument
			
		
		
			test
			test
			
				true
			
		
		
			site
			site
			
				true
			
		
	



	org.apache.maven.plugins
	maven-surefire-plugin
	2.8
	true
	
	
		once
		xml
		${project.build.directory}/generated-classes/emma/classes
	


Report的部份不用特別修改


	
		
		
			org.sonatype.maven.plugin
			emma-maven-plugin
			1.2
		

		
			org.apache.maven.plugins
			maven-surefire-report-plugin
			2.8
		

03 12月 2010

Maven3 and Site Plugin

Maven3 的 maven-site-plugin已將關於reporting的邏輯移除,所以如果用原先給maven2用的pom.xml,雖然可以執行,但除了用Doxia的report可以跑出結果來,其餘的report都不會產生。

要跑出先前的report就必需修改下pom.xml,Maven的report主要有分兩類,一是Project Information、另一則是Project Report,Information就是專案成員名單、使用的library、Issue Tracking等相關資訊,而Report則是其他外掛的Changelog、Unit test Surefire、CodeCoverage Emma等report,maven2的是將其分為兩部份控制,information是內建的,只要敲個mvn site就一定有,其他的report就必需在<reporting />中掛上plugin,而maven3的設定則希望全部在maven-site-plugin中加以控制,這是兩者比較大的分別。

直接看看maven3的設定項目吧,請記得下列所有report的<version />皆可以不指定

<project>
 <build>
  <plugins>
   <plugin>
    <groupid>org.apache.maven.plugins</groupid>
    <artifactid>maven-site-plugin</artifactid>
    <version>3.0-beta-3</version>
    <configuration>
     <reportplugins>
      <!-- maven-project-info-reports-plugin即是指供project information的plugin -->
      <plugin>
       <groupid>org.apache.maven.plugins</groupid>
       <artifactid>maven-project-info-reports-plugin</artifactid>
       <!-- 可不指定version -->
       <version>2.2</version>
       <!-- dependencyDetailsEnabled 及 dependencyLocationsEnabled 設為false
       時會讓 dependencies report 少產生部份資訊-->
       <configuration>
        <dependencydetailsenabled>true</dependencydetailsenabled>
        <dependencylocationsenabled>true</dependencylocationsenabled>
       </configuration>
       <!-- 基本的information report都在下面了,若有不需要看的就mark掉就好 -->
       <reports>
        <report>cim</report>
        <report>dependencies</report>
        <report>index</report>
        <report>issue-tracking</report>
        <report>license</report>
        <report>mailing-list</report>
        <report>plugin-management</report>
        <report>plugins</report>
        <report>project-team</report>
        <report>scm</report>
        <report>summary</report>
       </reports>
      </plugin>
      
      <!-- 以下為其他外掛的report plugin 設定處,version可以拿掉 -->
      <plugin>
       <groupid>org.apache.maven.plugins</groupid>
       <artifactid>maven-surefire-report-plugin</artifactid>
       <version>2.6</version>
      </plugin>
      <plugin>
       <groupid>org.apache.maven.plugins</groupid>
       <artifactid>maven-changelog-plugin</artifactid>
       <version>2.2</version>
      </plugin>
     </reportplugins>
    </configuration>
   </plugin>
  </plugins>
 </build>
</project>
</project>


18 10月 2010

Maven2 : Release Plugin

在專案的後期,要進入大量測試的階段,或是要完成測試要打包完整檔案給客戶時,通常都會在source code上加上一個tag,例如XXX-RC1,XXXX-RELEASE,以方便追踪各項問題,當然透過其他SCM提供的GUI Tools或是Commadn line來執行這種上tag的工作是沒有任何疑慮的,只不過Maven也提供了一個Plugin讓我們可以在沒在錯誤下完成一個Build時一併進行上Tag及其他release的工作,如修改pom.xml的version。

Maven Release Plugin請參考http://maven.apache.org/plugins/maven-release-plugin/index.html

基本上只要在pom.xml的plugin中加上

<plugin>
    <groupid>org.apache.maven.plugins</groupid>
    <artifactid>maven-release-plugin</artifactid>
    <version>2.1</version>
</plugin> 

然後在goals裡加上release:prepare即可

執行時會詢問你要簽入的version與tag/label的資料

[INFO] Working directory: /Users/elliot/tmp/target/checkout
[INFO] Checking dependencies and plugins for snapshots ...
What is the release version for "BuildDemo"? (idv.elliot:BuildDemo) 0.0.3: : 
What is SCM release tag or label for "BuildDemo"? (idv.elliot:BuildDemo) BuildDemo-0.0.3: : 
What is the new development version for "BuildDemo"? (idv.elliot:BuildDemo) 0.0.4-SNAPSHOT: :

當整個build在沒錯誤的情況下結束時,release plugin會依你提共的資訊對source code加上tag,然後修改pom.xml的version,再將pom.xml checkin到SCM中。

如果希望不要出現提示,可以用-D的方式將相關版本資訊帶入,或是修改release.properties,然後在build 時加上--batch-mode即可

例如:

mvn --batch-mode -Dtag=my-proj-1.2 -DreleaseVersion=1.2 -DdevelopmentVersion=2.0-SNAPSHOT release:prepare 


Maven2 : SCM

通常在Nightly Build的環節,我比較喜歡Clean Build,也就是從Checkout、Compile、Test、Deploy都是一個動作完成的Compile、Test、Deploy都可以靠Maven或Ant完成,但是自VCS中checkout source code就要看plugin的支援程度了。即便是plugin支援度不夠,只要該種VCS有提供command line的模式,我想就能利用shell或script的方式來達到完整的Clean Build。 例如:

git clone [url] #checkout source code from VCS
cd [project]
mvn site -Pprod

當然利用Maven提供的SCM來處理也是不錯,除了checkin, checkout之外也可以利用scm plugin來列出changelog或add、remove檔案,不過我個人是比較少用到這些功能就是。

Maven提供的SCM Plugin請參考 http://maven.apache.org/scm/plugins/index.html, 而支援的SCM的完整度則可以考http://maven.apache.org/scm/matrix.html


為了使用Maven的SCM Plugin,通常單獨將<scm>建一個pom.xml,其他plugin或build的東西就免寫了,當然要用原來project的pom.xml也無不可,簡單看個例子。

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

  <groupid>idv.elliot</groupid>
  <artifactid>BuildDemo</artifactid>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>pom</packaging>

  <name>BuildDemo</name>
  <url>http://github.com/ElliotChen/BuildDemo </url>

  <scm>
    <!-- 僅供讀取的Connection URL, 前面必需加上scm:xxx -->
    <connection>scm:git:git://github.com/ElliotChen/BuildDemo.git </connection>
    <!-- 可以執行checkin的Connection URL, 前面必需加上scm:xxx -->
    <developerconnection>scm:git:git://github.com/ElliotChen/BuildDemo.git </developerconnection>
    <url>http://github.com/ElliotChen/BuildDemo </url>
  </scm>
  <build>
    <plugins>
      <plugin>
        <groupid>org.apache.maven.plugins</groupid>
        <artifactid>maven-scm-plugin</artifactid>
        <version>1.3</version>
        <!-- Checkout之後要執行的Goal -->
        <configuration>
          <goals>site</goals>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project> 


簡單來說,只要在<scm>裡的<connection>填入SCM checkout source code的url,然後在url之前依你使用的SCM種類加上指定的prefix,然後在<maven-scm-plugin>的<configuration>中填上接下來要執行的goal,最後執行

mvn clean scm:bootstrap 
這樣就可以看到像下列的輸出:
[INFO] [scm:bootstrap {execution: default-cli}]
[INFO] Removing /Users/elliot/tmp/target/checkout
[INFO] Executing: /bin/sh -c cd /Users/elliot/tmp/target && git clone git://github.com/ElliotChen/BuildDemo.git /Users/elliot/tmp/target/checkout
[INFO] Working directory: /Users/elliot/tmp/target
[INFO] Executing: /bin/sh -c cd /Users/elliot/tmp/target/checkout && git pull git://github.com/ElliotChen/BuildDemo.git master
[INFO] Working directory: /Users/elliot/tmp/target/checkout
[INFO] Executing: /bin/sh -c cd /Users/elliot/tmp/target/checkout && git checkout
[INFO] Working directory: /Users/elliot/tmp/target/checkout
[INFO] Executing: /bin/sh -c cd /Users/elliot/tmp/target/checkout && git ls-files
[INFO] Working directory: /Users/elliot/tmp/target/checkout
[INFO] Scanning for projects...
[INFO] ------------------------------------------------------------------------
[INFO] Building BuildDemo
[INFO]    task-segment: [site]
[INFO] ------------------------------------------------------------------------
[INFO] [site:site {execution: default-site}]


13 10月 2010

Maven2 : Portable Configuration

最近Support中x信托個金的WebATM案子,非常訝異,SCM checkout出來的source code不能compile,四個環境上跑的是哪個版本也不能確定,環境上的configuration也都不能完全確定哪個是正確的,再來改版時的patch是一個個class複製到deployment目錄下,XML或Properties也都是手動一個個修改....拜託,什麼年代了!?

能用程式做的就不要手動,寫個maven或ant的設定有這麼麻煩嗎?時間要花在更有義意的事情上,減少手動的工作,也減少人為的錯誤,多出來的時間回去陪家人不是更好些嗎....

XML及Properties的變動不外乎兩種方式解決
(1)Merge : 在範本檔案以${變數名}做為標記,然後再為不同環境寫不同的設定檔,為每個變數定出符合該環境的值,在Build的時候將範本與變數檔進行Merge,產生該環境專用的檔案,該檔案應與範本檔案同名
(2)Replace:為不同環境另存不同名的檔案,在Build的時以更名覆蓋的方式產生該環境專用的檔案

Merge的變數值有幾種設定方式
(1)放在系統變數中,範本檔以${env.變數名}取得該值,例如 export profilename=ABC;
(2)放在java 啟動參數數,以 -D變數名=變數值 帶入,範本檔則以${變數名}取得該值,例如 mvn -Dprofilename=ABC
(3)放在pom.xml中,以<properties><變數名>變數值</變數名></properties>設定,範本檔則以${變數名}取得該值,各profile可以自訂不同的properties
(4)放在其他檔案中,以一般java的properties檔案格式設定,如 變數名=變數值,在pom.xml中以<filters><filter>變數值設定檔</filter></filters>,範本檔則以${變數名}取得該值。

簡單看一下Maven的例子,下圖是一個非常簡單的maven project

其中
conf/prod/env.properties是prod環境Merge用的變數值設定檔案

setting.envname=prod

conf/template/system.properties則是上列所提Merge用的範本檔

profile.name=${profilename} #取自pom.xml中的設定
package.envname=${setting.envname} #取自env.properties
M2=${env.M2_HOME} #取自系統變數

src/main/resource下的兩個檔案則是為了展示利用antrun來執行Replace的操作,裡面的內容隨便設定,只要不一樣即可

再來列出pom.xml中的profiles設定

<profiles>
    <profile>
        <id>prod</id>
        <!-- 在Maven內自訂變數值 -->
        <properties>
            <profilename>PROD</profilename>
        </properties>
        <build>
        <!-- 將變數訂在特定檔案(env.properties) -->
            <filters>
                <filter>${basedir}/conf/prod/env.properties</filter>
            </filters>
            <resources>
                <!-- 系統原用的resource -->
                <resource>
                    <directory>${basedir}/src/main/resources</directory>
                </resource>
    <!-- 因不同環境會有變動的設定檔範本 -->
    <resource>
        <directory>${basedir}/conf/template</directory>
        <filtering>true</filtering>
                </resource>
            </resources>
            <plugins>
            <!-- 利用Ant Run的Copy來取代檔案 -->
                <plugin>
                    <artifactid>maven-antrun-plugin</artifactid>
                    <executions>
                        <execution>
                            <phase>process-resources</phase>
                            <goals>
        <goal>run</goal>
                </goals>
                <configuration>
        <tasks>
            <delete file="${project.build.outputDirectory}/antrun.replace">
            </delete><copy tofile="${project.build.outputDirectory}/antrun.replace" file="${basedir}/src/main/resources/antrun.replace.prod">
        </copy></tasks>
                </configuration>
            </execution>
        </executions>
    </plugin>
            </plugins>
        </build>
    </profile>
</profiles>
</profiles>

再執行 mvn package -Pprod就可以看到結果了


08 4月 2010

m2eclipse與Jetty 7

Jetty是一個小巧又能高度客製化的Servlet Container,在很多場合可能會比Tomcat要來得方便,但是在配合Eclipse開發時有點缺憾,就是Jetty配合可用的Server Adapter更新不快,Jetty7至今仍未有一個方便的Server Adapter可以像使用Tomcat一樣快速Deploy,不過利用m2eclipse也可以減少利用Jetty7開發時的不便。
第一步:當然是要會裝m2eclipse....
第二步:修改pom.xml,加入maven-jetty-plugin
<plugin>
 <groupId>org.mortbay.jetty</groupId>
 <artifactId>jetty-maven-plugin</artifactId>
 <version>7.0.2.v20100331</version>
 <configuration>
 <scanIntervalSeconds>10</scanIntervalSeconds>
 <webAppConfig>
 <contextPath>/sample</contextPath>
 </webAppConfig>
 <stopPort>9966</stopPort>
 <stopKey>stop</stopKey>
 </configuration>
</plugin>
其中<contextPath>就是你想訂的web context名稱,如果不加會變成root context而不是依你web.xml中所訂的<display-name>。而<stopKey>跟<stopPort>也請務必要加,否則jetty:stop會無法正常使用。
第三步:在Eclipse加上Run/Debug Configurations,
(1)Jetty Run:
在"Main" Tab中
Base directory中輸入${project_loc}
Goals輸入jetty:run
(2)Jetty Stop:
在"Main" Tab中
Base directory中輸入${project_loc}
Goals輸入jetty:stop
(3)Jetty Debug:
先同於Jetty Run一樣
在"Main" Tab中
Base directory中輸入${project_loc}
Goals輸入jetty:run
然後在"JRE" Tab中
VM arguments:輸入
-Xdebug -Xnoagent -Djava.compiler=NONE -Xrunjdwp:transport=dt_socket,address=4000,server=y,suspend=n
其中address=4000,4000是指Remote debug所用的port,只要不被其他Server佔用就好。

(4)Remote Debug
加入一個Remote Java Application的設定
在這project就必需指定,不能用變數,主要是為了確認Java Source Code與Remote Application的對應,再來host填localhost,當然不一定要是localhost,也可以是其他IP,但是上列的情形來看一定是localhost,Port則是要同於上列(3)所指定的Port。
這樣一來,除了可以不離開Eclipse而啟動關閉Jetty外,也可以利用Remote Debug來做Debug的操作,雖然不能同於Server Adapter一樣方便,但只要會這方法,之後遇到其他Server也不用擔心。
ps;m2eclipse 0.10在設定Maven Build時有點問題,當你要輸入Base directory時請確認你的滑鼠是點在 Package Explorer中的某一個Project名稱而不是Project下某一檔案,否則會警告Base directory設定有誤。

套用Maven2在Eclipse上的Dynamic Web Project

這問題在最近一個月被問了三次,雖然沒什麼價值,想想還是寫出來好了。
不少朋友用Eclipse開了個Dynamic Web Project後再想加入Maven2作為Build Tool,但是由於兩者間的目錄結構不同而頗為困擾,這種情形下我比較建議修改pom.xml以符合現行Project的結構。

<build>
    <sourcedirectory>${basedir}/src</sourcedirectory>  
    <outputdirectory>${basedir}/build/classes</outputdirectory>  
    <resources>  
     <resource>  
     <directory>${basedir}/src</directory>  
      <includes>  
       <include>*.xml</include>  
      <include>*.properties</include>  
      </includes>  
      <excludes>  
       <exclude>**/.svn/</exclude>  
      </excludes>  
     </resource>  
    </resources>  
    <plugins>  
     <plugin>  
     <groupid> org.apache.maven.plugins</groupid>  
     <artifactid> maven-compiler-plugin</artifactid>  
      <version>2.1</version>  
      <inherited>true</inherited>  
      <configuration>  
       <source>1.6</source>  
       <target>1.6</target>  
      </configuration>  
     </plugin>  
     <plugin>  
     <groupid> org.apache.maven.plugins</groupid>  
     <artifactid>maven-war-plugin</artifactid>  
     <version>2.1-beta-1</version>  
      <inherited>true</inherited>  
      <configuration>  
       <webappdirectory>${basedir}/WebContent</webappdirectory>  
       <packagingexcludes>**/.svn/</packagingexcludes>  
      </configuration>  
     </plugin>  
    </plugins>  
   </build> 
主要是<sourcedirectory>、<resources>跟maven-war-plugin中的<webappdirectory>
<packagingexcludes>加入**/.svn/則視情形而定,如果覺得.svn被包進war沒差也就沒關係了。

04 12月 2009

病貓

有人跟我抱怨為什麼用Eclipse + m2eclipse deploy web project到tomcat時,老是㑹將servlet-api-XXX.jar跟jsp-api-XXX.jar丢到WEB-INF/lib下,結果tomcat就變成起不來的病貓,可是經我個人反覆測試,pom.xml中的dependency只要有加<scope>provided</scope>,一定不㑹被丟到WEB-INF/lib。

遇到這種見鬼的事情,第一件要做的事當然是...拿乖乖去拜你的電腦(誤

有幾個選擇可以解決

(1)自己砍掉WEB-INF/lib中的servlet-api.jar jsp-api.jar,缺點是每次你有改變dependency時就要再做一次。

(2)將serlvet-api跟jsp-api的dependency的設定移到profile中,然後在project->Java build path->Libraries->Add Library
選server runtime,再選tomcat,將tomcat runtime libraries加入你的project libraries,這樣的缺點是每次用Maven都要記得加 -P。

BTW,乖乖團購有比較便宜嗎?

27 10月 2009

emma-maven-plugin always executes test cases twice

這是碎碎唸
如果同時要出Emma Code Coverage跟Surefire Test report的話,一定要跑2次 Unit Test,聽起來很合理,但其實根本就不用。
只要在Surefire執行前先將test classes做instrument,這様測出來的就是具有coverage的unit test.
<plugin>
 <groupId>org.sonatype.maven.plugin</groupId>
 <artifactId>emma-maven-plugin</artifactId>
 <version>1.1</version>
 <inherited>true</inherited>
 <executions>
  <execution>
   <id>instrument</id>
   <phase>process-classes</phase>
   <goals>
    <goal>instrument</goal>
   </goals>
  </execution>
 </executions>
</plugin>
<plugin>
 <groupId>org.apache.maven.plugins</groupId>
 <artifactId>maven-surefire-plugin</artifactId>
 <version>2.4.3</version>
 <inherited>true</inherited>
 <configuration>
  <forkMode>once</forkMode>
        <reportFormat>xml</reportFormat>
  <classesDirectory>${project.build.directory}/generated-classes/emma/classes</classesDirectory>
 </configuration>
</plugin>
這様跑完就㑹產生coverage.em, coverage.ec等產生Code Coverage Report所需要的東西。


而jira上也提出這個問題很久了…就是他X的沒人解決,
Allow generating reports outside the emma:emma goal


現在只好偷偷用emma4it-maven-plugin,單獨來跑report,只是不能出現在project reports裡
<plugin>
 <groupId>org.sonatype.maven.plugin</groupId>
 <artifactId>emma4it-maven-plugin</artifactId>
 <version>1.3</version>
 <executions>
  <execution>
   <id>report</id>
   <phase>post-integration-test</phase>
   <goals>
    <goal>report</goal>
   </goals>
   <configuration>
    <sourceSets>
     <sourceSet>
      <directory>${project.build.sourceDirectory}</directory>
     </sourceSet>
    </sourceSets>
   </configuration>
  </execution>
 </executions>
</plugin>

20 10月 2009

hibernate3-maven-plugin直接使用Spring AnnotationSessionFactoryBean

新公司有自己的一套Framework,並自行開發一套code gen的工具,稍為喚起了我曽經用過Hibernate Tools的記憶,一方面是因為用了JDK5的Generic後,要寫的Code變少,另一方面也是因為如果有修改,code gen出來的東西比較不易配合更動,所以也沒有納入我常用的工具之一。不過既然想起了Hibernate tools,那就再用用看有沒有什麼改變,或許會有驚喜吧。

不過似乎沒有…特別是不能直接用Spring Configuration Xml中已經訂好的設定,一定要另訂hibernate.cfg.xml,這就又讓我難過了一下,再發現居然連hibernate3-maven-plugin也無法直接使用Spring 裡訂好的AnnotationSessionFactoryBean或LocalSessionFactoryBean,只好試著改看看有沒有辦法可以讓我懶一點不要再去重訂hibernate.cfg.xml。


發現hibernate3-maven-plugin中有一個AnnotationComponentConfiguration,看來似是一個不錯的切入點,稍為改了一下還發現真能work!下面列的就是實做出來的東西。


1.pom.xml

改maven的plugin不用maven也太說不過去了吧,所以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>org.elliot.hibernate</groupId>
 <artifactId>maven-hibernate3-jdk15</artifactId>
 <version>1.0-SNAPSHOT</version>
 <name>Maven Hibernate3 Implementation - JDK15</name>
 <packaging>jar</packaging>
 <dependencies>
  <dependency>
   <groupId>org.apache.maven</groupId>
   <artifactId>maven-model</artifactId>
   <version>2.0.6</version>
  </dependency>
  <dependency>
   <groupId>org.apache.maven</groupId>
   <artifactId>maven-plugin-api</artifactId>
   <version>2.0.6</version>
  </dependency>
  <dependency>
   <groupId>org.apache.maven</groupId>
   <artifactId>maven-artifact</artifactId>
   <version>2.0.6</version>
  </dependency>
  <dependency>
   <groupId>org.apache.maven</groupId>
   <artifactId>maven-project</artifactId>
   <version>2.0.6</version>
  </dependency>
  <dependency>
   <groupId>org.codehaus.mojo.hibernate3</groupId>
   <artifactId>maven-hibernate3-jdk15</artifactId>
   <version>2.2</version>
  </dependency>
  <dependency>
   <groupId>org.hibernate</groupId>
   <artifactId>hibernate-core</artifactId>
   <version>3.3.2.GA</version>
  </dependency>
  <dependency>
   <groupId>org.hibernate</groupId>
   <artifactId>hibernate-entitymanager</artifactId>
   <version>3.4.0.GA</version>
  </dependency>
  <dependency>
   <groupId>org.hibernate</groupId>
   <artifactId>ejb3-persistence</artifactId>
   <version>1.0.2.GA</version>
  </dependency>
  <dependency>
   <groupId>org.hibernate</groupId>
   <artifactId>hibernate-annotations</artifactId>
   <version>3.4.0.GA</version>
  </dependency>
  <dependency>
   <groupId>jboss</groupId>
   <artifactId>jboss-common</artifactId>
   <version>4.0.2</version>
  </dependency>
  <dependency>
   <groupId>javassist</groupId>
   <artifactId>javassist</artifactId>
   <version>3.4.GA</version>
  </dependency>
  <!--可視情形改用其他版本的Spring-->
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>org.springframework.orm</artifactId>
   <version>3.0.0.RC1</version>
  </dependency>
 </dependencies>
 <build>
  <plugins>
   <plugin>
    <artifactId>maven-compiler-plugin</artifactId>
    <configuration>
     <source>1.5</source>
     <target>1.5</target>
    </configuration>
   </plugin>
  </plugins>
 </build>
</project>
2. SpringComponentConfiguration.java

我暫用org.codehaus.mojo.hibernate3.configuration這package,怕AnnotationComponentConfiguration會不會有什麼method不能用,後來看code發現沒問題,也可以改成你喜歡的名稱

package org.codehaus.mojo.hibernate3.configuration;

import javax.sql.DataSource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.maven.plugin.MojoExecutionException;
import org.codehaus.mojo.hibernate3.ExporterMojo;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean;
import org.springframework.util.StringUtils;

public class SpringComponentConfiguration extends
  AnnotationComponentConfiguration {
 private static final Log logger = LogFactory
   .getLog(SpringComponentConfiguration.class);

 private ExporterMojo exporterMojo;
 private ApplicationContext applicationContext;

 public String getName() {
  return "springconfiguration";
 }

 public ExporterMojo getExporterMojo() {
  return exporterMojo;
 }

 public void setExporterMojo(ExporterMojo exporterMojo) {
  this.exporterMojo = exporterMojo;
 }

 @Override
 protected Configuration createConfiguration() {
  String sessionFactoryBean = getExporterMojo().getComponentProperty(
    "sessionFactoryBean", "sessionFactory");
  String appContextLocations = getExporterMojo().getComponentProperty(
    "appContextLocations", "classpath*:spring*.xml");
  logger.info("Initial info: [sessionFactoryBean]=" + sessionFactoryBean
    + ", [appContextLocations]=" + appContextLocations);

  String[] locations = StringUtils.delimitedListToStringArray(
    appContextLocations, ",");
  // Initial ApplicationContext from spring configuration xml files.
  this.applicationContext = new FileSystemXmlApplicationContext(locations);

  // Get AnnotationSessionFactoryBean from spring
  AnnotationSessionFactoryBean asfb = (AnnotationSessionFactoryBean) applicationContext
    .getBean("&" + sessionFactoryBean);

  DataSource dataSource = asfb.getDataSource();
  ThreadLocalHolder.setDataSource(dataSource);

  Configuration configuration = asfb.getConfiguration();
  configuration.setProperty(Environment.CONNECTION_PROVIDER,
    ThreadLocalConnectionProvider.class.getName());

  return configuration;
 }

 @Override
 protected void validateParameters() throws MojoExecutionException {
  // don't validate
 }

}
3.ThreadLocalConnectionProvider.java

因為Configuration不能直接設DataSource,所以只好放到ThreadLocal

package org.codehaus.mojo.hibernate3.configuration;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

import javax.sql.DataSource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.HibernateException;
import org.hibernate.connection.ConnectionProvider;

public class ThreadLocalConnectionProvider implements ConnectionProvider {
 private static final Log logger = LogFactory.getLog(ThreadLocalConnectionProvider.class);
 public ThreadLocalConnectionProvider() {
 }
 public void close() throws HibernateException {

 }

 public void closeConnection(Connection conn) throws SQLException {
  conn.close();
 }

 public void configure(Properties props) throws HibernateException {
  //Do nothing

 }

 public Connection getConnection() throws SQLException {
  DataSource dataSource = ThreadLocalHolder.getDataSource();
  if (null == dataSource) {
   logger.error("Please check ThreadLocalHolder.setDataSource has been invocked.");
   throw new SQLException("No usable DataSource.");
  }
  return dataSource.getConnection();
 }

 public boolean supportsAggressiveRelease() {
  // TODO Auto-generated method stub
  return true;
 }

}
4.ThreadLocalHolder.java

package org.codehaus.mojo.hibernate3.configuration;

import javax.sql.DataSource;

public abstract class ThreadLocalHolder {
 private static ThreadLocal<DataSource> dataSourceHolder = new ThreadLocal<DataSource>();

 public static DataSource getDataSource() {
  return dataSourceHolder.get();
 }

 public static void setDataSource(DataSource dataSource) {
  dataSourceHolder.set(dataSource);
 }
 
}
5.components.xml

這檔案放在src/main/resources/META-INF/plexus下,是maven plugin的設定檔

<component-set>
  <components>
 <component>
      <role>org.codehaus.mojo.hibernate3.configuration.ComponentConfiguration</role>
      <role-hint>springconfiguration</role-hint>
      <implementation>org.codehaus.mojo.hibernate3.configuration.SpringComponentConfiguration</implementation>
    </component>
  </components>
</component-set>
完成之後就用mvn install裝到repository裡以供使用,使用方式就只是改變hibernate3-maven-plugin中的dependency。

<build>
   <plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>hibernate3-maven-plugin</artifactId>
    <version>2.2</version>
    <configuration>
     <componentProperties>
      <jdk5>true</jdk5>
      <implementation>springconfiguration</implementation>
      <appContextLocations>classpath*:applicationContext.xml</appContextLocations>
      <sessionFactoryBean>sessionFactory</sessionFactoryBean>
     </componentProperties>
    </configuration>
    <dependencies>
     <dependency>
      <groupId>org.elliot.hibernate</groupId>
      <artifactId>maven-hibernate3-jdk15</artifactId>
      <version>1.0-SNAPSHOT</version>
     </dependency>
     <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-ehcache</artifactId>
      <version>3.3.2.GA</version>
     </dependency>
     <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-annotations</artifactId>
      <version>3.4.0.GA</version>
     </dependency>
     <dependency>
      <groupId>com.h2database</groupId>
      <artifactId>h2</artifactId>
      <version>1.2.121</version>
     </dependency>
    </dependencies>
   </plugin>
  </plugins>
 </build>
加入configuration中列出的設定,appContextLocations是專案中spring設定檔的檔案位置,sessionFactoryBean則是spring中你定義的AnnotationSessionFactoryBean名稱。

再來就可以用mvn hibernate3:hbm2ddl 之類的goals來測試囉。

16 9月 2009

Nexus : Maven Repository Server

Nexus,一個Maven Repository Server,在區網內如果架設一個Nexus來提供開發人員使用,可以有效減少對外網路頻寬的浪費,也提供一個可以管理團隊自行開發library的機制,之前較多使用的是Apache Archiva,但是Archiva較為複雜,相較之下Nexus則無論在安裝上跟管理上都較為容易。 以下是我在Ubuntu 8.10 與 Tomcat 6.0.18下安裝的方式
  1. Download nexus-webapp-XXX.war
    • Nexus的下載頁面在 http://nexus.sonatype.org/downloads/ ,雖然Nexus也有自帶jetty的版本,但我還是打算使用webapp來安裝,所以下載的是nexus-webapp-XXX.war。
  2. Deploy nexus-webapp-XXX.war
    • 將war改名為nexus.war後直接丟到${tomcat}/webapp下就好。
  3. 設定sonatype-work權限 (各OS與distribution㑹有所不同)
    • 由於nexus需要實體目錄存放下載的檔案,所以㑹在/usr/share/tomcat6下建一個sonatype-work的目錄,但由於/usr/share/tomcat6的權限原屬於root,所以執行
      $> sudo mkdir /usr/share/tomcat6/sonatype-work
      $> sudo chown tomcat6:tomcat6 /usr/share/tomcat6/sonatype-work
      
      後再重起tomcat即可
  4. 再來是設定client端maven2用的setting.xml
    • 加入下面的xml到setting.xml,將其中tomcat_ip與tomcat_port改成你實際使用的
<mirrors>
    <mirror>
        <id>nexus</id>
        <mirrorOf>*</mirrorOf>
        <url>http://${tomcat_ip}:${tomcat_port}/nexus/content/groups/public</url>
    </mirror>
  </mirrors>
  <profiles>
    <profile>
    <id>nexus</id>
    <repositories>
        <repository>
            <id>central</id>
            <url>http://central</url>
            <releases><enabled>true</enabled></releases>
            <snapshots><enabled>true</enabled></snapshots>
        </repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <id>central</id>
            <url>http://central</url>
            <releases><enabled>true</enabled></releases>
            <snapshots><enabled>true</enabled></snapshots>
        </pluginRepository>
    </pluginRepositories>
    </profile>
  </profiles>
  <activeProfiles>
    <activeProfile>nexus</activeProfile>
  </activeProfiles>
這樣就有一個Maven Repository Server 可用了!
PS:Mac上的maven在mirror中如果用hostname對應ip似乎不正常,在/etc/hosts已經設好了,但是就是連不到,用curl與wget都沒問題…

02 9月 2009

Maven2: Profile

通常在一個專案中,執行的環境通常不㑹只有一個,大多數的情形是3個,真正上線的Production環境,上線前的測試Staging環境,還有就是開發人員自己開發時用的Personal環境,所以在Package時自然應該要有不同的Script來處理不同環境下的設定檔,不然用人工的話很容易發生開發人員將Personal的設定檔包入Production要用的deployment file。Server起不來就算了,就怕滙入了什麼不該滙的,或是砍了什麼不能砍的…

早期使用Ant時,properties跟xml不是用merge就是用replace的,Maven的做法也不例外,只是Ant要寫不少個ant task,但Maven不用,當然,過於思念或割捨不下Ant時,仍然可以透過Ant run在Maven中讓你與Ant相逢。

下面舉個小小的例子,使用profile來區分不同的環境下使用的同名設定檔。 Project的Resources Structure如圖
profile_structure.tu4fAfcdsJOA.jpg
src/main/resources為production環境使用的設定檔,這個目錄也是Maven2預設的resources目錄
src/main/staging為上線前的staging璄環使用,
src/main/personal為開發人員本身所用的設定檔。
3個目錄中皆有一個同名的properties檔案:system.properties,其中內容有所不同
resources/system.properties

profile=production
staging/system.properties
profile=staging
personal/system.properties
profile=personal
而resources再多一個共用的設定檔exist.properties,用以確認在production之外的環境下除同名檔案被覆蓋外,其餘檔案仍正常存在,內容如下
exist=true

再寫一個簡易的JUnit Test Case
@RunWith(BlockJUnit4ClassRunner.class)
public class SampleTest {
   private ResourceBundle systemRb = null;
   private ResourceBundle existRb = null;
   @Before
   public void befor() {
       systemRb = ResourceBundle.getBundle("system");
       existRb = ResourceBundle.getBundle("exist");
   }
  
   @Test
   public void testResources() {
       System.out.println("profile for : "+this.systemRb.getString("profile"));
       System.out.println("check exist : " +this.existRb.getString("exist"));
   }
}
簡單地讀取system.properties及exist.properties,然後將profile及exist的值列出來而已。
再來看pom.xml

   
       
       
           
               src/main/resources
           
       
   

   
       
       
           staging
           
               
                   
                       src/main/staging
                       true
                   
               
           
       
       
       
           personal
           
               
                   
                       src/main/personal
                       true
                   
               
           
       
   

在profiles下定了staging及personal兩個profile,其中要注意的是<filtering>這個tag,雖說Maven是用這個值做為判斷是否要使用merge的依據,但設為true後㑹強制覆蓋同名檔案,這才是我希望的功能。
接下來只要在maven執行時加入-P<profile_id_1>即可,所以試著執行下列command看看結果

$> mvn clean test
-------------------------------------------------------
profile for : production
check exist : true
$> mvn -Pstaging clean test
-------------------------------------------------------
profile for : staging
check exist : true
$> mvn -Ppersonal clean test
-------------------------------------------------------
profile for : personal
check exist : true
三個結果很明顯地因為-P所帶的參數而有不同的結果

其他必需注意的,-P後面可以帶多個profile id,只要用逗號分隔即可,而profile除了區分resource外,還可以指定JDK版本,或是設定properties等作用,例如可以加上<maven.test.skip>true</maven.test.skip>來免除執行test。

12 8月 2009

Spring3 Maven Repository

Spring repositories
由於Spring3還是在測試階段,所以並沒有把library放到多數公開的repository上,所以要取用的話必需加些repository到maven裡

<repositories>
    <repository>
        <id>SpringSource Enterprise Bundle Repository - External Bundle Milestones</id>
        <url>http://repository.springsource.com/maven/bundles/milestone</url>
    </repository>
    <repository>
        <id>SpringSource Enterprise Bundle Repository - SpringSource Bundle Releases</id>
        <url>http://repository.springsource.com/maven/bundles/release</url>
    </repository>
    <repository>
        <id>SpringSource Enterprise Bundle Repository - External Bundle Releases</id>
        <url>http://repository.springsource.com/maven/bundles/external</url>
    </repository>
</repositories>

如果不知道有哪些library可以用,那可以透過下面這url確認一下

http://s3browse.com/explore/repository.springsource.com/maven/bundles/milestone/org/springframework/

15 7月 2009

Maven:Properties

Maven:Properties 本篇是參考MavenPropertiesGuide整理的
Maven在POM中可以用的Properties大約可以分為下列幾種
(1)Build in Properties
${basedir}:取得mvn執行時pom.xml的所在目錄
(2)Project Properties
基本上pom.xml中所有的tag都是算在這類,只要加上project這個prefix即可。
${project.name}:可以拿到<name>yourprojectname</name>中的yourprojectname。
${project.version}:可以拿到<version>buildversion</version>中的buildversion。
${project.build.directory}:可以拿到<build><directory>builddirectory</directory></build>中的builddirectory。
而要取得parent的pom.xml資訊,只要將prefix改為parent.project即可。
(3)System Environment Variables
使用env這個prefix,可以取得系統中的變數。
基本上,在console下打env,顯示出的變數只要加上env.這個“prefix“,就能在pom.xml中使用。
${env.M2_HOME}:可以取得Maven的安裝目錄
${env.CLICOLOR}:可以取得mac的terminal是否要顯示顏色。
(4)Java Environment Properties
請參考http://java.sun.com/javase/6/docs/api/java/lang/System.html#getProperties(),其中所有的Key都可以被pom.xml使用。
比較有機會用到的像是
${os.name}:可以知道系統用的OS為何。
${file.separator}:目錄的分隔符號。

要知道這些Properties到底是什麼值其實也有點麻煩,如果沒在pom.xml裡執行也不能確定到底是什麼,但是Maven本身也沒有提供任何方式可以顯示這些Properties。
所以只好利用Antrun中執行echo這task來顯示囉,這是我最直接能想到的,如果有更好的方法也請不吝告知。
在pom.xml中上加
<build>
	<plugins>
		<plugin>
			<groupId>org.apache.maven.plugins</groupId>
			<artifactId>maven-antrun-plugin</artifactId>
			<version>1.3</version>
			<executions>
				<execution>
					<phase>initialize</phase>
					<configuration>
						<tasks>
							<echo>basedir:${basedir}</echo>
							<echo>project.name:${project.name}</echo>
							<echo>project.version:${project.version}</echo>
							<echo>project.packaging:${project.packaging}</echo>
							<echo>project.build.finalName:${project.build.finalName}</echo>
							<echo>project.build.directory:${project.build.directory}</echo>
							<echo>project.build.outputDirectory:${project.build.outputDirectory}</echo>
							<echo>env.M2_HOME:${env.M2_HOME}</echo>
							<echo>env.CLICOLOR:${env.CLICOLOR}</echo>
							<echo>settings.localRepository:${settings.localRepository}</echo>
							<echo>java.home:${java.home}</echo>
							<echo>java.version:${java.version}</echo>
							<echo>java.vendor:${java.vendor}</echo>
							<echo>os.name:${os.name}</echo>
							<echo>os.arch:${os.arch}</echo>
							<echo>os.version:${os.version}</echo>
						</tasks>
					</configuration>
					<goals>
						<goal>run</goal>
					</goals>
				</execution>
			</executions>
		</plugin>
	</plugins>
</build>
自行修改<tasks>中的<echo> task成你要的,然後只要執行
>$ mvn initialize
就可以看到結果囉。

13 7月 2009

Maven: Create Eclipse Project

用Maven建立Eclipse Project其實頗為容易,第一步用plugin: archetype建立Maven Project,第二步再用plugin: eclipse建立Eclipse要用的設定檔,再來用Eclipse import即可。

1. run mvn archetype:generate
>$ mvn archetype:generate
[INFO] Scanning for projects...
[INFO] Searching repository for plugin with prefix: 'archetype'.
[INFO] ------------------------------------------------------------------------
[INFO] Building Maven Default Project
[INFO]    task-segment: [archetype:generate] (aggregator-style)
[INFO] ------------------------------------------------------------------------
[INFO] Preparing archetype:generate
[INFO] No goals needed for project - skipping
[INFO] Setting property: classpath.resource.loader.class => 'org.codehaus.plexus.velocity.ContextClassLoaderResourceLoader'.
[INFO] Setting property: velocimacro.messages.on => 'false'.
[INFO] Setting property: resource.loader => 'classpath'.
[INFO] Setting property: resource.manager.logwhenfound => 'false'.
[INFO] [archetype:generate {execution: default-cli}]
[INFO] Generating project in Interactive mode
[INFO] No archetype defined. Using maven-archetype-quickstart (org.apache.maven.archetypes:maven-archetype-quickstart:1.0)
Choose archetype:
1: local -> sampleweb-archetype (sampleweb-archetype)
2: internal -> appfuse-basic-jsf (AppFuse archetype for creating a web application with Hibernate, Spring and JSF)
.........
16: internal -> maven-archetype-quickstart ()
17: internal -> maven-archetype-site-simple (A simple site generation project)
18: internal -> maven-archetype-site (A more complex site project)
19: internal -> maven-archetype-webapp (A simple Java web application)
..........
41: internal -> gmaven-archetype-basic (Groovy basic archetype)
42: internal -> gmaven-archetype-mojo (Groovy mojo archetype)
Choose a number:  (1/2/3/4/5/6/7/8/9/10/11/12/13/14/15/16/17/18/19/20/21/22/23/24/25/26/27/28/29/30/31/32/33/34/35/36/37/38/39/40/41/42) 16: : 

可以見到洋洋灑灑42個Template給你選,若沒合意的就用預設16來建吧。

[INFO] artifact org.apache.maven.archetypes:maven-archetype-quickstart: checking for updates from central
Define value for groupId: : org.elliot.web
Define value for artifactId: : test
Define value for version:  1.0-SNAPSHOT: :
Define value for package:  org.elliot.web: :
Confirm properties configuration:
groupId: org.elliot.web
artifactId: test
version: 1.0-SNAPSHOT
package: org.elliot.web
Y: : y
[INFO] ----------------------------------------------------------------------------
[INFO] Using following parameters for creating OldArchetype: maven-archetype-quickstart:RELEASE
[INFO] ----------------------------------------------------------------------------
[INFO] Parameter: groupId, Value: org.elliot.web
[INFO] Parameter: packageName, Value: org.elliot.web
[INFO] Parameter: package, Value: org.elliot.web
[INFO] Parameter: artifactId, Value: test
[INFO] Parameter: basedir, Value: /Users/elliot/Documents/workspacetesting
[INFO] Parameter: version, Value: 1.0-SNAPSHOT
[INFO] ********************* End of debug info from resources from generated POM ***********************
[INFO] OldArchetype created in dir: /Users/elliot/Documents/workspacetesting/test
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESSFUL
[INFO] ------------------------------------------------------------------------

Maven要求你輸入groupId, artifactId, version, package後就會依你指定的artifactId建立一個Project。

2. run mvn eclipse:eclipse
進入該目錄後,執行mvn eclipse:eclipse
>$ cd test
>$mvn eclipse:eclipse
[INFO] Scanning for projects...
[INFO] Searching repository for plugin with prefix: 'eclipse'.
[INFO] ------------------------------------------------------------------------
[INFO] Building test
[INFO]    task-segment: [eclipse:eclipse]
[INFO] ------------------------------------------------------------------------
[INFO] Preparing eclipse:eclipse
[INFO] No goals needed for project - skipping
[INFO] [eclipse:eclipse {execution: default-cli}]
[INFO] Using as WTP server : null
[INFO] Adding default classpath contaigner: org.eclipse.jdt.launching.JRE_CONTAINER
[INFO] Using source status cache: /Users/elliot/Documents/workspacetesting/test/target/mvn-eclipse-cache.properties
[INFO] Not writing settings - defaults suffice
[INFO] Wrote Eclipse project for "test" to /Users/elliot/Documents/workspacetesting/test.
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESSFUL
[INFO] ------------------------------------------------------------------------

再import至Eclipse即可

import import
3. 如果你有裝m2eclipse,那可以略過2改執行mvn eclipse:m2eclipse
>$ mvn eclipse:m2eclipse
[INFO] Scanning for projects...
[INFO] Searching repository for plugin with prefix: 'eclipse'.
[INFO] ------------------------------------------------------------------------
[INFO] Building test
[INFO]    task-segment: [eclipse:m2eclipse]
[INFO] ------------------------------------------------------------------------
[INFO] Preparing eclipse:m2eclipse
[INFO] No goals needed for project - skipping
[INFO] [eclipse:m2eclipse {execution: default-cli}]
[INFO] Using source status cache: /Users/elliot/Documents/workspacetesting/test/target/mvn-eclipse-cache.properties
[INFO] Using as WTP server : null
[INFO] Not writing settings - defaults suffice
[INFO] Wrote Eclipse project for "test" to /Users/elliot/Documents/workspacetesting/test.
[INFO] 
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESSFUL
[INFO] ------------------------------------------------------------------------

一樣,import至Eclipse即可

import

使用Maven久了之後會發現,上列的方式仍有不便,例如Source Code Structure不符你的需求,相關的Plugin及Dependencies都需要一再加入pom.xml中,所以會希望能建立一個自己常用的範本。這時,你需要用的是archetype:create-from-project,然後將該archetype install到你Maven的repository中。簡單來說,用你現有的Project建立一個Template,之後再執行archetype:generate時再選擇你的template即可。

4. run mvn archetype:create-from-project
>$ mvn archetype:create-from-project
[INFO] Scanning for projects...
[INFO] Searching repository for plugin with prefix: 'archetype'.
[INFO] ------------------------------------------------------------------------
[INFO] Building test
[INFO]    task-segment: [archetype:create-from-project] (aggregator-style)
[INFO] ------------------------------------------------------------------------
[INFO] Preparing archetype:create-from-project
[INFO] ------------------------------------------------------------------------
[INFO] Building test
[INFO] ------------------------------------------------------------------------
[INFO] No goals needed for project - skipping
[INFO] Setting property: classpath.resource.loader.class => 'org.codehaus.plexus.velocity.ContextClassLoaderResourceLoader'.
[INFO] Setting property: velocimacro.messages.on => 'false'.
[INFO] Setting property: resource.loader => 'classpath'.
[INFO] Setting property: resource.manager.logwhenfound => 'false'.
[INFO] [archetype:create-from-project {execution: default-cli}]
[INFO] Setting default groupId: org.elliot.web
[INFO] Setting default artifactId: test
[INFO] Setting default version: 1.0-SNAPSHOT
[INFO] Setting default package: org.elliot.web
[INFO] Archetype created in target/generated-sources/archetype
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESSFUL
[INFO] ------------------------------------------------------------------------

Maven會將archetype範本產生在target/generated-sources/archetype目錄下,如果還有需要可以進到該目錄,若沒問題的下可以進行下一步

5. run mvn install
先進入target/generated-sources/archetype後再執行mvn install
>$ cd target/generated-sources/archetype/
>$ mvn install
[INFO] Scanning for projects...
[INFO] ------------------------------------------------------------------------
[INFO] Building test-archetype
[INFO]    task-segment: [install]
[INFO] ------------------------------------------------------------------------
[INFO] [resources:resources {execution: default-resources}]
[WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] Copying 7 resources
[INFO] [resources:testResources {execution: default-testResources}]
[WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] skip non existing resourceDirectory /Users/elliot/Documents/workspacetesting/test/target/generated-sources/archetype/src/test/resources
[INFO] Setting property: classpath.resource.loader.class => 'org.codehaus.plexus.velocity.ContextClassLoaderResourceLoader'.
[INFO] Setting property: velocimacro.messages.on => 'false'.
[INFO] Setting property: resource.loader => 'classpath'.
[INFO] Setting property: resource.manager.logwhenfound => 'false'.
[INFO] [archetype:jar {execution: default-jar}]
[INFO] [archetype:add-archetype-metadata {execution: default-add-archetype-metadata}]
[INFO] [archetype:integration-test {execution: default-integration-test}]
[INFO] [install:install {execution: default-install}]
[INFO] Installing /Users/elliot/Documents/workspacetesting/test/target/generated-sources/archetype/target/test-archetype-1.0-SNAPSHOT.jar to /Users/elliot/.m2/repository/org/elliot/web/test-archetype/1.0-SNAPSHOT/test-archetype-1.0-SNAPSHOT.jar
[INFO] [archetype:update-local-catalog {execution: default-update-local-catalog}]
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESSFUL
[INFO] ------------------------------------------------------------------------
6. run mvn archetype:generate -DarchetypeCatalog=local
再來就可以試者用自已的Template來建立Project了,不過這時要注意,由於Maven將你的Template加入local端的Catalog(存放 archetype的名稱),所以在run plugin:archetype:generate要加個參數指到local端的Catalog。
>$ mvn archetype:generate -DarchetypeCatalog=local
[INFO] Scanning for projects...
[INFO] Searching repository for plugin with prefix: 'archetype'.
[INFO] ------------------------------------------------------------------------
[INFO] Building Maven Default Project
[INFO]    task-segment: [archetype:generate] (aggregator-style)
[INFO] ------------------------------------------------------------------------
[INFO] Preparing archetype:generate
[INFO] No goals needed for project - skipping
[INFO] Setting property: classpath.resource.loader.class => 'org.codehaus.plexus.velocity.ContextClassLoaderResourceLoader'.
[INFO] Setting property: velocimacro.messages.on => 'false'.
[INFO] Setting property: resource.loader => 'classpath'.
[INFO] Setting property: resource.manager.logwhenfound => 'false'.
[INFO] [archetype:generate {execution: default-cli}]
[INFO] Generating project in Interactive mode
[INFO] No archetype defined. Using maven-archetype-quickstart (org.apache.maven.archetypes:maven-archetype-quickstart:1.0)
Choose archetype:
1: local -> sampleweb-archetype (sampleweb-archetype)
2: local -> test-archetype (test-archetype)
Choose a number:  (1/2): 

這時就能看到剛才加入的Template供選擇了囉!

Maven: Basic Concepts(Lifecycle, Phase, Goal)

Lifecycle / Phase / Goal
  • A build lifecycle is made up of phases.
    lifecycle將各phase有順序性的串連起來,所以當你指定執行一個phase時,maven將會執行排在其之前的所有phases.


  • A phase is made up of goals.
    一個Phase可以綁定多個Goals,但一般只有預設的一個Goal會被執行,所以要執行其他的Goal時,
    必需明白指出所要執行Goal。一般來說是以plugin:goal來表示,例如compile:test-compile


  • 說明下上面兩者的差別,例如test-compile這個phase,實際上是要執行compiler:testCompile,但是分別執行的結果如下
  • mvn test-compile
    >$ mvn test-compile
    [INFO] Scanning for projects...
    [INFO] ------------------------------------------------------------------------
    [INFO] Building Maven
    [INFO]    task-segment: [test-compile]
    [INFO] ------------------------------------------------------------------------
    [INFO] [resources:resources {execution: default-resources}]
    [WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!
    [INFO] skip non existing resourceDirectory /Users/elliot/Documents/workspacetesting/test/src/main/resources
    [INFO] [compiler:compile {execution: default-compile}]
    [INFO] No sources to compile
    [INFO] [resources:testResources {execution: default-testResources}]
    [WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!
    [INFO] skip non existing resourceDirectory /Users/elliot/Documents/workspacetesting/test/src/test/resources
    [INFO] [compiler:testCompile {execution: default-testCompile}]
    [INFO] No sources to compile
    [INFO] ------------------------------------------------------------------------
    [INFO] BUILD SUCCESSFUL
    [INFO] ------------------------------------------------------------------------
    
    maven認出test-compile是一個Phase,所以執行了排在test-compile之前的Phase,
    如generate-resources、compile、generate-test-resource,最後在執行完test-compile
    (其實就是compiler:testCompile)後結束。



  • mvn compiler:testCompile
    >$ mvn compiler:testCompile
    [INFO] Scanning for projects...
    [INFO] ------------------------------------------------------------------------
    [INFO] Building Maven
    [INFO]    task-segment: [compiler:testCompile]
    [INFO] ------------------------------------------------------------------------
    [INFO] [compiler:testCompile {execution: default-cli}]
    [INFO] No sources to compile
    [INFO] ------------------------------------------------------------------------
    [INFO] BUILD SUCCESSFUL
    [INFO] ------------------------------------------------------------------------
    
    
    Maven認出這是一個Goal所以只執行了compiler:testCompile就結束,並未執行其他的Goals。



  • Maven預設了三個Lifecycle ,各包涵了下列Phases.
    1. Clean Lifecycle
      • pre-clean
      • clean
      • post-clean
    2. Default Lifecycle
      • validate
      • initialize
      • generate-sources
      • process-sources
      • generate-resources
      • process-resources
      • compile
      • process-classes
      • generate-test-sources
      • process-test-sources
      • process-test-resources
      • test-compile
      • process-test-classes
      • test
      • prepare-package
      • package
      • pre-integration-test
      • integration-test
      • post-integration-test
      • verify
      • install
      • deploy
    3. Site Lifecycle
      • pre-site
      • site
      • post-site
      • site-deploy
    並不是所有的Phase都需要被執行,例如validate,在一般的情形下,單獨執行這個Phase會出現
    No goals needed for project - skipping而結束。
    而有些Phase會因設定的不同而執行不同的Goal,
    例如package,會因為你所設的packaging而執行war:war或jar:jar等不同的Goal。

    28 2月 2007

    Struts2 Note -- (1)struts-tags.tld

    Struts2發佈了2.0.6,下載後沒有注意到一件事,自2.0.6後的版本,struts-tags.tld要自 source code中經maven2 build後才會產生,所以找了老半天還有點火…,還好看了一下core/src/main/resources/META-INF/README.txt,才發現這個版本是要透過maven2才能產生struts-tags.tld,只好自行run mvn來做了,需要的話可以參考Building with Maven,遇上了OutOfMemoryError別忘了為Maven2加上個MAVEN_OPTS=-Xmx512m參數來執行。 我個人是有裝Maven2,所以問題不大,不過如果是希望下載後就能使用而且沒有需求使用Maven2的朋友,還是可能會感到些許不便吧。

    27 2月 2007

    First Struts2 Project with Eclipse and Maven2

    一個基本的Eclipse Struts Project至少需要以下的設定 pom.xml
    <?xml version="1.0"?>
    <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>org.elliot</groupId>
     <artifactId>firststruts</artifactId>
     <packaging>war</packaging>
     <name>firststruts</name>
     <version>1.0-SNAPSHOT</version>
     <url>http://maven.apache.org</url>
     <build>
      <sourceDirectory>${basedir}/src/main/java</sourceDirectory>
      <testSourceDirectory>
       ${basedir}/src/test/java
      </testSourceDirectory>
      <resources>
       <resource>
        <directory>${basedir}/src/main/resources</directory>
       </resource>
      </resources>
      <testResources>
       <testResource>
        <directory>${basedir}/src/test/resources</directory>
       </testResource>
      </testResources>
      <plugins>
       <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
         <source>1.5</source>
         <target>1.5</target>
        </configuration>
       </plugin>
    
       <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-war-plugin</artifactId>
        <version>2.0.2</version>
        <configuration>
         <warName>firststruts</warName>
        </configuration>
       </plugin>
      </plugins>
     </build>
     <dependencies>
      <dependency>
       <groupId>org.apache.struts</groupId>
       <artifactId>struts2-core</artifactId>
       <version>2.0.6</version>
      </dependency>
     </dependencies>
     <repositories>
      <repository>
       <id>Struts2</id>
       <name>Struts2</name>
       <snapshots>
        <enabled>true</enabled>
       </snapshots>
       <url>
        http://people.apache.org/repo/m2-snapshot-repository
       </url>
      </repository>
     </repositories>
    </project>
    
    web.xml
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app version="2.4" 
     xmlns="http://java.sun.com/xml/ns/j2ee" 
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
     xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
     http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
     <display-name>firststruts</display-name>
     <filter>
      <filter-name>struts2</filter-name>
      <filter-class>
       org.apache.struts2.dispatcher.FilterDispatcher
      </filter-class>
     </filter>
     <filter-mapping>
      <filter-name>struts2</filter-name>
      <url-pattern>/*</url-pattern>
     </filter-mapping>
     <jsp-config>
      <taglib>
       <taglib-uri>/struts-tags</taglib-uri>
       <taglib-location>/WEB-INF/struts-tags.tld</taglib-location>
      </taglib>
     </jsp-config>
    </web-app>
    
    resources還需要有struts.properties struts.devMode = true struts.enable.DynamicMethodInvocation = false 然後實做自己的Action extends from com.opensymphony.xwork2.ActionSupport 加入到struts.xml中即可 struts.xml
    <!DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
        "http://struts.apache.org/dtds/struts-2.0.dtd">
    <struts>
        <package name="first" namespace="/" extends="struts-default">
            <action name="first" class="org.elliot.action.FirstAction">
                <result name="Success">/jsp/first/firstActionResult.jsp</result>
            </action>
        </package>
    </struts>
    

    29 1月 2007

    Use xdoclet2 hibernate plugin in Maven2

    (1) Add pluginRepositories element to your pom.xml
    <project>
     <pluginRepositories>
      <pluginRepository>
       <id>codehaus-plugins</id>
       <url>http://dist.codehaus.org/</url>
       <layout>legacy</layout>
       <snapshots>
        <enabled>true</enabled>
       </snapshots>
       <releases>
        <enabled>true</enabled>
       </releases>
      </pluginRepository>
     </pluginRepositories>
    </project>
    
    (2) Add xdoclet2 plugin to pom.xml
    <plugins>
     <plugin>
      <groupId>xdoclet</groupId>
      <artifactId>maven2-xdoclet2-plugin</artifactId>
      <executions>
       <execution>
        <id>xdoclet</id>
        <phase>generate-sources</phase>
        <goals>
         <goal>xdoclet</goal>
        </goals>
       </execution>
      </executions>
      <dependencies>
       <dependency>
        <groupId>xdoclet-plugins</groupId>
        <artifactId>
         xdoclet-plugin-hibernate
        </artifactId>
        <version>1.0.4-SNAPSHOT</version>
       </dependency>
      </dependencies>
      <configuration>
       <configs>
        <config>
         <components>
          <component>
           <classname>
            org.xdoclet.plugin.hibernate.HibernateMappingPlugin
           </classname>
          </component>
         </components>
         <params>
          <version>3.0</version>
         </params>
        </config>
       </configs>
      </configuration>
     </plugin>
    </plugins>
    
    (3) Run mvn compile

    Technorati Tags: , ,