달력

32024  이전 다음

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31

Java WebService 를 이용할때 Axis 나 CXF 를 자주 이용하게 되는데,

프로젝트 셋팅할 때 Logging 설정을 미리 해 놓으면 웹서비스의 요청/응답에 대한 XML 흐름을 log4j 등을 

이용하여 볼 수 있지만, 만약 못해놓은 상태에서 급하게 봐야 한다면 다음과 같이 설정 하고

Fiddler2 를 이용하면 요청/응답의 XML 흐름을 볼 수 있다.


Main 메소드 또는 웹서비스를 호출하는 수정 가능한 클래스에 프록시 Property 설정 추가.

System.setProperty("http.proxyHost", "localhost");

System.setProperty("http.proxyPort", "8888");


그리고 Fiddler2 를 띠워보면 아래와 같이 나온다.

XML 이 깨지면 Notepad++ 같은 툴을 이용하던, Eclipse, Visual studio 등을 이용하여 Formatting 하여 이쁘게 보면 됨.


Posted by tornado
|

[출처] http://www.rgagnon.com/javadetails/java-0490.html



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

For a single file, a thread is launched to check the lastModified value and compare it with the previous value.

import java.util.*;
import java.io.*;

public abstract class FileWatcher extends TimerTask {
  private long timeStamp;
  private File file;

  public FileWatcher( File file ) {
    this.file = file;
    this.timeStamp = file.lastModified();
  }

  public final void run() {
    long timeStamp = file.lastModified();

    if( this.timeStamp != timeStamp ) {
      this.timeStamp = timeStamp;
      onChange(file);
    }
  }

  protected abstract void onChange( File file );
}

import java.util.*;
import java.io.*;

public class FileWatcherTest {
  public static void main(String args[]) {
    // monitor a single file
    TimerTask task = new FileWatcher( new File("c:/temp/text.txt") ) {
      protected void onChange( File file ) {
        // here we code the action on a change
        System.out.println( "File "+ file.getName() +" have change !" );
      }
    };

    Timer timer = new Timer();
    // repeat the check every second
    timer.schedule( task , new Date(), 1000 );
  }
}

For a directory, a thread is launched where we keep the Files in a Map, we check the current lastModifed value of a given file and compare it with the value stored in the Map. Also a special check is made to detect if a File is deleted.

import java.util.*;
import java.io.*;

public abstract class DirWatcher extends TimerTask {
  private String path;
  private File filesArray [];
  private HashMap dir = new HashMap();
  private DirFilterWatcher dfw;

  public DirWatcher(String path) {
    this(path, "");
  }

  public DirWatcher(String path, String filter) {
    this.path = path;
    dfw = new DirFilterWatcher(filter);
    filesArray = new File(path).listFiles(dfw);

    // transfer to the hashmap be used a reference and keep the
    // lastModfied value
    for(int i = 0; i < filesArray.length; i++) {
       dir.put(filesArray[i], new Long(filesArray[i].lastModified()));
    }
  }

  public final void run() {
    HashSet checkedFiles = new HashSet();
    filesArray = new File(path).listFiles(dfw);

    // scan the files and check for modification/addition
    for(int i = 0; i < filesArray.length; i++) {
      Long current = (Long)dir.get(filesArray[i]);
      checkedFiles.add(filesArray[i]);
      if (current == null) {
        // new file
        dir.put(filesArray[i], new Long(filesArray[i].lastModified()));
        onChange(filesArray[i], "add");
      }
      else if (current.longValue() != filesArray[i].lastModified()){
        // modified file
        dir.put(filesArray[i], new Long(filesArray[i].lastModified()));
        onChange(filesArray[i], "modify");
      }
    }

    // now check for deleted files
    Set ref = ((HashMap)dir.clone()).keySet();
    ref.removeAll((Set)checkedFiles);
    Iterator it = ref.iterator();
    while (it.hasNext()) {
      File deletedFile = (File)it.next();
      dir.remove(deletedFile);
      onChange(deletedFile, "delete");
    }
  }

  protected abstract void onChange( File file, String action );
}

import java.io.*;

public class DirFilterWatcher implements FileFilter {
  private String filter;

  public DirFilterWatcher() {
    this.filter = "";
  }

  public DirFilterWatcher(String filter) {
    this.filter = filter;
  }
  
  public boolean accept(File file) {
    if ("".equals(filter)) {
      return true;
    }
    return (file.getName().endsWith(filter));
  }
}

The example watches the c:/temp folder for any activities on any *.txt files.
import java.util.*;
import java.io.*;

public class DirWatcherTest {
  public static void main(String args[]) {
    TimerTask task = new DirWatcher("c:/temp", "txt" ) {
      protected void onChange( File file, String action ) {
        // here we code the action on a change
        System.out.println
           ( "File "+ file.getName() +" action: " + action );
      }
    };

    Timer timer = new Timer();
    timer.schedule( task , new Date(), 1000 );
  }
}

Posted by tornado
|
[link] http://java.decompiler.free.fr/

자바 디컴파일러.

GUI, Eclipse Plugin 을 제공.


Posted by tornado
|
[link] http://ehcache.org/

자바로 만들어진 캐시 라이브러리, 

간단한 설정으로 캐시를 사용할 수 있음.

로깅시 slf4j 가 필요함. -->  http://www.slf4j.org/download.html 에서 받으면 된다.

참고로  ServletFilter ZipStream 도 있음. 

 

Posted by tornado
|
대칭암호화알고리즘 소개 및 DES, Blowfish샘플코드
 
