/*********************************************************************************************************
 * : UploadedFiles.java : 2003.12.30 : 2003.11.15
 **********************************************************************************************************/

package kr.co.kihyun.io;

import java.io.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class OPTFileWriter {
    
    private static final Logger LOG = LoggerFactory.getLogger(OPTFileWriter.class);
        
    public void fileWrite(String fileName, String data) throws IOException {
        
        FileWriter fw = null;
        BufferedWriter outFile = null;
        
        try {
            //9.디렉토리 경로 조작(프로퍼티로딩)_CWE-22/23 : Add by KWON,HAN
            if(fileName.contains("..") || fileName. contains("/")) { // 특수문자열 검증
                LOG.debug("9.디렉토리 경로 조작(프로퍼티로딩)_CWE-22/23 : Not Test {}", fileName);
                return;
            }
            //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
                
            fw = new FileWriter(fileName);
            outFile = new BufferedWriter(fw);
            
            if (data != null) {
                outFile.write(data);
            }
            outFile.flush();
            //outFile.close();
        
        } catch (FileNotFoundException exception) {
                //34.오류메세지를 통한 정보 노출(toString)_CWE-209 : Update by YOUNGJUN,CHO
                //System.out.println("The file " + fileName + " was not found.");
                LOG.error("\nThe file {} was not found.", fileName);
                //================================================
        } catch (IOException exception) {
                //34.오류메세지를 통한 정보 노출(toString)_CWE-209 : Update by YOUNGJUN,CHO
                //System.out.println(exception);
                LOG.error("\nOPTFileWriter fileWrite() Exception - {}", exception.toString());
                //================================================                        
        } catch (ArrayIndexOutOfBoundsException e) {
            //31.오류 상황 대응 부재_CWE-390 Add by YOUNGJUN,CHO
            e.printStackTrace();
            //++++++++++++++++++++++++++++++++++++++++++++++++
        } finally {
            //v2 21.부적절한 자원 해제 (IO)_CWE-404 : Add by YOUNGJUN,CHO
            // 파일에 쓴 후, finally 에서 닫도록 수정함.
            if(outFile != null) {
                outFile.close();
            }
            
            if (fw != null) {
                fw.close();
            }
            //++++++++++++++++++++++++++++++++++++++++++++++++
        }
    }
}
