2009. 9. 14. 16:51

자바 정리 참고 1




<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" /> 

ResourceBundle 클래스, Properties 클래스 

ResourceBundle 클래스
Properties
클래스
 

jsp 파일에서 web.xml 의 값 읽어오기

################################################

ResourceBundle 클래스
리소스번들을 이용하여 프로퍼티 파일을 읽어오기
# Res_test.properties
SINCE_YEAR=2007
SINCE_MONTH=9
SINCE_DATE=2
SINCE_DAY=Sunday

import java.util.ResourceBundle;
import java.util.Enumeration;

public class ResourceBundleTest
{
 public static void main(String[] args)
 {
  ResourceBundle bundle = null;
  try{
   bundle = ResourceBundle.getBundle("Res_test");//test.Res_test

   Enumeration enum1 = bundle.getKeys();
   for(; enum1.hasMoreElements() ; ){
    String name = (String)enum1.nextElement();
    String value = bundle.getString(name);
    System.out.println(name+" : "+value);
   }
  }catch(Exception e){
   e.toString();
  }
 }
}


################################################
Properties
클래스
프로퍼티 파일에 입력하고 불러오는 PropertyTest .java 파일

import java.util.*;
import java.io.*;
/*
 * Can use globels.properties
 * Properties
 **/
class Property_Sub{
  
 private String PROPERTIES_FILE="C://java/exam/globals.properties";//globals.properties
 
 public String getProperty(String keyName){
  String value = null;
  try{
   Properties props =  new Properties();
   FileInputStream fis  = new FileInputStream(PROPERTIES_FILE);
   props.load(new java.io.BufferedInputStream(fis));
   value = props.getProperty(keyName).trim();
   fis.close();   
  }catch(java.lang.Exception e){
   e.printStackTrace();
  } 
  return value;
 }
 
 public void setProperty(String keyName, String value){
  try{
   Properties props = new Properties();
   FileInputStream fis  = new FileInputStream(PROPERTIES_FILE);
   props.load(new java.io.BufferedInputStream(fis));
   props.setProperty(keyName, value);
   props.store(new FileOutputStream(PROPERTIES_FILE), "");
   fis.close();
  }catch(java.lang.Exception e){
   e.printStackTrace();
  }
 }
 
}

public class PropertyTest extends Property_Sub{
 
 public static void main(String[] args){
  
  PropertyTest o = null;
  
  if(args.length == 1){
   o = new PropertyTest();
   System.out.println (args[0] + " : " + o.getProperty(args[0]) );
  }
  else if(args.length == 2){
   o = new PropertyTest();
   o.setProperty(args[0], args[1]);
   System.out.println(args[0] + " : " + o.getProperty (args[0]) );
  }
  else{
   System.out.println("wrong argument");
   
  }
  
 }
}
#
#globals.properties
db=sadong
driver=oracle
name=richard

################################################
jsp
파일에서 web.xml 의 값 읽어오기

web.xml 에는
<context-param>
  <param-name>jdf.config.file</param-name>
  <param-value>D:\eclipse\WEB-INF\jdf.properties</param-value>
</context-param>

jsp 에서는
getServletContext().getInitParameter("jdf.config.file")
 

################################################
import java.util.ResourceBundle;

ResourceBundle userxconfig = ResourceBundle.getBundle("com.aaa.bbb.userxconfig");
String CURR_HOST = (String)userxconfig.getObject("currHost");

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

userxconfig.properties 파일에
currHost=
www.naver.com

이라는 부분이 있을 경우

CURR_HOSTwww.naver.com이 할당된다.

 

 

 

JSP 기초과정

1. JSP 개요

2. 설치와 Setting

3. JSP에서 사용하는 스크립팅 요소들

4. JSP 유용한 클래스

 

#####################################################################

1. JSP 개요

- 서블릿(Servlet) CGI 프로그래밍에 대한 자바 기술의 대안이다.

- CGI 프로그램이 비교적 빠른 수행능력을 보인다면 프로세스가 시작할 때의 오버헤드를 빠른 수행시간으로 메울 수 있지만

그렇지 못하다. 서블릿을 쓸 때는 자바 가상 머신이 떠 있는 상태에서 각 요청이 들어올 때 마다 프로세스보다 가벼운 자바

스레드가 실행된다.

- Java Server Pages (JSP)는 동적인 HTML과 정적으로 생성된 HTML을 섞어 주는 기술이다. JSP

디자인 부분과 로직 부분이 나뉘어 있어 쉽게 일을 분리할 수 있다.

 

#####################################################################

2. 설치와 Setting

- 사용환경 J2SDK1.4 / Tomcat5.0 / MySQL4.0

- CLASSPATH란 자바가 어디서 클래스를 찾을 수 있는지 명시해 놓은 변수다. 이것이 명시되어 있지 않다면 자바는 현재

디렉토리와 표준 시스템 라이브러리에서 클래스를 찾게 된다. CLASSPATH를 설정할 때 현재 디렉토리를 나타내는 '.'

빼놓지 않도록 유의한다.

 

2.1 Unix (C Shell)

setenv CLASSPATH .:servlet_dir/servlet.jar:servlet_dir/jsp.jar:$CLASSPATH

 

2.2 Windows 95/98/NT

set CLASSPATH=.;servlet_dir/servlet.jar;servlet_dir/jsp.jar;%CLASSPATH%

 

2.3 Path setting

ex1) Windows98 - 시작\실행\sysedit\AUTOEXEC.BAT

 SET PATH=%PATH&;C:\JDK1.4\BIN

 SET JAVA_HOME=C:\j2sdk1.4

 SET TOMCAT_HOME=C:\TOMCAT4

 SET CLASSPATH=.;C:\tomcat5\common\lib\servlet-api.jar

 

ex2) WindowsXP, Windows2000 - 내컴퓨터\등록정보\환경변수\시스템변수

 PATH          C:j2sdk1.4\bin

 JAVA_HOME     C:\j2sdk1.4

 CATALINA_HOME C:\Tomcat5

 

2.4 Classpath setting servlet_api.jar, rt.jar 세팅함

CLASSPATH       .;C:\tomcat5\common\lib\servlet-api.jar

               ;C:\j2sdk1.4\jre\lib\rt.jar

(JDK1.2이후는 classpath를 따로 지정하지 않아도 됨)

참고 SET CLASSPATH=%CLASSPATH%;c:\tomcat4\lib\servlet.jar;c:\jdk1.3\jdbc\mm.mysql-2.02-bin.jar

톰켓에서만 JDBC를 사용하려면 TOMCAT\LIB밑에 mm.mysql-2.0.2-bin.jar파일을 복사

 

http://mmmysql.sourceforge.net mm.mysql-2.0.1-bin.jar를 다운받는다.

http://dev.mysql.com/downloads/connector/j/3.1.html 에서

mysql-connector-java-3.1.10.zip 다운받는다

 

- 확인방법 java -version, javap org.gjt.mm.mysql.Driver로 확인

c:\mysql\bin>mysql-max-nt -install

c:\mysql\bin>net start mysql

c:\mysql\bin>net stop mysql

c:\mysql\bin>mysql -u root -p

mysql>show databases;

mysql>show tables;

mysql>use mydb;

mysql>desc tablename;

mysql>create mydb;

mysql>exit;

 

"로드하고 연결하고 실행한다"

Class.forName("org.gjt.mm.mysql.Driver");

Class.forName("oracle.jdbc.dirver.OracleDriver");

Class.forName("sun.jdbc.odbc.jdbcOdbcDriver");

Class.forName("postgresql.Driver");

 

Connection conn =

DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb","id","passwd");

Connection conn =

DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:ORCL","id","passwd");

Connection conn =

DriverManager.getConnection("jdbc:odbc:odbc원본명","id","passwd");

 

 

2.5 작업용 Context를 하나 만들기로 하자.

- c:\tomcat5\webapps\bit 라는 디렉토리를 만들자.

- c:\tomcat5\conf\server.xml에서 </host> 앞쪽에 다음을 추가하자.

 

----------------------------------------------------------------

<!-- Tomcat bit Context -->

<Context path="/bit" docBase="c:/tomcat5/webapps/bit" debug="0"

reloadable="true" />

-----------------------------------------------------------------

- c:\tomcat5\webapps\bit\WEB-INF\web.xml을 아래와 같이 만들자.

------------------------------------------------------------------

<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app

PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"

"http://java.sun.com/dtd/web-app_2_3.dtd">

 

<web-app>

<servlet>

<servlet-name>HelloWorld</servlet-name>

<servlet-class>HelloWorld</servlet-class>

</servlet>

 

<servlet-mapping>

<servlet-name>HelloWorld</servlet-name>

<url-pattern>/servlet/HelloWorld</url-pattern>

</servlet-mapping>

</web-app>

------------------------------------------------------------------

Tomcat5.0 이하 버젼에서는 서블릿을 실행할때 설정하는 web.xml 내용임

