'풀그림'에 해당되는 글 38건

  1. 2009.03.23 cvs소스 svn으로 옮기기 by 파이팅야 2
  2. 2009.03.19 .net reflection by 파이팅야 1
  3. 2008.10.08 Java ClassLoader by 파이팅야 1
  4. 2008.09.26 Eclipse ganymede 실행오류 발생시 by 파이팅야 4
  5. 2008.09.10 package 관련 by 파이팅야 1
  6. 2008.09.09 annotation by 파이팅야 2
  7. 2008.09.05 java에서 property파일 쉽게 찾기 by 파이팅야 1
  8. 2008.08.23 Class Object명 by 파이팅야 2
  9. 2008.08.22 system.properties 값 by 파이팅야 1
  10. 2008.08.19 java xml jaxp sample by 파이팅야 1

. A서버 svn의 소스를 B서버 svn으로 옮길 때

             - A서버의 Repositories폴더에서 dump파일 생성

                           svnadmin dump 저장소명 > dump파일명

ex) svnadmin dump ClientNetwork > ClientNetwork.dump

             - B서버의 Repositories폴더에서 dump파일 복구(admin저장소 안의 ‘source/ipms’폴더안에 저장시)

                           svnadmin load --parent-dir “저장할 폴더명저장소명 < dump파일명

                     ex)svnadmin load --parent-dir "source/ipms" admin < ipms.dump


. A서버 cvs의 소스를 B서버 svn으로 옮길 때