대칭암호화알고리즘이 무엇인지 간략히 소개하고, JCA-JCE및 간단한 두가지 알고리즘을 획득하여 암호화 하는 방법을 소개하고자 한다. ( 2003/06/23 ) 241
Written by ienvyou - 최지웅
1 of 1
 


오랫만이 쓰는 아티클인것 같다. 여기서는 우선 맛보기로 간단하게 암호화에 대한 내용 및
대칭암호방법에 대한 내용을 설명하도록 하겠다.

요즘 같이 인터넷이 보편화되고 개방형 시스템들이 존재하게 되면서 개인의 정보및
비밀에 대한 정보보호가 굉장한 이슈로 대두되어지고 있다.

우리가 사용하게 되는 자바는 java.security및 javax.crypto패키지를 통하여 암호를 쉽게
사용할 수 있는 기능을 제공한다. 
만약 당신이 어떠한 데이터를 다른 사람에게 전달하던 도중 그 메시지를 다른 사람이 보게
된다면? 그게 만약 신용카드나 결제정보, 중요한 문서일수도 있는 것이다.
그러한 것들에 대한 침입위험으로부터 정보가 보호되어지기 위해서는 무언가의 수단이
필요하게 될것이다. 자바측에서도 코드정책에 대한 보안이 필요하겠지만 우선은
기본적인 사항만을 여기서 논하겠다.

기본적인 자바의 코드보안정책으로서 final class라든지, 패키지보안, jar파일 sign, 
serialization부분의 transient등에 대한 설명은 여기서 논의하지 않도록 하겠다.

▶ 대칭암호화 알고리즘

기본적으로 이 글을 읽는 사람이라면 학교다닐때 한번쯤은 친한 친구와의 의사소통이나
대화를 하는데에 있어서 남들이 알지 못하는 방법으로 대화를 하고 싶었던 적이 있을것이다.
(놀새~만 그랬나?) 
가령 내가 고등학교를 다닐때 친구와 이야기를 할때 모든 단어를 표현하고자 할때
중성을 뒤로 빼서 그것을 이용하여 한글자를 더 만들고 거기에 ㅅ받침을 이용하여 의사소통을
한적도 있었다. (예: 비둘기 --> 비시 두술 기시) 처럼말이다..

위의 예를 든것도 일종의 암호화의 한 방법이라고 할 수 있는데 일반 사람들이 듣기에는
어떠한 논리에 의하여 말을 하는 것인지 처음에는 알아듣지를 못하다가 단어를 적어주거나
한참후에야 그러한 원리가 있었음을 알게 된다.

위와 같이 암호화와 같은 정보를 이용하여 다시 복호화 할수 있는 데 좀 더 쉽게 예를 들어보자면
다음과 같을 수 있다.


A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
|                               
D E F G H I J K L M N O P Q R S T U V W X Y Z A B C 

각각의 문자를 3자리씩 뒤로 옮겨진 것 처럼 보여질 수 있는데  만약 HI, CAROUSER라는 단어는
KL, FDURXVIU 라는 단어로 바뀌게 되면 같은 패턴에 의하여 다시 복호화 되어질수 있는 
특징을 가지고 있다.
즉 메시지를 암호화와 복호화를 하기 위해서는 알고리즘과 키가 정의되어야 한다.

▶ 대칭암호화 알고리즘의 종류
  1. DES & TripleDES : DES(Data Encryption Standard)는 "Lucifer"라는 이름의 IBM에서 최초개발되었다. 또한 미국에서 최초 국가표준이 되었으며, 56비트키를 가지고 암복호화를 사용했다. 하지만 컴퓨터가 발전을 함에 있어서 56비트키의 경우 어느정도의 시간만 확보가 된다면 풀어낼수 있기 때문에 좀더 완벽한 보안을 위하여 Triple DES가 고안되어졌다.
  2. TripleDES : 이는 기존의 DES암호화 알고리즘방식을 다른키에 세번 적용시킨것이며, 첫번째 암호화과정, 두번째 복호화과정, 세번째는 또 다른 암호화 과정을 거치도록 하고 있다. 그래서 이름이 DESede(DES encryption, decryption, encryption)이 되었으며, 각각의 과정에 따라 56비트의 배수로 암호화 복잡도가 증가되게 되어있다.
  3. Blowfish : 1993년 Bruce Schneier에 의해 고안된 블록암호로서 DES보다 빠르고 안전한 기법을 제공한다. 최대 키의 비트수를 448비트까지 확장할수있다는 특징을 가지고 있다.
  4. RC4 : "Civest's Code 4"를 의미하며 1987년 RSA Data Security에서 발표되었다. 보통 이기법으로 TCP/IP연결을 안전하게 하는 SSL을 구현하는 데 많이 쓰인다(키의 길이 40비트 또는 128비트)