<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app

   PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"

   "http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>

 <display-name>Welcome to Tomcat</display-name>

 <description>

    Welcome to Tomcat

 </description>

 <servlet-mapping>

       <servlet-name>invoker</servlet-name>

       <url-pattern>/servlet/*</url-pattern>

  </servlet-mapping>

</web-app>

 

 

2.6. c:\tomcat5\webapps\bit\WEB-INF\classes 디렉토리를 만들고

C:\j2sdk1.4\bin\java.exe -jar -Duser.dir="C:\Tomcat4.1"

"C:\Tomcat4.1\bin\bootstrap.jar" start

 

HelloWorld.java 서블릿을 만들자.

 

//HelloWorld.java

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

 

public class HelloWorld extends HttpServlet {

       public void doGet(HttpServletRequest req, HttpServletResponse res)

throws ServletException, IOException{

       res.setContentType("text/html; charset=euc-kr");

       PrintWriter out = res.getWriter();

 

       out.println("<html>");

       out.println("<head><title>Hello World!</title></head>");

       out.println("<body>");

       out.println("<BIG>Hello World!</BIG>");

       out.println("</body></html>");

       }

}

 

#####################################################################

3. JSP에서 사용하는 스크립팅 요소들

 

- 스크립트들과 그 역할

- 스크립트렛(Scriptlet) <% %>  _jspService에 프로그램 추가

- 표현식(Expressions) <%= %>   _jspService에 프로그램 추가(out.print의 간략화)

- 선언문(Declarations) <%! %>  .java파일에 멤버필드와 멤버메서드 추가

- 지시문(Directives) <%@ %>    .java파일에 여러 가지 속성 정하기(지시문의 형태에 따라 .java파일의

적당한 장소에 추가)

 

java.io (PrintWriter 등을 위해서)

javax.servlet (HttpServlet 등을 위해서)

javax.servlet.http (HttpServletRequest HttpServletResponse를 위해서)

 

"javac directory\ServletClass.java" (윈도 사용자; 백 슬래시)

"javac directory /ServletClass.java" (유닉스 사용자; 슬래시)

 

3.1 Page 지시문과 import 사용하기

ex)

- Date.jsp, contentType="text/html;charset=ksc5601"  8859_1

 

<%@ page contentType="text/html;charset=euc-kr"%>

 

<%@ page import="java.util.*"%>

<%

       Date date = new Date();

       out.println("오늘의 날짜는 "+date);

%>

 

 

ex) <%@ page 속성="" %>

<%@ page session="false"%> 기본값은 true, session 을 사용할 것인지 여부

<%@ page isThreadSafe="true"%> 기본값은 false, 여러클라이언트의 요청이 동시에 이루어질때 문제가

일어나는 것을 막고자할때 사용

<%@ page errorPage="error.jsp"%> 에러가 발생되었을때 이동하는 페이지

<%@ page isErrorPage="true"%> 이페이지가 에러페이지로 사용되는 페이지인지 아닌지정함

 

3.2 JSP 내장 객체 - 9

- out, request, response, session

- pageContext(javax.servlet.jsp.PageContent) - 내장객체와 page 지령문의 몇가지 속성을 초기화할때

- application(javax.servlet.ServletContent) - 애플리케이션에 대한 정보를 가져올때

- config(javax.servlet.ServletCongfig) - ServletConfig의 내장객체

- page(javax.servlet.jsp.HttpJspPage) - 페이지 자신을 참조하는 객체

- exception(java.lang.Throwable) - 에러페이지에만 사용

 

package org.apache.jsp;  import org.apache.jasper.runtime.*;

<%@ page import="javax.servlet.*, javax.servlet.http.*, javax.servlet.jsp.*"%>

 

1. out 객체

- javax.servlet.jsp.JspWriter 클래스에 대한 내장객체

 

2. request 객체 - get, post, cookie 불러오기(getCookie()), 헤더정보가저오기

- javax.servlet.http.HttpServletRequest 클래스의 내장객체

 

ex1)

- formget.html

<form method="get" action="getform.jsp">

ID: <input type="text" name="id"><br>

PASS: <input type="password" name="pass"><br>

<input type="submit" value="submit"><input type="reset" value="reset">

</form>

- getform.jsp

 

<%@ page contentType="text/html;charset=euc=kr"%>

<%

 

       String id = request.getParameter("id");

       String pass = request.getParameter("pass");

       out.println("Id : "+id+"<br>");

       out.println("Password : "+pass+"<hr>");

       out.println("<a href='javascript:history.back(-1)'>Rear</a>";)

%>

ex2)

- formpost.html

<form method="post" action="postform.jsp">

ID: <input type="text" name="id"><br>

PASS: <input type="password" name="pass"><br>

<input type="submit" value="submit"><input type="reset" value="reset">

</form>

- postform.jsp

 

<%@ page contentType="text/html;charset=euc=kr"%>

<%

 

       String id = new String(request.getParameter("id").getBytes("8859_1"),

"euc-kr");

       String pass = request.getParameter("pass");

       out.println("Id : "+id+"<br>");

       out.println("Password : "+pass+"<hr>");

       out.println("<a href='javascript:history.back(-1)'>Rear</a>";)

%>

 

ex3)

- headerInfo.jsp

<%

       out.println("현재문서의경로 "+request.getRequestURI());

       out.println("호스트명           "+request.getHeader("HOST"));

       out.println("브라우저       "+request.getHeader("User-Agent"));

       out.println("파일명         "+request.getServletPath());

       out.println("서버명         "+request.getServerName());

       out.println("포트명         "+request.getServerPort());

       out.println("URL

http://"+request.getServerName()+":"+request.getServerPort()+getServletPath());

%>

 

3. response 객체 - mine타입지정, 헤더정보세팅, sendRedirect(), cookie값 저장(addCookie())

 

ex1)

- minesetting.jsp

<%

       response.setContentType("application/zip");

       out.println("hi ~~~");

%>

ex2)

- setheader.jsp

<%

       response.setHeader("Cache-Control","no-store");

       response.setHeader("Pragma","no-cache");

       //response.setHeader("Refresh","5;URL=http://www.yahoo.co.kr") 지정한시간에 url로 이동

%>

 

ex3)

- sendRedirect.jsp

<%

       response.sendRedirect("http://www.google.co.kr");

%>

- javascript.html

<script language="javascript">

       document.location.href='http://www.hotmail.com';

</script>

 

4. session 객체

- javax.servlet.http.HttpSession 에 대한 내장객체

 

#####################################################################

5. JSP 유용한 클래스

 

ex1)

- date-format.jsp

 

<%@ page contentType="text/html;charset=euc-kr"%>

 

<%@ page import="java.util.*, java.text.*"%>

<%

       try{

               Date date = new Date();

               SimpleDateFormat simpledateformat1 = new

SimpleDateFormat("yyyy-MM-dd h:mm: a");

               String style = "MM-dd-yyyy"

               SimpleDateFormat simpledateformat2 = new SimpleDateFormat(style);

               String today1 = simpledateformat1.format(date);

               String today2 = simpledateformat2.format(date);

 

               out.println("Today "+date+"<br>");

               out.println("Today Expression 1 "+today1+"<br>");

               out.println("Today Experssion 2 "+today2+"<br>");

 

       }catch(Exception e){

               out.println(e);

       }

%>

 

 

5.1 파일관련

ex1)

- fileorg.jsp

 

<%@ page contentType="text/html;charset=euc-kr"%>

<%@ page import="java.io.*"%>

<%

       try{

 

               String filename = "c:\\tomcat4.1\webapps\\root\\test.txt";

 

               //String filename = "/usr/local/tomcat5.0/webapps/root/test.txt";

               File file = new File(filename);

               file.createNewFile();

               out.println("파일생성<br>");

               if (file != null){

                       FileWriter fw = new FileWriter(filename);

 

                       String text="나는 파일로 쓰여질 문구\n두번째 라인\n세번째 라인";

 

                       fw.write(text);

                       fw.close();

                       out.println("파일쓰기완료<br>");

               }

               FileReader fr = new FileReader(filename);

           BufferedReader br = new BufferedReader(fr);

           //out.println(br.readLine());

           String line;

           while( (line=br.readLine())!=null ){

                          out.println(line+"<br>");

           }

 

               out.println("파일절대경로 "+f.getAbsolutePath());

               out.println("파일이름 "+f.getName());

               out.println("파일디렉토리 "+f.getParent()):

               out.println("파일크기 "+f.length());

               Thread.sleep(5000);

               if (f.exists()){

                       f.delete();

                       out.println("파일삭제");

               }else{

                       out.println("파일없슴");

 

               }

 

       }catch(Exception e){

               out.println(e);

       }

%>

 

<%-- jsp 주석 --%>

<!-- html주석 -->

<%@ include file="copyrigth.jsp"%>

 

#################################################

import java.sql.*;

public class ConnectionTest{

  public static void main(String[] args){

      try{

         Class.forName("org.gjt.mm.mysql.Driver");

         Connection conn =

DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb","root","");

         System.out.println("Connection클래스의 객체 con 생성");

         con.close();

         System.out.println("데이터베이스와 연결을 끊음");

      }catch(Exception e){}

  }

}

#################################################

 

 

유틸소스

import javax.crypto.*;

import javax.crypto.spec.SecretKeySpec;

import javax.crypto.spec.DESKeySpec;

import javax.crypto.spec.IvParameterSpec;

import java.security.*;

import sun.misc.BASE64Decoder;

import sun.misc.BASE64Encoder;

 

import java.io.UnsupportedEncodingException;

import java.security.MessageDigest;

import java.text.SimpleDateFormat;

import java.util.Calendar;

import java.util.Date;

import java.util.StringTokenizer;

import java.util.Vector;

 

import org.w3c.dom.*;

import javax.xml.parsers.DocumentBuilder;

import javax.xml.parsers.DocumentBuilderFactory;

import java.io.File;

import java.util.ArrayList;

import java.util.List;

import java.util.ResourceBundle;

 

public class Util {

        static byte[] seedKeyData = new byte[24];

        public Util(){   

        seedKeyData[0] = 0x01;

        seedKeyData[1] = 0x02;

        seedKeyData[2] = 0x03;

        seedKeyData[3] = 0x04;

        seedKeyData[4] = 0x05;

        seedKeyData[5] = 0x06;

        seedKeyData[6] = 0x07;

        seedKeyData[7] = 0x08;

        seedKeyData[8] = 0x09;

        seedKeyData[9] = 0x10;

        seedKeyData[10] = 0x11;

        seedKeyData[11] = 0x12;

        seedKeyData[12] = 0x13;

        seedKeyData[13] = 0x14;

        seedKeyData[14] = 0x15;

        seedKeyData[15] = 0x16;

        seedKeyData[16] = 0x01;

        seedKeyData[17] = 0x02;

        seedKeyData[18] = 0x03;

        seedKeyData[19] = 0x04;

        seedKeyData[20] = 0x05;

        seedKeyData[21] = 0x06;

        seedKeyData[22] = 0x07;

        seedKeyData[23] = 0x08;

        }

        public static String encTripleDES(String beforeStr) {

        String afterStr = "";

        try {

            SecretKeySpec desKey = new SecretKeySpec(seedKeyData, "DESede"); //seedKeyData로 암호화

            Cipher desCipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");

            byte[] cleartext = beforeStr.getBytes();

            desCipher.init(Cipher.ENCRYPT_MODE, desKey);

            byte[] ciphertext = desCipher.doFinal(cleartext);

            afterStr = (new BASE64Encoder()).encode(ciphertext);

        } catch (Exception e) {

            e.printStackTrace();

        }

        return afterStr;

    }

    public static String decTripleDES(String beforeStr) {        

        String afterStr = "";

        try {

            SecretKeySpec desKeyD = new SecretKeySpec(seedKeyData, "DESede");

            Cipher desCipherD = Cipher.getInstance("DESede/ECB/PKCS5Padding");

            desCipherD.init(Cipher.DECRYPT_MODE, desKeyD);

            byte[] decodedBytes = (new BASE64Decoder()).decodeBuffer(beforeStr);

            byte[] cleartext1 = desCipherD.doFinal(decodedBytes);

            afterStr = new String(cleartext1);

        } catch (Exception e) {

            e.printStackTrace();

        }

        return afterStr;

    }

    public static String getDate() {

        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        Date currentTime = new Date();

 

        return formatter.format(currentTime);

    }

    public static String cutRealNumber(String _real, int _cutPlace) {

        String result = _real;

        boolean isNumber = true;

        try {

            Double.parseDouble(_real);

        } catch (NumberFormatException e) {

            isNumber = false;

        }

        if (isNumber) {

            int pointIndex = _real.indexOf('.'); // 소수점 위치.

            if (pointIndex == -1) {

                // 소수점이 없을 때. 12 -> 12.000

                result += ".";

                for (int i = 0; i < _cutPlace; i++)

                    result += "0";

            } else {

                // 소수점이 있을 때.

                int decimalCount = (_real.length() - 1) - pointIndex; // 소수점 이하 개수 .

                if (_cutPlace > decimalCount) {

                    // 12.1 -> 12.100, 0.0 -> 0.000

                    for (int i = 0; i < _cutPlace - decimalCount; i++)

                        result += "0";

                } else if (_cutPlace < decimalCount) {

                    // 12.12345 -> 12.123

                    result = _real.substring(0, pointIndex + _cutPlace + 1);

                }

            }

        }

        return result;

    }

    public static String encode(String _origin) {

        String result = null;

        try {

            MessageDigest md5 = MessageDigest.getInstance("MD5");

            md5.update(_origin.getBytes());

            byte[] md5Password = md5.digest();

            BASE64Encoder enc = new BASE64Encoder();

            result = enc.encode(md5Password);

        } catch (Exception e) {

            e.printStackTrace();

        }

        return result;

    }

    public static String utfTo8859(String _str) {

        String result = "";

        try {

            if (_str != null)

                result = new String(_str.getBytes("UTF-8"), "8859_1");

        } catch (UnsupportedEncodingException e) {

            e.printStackTrace();

        }

        return result;

    }

    public static String kscTo8859(String _str) {

        String result = "";

        try {

            if (_str != null)

                result = new String(_str.getBytes("KSC5601"), "8859_1");

        } catch (UnsupportedEncodingException e) {

            e.printStackTrace();

        }

        return result;

    }

    public static String toKSC(String _str) {

        String result = "";

        try {

            if (_str != null)

                result = new String(_str.getBytes("8859_1"), "KSC5601");

        } catch (UnsupportedEncodingException e) {

            e.printStackTrace();

        }

        return result;

    }

    public static String toUTF(String _str) {

        String result = "";

        try {

            if (_str != null)

                result = new String(_str.getBytes("8859_1"), "UTF-8");

        } catch (UnsupportedEncodingException e) {

            e.printStackTrace();

        }

        return result;

    }

    // Unicode 2.0 -> Unicode 1.2

    public static String toUni12(String uni20) {

        int len = uni20.length();

        char[] out = new char[len];

        for (int i = 0; i < len; i++) {

            char c = uni20.charAt(i);

            if (c < 0xac00 || 0xd7a3 < c) {

                out[i] = c;

            } else  // 유니코드 2.0 한글 영역

            {

                try {

                    byte[] ksc = String.valueOf(c).getBytes("KSC5601");

                    if (ksc.length != 2) {

                        out[i] = '\ufffd';

                        System.err.println("Warning: Some of Unicode 2.0 hangul character was ignored.");

                    } else {

                        out[i] = (char) (0x3400 +

                                ((ksc[0] & 0xff) - 0xb0) * 94 +

                                (ksc[1] & 0xff) - 0xa1);

                    }

                } catch (UnsupportedEncodingException ex) {

                    throw new InternalError("Fatal Error: KSC5601 encoding is not supported.");

                }

            }

        }

        return new String(out);

    }

    // Unicode 1.2 -> Unicode 2.0

    public static String fromUni12(String uni12) {

        if (uni12 == null)

            uni12 = "";

        int len = uni12.length();

        char[] out = new char[len];

        byte[] ksc = new byte[2];

        for (int i = 0; i < len; i++) {

            char c = uni12.charAt(i);

            if (c < 0x3400 || 0x4dff < c) {

                out[i] = c;

            } else if (0x3d2e <= c) // 유니코드 1.2 한글 보충 영역 A, B

            {

                System.err.println("Warning: Some of Unicode 1.2 hangul character was ignored.");

                out[i] = '\ufffd';

            } else // 유니코드 1.2 KSC5601 대응 한글 영역

            {

                try {

                    ksc[0] = (byte) ((c - 0x3400) / 94 + 0xb0);

                    ksc[1] = (byte) ((c - 0x3400) % 94 + 0xa1);

                    out[i] = new String(ksc, "KSC5601").charAt(0);

                } catch (UnsupportedEncodingException ex) {

                    throw new InternalError("Fatal Error: KSC5601 encoding is not supported.");

                }

            }

        }

        return new String(out);

    }

    public String removeSpecialChar(String str) throws Exception {

        if (str == null || str.trim().length() == 0) return "";

        StringBuffer data = new StringBuffer(str);

        StringBuffer buf = new StringBuffer();

        for (int i = 0; i < data.length(); i++) {

            char c = data.charAt(i);

            if (((int) c > 47 && (int) c < 58)

                    || ((int) c > 64 && (int) c < 91)

                    || ((int) c > 96 && (int) c < 123))

                buf.append(c);

        }

 

        return buf.toString();

    }

    public static int cpMapping(int cpNum) {

        if (cpNum == 99)

            cpNum = 0;

        else if (cpNum == 20)

            cpNum = 15;

        else if (cpNum < 1 || cpNum > 15) cpNum = 0;

        return cpNum;

    }

    public static long diffDate(Calendar cal1, Calendar cal2) {

        long cal1sec = cal1.getTime().getTime();

        long cal2sec = cal2.getTime().getTime();

 

        long gap = cal1sec - cal2sec;

 

        long gapday = (gap / 86400) / 1000;

 

        return gapday;

    }

    public static String sqlInsectionProctect(String str) {

        if (str == null) return "";

        str = str.replace('\'', '\\');

        return str;

    }

    public static String removeSlush(String str) throws Exception {

        if (str == null || str.trim().length() == 0) return "";

        int i;

        while ((i = str.indexOf("/")) > -1) {

            str = str.substring(0, i) + str.substring(i + 1);

        }

 

        return str;

    }

    public static String removeDot(String str) throws Exception {

        if (str == null)

            return "";

        else {

            int i = -1;

            if ((i = str.indexOf(".")) > -1) {

                str = str.substring(0, i);

            }

            return str;

        }

    }

    public static String change_Code(String line, String oldString, String newString) {

        for (int index = 0; (index = line.indexOf(oldString, index)) >= 0; index += newString.length())

            line = line.substring(0, index) + newString + line.substring(index + oldString.length());

        return line;

    }

    public static String convertDate(String dateValue, String dateFormat, String gubun) {

        if (dateFormat == null || dateValue == null || dateValue.length() != 10) {

            return dateValue;

        } else if (dateFormat.equals("yyyy-MM-dd")) {

            return dateValue;

        } else {

            StringBuffer transDate = new StringBuffer(15);

            if (dateFormat.equals("dd-MM-yyyy"))

                return transDate.append(dateValue.substring(8, 10)).append(gubun).append(dateValue.substring(5, 7)).append(gubun).append(dateValue.substring(0, 4)).toString();

            else if (dateFormat.equals("MM-dd-yyyy"))

                return transDate.append(dateValue.substring(5, 7)).append(gubun).append(dateValue.substring(8, 10)).append(gubun).append(dateValue.substring(0, 4)).toString();

        }

        return "";

    }

    public static String[] splitString(String inputValue, String deli) {

        StringTokenizer st = null;

        String[] returnValue = null;

        try {

            st = new StringTokenizer(inputValue, deli);

            returnValue = new String[st.countTokens()];

            int i = 0;

            while (st.hasMoreTokens())

                returnValue[i++] = (st.nextToken());

        } catch (Exception ex) {

            returnValue = null;

        }

        return returnValue;

    }

    public static String[] splitStringIncludeNull(String inputValue, String deli) {

        StringTokenizer st = null;

        String[] returnValue = null;

        try {

            Vector returnVec = new Vector();

            st = new StringTokenizer(inputValue, deli, true);

            int count = st.countTokens();

            String previousValue = new String(deli);

            for (int i = 0; i < count; i++) {

                String currentValue = st.nextToken();

                if (previousValue.equals(currentValue)) {

                    returnVec.add("");

                } else {

                    if (!currentValue.equals(deli)) {

                        returnVec.add(currentValue);

                    }

                }

                previousValue = currentValue;

            }

            if (inputValue.substring((inputValue.length() - 1), (inputValue.length())).equals(deli))

                returnVec.add("");

            returnValue = new String[returnVec.size()];

            for (int i = 0; i < returnVec.size(); i++)

                returnValue[i] = (String) returnVec.get(i);

        } catch (Exception ex) {

            ex.printStackTrace();

            returnValue = null;

        }

        return returnValue;

    }

        public static String toEng (String ko)  {

               if (ko == null) {

                       return null;

               }             

               try {

                       return new String(ko.getBytes("KSC5601"),"8859_1");

               } catch(Exception e) {

                       return ko;

               }

        }

        public static String toKor (String en) {

               if (en == null) {

                       return null;

               }

               try {

                       return new String (en.getBytes("8859_1"), "KSC5601");

               } catch(Exception e) {

                       return en;

               }

        }

        /**

     * @param sDATE   : 입력 날짜 ==> 2000/03/09

     * @param sFORMAT : 날짜 형식(대소문자 구분없음) ==> YYYY/MM/DD

     *                ex) validDate("20040429", "yyyymmdd");

     *                validDate("2004-04-29", "yyyy-mm-dd");

     *                validDate("2004/04/29", "yyyy/mm/dd");

     */

    public static boolean validDate(String sDATE, String sFORMAT) {

        boolean bRET = false;

        sFORMAT = sFORMAT.toUpperCase();

        int iYYYY = Integer.parseInt(sDATE.substring(sFORMAT.indexOf("YYYY"), sFORMAT.indexOf("YYYY") + 4));

        int iMM = Integer.parseInt(sDATE.substring(sFORMAT.indexOf("MM"), sFORMAT.indexOf("MM") + 2));

        int iDD = Integer.parseInt(sDATE.substring(sFORMAT.indexOf("DD"), sFORMAT.indexOf("DD") + 2));

        bRET = iYYYY >= 0 && iYYYY < 10000 && iMM > 0 && iMM < 13 && iDD > 0 && iDD < 32;

        return bRET;

    }

  

        public static String checkDate(String input){

               String reVal = null;

               try

               {

                       if (input==null||input.length()!=8)

                       {

                              return input;

                       }else if (input.equals("00000000"))

                       {                     

                              return "99991231";

                       }      

                       Calendar ca = Calendar.getInstance();

                       int year = Integer.parseInt(input.substring(0,4));

                       int month = Integer.parseInt(input.substring(4,6));

                       int date = Integer.parseInt(input.substring(6));

                       ca.set(year, month-1, date);

                       String simple = "yyyyMMdd";

                       SimpleDateFormat simpledateformat = new SimpleDateFormat(simple);

                       reVal = simpledateformat.format(ca.getTime());

               }

               catch (Exception e)

               {

                       e.printStackTrace();

                       return input;

               }

               return reVal;

        }

        /**

        * 파라메터(data)의 스트링을 파라메터(before)인 문자열을 파라메터(after)로 대치한다.

        */

        public static String replaceAll(String data, String before, String after) throws Exception {

               // 쓰기전에 이스케이프 문자 처리

               if (data.length() < before.length())

                       return data;

               StringBuffer buf_data = new StringBuffer(data);

               StringBuffer buf_before = new StringBuffer(before);

               StringBuffer buffer = new StringBuffer();

               for (int i = 0; i < buf_data.length(); i++) {

                       if (buf_data.charAt(i) == buf_before.charAt(0)) {

                              if (i + before.length() <= buf_data.length() && buf_data.substring(i, i + before.length()).equals(before)) {

                                      buffer.append(after);

                                      i += buf_before.length() - 1;

                                      continue;

                              }

                       }

                       buffer.append(buf_data.charAt(i));

               }

               return buffer.toString();

        }

 

        public static String nvl(String str, String str2) {

               String retVal = null;

               if (str == null) {

                       retVal = str2;

               } else {

                       retVal = str;

               }

               return retVal;

        }

 

        public static void main(String[] args){

               try{

                       if (args.length > 0) {

                              for (int i = 0; i < args.length; i++) {

                                      String s = Util.encTripleDES(args[i]);

                                      String s1 = Util.decTripleDES(s);

                                      System.out.println("Original     ["+args[i]+"]");

                                      System.out.println("encTripleDES ["+s+"]");

                                      System.out.println("decTripleDES ["+s1+"]");

                              }      

                       }      

               } catch (Exception e) {

                       e.printStackTrace();

               }             

        }

}

 

 

 

