-. Quick Ref.
http://poi.apache.org/spreadsheet/quick-guide.html

-. HOW TO
http://poi.apache.org/spreadsheet/how-to.html


Iterate over rows and cells

Sometimes, you'd like to just iterate over all the rows in a sheet, or all the cells in a row. This is possible with a simple for loop.

Luckily, this is very easy. Row defines a CellIterator inner class to handle iterating over the cells (get one with a call to row.cellIterator()), and Sheet provides a rowIterator() method to give an iterator over all the rows.

Alternately, Sheet and Row both implement java.lang.Iterable, so using Java 1.5 you can simply take advantage of the built in "foreach" support - see below.

	Sheet sheet = wb.getSheetAt(0);
	for (Iterator<Row> rit = sheet.rowIterator(); rit.hasNext(); ) {
		Row row = rit.next();
		for (Iterator<Cell> cit = row.cellIterator(); cit.hasNext(); ) {
			Cell cell = cit.next();
			// Do something here
		}
	}
				

Iterate over rows and cells using Java 1.5 foreach loops

Sometimes, you'd like to just iterate over all the rows in a sheet, or all the cells in a row. If you are using Java 5 or later, then this is especially handy, as it'll allow the new foreach loop support to work.

Luckily, this is very easy. Both Sheet and Row implement java.lang.Iterable to allow foreach loops. For Row this allows access to the CellIterator inner class to handle iterating over the cells, and for Sheet gives the rowIterator() to iterator over all the rows.

	Sheet sheet = wb.getSheetAt(0);
	for (Row row : sheet) {
		for (Cell cell : row) {
			// Do something here
		}
	}


Getting the cell contents

To get the contents of a cell, you first need to know what kind of cell it is (asking a string cell for its numeric contents will get you a NumberFormatException for example). So, you will want to switch on the cell's type, and then call the appropriate getter for that cell.

In the code below, we loop over every cell in one sheet, print out the cell's reference (eg A3), and then the cell's contents.

// import org.apache.poi.ss.usermodel.*;

Sheet sheet1 = wb.getSheetAt(0);
for (Row row : sheet1) {
	for (Cell cell : row) {
		CellReference cellRef = new CellReference(row.getRowNum(), cell.getCellNum());
		System.out.print(cellRef.formatAsString());
		System.out.print(" - ");
		
		switch(cell.getCellType()) {
      case Cell.CELL_TYPE_STRING:
        System.out.println(cell.getRichStringCellValue().getString());
        break;
      case Cell.CELL_TYPE_NUMERIC:
        if(DateUtil.isCellDateFormatted(cell)) {
          System.out.println(cell.getDateCellValue());
        } else {
          System.out.println(cell.getNumericCellValue());
        }
        break;
      case Cell.CELL_TYPE_BOOLEAN:
        System.out.println(cell.getBooleanCellValue());
        break;
      case Cell.CELL_TYPE_FORMULA:
        System.out.println(cell.getCellFormula());
        break;
      default:
        System.out.println();
		}
	}
}
 

출처 : http://www.jakartaproject.com/article/jakarta/122463359124589

그냥

logger.debug("something wrong" + e.printStackTrace());    // 문법오류 

logger.debug("something wrong" + e.printStackTrace().toString());    // 마지막 에러만 표기 

그래서 아래와 같이 사용하면 콘솔에서 보는것과 같이 에러를 추적할수 있습니다. 

catch (Exception e) {
logger.error ("something wrong", e);
//  or
logger.debug ("something wrong", e);
...
}


 
출처 : http://www.jakartaproject.com/article/jakarta/118827865707684

최근 오라클버젼들은 일반 String처럼 clob을 처리할 수 있지만 그렇지 않은 버젼들은 DBUtils를 조금 수정해 주서야 합니다

resultset의 메타 정보를 이용해서 컬럼 타입이 clob인 넘들만 따로 처리하는 로직입니다

org.apache.commons.dbutils.BasicRowProcessor.java 를 다음과 같이 수정한 후 다시 컴팔 하세요


    private Object createBean(
        ResultSet rs,
        Class type,
        PropertyDescriptor[] props,
        int[] columnToProperty,
        int cols)
        throws SQLException {


        Object bean = this.newInstance(type);       
        Object value = null;
        ResultSetMetaData meta = rs.getMetaData();
        for (int i = 1; i <= cols; i++) {

            if (columnToProperty[i] == PROPERTY_NOT_FOUND) {
                continue;
            }
           
            PropertyDescriptor prop = props[columnToProperty[i]];
            Class propType = prop.getPropertyType();
           
            if ("CLOB".equals(meta.getColumnTypeName(i))) {
                value = readClob(rs, i);
            }
            else {
                value = rs.getObject(i);
            }

            if (propType != null && value == null && propType.isPrimitive()) {
                value = primitiveDefaults.get(propType);
            }
           
            this.callSetter(bean, prop, value);
        }

        return bean;
    }
   
    protected Object readClob(ResultSet rs, int idx) {
        StringBuffer stringbuffer = new StringBuffer();
        char[] charbuffer = new char[1024];
        int read = 0;
       
        Reader reader = null;
        String result = null;
        try {
            reader = rs.getCharacterStream(idx);
            while ((read = reader.read(charbuffer, 0, 1024)) != -1)
                stringbuffer.append(charbuffer, 0, read);

            result = stringbuffer.toString();
        } catch (Exception exception) {
            System.out.println(exception);
        } finally {
            if (reader != null) try { reader.close(); } catch (Exception e){}
        }

        return result;
    }



