<?xml version="1.0" encoding="utf-8" ?>
<?xml-stylesheet href="http://rss.egloos.com/style/blog.xsl" type="text/xsl" media="screen"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/">
<channel>
	<title>개발을 통한 자기수양 - benelog</title>
	<link>http://benelog.egloos.com</link>
	<description>변화를 응원하기</description>
	<language>ko</language>
	<pubDate>Tue, 29 Sep 2009 23:02:57 GMT</pubDate>
	<generator>Egloos</generator>
	<image>
		<title>개발을 통한 자기수양 - benelog</title>
		<url>http://md.egloos.com/img/samplelogo2.gif</url>
		<link>http://benelog.egloos.com</link>
		<width>80</width>
		<height>80</height>
		<description>변화를 응원하기</description>
	</image>
  	<item>
		<title><![CDATA[ Customer tag library에 대한 테스트 코드 작성 ]]> </title>
		<link>http://benelog.egloos.com/2421450</link>
		<guid>http://benelog.egloos.com/2421450</guid>
		<description>
			<![CDATA[ 
  <p>&nbsp;</p><p>&nbsp;커스텀 태그 라이브러리는 그 실행결과를 확인하는 것이 많이 번거롭습니다. 따로 테스트 코드를 짜지 않는다면, Web Application 를 띄우고&nbsp;커스템 태그를 사용하는 JSP를 직접 실행한 다음에 나오는 텍스트값을 확인해서 눈으로 값이 제대로 찍히는지 검증하고, 틀리면 다시 코드를 고치는 방식을 반복하는 경우도 많습니다. 그리고 보통 커스텀태그에서는 setter로 지정된 속성에 따라서&nbsp;조건분기도 많이 들어가기 때문에 더욱 디버깅이 까다롭습니다. 이 때 위와 같이&nbsp;JSP를 거치지 않고 바로&nbsp;출력될 값을 찎어주고, 검증로직을 추가할 수 있는 테스트 코드를 짠다면 개발할 때 많은 시간이 절약될 것입니다.</p><p>&nbsp;</p><p>&nbsp; <a class="external" title="http://www.docjar.org/docs/api/javax/servlet/jsp/tagext/TagSupport.html" href="http://www.docjar.org/docs/api/javax/servlet/jsp/tagext/TagSupport.html">javax.servlet.jsp.tagext.TagSupport</a>를 상속한 클래스라면, TagSupport.setPageContext 메소드를 활용해서 mock같은 테스트용 객체들을 삽입하면 됩니다.&nbsp;이 메소드를 통해서&nbsp;PageContext와 PageContext.getOut으로 돌려주는 javax.servlet.jsp.JspWriter객체를 모두 mock으로 지정할 수도 있습니다.<br></p><p>&nbsp; Spring에서는 이를 더욱 간편하게 할 수 있는 <a class="external" title="http://static.springsource.org/spring/docs/2.5.6/api/org/springframework/mock/web/MockPageContext.html" href="http://static.springsource.org/spring/docs/2.5.6/api/org/springframework/mock/web/MockPageContext.html">MockPageContext</a>라는 객체를 제공합니다.</p><p><span style="COLOR: #1f497d; FONT-FAMILY: '맑은 고딕'">&nbsp;</span> 이를 활용한 Custom 태그 테스트 코드는 아래와 같이 만들 수 있습니다.</p><p>&nbsp;</p><blockquote><p>&nbsp;&nbsp;ButtonTag tag = new ButtonTag();<br>&nbsp;&nbsp;tag.setFunctionName("alert");<br>&nbsp;&nbsp;tag.setType("basic");<br>&nbsp;&nbsp;<br>&nbsp;&nbsp;PageContext pageContext = new MockPageContext();<br>&nbsp;&nbsp;tag.setPageContext(pageContext);</p><p>&nbsp;&nbsp;assertEquals(TagSupport.EVAL_BODY_INCLUDE, tag.doStartTag());<br>&nbsp;&nbsp;assertEquals(TagSupport.EVAL_PAGE, tag.doEndTag());<br>&nbsp;&nbsp;<strong><u>String output = ((MockHttpServletResponse) pageContext.getResponse()).getContentAsString();</u></strong><br>&nbsp;&nbsp;System.out.println(output);<br>&nbsp;&nbsp;assertTrue(output.contains("&lt;span class='r'&gt;"));<br>&nbsp;&nbsp;//출력된 결과에 대한 추가&nbsp; 검증</p></blockquote><p>&nbsp;</p><br/><br/>tag : <a href="/tag/Spring" rel="tag">Spring</a>,&nbsp;<a href="/tag/Customtag" rel="tag">Customtag</a>,&nbsp;<a href="/tag/unittest" rel="tag">unittest</a>,&nbsp;<a href="/tag/테스트코드" rel="tag">테스트코드</a>,&nbsp;<a href="/tag/스프링" rel="tag">스프링</a>			 ]]> 
		</description>
		<category>기술 자료</category>
		<category>Spring</category>
		<category>Customtag</category>
		<category>unittest</category>
		<category>테스트코드</category>
		<category>스프링</category>

		<comments>http://benelog.egloos.com/2421450#comments</comments>
		<pubDate>Tue, 08 Sep 2009 11:20:01 GMT</pubDate>
		<dc:creator>정상혁</dc:creator>
	</item>
	<item>
		<title><![CDATA[ [Hadoop]Oracle을 사용해 입출력하는 Map-Reduce ]]> </title>
		<link>http://benelog.egloos.com/2271302</link>
		<guid>http://benelog.egloos.com/2271302</guid>
		<description>
			<![CDATA[ 
  <p>&nbsp;&nbsp; Hadoop의 Map-Reduce처리에서는 DB를 바로 연결해서 처리할 수 있는&nbsp; <a class="external" title="http://hadoop.apache.org/core/docs/current/api/org/apache/hadoop/mapred/lib/db/DBInputFormat.html" href="http://hadoop.apache.org/core/docs/current/api/org/apache/hadoop/mapred/lib/db/DBInputFormat.html">DBInputFormat</a>, <a class="external" title="http://hadoop.apache.org/core/docs/current/api/org/apache/hadoop/mapred/lib/db/DBOutputFormat.html" href="http://hadoop.apache.org/core/docs/current/api/org/apache/hadoop/mapred/lib/db/DBOutputFormat.html">DBOutputFormat</a>의 클래스가 제공되고 있습니다.&nbsp;</p><p>&nbsp;&nbsp; 그러나 이 클래스들은 이름이 'DB'가 붙어있는 것이 무색하게 Oracle과 연결해서 사용해보면 에러가 납니다.&nbsp;<a class="external" title="http://hadoop.apache.org/core/docs/current/api/org/apache/hadoop/mapred/lib/db/DBInputFormat.html" href="http://hadoop.apache.org/core/docs/current/api/org/apache/hadoop/mapred/lib/db/DBInputFormat.html">DBInputFormat</a>에서는 웹에서의 페이지 처리 쿼리처럼 데이터를 잘라서 가지고 오기 위해 원래 쿼리에다 LIMIT와 OFFSET 키워드를 붙이는데, 이 것은 Oracle에서는 지원되지 않습니다. 그리고 <a class="external" title="http://hadoop.apache.org/core/docs/current/api/org/apache/hadoop/mapred/lib/db/DBOutputFormat.html" href="http://hadoop.apache.org/core/docs/current/api/org/apache/hadoop/mapred/lib/db/DBOutputFormat.html">DBOutputFormat</a>에서는 insert문의 맨 뒤에 세미콜론(;)을 붙여버리는데, 이것 역시 Oracle의 JDBC를 사용할 때는 에러를 냅니다.</p><p>&nbsp; 따라서, 결국 이 클래스들을 Oracle에서 쓸 수 있도록 상속해서 구현을 해 줄수 밖에 없었습니다. 얼핏 생각하면 쿼리만 바꾸어주면 되는 것이니 메소드 하나만 오버라이딩 해주면 될 것으로 예상했으나, 원래 클래스들의 구조가 그 정도로 단순하지 않았습니다.Inner클래스가 많아서 여러 클래스와 메서드들을 다 overriding해 줄 수 밖에 없었습니다. 더군다나, 새로 상속한 클래스의 내부에서 꼭 호출해야 하는 DBConfiguration클래스의 생성자가 public이 아닌 package private(아무것도 선언안한 디폴트 접근자)인 탓에, 패키지를 원래의 <a class="external" title="http://hadoop.apache.org/core/docs/current/api/org/apache/hadoop/mapred/lib/db/DBInputFormat.html" href="http://hadoop.apache.org/core/docs/current/api/org/apache/hadoop/mapred/lib/db/DBInputFormat.html">DBInputFormat</a>, <a class="external" title="http://hadoop.apache.org/core/docs/current/api/org/apache/hadoop/mapred/lib/db/DBOutputFormat.html" href="http://hadoop.apache.org/core/docs/current/api/org/apache/hadoop/mapred/lib/db/DBOutputFormat.html">DBOutputFormat</a>와 같은 패키지로 맞추어야 하는 불편함도 있었습니다. protected로 선언된 메소드들이 많은 것보면 분명히 상속해서 덮어쓰라고 만들어놓은 클래스 같은데, 막상 그렇게 활용하기에는 간편하지 않았던 것이죠.</p><p>&nbsp; 그리고 또 구조적으로 아쉬운 점은 두 클래스가 같은 DBConfiguration을 보게 있어서 Map에서 입력자료를 얻어오는 DB와 Reduce에서 쓰는 DB가 다를 때는 다시 별도의 클래스를 만들어주어야 한다는 것입니다.</p><p>&nbsp;</p><p>&nbsp; Spring batch에서도&nbsp;<a class="external" title="http://static.springsource.org/spring-batch/apidocs/org/springframework/batch/item/database/JdbcPagingItemReader.html" href="http://static.springsource.org/spring-batch/apidocs/org/springframework/batch/item/database/JdbcPagingItemReader.html">JdbcPagingItemReader</a>라는 약간 유사한 클래스가 있습니다.&nbsp;<a class="external" title="http://hadoop.apache.org/core/docs/current/api/org/apache/hadoop/mapred/lib/db/DBInputFormat.html" href="http://hadoop.apache.org/core/docs/current/api/org/apache/hadoop/mapred/lib/db/DBInputFormat.html">DBInputFormat</a>이 하나의 쿼리에서 가지고 올 데이터를 동시에 여러번 쿼리해서 나누어 가지고 오는 반면에 <a class="external" title="http://static.springsource.org/spring-batch/apidocs/org/springframework/batch/item/database/JdbcPagingItemReader.html" href="http://static.springsource.org/spring-batch/apidocs/org/springframework/batch/item/database/JdbcPagingItemReader.html">JdbcPagingItemReader</a>에서는 부분씩 가지고 오더라도 순차적으로 쿼리를 하는 차이점이 있기는 합니다. 그래도, 페이지 처리 쿼리처럼, 데이터를 나누어서 가지고 오는 쿼리를 제공한다는 점에서는 유사합니다. <a class="external" title="http://static.springsource.org/spring-batch/apidocs/org/springframework/batch/item/database/JdbcPagingItemReader.html" href="http://static.springsource.org/spring-batch/apidocs/org/springframework/batch/item/database/JdbcPagingItemReader.html">JdbcPagingItemReader</a>에서는 내부적으로 <a class="external" title="http://static.springsource.org/spring-batch/apidocs/org/springframework/batch/item/database/PagingQueryProvider.html" href="http://static.springsource.org/spring-batch/apidocs/org/springframework/batch/item/database/PagingQueryProvider.html">PagingQueryProvider</a> 라는 인터페이스를 사용하게 되어 있고, 이 인터페이스는 각 DB종류별로 <a title="class in org.springframework.batch.item.database.support" href="http://benelog.springnote.com/org/springframework/batch/item/database/support/OraclePagingQueryProvider.html">OraclePagingQueryProvider</a>,&nbsp; <a title="class in org.springframework.batch.item.database.support" href="http://benelog.springnote.com/org/springframework/batch/item/database/support/HsqlPagingQueryProvider.html">HsqlPagingQueryProvider</a>, <a title="class in org.springframework.batch.item.database.support" href="http://benelog.springnote.com/org/springframework/batch/item/database/support/MySqlPagingQueryProvider.html">MySqlPagingQueryProvider</a>, , <a title="class in org.springframework.batch.item.database.support" href="http://benelog.springnote.com/org/springframework/batch/item/database/support/SqlServerPagingQueryProvider.html">SqlServerPagingQueryProvider</a>,<a title="class in org.springframework.batch.item.database.support" href="http://benelog.springnote.com/org/springframework/batch/item/database/support/SybasePagingQueryProvider.html">SybasePagingQueryProvider</a> 등의 구현클래스를 가지고 있습니다. Hadoop의 <a class="external" title="http://hadoop.apache.org/core/docs/current/api/org/apache/hadoop/mapred/lib/db/DBInputFormat.html" href="http://hadoop.apache.org/core/docs/current/api/org/apache/hadoop/mapred/lib/db/DBInputFormat.html">DBInputFormat</a>도 이런 구조였다면 이를 응용하려는 개발자가 훨씬 쉽게 클래스 확장방법을&nbsp; 이해했을 것입니다.</p><p>&nbsp; 아뭏든 지금까지 현재 공개된 API만으로는 Hadoop의 DB연결 지원 클래스들은 빈약해 보이고, API도 좋은 설계요건을 갖추었다고 느껴지지는 않습니다. 아무래도 포털 등에서 대용량 데이터를 처리하는 곳에 쓰이다보니 DB와 함께 연결되는 쓰임새가 그리 많지는 않았나봅니다. 더군다나 Oracle에서는 한번도 안 돌려본 클래스가 버젓이 DB...로 시작되는 이름으로 들어간 것 보면 Oracle이 쓰이는 동네와 Hadoop이 사는 곳은 아주 멀리 떨어져 있었던 것 같습니다. 그러나, 앞으로&nbsp; 엔터프라이즈 환경에서도 Hadoop이 쓰이려면 DB와의 integration은 반드시 거쳐야할 다리인 것 같습니다. <a class="external" title="http://www.jaso.co.kr/283" href="http://www.jaso.co.kr/283">Enterprise 시장에서의 mapreduce</a> 링크를 보아도 이미 그런 시도들이 시작된 것을 알 수 있습니다.</p><p>&nbsp;</p><p>&nbsp; 한편,&nbsp; Hadoop의 <a class="external" title="http://hadoop.apache.org/core/docs/current/api/org/apache/hadoop/mapred/FileInputFormat.html" href="http://hadoop.apache.org/core/docs/current/api/org/apache/hadoop/mapred/FileInputFormat.html">FileInputFormat</a>가 Spring batch의 <a class="external" title="http://static.springsource.org/spring-batch/apidocs/org/springframework/batch/item/file/FlatFileItemReader.html" href="http://static.springsource.org/spring-batch/apidocs/org/springframework/batch/item/file/FlatFileItemReader.html">FlatFileItemReader</a>와 유사한 것 등이나 Spring batch도 2.0에서 아직 분산, 동시처리 등을 지원하기 시작했다는 점은 두 프레임웍의 겹치는 지점이 늘어날 수도 있다는 생각도 듭니다. 뭐 아직 Spring batch의 분산지원은 걸음마 단계이기는 합니다만, DB에서 HDFS에 들어가는 파일을 쓸 때 Spring batch의 API를 활용하는 것 깉은 활용법은 시도해 볼만하다고 생각됩니다.</p><p>&nbsp;</p><p>&nbsp;</p><h4>소스</h4><p>&nbsp;</p><h5>OracleInputFormat</h5><blockquote><p>package org.apache.hadoop.mapred.lib.db;<br><br>import java.io.IOException;<br>import java.sql.SQLException;<br><br>import org.apache.hadoop.io.LongWritable;<br>import org.apache.hadoop.mapred.InputSplit;<br>import org.apache.hadoop.mapred.JobConf;<br>import org.apache.hadoop.mapred.RecordReader;<br>import org.apache.hadoop.mapred.Reporter;<br><br>public class OracleInputFormat&lt;T extends DBWritable&gt; extends DBInputFormat&lt;T&gt;{<br><br>&nbsp;&nbsp;&nbsp; private DBConfiguration dbConf = null;<br>&nbsp;&nbsp;&nbsp; private DBInputSplit split;<br><br>&nbsp;&nbsp;&nbsp; @Override<br>&nbsp;&nbsp;&nbsp; public RecordReader&lt;LongWritable,T&gt; getRecordReader(InputSplit split, JobConf job,<br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; Reporter reporter) throws IOException {<br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; dbConf = new DBConfiguration(job);<br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; this.split = (DBInputSplit)split;<br><br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; @SuppressWarnings("unchecked")<br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; Class inputClass = dbConf.getInputClass();<br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; try {<br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; @SuppressWarnings("unchecked")<br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; RecordReader&lt;LongWritable,T&gt; reader = new OracleRecordReader((DBInputSplit) split, inputClass, job);<br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; return reader;<br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; } catch (SQLException ex) {<br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; throw new IOException(ex.getMessage());<br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }<br>&nbsp;&nbsp;&nbsp; }<br><br>&nbsp;&nbsp;&nbsp; public static void setInput(JobConf job, Class&lt;? extends DBWritable&gt; inputClass,<br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; String inputQuery, String inputCountQuery) {<br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; DBInputFormat.setInput(job, inputClass, inputQuery, inputCountQuery);<br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; job.setInputFormat(OracleInputFormat.class);<br>&nbsp;&nbsp;&nbsp; &nbsp;}<br><br>&nbsp;&nbsp;&nbsp; protected class OracleRecordReader extends DBRecordReader{<br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; protected OracleRecordReader(DBInputSplit split, Class&lt;T&gt; inputClass,<br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; JobConf conf) throws SQLException {<br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; super(split, inputClass, conf);<br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }<br><br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; @Override<br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; protected String getSelectQuery() {<br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; long length = 0;<br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; long start = 0;<br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; try{<br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; length = split.getLength();<br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; start = split.getStart();<br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; } catch(IOException e){<br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; throw new IllegalArgumentException<br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; ("cannot read length or start variable from DBInputSplit",e);<br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }<br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; StringBuilder query = new StringBuilder();<br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; query.append(" SELECT * \r\n");<br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; query.append(" FROM (SELECT m.* , ROWNUM rno ");<br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; query.append("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; FROM ( ");<br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; query.append(&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; dbConf.getInputQuery());<br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; query.append("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; )&nbsp; m");<br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; query.append("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; WHERE ROWNUM &lt;= " + start + " + " + length + ")");<br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; query.append(" WHERE RNO &gt; " + start);<br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; System.out.println(query.toString());<br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; return query.toString();<br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }<br>&nbsp;&nbsp;&nbsp; }<br>}</p></blockquote><p>&nbsp;</p><h5>OracleOutputFormat</h5><blockquote><p>package org.apache.hadoop.mapred.lib.db;<br>import org.apache.hadoop.mapred.JobConf;<br><br>public class OracleOutputFormat&lt;K&nbsp; extends DBWritable, V&gt; extends DBOutputFormat&lt;DBWritable, V&gt;{<br>&nbsp;&nbsp;&nbsp; @Override<br>&nbsp;&nbsp;&nbsp; protected String constructQuery(String table, String[] fieldNames) {<br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; if(fieldNames == null) {<br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; throw new IllegalArgumentException("Field names may not be null");<br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }<br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; StringBuilder query = new StringBuilder();<br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; query.append("INSERT INTO ").append(table);<br><br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; if (fieldNames.length &gt; 0 &amp;&amp; fieldNames[0] != null) {<br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; query.append(" (");<br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; for (int i = 0; i &lt; fieldNames.length; i++) {<br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; query.append(fieldNames[i]);<br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if (i != fieldNames.length - 1) {<br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; query.append(",");<br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; query.append(")");<br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }<br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; query.append(" VALUES (");<br><br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; for (int i = 0; i &lt; fieldNames.length; i++) {<br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; query.append("?");<br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if(i != fieldNames.length - 1) {<br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; query.append(",");<br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }<br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; query.append(")");<br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; return query.toString();<br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; }<br>&nbsp;&nbsp;&nbsp; public static void setOutput(JobConf job, String tableName, String... fieldNames) {<br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; DBOutputFormat.setOutput(job, tableName, fieldNames);<br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; job.setOutputFormat(OracleOutputFormat.class);<br>&nbsp;&nbsp;&nbsp; }<br>}</p></blockquote><p>&nbsp;</p><h5>Job 구성 예</h5><p>&nbsp;</p><blockquote><p>public class SampleJob {<br><br>&nbsp;&nbsp;&nbsp; public static void main(String args[]) throws IOException, URISyntaxException{<br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; JobConf conf = new JobConf(SampleJob.class);<br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; initClasspath(conf);<br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; conf.setJobName("sampleJob");<br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; DBConfiguration.configureDB(conf, "oracle.jdbc.driver.OracleDriver",<br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; "jdbc:oracle:thin:@localhost:1525:TEST",<br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; "myuser", "mypassword");<br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; OracleInputFormat.setInput(conf, Query.class,<br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; "SELECT query, category, user_id FROM query_log ",<br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; "SELECT COUNT(*) FROM query_log");<br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; conf.setOutputKeyClass(Query.class);<br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; conf.setOutputValueClass(IntWritable.class);<br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; conf.setMapperClass(SampleMapper.class);<br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; conf.setReducerClass(SampleReducer.class);<br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; conf.setCombinerClass(SampleReducer.class);<br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; OracleOutputFormat.setOutput(conf, "category", "user_id","cnt");<br><br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; JobClient.runJob(conf);<br>&nbsp;&nbsp;&nbsp; }<br><br>&nbsp;&nbsp;&nbsp; private static void initClasspath(JobConf conf) throws URISyntaxException,<br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; IOException {<br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; DistributedCache.addCacheFile(new URI("lib/ojdbc5-11.1.0.6.jar"), conf);<br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; DistributedCache.addFileToClassPath(new Path("lib/ojdbc5-11.1.0.6.jar"), conf);<br>&nbsp;&nbsp;&nbsp; }<br>}</p><p>&nbsp;</p></blockquote><p>&nbsp;</p><p>&nbsp;</p><h4>hadoop의 DBInputFormat 참고자료</h4><p><a href="http://developer.yahoo.net/blogs/hadoop/DBInputFormat.ppt">http://developer.yahoo.net/blogs/hadoop/DBInputFormat.ppt</a></p><p><a href="http://www.cloudera.com/blog/wp-content/uploads/DBInputFormat.pdf">http://www.cloudera.com/blog/wp-content/uploads/DBInputFormat.pdf</a></p><p><a href="http://www.cloudera.com/blog/2009/03/06/database-access-with-hadoop/">http://www.cloudera.com/blog/2009/03/06/database-access-with-hadoop/</a></p><p><a href="http://www.cloudera.com/blog/tag/dbinputformat/">http://www.cloudera.com/blog/tag/dbinputformat/</a></p><br/><br/>tag : <a href="/tag/hadoop" rel="tag">hadoop</a>,&nbsp;<a href="/tag/oracle" rel="tag">oracle</a>,&nbsp;<a href="/tag/Springbatch" rel="tag">Springbatch</a>,&nbsp;<a href="/tag/DBInputFormat" rel="tag">DBInputFormat</a>,&nbsp;<a href="/tag/DBOutputFormat" rel="tag">DBOutputFormat</a>			 ]]> 
		</description>
		<category>기술 자료</category>
		<category>hadoop</category>
		<category>oracle</category>
		<category>Springbatch</category>
		<category>DBInputFormat</category>
		<category>DBOutputFormat</category>

		<comments>http://benelog.egloos.com/2271302#comments</comments>
		<pubDate>Tue, 24 Mar 2009 23:03:54 GMT</pubDate>
		<dc:creator>정상혁</dc:creator>
	</item>
	<item>
		<title><![CDATA[ Java의 auto boxing과 unbox은 어떻게 컴파일될까? ]]> </title>
		<link>http://benelog.egloos.com/2229687</link>
		<guid>http://benelog.egloos.com/2229687</guid>
		<description>
			<![CDATA[ 
  <p>&nbsp; 아래 코드는 <a class="external" title="http://westzero.net/22" href="http://westzero.net/22">프리미티브 타입과 Wrapper 클래스, 자동 Boxing, 자동 UnBoxing</a>이라는 글에 나오는 것을 입력해 본 것입니다. int와 java.lang.Integer객체를 "=="와 "equals()"메소드로 비교하고 있습니다.</p><p>&nbsp;</p><p><img class="attachment" title="AutoBoxingTest.JPG" alt="AutoBoxingTest.JPG" src="http://benelog.springnote.com/pages/2567738/attachments/1118412">&nbsp;</p><p>&nbsp; 위의 코드에서 생성한 .class파일을 역컴파일해보면 아래와 같은 코드가 나옵니다. autoboxing과 unboxing이 어떤 방식으로 이루어 지는지 잘 확인할 수 있습니다. java.lang.Integer가 int로 바뀔 때는 intValue() 메소드, int가 java.lang.Integer로 바뀔 때는 Integer.valueOf()메소드를 사용하고 있습니다. JDK 1.4이하 버전과의 하위호환성을 위해서 이런 방식을 쓰는 것이겠죠.</p><blockquote><p>&nbsp;int a = 1;<br>&nbsp;int b = 1;<br>&nbsp;Integer c = new Integer(1);<br>&nbsp;Integer d = new Integer(1);<br>&nbsp;System.out.println((new StringBuilder("1:")).append(System.identityHashCode(Integer.valueOf(a))).toString());<br>&nbsp;System.out.println((new StringBuilder("2:")).append(System.identityHashCode(Integer.valueOf(b))).toString());<br>&nbsp;System.out.println((new StringBuilder("3:")).append(System.identityHashCode(c)).toString());<br>&nbsp;System.out.println((new StringBuilder("4:")).append(System.identityHashCode(d)).toString());<br>&nbsp;System.out.println((new StringBuilder("5:")).append(a == b).toString());<br>&nbsp;System.out.println((new StringBuilder("7:")).append(c == d).toString());<br>&nbsp;System.out.println((new StringBuilder("8:")).append(c.equals(d)).toString());<br>&nbsp;System.out.println((new StringBuilder("9:")).append(a == c.intValue()).toString());</p></blockquote><p>&nbsp;</p><p>&nbsp; new Integer()로 생성자를 호출하면 매로 새로 객체를 생성하는데, Integer.valueOf()메소드를 사용하면 캐쉬된 값을 사용할 수 있습니다. 이 메소드의 소스를 보면 -128부터 127까지의 static영역에 캐쉬로 쌓아두고 있습니다.</p><p>&nbsp;</p><blockquote><p>&nbsp;static {<br>&nbsp; cache = new Integer[256];<br>&nbsp; for (int i = 0; i &lt; cache.length; i++)<br>&nbsp; cache[i] = new Integer(i - 128);<br>}</p><p>public static Integer valueOf(int i) {<br>&nbsp; if (i &gt;= -128 &amp;&amp; i &lt;= 127)<br>&nbsp; return IntegerCache.cache[i + 128];<br>&nbsp; else<br>&nbsp; return new Integer(i);<br>}</p></blockquote><p>&nbsp;</p><p>&nbsp;처음에 나왔던 저의 Eclipse 캡쳐화면을 보면 findbugs 플러그인에서 new Integer()사용 코드에 대한 경고를 보여주고 있습니다. 자세한 설명을 보니,&nbsp; Integer.valueOf()를 사용할 경우 약 3.5배 정도 실행속도가 빠르다고 하네요.</p><blockquote><p>M P Bx] Method invokes inefficient Number constructor; use static valueOf instead [DM_NUMBER_CTOR]</p><p>Using new Integer(int) is guaranteed to always result in a new object whereas Integer.valueOf(int) allows caching of values to be done by the compiler, class library, or JVM. Using of cached values avoids object allocation and the code will be faster.</p><p>Values between -128 and 127 are guaranteed to have corresponding cached instances and using valueOf is approximately 3.5 times faster than using constructor. For values outside the constant range the performance of both styles is the same.</p><p>Unless the class must be compatible with JVMs predating Java 1.5, use either autoboxing or the valueOf() method when creating instances of Long, Integer, Short, Character, and Byte.</p></blockquote><p>&nbsp;</p><p>&nbsp; 이런 원리들을 잘 염두해 둬서, auto boxing과 unboxing이 사용될 때 필요없는 객체가 생성되지 않는지 유의해야 합니다.</p><p>&nbsp;</p><p>&nbsp; 다음 코드는 Effective Java 2nd Edition의 Item 5 - '불필요한 객체를 생성하지 마라'에 나오는 예제입니다.</p><blockquote><p>Long sum = 0L;<br>for(long i=0;i&lt; Integer.MAX_VALUE;i++){<br>&nbsp;&nbsp; sum += i;<br>}<br>System.out.println(sum);</p></blockquote><p>&nbsp;&nbsp;이 코드를 컴파일한 후 다시 역컴파일 해보면 다음과 같이 나옵니다.</p><blockquote><p>Long sum = Long.valueOf(0L);<br>for(long i = 0L; i &lt; 0x7fffffffL; i++)&nbsp; sum = Long.valueOf(sum.longValue() + i);</p><p>System.out.println(sum);</p></blockquote><p>&nbsp;&nbsp;&nbsp;java.lang.Double.valueOf(double) 메서드는 매번 새로운 객체를 생성하게 되어 있습니다.</p><blockquote><p>public static Double valueOf(double d) {<br>&nbsp;&nbsp;return new Double(d);<br>}</p></blockquote><p>&nbsp;</p><p>&nbsp; 이렇듯 불필요한 객체생성을 막기 위해&nbsp;되도록 primitive type을 선호해야&nbsp;합니다. auto boxing은 Collection이나 Map에 들어가는 요소로 변수가 쓰일 때, generics가 적용한 코드를 작성할 때 등이 적절한 사용의 예입니다. (Effective Java 2nd Edition, Item 49 참조)</p><br/><br/>tag : <a href="/tag/java" rel="tag">java</a>,&nbsp;<a href="/tag/autoboxing" rel="tag">autoboxing</a>			 ]]> 
		</description>
		<category>기술 자료</category>
		<category>java</category>
		<category>autoboxing</category>

		<comments>http://benelog.egloos.com/2229687#comments</comments>
		<pubDate>Mon, 09 Feb 2009 23:21:46 GMT</pubDate>
		<dc:creator>정상혁</dc:creator>
	</item>
	<item>
		<title><![CDATA[ Spring MVC 2.5을 활용한 파일업로드 ]]> </title>
		<link>http://benelog.egloos.com/2228221</link>
		<guid>http://benelog.egloos.com/2228221</guid>
		<description>
			<![CDATA[ 
  <p>&nbsp; 간단한 파일 업로드 기능을 만들어야 할 일이 생겨서, Spring 2.5의 annotation을 이용한 Action에서 이를 처리하게 했습니다. 실무에서 썼던 것을 더 단순한 예제로 재구성해서 정리해봅니다.<br></p><p>&nbsp;&nbsp;Maven의 pom.xml에 파일업로드 기능에서 참조하는 commons-fileupload 라이브러리에 대한 dependency를 추가합니다.</p><blockquote><p>&lt;dependency&gt;<br>&nbsp;&nbsp; &lt;groupId&gt;commons-fileupload&lt;/groupId&gt;<br>&nbsp;&nbsp; &lt;artifactId&gt;commons-fileupload&lt;/artifactId&gt;<br>&nbsp;&nbsp; &lt;version&gt;1.2.1&lt;/version&gt;</p><p>&lt;/dependency&gt;</p></blockquote><p>web.xml에는 applicationContext 파일의 위치를 지정하고, *.do를 스프링에서 처리하도록 설정합니다.</p><p>&lt;servlet&gt;<br>&nbsp;&nbsp; &lt;servlet-name&gt;dispatcher&lt;/servlet-name&gt;<br>&nbsp;&nbsp; &lt;servlet-class&gt;org.springframework.web.servlet.DispatcherServlet&lt;/servlet-class&gt;<br>&nbsp;&nbsp; &lt;init-param&gt;<br>&nbsp;&nbsp;&nbsp;&nbsp; &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;<br>&nbsp;&nbsp; &nbsp; &lt;param-value&gt;classpath:applicationContext.xml&lt;/param-value&gt;<br>&nbsp;&nbsp; &lt;/init-param&gt;<br>&nbsp;&nbsp; &lt;/servlet&gt;<br>&nbsp;&nbsp; &lt;servlet-mapping&gt;<br>&nbsp;&nbsp;&nbsp;&nbsp; &lt;servlet-name&gt;dispatcher&lt;/servlet-name&gt;<br>&nbsp;&nbsp;&nbsp;&nbsp; &lt;url-pattern&gt;*.do&lt;/url-pattern&gt;<br>&nbsp;&nbsp; &lt;/servlet-mapping&gt;</p><p><br></p><p>&nbsp; 업로드 기능을 간단히 테스트할 수 있는 jsp페이지를 만들어봅니다. 단순히 파일 1개를 "file"이라는 변수명으로 업로드 요청을 하는 페이지입니다.</p><blockquote><p>&lt;%@ page language="java" contentType="text/html; charset=UTF-8"<br>&nbsp;&nbsp;&nbsp; pageEncoding="UTF-8"%&gt;<br>&lt;%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%&gt;<br>&lt;%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%&gt;<br>&lt;html&gt;<br>&lt;head&gt;<br>&nbsp;&nbsp;&nbsp; &lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8"&gt;<br>&nbsp;&nbsp;&nbsp; &lt;title&gt;업로드 테스트&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>&lt;form action="/study/upload.do" method="post" enctype="multipart/form-data"&gt;<br>&lt;p&gt;<br>&nbsp;&nbsp;&nbsp; &lt;label for="file"&gt;파일1 &lt;/label&gt;<br>&nbsp;&nbsp;&nbsp; &lt;input type="file" name="file"&gt;<br>&lt;/p&gt;<br>&lt;p&gt;<br>&nbsp;&nbsp;&nbsp; &lt;input type="submit" value="전송"/&gt;<br>&lt;/p&gt;<br>&lt;/form&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</p></blockquote><p><br></p><p>&nbsp;그리고 applicationContext파일을 아래와 같이 선언합니다.DefaultAnnotationHandlerMapping을 이용해서 annotation을 이용한 Controller 설정을가능하게 합니다. &lt;context:component-scan/&gt; 태그를 사용해서, 설정을 scan할 패키지를지정합니다.&nbsp;그리고, 파일이 저장될 디렉토리는 ${repository.path} 속성으로 표시했습니다. Maven의 resource filter기능을 이용해서 실행환경에 따라 다른 값을 넣게 하면 편리합니다.<br></p><blockquote><p>&lt;?xml version="1.0" encoding="UTF-8"?&gt;<br>&lt;beans xmlns="http://www.springframework.org/schema/beans"<br>&nbsp;&nbsp;&nbsp; xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"<br>&nbsp;&nbsp;&nbsp; xmlns:context="http://www.springframework.org/schema/context"<br>&nbsp;&nbsp;&nbsp; xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd<br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"&gt;<br><br>&nbsp;&nbsp;&nbsp; &lt;bean&nbsp; class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"&gt;<br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &lt;property name="alwaysUseFullPath" value="true"/&gt;<br>&nbsp;&nbsp;&nbsp; &lt;/bean&gt;<br>&nbsp;&nbsp;&nbsp; &lt;bean id="multipartResolver"<br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/&gt;<br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;<br>&nbsp;&nbsp;&nbsp; &lt;bean id="respository" class="study.repository.FileRepository"&gt;<br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &lt;constructor-arg value="${repository.path}" /&gt;<br>&nbsp;&nbsp;&nbsp; &lt;/bean&gt;<br>&nbsp;&nbsp;&nbsp; &lt;context:component-scan&nbsp;&nbsp;&nbsp; base-package="study.action"/&gt;<br>&lt;/beans&gt;<br></p></blockquote><p><br></p><p>&nbsp; 실제적인 파일의 저장기능을 담당하는 클래스인 FileRepository에서는 간단하게 UIDD를 이용해서 키를 생성하고 path필드로 지정된 디렉토리에 저장을 해줍니다.&nbsp; <br></p><p><br></p><blockquote><p>package study.repository;<br><br>import java.io.File;<br>import java.io.IOException;<br>import java.util.UUID;<br><br>import org.springframework.web.multipart.MultipartFile;<br><br>public class FileRepository {<br>&nbsp;&nbsp;&nbsp; private String path;<br>&nbsp;&nbsp;&nbsp; public FileRepository(String path) {<br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; this.path = path;<br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; File saveFolder = new File(path);<br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; if(!saveFolder.exists() || saveFolder.isFile()){<br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; saveFolder.mkdirs();<br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;<br>&nbsp;&nbsp;&nbsp; }<br>&nbsp;&nbsp;&nbsp;<br>&nbsp;&nbsp;&nbsp; public String saveFile(MultipartFile sourcefile) throws IOException{<br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; if ((sourcefile==null)||(sourcefile.isEmpty())) return null;<br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; String key = UUID.randomUUID().toString();<br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; String targetFilePath = path+"/"+ key;<br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; sourcefile.transferTo(new File(targetFilePath));<br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; return key;<br>&nbsp;&nbsp;&nbsp; }<br>}<br></p></blockquote><p>&nbsp; 추가적으로 키값을 넣어주면 파일을 반환해주는 메소드나, 파일의 종류나 날짜에 따라서 하위 디렉토리를 구분해서 생성하는 기능도 넣을 수있을 것입니다. 그리고 더 확장한다면, 따로 주요 메서드를 선언한 Repository 라는&nbsp;인터페이스를 정의하고, DB를저장소로 활용하는 DbRepository 와 같이 이름 붙인 구현 클래스도 만들어 볼 수 있겠습니다.&nbsp; <br></p><p>&nbsp; 그리고 @Controller&nbsp;, @RequestMapping,&nbsp;@RequestParam, @Autowired의 Anntation을활용해서 Controller 클래스를 작성합니다. 업로드 후 화면에 키값만 뿌도록 해서 java.io.Writer클래스를 화면출력을 위해 사용했습니다.<br></p><p><br></p><blockquote><p>package study.action;<br><br>import java.io.IOException;<br>import java.io.Writer;<br>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.stereotype.Controller;<br>import org.springframework.web.bind.annotation.RequestMapping;<br>import org.springframework.web.bind.annotation.RequestParam;<br>import org.springframework.web.multipart.MultipartFile;<br><br>import study.repository.FileRepository;<br><br>@Controller<br>public class FileAction {<br>&nbsp;&nbsp;&nbsp;&nbsp; private FileRepository respository;<br>&nbsp;&nbsp;&nbsp;<br>&nbsp;&nbsp;&nbsp; @Autowired<br>&nbsp;&nbsp;&nbsp; public void setRespository(FileRepository respository) {<br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; this.respository = respository;<br>&nbsp;&nbsp;&nbsp; }<br>&nbsp;&nbsp;&nbsp; @RequestMapping("/upload.do")<br>&nbsp;&nbsp;&nbsp; public void execute(@RequestParam("file") MultipartFile file,<br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; Writer out) throws IOException{<br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; String key = respository.saveFile(file);<br>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; out.write(key);<br>&nbsp;&nbsp;&nbsp; }<br>}</p></blockquote><p>&nbsp;import 절을&nbsp; 빼면, 정말 몇줄 안됩니다.&nbsp; Struts, Webwork등 다른 MVC프레임웍의 Action단보다 더유연하고, 생산성도 높아 보입니다. POJO 클래스이니 테스트코드 작성도 더 쉬워보입니다. MultipartFile 클래스는 <a class="external" title="http://static.springsource.org/spring/docs/3.0.0.M1/javadoc-api/org/springframework/mock/web/MockMultipartFile.html" href="http://static.springsource.org/spring/docs/3.0.0.M1/javadoc-api/org/springframework/mock/web/MockMultipartFile.html">MockMultiPartFile</a>를 이용해서 테스트하면 됩니다. <a class="external" title="http://chanwook.tistory.com/758" href="http://chanwook.tistory.com/758">최근 로드존슨이 인터뷰에서 한 말</a>에 따르면 기존 Spring MVC의 Controller interface는 삭제될 것이라고 하네요.<br></p><p><br></p><h4>Spring MVC 2.5 관련 자료<br></h4><p><a href="http://www.infoq.com/articles/spring-2.5-ii-spring-mvc">http://www.infoq.com/articles/spring-2.5-ii-spring-mvc</a><br></p><p><a class="external" title="스프링 2.5 애노테이션 기반 MVC 예제" href="http://chanwook.tistory.com/576"><span style="COLOR: #0066cc">스프링 2.5 애노테이션 기반 MVC 예제</span></a><br></p><p style="MARGIN-LEFT: 2em"><a href="http://springtutorial.googlecode.com/svn/trunk/moimApp/src/spring/tutorial/web/MoimController.java"><span style="COLOR: #0066cc">http://springtutorial.googlecode.com/svn/trunk/moimApp/src/spring/tutorial/web/MoimController.java</span></a><br></p><p><a class="external" title="http://steelheart.kr/tc/173" href="http://steelheart.kr/tc/173"><span style="COLOR: #0066cc">Spring 2.5 Annotation기반 Controller 끄적거림</span></a><br></p><p><a class="external" title="http://steelheart.kr/tc/entry/using-web-argument-resolver?category=0" href="http://steelheart.kr/tc/entry/using-web-argument-resolver?category=0">Annotation기반 컨트롤러에 custom argument 적용하기 (WebArgumentResolver)</a><br></p><p><u><a class="external" title="Annotated Spring MVC Controller !! " href="http://chanwook.tistory.com/548"><span style="COLOR: #0066cc">Annotated Spring MVC Controller !!</span></a></u><br></p><p><a title="PermaLink :: Annotation-based controller configuration" href="http://benelog.springnote.com/1291"><span style="COLOR: #0066cc">Annotation-based controller configuration</span></a><br></p><p><a class="external" title="http://corund.egloos.com/1815311" href="http://corund.egloos.com/1815311">Spring Framework 2.5의 Annotation based Controller의 메서드 파라미터에서 주의점</a><br></p><p><br></p><br/><br/>tag : <a href="/tag/SpringMVC" rel="tag">SpringMVC</a>,&nbsp;<a href="/tag/annotation" rel="tag">annotation</a>			 ]]> 
		</description>
		<category>기술 자료</category>
		<category>SpringMVC</category>
		<category>annotation</category>

		<comments>http://benelog.egloos.com/2228221#comments</comments>
		<pubDate>Sun, 08 Feb 2009 14:48:03 GMT</pubDate>
		<dc:creator>정상혁</dc:creator>
	</item>
	<item>
		<title><![CDATA[ FindBugs + Eclipse + Maven2 + Hudson ]]> </title>
		<link>http://benelog.egloos.com/2079841</link>
		<guid>http://benelog.egloos.com/2079841</guid>
		<description>
			<![CDATA[ 
  <p>&nbsp; <a class="external" title="http://findbugs.sourceforge.net/" href="http://findbugs.sourceforge.net/">FindBugs</a>를 이용한 코드검사를 Maven2을 통해 실행하고, Hudson을 통해 확인하는 설정을 정리해 봅니다. Hudson을 설치하는데 필요한 정보를 추가로 얻고 싶으신 분들은 <a href="http://benelog.springnote.com/pages/1822522">http://benelog.springnote.com/pages/1822522</a> 페이지에 모아진 링크를 참조하시면 어렵지 않게 진행하실 수 있으실 것입니다.<br></p><p>&nbsp;&nbsp; Eclipse에서 findbugs로 코드검사를 해볼 수 있는 툴은 <a href="http://findbugs.cs.umd.edu/eclipse/">http://findbugs.cs.umd.edu/eclipse/</a> 를 update site로 지정하면 설치할 수 있습니다.&nbsp;설치가 잘 되었다면 소스 폴더를 선택하고 마우스 우클릭을 하면 'Find Bugs'라는 메뉴가 생긴 것이 보일 것입니다. 그 메뉴를 통해 원하는 프로젝트를 검사하고, Bug Explorer 탭을 선택하보면 아래와 같은 화면이 나옵니다.<br></p><p><br></p><p><img class="attachment" title="EclipseFindBugs.JPG" alt="EclipseFindBugs.JPG" src="http://benelog.springnote.com/pages/1855102/attachments/1117678"></p><p>&nbsp;Bug Explorer 탭에서는 버그를 유형별로 정리해서 보여주고, 소스탭에서는 해당하는 코드에 벌레 모양 아이콘을 찍어줍니다.그리고 Problems 창에서는 Eclipse에서 잡아내는 다른 경고처럼 warning으로 해당 소스를 표시해 줍니다. BugDetails 탭을 누르면 버그에 대한 자세한 설명도 볼 수 있습니다.</p><p>&nbsp; 프로젝트의 Properties 메뉴에서 FindBugs 설정란으로 가면 검사할 규칙 등을 선택할 수 있습니다.</p><p><img class="attachment" title="EclipseFindBugsConfig.JPG" alt="EclipseFindBugsConfig.JPG" src="http://benelog.springnote.com/pages/1855102/attachments/1117798"></p><p><br></p><p>&nbsp;이 설정화면에서 'Run FindBugs automatically'를 선택하면, 소스가 바뀔 때마다 자동으로 검사를 수행해줍니다. 이 기능이 선택되어 있지 않다면, 지적된 소스를 수정해도 다시 수동으로 검사를 돌려야지 경고메시지 지워지므로,이클립스가 아주 느리다는 느낌이 안 들정도라면 선택하는 것이 좋습니다.</p><p>&nbsp; Detector Configuration 탭에서는 검사할 규칙들을 지정할 수 있고, Reporter configuration 탭에서는 보고해 줄 버그의 경고단계와 분류를 선택할 수 있습니다.</p><p>&nbsp; <img class="attachment" title="EclipseFindBugsConfig2.JPG" alt="EclipseFindBugsConfig2.JPG" src="http://benelog.springnote.com/pages/1855102/attachments/1117868"></p><p><br></p><p>Filter files 탭에서는 별도의 XML파일로 선언된 포함하거나 제외시킬 버그와 파일에 대한 설정을 가지고 올 수 있습니다.</p><p><br></p><p><img class="attachment" title="EclipseFindBugsConfig3.JPG" alt="EclipseFindBugsConfig3.JPG" src="http://benelog.springnote.com/pages/1855102/attachments/1117876?dummy=1232688502468"></p><p><br></p><p>&nbsp;아래에 자세히 설명하겠지만,&nbsp; Maven 설정에서 참조하는 findBugsExclude.xml을 Eclipse plugin에서도 똑같이 지정해서 Maven과 Eclipse에서 같은 기준으로&nbsp; 검사가 수행되도록 했습니다.</p><p><br></p><p>&nbsp; Maven2의 <a class="external" title="http://mojo.codehaus.org/findbugs-maven-plugin/" href="http://mojo.codehaus.org/findbugs-maven-plugin/">findbugs-maven-plugin</a>은&nbsp; pom.xml에 아래와 같이 설정됩니다.</p><p><br></p><blockquote><p>&lt;plugin&gt;<br>&nbsp; &nbsp;&lt;groupId&gt;org.codehaus.mojo&lt;/groupId&gt;<br>&nbsp;&nbsp;&nbsp; &nbsp;&lt;artifactId&gt;findbugs-maven-plugin&lt;/artifactId&gt;<br>&nbsp;&nbsp; &nbsp; &lt;version&gt;1.2.1&lt;/version&gt;<br>&nbsp;&nbsp; &nbsp; &lt;configuration&gt;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&lt;findbugsXmlOutput&gt;true&lt;/findbugsXmlOutput&gt;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;findbugsXmlWithMessages&gt;true&lt;/findbugsXmlWithMessages&gt;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;xmlOutput&gt;true&lt;/xmlOutput&gt;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;excludeFilterFile&gt;${basedir}/findBugsExclude.xml&lt;/excludeFilterFile&gt;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;<br>&nbsp;&nbsp;&nbsp; &lt;/configuration&gt;<br>&lt;/plugin&gt;</p></blockquote><p><br></p><p>&nbsp; 위의 설정에 들어가는 속성들에 대해서는 <a class="external" title="http://mojo.codehaus.org/findbugs-maven-plugin/findbugs-mojo.html" href="http://mojo.codehaus.org/findbugs-maven-plugin/findbugs-mojo.html">findbugs-maven-plugin 설명 페이지</a>에서 자세한 내용을 보실 수 있습니다.</p><p>&nbsp; 저는 제외할 검사규칙을 지정하기 위해서 excludeFilterFile속성에 findBugsExclude.xml을 지정했습니다.</p><p>findBugsExclude.xml의 내용은 아래와 같이 설정했습니다.</p><p><br></p><blockquote><p>&lt;FindBugsFilter&gt;<br>&nbsp;&nbsp;&nbsp; &lt;Match&gt;<br>&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &lt;Bug code="Se,SnVI,Dm" /&gt;<br>&nbsp;&nbsp;&nbsp; &lt;/Match&gt;<br>&lt;/FindBugsFilter&gt;</p></blockquote><p>&nbsp; 제외할 것을 선언하는 파일에 이렇게 적었으니 Bug code가 "Se,SnVI,Dm"에 해당하는 버그검사는 제외한다는 의미입니다. Filter의 설정 방법에 대해서는 <a class="external" title="http://mojo.codehaus.org/findbugs-maven-plugin/findbugs-mojo.html" href="http://mojo.codehaus.org/findbugs-maven-plugin/findbugs-mojo.html">findbugs의 매뉴얼</a>을 참조하시면 됩니다.</p><p>&nbsp; 버그 코드 중 Se,SnVI는 serialVersionUID에 관한 것이고 Dm은 String.toUpperCase 등의 메소드에서 Local설정을 권유하는 검사입니다. &nbsp; (<a class="external" title="http://findbugs.sourceforge.net/bugDescriptions.html" href="http://findbugs.sourceforge.net/bugDescriptions.html">버그 코드에 대한 설명 페이지</a> 참조)</p><p>&nbsp;이렇게 설정을 하고 mvn findbugs:findbugs로 maven을 실행시키면 필요한 라이브러리들을 다운로드 받고 빌드가실행됩니다. 실행이 성공했다면 목적지 폴더에 findbugs.xml과 findbugsXml.xml파일이 생성이 되었을 것입니다.</p><p><br></p><p>&nbsp; 이것을 Hudson을 통해서 보기 위해서는 Hudson에서도 findbugs plugin을 설치해야 됩니다.</p><p>&nbsp;Hudson 첫 화면에서 Manage Hudson - Manage Plugins 메뉴를 찾아갑니다. Available 탭에서findbugs를 선택하고 화면 우측하단의 'install'버튼을 누르면 Hudson이 알아서 라이브러리를 다운 받아줍니다.설치한 plug-in이 실행되기 위해서는 Hudson을 재시작해야 합니다.</p><p>&nbsp; 그런 다음에 findbugs를 적용하고자 하는 프로젝트에 가서 Configure메뉴를 선택하면 아래와 같이 Publish FindBugs Analysis Result라는 부분이 추가된 것을 보실 수 있을 것입니다.</p><p><br></p><p style="TEXT-ALIGN: center"><img class="attachment" title="fingbugs_config.JPG" alt="fingbugs_config.JPG" src="http://benelog.springnote.com/pages/1855102/attachments/810964"></p><p>&nbsp; 이것을 선택하고 원하는 기준값이 있을 경우 입력한 뒤에 "save'버튼을 누르고 build를 해보면 됩니다. 물론 build에는 findbugs:findbugs goal이 포함되어야 하겠죠.</p><p>&nbsp; 빌드가 성공하는 것을 보고 프로젝트의 메뉴를 보면 FindBugs Warnings라는 메뉴가 추가된 것을 확인하실 수 있습니다.</p><p style="TEXT-ALIGN: center"><img class="attachment" title="findbugs_menu.JPG" alt="findbugs_menu.JPG" src="http://benelog.springnote.com/pages/1855102/attachments/810994"></p><p>&nbsp; 그 메뉴를 누르면 생성된 보고서가 보입니다.</p><p style="TEXT-ALIGN: center"><img class="attachment" title="findbugs_report.JPG" alt="findbugs_report.JPG" src="http://benelog.springnote.com/pages/1855102/attachments/811002"><br></p><p>&nbsp; warning이 존재할 경우 건수를 클릭하면 해당하는 클래스들이 나오고, 클래스를 선택하면 소스에서 warning을 발생시키는 부분까지 보여줍니다.</p><p>&nbsp;만약 hudson의 findbugs plugin을 실행할 때 Cannot find setter nor field inorg.apache.maven.plugins.site.SiteMojo for 'xmlOutput' 와 같은 에러가 난다면 <a class="external" title="http://benelog.egloos.com/2208375" href="http://benelog.egloos.com/2208375">Hudson plugin 수동으로 빌드&amp;업로드</a>를 참조해서 최신 버전으로 플러그인을 업데이트 해보시기 바랍니다.</p><p><br></p><h4>관련 자료</h4><ul><li><a class="external" title="http://okjsp.tistory.com/1165643579" href="http://okjsp.tistory.com/1165643579">Sun Techdays 2008 Lightning Talk 발표자료; findbugs</a><br></li><li><a class="external" title="http://okjsp.tistory.com/1165643626" href="http://okjsp.tistory.com/1165643626">Hudson의 Findbugs 플러그인 이용하기</a></li><li><a class="external" title="http://okjsp.tistory.com/1165643570" href="http://okjsp.tistory.com/1165643570">findbugs eclipse plugin 설치</a></li><li><a class="external" title="http://www.buggymind.com/177" href="http://www.buggymind.com/177">FindBugs: 코드의 정적 분석을 통한 버그 탐색</a> : 동영상 강연을 보니 구글에서도 이 도구를 사용하고 있다고 합니다.<br></li></ul><br/><br/>tag : <a href="/tag/FindBugs" rel="tag">FindBugs</a>,&nbsp;<a href="/tag/Maven" rel="tag">Maven</a>,&nbsp;<a href="/tag/Hudson" rel="tag">Hudson</a>,&nbsp;<a href="/tag/Eclipse" rel="tag">Eclipse</a>			 ]]> 
		</description>
		<category>기술 자료</category>
		<category>FindBugs</category>
		<category>Maven</category>
		<category>Hudson</category>
		<category>Eclipse</category>

		<comments>http://benelog.egloos.com/2079841#comments</comments>
		<pubDate>Fri, 23 Jan 2009 22:51:00 GMT</pubDate>
		<dc:creator>정상혁</dc:creator>
	</item>
	<item>
		<title><![CDATA[ EMMA + Eclipse + Maven2 + Hudson ]]> </title>
		<link>http://benelog.egloos.com/2212119</link>
		<guid>http://benelog.egloos.com/2212119</guid>
		<description>
			<![CDATA[ 
  <p>&nbsp; <a class="external" title="http://emma.sourceforge.net/" href="http://emma.sourceforge.net/">EMMA</a>는 테스트코드가 검증해 주는&nbsp;코드영역에 대해서 보고해 주는 도구입니다. 전체 코드 중 몇 %가 테스트 코드를 거쳐가고 있는지 쉽게 수치를 낼 수 있습니다.</p><p>&nbsp;&nbsp;EMMA의 &nbsp;Eclipse plugin인 EclEmma는 <a class="external" title="http://update.eclemma.org/" href="http://update.eclemma.org/">http://update.eclemma.org/</a>를 plugin의 update site로 지정하면 설치할 수 있습니다.&nbsp; 설치 후 프로젝트에서 우클릭-Coverage As - JUnit Test 메뉴를 선택하면 전체 Junit Test를 실행하고, Test Coverage에 대한 보고서를 생성해 줍니다.</p><p>&nbsp;</p><p><img class="attachment" title="EclipseEmmaMenu.JPG" alt="EclipseEmmaMenu.JPG" src="http://benelog.springnote.com/pages/2540462/attachments/1108872"></p><p>&nbsp; 실행결과는 아래와 같이 코드창에서도 테스트 코드가 거쳐가는 곳과 아닌 곳을 색깔별로 표시해 주고, 패키지별, 클래스별로도 coverage 수치를 보여줍니다.</p><p><img title="images/screen.png" alt="images/screen.png" src="http://update.eclemma.org/images/screen.png"></p><p style="TEXT-ALIGN: center">(이미지 출처: <a href="http://update.eclemma.org/">http://update.eclemma.org/</a> 에서)</p><p>&nbsp;</p><p>&nbsp; EMMA의 Maven2 plugin인 <a class="external" title="http://mojo.codehaus.org/emma-maven-plugin/" href="http://mojo.codehaus.org/emma-maven-plugin/">Emma Maven Plugin Maven</a>을&nbsp; pom.xml파일의 reporting 선언에 아래와 같은 설정을 추가합니다.</p><blockquote><p>&lt;reporting&gt;<br>&nbsp; &lt;plugins&gt;<br>&nbsp;&nbsp; ...<br>&nbsp;&nbsp;&nbsp; &lt;plugin&gt;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;groupId&gt;org.codehaus.mojo&lt;/groupId&gt;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;artifactId&gt;emma-maven-plugin&lt;/artifactId&gt;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;/plugin&gt;<br>&nbsp;&nbsp;&nbsp; &lt;/plugins&gt;<br>&lt;/reporting&gt;</p></blockquote><p>&nbsp;</p><p><a class="external" title="http://hudson.gotdns.com/wiki/display/HUDSON/Emma+Plugin " href="http://hudson.gotdns.com/wiki/display/HUDSON/Emma+Plugin%20">Hudson의 위키에 있는 Emma plugin 설명페이지</a>나 <a class="external" title="http://mojo.codehaus.org/emma-maven-plugin/usage.html" href="http://mojo.codehaus.org/emma-maven-plugin/usage.html">Maven의 emma-plugin 설명페이지</a>를 보면 build절에도 plugin 설정을 추가하라고 되어있는데, 그렇게 하지 않아도 잘&nbsp; 실행이 되었습니다. &nbsp;오히려 그렇게 추가를 하니, mvn test site처럼 test와 site phrase가 같이 돌아갈 때 아래와 같은 에러가 발생했습니다.</p><p>&nbsp;</p><blockquote><p>java.lang.IllegalStateException: class [......] appears to be instrumented already</p></blockquote><p>&nbsp; Emma plugin 설정을 reporting 부분에 넣으면 테스트가 실행되므로 일부러 test phrase를 넣어줄 필요는 없습니다. 즉 이 때는 mvn site만 돌려주시면 테스트 결과와 Coverage Report를 모두 얻을 수 있습니다.&nbsp; emma plugin이 있을 때 'mvn test site'로 실행시켜서 테스트가 두번 돌면 Hudson에서 보고하는 테스트 개수도 2번씩 중복 집계가 되므로 더 혼동만 줍니다.</p><p>&nbsp; <a class="external" title="http://mojo.codehaus.org/emma-maven-plugin/usage.html" href="http://mojo.codehaus.org/emma-maven-plugin/usage.html">Maven의 emma-plugin 설명페이지</a>에 따르면,&nbsp; maven-surefire-plugin 설정에서 별도의 JVM으로 테스트를 실행시키위해 forkMode를 always로 설정하는 것은 중요하다고 합니다. EMMA가 JVM의 종료 때도 기록을 하기 때문에 그렇다는군요. 다음과 같이 설정합니다.</p><blockquote><p>&lt;plugin&gt;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;artifactId&gt;maven-surefire-plugin&lt;/artifactId&gt;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;inherited&gt;true&lt;/inherited&gt;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;configuration&gt;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;forkMode&gt;always&lt;/forkMode&gt;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;reportFormat&gt;xml&lt;/reportFormat&gt;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;/configuration&gt;<br>&lt;/plugin&gt;</p></blockquote><p>&nbsp; 이렇게 Maven을 통해 생성한 리포트를&nbsp; Huson으로 보기 위해서는 <u><strong>Manage Hudson&gt;Manage Plugins</strong></u> 메뉴에서 Hudson Emma plugin을 설치하고 Hudson을 재시작합니다.</p><p>&nbsp;설치가 잘 되었다면, 프로젝트의 Configure 메뉴에서 EMMA의 보고서에 대해서 설정할 수 있는 항목이 생깁니다.</p><p><img class="attachment" title="HudsonEmmaConfig.JPG" alt="HudsonEmmaConfig.JPG" src="http://benelog.springnote.com/pages/2540462/attachments/1118092"></p><p>&nbsp;여기에서 Emma XML report 항목에 workspace를 기준으로 한 상대적인 경로로 coverage.xml의 위치를 지정해줍니다. <a class="external" title="http://hudson.gotdns.com/wiki/display/HUDSON/Emma+Plugin " href="http://hudson.gotdns.com/wiki/display/HUDSON/Emma+Plugin%20">Hudson의 위키에 있는 Emma plugin 설명페이지</a>에 보면 이 항목이 target/site/emma/coverage.xml으로 되어 있어서 혼동이 오기 쉬운데, trunk와 같은 Local module directory를 반드시 포함시켜줘야 합니다. 보통 SVN을 쓸 때 프로젝트 설정에서 별도로 지정을 하지 않으면 trunk같은 SVN의 path의 마지막 디렉토리가 Local module directory로 지정됩니다.</p><p><img class="attachment" title="hudsonSvnConfig.JPG" alt="hudsonSvnConfig.JPG" src="http://benelog.springnote.com/pages/2540462/attachments/1118132"></p><p>&nbsp; Emma 보고서 설정란에서 the work space root라는 링크를 눌러도 금방 확인 할 수 있습니다.</p><p>&nbsp; 위와 같이 설정된 프로젝트를 build하면 빌드의 맨 끝에 Recording Emma reports trunk/target/site/emma/coverage.xml 와 같은 메시지가 Console out 화면에서 뜰 것입니다. &nbsp;그렇게 생성된 보고서는 <u><strong>프로젝트명&gt;빌드번호&gt;Coverage Report</strong></u> 메뉴에서 보실 수 있습니다.</p><p>&nbsp;</p><p style="TEXT-ALIGN: center"><img class="attachment" title="HudsonEmmaMenu.JPG" alt="HudsonEmmaMenu.JPG" src="http://benelog.springnote.com/pages/2540462/attachments/1118222"></p><p><img class="attachment" title="HudsonEmmaReport.JPG" alt="HudsonEmmaReport.JPG" src="http://benelog.springnote.com/pages/2540462/attachments/1118226"></p><p>&nbsp; 만약 Hudson에서 Emma를 실행한 빌드번호의 메뉴에서 'Coverage Report'라는 메뉴가 보이지 않는다면 <a class="external" title="http://benelog.egloos.com/2208375" href="http://benelog.egloos.com/2208375">Hudson plugin 수동으로 빌드&amp;업로드</a>를 참조해서 최신 버전으로 플러그인을 업데이트 해보시기 바랍니다.</p><p>&nbsp; &nbsp;</p><p>&nbsp;</p><p>&nbsp;</p><br/><br/>tag : <a href="/tag/EMMA" rel="tag">EMMA</a>,&nbsp;<a href="/tag/Eclipse" rel="tag">Eclipse</a>,&nbsp;<a href="/tag/Maven" rel="tag">Maven</a>,&nbsp;<a href="/tag/Hudson" rel="tag">Hudson</a>			 ]]> 
		</description>
		<category>기술 자료</category>
		<category>EMMA</category>
		<category>Eclipse</category>
		<category>Maven</category>
		<category>Hudson</category>

		<comments>http://benelog.egloos.com/2212119#comments</comments>
		<pubDate>Thu, 22 Jan 2009 23:32:21 GMT</pubDate>
		<dc:creator>정상혁</dc:creator>
	</item>
	<item>
		<title><![CDATA[ Hudson plugin 수동으로 빌드&업로드 ]]> </title>
		<link>http://benelog.egloos.com/2208375</link>
		<guid>http://benelog.egloos.com/2208375</guid>
		<description>
			<![CDATA[ 
  <p>&nbsp; Hudson의 plugin들은 Manage Hudson&gt;Manage Plugins의 updates 탭에서 최신버전들을 업그레이드할 수 있습니다. 그래서 수동으로 업데이트를 해줘야할 일은 없습니다.<br></p><p>&nbsp; 저는 Hudson을 사용하면서 두 번 수동업데이트가 필요한 상황을 경험했습니다.<br></p><h4>Findbugs plugins의 수동 업데이트</h4><p>(Findbugs plugin에 대한 자세한 설명은 <a class="external" title="http://benelog.egloos.com/2079841" href="http://benelog.egloos.com/2079841">FindBugs + Eclipse + Maven2 + Hudson</a> 참조)<br></p><p><br></p><p>&nbsp;findbugs plugins을 쓰다가 버전 3.2를 업데이트하니, 전에는 없었던 에러가 발생했습니다. 다음의 메시지를 받았었습니다.</p><blockquote><p>Cannot find setter nor field in org.apache.maven.plugins.site.SiteMojo for 'xmlOutput'</p></blockquote><p>&nbsp; 검색을 해보니 저보다 하루 먼저 이 에러를 발견한 사람이 신고를 했고, 곧 이 에러가 고쳐진&nbsp; findbugs plugins 버전 3.3이 나왔습니다. (<a href="https://hudson.dev.java.net/issues/show_bug.cgi?id=2880"></a><a href="https://hudson.dev.java.net/issues/show_bug.cgi?id=2880"></a><a href="https://hudson.dev.java.net/issues/show_bug.cgi?id=2880">https://hudson.dev.java.net/issues/show_bug.cgi?id=2880</a> 참조)</p><p>&nbsp; 나오자마자 적용하려고 하니, update 탭에서 바로 뜨지가 않더군요. Hudson의 사이트에서 바로 최신버전의 <a class="external" title="https://hudson.dev.java.net/servlets/ProjectDocumentList?folderID=7826&amp;expandFolder=7826&amp;folderID=0" href="https://hudson.dev.java.net/servlets/ProjectDocumentList?folderID=7826&amp;expandFolder=7826&amp;folderID=0">findbugs.hpi</a>파일을 다운 받아서 PC에 저장을 한후, Manage Hudson&gt;Manage Plugins &gt; Advanced 탭에서 업로드 시켰습니다.</p><p><br></p><p style="TEXT-ALIGN: center"><img class="attachment" title="HudsonPluginUpload.JPG" alt="HudsonPluginUpload.JPG" src="http://benelog.springnote.com/pages/2554720/attachments/1114734"></p><p>&nbsp; 설치된 플러그인은 Hudson을&nbsp; 재시작해야지 적용이 됩니다. installed 탭에서는 현재 의도한 버전의 플러그인이 설치되어 있는지 확인할 수 있습니다.</p><p><br></p><h4>Emma plugin의 빌드와 수동 업데이트</h4><p>&nbsp; (EMMA Plugin에 대한 자세한 설명은 <a class="external" title="http://benelog.egloos.com/2212119" href="http://benelog.egloos.com/2212119">EMMA + Eclipse + Maven2 + Hudson</a> 참조) <br></p><p>&nbsp; Emma plugin은 현재 2007년 7월 이후의 1.8 버전이후로 정식 배포판은 추가로 나오지 않고 있습니다. ( <a href="https://hudson.dev.java.net/servlets/ProjectDocumentList?folderID=6664&amp;expandFolder=6664&amp;folderID=5818">https://hudson.dev.java.net/servlets/ProjectDocumentList?folderID=6664&amp;expandFolder=6664&amp;folderID=5818</a> 참조) 제가 설정한 환경에서는 emma-plugin 1.8버전으로 아무리 빌드를 해봐도 Hudson에서 볼 수 있는 리포트 메뉴가 나오지 않았습니다. 그래서, 소스를 뒤져서 분석을 해보니, 현재 snapshot 버전의 소스에서는 리포트가 생성되지 않을 이유가 없었습니다. 1.8버전과의 소스 비교를 해 보는 것도 번거롭고 해서 최신 snapshot을 직접 빌드시켜서 적용시켜 보기로 했습니다.<br></p><p>&nbsp; 먼저&nbsp; https://svn.dev.java.net/svn/hudson/trunk/hudson 의 SVN 주소에서 hudson 전체 소스를 check out 받습니다. 그리고 '프로젝트폴더/plugins/emma' 디렉토리에 가서 mvn package를 실행시킵니다. 제가 이렇게 빌드를 시도했을 때의 시점에는 Dependency 중 artifactId가 hudson-test-harnes 인 버전 1.277을 찾을 수 없다고 에러가 났었습니다. 해당 버전을 찾아서 따로 설치해 줄 수도 있지만, 그냥 하나 더 낮을 버전으로 다시 '프로젝트폴더/plugins/emma' 아래에 있는 pom.xml에 dependency 선언을 해 주었습니다. 가장 가까운 거리에 있는 선언의 버전을 따르게 되어 있으니, 해당 pom.xml에서 직접 지정한 버전을 받게 될 것입니다.</p><p><br></p><blockquote><p>&nbsp; &lt;dependency&gt;<br>&nbsp;&nbsp;&nbsp; &lt;groupId&gt;org.jvnet.hudson.main&lt;/groupId&gt;<br>&nbsp;&nbsp;&nbsp; &lt;artifactId&gt;hudson-test-harness&lt;/artifactId&gt;<br>&nbsp;&nbsp;&nbsp; &lt;version&gt;1.276&lt;/version&gt;<br>&nbsp; &lt;/dependency&gt;</p><p><br></p></blockquote><p>&nbsp; 그러고 나서 mvn package가 성공적으로 실행되었다면 target디렉토리에 있는 emma.hpi를 찾아봅니다. 그리고 그 파일을 Hudson에 접속해서 Manage Hudson&gt;Manage Plugins &gt; Advanced 탭을 통해서 업로드하고, Hudson을 재시작시키면 됩니다.</p><p>&nbsp; emma-plugin은 1.9-SNAPSHOT 버전을 바꾸고 나서 다시 빌드를 돌리니 잘 작동하는군요.</p><p><br></p><br/><br/>tag : <a href="/tag/Hudson" rel="tag">Hudson</a>,&nbsp;<a href="/tag/Emma" rel="tag">Emma</a>,&nbsp;<a href="/tag/Findbugs" rel="tag">Findbugs</a>,&nbsp;<a href="/tag/Maven" rel="tag">Maven</a>			 ]]> 
		</description>
		<category>기술 자료</category>
		<category>Hudson</category>
		<category>Emma</category>
		<category>Findbugs</category>
		<category>Maven</category>

		<comments>http://benelog.egloos.com/2208375#comments</comments>
		<pubDate>Mon, 19 Jan 2009 13:07:35 GMT</pubDate>
		<dc:creator>정상혁</dc:creator>
	</item>
	<item>
		<title><![CDATA[ JDepend + Eclipse + Maven2 ]]> </title>
		<link>http://benelog.egloos.com/2208368</link>
		<guid>http://benelog.egloos.com/2208368</guid>
		<description>
			<![CDATA[ 
  <p>&nbsp; &nbsp;<a href="http://clarkware.com/software/JDepend.html" class="external" title="http://clarkware.com/software/JDepend.html">JDepend</a>는 Java패키지간의 의존성에 대한 수치들을 알려 주는 도구입니다.</p><p>&nbsp;&nbsp; JDepend의 Eclipse의 Plugin은&nbsp;<a href="http://andrei.gmxhome.de/eclipse/">http://andrei.gmxhome.de/eclipse/</a>를 Update site에 추가하면 설치할 수 있습니다. 다음의 링크들에서 보다 자세한 내용을 참조할 수 있습니다. 분석을 하고자 하는 소스폴더 위에서 우클릭을 한 후 'Run JDepend Analysis' 메뉴를 선택하면 의존성 분석 결과가 나옵니다.&nbsp;&nbsp;<br />
</p><p><br />
</p><p><img title="EclipseJDepend.JPG" class="attachment" src="http://benelog.springnote.com/pages/2515850/attachments/1106046" alt="EclipseJDepend.JPG"></p><p><br />
</p><p>&nbsp; 이를 Maven을 통해서 생성하는 <a href="http://mojo.codehaus.org/jdepend-maven-plugin/" class="external" title="http://mojo.codehaus.org/jdepend-maven-plugin/">jdepend-maven-plugin</a> 은 pom.xml에 아래와 같이 추가할 수 있습니다.</p><p><br />
</p><blockquote><p>&lt;reporting&gt;</p><p>.....</p><p>&lt;plugin&gt;<br />
&nbsp; &lt;groupId&gt;org.codehaus.mojo&lt;/groupId&gt;<br />
&nbsp; &lt;artifactId&gt;jdepend-maven-plugin&lt;/artifactId&gt;<br />
&nbsp; &lt;version&gt;2.0-beta-2&lt;/version&gt;<br />
&lt;/plugin&gt;</p><p>&lt;/reporting&gt;</p></blockquote><p><br />
</p><p>mvn jdepend:generate 또는 mvn site명령을 통해서 보고서가 생성됩니다. mvn site로 실행했다면 Hudson의 프로젝트 홈에서 Maven Generated Site 메뉴를 통해서도&nbsp;확인할 수 있습니다. <a href="http://mojo.codehaus.org/jdepend-maven-plugin/examples/jdepend-report.html" class="external" title="http://mojo.codehaus.org/jdepend-maven-plugin/examples/jdepend-report.html">샘플페이지</a> 에 생성된 보고서의 형식이 나와있습니다.&nbsp;</p><p><br />
</p><p><img title="JDependReport.JPG" class="attachment" src="http://benelog.springnote.com/pages/2515850/attachments/1097860" alt="JDependReport.JPG"></p><p><a href="http://clarkware.com/software/JDepend.html" class="external" title="http://clarkware.com/software/JDepend.html">JDepend 첫페이지</a>나 생성된 보고서 안에서도 위의 요약 테이블에&nbsp; 수치들에 대한 설명이 잘 나와있습니다. 간단히 요약해서 정리하면,</p><ul><li>TC (Total Classes) : 전체 클래스 수. CC + AC</li><li>CC (Concrete Classes) : Inteface나 추상클래스가 아닌 구상 클래스 수</li><li>AC (Abstract Classes) : Interface나 Abstract Class로 선언된 클래스 수</li><li>Ca (<span id="intelliTxt">Afferent Couplings</span>) : 이 패키지를 의존하고 있는 다른 패키지의 수. 이 패키지의 책임감을 나타내는 지표</li><li>Ce (<span id="intelliTxt">Efferent Couplings</span>) : 이 패키지가 의존하고 있는 클래스가 있는 다른 패키지의 수. 이 패키지의 독립성을 나타내는 지표.</li><li>A (<span id="intelliTxt">Abstractness</span>) : 총 클래스 갯수 중 인터페이스나 추상클래스의 비율. 1이라면 해당 패키지는 추상클래스나 인터페이스 밖에 없는 것.</li><li>I (<span id="intelliTxt">Instability</span>) : &nbsp; 총 결합도 중 이 패키지의 외부의존성의 비율 (Ce / (Ce + Ca)). 변화에 대한 내성을 나타내는 지표. I=0이라면 완전하게 안정적인 것.</li><li>D <span id="intelliTxt">(Distance&nbsp;from Main Sequence</span>) :&nbsp; 이상적인 균형의 상태인&nbsp; A + I = 1 의 함수에서 수직으로 떨어진 거리. (아래 그래프 참조)</li></ul><p><br />
</p><p style="text-align: center;"><img title="onjava/2004/01/21/graphics/figure3.gif" src="http://www.onjava.com/onjava/2004/01/21/graphics/figure3.gif" alt="onjava/2004/01/21/graphics/figure3.gif"></p><p style="text-align: center;">이미지 출저 : <a href="http://www.onjava.com/pub/a/onjava/2004/01/21/jdepend.html" class="external" title="http://www.onjava.com/pub/a/onjava/2004/01/21/jdepend.html">Managing Your Dependencies with JDepend</a></p><p><br />
</p><p>가장 중요한 것은 패키지 간의 순환참조를 보여주는 Cycles 부분입니다.</p><p><img title="JDependCycles.JPG" class="attachment" src="http://benelog.springnote.com/pages/2515850/attachments/1098126" alt="JDependCycles.JPG"></p><p>&nbsp; 순환참조 관계의 패키지들은 부분적으로 배포될 수도 없고, 한 패키지를 변경할 때 그 영향력을 파악하기도 힘들게 만듭니다. 순환 참조에 대한 자세한 내용은 아래의 링크를 참조하시기 바랍니다.</p><ul><li><a href="http://toby.epril.com/?p=263" title="http://toby.epril.com/?p=263" class="external">Code Organization &amp; Cyclic Dependency Problem</a></li><li><a href="http://blog.kirkk.com/index.php?itemid=30" class="external" title="http://blog.kirkk.com/index.php?itemid=30">Cyclic Dependencies</a></li><li><a href="http://www.onjava.com/pub/a/onjava/2004/01/21/jdepend.html" class="external" title="http://www.onjava.com/pub/a/onjava/2004/01/21/jdepend.html">Managing Your Dependencies with JDepend</a><br />
</li><li><a href="http://whiteship.tistory.com/1767" class="external" title="http://whiteship.tistory.com/1767">Code Organization Guidelines for Large Code Bases - 유겐 휄러</a></li></ul><p><br />
</p><h4>관련자료<br />
</h4><ul><li><a href="http://younghoe.info/50" class="external" title="http://younghoe.info/50">JDepend에서 지원하는 설계 품질 측정치(design quality metrics)</a></li><li><a href="http://www.powerjava.net/blog/soulcarta/entry/Eclipse-Plugin-JDepend%EB%A5%BC-%EC%9D%B4%EC%9A%A9%ED%95%9C-%EC%9D%98%EC%A1%B4%EC%84%B1-%EA%B2%80%EC%82%AC" class="external" title="http://www.powerjava.net/blog/soulcarta/entry/Eclipse-Plugin-JDepend%EB%A5%BC-%EC%9D%B4%EC%9A%A9%ED%95%9C-%EC%9D%98%EC%A1%B4%EC%84%B1-%EA%B2%80%EC%82%AC">[Eclipse Plugin] JDepend를 이용한 의존성 검사 개발관련</a><br />
</li><li><a href="http://whiteship.tistory.com/967" class="external" title="http://whiteship.tistory.com/967">Eclipse에서 JDepend 사용하기</a><br />
</li></ul><p><br />
</p><br/><br/>tag : <a href="/tag/JDepend" rel="tag">JDepend</a>,&nbsp;<a href="/tag/Maven" rel="tag">Maven</a>,&nbsp;<a href="/tag/Eclipse" rel="tag">Eclipse</a>			 ]]> 
		</description>
		<category>기술 자료</category>
		<category>JDepend</category>
		<category>Maven</category>
		<category>Eclipse</category>

		<comments>http://benelog.egloos.com/2208368#comments</comments>
		<pubDate>Mon, 19 Jan 2009 13:00:35 GMT</pubDate>
		<dc:creator>정상혁</dc:creator>
	</item>
	<item>
		<title><![CDATA[ JavaNCSS + Maven2 + Hudson ]]> </title>
		<link>http://benelog.egloos.com/2204823</link>
		<guid>http://benelog.egloos.com/2204823</guid>
		<description>
			<![CDATA[ 
  <p>&nbsp; JavaNCSS를 Maven2을 통해 실행하고, Hudson을 통해 리포트를 확인하는 과정을 정리했습니다. <a href="http://www.kclee.de/clemens/java/javancss/" class="external" title="http://www.kclee.de/clemens/java/javancss/">JavaNCSS</a>는 주석이 아닌 라인수(Non Commenting Source Statements,NCSS)와 순환복잡도 수 (Cyclomatic Comlexity Number, CCN) 등을 측정해 주는 도구입니다.</p><p>&nbsp; JavanNCSS에 관한 eclipse 플러그인도 찾을 수는 있었지만(<a href="http://sourceforge.net/projects/jncss4eclipse/">http://sourceforge.net/projects/jncss4eclipse/</a> ) 가장 최신버전이 2002년에 올라온 것이라서 적용하지 않기로 했습니다.&nbsp;</p><p>&nbsp; 그리고, JavaNCSS에 대한 Maven의 플러그인도&nbsp; <a href="http://mojo.codehaus.org/javancss-maven-plugin/" class="external" title="http://mojo.codehaus.org/javancss-maven-plugin/">javancss-maven-plugin</a>과 <a href="http://maven-plugins.sourceforge.net/maven-javancss-plugin/" class="external" title="http://maven-plugins.sourceforge.net/maven-javancss-plugin/">maven-javancss-plugin</a>의 2가지가 존재했는데, <a href="http://mojo.codehaus.org/javancss-maven-plugin/" class="external" title="http://mojo.codehaus.org/javancss-maven-plugin/">javancss-maven-plugin</a> 쪽이 보다 문서화가 잘 되어 있어서 그 쪽을 선택했습니다.</p><p>&nbsp; pom.xml 에 아래 선언을 추가합니다.<br />
</p><p><br />
</p><blockquote><p>&lt;reporting&gt;</p><p>...</p><p>&nbsp; &nbsp;&lt;plugin&gt;</p><p>&nbsp; &nbsp;&nbsp; &lt;groupId&gt;org.codehaus.mojo&lt;/groupId&gt;<br />
&nbsp;&nbsp;&nbsp;&nbsp; &lt;artifactId&gt;javancss-maven-plugin&lt;/artifactId&gt;<br />
&nbsp;&nbsp;&nbsp;&nbsp; &lt;version&gt;2.0-beta-2&lt;/version&gt;<br />
&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&lt;configuration&gt;<br />
&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&lt;forceEncoding&gt;utf-8&lt;/forceEncoding&gt;<br />
&nbsp;&nbsp;&nbsp;&nbsp; &nbsp; &lt;/configuration&gt;<br />
&nbsp;&nbsp;&nbsp; &lt;/plugin&gt;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br />
&nbsp; &lt;/plugins&gt;<br />
&lt;/reporting&gt;</p></blockquote><p><br />
</p><p>그리고는 mvn javancss:report javancss:check로 플러그인을 실행시켜 봅니다. 각각의 골에 대한 설명은 아래 페이지에서 보시면 됩니다.</p><ul><li><a href="http://mojo.codehaus.org/javancss-maven-plugin/report-mojo.html" title="http://mojo.codehaus.org/javancss-maven-plugin/report-mojo.html" class="external">javancss:report</a> : 리포트 생성</li><li><a href="http://mojo.codehaus.org/javancss-maven-plugin/check-mojo.html" title="http://mojo.codehaus.org/javancss-maven-plugin/check-mojo.html" class="external">javancss:check</a> : CCN이나 NCSS 값이 너무 크면 빌드를 실패시킴</li></ul><p><br />
</p><p>제외하거나 추가할 파일을 지정하려면 아래의 configuration 태그 아래에 includes, excludes 태그로 지정하면 됩니다.</p><blockquote><p>&lt;configuration&gt;</p><p>.....<br />
&nbsp; &lt;includes&gt;<br />
&nbsp;&nbsp;&nbsp; &lt;include&gt;**/*foo.java&lt;/include&gt;<br />
&nbsp; &lt;/includes&gt;<br />
&nbsp; &lt;excludes&gt;<br />
&nbsp;&nbsp;&nbsp; &lt;exclude&gt;**/bar.java&lt;/exclude&gt;<br />
&nbsp; &lt;exclude&gt;**/foobar.java&lt;/exclude&gt;<br />
&nbsp; &lt;/excludes&gt;<br />
&lt;/configuration&gt;</p></blockquote><p><br />
</p><p>CCN이나 NCSS값의 한계 허용치는 아래와 같이 지정합니다.</p><blockquote><p>&lt;configuration&gt;<br />
....<br />
&nbsp; &lt;failOnViolation&gt;true&lt;/failOnViolation&gt;<br />
&nbsp; &lt;ccnLimit&gt;12&lt;/ccnLimit&gt;<br />
&nbsp; &lt;ncssLimit&gt;90&lt;/ncssLimit&gt;<br />
&lt;/configuration&gt;</p></blockquote><p><br />
</p><p>&nbsp; 한가지 주의할 점은, 2.0-beta-2 버전을 실행할 경우, 메서드 내부에 annotation선언이 있다면 아래와 같은 에러메시지를 받게 됩니다.<br />
</p><blockquote><p>Encountered "@ SuppressWarnings ( \"unused\" ) int notUsedVariable =" at line xxx, column yyy.</p></blockquote><p>&nbsp; 이 것은 &nbsp; <a href="http://mojo.codehaus.org/javancss-maven-plugin/" class="external" title="http://mojo.codehaus.org/javancss-maven-plugin/">javancss-maven-plugin</a>&nbsp; 버전 2.0-beta-2가 이 의존하고 있는 JavaNCSS 버전 29.49 에서 가지고 있는 버그입니다. (<a href="http://jira.codehaus.org/browse/MJNCSS-16">http://jira.codehaus.org/browse/MJNCSS-16</a> 참조) JavaNCSS 버전 29.50에서는 해결된 문제이고, 이 플러그인의 최신 버전인 <a href="http://mojo.codehaus.org/javancss-maven-plugin/" class="external" title="http://mojo.codehaus.org/javancss-maven-plugin/">javancss-maven-plugin</a> 2.0-beta-3버전에서는 이런 문제가 발생하지 않는다고 합니다. 그런데, codehause의 Maven Repository를 뒤져보니 (<a href="http://repository.codehaus.org/org/codehaus/mojo/javancss-maven-plugin/">http://repository.codehaus.org/org/codehaus/mojo/javancss-maven-plugin/</a>) 아직 2.0-beta-3버전은 올라와 있지 않습니다. snapshop 버전을 찾아서 쓸 수도 있겠지만, 그것보다는plugin 설정에서 dependency설정을 덥어쓰는 편이 더 간편하게 느껴졌습니다. pom.xml의 build절에 아래와같이 추가하면 됩니다.<br />
</p><p><br />
</p><blockquote><p>&lt;build&gt;</p><p>&nbsp; &nbsp;&lt;plugin&gt;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br />
&nbsp;&nbsp;&nbsp; &nbsp;&lt;groupId&gt;org.codehaus.mojo&lt;/groupId&gt;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp; &lt;artifactId&gt;javancss-maven-plugin&lt;/artifactId&gt;<br />
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &lt;version&gt;2.0-beta-2&lt;/version&gt;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;dependencies&gt;<br />
&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&lt;dependency&gt;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&lt;groupId&gt;javancss&lt;/groupId&gt;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&lt;artifactId&gt;javancss&lt;/artifactId&gt;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp; &lt;version&gt;29.50&lt;/version&gt;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &lt;/dependency&gt;<br />
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp; &lt;/dependencies&gt;<br />
&nbsp;&nbsp;&nbsp; &nbsp;&lt;/plugin&gt;<br />
&nbsp;&nbsp;&nbsp;&nbsp; &lt;/plugins&gt;<br />
&nbsp; &lt;/build&gt;</p></blockquote><p>&nbsp; 생성된 리포트를 보기 위해서, Hudson에서는 프로젝트에서 Configure 설정에서 Publish Java NCSS report를 선택을 합니다.</p><p><img class="attachment" title="HudsonJavancssConfig.JPG" src="http://benelog.springnote.com/pages/2515032/attachments/1097506?dummy=1232007342166" alt="HudsonJavancssConfig.JPG"></p><p>그리고는&nbsp;<a href="http://mojo.codehaus.org/javancss-maven-plugin/report-mojo.html" title="http://mojo.codehaus.org/javancss-maven-plugin/report-mojo.html" class="external">javancss:report</a>&nbsp; Goal이 포함된 빌드를 실행시켰다면 프로젝트 홈 화면에서 Java NCSS Report라는 링크가 생기게 됩니다.</p><p style="text-align: center;"><img class="attachment" title="HudsonJavancssMenu.JPG" src="http://benelog.springnote.com/pages/2515032/attachments/1097570" alt="HudsonJavancssMenu.JPG"></p><p>클릭을 하면 생성된 리포트를 볼 수가 있죠. (패키지명은 제가 지웠습니다.)</p><p><img class="attachment" title="HudsonJavancssReport.JPG" src="http://benelog.springnote.com/pages/2515032/attachments/1097718" alt="HudsonJavancssReport.JPG"></p><p><br />
</p><p>&nbsp;Maven에서 mvn site명령으로 site 절(phrase)까지 들어갔다면 리포트를 모은 페이지를 따로 생성해 주기도합니다. Hudson의 프로젝트 메인화면에서 Maven-generated site 링크를 통해서 보실 수 있습니다.Hudson에서 생성해주는 페이지가 더 이쁘기는하지만,&nbsp;JavaNCSS의 보고서는 Maven-generated site가 더많은 정보를 제공합니다. 예를 들면 가장 주석을 제외한 라인수(NCSS)가 많은 30위까지의 클래스들, 메소드들 같은 순위등같은 것들을 확인할 수 있습니다.</p><p><br />
</p><p><img class="attachment" title="MvnSiteReports.JPG" src="http://benelog.springnote.com/pages/2515032/attachments/1097742" alt="MvnSiteReports.JPG"></p><p><br />
</p><p><br />
</p><br/><br/>tag : <a href="/tag/Javancss" rel="tag">Javancss</a>,&nbsp;<a href="/tag/Hudson" rel="tag">Hudson</a>,&nbsp;<a href="/tag/Maven" rel="tag">Maven</a>			 ]]> 
		</description>
		<category>기술 자료</category>
		<category>Javancss</category>
		<category>Hudson</category>
		<category>Maven</category>

		<comments>http://benelog.egloos.com/2204823#comments</comments>
		<pubDate>Thu, 15 Jan 2009 21:51:51 GMT</pubDate>
		<dc:creator>정상혁</dc:creator>
	</item>
	<item>
		<title><![CDATA[ PMD + Eclipse + Maven2 + Hudson ]]> </title>
		<link>http://benelog.egloos.com/2176171</link>
		<guid>http://benelog.egloos.com/2176171</guid>
		<description>
			<![CDATA[ 
  <p>&nbsp; 코드 검사도구인 <a href="http://pmd.sourceforge.net/" title="http://pmd.sourceforge.net/" class="external">PMD</a> 를 Eclipse plugin을 설정하고, Maven을 통해서도 같은 규칙으로 코드를 검사한 보고서를 생성하고, Hudson을 통해서 확인하는 과정을 정리해 봤습니다.&nbsp;<br />
</p><p>&nbsp; Eclipse에서는 update site를 <a href="http://pmd.sf.net/eclipse">http://pmd.sf.net/eclipse</a> 로 지정해서 플러인을 설치합니다.</p><p>&nbsp;&nbsp;Eclipse 메뉴의 Window- Preferences를 가면 Rule설정 파일을 export, import할 수 있는 기능이 있습니다.</p><p><img title="PmdPreference.JPG" class="attachment" src="http://benelog.springnote.com/pages/2295354/attachments/1019796" alt="PmdPreference.JPG"></p><p><br />
</p><p>Project의 Properties에도 PMD관련 설정이 있습니다. 외부에서 만든 Rule파일을 바로 참조해도 되고, 여기서 설정된 것을파일로 생성할 수도 있습니다. 이미 있는 프로젝트에서 Rule를 설정할 때는 Project의 Properties에서 Rule들을고른 후에 생기는 warning이나 error를 보고 warning이 안 뜨게 소스를 고거나 Rule을 제외한 후, 최종결정Rule들로 Ruleset 정의 파일을 생성하는 것이 편리할 것입니다. 저는 처음에 모든 Rule을 다 선택한 다음에warning들을 없애가면서 Rule들을 하나하나 검토해 나갔었습니다.</p><p><img title="PmdProject.JPG" class="attachment" src="http://benelog.springnote.com/pages/2295354/attachments/1019792?dummy=1229682190192" alt="PmdProject.JPG"></p><p><br />
</p><p>위의 화면에서 Enable PMD를 선택하면 .project파일에&nbsp;아래와 같은 부분이 추가될 것입니다.</p><blockquote><p>&lt;natures&gt;<br />
&nbsp;&nbsp;&nbsp; &nbsp; ....<br />
&nbsp;&nbsp; &lt;nature&gt;net.sourceforge.pmd.eclipse.plugin.pmdNature&lt;/nature&gt;<br />
&lt;/natures&gt;</p></blockquote><p>이제 해당 프로젝트는 Eclipse의 Problems View에서 PMD에서 보고하는 error, warning까지 모두 다 뜨게됩니다.&nbsp;개발을 하면서 Rule&nbsp;준수에 대한 빠른 피드백을 얻기 위해 되도록 이 기능을 사용하는 것이 좋습니다. 대신 이미Project에 warning이 많으면 새로운 warning들이 잘 눈에 띄지 않게 되므로, Project를 warning없이깨끗히 정리한 다음에 사용할 것을 권장해 드립니다.</p><p>&nbsp;&nbsp;모든 Rule을 다 적용하면 아마&nbsp;굉장히&nbsp;많은 warning과 때로는 에러까지도 나올 것입니다. 그런 것들을 다 검토해서 포함시킬지를 결정해야&nbsp;합니다.&nbsp;<a href="http://pmd.sourceforge.net/rule-guidelines.html">http://pmd.sourceforge.net/rule-guidelines.html</a>를 참조하셔서, 프로젝트 상황에 맞게 적용해야겠죠.&nbsp;그중 몇가지 Rule에 대해서만&nbsp;언급을 하고 넘어가겠습니다.</p><p><br />
</p><ul><li><a href="http://pmd.sourceforge.net/rules/basic.html" title="http://pmd.sourceforge.net/rules/basic.html" class="external">Basic Rules</a>-EmptryInitializer:&nbsp; PMD 5.0에서 추가된 룰로 Maven의 PMD&nbsp;plugin버전 2.4에서는 PMD 버전 4.2.2를 참조하기 때문에 이Rule은 지원되지 않습니다. 따라서 PMD의 Eclipse plugin에서 이를 지원한다고 할지라도 Maven plugin과같이 쓰기 위해서는 이 Rule을 반드시 제외해야 합니다.</li><li><a href="http://pmd.sourceforge.net/rules/optimizations.html" title="http://pmd.sourceforge.net/rules/optimizations.html" class="external">Optimization Rules</a>-LocalVariableCouldBeFinal과&nbsp;Controversial Rules-AvoidFinalLocalVariable : 서로 상반되는 Rule로 한쪽 Rule을피하면 다른 쪽에 걸려드는 Rule입니다. 그래서 warning을 안보려면 둘 중에 하나는 꼭 제외해야 합니다. 그런데,final을 Local variable에 일일히 선언하는 것도 번거로운 일이고, 메소드 내의 inner class에서 참조해야되어서 꼭 final이 되어야하는 local variable도 있으므로, 둘 다 제외하는 것도&nbsp;좋습니다</li><li><a href="http://pmd.sourceforge.net/rules/controversial.html" title="http://pmd.sourceforge.net/rules/controversial.html" class="external">Controversial Rules</a>-OnlyOneReturnRule :&nbsp; 메서드에서 return문이 여러 개일 경우 경고를 주는데, 메서드 중간의 return문은 복잡한 조건문의 구조를 단순하게 하는데 도움이 경우가 많고, <a href="http://www.yes24.com/Goods/FTGoodsView.aspx?goodsNo=2824034&amp;CategoryNumber=001001003016001006" class="external" title="http://www.yes24.com/Goods/FTGoodsView.aspx?goodsNo=2824034&amp;CategoryNumber=001001003016001006">켄트벡의 구현패턴</a> 7장 중 '보호절'을 보면 이를 권장하고 있습니다.</li><li><p><a href="http://pmd.sourceforge.net/rules/design.html" title="http://pmd.sourceforge.net/rules/design.html" class="external">Design Rules</a>-UnnecessaryLocalBeforeReturn: return 전에 따로 local 변수로 반환할 값을 선언할 때 주는 경고인데, 기능적으로는 별 의미 없는 코드이나,return 문장에는 @SupressWarning 의 Annotation을 추가할 수 없기 때문에,&nbsp; Annotation 적용범위를 최소화하기 위해 그런 선언이 필요한 때도 있습니다. (Java Language Spec 9.7, EffectiveJava 2nd Edition Item 24 참조)</p><p><br />
</p></li></ul><p>&nbsp;검토해보니 가장 부담없이 적용가능한 RuleSet이 괄호에 대한 규칙을 정의하는 Braces Rules이고, Controversial Rules가 이름 그래도 가장 제외할 것이 많은 Rule Set입니다.</p><p>&nbsp; 이런 과정을 거쳐서 선별된&nbsp;Rule 정의 파일이 만들어지면&nbsp;그것을&nbsp;Maven의 PMD plugin에서도 참조할 수 있게 설정합니다.&nbsp;저는 Rule설정 파일이름을 .ruleset으로 하고 pom.xml에 추가했습니다.</p><blockquote><p>&nbsp; &lt;reporting&gt;<br />
&nbsp;&nbsp;&nbsp; &lt;plugins&gt;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;plugin&gt;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;artifactId&gt;maven-pmd-plugin&lt;/artifactId&gt;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;version&gt;2.4&lt;/version&gt;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;configuration&gt;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;rulesets&gt;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;ruleset&gt;${basedir}/.ruleset&lt;/ruleset&gt;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;/rulesets&gt;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;sourceEncoding&gt;utf-8&lt;/sourceEncoding&gt;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;targetJdk&gt;1.6&lt;/targetJdk&gt;<br />
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &lt;minimumTokens&gt;10&lt;/minimumTokens&gt;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;/configuration&gt;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;/plugin&gt;<br />
&nbsp; &lt;/reporting&gt;</p></blockquote><p><br />
</p><p>그리고는 mvn site 혹은 mvn pmd:pmd pmd:cpd 처럼 PMD plugin의 goal을 포함시킨 빌드를 한번 실행시켜 봅니다.</p><p>문제가 없이 돌아갔으면 hudson에도 PMD플러그인을 설정합니다.. PMD 플러그인의 goal이 포함된 빌드를 돌리고 나면PMD warning라는 링크가 해당 프로젝트에 생기고, 거기서 아래와 같은 보고서를 확인할 수 있습니다.</p><p><br />
</p><p><img title="HudsonPmdResult.JPG" class="attachment" src="http://benelog.springnote.com/pages/2295354/attachments/1019794?dummy=1229687383197" alt="HudsonPmdResult.JPG"></p><p><br />
</p><h4>관련자료</h4><ul><li><a href="http://www.ibm.com/developerworks/kr/library/j-pmd/" title="http://www.ibm.com/developerworks/kr/library/j-pmd/" class="external">PMD로 버그 잡기</a></li><li><a href="http://pmd.sourceforge.net/rule-guidelines.html" class="external" title="http://pmd.sourceforge.net/rule-guidelines.html">PMD Rule guideline</a></li><li><a href="http://moai.tistory.com/541" title="http://moai.tistory.com/541" class="external">PMD로 코드리뷰 자동으로 수행하기</a></li><li><a href="http://blog.empas.com/seeiris/14381547" title="http://blog.empas.com/seeiris/14381547" class="external">PMD 이클립스 플러그인 사용법</a></li><li><a href="http://ecogeo.tistory.com/70" title="http://ecogeo.tistory.com/70" class="external">Hudson : 리포트/차트 보기</a></li></ul><p><br />
</p><br/><br/>tag : <a href="/tag/PMD" rel="tag">PMD</a>,&nbsp;<a href="/tag/Maven" rel="tag">Maven</a>,&nbsp;<a href="/tag/Hudson" rel="tag">Hudson</a>,&nbsp;<a href="/tag/Eclipse" rel="tag">Eclipse</a>			 ]]> 
		</description>
		<category>기술 자료</category>
		<category>PMD</category>
		<category>Maven</category>
		<category>Hudson</category>
		<category>Eclipse</category>

		<comments>http://benelog.egloos.com/2176171#comments</comments>
		<pubDate>Fri, 19 Dec 2008 11:46:21 GMT</pubDate>
		<dc:creator>정상혁</dc:creator>
	</item>
</channel>
</rss>