자바소스 정리

01. ServerSocket Socket 간의 채팅 소스

02. Swing에서 이미지 아이콘 삽입 및 종료

03. RMI 정상적인 예제

04. RMI registry 등록하지 않고 사용

05. RMI 통신법

06. Directory 찾아서 리스트 만들기

07. IO 관련 소스

08. 파일을 읽는 소스

09. 입력받은 파일을 읽는 소스

10. 스트링을 파일로 저장하는 소스

11. 파일을 저장하는 소스

12. 에디터에는 볼 수 없으나 도스에서는 보임

13. Properties 파일에 관련된 소스

14. 파일과 관련해서 Properties 에서 읽어 오는 소스

15. 읽은 파일입력 후 내용확인하는 소스

16. 입력파일과 저장할 파일을 쓰는 소스

17. 파일을 읽어서 보여주는 소스

18. 2초마다 출력하는 쓰레드 소스

19. 배열과 관련하여

20. 배열로 합계 평균을 내는 소스

21. 프로그램 인수를 받아 평균과 총계를 보여주는 소스

22. 실행되지 않으나 참고해야 할 소스

23. 데이터베이스 커넷션하고 로그파일을 만듬

24. 엔터키를 두르면 검색하는 소스

25. 날짜 포맷 바꾸는 방법

26. Random 클래스로 가져온 값을 중복체크하기

27. TripleDES 을 이용한 암호화 알고리즘

28. MD5로 암호화 하는 알고리즘 (Base64 필요)

29. 버블 소트로 데이타 정렬

30. Random 함수로 받은 값을 중복 체크하는 소소

31. 날짜 관련 함수 이용

32. 특수문자 제거 메소드

33. 암호와 알고리즘을 사용후 복호화 하는 소스와 적용예

34. 특정 폴더에 쌓이는 파일을 없애는 소스

35. 원도우 배치 프로그램 실행하기

36. 메일을 발송하는 프로그램 소스

37. 세션관련 정리 소스

38. 로긴 및 서블릿 관련 소스(한글처리)

39. 쿠키 셋팅에 관한 예제

40. 클래스를 이용하는 샘플예제 소스

41. 버블 소트와 중복체크 예제

42. 날짜 체크하는 메소드 만들기

43. 조건에 맞게 메일을 보내는 소스

44. 로그를 만드는 소스

 

 

#####################################################################

44. 로그를 만드는 소스

#####################################################################

 

import java.io.*;

import java.text.SimpleDateFormat;

import java.util.Date;

 

public class LogMaker{

        static SimpleDateFormat simpledateformat = new SimpleDateFormat("HH:mm:ss");

       

        public static void println(String filename, String log){

               try{

                       Date date = new Date();

                       String pid = simpledateformat.format(date);

                       //System.out.println("LogMaker String pid->/"+pid+"/");

                       FileWriter fw = new FileWriter(filename+".log",true);

                       fw.write(pid + " : "+log+"\n");

                       fw.flush();

                       fw.close();

               } catch(Exception ex){

               }

        }

}

#####################################################################

 

#####################################################################

43. 조건에 맞게 메일을 보내는 소스

#####################################################################

 

import java.sql.*;

import java.util.*;

import java.io.*;

import javax.mail.*;

import javax.mail.internet.*;

import java.util.StringTokenizer;

import java.text.SimpleDateFormat;

import java.util.Date;

 

public class AirforwarderMailNCC extends Thread

{

        public static void main(String[] args) throws MessagingException