- A서버에서 python [d:\ Python26]폴더에 설치 (http://www.python.org)

- A서버에서 cvs2svn설치 (http://cvs2svn.tigris.org)에서 다운 받아서 [pthon.exe setup.py install]로 설치

- A서버에서 GNU sort(UnxUtils.zip)

(http://sourceforge.net/projects/unxutils)

압축풀고 [user/local/wbain/sort.exe] [d:\temp]에 복사

- A서버에서 다음의 명령어 실행해서 d:\temp폴더에 dump파일 생성

python D:\Python26\Scripts\cvs2svn --sort=D:\temp\sort.exe --encoding=cp949 --dumpfile=d:\temp\ipms.dump d:/cvs/ipms

- B서버의 Repositories폴더에서 다음의 명령어 실행해서 dump파일 복구

svnadmin load --parent-dir "source/ipms" admin < ipms.dump


. Reference

http://cvs2svn.tigris.org

http://www.python.org

http://sourceforge.net/projects/unxutils

http://iolothebard.tistory.com/401

http://www.xinublog.com/438 (linux에서)

 

Posted by 파이팅야
,

.net reflection

풀그림 2009. 3. 19. 17:51

. 포함관계

다음과 같이 Assemblies안에 포함관계가 있다.

Assemblies> Modules> types> members

 

예제

// Gets the mscorlib assembly in which the object is defined.

Assembly a = typeof(Object).Module.Assembly;

 

// Loads an assembly using its file name.

Assembly a = Assembly.LoadFrom ("MyExe.exe");

// Gets the type names from the assembly.

Type [] types2 = a.GetTypes ();

foreach (Type t in types2)

{

    Console.WriteLine (t.FullName);

}

 

// This program lists all the public constructors

// of the System.String class.

using System;

using System.Reflection;

class ListMembers {

    public static void Main(String[] args) {

        Type t = typeof(System.String);

        Console.WriteLine ("Listing all the public constructors of the {0} type", t);

        // Constructors.

        ConstructorInfo[] ci = t.GetConstructors(BindingFlags.Public | BindingFlags.Instance);

        Console.WriteLine ("//Constructors");

        PrintMembers (ci);

    }

    public static void PrintMembers(MemberInfo [] ms) {

        foreach (MemberInfo m in ms) {

            Console.WriteLine ("{0}{1}", "     ", m);

        }

        Console.WriteLine();

    }

}

 

 

class Mymemberinfo

{

    public static void Main(string[] args)

    {

        Console.WriteLine ("\nReflection.MemberInfo");

        // Gets the Type and MemberInfo.

        Type MyType =Type.GetType("System.IO.File");

        MemberInfo[] Mymemberinfoarray = MyType.GetMembers();

        // Gets and displays the DeclaringType method.

        Console.WriteLine("\nThere are {0} members in {1}.",

            Mymemberinfoarray.Length, MyType.FullName);

        Console.WriteLine("{0}.", MyType.FullName);

        if (MyType.IsPublic)

        {

            Console.WriteLine("{0} is public.", MyType.FullName);

        }

    }

}

 

 

// This code displays information about the GetValue method of FieldInfo.

class MyMethodInfo {

    public static int Main() {

        Console.WriteLine("Reflection.MethodInfo");

        // Gets and displays the Type.

        Type MyType = Type.GetType("System.Reflection.FieldInfo");

        // Specifies the member for which you want type information.

        MethodInfo Mymethodinfo = MyType.GetMethod("GetValue");

        Console.WriteLine(MyType.FullName + "." + Mymethodinfo.Name);

        // Gets and displays the MemberType property.

        MemberTypes Mymembertypes = Mymethodinfo.MemberType;

        if (MemberTypes.Constructor == Mymembertypes) {

            Console.WriteLine("MemberType is of type All");

        }

        else if (MemberTypes.Custom == Mymembertypes) {

            Console.WriteLine("MemberType is of type Custom");

        }

        else if (MemberTypes.Event == Mymembertypes) {

            Console.WriteLine("MemberType is of type Event");

        }

        else if (MemberTypes.Field == Mymembertypes) {

            Console.WriteLine("MemberType is of type Field");

        }

        else if (MemberTypes.Method == Mymembertypes) {

            Console.WriteLine("MemberType is of type Method");

        }

        else if (MemberTypes.Property == Mymembertypes) {

            Console.WriteLine("MemberType is of type Property");

        }

        else if (MemberTypes.TypeInfo == Mymembertypes) {

            Console.WriteLine("MemberType is of type TypeInfo");

        }

        return 0;

    }

}

 

 

 

// This program lists all the members of the

class ListMembers {

    public static void Main(String[] args) {

        // Specifies the class.

        Type t = typeof (System.IO.BufferedStream);

        Console.WriteLine ("Listing all the members (public and non public) of the {0} type", t);

 

        // Lists static fields first.

        FieldInfo [] fi = t.GetFields (BindingFlags.Static |

         BindingFlags.NonPublic | BindingFlags.Public);

        Console.WriteLine ("// Static Fields");

        PrintMembers (fi);

 

        // Static properties.

        PropertyInfo [] pi = t.GetProperties (BindingFlags.Static |

         BindingFlags.NonPublic | BindingFlags.Public);

        Console.WriteLine ("// Static Properties");

        PrintMembers (pi);

 

        // Static events.

        EventInfo [] ei = t.GetEvents (BindingFlags.Static |

         BindingFlags.NonPublic | BindingFlags.Public);

        Console.WriteLine ("// Static Events");

        PrintMembers (ei);

 

        // Static methods.

        MethodInfo [] mi = t.GetMethods (BindingFlags.Static |

         BindingFlags.NonPublic | BindingFlags.Public);

        Console.WriteLine ("// Static Methods");

        PrintMembers (mi);

 

        // Constructors.

        ConstructorInfo [] ci = t.GetConstructors (BindingFlags.Instance |

         BindingFlags.NonPublic | BindingFlags.Public);

        Console.WriteLine ("// Constructors");

        PrintMembers (ci);

 

        // Instance fields.

        fi = t.GetFields (BindingFlags.Instance | BindingFlags.NonPublic |

         BindingFlags.Public);

        Console.WriteLine ("// Instance Fields");

        PrintMembers (fi);

 

        // Instance properites.

        pi = t.GetProperties (BindingFlags.Instance | BindingFlags.NonPublic |

         BindingFlags.Public);

        Console.WriteLine ("// Instance Properties");

        PrintMembers (pi);

 

        // Instance events.

        ei = t.GetEvents (BindingFlags.Instance | BindingFlags.NonPublic |

         BindingFlags.Public);

        Console.WriteLine ("// Instance Events");

        PrintMembers (ei);

 

        // Instance methods.

        mi = t.GetMethods (BindingFlags.Instance | BindingFlags.NonPublic  

         | BindingFlags.Public);

        Console.WriteLine ("// Instance Methods");

        PrintMembers (mi);

 

        Console.WriteLine ("\r\nPress ENTER to exit.");

        Console.Read();

    }

 

    public static void PrintMembers (MemberInfo [] ms) {

        foreach (MemberInfo m in ms) {

            Console.WriteLine ("{0}{1}", "     ", m);

        }

        Console.WriteLine();

    }

}

 

 

// Code for building SimpleType.dll.

using System;

 

namespace Simple_Type

{

    public class MySimpleClass

    {

        public void MyMethod(string str, int i)

        {

            Console.WriteLine("MyMethod parameters: {0}, {1}", str, i);

        }

 

        public void MyMethod(string str, int i, int j)

        {

            Console.WriteLine("MyMethod parameters: {0}, {1}, {2}",

                str, i, j);

        }

    }

}

 

 

using System;

using System.Reflection;

using System.Globalization;

// The Simple Type namespace.

using Simple_Type;

namespace Custom_Binder

{

    class MyMainClass

    {

        static void Main()

        {

            // Get the type of MySimpleClass.

            Type myType = typeof(MySimpleClass);

 

            // Get an instance of MySimpleClass.

            MySimpleClass myInstance = new MySimpleClass();

            MyCustomBinder myCustomBinder = new MyCustomBinder();

 

            // Get the method information for the particular overload

            // being sought.

            MethodInfo myMethod = myType.GetMethod("MyMethod",

                BindingFlags.Public | BindingFlags.Instance,

                myCustomBinder, new Type[] {typeof(string),

                    typeof(int)}, null);

            Console.WriteLine(myMethod.ToString());

           

            // Invoke the overload.

            myType.InvokeMember("MyMethod", BindingFlags.InvokeMethod,

                myCustomBinder, myInstance,

                    new Object[] {"Testing...", (int)32});

        }

    }

 

    //****************************************************

    //  A simple custom binder that provides no

    //  argument type conversion.

    //****************************************************

    class MyCustomBinder : Binder

    {

        public override MethodBase BindToMethod(

            BindingFlags bindingAttr,

            MethodBase[] match,

            ref object[] args,

            ParameterModifier[] modifiers,

            CultureInfo culture,

            string[] names,

            out object state)

        {

            if(match == null)

                throw new ArgumentNullException("match");

            // Arguments are not being reordered.

            state = null;

            // Find a parameter match and return the first method with

            // parameters that match the request.

            foreach(MethodBase mb in match)

            {

                ParameterInfo[] parameters = mb.GetParameters();

 

                if(ParametersMatch(parameters, args))

                    return mb;

            }

            return null;

        }

 

        public override FieldInfo BindToField(BindingFlags bindingAttr,

            FieldInfo[] match, object value, CultureInfo culture)

        {

            if(match == null)

                throw new ArgumentNullException("match");

            foreach(FieldInfo fi in match)

            {

                if(fi.GetType() == value.GetType())

                    return fi;

            }

            return null;

        }

 

        public override MethodBase SelectMethod(

            BindingFlags bindingAttr,

            MethodBase[] match,

            Type[] types,

            ParameterModifier[] modifiers)

        {

            if(match == null)

                throw new ArgumentNullException("match");

 

            // Find a parameter match and return the first method with

            // parameters that match the request.

            foreach(MethodBase mb in match)

            {

                ParameterInfo[] parameters = mb.GetParameters();

                if(ParametersMatch(parameters, types))

                    return mb;

            }

 

            return null;

        }

 

        public override PropertyInfo SelectProperty(

            BindingFlags bindingAttr,

            PropertyInfo[] match,

            Type returnType,

            Type[] indexes,

            ParameterModifier[] modifiers)

        {

            if(match == null)

                throw new ArgumentNullException("match");

            foreach(PropertyInfo pi in match)

            {

                if(pi.GetType() == returnType &&

                    ParametersMatch(pi.GetIndexParameters(), indexes))

                    return pi;

            }

            return null;

        }

 

        public override object ChangeType(

            object value,

            Type myChangeType,

            CultureInfo culture)

        {

            try

            {

                object newType;

                newType = Convert.ChangeType(value, myChangeType);

                return newType;

            }

            // Throw an InvalidCastException if the conversion cannot

            // be done by the Convert.ChangeType method.

            catch(InvalidCastException)

            {

                return null;

            }

        }

 

        public override void ReorderArgumentArray(ref object[] args,

            object state)

        {

            // No operation is needed here because BindToMethod does not

            // reorder the args array. The most common implementation

            // of this method is shown below.

           

            // ((BinderState)state).args.CopyTo(args, 0);

        }

 

        // Returns true only if the type of each object in a matches

        // the type of each corresponding object in b.

        private bool ParametersMatch(ParameterInfo[] a, object[] b)

        {

            if(a.Length != b.Length)

                return false;

            for(int i = 0; i < a.Length; i++)

            {

                if(a[i].ParameterType != b[i].GetType())

                    return false;

            }

            return true;

        }

 

        // Returns true only if the type of each object in a matches

        // the type of each corresponding entry in b.

        private bool ParametersMatch(ParameterInfo[] a, Type[] b)

        {

            if(a.Length != b.Length)

                return false;

            for(int i = 0; i < a.Length; i++)

            {

                if(a[i].ParameterType != b[i])

                    return false;

            }

            return true;

        }

    }

}

 

 

 

public class CustomBinderDriver

{

    public static void Main (string[] arguments)

    {

    Type t = typeof (CustomBinderDriver);

    CustomBinder binder = new CustomBinder();

    BindingFlags flags = BindingFlags.InvokeMethod|BindingFlags.Instance|

        BindingFlags.Public|BindingFlags.Static;

 

    // Case 1. Neither argument coercion nor member selection is needed.

    args = new Object[] {};

    t.InvokeMember ("PrintBob", flags, binder, null, args);

 

    // Case 2. Only member selection is needed.

    args = new Object[] {42};

    t.InvokeMember ("PrintValue", flags, binder, null, args);

 

    // Case 3. Only argument coercion is needed.

    args = new Object[] {"5.5"};

    t.InvokeMember ("PrintNumber", flags, binder, null, args);

    }

 

    public static void PrintBob ()

    {

        Console.WriteLine ("PrintBob");

    }

 

    public static void PrintValue (long value)

    {

        Console.WriteLine ("PrintValue ({0})", value);

    }

    public static void PrintValue (String value)

    {

        Console.WriteLine ("PrintValue\"{0}\")", value);

    }

  

    public static void PrintNumber (double value)

    {

        Console.WriteLine ("PrintNumber ({0})", value);

    }

}

 

 

Type t = typeof(DefaultMemberAttribute);

DefaultMemberAttribute defMem = (DefaultMemberAttribute)Attribute.GetCustomAttribute(Assembly.GetAssembly(t), t);

MemberInfo[] memInfo = t.GetMember(defMem.MemberName);

 

 

MemberInfo[] memInfo = t.GetDefaultMembers();

 

 

MethodInfo m = t.GetMethod ("MyMethod");

ParameterInfo[] ps = m.GetParameters();

for (int i = 0; i < ps.Length; i++) {

    Console.WriteLine("Default Value == {0}", ps[i].DefaultValue);

}

 

 

 

class MainClass

{

public static void Main()

{

    System.Reflection.MemberInfo info = typeof(MyClass);

    object[] attributes = info.GetCustomAttributes();

    for (int i = 0; i < attributes.Length; i ++)

        {

        System.Console.WriteLine(attributes[i]);

        }

    }

}

. 구현한 예제(첨부파일안의 내용)

 

[Att1("Program Class", 0, IsClass=true)]

    public class _Main

    {

        [Att1("Program TestMethod1 Method", 1, IsClass=false)]

        public void TestMethod1()

        {

            System.Console.WriteLine("in Program.TestMethod1()");

        }

        public static void PrintAnnotation(Type type)

        {

            // 해당ClassAttribute가있는지확인

            Att1[] att1s = (Att1[])Attribute.GetCustomAttributes(type, typeof(Att1));

            if (att1s == null)

            {

                Console.WriteLine(">>Class[{0}], Attributes is null", type);

                return;

            }

            else if (att1s.Length == 0)

            {

                Console.WriteLine(">>Class[{0}], Attributes Length is 0", type);

                return;

            }

 

            for (int i = 0; i < att1s.Length; i++)

            {

                Console.WriteLine("***********\r\nClass[{0}]\r\n\tdesc[{1}], level[{2}], isClass[{3}]",

                    type, att1s[i].Description, att1s[i].Level, att1s[i].IsClass);

            }

 

            // MethodAnnotation있는지확인

            MemberInfo[] memberInfos = type.GetMembers();

            //Console.WriteLine("memberInfos.length[{0}]", memberInfos.Length);

 

            Object objectInstance = type.InvokeMember(null,

                BindingFlags.CreateInstance, null, null, new Object[] {});

//            Console.WriteLine("objectInstance[{0}]", objectInstance);

 

            for (int i = 0; i < memberInfos.Length; i++)

            {

                Console.Write("Method[{0}], Annotaion[", memberInfos[i].ToString());

 

                Att1 att1Method = (Att1)Attribute.GetCustomAttribute(memberInfos[i], typeof(Att1));

                if (att1Method == null)

                    Console.WriteLine("X]");

                else

                {

                    Console.WriteLine("O]\r\n\tdesc[{0}], level[{1}], isClass[{2}]",

                        att1Method.Description, att1Method.Level, att1Method.IsClass);

                   

                    Console.WriteLine("\t[실행전]");

                    type.InvokeMember(

                        memberInfos[i].Name,

                        BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance | BindingFlags.InvokeMethod

                        , null, objectInstance, null);

                    Console.WriteLine("\t[실행후]");

                }

            }

        }

 

        public static void Main(string[] args)

        {

            // 현재클래스나같은프로젝트의다른클래스의Annotation정보출력

            PrintAnnotation(typeof(_Main));

            PrintAnnotation(typeof(Example1));

 

            // 외부Assembly를읽어서Annotation정보출력

//            Assembly assembly = Assembly.LoadFile("D:\\Dev\\_Test\\TestAnnotation\\ExampleLibrary\\bin\\Debug\\ExampleLibrary.dll");

            Assembly assembly = Assembly.LoadFrom("D:\\Dev\\_Test\\TestAnnotation\\ExampleLibrary\\bin\\Debug\\ExampleLibrary.dll");

            Type[] types = assembly.GetTypes();

 

            foreach (Type type in types)

            {

                PrintAnnotation(type);

            }

 

            Console.ReadLine();

}

    }

 

Assembly.LoadFile() A.dll을 호출하면 A.dll에서 참조하는 B.dll은 호출할수 없으나,

Assembly.LoadFrom()으로 호출하면 가능

 

. 참조URL

- Reflection Overview

http://msdn.microsoft.com/en-us/library/f7ykdhsy(VS.71).aspx

- Viewing Type Information

http://msdn.microsoft.com/en-us/library/t0cs7xez(VS.71).aspx

- Dynamically Loading and Using Types

http://msdn.microsoft.com/en-us/library/k3a58006(VS.71).aspx

- Accessing Default Members

http://msdn.microsoft.com/en-us/library/zcfck9kw(VS.71).aspx

- Accessing Default Argument Values

http://msdn.microsoft.com/en-us/library/x0acewhc(VS.71).aspx

- Accessing Custom Attributes

http://msdn.microsoft.com/en-us/library/a4a92379(VS.71).aspx

 

Posted by 파이팅야
,

Java ClassLoader

풀그림 2008. 10. 8. 11:17

. ClassLoader ?

- The Java Classloader is a part of the Java Runtime Environment that dynamically loads Java classes into the Java Virtual Machine

- 클래스 로더는 런타임에 클래스 파일을 찾고 로딩하는 임무를 맡는다. 자바에서는 상이한 클래스 로더를 사용하는 것이 가능하며, 커스터마이즈로 클래스 로더를 사용해도 된다. 클래스 파일은 스태틱(static)하게 빌드된 C 프로그램처럼 메모리에 한꺼번에 로드되지 않고 온디맨드 방식으로 로드된다. ClassLoader가 메모리에 올리게 한다.

- .class ClassLoader가 메모리에 올라가는 [Class 객체]로 만드는 것이다. 여기서 주의할 점은 [Class 객체] [일반객체]가 아님을 알아 두어야 한다. [Class객체]를 통해서 [일반객체]들이 생성된다. static변수들도 [Class객체]에 있어서 Global하게 사용이 가능하다. ([일반 객체] Garbage Collection의 대상이 되지만 [Class 객체] Garbage Collection의 대상이 되지 않기 때문이다.)

- 클래스 로더는 클래스들을 Java Virtual Machine (JVM)에 로딩하는 일을 담당한다

. 기능

- 로컬이나 네트웤에 있는 .class .jar파일들을 동적으로 로딩이 가능하다.

(클래스패스로 잡혀 있지 않은 경우에 URLClassLoader 이용해서 동적으로 클래스를 로딩할 있다. 주의할 점들이 있어서 남긴다. URLClassLoader 클래스는 java.net 패키지에 존재한다. 클래스는 클래스들을 URL 기반으로 하여 디스크나 네트워크를 통해서 다이나믹하게 로딩하는 것을 지원해 준다)

(http://cafe.naver.com/lekpro.cafe?iframe_url=/ArticleRead.nhn%3Farticleid=242)

. 종류 와 설명

- Bootstrap class loader,  Extensions class loader, System class loader

The bootstrap class loader loads the core Java libraries, i.e. core.jar, server.jar etc. in the <JAVA_HOME>/lib directory. This class loader, which is part of the core JVM, is written in native code.

The extensions class loader loads the code in the extensions directories (<JAVA_HOME>/lib/ext or any other directory specified by the java.ext.dirs system property). It is implemented by the sun.misc.Launcher$ExtClassLoader class.

The system class loader loads code found on java.class.path, which maps to the system CLASSPATH variable. This is implemented by the sun.misc.Launcher$AppClassLoader class.

(http://en.wikipedia.org/wiki/Java_Classloader)

-

 Bootstrap classLoader는 모든 ClassLoader의 부모 ClassLoader이며,   ClassLoader를 사용해서 standard JDK classes를 로드하게 됩니다.
Extensions ClassLoader
Bootstrap ClassLoader를 상속하며, lib/ext 디렉토리에 있는 클래스를 로드하게 됩니다
.
마지막으로 System-Classpath ClassLoader Extensions ClassLoader를 상속하며, CLASSPATH에 잡혀 있는 모든 클래스, java.class.path 시스템 프라퍼티, -cp 혹은 -classpath에 잡혀 있는 모든 클래스를 로드하게 됩니다
.

OSGi
를 이해하는데 중요한 개념이 ClassLoader이기 때문에 ClassLoader를 조금 살펴봤습니다. 물론 OSGi가 아니더라도 중요한 문제겠죠
.

Crosscutter
님께서
좋은 를 해주셔서 열심히 읽어 봤습니다. 간단히 정리해보면 아래와 같습니다. 자세한 내용은 링크를 직접 읽어보시면 됩니다.

- 규칙 1. 클래스 로더는 계층 구조를 형성
-
규칙 2. 클래스는 필요 시점에 로딩된다.
-
규칙 3. 클래스 A를 로팅할 때는, 클래스 A를 호출한 클래스 B의 클래스 로더가 인스턴스 로딩을 담당한다
.
-
규칙 4. 클래스 유일성 식별: 클래스명+패키지명+클래스로더 인스턴스

-
규칙 5. 클래스 로더에는 명시적인 Unload가 없다. 대신 GC될 때 Unload 된다.

(http://chanwook.tistory.com/622)

. 내용

- 모든 ClassLoader의 입구는 loadClass 메소드가 된다. loadClass를 호출하게 되면 최초로 findLoadedClass라는 메소드를 호출하는데, 이것은 메모리에 Class 객체가 존재하는지 먼저 확인하고 있으면 바로 Class 객체를 반환하게 되고, 없으면 상위 ClassLoader에게 의뢰하게 된다. 이러한 식으로 최상위인 System ClassLoader까지 거슬러 올라가서 메모리를 확인한다. System ClassLoader에서는 findLoadedClass 메소드를 통해서 아무런 Class 객체를 찾을 수 없다면 비로소 findClass 메소드를 호출하게 된다. findClass는 실제로 자신의 Classpath를 뒤져서 해당 .class 파일을 찾게 된다. findClass 메소드 내부에서 .class 파일을 찾게 되면 defineClass라는 메소드를 호출하게 되는데, 이는 protected 메소드이므로 시퀀스 다이어그램에서 표현하지는 않았다. defineClass 메소드는 찾은 .class 라는 자바 바이트 코드 파일을 Class 객체로 변환하는 작업을 하게 된다. 만약 findClass 메소드에서 .class 파일을 찾지 못하면 ClassNotFoundException을 발생시키며 바로 하위 ClassLoader에게 보낸다.

하위 ClassLoader에서는 위에서 수행한 findClass 메소드를 수행한다. 여기서도 발견을 못하면 또 하위로 ClassNotFoundException을 내려 보낸다. 계속해서 최하위까지 내려 갔을 경우 아무 것도 찾지 못했다면, 결국 사용자가 ClassNotFoundException을 받게 되는 것이다.

[출처] ClassLoader 비밀|작성자 asura71

 

- 로드된 클래스를 위해 ClassLoder 의 어떤 인스턴스가 메쏘드를 호출했는지는 매우 중요하다. 그러므로 두 개의 ClassLoder 인스턴스가 동일한 혹은 상이한 소스의 바이트 코드를 정의한다면 정의된 클래스는 다르게 다뤄진다.

. 사용예

// Hello.java
public class Hello {
  public String returnSay() {
    return "Hello World";
  }
}
 
// Hello2.java
import java.lang.reflect.*;
import java.net.*;
 
public class Hello2 {
  public static void main(String[] args) throws Exception {
    if (args.length != 2) {
      System.out.println("Usage: java Hello2 클래스명 메소드명");
      System.exit(0);
    }
    URL[] urlArray =
    {
      new java.io.File("ttr/").toURL()
    };
    Class cls = new URLClassLoader(urlArray).loadClass(args[0]);
    Object obj = cls.newInstance();
    Method method = cls.getMethod(args[1],null);
    String s = (String)method.invoke(obj,null);
    System.out.println(s);
  }
}

[SeparateClassLoaderWithStatic2.
class.getClassLoader()]
null이 들어가면 결과가 true, false가 나온다.

 

. 간단히 dynamic loading하는 소스

- Class type = ClassLoader.getSystemClassLoader().loadClass(name);

Object obj = type.newInstance();

 

. The basics of Java class loaders

http://www.javaworld.com/javaworld/jw-10-1996/jw-10-indepth.html

. classloader를 자세히 설명되어 있음

http://blog.naver.com/asura71?Redirect=Log&logNo=30021992124

. URLClassLoader 셈플

http://cafe.naver.com/lekpro.cafe?iframe_url=/ArticleRead.nhn%3Farticleid=242

. Classloader에 대한 기사내용

http://news.naver.com/main/read.nhn?mode=LSD&mid=sec&sid1=105&oid=092&aid=0000008699

. IBM ClassLoader관련 자세한 설명

http://www.ibm.com/developerworks/kr/series/j-dclp.html?ca=dnn-krt-20071226

. auto reload하는 프로그램(Thread.currentThread().setContextClassLoader(classLoader) 사용예)http://blog.naver.com/jjoommnn?Redirect=Log&logNo=130027297615

 

Posted by 파이팅야
,

---------------------------
Eclipse
---------------------------
JVM terminated. Exit code=-1
-Dosgi.requiredJavaVersion=1.5
-Xms40m
-Xmx512m
-XX:MaxPermSize=256M
-Djava.class.path=D:\Dev\eclipse\plugins\org.eclipse.equinox.launcher_1.0.101.R34x_v20080819.jar
-os win32
-ws win32
-arch x86
-showsplash D:\Dev\eclipse\\plugins\org.eclipse.platform_3.3.101.v200809111700\splash.bmp
-launcher D:\Dev\eclipse\eclipse.exe
-name Eclipse
--launcher.library D:\Dev\eclipse\plugins\org.eclipse.equinox.launcher.win32.win32.x86_1.0.101.R34x_v20080731\eclipse_1115.dll
-startup D:\Dev\eclipse\plugins\org.eclipse.equinox.launcher_1.0.101.R34x_v20080819.jar
-vm C:\Program Files\Java\jre1.6.0_01\bin\client\jvm.dll
-vmargs
-Dosgi.requiredJavaVersion=1.5
-Xms40m
-Xmx512m
-XX:MaxPermSize=256M
-Djava.class.path=D:\Dev\eclipse\plugins\org.eclipse.equinox.launcher_1.0.101.R34x_v20080819.jar

위와 같은 오류가 발생하면 다음과 같이 eclipse.ini파일을 수정하면 된다.
(실행환경, win server 2003)
-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
256m
-vm
C:\Java\JDK\1.5\bin\javaw.exe
-vmargs
-Xms40m
-Xmx512m
출처 : http://wiki.eclipse.org/Eclipse.ini
Posted by 파이팅야
,

package 관련

풀그림 2008. 9. 10. 17:25

. Package.getPackages()를 호출하면 현재의 ClassLoader가 로드했던 Package들만 반환된다.

 

. jar파일안의 package에 해당하는 class들 출력

public static List getClasseNamesInPackage(String jarName, String packageName) {

         ArrayList classes = new ArrayList();

 

         packageName = packageName.replaceAll("\\.", "/");

         System.out.println("Jar " + jarName + " looking for " + packageName);

         try {

                  JarInputStream jarFile =

                           new JarInputStream(new FileInputStream(jarName));

                  JarEntry jarEntry;

 

                  while (true) {

                           jarEntry = jarFile.getNextJarEntry();

                           if (jarEntry == null) {

                                   break;

                           }

                           if ((jarEntry.getName().startsWith(packageName))

                                 && (jarEntry.getName().endsWith(".class"))) {

         System.out.println("Found " + jarEntry.getName().replaceAll("/", "\\."));

                       classes.add(jarEntry.getName().replaceAll("/", "\\."));

                           }

                  }

         } catch (Exception e) {

                  e.printStackTrace();

         }

         return classes;

}
. 해당 package에 있는 class Command instance인 것 찾기
public static void find(String pckgname) {

         String name = new String(pckgname);

         if (!name.startsWith("/")) {

                  name = "/" + name;

         }

         name = name.replace('.', '/');

 

         // Get a File object for the package

         URL url = Launcher.class.getResource(name);

         File directory = new File(url.getFile());

         // New code

         // ======

         if (!directory.exists())

                  return ;

         // Get the list of the files contained in the package

         String[] files = directory.list();

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

         // we are only interested in .class files

         if (files[i].endsWith(".class")) {

                  // removes the .class extension

                  String classname = files[i].substring(0,

                                   files[i].length() - 6);

                  try {

                           // Try to create an instance of the object

                           Object o = Class.forName(pckgname + "." + classname)

                                            .newInstance();

                           if (o instanceof Command) {

                                   System.out.println(classname);

                           }

                  } catch (ClassNotFoundException cnfex) {

                           System.err.println(cnfex);

                  } catch (InstantiationException iex) {

                           // We try to instantiate an interface

                           // or an object that does not have a

                           // default constructor

                  } catch (IllegalAccessException iaex) {

                           // The class is not public

                  }

         }

         }

}

출처 :

http://www.javaworld.com/javaworld/javatips/jw-javatip113.html

http://www.rgagnon.com/javadetails/java-0513.html

Posted by 파이팅야
,

annotation

풀그림 2008. 9. 9. 21:46

Many APIs require a fair amount of boilerplate code. For example, in order to write a JAX-RPC web service, you must provide a paired interface and implementation. This boilerplate could be generated automatically by a tool if the program were decorated with annotations indicating which methods were remotely accessible.

Other APIs require side files to be maintained in parallel with programs. For example JavaBeans requires a BeanInfo class to be maintained in parallel with a bean, and Enterprise JavaBeans (EJB) requires a deployment descriptor. It would be more convenient and less error-prone if the information in these side files were maintained as annotations in the program itself.

The Java platform has always had various ad hoc annotation mechanisms. For example the transient modifier is an ad hoc annotation indicating that a field should be ignored by the serialization subsystem, and the @deprecated javadoc tag is an ad hoc annotation indicating that the method should no longer be used. As of release 5.0, the platform has a general purpose annotation (also known as metadata) facility that permits you to define and use your own annotation types. The facility consists of a syntax for declaring annotation types, a syntax for annotating declarations, APIs for reading annotations, a class file representation for annotations, and an annotation processing tool.

Annotations do not directly affect program semantics, but they do affect the way programs are treated by tools and libraries, which can in turn affect the semantics of the running program. Annotations can be read from source files, class files, or reflectively at run time.

Annotations complement javadoc tags. In general, if the markup is intended to affect or produce documentation, it should probably be a javadoc tag; otherwise, it should be an annotation.

Typical application programmers will never have to define an annotation type, but it is not hard to do so. Annotation type declarations are similar to normal interface declarations. An at-sign (@) precedes the interface keyword. Each method declaration defines an element of the annotation type. Method declarations must not have any parameters or a throws clause. Return types are restricted to primitives, String, Class, enums, annotations, and arrays of the preceding types. Methods can have default values. Here is an example annotation type declaration:

/**

 * Describes the Request-For-Enhancement(RFE) that led

 * to the presence of the annotated API element.

 */

public @interface RequestForEnhancement {

    int    id();

    String synopsis();

    String engineer() default "[unassigned]";

    String date();    default "[unimplemented]";

}

Once an annotation type is defined, you can use it to annotate declarations. An annotation is a special kind of modifier, and can be used anywhere that other modifiers (such as public, static, or final) can be used. By convention, annotations precede other modifiers. Annotations consist of an at-sign (@) followed by an annotation type and a parenthesized list of element-value pairs. The values must be compile-time constants. Here is a method declaration with an annotation corresponding to the annotation type declared above:

@RequestForEnhancement(

    id       = 2868724,

    synopsis = "Enable time-travel",

    engineer = "Mr. Peabody",

    date     = "4/1/3007"

)

public static void travelThroughTime(Date destination) { ... }

An annotation type with no elements is termed a marker annotation type, for example:

/**

 * Indicates that the specification of the annotated API element

 * is preliminary and subject to change.

 */

public @interface Preliminary { }

It is permissible to omit the parentheses in marker annotations, as shown below:

@Preliminary public class TimeTravel { ... }

In annotations with a single element, the element should be named value, as shown below:

/**

 * Associates a copyright notice with the annotated API element.

 */

public @interface Copyright {

    String value();

}

It is permissible to omit the element name and equals sign (=) in a single-element annotation whose element name is value, as shown below:

@Copyright("2002 Yoyodyne Propulsion Systems")

public class OscillationOverthruster { ... }

To tie it all together, we'll build a simple annotation-based test framework. First we need a marker annotation type to indicate that a method is a test method, and should be run by the testing tool:

import java.lang.annotation.*;

 

/**

 * Indicates that the annotated method is a test method.

 * This annotation should be used only on parameterless static methods.

 */

@Retention(RetentionPolicy.RUNTIME)

@Target(ElementType.METHOD)

public @interface Test { }

Note that the annotation type declaration is itself annotated. Such annotations are called meta-annotations. The first (@Retention(RetentionPolicy.RUNTIME)) indicates that annotations with this type are to be retained by the VM so they can be read reflectively at run-time. The second (@Target(ElementType.METHOD)) indicates that this annotation type can be used to annotate only method declarations.

Here is a sample program, some of whose methods are annotated with the above interface:

public class Foo {

    @Test public static void m1() { }

    public static void m2() { }

    @Test public static void m3() {

        throw new RuntimeException("Boom");

    }

    public static void m4() { }

    @Test public static void m5() { }

    public static void m6() { }

    @Test public static void m7() {

        throw new RuntimeException("Crash");

    }

    public static void m8() { }

}

Here is the testing tool:

import java.lang.reflect.*;

 

public class RunTests {

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

      int passed = 0, failed = 0;

      for (Method m : Class.forName(args[0]).getMethods()) {

         if (m.isAnnotationPresent(Test.class)) {

            try {

               m.invoke(null);

               passed++;

            } catch (Throwable ex) {

               System.out.printf("Test %s failed: %s %n", m, ex.getCause());

               failed++;

            }

         }

      }

      System.out.printf("Passed: %d, Failed %d%n", passed, failed);

   }

}

The tool takes a class name as a command line argument and iterates over all the methods of the named class attempting to invoke each method that is annotated with the Test annotation type (defined above). The reflective query to find out if a method has a Test annotation is highlighted in green. If a test method invocation throws an exception, the test is deemed to have failed, and a failure report is printed. Finally, a summary is printed showing the number of tests that passed and failed. Here is how it looks when you run the testing tool on the Foo program (above):

$ java RunTests Foo

Test public static void Foo.m3() failed: java.lang.RuntimeException: Boom

Test public static void Foo.m7() failed: java.lang.RuntimeException: Crash

Passed: 2, Failed 2

While this testing tool is clearly a toy, it demonstrates the power of annotations and could easily be extended to overcome its limitations.


출처 : http://java.sun.com/j2se/1.5.0/docs/guide/language/annotations.html

Posted by 파이팅야
,

java로 프로그래밍을 하다가 보면 몇가지 설정값을 외부에서 받아야 하는 경우가 있는데 이때 사용하는 것이 property 파일이다.

jdk에도 이 프로퍼티 파일을 다룰 수 있는 클래스가 마련되어 있다. java.util.Properties 클래스가 그 용도이다.

이 클래스를 사용하려면 load라는 메소드를 통해서 프로퍼티 파일일 읽어 와야 하는데 이때 전달되는 인자는 InputStream이다.

문제는 이 InputStream을 전달하려면 FileInputStream을 만들어서 전달해야 하는데 이 FileInputStream을 생성하려면 그 프로퍼티 파일의 경로를 알아야 한다는 것이다.

프로퍼티 파일의 경로를 알아오는 방법에 대해서 몇가지 생각해 보자

1. 프로그램 코드에 상수로 프로터피 파일의 경로를 둔다.

예를들면,

public staitc final String PATH = "/app/myapp/myprop.properties";

 

라고 두는 것이다. 뭐 이건 말 안해도 알겠지만 별로 좋지 않은 방법이다. 경로나 이름이 바뀌면 새로 컴파일 해야 하고, 뭐 이래저래 좋지 않은거 같다.

 

2. java 실행 옵션으로 세팅해서 프로그램에서 사용한다.

java 프로그램을 실행시킬 때 실행 옵션으로 프로퍼티 파일의 경로를 줘서 그 옵션값을 읽어서 경로로 사용하도록 하는 것이다.

 

String path = System.getProperty( "path" );

라는 형태로 사용하면 실행시 준 옵션값을 가져올 수 있다.

이 방법도 많이 사용하는 방법으로 나름대로 쓸만하다. 그렇지만 실행시 옵션을 설정한다는 것이 별로 마음에 안든다.

 

 

3. ClassLoader를 사용하여 가져온다.

혹시 이거 신기하게 생각해 본 사람이 있을지 모르겠는데, log4j를 사용하다 보면 log4j.properties라는 파일을 생성해 두면 내가 특별히 경로를 세팅하지 않았는데도 log4j가 알아서 log4j.properties를 읽어서 사용한다. 나는 처음에 이게 무지 신기했다. log4j가 어떻게 알고 그 위치의 log4j.properties를 읽어 들이는 걸까?

 

해답은 ClassLoader 였다.

 

classloader 주요 기능은 클래스를 로딩하는 것이다.(이름에서 알 수 있는 너무 당연한 이야긴가? ^^;)

 

하지만 기능이 한가지 더 있는데 바로 클래스 파일 뿐아니라 다른 리소스 파일도 읽어 주는 역할이다.

ClassLoader.getResource( String name )이 그 역할을 하는 메소드다(이 메소드 외에도 getResource... 메소드들이 몇가지 더 있다. 알아서 찾아 보시길...)

 

getResource는 클래스 패스내에서 해당 이름으로 된 파일을 찾아서 그 URL을 넘겨준다. 중요한 포인트는 바로 클래스 패스 내에 있는 파일이라는 것이다.

 

java를 실행시킬때 -classpath라고 주는 바로 그 클래스 패스 말이다. classpath에 설정한 클래스 패스내에 프로퍼티 파일을 두면 ClassLoader를 통해서 프로퍼티 파일을 가져올 수 있는 것이다. 별거 아닌 기능 같지만 쓰다보면 상당히 편리하다.

실제 구현 내용을 간단히 살펴보면 다음과 같다.

 

        ClassLoader cl;
        cl = Thread.currentThread().getContextClassLoader();
        if( cl == null )
            cl = ClassLoader.getSystemClassLoader();
               
        URL url = cl.getResource( "myprop.properties" );

 

위 내용은 log4j의 소스에서 일부 참조한 것이다.

위 소스를 참조해서 쉽게 프로퍼티 파일을 다룰 수 있는 클래스를 만들어 보는 것도 좋을 듯 하다.

앞선 글에서 ClassLoader를 이용하여 property 파일 찾는 코드에 대해 부연 설명을 좀 해 보자.

앞선 코드는

 

        ClassLoader cl;
        cl = Thread.currentThread().getContextClassLoader();
        if( cl == null )
            cl = ClassLoader.getSystemClassLoader();                
        URL url = cl.getResource( "myprop.properties" );

 

였다.

이때 그냥

 

ClassLoader cl = ClassLoader.getSystemClassLoader();

하지 않고

 

cl = Thread.getContextClassLoader();

를 통해서 먼저 ClassLoader를 구해오는 것은 나름대로 이유가 있다.

 

java 프로그래밍의 상당 부분은 독립실행되는 java application보다 web application의 형태로, container(tomcat, weblogic 등등) 안에서 실행되는 application으로 제작되는 경우가 많다.

 

container는 여러 application을 분리하기 위해 각 application마다 ClassLoader를 새로 생성해서 사용하며, application을 구동시키기 위해 Thread를 생성한다. 이때 container application을 위해 생성한 Thread setContextClassLoader를 통하여 그 application을 위해 생성한 ClassLoader를 세팅해 준다.

 

따라서 container안에서 실행되는 application에서는 resource를 찾기 위해 system ClassLoader가 아니라 그 application을 로드하는 ClassLoader를 사용해야 한다. 그래서 위의 코드처럼 Thread ClassLoader를 먼저 체크해 봐야 하는 것이다.

 

예상했겠지만, 이때 그 application을 위해 생성된 ClassLoader에 세팅되는 Class Path, application에만 해당되는 path( ex)classes, lib 등등)만 추가되기 때문에 다른 위치에 있는 resource는 가져오지 않는, 아니 가져올 수 없게 되는 것이다.

 

물론 독립실행형 java application에서는 그냥 System.getSystemClassLoader()만 사용해도 된다.

[출처] java에서 Property 파일 쉽게 찾기2|작성자 쫌조

 

Posted by 파이팅야
,

Class Object명

풀그림 2008. 8. 23. 16:29

Class cls = java.lang.String.class;

String name = cls.getName();        // java.lang.String

 

// inner class

cls = java.util.Map.Entry.class;

name = cls.getName();               // java.util.Map$Entry 

 

// primitive type

name = int.class.getName();      // int

name = Integer.class.getName();  // java.lang.Integer

name = Integer.TYPE.getName();    // int

// array

name = boolean[].class.getName();   // [Z

name = byte[].class.getName();      // [B

name = char[].class.getName();      // [C

name = short[].class.getName();     // [S

name = int[].class.getName();       // [I

name = long[].class.getName();      // [J

name = float[].class.getName();     // [F

name = double[].class.getName();    // [D

name = String[].class.getName();    // [Ljava.lang.String;

name = int[][].class.getName();     // [[I

 

// void

cls = Void.TYPE;

name = cls.getName();               // void

// CanonicalName

name = cls.getCanonicalName();               // java.lang.String

name = cls.getCanonicalName();               // java.util.Map.Entry

name = boolean[].class.getCanonicalName(); // boolean[]

참조 URL : http://java.sun.com/developer/technicalArticles/ALT/Reflection/index.html

Posted by 파이팅야
,

system.properties 값

풀그림 2008. 8. 22. 14:14

key

value

java.runtime.name

Java(TM) SE Runtime Environment

sun.boot.library.path

C:\Program Files\Java\jre1.6.0_01\bin

java.vm.version

1.6.0_01-b06

java.vm.vendor

Sun Microsystems Inc.

java.vendor.url

http://java.sun.com/

path.separator

;

java.vm.name

Java HotSpot(TM) Client VM

file.encoding.pkg

sun.io

sun.java.launcher

SUN_STANDARD

user.country

KR

sun.os.patch.level

Service Pack 2

java.vm.specification.name

Java Virtual Machine Specification

user.dir

D:\Dev\eclipse\workspace\icafe-middlewd

java.runtime.version

1.6.0_01-b06

java.awt.graphicsenv

sun.awt.Win32GraphicsEnvironment

java.endorsed.dirs

C:\Program Files\Java\jre1.6.0_01\lib\endorsed

os.arch

x86

java.io.tmpdir

C:\DOCUME~1\FIGHTI~1\LOCALS~1\Temp\

line.separator

 

java.vm.specification.vendor

Sun Microsystems Inc.

user.variant

 

os.name

Windows 2003

sun.jnu.encoding

MS949

java.library.path

C:\Program Files\Java\jre1.6.0_01\bin;.;C:\WINDOWS\Sun\Java\bin;

java.specification.name

Java Platform API Specification

java.class.version

50

sun.management.compiler

HotSpot Client Compiler

os.version

5.2

user.home

C:\Documents and Settings\fightingaf

user.timezone

 

java.awt.printerjob

sun.awt.windows.WPrinterJob

file.encoding

MS949

java.specification.version

1.6

java.class.path

D:\Dev\eclipse\workspace\icafe-middlewd\bin;D:\Dev\eclipse\workspace\icafe-middlewd\conf;D:\Dev\eclipse\workspace\icafe-middlewd\lib\activation-1.1.jar;

user.name

fightingaf

java.vm.specification.version

1

java.home

C:\Program Files\Java\jre1.6.0_01

sun.arch.data.model

32

user.language

ko

java.specification.vendor

Sun Microsystems Inc.

awt.toolkit

sun.awt.windows.WToolkit

java.vm.info

mixed mode, sharing

java.version

1.6.0_01

java.ext.dirs

C:\Program Files\Java\jre1.6.0_01\lib\ext;C:\WINDOWS\Sun\Java\lib\ext

sun.boot.class.path

C:\Program Files\Java\jre1.6.0_01\lib\resources.jar;

C:\Program Files\Java\jre1.6.0_01\lib\rt.jar;C:\Program Files\Java\jre1.6.0_01\lib\sunrsasign.jar;C:\Program Files\Java\jre1.6.0_01\lib\jsse.jar;C:\Program Files\Java\jre1.6.0_01\lib\jce.jar;C:\Program Files\Java\jre1.6.0_01\lib\charsets.jar;C:\Program Files\Java\jre1.6.0_01\classes

java.vendor

Sun Microsystems Inc.

file.separator

\

java.vendor.url.bug

http://java.sun.com/cgi-bin/bugreport.cgi

sun.io.unicode.encoding

UnicodeLittle

sun.cpu.endian

little

sun.desktop

windows

sun.cpu.isalist

 


Properties prop = System.getProperties();

Enumeration propKeys = prop.keys();

while(propKeys.hasMoreElements()) {

       Object obj = propKeys.nextElement();

       System.out.println(obj + " => [" + prop.getProperty(obj.toString()) + "]");

}

Posted by 파이팅야
,

java xml jaxp sample

풀그림 2008. 8. 19. 19:05

JAXP (Java API for XML Processing)을 사용하는 간단한 예제들을 볼수 있음

== XML 데이터 == (XSD나 DTD는 안넣어놨음. )
<?xml version="1.0" encoding="utf-8"?>
<CHESSBOARDS>
 <CHESSBOARD>
  <WHITEPIECES>
   <KING><POSITION COLUMN="G" ROW="1"/></KING>
   <BISHOP><POSITION COLUMN="D" ROW="6"/></BISHOP>
     <ROOK><POSITION COLUMN="E" ROW="1"/></ROOK>
     <PAWN><POSITION COLUMN="A" ROW="4"/></PAWN>
     <PAWN><POSITION COLUMN="B" ROW="3"/></PAWN>
     <PAWN><POSITION COLUMN="C" ROW="2"/></PAWN>
     <PAWN><POSITION COLUMN="F" ROW="2"/></PAWN>
     <PAWN><POSITION COLUMN="G" ROW="2"/></PAWN>
     <PAWN><POSITION COLUMN="H" ROW="5"/></PAWN>
  </WHITEPIECES>
  <BLACKPIECES>
     <KING><POSITION COLUMN="B" ROW="6"/></KING>
     <QUEEN><POSITION COLUMN="A" ROW="7"/></QUEEN>
     <PAWN><POSITION COLUMN="A" ROW="5"/></PAWN>
     <PAWN><POSITION COLUMN="D" ROW="4"/></PAWN>
   </BLACKPIECES>
  </CHESSBOARD>
</CHESSBOARDS>

import org.xml.sax.*;
import javax.xml.parsers.*;
import java.io.*;
public class ChessboardSAXPrinter {
 private SAXParser parser;
 private static PrintStream out;
 
 @SuppressWarnings("deprecation")
 public class ChessboardHandler extends HandlerBase
 {
  private boolean whitePiece= false;
 
  @SuppressWarnings("deprecation")
  public void startElement(String name, AttributeList attrs)
  {
   if(name.equals("WHITEPIECES"))
   {
    whitePiece=true;
   }
   else if(name.equals("BLACKPIECES"))
   {
    whitePiece=false;
   }
   else if(name.equals("KING") || name.equals("QUEEN") || name.equals("BISHOP")|| name.equals("ROOK")
     || name.equals("ROOK") || name.equals("KNIGHT") || name.equals("PAWN"))
   {
    System.out.print((whitePiece ? "White" : "Black") + " " + name.toLowerCase() + ": ");   
   }
   else if(name.equals("POSITION"))
   {
    if(attrs!=null)
    {
     System.out.print(attrs.getValue("COLUMN"));
     System.out.println(attrs.getValue("ROW"));
    }  
   }
   return;   
  }
 }
 public ChessboardSAXPrinter(boolean validating) throws Exception
 {
  SAXParserFactory factory=SAXParserFactory.newInstance();
  factory.setValidating(validating);
  parser=factory.newSAXParser();
 
  return;
 }
 
 public void print(String fileName, PrintStream out) throws SAXException, IOException
 {
  ChessboardHandler dh=new ChessboardHandler();
 
  parser.parse(fileName, dh);
  return;
 }
 
 public static void main(String[] args)
 {
  boolean validating=true;
  int r,n;
  r=1;
  n=1;
  for(int k=0; k < r; k++)
  {
   try
   {
    ChessboardSAXPrinter saxPrinter=new ChessboardSAXPrinter(validating);
    long time = System.currentTimeMillis();
      for (int i = 0; i < n; i++) {
        // n: number of document processed per run
       //saxPrinter.print(args[0], out);
       saxPrinter.print(args[0], out);
      }
     
      // print out the average time (s)
      // to process a document during the current run
      System.err.print(((double) (System.currentTimeMillis()- time)) / 1000 / n + "\t");
   }
   catch(SAXException ex)
   {
    System.out.println(ex.getMessage());
   }
   catch(IOException iex)
   {
    System.out.println(iex.getMessage());
   }
   catch(Exception uex)
   {
    System.out.println(uex.getMessage());
   }
  }
 }
}


----- DOM으로 처리한 경우 ----------

import org.w3c.dom.*;
import org.xml.sax.*;
import javax.xml.parsers.*;
import java.io.*;

public class ChessboardDOMPrinter {
 private DocumentBuilder builder;
 boolean validate;
 public ChessboardDOMPrinter(boolean _validate)
 {
  validate=_validate;
 }
 
 public void print(String fileName, PrintStream out) throws SAXException, IOException, ParserConfigurationException
 { 
  DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
     dbf.setValidating(validate);
     dbf.setNamespaceAware(true);
     dbf.setIgnoringElementContentWhitespace(true);
 
     DocumentBuilder builder = dbf.newDocumentBuilder();
    
  Document document = builder.parse(fileName);
  NodeList nodes_i = document.getDocumentElement().getChildNodes();
 
  for(int i=0; i< nodes_i.getLength(); i++)
  {
   Node node_i=nodes_i.item(i);
   if(node_i.getNodeType()==Node.ELEMENT_NODE && ((Element)node_i).getTagName().equals("CHESSBOARD"))
   {
    Element chessboard=(Element) node_i;
    NodeList nodes_j=chessboard.getChildNodes();
   
    for(int j=0; j< nodes_j.getLength(); j++)
    {
     Node node_j = nodes_j.item(j);
     if (node_j.getNodeType() == Node.ELEMENT_NODE) {
      Element pieces = (Element) node_j;
      NodeList nodes_k = pieces.getChildNodes();
      for (int k = 0; k < nodes_k.getLength(); k++) {
       Node node_k = nodes_k.item(k);
       if (node_k.getNodeType() == Node.ELEMENT_NODE) {
        Element piece = (Element) node_k;
        Element position = (Element) piece.getChildNodes().item(0);
        System.out.println((pieces.getTagName()
                            .equals("WHITEPIECES")
                          ? "White " : "Black ")
                         + piece.getTagName().toLowerCase()
                         + ": "
                         + position.getAttribute("COLUMN")
                         + position.getAttribute("ROW"));       
       }
      }
     }
    }
   }
  }
 
  return;
 }
 
 public void print2(String fileName, PrintStream out) throws SAXException, IOException, ParserConfigurationException {
  DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
     dbf.setValidating(validate);
     dbf.setNamespaceAware(true);
     dbf.setIgnoringElementContentWhitespace(true);
 
     DocumentBuilder builder = dbf.newDocumentBuilder();
    
  Document document = builder.parse(fileName);
  NodeList positions = document.getElementsByTagName("POSITION");
  for (int i = 0; i < positions.getLength(); i++) {
   Element position = (Element) positions.item(i);
   Element piece = (Element) position.getParentNode();
   Element pieces = (Element) piece.getParentNode();
   out.println( (pieces.getTagName().equals("WHITEPIECES") ? "White " : "Black ")
      + piece.getTagName().toLowerCase() + ": "
      + position.getAttribute("COLUMN")
      + position.getAttribute("ROW"));
  }
  return;
 }
 
 public static void main(String[] args)
 {
  PrintStream out=System.out;
  try{
   ChessboardDOMPrinter domPrinter=new ChessboardDOMPrinter(false);
   domPrinter.print2("E:\\DEV_STUDY\\WebCrawler\\WebCrawler\\chessboard.xml", out);
  }
  catch(SAXException sex){
   System.err.println(sex.getMessage());
  }
  catch(IOException iex){
   System.err.println(iex.getMessage());
  }
  catch(ParserConfigurationException pcex)
  {
   System.err.println(pcex.getMessage());
  }
  catch(Exception ex){
   System.err.println(ex.getMessage());
  }
 
 }
}

====== XPATH 관련 ==========
// 추가
import javax.xml.transform.*;
import javax.xml.xpath.*;
.............

public void print3(String fileName, PrintStream out) throws TransformerException,SAXException, IOException, ParserConfigurationException
 {
  DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
     dbf.setValidating(validate);
     dbf.setNamespaceAware(true);
     dbf.setIgnoringElementContentWhitespace(true);
    
     DocumentBuilder builder = dbf.newDocumentBuilder();
     Document document = builder.parse(fileName);

     NodeList allPieces=XPathAPI.selectNodeList(document.getDocumentElement(), "//*[self::WHITEPIECES or self::BLACKPIECES]/*");
    
     for(int i=0; i < allPieces.getLength(); i++)
     {
      Element piece=(Element)allPieces.item(i);
      Element pieces=(Element)piece.getParentNode();
      Element position = (Element) piece.getChildNodes().item(0);
      System.out.println((pieces.getTagName().equals("WHITEPIECES")? "White ":"Black ")+piece.getTagName().toLowerCase()+": " + position.getAttribute("COLUMN")+position.getAttribute("ROW"));    
     }
    
     return;
 }

출처 : http://ausgang.egloos.com/1998938
참조 : http://java.sun.com/developer/technicalArticles/xml/JavaTechandXML/#code14
 http://www.java2s.com/
 http://www.java2s.com/Code/JavaAPI/javax.xml.parsers/DocumentBuilderFactorynewDocumentBuilder.htm

Posted by 파이팅야
,