위과 같이 대칭암호화의 경우는 모든 알고리즘이 같은 방식으로 동작을 하게 되는데 문제는 메시지를 보내고 받는 사람이 같은 키를 가지게 되며, 중간에 그 키가 노출이 되었을 땐 이미 우리의 메시지는 남에게 읽힐수 있는 문제점을 가지고 된다. 즉 비밀키가 노출되게 되면 암호화된 메시지또한 동시에 노출될 수 있다는 단점을 가지고 있다. ▶ DES방식의 샘플코드 우리는 여기서 간단하게 DES방식을 이용하여 암복호화 프로그램을 하나 예제로 보도록 한다. 기본적으로 자바측에서 제공할수 있는 암호에 관련된 패키지는 JCA(java cryptograhpy arch.)와 JCE(java cryptography extension)을 사용할 수 있다. JCA는 기본적으로 Java2 Runtime Environment의 일부이며, JCA는 그것의 확장패키지이다. 기본적인 JCA에서는 전자서명, 메시지 다이제스트, 키생성기등의 클래스를 가지고 있으며 그러한 기본적인 클래스들을 우리가 사용하고자 했을 때 new에 의한 생성이 아니라 이미 아키텍쳐가 가지고 있는 암호화 기법에 의하여 factory형태의 클래스에게 생성을 요청하여야 한다. 기본적인JCE같은 경우 당신이 JDK1.3.1을 사용한다면 패키지를 썬에서 다운로드 받을수있으며 jdk1.4버젼을 사용한다면 이미 포함되어져 있으니 그냥 코딩을 해도 무방할 듯 하다. 우선 아래의 코드를 보기 전에 중요한 클래스를 살펴보아야 할 필요가 있는데 그것은 바로 javax.crypto.Cipher라는 클래스로서 데이터를 암호화하고 복호화하는데 사용되는 기본적인 엔진부분이다. 몇가지의 메소드만을 살펴보겠는데 우선 getIntance(), init(), update(), doFinal()로서 암호화 알고리즘의 생성, Cipher인스턴스의 초기화, 암복호화, 암호화된 배열을 획득을 하는 메소드들이다. 또한 javax.crypto.KeyGenerator클래스는 암호화와 복호화에 필요한 키를 생성해내는 데 쓰이며 getInstance(), init(), generateKey()의 메소드 정도면 Cipher에 필요한 키를 만들어낼 수 있다.

import java.security.*;
import javax.crypto.*;

public class SimpleExample {
    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);
    }
};
위의 코드로서 간단하게 살펴볼 수 있는데, 출력되는 생성되는 키에 따라 결정되므로 매번 다른 결과의 암호화된 문자열을 볼 수 있는 특징을 가지고 있다. Blowfish의 대칭암호화 기법또한 같은 방법에 의하여 만들어낼 수 있는데 단순히 위의 코드상에서의 변화는 KeyGenerator에서 "Blowfish"와 Cipher에서 인스턴스를 얻어낼때 단순히 "Blowfish/ECB/PKCS5Padding"을 이용하여 처리하면 128비트의 키를 이용한 암복호화를 테스트해볼 수 있다. ▶ Conclusion 기본적으로 가장 기본적인 암호화 방법을 살펴보았으며 기본적인 대칭알고리즘의 개념이 무엇인지만 알고 있어도 놀새~가 여러분들을 보는 기준에서 별 무리가 없어 보일듯 하다. 다음에 쓸 것으로는 유닉스 패스워드의 형태로 많이 쓰이는 메시지 다이제스트방법을 간단한 자바코딩을 이용하여 처리해보겠다. 위의 경우 웹사이트를 직접 만들었을 경우 사용자들에 대한 user id, password를 데이터베이스에 직접저장하는 것이 아니라 universal key의 개념으로 변환하여 처리하는 샘플을 보도록 하겠다..

'JAVA > Core Java' 카테고리의 다른 글

자바 디컴파일러...  (0) 2011.04.26
[link] EHCache --> Java Cache library  (0) 2011.03.31
jdbc mysql named instance 접속  (0) 2009.02.20
[자바] 아주 쉬운 XML 생성 도구  (0) 2008.12.01
[JAVA] SHA-1 암호화 하기  (0) 2008.09.23
Posted by tornado
|

출처 : http://www.bluestudios.co.uk/blog/?p=237


Recently I came across a small problem with setting up Oracle UCM 10gR3 on a MSSQL2005 instance.
Using the net.sourceforge.jtds.jdbc.Driver class.

The DBAs had setup a clustered SQL environment and had given me MSSQLDB0001\ARCHIVETR.
ARCHIVETR being the SQL instance which I needed to install the UCM to.

For future reference all you need to do is append ‘;instance=ARCHIVETR’ to the connection string like the following:

jdbc:jtds:sqlserver://<SQLServer>:<PORT>/<DBName>;instance=<SQLInstanceName>

Example:
jdbc:jtds:sqlserver://MSSQLDB0001:1433/UCM;instance=ARCHIVETR

Posted by tornado
|
출처 : http://www.ociweb.com/mark/programming/WAX.html

삽질 끝????

Introduction

What's the best way to read a large XML document? Of course you'd use a SAX parser or a pull parser. What's the best way to write a large XML document? Building a DOM structure to describe a large XML document won't work because it won't fit in memory. Even if it did, it's not a simple API to use. There hasn't been a solution that is simple and memory efficient until now.

Writing API for XML (WAX) is a free, open-source, library for writing XML documents. I created it because I got an OutOfMemoryError while trying to output a large XML document from an application I wrote using JDOM, another Java-based XML library. I searched for other libraries that could write large XML documents but couldn't find any that were as simple to use as I thought they should be.

WAX is released under the LGPL with the intention of making its use unencumbered. It is well-tested and ready for production use. The WAX home page is at http://www.ociweb.com/wax/. Java and Ruby versions are available now. The Java version of WAX can be downloaded from Google Code at http://code.google.com/p/waxy/. For information about the Ruby version, click here. Ports for other programming languages will follow.