        {

                       Connection  conn_0 = null;

                       PreparedStatement pstmt_0 = null;

                       ResultSet rs_0 = null;

                      

                       String sDB_URL = "jdbc:oracle:thin:@165.213.251.202:1521:itts";

                       String sDB_USER = "itts";

                       String sDB_PASSWORD = "skan00";

              

                             

                       String name ="PTS_AirforwarderNCC";

                       String from = "pts.sec@samsung.com";

                       String to = null;

                       String title = "Notice from PTS";

                       String contents = null;

                       String host = "203.254.221.26"; 

                      

                       String logDir = "log";

                       SimpleDateFormat simpledateformat = new SimpleDateFormat("yyyy-MM-dd");

                       Calendar c = Calendar.getInstance();

                       Date d = c.getTime();

                       String fid = simpledateformat.format(d);

                       File resultFile = new File(logDir, fid);

                       if(resultFile.exists()== false)

                              resultFile.mkdir();

                       logDir = logDir + File.separator + fid;

                      

                       boolean ok1 = false, ok2 = false, ok3 = false;

 

                       try{

                              Class.forName("oracle.jdbc.driver.OracleDriver");                       

                             

                              StringBuffer sbSql_0 = new StringBuffer();                            

                             

                              sbSql_0.append(" SELECT EMAIL, USER_NAME, USER_ID FROM USER_INFO U, BASIC_CODE B WHERE  U.COMPANY_CODE=B.CODE AND DESC2 like 'AIR%' AND U.EMAIL IS NOT NULL AND U.STATUS='approved' AND U.PTS_MAIL='T' AND USER_TYPE='CARRIERLOAD' ");

                              conn_0 = DriverManager.getConnection(sDB_URL, sDB_USER, sDB_PASSWORD);

                              pstmt_0 = conn_0.prepareStatement(sbSql_0.toString());

                              rs_0 = pstmt_0.executeQuery();                        

                              int cnt_total = 0;

                             

                              while(rs_0.next()){     

                             

                                      int cnt_new = 0, cnt_change = 0, cnt_cancel = 0;

                                     

                                      to = rs_0.getString("EMAIL");

                                     

                                      //Count 보낼 메일 가져오기                                           

                                      StringBuffer sbSql_newmail = new StringBuffer(); //New Mail Count

                                      sbSql_newmail.append(" SELECT INV_NO, BILLNO_, UPDDATE, GETCONSIGNAME(CONSIG) CONSIG_NAME, GETCONSIGNAME(SHIPPE) SHIPPE_NAME, TRSTYP, MLDTUE, GI_DAT , A.CREDATE FROM INV_DOC A, USER_INFO U WHERE  USER_ID=? AND SHIPPE <> 'C100' AND A.SHIPPE = U.DEALING_SUBSIDIARY_CODE AND A.MLCARI = U.COMPANY_CODE AND MLCARI <> 'SITA' AND SHIPPE <> 'C100' AND TRSTYP = 'AIR' AND A.RCDFLG = 'A' AND A.UPDDATE = '99991231235959' AND MAIL_STS='F' ");

 

                                      Connection conn_1 = DriverManager.getConnection(sDB_URL, sDB_USER, sDB_PASSWORD);

                                      PreparedStatement pstmt_1 = conn_1.prepareStatement(sbSql_newmail.toString());

                                      pstmt_1.setString(1, rs_0.getString("USER_ID")); //순차적으로 조건을 셋팅

                                     

                                      ResultSet rs_1 = pstmt_1.executeQuery();

                                     

                                      while(rs_1.next()){                                           

                                             cnt_new = rs_1.getRow();                                            

                                      }

                                     

                                      pstmt_1.close();

                                      rs_1.close();

                                      conn_1.close();                               

                                     

                                      StringBuffer sbSql_changemail = new StringBuffer(); //Changed Mail Count

                                      sbSql_changemail.append(" SELECT INV_NO, BILLNO_, UPDDATE, GETCONSIGNAME(CONSIG) CONSIG_NAME, GETCONSIGNAME(SHIPPE) SHIPPE_NAME, TRSTYP, MLDTUE, GI_DAT , A.CREDATE FROM INV_DOC A, USER_INFO U WHERE  USER_ID=? AND SHIPPE <> 'C100' AND A.SHIPPE = U.DEALING_SUBSIDIARY_CODE AND A.MLCARI = U.COMPANY_CODE AND MLCARI <> 'SITA' AND SHIPPE <> 'C100' AND TRSTYP = 'AIR' AND A.RCDFLG = 'A' AND A.UPDDATE <> '99991231235959' AND MAIL_STS='F'  ");

 

                                      Connection conn_3 = DriverManager.getConnection(sDB_URL, sDB_USER, sDB_PASSWORD);

                                      PreparedStatement pstmt_3 = conn_3.prepareStatement(sbSql_changemail.toString());

                                      pstmt_3.setString(1, rs_0.getString("USER_ID")); //순차적으로 조건을 셋팅

                                      ResultSet rs_3 = pstmt_3.executeQuery();

                                     

                                      while(rs_3.next()){                                           

                                             cnt_change = rs_3.getRow();                                         

                                      }

                                      System.out.println("보낼 Change Content 갯수 "+cnt_change);    

                                      pstmt_3.close();

                                      rs_3.close();

                                      conn_3.close();

                             

                                      StringBuffer sbSql_cancelmail = new StringBuffer(); //Canceled Mail Count

                                      sbSql_cancelmail.append(" SELECT INV_NO, BILLNO_, UPDDATE, GETCONSIGNAME(CONSIG) CONSIG_NAME, GETCONSIGNAME(SHIPPE) SHIPPE_NAME, TRSTYP, MLDTUE, GI_DAT , A.CREDATE FROM INV_DOC A, USER_INFO U WHERE  USER_ID=? AND SHIPPE <> 'C100' AND A.SHIPPE = U.DEALING_SUBSIDIARY_CODE AND A.MLCARI = U.COMPANY_CODE AND MLCARI <> 'SITA' AND SHIPPE <> 'C100' AND TRSTYP = 'AIR' AND A.RCDFLG = 'D' AND MAIL_STS='F'        ");

 

                                      Connection conn_5 = DriverManager.getConnection(sDB_URL, sDB_USER, sDB_PASSWORD);

                                      PreparedStatement pstmt_5 = conn_5.prepareStatement(sbSql_cancelmail.toString());

                                      pstmt_5.setString(1, rs_0.getString("USER_ID")); //순차적으로 조건을 셋팅

                                      ResultSet rs_5 = pstmt_5.executeQuery();

                                     

                                      while(rs_5.next()){                                           

                                             cnt_cancel = rs_5.getRow();                                          

                                      }

                                      System.out.println("보낼 Cancel Content 갯수 "+cnt_cancel);     

                                      System.out.println();

                                      pstmt_5.close();

                                      rs_5.close();

                                      conn_5.close();

                                            

                                      // End 메일 카운터 RS_0 ~ RS_7

                                     

                                      //이쪽에서 한개의 메일을 받아서 아래의 컨텐츠를 보내야 함

                                      StringBuffer sbMessage = new StringBuffer();

                                     

                                      sbMessage.append("<html><head>");                                 

                                      sbMessage.append("<style type=\"text/css\" >");

                                      sbMessage.append("BODY,TD,font {");

                                      sbMessage.append("color: #666666; font-family: Arial;   font-size:9pt;line-height: 130%;}");

                                      sbMessage.append("A:link {color:#00639C;text-decoration: underline;}");

                                      sbMessage.append("A:visited {color:#006699;text-decoration:underline;}");

                                      sbMessage.append("A:active {color:#006699;text-decoration:none;}");

                                      sbMessage.append("A:hover {color:#FFFFFF;text-decoration:none;background-color:#E4628B;}");

                                      sbMessage.append("</style></head><body>");

                                     

                                      sbMessage.append("<table width=700 border=0 cellspacing=0 cellpadding=0>");  

                                      sbMessage.append("<tr><td height=4 bgcolor=#CDCDCD><img src=http://www.samsungitts.com/img/ptmail/blank.gif width=1 height=1></td></tr>");

                                      sbMessage.append("<tr><td height=43 bgcolor=#0A79A8><img src=http://www.samsungitts.com/img/ptmail/logo.gif width=127 height=43></td></tr></table>");

                                     

                                      sbMessage.append("<table width=700 border=0 cellspacing=0 cellpadding=0>");

                                      sbMessage.append("<tr><td width=551 class=text><Br><br><p>Dear,  "+rs_0.getString("USER_ID")+"</p><br><br>");

                                                                             

                                      sbMessage.append("Please, check the documents below.<br>");

                                      sbMessage.append("<b>*Total number of new invoices - <b>"+cnt_new+"</b> cases<br> </b>");

                                      sbMessage.append("<b>*Total number of changed invoices - <b>"+cnt_change+"</b> cases<br> </b>");

                                      sbMessage.append("<b>*Total number of canceled invoices - <b>"+cnt_cancel+"</b> cases<br> </b>");

                                                                           

                                      sbMessage.append("Please check it at <a href=http://www.samsungitts.com target=_blank>http://www.samsungitts.com</a></p> <br></p></td>");

                                      sbMessage.append("<td width=149 valign=top><img src=http://www.samsungitts.com/img/ptmail/img.jpg width=160 height=172></td></tr></table>");

 

                                      sbMessage.append("<table width=700 border=0 cellspacing=0 cellpadding=0><tr><td><p><b>New Invoice</b> (You have not opened or printed.)</p></td></tr></table>");

                                      sbMessage.append("<table width=700 border=0 cellspacing=0 cellpadding=0><tr><td bgcolor=#669900>");

                                      sbMessage.append("<table width=700 border=0 cellspacing=1 cellpadding=0>");

                                      sbMessage.append("<tr align=center bgcolor=#BBDD75>");

                                      sbMessage.append("<td height=20><strong>I/V No.</strong></td>");

                                      sbMessage.append("<td height=20><strong>B/L No.</strong></td>");

                                      sbMessage.append("<td height=20><strong>Consignee</strong></td>");

                                      sbMessage.append("<td height=20><strong>Trans Type</strong></td>");

                                      sbMessage.append("<td height=20><strong>ETA</strong></td>");

                                      sbMessage.append("<td height=20><strong>ETD</strong></td></tr>");          

                                     

                                      StringBuffer sbSql_1= new StringBuffer(); // New Mail Send

                                     

                                      sbSql_1.append(" SELECT INV_NO, BILLNO_,  GETCONSIGNAME(CONSIG) CONSIG_NAME,  TRSTYP, MLDTUE, GI_DAT FROM INV_DOC A, USER_INFO U WHERE  USER_ID=? AND SHIPPE <> 'C100' AND A.SHIPPE = U.DEALING_SUBSIDIARY_CODE AND A.MLCARI = U.COMPANY_CODE AND MLCARI <> 'SITA' AND SHIPPE <> 'C100' AND TRSTYP = 'AIR' AND A.RCDFLG = 'A' AND A.UPDDATE = '99991231235959' AND MAIL_STS='F'  ");

                      

                                      Connection conn_9 = DriverManager.getConnection(sDB_URL, sDB_USER, sDB_PASSWORD);

                                      PreparedStatement pstmt_9 = conn_9.prepareStatement(sbSql_1.toString());

                                      pstmt_9.setString(1, rs_0.getString("USER_ID")); //순차적으로 조건을 셋팅

                                     

                                      ResultSet rs_9 = pstmt_9.executeQuery();

                                     

                                      ok1 = false;

                                      while(rs_9.next()){

                                                 ok1 = true;        

                                                     sbMessage.append("<tr align=center bgcolor=#BBDD75>");

                                                     sbMessage.append("<td height=20>"+rs_9.getString("INV_NO")+"</td>");

                                                     sbMessage.append("<td height=20>"+rs_9.getString("BILLNO_")+"</td>");

                                                     sbMessage.append("<td height=20>"+rs_9.getString("CONSIG_NAME")+"</td>");

                                                     sbMessage.append("<td height=20>"+rs_9.getString("TRSTYP")+"</td>");

                                                     sbMessage.append("<td height=20>"+rs_9.getString("MLDTUE")+"</td>");

                                                     sbMessage.append("<td height=20>"+rs_9.getString("GI_DAT")+"</td>");

                                                     sbMessage.append("</tr>");    

                                                    

                                                     //Update

                                                     StringBuffer sb_update0 = new StringBuffer();

                                                     sb_update0.append (" UPDATE INV_DOC SET MAIL_STS='T' WHERE INV_NO=?  ");

                                                     Connection con_update0 = DriverManager.getConnection(sDB_URL, sDB_USER, sDB_PASSWORD);

                                                     PreparedStatement pstmt_update0 = con_update0.prepareStatement(sb_update0.toString());

                                                     pstmt_update0.setString(1, rs_9.getString("INV_NO"));

                                                     ResultSet rs_update0 = pstmt_update0.executeQuery();

                                                     con_update0.commit();

                                                     rs_update0.close();

                                                     pstmt_update0.close();

                                                     con_update0.close();                                         

                                                    

                                      }// 9 For

                                      pstmt_9.close();

                                      rs_9.close();

                                      conn_9.close();

                                      //데이타 없을때 처리

                                      if(!ok1){

                                                     sbMessage.append("<tr bgcolor=#ffffff><td colspan=6><center><b>No Data Found</b></center></td></tr>");

                                      }

                                     

                                      sbMessage.append("</table></table><br><br>");

 

                                      sbMessage.append("<table width=700 border=0 cellspacing=0 cellpadding=0><tr><td><p><b>Changed Invoice</b></p></td></tr></table>");

                                      sbMessage.append("<table width=700 border=0 cellspacing=0 cellpadding=0><tr><td bgcolor=#669900>");

                                      sbMessage.append("<table width=700 border=0 cellspacing=1 cellpadding=0>");

                                      sbMessage.append("<tr align=center bgcolor=#BBDD75>");

                                      sbMessage.append("<td height=20><strong>I/V No.</strong></td>");

                                      sbMessage.append("<td height=20><strong>B/L No.</strong></td>");

                                      sbMessage.append("<td height=20><strong>Consignee</strong></td>");

                                      sbMessage.append("<td height=20><strong>Trans Type</strong></td>");

                                      sbMessage.append("<td height=20><strong>ETA</strong></td>");

                                      sbMessage.append("<td height=20><strong>ETD</strong></td></tr>");

 

                                      StringBuffer sbSql_2= new StringBuffer(); //Changed Mail Send

                                     

                                      sbSql_2.append(" SELECT INV_NO, BILLNO_,  GETCONSIGNAME(CONSIG) CONSIG_NAME,  TRSTYP, MLDTUE, GI_DAT FROM INV_DOC A, USER_INFO U WHERE  USER_ID=? AND SHIPPE <> 'C100' AND A.SHIPPE = U.DEALING_SUBSIDIARY_CODE AND A.MLCARI = U.COMPANY_CODE AND MLCARI <> 'SITA' AND SHIPPE <> 'C100' AND TRSTYP = 'AIR' AND A.RCDFLG = 'A' AND A.UPDDATE <> '99991231235959' AND MAIL_STS='F'  ");

                                     

                                      Connection conn_10 = DriverManager.getConnection(sDB_URL, sDB_USER, sDB_PASSWORD);

                                      PreparedStatement pstmt_10 = conn_10.prepareStatement(sbSql_2.toString());

                                      pstmt_10.setString(1, rs_0.getString("USER_ID")); //순차적으로 조건을 셋팅

                                     

                                      ResultSet rs_10 = pstmt_10.executeQuery();

                                     

                                      ok2 = false ;

                                      while(rs_10.next()){

                                                     ok2 = true;                                                                                                                              

                                                     sbMessage.append("<tr align=center bgcolor=#BBDD75>");

                                                     sbMessage.append("<td height=20>"+rs_10.getString("INV_NO")+"</td>");

                                                     sbMessage.append("<td height=20>"+rs_10.getString("BILLNO_")+"</td>");

                                                     sbMessage.append("<td height=20>"+rs_10.getString("CONSIG_NAME")+"</td>");

                                                     sbMessage.append("<td height=20>"+rs_10.getString("TRSTYP")+"</td>");

                                                     sbMessage.append("<td height=20>"+rs_10.getString("MLDTUE")+"</td>");

                                                     sbMessage.append("<td height=20>"+rs_10.getString("GI_DAT")+"</td>");

                                                     sbMessage.append("</tr>");

                                                     //Do Update    

                                                     System.out.println("Change Invoice Number :::: "+rs_10.getString("INV_NO"));

                                                     StringBuffer sb_update1 = new StringBuffer();

                                                     sb_update1.append (" UPDATE INV_DOC SET MAIL_STS='T' WHERE INV_NO=?  ");

                                                     Connection con_update1 = DriverManager.getConnection(sDB_URL, sDB_USER, sDB_PASSWORD);

                                                     PreparedStatement pstmt_update1 = con_update1.prepareStatement(sb_update1.toString());

                                                     pstmt_update1.setString(1, rs_10.getString("INV_NO"));

                                                     ResultSet rs_update1 = pstmt_update1.executeQuery();

                                                     con_update1.commit();

                                                     rs_update1.close();

                                                     pstmt_update1.close();

                                                     con_update1.close();                                                 

                                                    

                                      } // 10 For

                                      pstmt_10.close();

                                      rs_10.close();

                                      conn_10.close();

                                      if(!ok2){

                                                     sbMessage.append("<tr bgcolor=#ffffff><td colspan=6><center><b>No Data Found</b></center></td></tr>");

                                      }                                            

                                     

                                      sbMessage.append("</table></table><br><br>");

                                     

                                      sbMessage.append("<table width=700 border=0 cellspacing=0 cellpadding=0><tr><td><p><b>Canceled Invoice</b> (The shipper has canceled.)</p></td></tr></table>");

                                      sbMessage.append("<table width=700 border=0 cellspacing=0 cellpadding=0><tr><td bgcolor=#669900>");

                                      sbMessage.append("<table width=700 border=0 cellspacing=1 cellpadding=0>");

                                      sbMessage.append("<tr align=center bgcolor=#BBDD75>");

                                      sbMessage.append("<td height=20><strong>I/V No.</strong></td>");

                                      sbMessage.append("<td height=20><strong>B/L No.</strong></td>");

                                      sbMessage.append("<td height=20><strong>Consignee</strong></td>");

                                      sbMessage.append("<td height=20><strong>Trans Type</strong></td>");

                                      sbMessage.append("<td height=20><strong>ETA</strong></td>");

                                      sbMessage.append("<td height=20><strong>ETD</strong></td></tr>");

 

                                      StringBuffer sbSql_3= new StringBuffer(); //Canceled Mail Send

                                     

                                      sbSql_3.append(" SELECT INV_NO, BILLNO_,  GETCONSIGNAME(CONSIG) CONSIG_NAME,  TRSTYP, MLDTUE, GI_DAT FROM INV_DOC A, USER_INFO U WHERE   SHIPPE <> 'C100' AND A.SHIPPE = U.DEALING_SUBSIDIARY_CODE AND A.MLCARI = U.COMPANY_CODE AND MLCARI <> 'SITA' AND SHIPPE <> 'C100' AND TRSTYP = 'AIR' AND A.RCDFLG = 'D' AND MAIL_STS='F' AND USER_ID=?   ");

                                     

                                     

                                      Connection conn_11 = DriverManager.getConnection(sDB_URL, sDB_USER, sDB_PASSWORD);

                                      PreparedStatement pstmt_11 = conn_11.prepareStatement(sbSql_3.toString());

                                      pstmt_11.setString(1, rs_0.getString("USER_ID")); //순차적으로 조건을 셋팅

                                     

                                      ResultSet rs_11 = pstmt_11.executeQuery();

                                     

                                      ok3 = false ;

                                      while(rs_11.next()){

                                                     ok3 = true;    

                                                     sbMessage.append("<tr align=center bgcolor=#BBDD75>");

                                                     sbMessage.append("<td height=20>"+rs_11.getString("INV_NO")+"</td>");

                                                     sbMessage.append("<td height=20>"+rs_11.getString("BILLNO_")+"</td>");

                                                     sbMessage.append("<td height=20>"+rs_11.getString("CONSIG_NAME")+"</td>");

                                                     sbMessage.append("<td height=20>"+rs_11.getString("TRSTYP")+"</td>");

                                                     sbMessage.append("<td height=20>"+rs_11.getString("MLDTUE")+"</td>");

                                                     sbMessage.append("<td height=20>"+rs_11.getString("GI_DAT")+"</td>");

                                                     sbMessage.append("</tr>");

                                                     //Do Update                                  

                                                     StringBuffer sb_update2 = new StringBuffer();

                                                     sb_update2.append (" UPDATE INV_DOC SET MAIL_STS='T' WHERE INV_NO=?  ");

                                                     Connection con_update2 = DriverManager.getConnection(sDB_URL, sDB_USER, sDB_PASSWORD);

                                                     PreparedStatement pstmt_update2 = con_update2.prepareStatement(sb_update2.toString());

                                                     pstmt_update2.setString(1, rs_11.getString("INV_NO"));

                                                     ResultSet rs_update2 = pstmt_update2.executeQuery();

                                                     con_update2.commit();

                                                     rs_update2.close();

                                                     pstmt_update2.close();

                                                     con_update2.close();                                                 

                                                    

                                      } // 11 For

                                      pstmt_11.close();

                                      rs_11.close();

                                      conn_11.close();

                                      if(!ok3){

                                                     sbMessage.append("<tr bgcolor=#ffffff><td colspan=6><center><b>No Data Found</b></center></td></tr>");

                                      }                             

                                     

                                      sbMessage.append("</table></table><br><br>");

                                     

                                      sbMessage.append("</table></table><br></td></tr></table><br>");

                                      sbMessage.append("<table width=700 border=0 cellspacing=0 cellpadding=0>");  

                                      sbMessage.append("<tr><td height=1 bgcolor=#CDCDCD><img src=http://www.samsungitts.com/img/ptmail/blank.gif width=1 height=1></td>      </tr>");

                                      sbMessage.append("<tr><td align=center>Copyright(c)2003 Samsung Electronics co.,Ltd. All rights reserved.</td></tr></table> </body></html>");

                                                            

                                      contents = sbMessage.toString();                             

                                     

                                      //System.out.println("내용 확인 222222222222 "+contents);

                                      if(ok1 || ok2 || ok3){

                                             StringTokenizer stTo = new StringTokenizer(to, ";");

                                             while(stTo.hasMoreTokens()){

                                                    

                                                     to = stTo.nextToken();

                                                     //메일 클래스 객체 생성

                                                     Properties prop = System.getProperties();      

                                                     Session session = Session.getInstance(prop, null);    

                                                     MimeMessage message = new MimeMessage(session);

                                                     message.setFrom(new InternetAddress(name+"<"+from+">"));

                                                     message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));    

                                                     message.setSubject(title);

                                                     message.setContent(contents,"text/html;charset=euc-kr");

                                                     //message.setText(contents);

                                                    

                                                     Transport transport = session.getTransport("smtp");

                                                     transport.connect(host,"","");    

                                                     transport.sendMessage(message, message.getAllRecipients());

                                                     transport.close();

                                                     LogMaker lm = new LogMaker();

                                                     lm.println(logDir+File.separator+"AirforwarderMailNCC", to);

                                                                                                 

                                             }

                                             ++cnt_total;

                                             System.out.println("Total Mail 갯수 "+cnt_total); 

                                      }else{

                                                     System.out.println("메일을 보내지 않는다");

                                                     System.out.println();

                                      }                                                                  

                              } //Mail For         

                       Thread.currentThread().sleep(50);

                       }catch(ClassNotFoundException e){

                              e.printStackTrace();

                       }catch(SQLException e){

                              e.printStackTrace();

                       }catch(Exception e){

                              e.printStackTrace();

                       }finally{

                              try{

                                      if(pstmt_0 != null){pstmt_0.close();}

                                      if(rs_0 != null){rs_0.close();}

                                      if(conn_0 != null){conn_0.close();}

                                     

                              }catch(Exception e){

                                      e.printStackTrace();

                              }

                       }

        }

}

 