출처 : http://www.jakartaproject.com/article/jakarta/117730447142917

Commons-Fileupload 1.2


1.2 버젼이 2007.2.13에 새롭게배포되었습니다

1.1 이하단계 버젼과 달라진 점을 알아보도록 하지요

 

I. commons-fileupload 1.1

http://www.jakartaproject.com/article/jakarta/110887666654000

 

 

II. 다운로드 및 설치

 -. fileupload는 commons의 io가 필요합니다

commons-fileupload

http://jakarta.apache.org/site/downloads/downloads_commons-fileupload.cgi

commons-io

http://jakarta.apache.org/site/downloads/downloads_commons-io.cgi



III. 달라진점

 -. DiskFileUpload 가 Deprecated 되었습니다

 -. 리스너 추가를 통해 업로드 진행 상태를 파악할 수 있습니다(대용량 파일인 경우 유용)

 -. 비정상적인 업로드시 나타나는 중간 쓰레기 파일들을 제거할 수 있습니다

 

IV. 예제소스코드


upload.html

<form name=fileupload method=post action=./upload enctype="multipart/form-data">
 file : <input type=file name=file1><br>
 text : <input type=text name=text1><br>
 <input type=submit name=button1 value=submit>
</form>

web.xml

가비지 파일 cleaner에 사용되는 FileCleanerCleanup을 listener로 추가

샘플 코드에서 사용되는 서블릿 등록

<web-app>

   ...

 

   <listener>
       <listener-class>
           org.apache.commons.fileupload.servlet.FileCleanerCleanup
       </listener-class>
   </listener>


    ...


    <servlet>
        <servlet-name>uploadServlet</servlet-name>
        <servlet-class>UploadServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>uploadServlet</servlet-name>
        <url-pattern>/upload</url-pattern>
    </servlet-mapping>

    ...

</web-app>


UploadServlet.java


import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.ProgressListener;
import org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;


public class UploadServlet extends HttpServlet {
   
    String upload_dir = null;
    public void init(ServletConfig config) throws ServletException {
          super.init(config); 
          upload_dir = config.getServletContext().getRealPath("/upload/");
    }


    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
   

        // form type이 multipart/form-data 면 true 그렇지 않으면 false를 반환
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
       