WAX has the following characteristics:

  • focuses on writing XML, not reading it
  • requires less code than other approaches
  • uses less memory than other approaches
    (because it outputs XML as each method is called rather than
    storing it in a DOM-like structure and outputting it later)
  • doesn't depend on any Java classes other than standard JDK classes
  • is a small library (around 16K)
  • writes all XML node types
  • always outputs well-formed XML or throws an exception unless running in "trust me" mode
  • provides extensive error checking
  • automatically escapes special characters in text and attribute values (unless "unescaped" methods are used)
  • allows most error checking to be turned off for performance
  • knows how to associate DTDs, XML Schemas and XSLT stylesheets with the XML it outputs
  • is well-suited for writing XML request and response messages for REST-based and SOAP-based services

WAX Tutorial

This section provides many examples of using WAX. Each code snippet is followed by the output it produces.

When the no-arg WAX constructor is used, XML is written to standard output. There are also WAX constructors that take a java.io.OutputStream or a java.io.Writer object.

Here's a simple example where only a root element is written:

WAX wax = new WAX();
wax.start("car").close();
<car/>

After a WAX object is closed, a new one must be created in order to write more XML. In the examples that follow, assume that has been done.

Let's write a root element with some text inside:

wax.start("car").text("Prius").end().close();
<car>Prius</car>

The default indentation used is two spaces. The end method terminates the element that is started by the start method. In this case it's not necessary to call end because the close method terminates all unterminated elements.

Let's put the text inside a child element:

wax.start("car").start("model").text("Prius").close();
<car>
<model>Prius</model>
</car>

Let's do the same with the child convenience method: which is equivalent to calling start, text and end.

wax.start("car").child("model", "Prius").close();
<car>
<model>Prius</model>
</car>

Let's put text containing all the special XML characters in a CDATA section:

wax.start("car").start("model").cdata("1<2>3&4'5\";6").close();
<car>
<model>
<![CDATA[1<2>3&4'5"6]]>
</model>
</car>

Let's output the XML without indentation, on a single line:

wax.noIndentsOrLineSeparators();
wax.start("car").child("model", "Prius").close();
<car><model>Prius</model></car>

Let's indent the XML with four spaces instead of the default of two:

wax.setIndent("    "); // can also call setIndent(4)
wax.start("car").child("model", "Prius").close();
<car>
<model>Prius</model>
</car>

Let's add an attribute:

wax.start("car").attr("year", 2008).child("model", "Prius").close();
<car year="2008">
<model>Prius</model>
</car>

Attributes must be specified before any content for their element is specified. For example, calling start, attr and text is valid, but calling start, text and attr is not. If this rule is violated then an IllegalStateException is thrown.

Let's add an XML declaration:

WAX wax = new WAX(Version.V1_0); // Version is an enum
wax.start("car").attr("year", 2008)
.child("model", "Prius").close();
<?xml version="1.0" encoding="UTF-8"?>
<car year="2008">
<model>Prius</model>
</car>

Let's add a comment:

wax.comment("This is a hybrid car.")
.start("car").child("model", "Prius").close();
<!-- This is a hybrid car. -->
<car>
<model>Prius</model>
</car>

Let's add a processing instruction:

wax.processingInstruction("target", "data")
.start("car").attr("year", 2008)
.child("model", "Prius").close();
<?target data?>
<car year="2008">
<model>Prius</model>
</car>

Let's associate an XSLT stylesheet with the XML: The xslt method is a convenience method for adding this commonly used processing instruction.

wax.xslt("car.xslt")
.start("car").attr("year", 2008)
.child("model", "Prius").close();
<?xml-stylesheet type="text/xsl" href="car.xslt"?>
<car year="2008">
<model>Prius</model>
</car>

Let's associate a default namespace with the XML:

wax.start("car").attr("year", 2008)
.defaultNamespace("http://www.ociweb.com/cars")
.child("model", "Prius").close();
<car year="2008"
xmlns="http://www.ociweb.com/cars">
<model>Prius</model>
</car>

Let's associate a non-default namespace with the XML:

String prefix = "c";
wax.start(prefix, "car").attr("year", 2008)
.namespace(prefix, "http://www.ociweb.com/cars")
.child(prefix, "model", "Prius").close();
<c:car year="2008"
xmlns:c="http://www.ociweb.com/cars">
<c:model>Prius</c:model>
</c:car>

Like attributes, namespaces must be specified before any content for their element is specified. If this rule is violated then an IllegalStateException is thrown.

Let's associate an XML Schema with the XML:

wax.start("car").attr("year", 2008)
.defaultNamespace("http://www.ociweb.com/cars", "car.xsd")
.child("model", "Prius").close();
<car year="2008"
xmlns="http://www.ociweb.com/cars"
xmlns:xsi="http://www.w3.org/1999/XMLSchema-instance"
xsi:schemaLocation="http://www.ociweb.com/cars car.xsd">
<model>Prius</model>
</car>

Let's associate multiple XML Schemas with the XML:

wax.start("car").attr("year", 2008)
.defaultNamespace("http://www.ociweb.com/cars", "car.xsd")
.namespace("m", "http://www.ociweb.com/model", "model.xsd")
.child("m", "model", "Prius").close();
<car year="2008"
xmlns="http://www.ociweb.com/cars"
xmlns:m="http://www.ociweb.com/model"
xmlns:xsi="http://www.w3.org/1999/XMLSchema-instance"
xsi:schemaLocation="http://www.ociweb.com/cars car.xsd
http://www.ociweb.com/model model.xsd">
<m:model>Prius</m:model>
</car>

Let's associate a DTD with the XML:

wax.dtd("car.dtd")
.start("car").attr("year", 2008)
.child("model", "Prius").close();
<!DOCTYPE car SYSTEM "car.dtd">
<car year="2008">
<model>Prius</model>
</car>

Let's add and use entity definitions:

String url = "http://www.ociweb.com/xml/";
wax.entityDef("oci", "Object Computing, Inc.")
.externalEntityDef("moreData", url + "moreData.xml")
.start("root")
.unescapedText("The author works at &oci; in St. Louis, Missouri.",
true) // avoiding escaping for entity reference
.unescapedText("&moreData;", true)
.close();
<!DOCTYPE root [
<!ENTITY oci "Object Computing, Inc.">
<!ENTITY moreData SYSTEM "http://www.ociweb.com/xml/moreData.xml">
]>
<root>
The author works at &oci; in St. Louis, Missouri.
&moreData;
</root>

A common usage pattern is to pass a WAX object to a method of model objects that use it to write their XML representation. For example, a Car class could have the following method.

public void toXML(WAX wax) {
wax.start("car")
.attr("year", year)
.child("make", make)
.child("model", model)
.end();
}

An example of the XML this would produce follows:

<car year="2008">
<make>Toyota</make>
<model>Prius</model>
</car>

A Person class whose objects hold a reference to an Address object could have the following method.

public void toXML(WAX wax) {
wax.start("person")
.attr("birthdate", birthdate)
.child("name", name);
address.toXML(wax);
wax.end();
}

The Address class could have the following method.

public void toXML(WAX wax) {
wax.start("address")
.child("street", street);
.child("city", city);
.child("state", state);
.child("zip", zip);
.end();
}

An example of the XML this would produce follows:

<person birthdate="4/16/1961">
<name>R. Mark Volkmann</name>
<address>
<street>123 Some Street</street>
<city>Some City</city>
<state>MO</state>
<zip>12345</zip>
</address>
</person>

Posted by tornado
|

import java.io.*;
import java.security.*;
import sun.misc.*;

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

  byte[] txtByte = "테스트테스트".getBytes();

  MessageDigest md = MessageDigest.getInstance("SHA-1");

  md.update(txtByte);

  byte[] digest = md.digest();

  BASE64Encoder encoder = new BASE64Encoder();

  String base64 = encoder.encode(digest);

        // should be 20 bytes, 160 bits long
        System.out.println( digest.length );

        // dump out the hash
        for ( byte b : digest )
        {
            System.out.print( Integer.toHexString( b & 0xff )  );
        }

  //String result = new String(digest.toCha);

  System.out.println("\r\n" + toString(digest, 0, digest.length));

  //System.out.println("hexaString : " + HexString.bufferToHex(md.digest()));

 }

 private static final char[] HEX_DIGITS = "0123456789abcdef".toCharArray();


 public static final String toString(byte[] ba, int offset, int length) {
      char[] buf = new char[length * 2];
      for (int i = 0, j = 0, k; i < length; ) {
         k = ba[offset + i++];
         buf[j++] = HEX_DIGITS[(k >>> 4) & 0x0F];
         buf[j++] = HEX_DIGITS[ k        & 0x0F];
      }
      return new String(buf);
  }

}
Posted by tornado
|