#####################################################################

 

#####################################################################

42. 날짜 체크하는 메소드 만들기

#####################################################################

import java.util.*;

import java.text.*;

public class DateTest

{             

        public String checkDate(String input){                        

               String reVal = null;           

               //리턴 타입을 설정한다

               try

               {             

                       if ( input == null || input.length() != 8 )

                       {

                              return input;

                              //OR의 우선순위는 앞에 있슴. 에러사항을 체크하여 Return을 한다

                       }             

                       Calendar cl = Calendar.getInstance();

                       int yyyy = Integer.parseInt(input.substring(0, 4));

                       int month = Integer.parseInt(input.substring(4, 6));

                       int day = Integer.parseInt(input.substring(6));

                       //입력값에 대해서 substring으로 나누어 가져온다

                       cl.set(yyyy, month-1, day);

                       //Calendar에 년월일을 셋팅한다

                       /*

                       int yy = cl.get(Calendar.YEAR);

                       int mm = cl.get(Calendar.MONTH)+1;

                       int dd = cl.get(Calendar.DATE);                

                       System.out.println(yy +", "+mm+", "+dd);

                       */                    

                       String date_format = "yyyyMMdd";

                       SimpleDateFormat simpledateformat = new SimpleDateFormat(date_format);     

                       reVal = simpledateformat.format(cl.getTime());                                        

               }catch (Exception e)

               {      

                       e.printStackTrace();

                       return input;

               }

               return reVal;

               //try catch 구분 밖에서 Return 타입을 받는다

        }

        public static void main(String[] args)

        {

               DateTest dt = new DateTest();

               System.out.println( dt.checkDate("20050200") );

               //객체를 생성하여 메소드를 호출한다

        }      

}

 

#####################################################################

41. 버블 소트와 중복체크 예제

#####################################################################

import java.util.*;

public class RandomTest

{

        public static void main(String[] args)

        {

               Random random = new Random();

               boolean[] boo = new boolean[45];

               int[] choo = new int[6];

               for (int i=0; i<boo.length ;  )

               {

                       boo[i] = true;

               }

               for (int i=0; i<choo.length ; i++)

               {

                       int num = random.nextInt(45);

                       if (boo[num])

                       {

                              boo[num] = false;

                choo[i] = num+1;

                       }                             

                       System.out.println(choo[i]);

               }

        }

}

class SortTest

{

        public static void main(String[] args)

        {

               String[] str = {"Orange","Apple","Grape","Peach","Lemon"};

               System.out.println("@@@@@ 정렬 전 @@@@@");

               for (int i=0; i<str.length; i++)

               {

                       System.out.println(str[i]);

               }

               System.out.println("@@@@@ 정렬 후 @@@@@");

               for (int j=0; j<str.length ; j++ )

               {

                       for (int i= j+1 ; i<str.length ; i++)

                       {

                              if ( str[i].compareTo(str[j]) < 0 )

                              {

                                      String temp = str[j];

                                      str[j] = str[i];

                                      str[i] = temp;  

                              }

                       }

                       System.out.println(str[j]);                                     

               }

        }

}

#####################################################################

 

#####################################################################

40. 클래스를 이용하는 샘플예제 소스

#####################################################################

class TopScret

{

        private int scret;

        public void setScret(int x){

               scret = x;

        }

        public int getScret(){

               return scret;

        }

}

public class TopScretMain

{

        public static void main(String[] args){

       

               TopScret top = new TopScret();

               top.setScret(4000);

               int i = top.getScret();

               System.out.println("i ->"+i);

               System.out.println("top.getScret() ->"+top.getScret());

        }

};

 

class MeanCalc

{

        private int sum;

        private int num;

        public void setValue(int x, int y, int z, int n){

               sum = x * y * z;

               num = n;

        }

        public int getValue(){

               return sum - num;

        }

}

public class MeanCalcMain

{

        public static void main(String[] args){

               MeanCalc cal = new MeanCalc();

               cal.setValue(100, 40, 500, 6);

               int z = cal.getValue();

               System.out.println("z ->"+z);

               System.out.println("cal ->"+cal);

        }

};

 

class MotorCycle

{

        private int id;

        private int speed;

        public void setData(int x, int y){

               id = x;

               speed = y;

        }

        public void drive(){

               System.out.println("id ->"+id);

               System.out.println("speed ->"+speed);

        }

}

public class MotorCycleMain

{

        public static void main(String[] args){

               MotorCycle m = new MotorCycle();

               m.setData(5384, 120);

               m.drive();

               System.out.println("m ->"+m);

 

               MotorCycle c = m;

               c.setData(7777, 100);

               c.drive();

               System.out.println("c ->"+c);

        }

};

#####################################################################

 

 

#####################################################################

39. 쿠키 셋팅에 관한 예제

#####################################################################

<form method="post" action="setCookie.jsp">

<input type="text" name="id"><br>

<input type="password" name="passwd"><br>

<input type="submit"><input type="reset">

 

<%@ page contentType="text/html;charset=euc-kr"%>

<%

        String id = request.getParameter("id");

        String passwd = request.getParameter("passwd");

        String value = request.getHeader("Cookie");

        if (value == null){

               Cookie cookie = new Cookie(id, passwd);

               cookie.setMaxAge(60);

               response.addCookie(cookie);

               out.println("Setting Cookie<br><hr>");

               out.println("id :"+id+ "<br>passwd :"+passwd);

 

        }else{

               out.println("Have done Cookie<br><hr>");      

               out.println("id :"+id+ "<br>passwd :"+passwd+"<br>");

               Cookie[] cookies = request.getCookies();

               for (int i=0; i<cookies.length; i++){

                       out.println("name :"+cookies[i].getName()+"<br>");

                       out.println("value :"+cookies[i].getValue()+"<br>");

                       out.println("domain :"+cookies[i].getDomain()+"<br>");

                       out.println("maxage :"+cookies[i].getMaxAge()+"<br>");

                       out.println("path :"+cookies[i].getPath()+"<br>");

                       out.println("secure :"+cookies[i].getSecure()+"<br>");

                       out.println("comment :"+cookies[i].getComment()+"<br>");

                       out.println("version :"+cookies[i].getVersion()+"<br>");

               }

 

        }

%>

#####################################################################

 

#####################################################################

38. 로긴 및 서블릿 관련 소스(한글처리)

#####################################################################

<BODY onContextmenu="return false">

<form name="login" action="/ServletJsp/servlet/loginServlet" method="post">

        <table border=1 cellspacing="0" cellpadding="0">

               <tr>

                       <td>User ID  </td>

                       <td><input type="text" name="id" ></td>

               </tr>

               <tr>

                       <td>Password  </td>

                       <td><input type="password" name="passwd"></td>

               </tr>

               <tr>

                       <td colspan=2 align=center>

                       <input type="submit" value="CONFIRM">

                       <input type="reset" value="CANCEL">

                       </td>

               </tr>

        </table>

</form>

</BODY>

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

import util.HangulConversion;

public class loginServlet extends HttpServlet

{

        public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException

        {             

               //res.setContentType("text/html;charset=euc-kr");// 필히 설정함

               //PrintWriter out = res.getWriter();

               res.setContentType("text/html");        

               PrintWriter out = new PrintWriter( new OutputStreamWriter(res.getOutputStream(), "KSC5601"), true );

               String userid = HangulConversion.toKor(req.getParameter("id")); //util 팩키지에서 메소드 이용

               String passwd = req.getParameter("passwd");

               out.println("<html><body>");          

               if ( userid.equals("") && passwd.equals(""))

               {

                       out.println("NOWHERE");

               }else{         

                       out.println("INPUT ID IS :"+ userid +"<br>");

                       out.println("INPUT PASSWORD IS :"+passwd);

               }

               out.println("<p><font size=2><a href=javascript:history.back()>BACK TO THE FUTURE</a></font>");

               out.println("<body></html>");

               out.close();

        }

}

package util;

import java.io.*;

public class HangulConversion

{

        public static String toEng(String ko){

               if (ko ==null)

               {

                       return null;

               }

               try

               {

                       return new String(ko.getBytes("KSC5601"), "8859_1");

               }

               catch (Exception e)

               {

                       return ko;

               }

        }

        public static String toKor(String en){

               if (en == null)

               {

                       return null;

               }

               try

               {

                       return new String(en.getBytes("8859_1"), "KSC5601");

               }

               catch (Exception e)

               {

                       return en;

               }

        }

}

#####################################################################

37. 세션관련 정리 소스

#####################################################################

<form action="sessionCreate.jsp" method="post">

<table border="1" cellspacing=0 cellpadding=0 >

        <tr>

               <td> IDENTIFICATION </td>

               <td><input type=textfield name=id></td>

        </tr>

        <tr align=center>

               <td colspan=2><input type="submit" value="Confirm"><input type="reset" value="Cancel"></td>

        </tr>

<table>

</form>

<%@ page contentType="text/html;charset=euc-kr" session="false"%>

<%@ page import="util.HangulConversion"%>

<html>

<body>

Session Creation<br>

<%

        String id = HangulConversion.toKor(request.getParameter("id"));

        if (id.equals("")){              

               out.println("<hr>No Data<br>");

               out.println("<a href=javascript:history.back()>Back To The Future</a>");

               //response.sendRedirect("sessionLogin.html");

                return;

        }

        HttpSession session = request.getSession(true);

        if(session.isNew()){

               session.setAttribute("id", id); //세션을 설정한다

               out.println("<hr>New session is created :"+ id+"<br>");

               out.println("Session ID :"+session.getId()+"<br>");

               out.println("<a href=sessionRead.jsp>[Get Session]</a><br>");

        }else{

               out.println("<hr>Already exist session<br>");

               out.println("Input Id :"+id +"<br>");

               out.println("Session ID :"+session.getId()+"<br>"); //기존에 만든 세선 Id를 가져온다

               out.println("<a href=sessionRead.jsp>[Get Session]</a>");

        }

%>

</body>

</html>

<%@ page contentType="text/html;charset=euc-kr" session="false"%>

<html>

<body>

<%

        HttpSession session = request.getSession(false);

        String s = (String)session.getAttribute("id");

        if (s == null){

               out.println("Not Session");     

        }else{

               out.println("Attribute id is :"+s+"<br>");

        }

%>

<hr>

isNew() :<%= session.isNew()%><br>

Session ID :<%= session.getId()%><br>

Session Create Time :<%= new java.util.Date(session.getCreationTime()).toString()%><br>

Session Last Time&nbsp;&nbsp;:<%= new java.util.Date(session.getLastAccessedTime()).toString()%><br>

Session Active Time :<%= session.getMaxInactiveInterval()%> sec<br>

<a href="sessionDelete.jsp">[Session Delete]</a> <a href="sessionLogin.html">[Login Page]</a>

</body>

</html>

<%@ page contentType="text/html;charset=euc-kr" session="false" %>

<%

        HttpSession session = request.getSession(false);

        String s = (String)session.getAttribute("id");

        out.println("Id :"+s+"<br><hr>");

        if (session != null){

               session.invalidate();

        }

%>

Delete Session<br>

<a href="sessionLogin.html">Login Page</a>

 

#####################################################################

36. 메일을 발송하는 프로그램 소스

#####################################################################

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.util.Hashtable;

import java.util.Properties;

import javax.mail.Message;

import javax.mail.Session;

import javax.mail.Transport;

import javax.mail.internet.InternetAddress;

import javax.mail.internet.MimeMessage;

public class SendMail {

        /**

         * @param pMAIL

         * @param conn

         */

        public Properties sendCronMail(Properties pARGS, Connection conn) {

               Properties pRETURN = new Properties();

               pRETURN.setProperty("RESULT", "true");

               String sMAIL_SMTP_HOST = pARGS.getProperty("MAIL_SMTP_HOST", "203.254.221.26");

               String sEMAIL_ADDRESS_FROM = pARGS.getProperty("EMAIL_ADDRESS_FROM", "swbupload@samsung.com"); // 보내는 사람 주소

               String sEMAIL_ADDRESS_TO = pARGS.getProperty("EMAIL_ADDRESS_TO", "swbupload@samsung.com"); // 받는 사람 주소

               String sSUBJECT = pARGS.getProperty("SUBJECT", "CronMail Error..."); // 타이틀

               String sTEXT = pARGS.getProperty("TEXT", "CronMail Error!!!"); // 내용

               try {

                       Properties pMAIL = System.getProperties();

                       pMAIL.put("mail.smtp.host", sMAIL_SMTP_HOST);

                       Session sMAIL_SESSION = Session.getDefaultInstance(pMAIL, null);

                       if (sMAIL_SESSION == null) {

                              pRETURN.setProperty("RESULT", "false");

                              pRETURN.setProperty("MSG", "Mail Session can't be created...");

                              return pRETURN;

                       }

                       MimeMessage reply = new MimeMessage(sMAIL_SESSION);

                       reply.setFrom(new InternetAddress(sEMAIL_ADDRESS_FROM));

                       reply.setSubject(sSUBJECT);

                       reply.setText(sTEXT);

                       reply.addRecipient(Message.RecipientType.TO, new InternetAddress(sEMAIL_ADDRESS_TO));

                       Transport.send(reply);

                       StringBuffer sbSQL = new StringBuffer();

                       sbSQL.append(" UPDATE SENDMAIL SET SENDDATE = TO_CHAR(SYSDATE, 'YYYYMMDDHH24MISS') WHERE MAIL_ID = ?");

                       conn.setAutoCommit(false);

                       PreparedStatement pstmt = conn.prepareStatement(sbSQL.toString());

                       pstmt.setString(1, pARGS.getProperty("MAIL_ID", "1"));

                       pstmt.executeUpdate();

                       conn.commit();

               } catch (Exception e) {

                       pRETURN.setProperty("RESULT", "false");

                       pRETURN.setProperty("MSG", "sendCronMail(Properties pARGS) Error : " + e.toString());

               }

               return pRETURN;

        }

        public static void main(String[] args) {

               String sDB_URL = "jdbc:oracle:thin:@165.213.251.202:1521:itts";

               String sDB_USER = "itts";

               String sDB_PASSWORD = "skan00";

               Connection conn = null;

               PreparedStatement pstmt = null;

               ResultSet rs = null;

               try {

                       Class.forName("oracle.jdbc.driver.OracleDriver");

                       conn = DriverManager.getConnection(sDB_URL, sDB_USER, sDB_PASSWORD);

                       if (conn != null) {

                              StringBuffer sbSQL = new StringBuffer();

                              sbSQL.append(" SELECT MAIL_ID, MAIL_FROM, MAIL_TO, MAIL_SUBJECT, MAIL_BODY FROM SENDMAIL WHERE SENDDATE = '99991231235959'");

                              pstmt = conn.prepareStatement(sbSQL.toString());

                              rs = pstmt.executeQuery();

                              Hashtable htSENDMAIL = new Hashtable();

                              for (int i = 0; rs.next(); i++) {

                                      Properties pSendCronMail_ARGS = new Properties();

                                      pSendCronMail_ARGS.setProperty("MAIL_ID", rs.getString("MAIL_ID"));

                                      pSendCronMail_ARGS.setProperty("EMAIL_ADDRESS_FROM", rs.getString("MAIL_FROM"));

                                      pSendCronMail_ARGS.setProperty("EMAIL_ADDRESS_TO", rs.getString("MAIL_TO"));

                                      pSendCronMail_ARGS.setProperty("SUBJECT", rs.getString("MAIL_SUBJECT"));

                                      pSendCronMail_ARGS.setProperty("TEXT", rs.getString("MAIL_BODY"));

                                      htSENDMAIL.put(new Integer(i), pSendCronMail_ARGS);

                              }

                              rs.close();

                              pstmt.close();

                              SendMail cm = new SendMail();

                              for (int i = 0; i < htSENDMAIL.size(); i++) {

                                      cm.sendCronMail((Properties) htSENDMAIL.get(new Integer(i)), conn);

                              }

                       }

               } catch (ClassNotFoundException e) {

                       System.err.println(e.toString());

               } catch (SQLException e) {

                       System.err.println(e.toString());

               } finally {

                       try {

                              conn.close();

                       } catch (SQLException e1) {

                              System.err.println(e1.toString());

                       }

               }

        }

}