        if (isMultipart) {
            try {

                int yourMaxMemorySize = 1024 * 10;                 // threshold  값 설정
                long yourMaxRequestSize = 1024 * 1024 * 100;   //업로드 최대 사이즈 설정 (100M)

                File yourTempDirectory = new File(upload_dir);
               
                DiskFileItemFactory factory = new DiskFileItemFactory();
                factory.setSizeThreshold(yourMaxMemorySize);
                factory.setRepository(yourTempDirectory);               
   
                ServletFileUpload upload = new ServletFileUpload(factory);
                upload.setSizeMax(yourMaxRequestSize);          // 임시 업로드 디렉토리 설정
                upload.setHeaderEncoding("EUC_KR");               // 인코딩 설정
               

                /**

                 *  업로드 진행 상태 출력 (Watching progress)

                */
                ProgressListener progressListener = new ProgressListener(){
                   private long megaBytes = -1;
                   public void update(long pBytesRead, long pContentLength, int pItems) {
                       long mBytes = pBytesRead / 1000000;
                       if (megaBytes == mBytes) {
                           return;
                       }
                       megaBytes = mBytes;
                       System.out.println("We are currently reading item " + pItems);
                       if (pContentLength == -1) {
                           System.out.println("So far, " + pBytesRead + " bytes have been read.");
                       } else {
                           System.out.println("So far, " + pBytesRead + " of " + pContentLength
                                              + " bytes have been read.");
                       }
                   }
                };
                upload.setProgressListener(progressListener);   // 진행상태 리스너 추가
   

                String fieldName = null;
                String fieldValue = null;
                String fileName = null;
                String contentType = null;
                long sizeInBytes = 0;

                List items = upload.parseRequest(request);               
                Iterator iter = items.iterator();
                while (iter.hasNext()) {
                    FileItem item = (FileItem) iter.next();
   

                    // 정상적인 폼값 출력 및 처리
                    if (item.isFormField()) {
                        fieldName = item.getFieldName();
                        fieldValue = item.getString();
                       
                        System.out.println("-----+-----+-----+-----+-----+-----+-----+-----");
                        System.out.println("Field Name : "+fieldName);
                        System.out.println("Field Value : "+fieldValue);
                        System.out.println("-----+-----+-----+-----+-----+-----+-----+-----");
                       

                    // 업로드 파일 처리
                    } else {
                        fieldName = item.getFieldName();
                        fileName = item.getName();
                        contentType = item.getContentType();
                        sizeInBytes = item.getSize();
                       
                        System.out.println("-----+-----+-----+-----+-----+-----+-----+-----");
                        System.out.println("Field Name : "+fieldName);
                        System.out.println("File Name : "+fileName);
                        System.out.println("ContentType : "+contentType);
                        System.out.println("File Size : "+sizeInBytes);
                        System.out.println("-----+-----+-----+-----+-----+-----+-----+-----");

                        String savefile = fileName.substring(fileName.lastIndexOf("\\")+1, fileName.length());
                        File uploadedFile = new File(upload_dir+"\\"+savefile);
                        item.write(uploadedFile);
                    }
                }


            // 설정한 업로드 사이즈 초과시 exception 처리
            } catch (SizeLimitExceededException e) {
                e.printStackTrace();   

            // 업로드시 io등 이상 exception 처리
            } catch (FileUploadException e) {
                e.printStackTrace();

            // 기타 exception 처리
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }   
}


V. 실행결과

-----+-----+-----+-----+-----+-----+-----+-----+-----
Field Name : file1
File Name : C:\Program Backup\AromNet11a\AromNet.exe
ContentType : application/octet-stream
File Size : 274432
-----+-----+-----+-----+-----+-----+-----+-----+-----
-----+-----+-----+-----+-----+-----+-----+-----+-----
Field Name : text1
Field Value : this is test
-----+-----+-----+-----+-----+-----+-----+-----+-----

큰 파일을 업로드한 경우 업로드 상태 출력

We are currently reading item 0
So far, 4096 of 338043623 bytes have been read.
We are currently reading item 1
So far, 1003477 of 338043623 bytes have been read.
We are currently reading item 1
So far, 2002901 of 338043623 bytes have been read.
We are currently reading item 1
So far, 3002325 of 338043623 bytes have been read.
We are currently reading item 1
So far, 4001749 of 338043623 bytes have been read.
We are currently reading item 1
So far, 5001173 of 338043623 bytes have been read.
We are currently reading item 1
So far, 6000597 of 338043623 bytes have been read.
We are currently reading item 1
So far, 7000021 of 338043623 bytes have been read.
We are currently reading item 1
So far, 8003498 of 338043623 bytes have been read.
We are currently reading item 1
So far, 9002922 of 338043623 bytes have been read.
We are currently reading item 1
So far, 10002346 of 338043623 bytes have been read.
We are currently reading item 1
So far, 11001770 of 338043623 bytes have been read.
We are currently reading item 1
So far, 12001194 of 338043623 bytes have been read.
We are currently reading item 1
So far, 13000618 of 338043623 bytes have been read.
We are currently reading item 1
So far, 14000042 of 338043623 bytes have been read.
We are currently reading item 1
So far, 15003605 of 338043623 bytes have been read.
We are currently reading item 1
So far, 16003029 of 338043623 bytes have been read.

...


=============================================

본문서는 자유롭게 배포/복사 할수 있지만

이문서의 저자에 대한 언급을 삭제하시면 안됩니다

저자 : GoodBug (unicorn@jakartaproject.com)

최초 : http://www.jakartaproject.com 

=============================================

스트럿츠를 사용하면서 메시지 파일을 매번 native2ascii로 컴파일하기 짜증나고 귀찮으셨죠?

build.xml에 걸어놔도 결국 똑같은 파일이 2개씩 유지되는게 왠지 찜찜하지 않으신가요?

이것은 스트럿츠에서 메시지 파일을 읽어올때 사용하는 Java의 Properties 클래스가 ISO 8859-1만 지원해서 생기는 문제로, 스트럿츠의 MessageResourcesFactory를 상속받아 메시지 파일을 UTF-8로 읽도록 구현하면 해결할 수 있습니다. UTF-8은 단일 문자셋으로 여러 언어를 지원하므로 한국어 뿐만 아니라 다른 언어를 사용할때도 번거롭게 native2ascii를 사용할 필요가 없게 됩니다.

스트럿츠 1.2 코어에서 테스트했습니다. (Validiator는 안해봐서 모름)

소스는 PUBLIC DOMAIN(저작권 없음)입니다. 상업적으로 쓰던 일부만 잘라쓰던 고쳐쓰던 마음껏 쓰세요.

추가:Locale 검색하는 메소드는 스트럿츠의 코드이며 스트럿츠 코드는 아파치 라이센스입니다.

출처 : okjsp

+ Recent posts