출처 : http://javaexchange.com/aboutRandomGUID.html

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


Random GUID generator in Java


Download RandomGUID. -- generates truly random GUIDs in the standard format.


RandomGUID.java


/* * RandomGUID * @version 1.2.1 11/05/02 * @author Marc A. Mnich * * From www.JavaExchange.com, Open Software licensing * * 11/05/02 -- Performance enhancement from Mike Dubman. * Moved InetAddr.getLocal to static block. Mike has measured * a 10 fold improvement in run time. * 01/29/02 -- Bug fix: Improper seeding of nonsecure Random object * caused duplicate GUIDs to be produced. Random object * is now only created once per JVM. * 01/19/02 -- Modified random seeding and added new constructor * to allow secure random feature. * 01/14/02 -- Added random function seeding with JVM run time * */ import java.net.*; import java.util.*; import java.security.*; /* * In the multitude of java GUID generators, I found none that * guaranteed randomness. GUIDs are guaranteed to be globally unique * by using ethernet MACs, IP addresses, time elements, and sequential * numbers. GUIDs are not expected to be random and most often are * easy/possible to guess given a sample from a given generator. * SQL Server, for example generates GUID that are unique but * sequencial within a given instance. * * GUIDs can be used as security devices to hide things such as * files within a filesystem where listings are unavailable (e.g. files * that are served up from a Web server with indexing turned off). * This may be desireable in cases where standard authentication is not * appropriate. In this scenario, the RandomGUIDs are used as directories. * Another example is the use of GUIDs for primary keys in a database * where you want to ensure that the keys are secret. Random GUIDs can * then be used in a URL to prevent hackers (or users) from accessing * records by guessing or simply by incrementing sequential numbers. * * There are many other possiblities of using GUIDs in the realm of * security and encryption where the element of randomness is important. * This class was written for these purposes but can also be used as a * general purpose GUID generator as well. * * RandomGUID generates truly random GUIDs by using the system's * IP address (name/IP), system time in milliseconds (as an integer), * and a very large random number joined together in a single String * that is passed through an MD5 hash. The IP address and system time * make the MD5 seed globally unique and the random number guarantees * that the generated GUIDs will have no discernable pattern and * cannot be guessed given any number of previously generated GUIDs. * It is generally not possible to access the seed information (IP, time, * random number) from the resulting GUIDs as the MD5 hash algorithm * provides one way encryption. * * ----> Security of RandomGUID: <----- * RandomGUID can be called one of two ways -- with the basic java Random * number generator or a cryptographically strong random generator * (SecureRandom). The choice is offered because the secure random * generator takes about 3.5 times longer to generate its random numbers * and this performance hit may not be worth the added security * especially considering the basic generator is seeded with a * cryptographically strong random seed. * * Seeding the basic generator in this way effectively decouples * the random numbers from the time component making it virtually impossible * to predict the random number component even if one had absolute knowledge * of the System time. Thanks to Ashutosh Narhari for the suggestion * of using the static method to prime the basic random generator. * * Using the secure random option, this class compies with the statistical * random number generator tests specified in FIPS 140-2, Security * Requirements for Cryptographic Modules, secition 4.9.1. * * I converted all the pieces of the seed to a String before handing * it over to the MD5 hash so that you could print it out to make * sure it contains the data you expect to see and to give a nice * warm fuzzy. If you need better performance, you may want to stick * to byte[] arrays. * * I believe that it is important that the algorithm for * generating random GUIDs be open for inspection and modification. * This class is free for all uses. * * * - Marc */ public class RandomGUID extends Object { public String valueBeforeMD5 = ""; public String valueAfterMD5 = ""; private static Random myRand; private static SecureRandom mySecureRand; private static String s_id; /* * Static block to take care of one time secureRandom seed. * It takes a few seconds to initialize SecureRandom. You might * want to consider removing this static block or replacing * it with a "time since first loaded" seed to reduce this time. * This block will run only once per JVM instance. */ static { mySecureRand = new SecureRandom(); long secureInitializer = mySecureRand.nextLong(); myRand = new Random(secureInitializer); try { s_id = InetAddress.getLocalHost().toString(); } catch (UnknownHostException e) { e.printStackTrace(); } } /* * Default constructor. With no specification of security option, * this constructor defaults to lower security, high performance. */ public RandomGUID() { getRandomGUID(false); } /* * Constructor with security option. Setting secure true * enables each random number generated to be cryptographically * strong. Secure false defaults to the standard Random function seeded * with a single cryptographically strong random number. */ public RandomGUID(boolean secure) { getRandomGUID(secure); } /* * Method to generate the random GUID */ private void getRandomGUID(boolean secure) { MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { System.out.println("Error: " + e); } try { long time = System.currentTimeMillis(); long rand = 0; if (secure) { rand = mySecureRand.nextLong(); } else { rand = myRand.nextLong(); } // This StringBuffer can be a long as you need; the MD5 // hash will always return 128 bits. You can change // the seed to include anything you want here. // You could even stream a file through the MD5 making // the odds of guessing it at least as great as that // of guessing the contents of the file! sbValueBeforeMD5.append(s_id); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); byte[] array = md5.digest(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; ++j) { int b = array[j] & 0xFF; if (b < 0x10) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { System.out.println("Error:" + e); } } /* * Convert to the standard format for GUID * (Useful for SQL Server UniqueIdentifiers, etc.) * Example: C2FEEEAC-CFCD-11D1-8B05-00600806D9B6 */ public String toString() { String raw = valueAfterMD5.toUpperCase(); StringBuffer sb = new StringBuffer(); sb.append(raw.substring(0, 8)); sb.append("-"); sb.append(raw.substring(8, 12)); sb.append("-"); sb.append(raw.substring(12, 16)); sb.append("-"); sb.append(raw.substring(16, 20)); sb.append("-"); sb.append(raw.substring(20)); return sb.toString(); } /* * Demonstraton and self test of class */ public static void main(String args[]) { for (int i=0; i< 100; i++) { RandomGUID myGUID = new RandomGUID(); System.out.println("Seeding String=" + myGUID.valueBeforeMD5); System.out.println("rawGUID=" + myGUID.valueAfterMD5); System.out.println("RandomGUID=" + myGUID.toString()); } } }

Download RandomGUID. -- generates truly random GUIDs in the standard format.
Posted by tornado
|

Subversion 설치.

 

설치 파일 : CollabNetSubversion-server-1.5.0-23.win32.exe

 

 

설치시에 repository 부분 설정하는 곳이 있는데 윈도우 인스톨 된 드라이브 말고

 

d 드라이브나 데이터 저장되는 드라이브로 변경해 주세요.

 

 

1. ehr 소스가 저장될 프로젝트를 생성해 주세요.

 

커맨드 창에서 아래와 같이 해주시면 됩니다.

 

svnadmin create --fs-type fsfs c:\svn_repository\ehr_2008_07

 

 

2. 소스세이프에 생성된 프로젝트 에서 현재 프로젝트의 접근 설정을 해주세요.

 

c:\svn_repository\ehr_2008_07\conf 디렉토리에 보면

 

 

svnserve.conf 파일이 있습니다.

 

이곳에서 아래의 부분을 수정해 주세요.(# 표시를 지워주세요)

 

12번째 줄 : #anon-access = read --> anon-access = none

 

13번째 줄 : #auth-access = write

 

20번째 줄 : #password-db = passwd --> 앞에 # 표시 제거

 

32번째 줄 : # realm = My First Repository --> realm = ehr_2008_07

 

 

 

 

3. 사용자를 등록해야 합니다.

 

c:\svn_repository\ehr_2008_07\conf 디렉토리에 보면

 

passwd 라는 텍스트 파일이 존재합니다.

 

해당 파일을 아래와 같이 수정해 주세요.

 

### This file is an example password file for svnserve.

### Its format is similar to that of svnserve.conf. As shown in the

### example below it contains one section labelled [users].

### The name and password for each user follow, one account per line.

 

[users]

# harry = harryssecret

# sally = sallyssecret

 

jy = 1111

tornado = 1111

 

 

4. svn manager 설치해주세요.(재부팅 되도 svn 이 자동실행 됩니다)

 

SVNManager-1.1.1-Setup.msi  파일을 설치

 

설치 하신 후 아래의 순서로 셋팅해 주시면 됩니다.

 

시작 --> 모든 프로그램 --> Subversion --> SVNServe manager 를 실행

 

실행하면 작업 트레이에 아이콘 생성됨.

 

아이콘 더블클릭 하면 설정 화면 보여짐.

 

Subversion Repository 에서 경로를 d:\svn_repository 로 맞춤

 

Port --> 3690  으로 입력

 

Run Mode --> Normal 로 선택

 

Start 버튼 클릭

 

Hide 버튼 클릭

 

 

끝입니다

Posted by tornado
|

오랜만에 자바 코딩해봤음 ^^

jxl 예제에 엑셀 파일 생성, 읽기 부분만 나와있고 기존 파일에 추가하는 방법이 안나와서,
API 를 보니


public static WritableWorkbook createWorkbook(java.io.File file,
                                              Workbook in)
                                       throws java.io.IOException
Creates a writable workbook with the given filename as a copy of the workbook passed in. Once created, the contents of the writable workbook may be modified
Parameters:
file - the output file for the copy
in - the workbook to copy
Returns:
a writable workbook
Throws:
java.io.IOException



요런 부분이 있음.

글치.. 왜 없었겠어~ 그래서 API 를 자세히 봐야지~

아래는 간단하게 테스트 해본 소스이다.

1번줄 부터 생성한 이유는 엑셀 파일 첫줄이 Select box 로 정렬 할 수 있게 해놨기 때문임.



----------------------------------------------------------------------------------
package com.javarush;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

public class JxlUtil {
 
 public static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
 
 public File getExcelToOrder() throws Exception{
 
  File dir = new File("d:/springStudy/JxlTest/src/com/javarush/");
  File f = new File(dir, "excel_default.xls");
 
  if(!f.exists()){
   throw new Exception("file not found");
  }
 
  if(!f.canRead()){
   throw new Exception("can't read file");
  }

  Workbook workbook = Workbook.getWorkbook(f);
 
  if(workbook == null){
   throw new Exception("Workbook is null!!");
  }
 
  File newExcel = new File(dir, System.currentTimeMillis() + ".xls");
     
  WritableWorkbook writeBook = Workbook.createWorkbook(newExcel, workbook);

  WritableSheet writeSheet = writeBook.getSheet(0);
 
  // 1열의 0번행에 ^^ 를 출력
  Label a = new Label(0,1, "^^");
 
  // 1열의 1번행에 날짜 출력
  Label d = new Label(1, 1, sdf.format( Calendar.getInstance().getTime()));
   
  writeSheet.addCell(a);
  writeSheet.addCell(d);
 
  writeBook.write();
  writeBook.close();
 
  return newExcel;
 }
}

Posted by tornado
|
Posted by tornado
|

자바로 zip 파일을 다룰때(압축 풀기/압축하기) 영문이름으로 된 파일은 정상적으로 잘 되지만

한글이름으로된 파일을 다룰때에는 Exception이 발생한다.

간단하게 예제를 살펴보자.


import java.io.File;
import java.io.FileInputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;


public class ZipTest {

    public static void main(String[] args) throws Exception {
        File file = new File("e:/교육자료/이클립스단축키.zip");
        ZipInputStream in = new ZipInputStream(new FileInputStream(file));
        ZipEntry entry = null;
        while((entry = in.getNextEntry()) != null ){
            System.out.println(entry.getName()+" 파일이 들어 있네요.");
        }
    }

}


위 예제는 이클립스단축키.zip 라는 zip 파일안에 어떤 파일들이 압축되어 있는지 단순하게 리스트를 출력해보는 프로그램이다. 이클립스단축키.zip 파일안에는 다음과 같은 파일 2개가 압축되어 있다.

Keyboard_shortcuts.pdf

이클립스단축키.txt


이 프로그램을 실행시켜보면 아래와 같은 에러가 발생한다.


Keyboard_shortcuts.pdf 파일이 들어 있네요.
java.lang.IllegalArgumentException
 at java.util.zip.ZipInputStream.getUTF8String(ZipInputStream.java:284)
 at java.util.zip.ZipInputStream.readLOC(ZipInputStream.java:237)
 at java.util.zip.ZipInputStream.getNextEntry(ZipInputStream.java:73)
 at ZipTest.main(ZipTest.java:29)
Exception in thread "main"


[Keyboard_shortcuts.pdf] 파일명을 처리할때는 문제가 없다가 [이클립스단축키.txt] 처럼 한글이름으로 된 파일명을 다룰때는 Exception 이 발생함을 알 수 있는데, 이문제는 java.util.zip 패키지의 한글처리 인코딩로직의 버그이다. 하지만 한글 인코딩 문제는 의외로 아주 간단하게 해결된다.


Jochen Hoenicke 가 만든 jazzlib.jar 라이브러리를 다운받아 클래스패스에 추가하면 된다. 소스는 전혀 수정할 필요가 없고 단지 import 문만 아래와 같이 수정해 주면 된다.


import java.io.File;
import java.io.FileInputStream;
import net.sf.jazzlib.ZipEntry;
import net.sf.jazzlib.ZipInputStream;


public class ZipTest {

    public static void main(String[] args) throws Exception {
        File file = new File("e:/교육자료/이클립스단축키.zip");
        ZipInputStream in = new ZipInputStream(new FileInputStream(file));
        ZipEntry entry = null;
        while((entry = in.getNextEntry()) != null ){
            System.out.println(entry.getName()+" 파일이 들어 있네요.");
        }
    }

}


다시 프로그램을 실행시켜 보면 아래와 같이 정상적인 결과를 확인할 수 있다.

Keyboard_shortcuts.pdf 파일이 들어 있네요.
이클립스단축키.txt 파일이 들어 있네요.


jazzlib.jar 파일은 인코딩 문제를 해결한 라이브러리이므로 압축할때와 압축을 풀때 모두 잘 작동한다.


Reference is jazzlib

Posted by tornado
|

Jad home page: http://www.geocities.com/SiliconValley/Bridge/8617/jad.html
Copyright 2000 Pavel Kouznetsov (kpdus@yahoo.com). 


[ 사용방법 ]


1. 클래스 하나만 디컴파일시

           example1.class   를 디컴파일시 

           jad.exe 를 디컴파일할 파일과 동일한 폴더에 놓는다.

         

           Command 창에   jad -o -sjava example1.class   

       

   결과물 : 'example1.java' 

   

2. Package 를 디컴파일시   

         tree  폴더 아래의 모든 클래스파일을 디컴파일시 

         폴더와 같은 폴더에 jad.exe  를 위치하고


          Command 창에    jad -o -r -sjava -dsrc tree/**/*.class 

          

          결과물 : 폴더내에 [src] 폴더가 생성된다. 

Posted by tornado
|
Linux(RedHat), FreeBSD, Windows에 Java Path 설정 조회 35 | 추천 | 스크랩
IT 상식 | 2004-11-16 00:08:04  
PATH 지정의 목적 : 현재 디랙토리가 어디이던 JDK의 "bin"폴더에 있는java.exe, javac.exe등을 실행시키기 위한 경로를 지정
 
 
 
Linux
=====
 
 .bash_profile 또는 .bashrc에서
export PATH=$JAVA_HOME/bin을 지정
 
#설치 위치 : /usr/local/j2sdk1.4.2_02/ (/usr/local/jdk 로 심볼릭 링크)
#export JAVA_HOME=/usr/local/jdk
#export CLASSPATH=$JAVA_HOME/classes12.zip:/root/j2sdk1.4.2_02/lib
#export PATH=$PATH:$JAVA_HOME/bin:$JAVA_HOME/jre/lib
 
 
# .bash_profile
# Get the aliases and functions
if [ -f ~/.bashrc ]; then
 . ~/.bashrc
fi
# User specific environment and startup programs
PATH=$PATH:$HOME/bin
BASH_ENV=$HOME/.bashrc
USERNAME="root"
export USERNAME BASH_ENV PATH
export PATH=$PATH:$usr/java/j2re1.4.2_06/bin/
 
 
 

 

 
FreeBSD
========
 
/etc/profile 또는 $HOME/.bash_profile $HOME/.bashrc, .cshrc
(env 명령으로 쉘을 확인한 후 어떤 쉘을 쓰는지 확인)
 
# tcsh 쉘의 설정(.cshrc)
----------------------
# alias
alias l  ls -alF
alias ns netstat -nr
alias pp ps -aux
 
# path
set path = (/sbin /bin /user/sbin /usr/bin /usr/local/sbin /usr/local/bin /usr/X11R6/bin)
set path = ($path $HOME/bin)
 
# 환경변수
setenv LANG ko_KR.EUC
 
# 쉘 프롬프트
set prompt = "$user %c2> "
set prompt = "$user $cwd> "
set prompt = "`hostname -s`> "
 
# jdk
setenv JDK /usr/local/jdk1.1.8
set path = ($path $JDK/bin)
setenv CLASSPATH $JDK/lib/classes.zip:.
setenv LD_LIBRARY_PATH $JDK/lib/i386
 
# stty
stty erase ^H

 
# Bourne Shell의 설정(.profile)
-----------------------------
# alias
alias l='ls -alF'
 
# 로케일
LANG="ko_KR.EUC"; export LANG
 
#path
PATH=/sbin:/bin:/usr/sbin:/usr/bin:$HOME/bin; export PATH
 

 
Windows
========

도스창을 열고 set path=...... 명령을 넣으면 그 도스창을 띄운 프로세스에만 적용
 
autoexec.bat에 아래 내용 추가후 Rebooting
예) set path=%path%;c:JDK설치위치bin
설명 ) path라는 변수를 셋팅하는데 "기존의 path 변수에 있는 설정값"을 가져오고(%path%) , 추가로(;) "c:j2sebin"라는 폴더를
패스를 잡아서 어디서든지 그 안에 있는 명령어들을 쓸수있게 한다
 
환경변수를 아래와 같이 수정
예) '시작' > '설정' > '제어판' > '시스템' 으로 가서... '고급'tab > '환경변수' 버튼 클릭
     > '시스템 변수'에 "path" 더블 클릭 >  ;c:JDK설치위치bin 내용 추가
Posted by tornado
|