#####################################################################

35. 원도우 배치 프로그램 실행하기

#####################################################################

xcopy /s /e /y C:\Tomcat4\webapps\itts\paperless\fileupload e:\paperless\fileupload

 

move /Y C:\Tomcat4\webapps\itts\paperless\swbTempDir\*.* D:\PT-LOG\swbTempDir\

move /Y C:\Tomcat4\webapps\itts\paperless\mProSystem\log\*.* D:\PT-LOG\mProSystem\

move /Y C:\Tomcat4\webapps\itts\paperless\logs\*.* D:\PT-LOG\logs\

 

#####################################################################

34. 특정 폴더에 쌓이는 파일을 없애는 소스

#####################################################################

 

배치 프로그램을 돌리면서 로그파일을 남김.

java paperless.cron.TempPdfDelete e:\\pdf_temp 1 >> PtPDF_TEMP_DIR_DEL.log

 

import java.io.File;

import java.text.SimpleDateFormat;

import java.util.Date;

import java.util.Properties;

public class TempPdfDelete {

        public static void main(String[] args) {

               TempPdfDelete td = new TempPdfDelete();             

               String sTRASH_LOCATION = "e:\\pdf_temp";

               String sTRASH_DELETE_DAY = "1";           

               if( args.length == 2 ) {

                       sTRASH_LOCATION = args[0];

                       sTRASH_DELETE_DAY = args[1];

               }

               Properties pARGS = new Properties();

               pARGS.setProperty("TRASH_LOCATION", sTRASH_LOCATION);

               pARGS.setProperty("TRASH_DELETE_DAY", sTRASH_DELETE_DAY);

               Properties pRETURN = td.trashDelete(pARGS);

               SimpleDateFormat sdfTODAY = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

               Date dTODAY = new Date();           

               System.out.println("[" + sdfTODAY.format(dTODAY) + "] '"+sTRASH_LOCATION+"' Directory Deletion Started...");

               for(int i=0; i<Integer.parseInt(pRETURN.getProperty("DELETED_TRASH_FILE_COUNT")); i++) {

                       dTODAY = new Date();

                       System.out.println("[" + sdfTODAY.format(dTODAY) + "] " + pRETURN.getProperty("#" + i, "Deleted File Name not found") + " was deleted");

               }

               dTODAY = new Date();

               System.out.println("[" + sdfTODAY.format(dTODAY) + "] '"+sTRASH_LOCATION+"' Directory Deletion Ended...");

        }

        /**

         * @param pARGS

         * @return

         */

        private Properties trashDelete(Properties pARGS) {

               Properties pRETURN = new Properties();

               pRETURN.setProperty("RESULT", "true");

               String sTRASH_LOCATION = pARGS.getProperty("TRASH_LOCATION", "e:\\pdf_temp");

               if (sTRASH_LOCATION.trim().equals("")) {

                       pRETURN.setProperty("RESULT", "true");

                       pRETURN.setProperty("MSG", "TRASH_LOCATION is null...");

                       return pRETURN;

               }

               long lTRASH_DELETE_DAY = Long.parseLong(pARGS.getProperty("TRASH_DELETE_DAY", "0")) * 24 * 60 * 60 * 1000;

               File fTRASH_LOCATION = new File(sTRASH_LOCATION);

               int iDELETED_TRASH_FILE_COUNT = 0;

               if (fTRASH_LOCATION.isDirectory()) {

                       File[] fofTRASH_LOCATION_FILES = fTRASH_LOCATION.listFiles();

                       Date dTODAY = new Date();

                       for (int i = 0; i < fofTRASH_LOCATION_FILES.length; i++) {

                              long lTRASH_FILE_AGE = dTODAY.getTime() - fofTRASH_LOCATION_FILES[i].lastModified();

                              if (fofTRASH_LOCATION_FILES[i].isFile() && lTRASH_FILE_AGE >= lTRASH_DELETE_DAY) {

                                      if (fofTRASH_LOCATION_FILES[i].delete()) {

                                             pRETURN.setProperty("#" + String.valueOf(iDELETED_TRASH_FILE_COUNT), fofTRASH_LOCATION_FILES[i].getName());

                                             iDELETED_TRASH_FILE_COUNT++;

                                      }

                              }

                       }

               }

               pRETURN.setProperty("DELETED_TRASH_FILE_COUNT", String.valueOf(iDELETED_TRASH_FILE_COUNT));

               return pRETURN;

        }

}

#####################################################################

33. 암호와 알고리즘을 사용후 복호화 하는 소스와 적용예

#####################################################################

import javax.crypto.*;

import javax.crypto.spec.SecretKeySpec;

import javax.crypto.spec.DESKeySpec;

import javax.crypto.spec.IvParameterSpec;

import java.security.*;

import sun.misc.BASE64Decoder;

import sun.misc.BASE64Encoder;

public class AlgoDES {

    static byte[] seedKeyData = new byte[24];

    public AlgoDES() {

        seedKeyData[0] = 0x01;

        seedKeyData[1] = 0x02;

        seedKeyData[2] = 0x03;

        seedKeyData[3] = 0x04;

        seedKeyData[4] = 0x05;

        seedKeyData[5] = 0x06;

        seedKeyData[6] = 0x07;

        seedKeyData[7] = 0x08;

        seedKeyData[8] = 0x09;

        seedKeyData[9] = 0x10;

        seedKeyData[10] = 0x11;

        seedKeyData[11] = 0x12;

        seedKeyData[12] = 0x13;

        seedKeyData[13] = 0x14;

        seedKeyData[14] = 0x15;

        seedKeyData[15] = 0x16;

        seedKeyData[16] = 0x01;

        seedKeyData[17] = 0x02;

        seedKeyData[18] = 0x03;

        seedKeyData[19] = 0x04;

        seedKeyData[20] = 0x05;

        seedKeyData[21] = 0x06;

        seedKeyData[22] = 0x07;

        seedKeyData[23] = 0x08;

    }

    public static String encTripleDES(String beforeStr) {

        String afterStr = "";

        try {

            SecretKeySpec desKey = new SecretKeySpec(seedKeyData, "DESede"); //seedKeyData로 암호화

            Cipher desCipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");

            byte[] cleartext = beforeStr.getBytes();

            desCipher.init(Cipher.ENCRYPT_MODE, desKey);

            byte[] ciphertext = desCipher.doFinal(cleartext);

            afterStr = (new BASE64Encoder()).encode(ciphertext);

        } catch (Exception e) {

            e.printStackTrace();

        }

        return afterStr;

    }

    public static String decTripleDES(String beforeStr) {        

        String afterStr = "";

        try {

            SecretKeySpec desKeyD = new SecretKeySpec(seedKeyData, "DESede");

            Cipher desCipherD = Cipher.getInstance("DESede/ECB/PKCS5Padding");

            desCipherD.init(Cipher.DECRYPT_MODE, desKeyD);

            byte[] decodedBytes = (new BASE64Decoder()).decodeBuffer(beforeStr);

            byte[] cleartext1 = desCipherD.doFinal(decodedBytes);

            afterStr = new String(cleartext1);

        } catch (Exception e) {

            e.printStackTrace();

        }

        return afterStr;

    }

        public static void main(String args[]) {         

               try{

                       if (args.length > 0) {

                              for (int i = 0; i < args.length; i++) {

                                      String s = AlgoDES.encTripleDES(args[i]);

                                      String s1 = AlgoDES.decTripleDES(s);

                                      System.out.println("Original ["+args[i]+"]");

                                      System.out.println("encTripleDES ["+s+"]");

                                      System.out.println("decTripleDES ["+s1+"]");

                              }

       

                       }      

               } catch (Exception e) {

                       e.printStackTrace();

               }

        }

}

/** 적용예제

        if(secu) {

               _sdbServer = AlgoDES.decTripleDES(ReadConfig.get ("DATABASE", "dbServer")) ;

        }else{

               _sdbServer = ReadConfig.get ("DATABASE", "dbServer") ;

        }

    if(secu){

               _sdbPassword = AlgoDES.decTripleDES(ReadConfig.get ("DATABASE", "dbPassword")) ;

        }else{

               _sdbPassword = ReadConfig.get ("DATABASE", "dbPassword") ;

        }

*/

#####################################################################

32. 특수문자 제거 메소드

#####################################################################

public static String removeSpecialChar(String str) {

               if (str == null || str.trim().length() == 0)

                       return "";

               StringBuffer data = new StringBuffer(str);

               StringBuffer buf = new StringBuffer();

               for (int i = 0; i < data.length(); i++) {

                       char c = data.charAt(i);

                       if (((int) c > 47 && (int) c < 58) || ((int) c > 64 && (int) c < 91) || ((int) c > 96 && (int) c < 123))

                              buf.append(c);

               }

 

               return buf.toString();

}

 

#####################################################################

31. 날짜 관련 함수 이용

#####################################################################

import java.util.*;

import java.io.*;

import java.text.*;

public class DateCheck

{

        public static void main(String[] args)

        {

               SimpleDateFormat date = new SimpleDateFormat();

               date = (SimpleDateFormat)DateFormat.getDateTimeInstance();

               long now = System.currentTimeMillis();

               System.out.println("Now  ->/"+now+"/");

               Date dd = new Date();         

               System.out.println("Date ->/"+dd+"/");

               String str = date.format(new Date(now));

               System.out.println("Time ->/"+str+"/");         

        }

}

 

 

#####################################################################

30. Random 함수로 받은 값을 중복 체크하는 소소

#####################################################################

import java.util.*;

public class RandomTest

{

        public static void main(String[] args)

        {

               Random random = new Random();

               boolean[] total = new boolean[45];

               int[] choose = new int[6];             

               for (int i=0; i<total.length ; i++ )

               {

                       total[i] = true;

               }             

               for (int i=0; i<choose.length ; i++)

               {

                       int num = random.nextInt(45);                 

                       if (total[num])

                       {

                              total[num] = false;

                              choose[i] = num+1;                                  

                       }             

                       System.out.print( choose[i] + " \n");                 

               }

        }

}

 

#####################################################################

29. 버블 소트로 데이타 정렬

#####################################################################

public class SortTest

{

        public static void main(String[] args)

        {

               String[] str = {"Orange","Apple","Grape","Peach","Lemon"};

               System.out.println("@@@@@ 정렬 전 @@@@@");

               for (int i=0; i<str.length; i++)

               {

                       System.out.println(str[i]);

               }

               System.out.println("@@@@@ 정렬 후 @@@@@");

               for (int j=0; j<str.length ; j++ )

               {

                       for (int i= j+1 ; i<str.length ; i++)

                       {

                              if ( str[i].compareTo(str[j]) < 0 ) //음수이면 들어감

                              {

                                      String temp = str[j];

                                      str[j] = str[i];

                                      str[i] = temp;  

                              }

                       }

                       System.out.println(str[j]);                                     

               }

        }

}

#####################################################################

28. MD5로 암호화 하는 알고리즘 (Base64 필요)

#####################################################################

import sun.misc.*;

import java.io.*;

public class Base64Util {      

    public Base64Util() {}

    /**

     *   Base64Encoding을 수행한다. binany in ascii out

     *

     *   @param encodeBytes encoding byte array

     *   @return encoding String

     */

    public static String encode(byte[] encodeBytes) {

        BASE64Encoder base64Encoder = new BASE64Encoder();

        ByteArrayInputStream bin = new ByteArrayInputStream(encodeBytes);

        ByteArrayOutputStream bout = new ByteArrayOutputStream();

        byte[] buf = null;

        try{

            base64Encoder.encodeBuffer(bin, bout);

        } catch(Exception e) {

            System.out.println("Exception");

            e.printStackTrace();

        }

        buf = bout.toByteArray();

        return new String(buf).trim();

    }

    /**

     *   Base64Decoding 수행한다. binany out ascii in

     *

     *   @param strDecode decoding String

     *   @return decoding byte array

     */

    public static byte[] decode(String strDecode) {       

        BASE64Decoder base64Decoder = new BASE64Decoder();

        ByteArrayInputStream bin = new ByteArrayInputStream(strDecode.getBytes());

        ByteArrayOutputStream bout = new ByteArrayOutputStream();

        byte[] buf = null;

        try {           

            base64Decoder.decodeBuffer(bin, bout);

        } catch(Exception e) {

            System.out.println("Exception");

            e.printStackTrace();

        }

        buf = bout.toByteArray();

        return buf;

    }

}

import java.security.*;

public class  SecurityUtil {

    /**

     *   byte[] ret = HashUtil.digest("MD5", "abcd".getBytes());

     *  처럼 호출

     */

    public static byte[] digest(String alg, byte[] input) throws NoSuchAlgorithmException {

        MessageDigest md = MessageDigest.getInstance(alg);

        return md.digest(input);

    }

    public static String getCryptoMD5String(String inputValue) throws Exception {

        if( inputValue == null ) throw new Exception("Can't conver to Message Digest 5 String value!!");

        byte[] ret = digest("MD5", inputValue.getBytes());

        String result = Base64Util.encode(ret);   

        return result;

    }

        public static void main(String[] args) throws Exception

        {

               String passwd = SecurityUtil.getCryptoMD5String("gkskfh2005");

               System.out.println("passwd :"+passwd);

        }

}

#####################################################################

 

#####################################################################

27. TripleDES 을 이용한 암호화 알고리즘

#####################################################################

import javax.crypto.*;

import javax.crypto.spec.SecretKeySpec;

import javax.crypto.spec.DESKeySpec;

import javax.crypto.spec.IvParameterSpec;

import java.security.*;

import sun.misc.BASE64Decoder;

import sun.misc.BASE64Encoder;

public class AlgoDES {

    static byte[] seedKeyData = new byte[24];

    public AlgoDES() {

        seedKeyData[0] = 0x01;

        seedKeyData[1] = 0x02;

        seedKeyData[2] = 0x03;

        seedKeyData[3] = 0x04;

        seedKeyData[4] = 0x05;

        seedKeyData[5] = 0x06;

        seedKeyData[6] = 0x07;

        seedKeyData[7] = 0x08;

        seedKeyData[8] = 0x09;

        seedKeyData[9] = 0x10;

        seedKeyData[10] = 0x11;

        seedKeyData[11] = 0x12;

        seedKeyData[12] = 0x13;

        seedKeyData[13] = 0x14;

        seedKeyData[14] = 0x15;

        seedKeyData[15] = 0x16;

        seedKeyData[16] = 0x01;

        seedKeyData[17] = 0x02;

        seedKeyData[18] = 0x03;

        seedKeyData[19] = 0x04;

        seedKeyData[20] = 0x05;

        seedKeyData[21] = 0x06;

        seedKeyData[22] = 0x07;

        seedKeyData[23] = 0x08;

    }

    public static String encTripleDES(String beforeStr) {

        String afterStr = "";

        try {

            SecretKeySpec desKey = new SecretKeySpec(seedKeyData, "DESede"); //seedKeyData로 암호화

            Cipher desCipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");

            byte[] cleartext = beforeStr.getBytes();

            desCipher.init(Cipher.ENCRYPT_MODE, desKey);

            byte[] ciphertext = desCipher.doFinal(cleartext);

            afterStr = (new BASE64Encoder()).encode(ciphertext);

        } catch (Exception e) {

            e.printStackTrace();

        }

        return afterStr;

    }

    public static String decTripleDES(String beforeStr) {        

        String afterStr = "";

        try {

            SecretKeySpec desKeyD = new SecretKeySpec(seedKeyData, "DESede");

            Cipher desCipherD = Cipher.getInstance("DESede/ECB/PKCS5Padding");

            desCipherD.init(Cipher.DECRYPT_MODE, desKeyD);

            byte[] decodedBytes = (new BASE64Decoder()).decodeBuffer(beforeStr);

            byte[] cleartext1 = desCipherD.doFinal(decodedBytes);

            afterStr = new String(cleartext1);

        } catch (Exception e) {

            e.printStackTrace();

        }

        return afterStr;

    }

        public static void main(String args[]) {         

               try{

                       if (args.length > 0) {

                              for (int i = 0; i < args.length; i++) {

                                      String s = AlgoDES.encTripleDES(args[i]);

                                      String s1 = AlgoDES.decTripleDES(s);

                                      System.out.println("Original ["+args[i]+"]");

                                      System.out.println("encTripleDES ["+s+"]");

                                      System.out.println("decTripleDES ["+s1+"]");

                              }      

                       }      

               } catch (Exception e) {

                       e.printStackTrace();

               }

        }

}

 

import java.security.*;

import javax.crypto.*;

public class TripleDes {

    public static void main(String [] args) throws Exception {

        if( args.length != 1) {

            System.out.println("Usage : java SimpleExample text ");

            System.exit(1);

        }

        String text = args[0];

        System.out.println("Generating a DESded (TripleDES) key...");

        // Triple DES 생성

        KeyGenerator keyGenerator = KeyGenerator.getInstance("DESede");

        keyGenerator.init(168);   // 키의 크기를 168비트로 초기화

        Key key = keyGenerator.generateKey();

        System.out.println("키생성이 완료되었음");

        // Cipher를 생성, 사용할 키로 초기화

        Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");

        cipher.init(Cipher.ENCRYPT_MODE, key);

        byte [] plainText = text.getBytes("UTF8");

        System.out.println("Plain Text : ");

        for (int i = 0; i < plainText.length ; i++) {

            System.out.print(plainText[i] + " ");

        }

        // 암호화 시작

        byte [] cipherText = cipher.doFinal(plainText);

        // 암호문서 출력

        System.out.println("\nCipher Text : ");

        for (int i = 0; i < cipherText.length ; i++)       {

            System.out.print(cipherText[i] + " ");

        }

        //복호화 모드로서 다시 초기화

        cipher.init(Cipher.DECRYPT_MODE, key);

        //복호화 수행

        byte [] decryptedText = cipher.doFinal(cipherText);

        String output =  new String(decryptedText, "UTF8");

        System.out.println("\nDecrypted Text : " + output);

    }

};

#####################################################################

 

#####################################################################

26. Random 클래스로 가져온 값을 중복체크하기

#####################################################################

import java.util.*;

public class RandomTest

{

        public static void main(String[] args)

        {

               Random random = new Random();

               boolean[] boo = new boolean[45];

                int[] choo = new int[6];

               for (int i=0; i<boo.length ;  )

               {

                       boo[i] = true;

               }

               for (int i=0; i<choo.length ; i++)

               {

                       int num = random.nextInt(45);

                       if (boo[num])

                       {

                              boo[num] = false;

                              choo[i] = num+1;      

                              System.out.println(choo[i]);

                       }                     

               }

        }

}

#####################################################################

 

#####################################################################

26. MS-SQL JDBC 드라이버 연결하는 방법

#####################################################################

 

다음의 사이트를 방문하여 MS-SQL2000 JDBC 드라이버를 다운로드

http://www.microsoft.com/sql/downloads/2000/jdbc.asp

적절한 위치에 설치하고 다음의 세 파일을 클래스패스에 추가 (%JAVA_HOME%\lib\ext\classes12.zip;)

설치 디렉터리/lib/msbase.jar 

설치 디렉터리/lib/msutil.jar 

설치 디렉터리/lib/mssqlserver.jar

 

MS-SQL2000, Oracle 그리고 MySQL 데이터베이스의 드라이버를 로딩하는 것을 각각 보여주고 있습니다.

Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");

Class.forName("oracle.jdbc.driver.OracleDriver");

Class.forName("org.gjt.mm.mysql.Driver");

 

 

#####################################################################

 

#####################################################################

25. 날짜 포맷 바꾸는 방법

#####################################################################

 

String ETA_END_DATE = null;

String ETA_START_DATE = null;

String date_format = "yyyy-MM-dd";

SimpleDateFormat simpledateformat = new SimpleDateFormat(date_format);             

ETA_END_DATE = simpledateformat.format(Format.getSwbEndDate());

ETA_START_DATE = simpledateformat.format(Format.getSwbStartDate());

 

#####################################################################

24. 엔터키를 두르면 검색하는 소스

#####################################################################

 

<script language="JavaScript">

function goUrl(command, _url) {

        theForm = document.searchForm;      

        if (command == 'search'  && theForm.BLNO.value != null)

               theForm.BLNO.value = theForm.BLNO.value.toUpperCase();             

        theForm.command.value=command;

        theForm.PAGE.value="1";

        theForm.action = _url;

        theForm.submit();

}

function EnterCheck()

{      

        if(event.keyCode == 13)

               goUrl('search', '/servlet/paperless.SwbListServlet');

}

</script>

<form name="searchForm" method="post" action="">

<table width="98%" border="0" cellspacing="1" cellpadding="3">

    <input type="text" name="BLNO" class="main_input" value = "<%=blno%>"size="20" __onBlur="checkBLNo(this)" onKeyDown="EnterCheck()">

        <img src="../img/btn_multifile_upload.gif" width="92" height="18" border="0"

         onmouseover="this.style.cursor='hand'"

          onClick="goUrl('','/servlet/paperless.SwbUploadServlet')"/>

        <input type="hidden" name="PROCESS_TYPE" value="CARRIER"/>

</table>

</form>

 

#####################################################################

23. 데이터베이스 커넷션하고 로그파일을 만듬

#####################################################################

package common;

import BrokerBean;

import javax.servlet.jsp.PageContext;

import java.sql.SQLException;

import java.sql.Connection;

import java.sql.PreparedStatement;

public class SystemUsageHandler {

            synchronized public static void insertLog(PageContext jspContext, String id, String menu, String func, String comment) throws SQLException, Exception

            {

                       BrokerBean brokerBean = null;

                       Connection conn = null;

                       PreparedStatement pstmt = null;

                       try {

                              brokerBean = (BrokerBean) jspContext.getServletContext().getAttribute("DBPOOL");

                              conn = brokerBean.getDbConnection();

                              conn.setAutoCommit(false);

                              pstmt = conn.prepareStatement("insert into SYSTEM_USAGE_DETAIL (USER_ID, MENU, FUNC, COMMON ) "

                                             + " values (?,?,?,?)");

                              pstmt.setString(1, id);

                              pstmt.setString(2, menu);

                              pstmt.setString(3, func);

                              pstmt.setString(4, comment);

                              pstmt.executeUpdate();

                              conn.commit();

                       } catch (SQLException e) {

                              e.printStackTrace();

                              conn.rollback();

                       } catch (Exception e) {

                              e.printStackTrace();

                              conn.rollback();

                       } finally {

                              try {

                                      if (pstmt != null) pstmt.close();

                                      if (conn != null) brokerBean.freeConnection(conn);

                              } catch (Exception ae) {

                                      ae.printStackTrace();

                              }

                       }

               }

}

#####################################################################

 

 

#####################################################################

01. ServerSocket Socket 간의 채팅 소스

#####################################################################

import java.io.*;

import java.net.*;

import java.util.*;

public class Server_15

{

        public static void main(String[] args)

        {

               try

               {

                       ServerSocket server = new ServerSocket(9999);

                       while (true)

                       {

                              System.out.println("Server Ready");

                              Socket socket = server.accept();

                              ServerHandle_15 sh = new ServerHandle_15(socket);

                              Thread th = new Thread(sh);

                              th.start();

                       }

               }catch (IOException e){}       

        }

}

class ServerHandle_15 implements Runnable

{

        private DataInputStream dis = null;

        private DataOutputStream dos = null;

        private Socket socket = null;

        public static Vector v = new Vector();

        public ServerHandle_15(Socket socket){

               try

               {

                       dis = new DataInputStream(socket.getInputStream());

                       dos = new DataOutputStream(socket.getOutputStream());

                       v.addElement(this);

               }catch (IOException e){}       

        }

        public void run(){

               try

               {

                       while (true)

                       {

                              String str = dis.readUTF();

                              broad(str);

                       }                             

               }catch (IOException e){}

        }

        public void broad(String str){

               for (int i=0; i<v.size() ; i++)

               {

                       try

                       {

                              ServerHandle_15 sh = (ServerHandle_15)v.elementAt(i);

                              sh.dos.writeUTF(str);

                       }catch (IOException e){ }                     

               }                             

        }

};

 

import java.io.*;

import java.net.*;

public class Client_15 implements Runnable

{

        private DataInputStream dis = null;

        private DataOutputStream dos = null;

        private Socket socket = null;

        public Client_15()

        {

               try

               {

                       socket = new Socket("localhost", 9999);

                       dis = new DataInputStream(socket.getInputStream());

                       dos = new DataOutputStream(socket.getOutputStream());

                       Thread th = new Thread(this);

                       th.start();

                       display();

               }catch (IOException e){}

        }

        public void run(){

               try

               {

                       while (true)

                       {

                              String str = dis.readUTF();

                              System.out.println(str);

                       }                                                                  

               }catch (IOException e){}

        }

        public void display(){

               try

               {

                       BufferedReader br = new BufferedReader(new InputStreamReader(System.in));                          

                       while (true)

                       {

                              String str = br.readLine();     

                              dos.writeUTF(str);

                       }                     

               }catch (IOException e){}

        }

        public static void main(String[] args){

               Client_15 sc = new Client_15();

        }

}

#####################################################################

 

 

#####################################################################

02. Swing에서 이미지 아이콘 삽입 및 종료

#####################################################################

import java.awt.*;

import javax.swing.*;

JFrame: Construct

private Container con;

con = this.getContentPane();

con.add(jbutton);

this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //플레임 종료

ImageIcon:

ImageIcon im = new ImageIcon("aa.gif");

this.setIconImage(im.getImage());

#####################################################################

 

 

#####################################################################

03. RMI 정상적인 예제

#####################################################################

package ksh.first;

import java.rmi.*;

public interface FirstRMI extends Remote{

        String getString() throws RemoteException;

        //void setString(String str) throws RemoteException;

}

#####################################################################

package ksh.first;

import java.rmi.*;

import java.rmi.server.*;

public class SecondRMI extends UnicastRemoteObject implements FirstRMI{

        public SecondRMI() throws RemoteException{

               super();

        }

        public String getString() throws RemoteException{

               return "Hello RMI!!!";

        }

}

#####################################################################

import ksh.first.*;

import java.rmi.*;

import java.net.*;

public class ThirdRMI{

        public static void main(String[] ar){

               SecondRMI sr = null;

               try{

                       sr = new SecondRMI();

                       Naming.rebind("first", sr);

                       System.out.println("Server Ready...");

               }catch(RemoteException ee){

               }catch(MalformedURLException ee){}

        }

}

#####################################################################

import ksh.first.*;

import java.rmi.*;

import java.net.*;

public class FourthRMI{

        public static void main(String[] ar){

               FirstRMI fr = null;

               try{

                       fr = (FirstRMI)Naming.lookup("rmi://192.168.0.155/first");

                       String str = fr.getString();

                       System.out.println("실행된 메시지 = " + str);

               }catch(NotBoundException ee){

               }catch(MalformedURLException ee){

               }catch(RemoteException ee){}

        }

}

#####################################################################

 

 

#####################################################################

04. RMI registry 등록하지 않고 사용

#####################################################################

package ksh.second;

import java.rmi.*;

public interface FirstRMI extends Remote{

        String getString() throws RemoteException;

}

#####################################################################

package ksh.second;

import java.rmi.*;

import java.rmi.server.*;

public class SecondRMI extends UnicastRemoteObject   implements FirstRMI{

        public SecondRMI() throws RemoteException{

               super();

        }

        public String getString() throws RemoteException{

               return "Hello RMI2!!";

        }

}

#####################################################################

import ksh.second.*;

import java.rmi.*;

import java.rmi.registry.*;

import java.net.*;

public class ThirdRMI{

        public static void main(String[] ar){

               Registry rg = null;

               SecondRMI sr = null;

               try{

                       rg = LocateRegistry.createRegistry(2000);

                       sr = new SecondRMI();

                       Naming.rebind("rmi://192.168.0.155:2000/second", sr);

                       System.out.println("Server Ready...");

               }catch(RemoteException ee){

               }catch(MalformedURLException ee){}

        }

}

#####################################################################

import ksh.second.*;

import java.rmi.*;

import java.net.*;

public class FourthRMI{

        public static void main(String[] ar){

               FirstRMI fr = null;

               try{

                       fr = (FirstRMI)Naming.lookup(

                                                                    "rmi://192.168.0.155:2000/second");

                       String str = fr.getString();

                       System.out.println("메시지 = " + str);

               }catch(NotBoundException ee){

               }catch(MalformedURLException ee){

               }catch(RemoteException ee){}

        }

}

#####################################################################

 

 

#####################################################################

05. RMI 통신법

#####################################################################

기본 Port 1099

Remote Method Invocation

rmi package & 중요 클래스

---------------------------------------------------------------------

1.서버: 공통 인터페이스, 구현 클래스, 스켈레톤 클래스, 서버실행 클래스

서버기동 bind(String str, Remote obj)

- 공통 인터페이스

        public 인터페이스, Remote 인터페이스를 상속

        abstract Method RemoteException 를 처리

        매개변수들은 객체이거나 직렬화가 가능

- 구현클래스

        public class Second extends UnicastRemoteObject implements FirstRMI 를 상속

- 스텝과 스켈레톤 계증 만들기

        rmic -d . ksh.first.SecondRMI 구현클래스로 생성한다.

- rmiregistry 기동해야 한다. 1099 Port 이용

        대체클래스로 기동할 수도 있다

        start rmiregistry 새창으로 돌려라 (unix에 백앤드 프로그램 생성하는 것과 같다)

- Binding 시키기 (등록시킨다)

        ThirdRMI {

               SecondRMI sr = new SecondRMI();

               sr.rebind("first", sr);

        }

        C\>start java ThirdRMI 로 실행

#####################################################################

2.클라이언트: 공통인터페이스, 스넵 클래스, GUI 클래스

- 서버 파일 가져오기, 스텝 클래스를 가져온다

        공통인터페이스 FirstRMI.class, SecondRMI_Stub.class

- 서버의 기동중인 객체를 얻어오기

        import ksh.first.*;

        import java.rmi.*;

        public class FourthRMI{

               try

               {

                       FirstRMI fr = new First();

                       fr = (FirstRMI)Naming.lookup("rmi://165.213.42.29:1099/first");

               }

               catch (NotBoundException e){}

               catch (MalformedURLException e){}

               catch (RemoteException e){}

        }

- 해당 객체를 통해서 Method 를 사용하기

        String str = fr.getString();

        System.out.println("얻어온 실행된 메시지 "+str);

#####################################################################

3. rmiregistry 대체 클래스

Registry interface (Naming class 와 유사)

LocateRegistry class

 

import ksh.second.*;

import java.rmi.*;

import java.rmi.registry.*;

import java.net.*;

public class ThirdRMI

{

        public static void main(String[] args){

               SecondRMI sc = null;

               Registry rg = null;

               try

               {

                       rg = LocateRegistry.createRegistry(2000);

                       sc = new SecondRMI();

                       Naming.rebind("rmi:192.168.0.155:2000/second", sc);

               }

               catch (RemoteException e){}

               catch (MalformedURLException e){}

        }

};

#####################################################################

 

 

#####################################################################

06. Directory 찾아서 리스트 만들기

#####################################################################

 

import java.io.*;

public class MakeFileList

{

        PrintWriter pw = null;

        public MakeFileList(){

               try

               {

                       FileOutputStream fos = new FileOutputStream(new File("./Text.txt"));

                       OutputStreamWriter osw = new OutputStreamWriter(fos, "EUC-KR");

                       pw = new PrintWriter(osw, true);

               }catch (IOException e){

                       System.out.println("File write error "+e);

               }

               searchDirectory(new File("."));

               pw.flush();

               pw.close();

        }

        public void searchDirectory(File here){

               File[] rootFileList = here.listFiles();

               for (int i=0; i<rootFileList.length ; i++ )

               {

                       if (rootFileList[i].isDirectory())

                       {

                              searchDirectory(rootFileList[i]);

                       }else{

                              try

                              {

                                      String filename = rootFileList[i].getName();

                                      String ext = filename.substring(filename.lastIndexOf("."), filename.length());

                                      if (!ext.equalsIgnoreCase(".gif") && !ext.equalsIgnoreCase(".jpg") )

                                      {

                                             pw.print(rootFileList[i].toURL());

                                             pw.print("\n");

                                             System.out.println(rootFileList[i].toURL());

                                      }else{

                                             System.out.println(ext);

                                      }

                              }catch (Exception e){}

                       }

               }

        }

        public static void main(String[] args){

               MakeFileList mf = new MakeFileList();

        }

};

#####################################################################

 

 

#####################################################################

07. IO 관련 소스

#####################################################################

Abstract OutStream을 이용한 입력하기

 

ch01 - AAA - Exam02_01.java, jar02.jar (jar -cvf jar02.jar *.*)

       BBB - Exam02_Main.java

jar 위치: C:\jdk1.3.1\jre\lib\ext\jar02.jar

 

private PrintStream ps;

public Exam02_03(){

        super();

        ps = System.out;

}

public void write(int i){

        ps.write(i);

        ps.flush();

}

public void close(){

        ps.close();

}

 

Exam02_03 es = new Exam02_03();

es.write(65);

es.write('\r');

es.write('\n');

byte[] bb = {'h','e','l','l','o'};

es.write(bb);

//es.close();

byte[] cc = "HELLO JAVA".getBytes();

es.write('\r');

es.write('\n');

es.write(cc, 0, 5);

es.write("송하연".getBytes("ISO8859_1"));

#####################################################################

private InputStream is;

public Exam02_04(){

        super();

        is  = System.in;

}

public int read() throws IOException{

        int xx = is.read();

        if (xx == '\n')

        {

               return -1;

        }

        return xx;

}

 

/*

byte[] bb = new byte[20];

System.out.print("입력 ");

System.in.read(bb);

int i = System.in.read();

System.out.println("입력된 문자 "+ new String(bb));

*/

Exam02_04 es = new Exam02_04();

byte[] bb = new byte[20];

System.out.print("입력 : ");

es.read(bb);

System.out.println("입력된 문자 : "+ new String(bb));

#####################################################################

 

 

#####################################################################

08. 파일을 읽는 소스

#####################################################################

 

int cnt;

FileReader rf = new FileReader("Test.java");            

cnt = rf.read();

while (cnt != -1)

{

        System.out.print(cnt);

        cnt = rf.read();

}

#####################################################################

 

 

#####################################################################

09. 입력받은 파일을 읽는 소스

#####################################################################

 

int cnt = 0;

System.out.print("Input your filename ");

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

String str = br.readLine();

RandomAccessFile raf = new RandomAccessFile(str, "r");

cnt = raf.read();

while (cnt != -1)

{

        System.out.print((char)cnt);

        cnt = raf.read();

}

#####################################################################

 

 

#####################################################################

10. 스트링을 파일로 저장하는 소스

#####################################################################

 

String str = "어디로 가야 할지";

char[] ch =  new char[str.length()];

str.getChars(0, ch.length, ch, 0);

FileWriter fw = new FileWriter(args[0]);

fw.write(ch);

fw.close();

#####################################################################

 

 

#####################################################################

11. 파일을 저장하는 소스

#####################################################################

 

FileOutputStream fos = new FileOutputStream(args[0]);

for (int i=0; i<500 ; i++ )

{

        fos.write(i);

}

fos.close();

System.out.println("FileOutputStream 했습니다!");

#####################################################################

 

 

#####################################################################

12. 에디터에는 볼 수 없으나 도스에서는 보임

#####################################################################

 

int cnt;

FileInputStream fis = new FileInputStream(args[0]);             

while ( (cnt = fis.read()) != -1)

{                     

        System.out.println(cnt);

}

System.out.println("FileInputStreamDemo를 확인했습니다.");

#####################################################################

 

 

#####################################################################

13. Properties 파일에 관련된 소스

#####################################################################

파일과 관련해서 Properties 저장하는 소스

 

Properties props = new Properties();

props.put("이름","마법사프로퍼티");

props.put("주소","마법의나라");

props.store(new FileOutputStream("properties.dat"),"프로퍼트테스트");

#####################################################################

 

 

#####################################################################

14. 파일과 관련해서 Properties 에서 읽어 오는 소스

#####################################################################

 

Properties props = new Properties();

props.load(new FileInputStream("properties.dat"));

System.out.println("이름: "+props.getProperty("이름"));

System.out.println("주소: "+props.getProperty("주소"));

#####################################################################

 

 

#####################################################################

15. 읽은 파일입력 후 내용확인하는 소스

#####################################################################

 

String fileInput;

int c = 0;;

System.out.print("Input your file name ");

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

fileInput = br.readLine();

RandomAccessFile raf = new RandomAccessFile(fileInput, "r");

c = raf.read();

while ( c != -1 )

{

        System.out.print((char)c);

        c = raf.read();

}

raf.close();

#####################################################################

 

 

#####################################################################

16. 입력파일과 저장할 파일을 쓰는 소스

#####################################################################

 

String fileinput;

String fileoutput;

int c;

System.out.print("Input your filename ");

BufferedReader bf1 = new BufferedReader(new InputStreamReader(System.in));

fileinput = bf1.readLine();

System.out.print("Write save filename ");

BufferedReader bf2 = new BufferedReader(new InputStreamReader(System.in));

fileoutput = bf2.readLine();

RandomAccessFile raf1 = new RandomAccessFile(fileinput, "r");

RandomAccessFile raf2 = new RandomAccessFile(fileoutput, "rw");

c = raf1.read();

while (c!=-1)

{

        raf2.write(c);

        System.out.print((char)c);

        c = raf1.read();

}

raf1.close();

raf2.close();

#####################################################################

 

 

#####################################################################

17. 파일을 읽어서 보여주는 소스

#####################################################################

 

FileInputStream fis = new FileInputStream("Tst.java");

byte[] byteTxt = new byte[fis.available()];

fis.read(byteTxt);

fis.close();

System.out.println(new String(byteTxt));

#####################################################################

 

 

#####################################################################

18. 2초마다 출력하는 쓰레드 소스

#####################################################################

 

public class ThreadFromThread extends Thread

{

        public static void main(String[] args)

        {

               ThreadFromThread tt = new ThreadFromThread();

               tt.start();

        }

        public void run(){     

               try{

                       for(int i=0; i<10; i++)

                       {

                               Thread.sleep(2000);

                              System.out.println(i + " 2초 마다 출력되는 소스 !!!");

                       }                     

               }

               catch(InterruptedException e){}

        }

};

#####################################################################

 

#####################################################################

19. 배열과 관련하여

#####################################################################

2차원 배열 출력하는 소스

 

int[][] aa =

        {

               {1,  6, 11, 16, 21},

               {2,  7, 12, 17, 22},

               {3,  8, 13, 18, 23},

               {4,  9, 14, 19, 24},

               {5, 10, 15, 20, 25}

        };

for (int i=0; i<aa.length ; i++)

{

        if (i<5)

        {

               for (int j=0; j<aa[i].length ; j++ )

               {

                       System.out.print(aa[i][j] +"  ");

               }

               System.out.println();

        }                     

}

#####################################################################

 

 

#####################################################################

20. 배열로 합계 평균을 내는 소스

#####################################################################

 

int sum = 0;

long average = 0;             

int[] aa = {20, 30, 40, 50, 30, 70};

int len = aa.length;

for (int i=0; i<aa.length ; i++)

{             

        sum += aa[i];

}

System.out.println("sum ->/"+sum+"/");

System.out.println("average ->/"+(long)sum/len+"/");

#####################################################################

 

 

#####################################################################

21. 프로그램 인수를 받아 평균과 총계를 보여주는 소스

#####################################################################

 

if ( args.length<1 )

{

        System.out.println("Usage : java ArrayDe_05  ");

        System.exit(-1);

}

int aa = Integer.parseInt(args[0]);

int[] bb = new int[aa];

for (int i=0; i<bb.length ; i++ )

{

        bb[i] = i+1;

}

int sum = 0;

long average = 0;

int len = bb.length;

for (int i=0; i<bb.length ; i++ )

{

        sum += bb[i];

}

System.out.println("sum ->/"+sum+"/");

System.out.println("average ->/"+(long)sum/len+"/");

#####################################################################

 

 

#####################################################################

22. [실행되지 않으나 참고해야 할 소스]

#####################################################################

프로그램 실행시간을 체크하는 소스

 

CronLog cl = new CronLog("Maker.log");

Date dSTART_PROG = new Date();

중간 프로세스 처리

Date dEND_PROG = new Date();

long lELAPSED = dEND_PROG.getTime() - dSTART_PROG.getTime();

cl.log("Making started at " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(dSTART_PROG));

cl.log("Making ended at " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(dEND_PROG));

cl.log("Making " + lELAPSED / 1000 + " seconds elapsed.");

#####################################################################

 

 

#####################################################################

23. 로그 관련 소스

#####################################################################

import java.io.File;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.PrintStream;

import java.util.Date;

import java.text.SimpleDateFormat;

import java.util.Calendar;

public class CronLog {

        private String sLOG_FILE = null, sLOG_PATH = null;

        private PrintStream out = null;

        SimpleDateFormat formatter;

        int iBACKUPFILE_KEEPING_DURATION = 30;    // 로그 파일 보관 일수(디폴트 30)

        public CronLog() {

               sLOG_FILE = makeLogFileName(Calendar.getInstance(), "MINU.log");

               formatter = new SimpleDateFormat("HH:mm:ss");

               removeLog( sLOG_FILE );

        }

        public CronLog(String sLOG_FILENAME) {

               sLOG_FILE = makeLogFileName(Calendar.getInstance(), sLOG_FILENAME);

               formatter = new SimpleDateFormat("HH:mm:ss");

               removeLog( sLOG_FILE );

        }

        public CronLog(String sLOG_FILENAME, int iBACKUPFILE_KEEPING_DURATION) {

               sLOG_FILE = makeLogFileName(Calendar.getInstance(), sLOG_FILENAME);

               formatter = new SimpleDateFormat("HH:mm:ss");

               this.iBACKUPFILE_KEEPING_DURATION = iBACKUPFILE_KEEPING_DURATION;

               removeLog( sLOG_FILE );

        }

        /** 해당 주기(iBACKUPFILE_KEEPING_DURATION)에 따라 로그 파일을 삭제함... */

        public void removeLog(String sLOG_FILE) {

               String sLOG_PATH = sLOG_FILE.substring(0, sLOG_FILE.lastIndexOf(File.separator)+1);

               if( sLOG_PATH.trim().equals("") ) {

                       sLOG_PATH = ".";

               }

               File fLOG_PATH = new File(sLOG_PATH);

               if( fLOG_PATH.isDirectory() ) {

                       File[] foLOG_FILES = fLOG_PATH.listFiles();

                       for(int i=0; i<foLOG_FILES.length; i++) {

                              File fLOG_FILE = foLOG_FILES[i];

                              long lLOG_FILE_ELAPSED = (new Date().getTime() - fLOG_FILE.lastModified()) / (24 * 60 * 60 * 1000);

                              if( fLOG_FILE.isFile() && lLOG_FILE_ELAPSED >= iBACKUPFILE_KEEPING_DURATION) {

                                      fLOG_FILE.delete();

                              }

                       }

               }

        }

        public void log(String sLOG) {

               if( sLOG_FILE == null ) {

                       sLOG_FILE = makeLogFileName(Calendar.getInstance(), "MINU.log");

               }             

               if( out == null ) {

                       File fLOG_FILE = new File(sLOG_FILE);       

                       FileOutputStream fos = null;

                       try {

                              fos = new FileOutputStream(sLOG_FILE, true);

                       } catch (FileNotFoundException e) {

                              System.err.println(e.toString());

                       }

                       out = new PrintStream(fos);

               }

               out.println("[" + formatter.format(new Date()) + "] " + sLOG);

        }

        public static String makeLogFileName(Calendar cal, String name) {

               java.util.Date dt = cal.getTime();

               SimpleDateFormat formatter = new SimpleDateFormat("@yyyy-MM-dd");

               String dateString = formatter.format(dt);

               int ind = name.indexOf(".");

               String head = name.substring(0, ind);

               String tail = name.substring(ind);

               name = head + dateString + tail;              

               checkDirectory(new File(name.substring(0, name.lastIndexOf(File.separator))));

               return name;

        }

        public static File checkDirectory(File dir) {

               File retVal = null;

               try {

                       if (!dir.isDirectory()) {

                              if (dir.mkdir()) {

                                      System.out.println("[" + dir.toString() + "] Directory Created, sucessfully.");

                              }

                       }

               } catch (Exception e) {

                       e.printStackTrace();

               }

               return dir;

        }

        public static void main(String[] args) {

               CronLog l = new CronLog("KKK.LOG");

               for(int i=0; i<100; i++ ) {

                       l.log(String.valueOf(i));

               }

               l.log("한글은???????????????????????????");

               l.log("Enddddddddddddddddddddddddddddddd");

        }

        public void log(int i) {

               log(String.valueOf(i));

        }

}

#####################################################################