'java core' 카테고리의 다른 글

Cheking JMX Port Alive  (0) 2009.11.19
JDK 7 언어적으로 특징적으로 변하는 부분. (api 제외)  (0) 2009.11.13
Java Memroy Model  (0) 2009.08.06
Java Pattern 활용하기  (0) 2009.07.23
Symmetric Encryption by using java.security.  (0) 2009.07.22
Posted by '김용환'
,

Java Memroy Model

java core 2009. 8. 6. 13:47
Posted by '김용환'
,

$${aaa.bbb.ccc} 이라는 템플릿에 대한 검증 또는 데이터 저장하는 코드.


public class TemplatePropertyMaker {
 
 public static boolean isAvailable(String value) {
  return getGroup(value) == null ? false : true;
 }
 
 private static String getGroup(String value) {
  Pattern pattern = Pattern.compile("\\$\\$\\{(.*)\\}");
  Matcher matcher = pattern.matcher(value);
  String content = null;
  if (matcher.find()) {
   if (Logger.DEBUG) {
    System.out.println("TemplatePropertyMaker: " + value.substring(matcher.start(), matcher.end()));
    System.out.println("TemplatePropertyMaker: " + matcher.group(1));
   }
   content = matcher.group(1);
  }
  
  if (content == null) {
   return null;
  }
  return content;
 }
 
 public static TemplateProperty getTemplatProperty(String key, String value) {
  String content = getGroup(value);
  Pattern pattern = Pattern.compile("(\\w++).(\\w++).(\\w++)");
  Matcher matcher = pattern.matcher(content);
  
  TemplateProperty templateProperty = new TemplateProperty();
  if (matcher.find()) {
   int number = matcher.groupCount();
   while (number > 0) {
    templateProperty.setValue(number, matcher.group(number));
    number--;
   }
  }
  templateProperty.setKey(key);
  return templateProperty;
 }
}

'java core' 카테고리의 다른 글

파일 copy 테스트 (nio, inputstream) 테스트 in java  (0) 2009.09.11
Java Memroy Model  (0) 2009.08.06
Symmetric Encryption by using java.security.  (0) 2009.07.22
URLConnection vs HTTPURLConnection  (0) 2009.07.20
Finally 범위  (0) 2009.07.15
Posted by '김용환'
,

대칭 키로서, 로컬 PC에서 사용할 대칭키 알고리즘을 사용한 클래스이다.

import java.security.InvalidKeyException;
import java.security.Key;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.spec.SecretKeySpec;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
public class SimpleCodec {
 private static String algorithm = "AES"; 
 private static Key key = null;
 private static Cipher cipher = null;
 
 public SimpleCodec() throws Exception {
  
  key = KeyGenerator.getInstance(algorithm).generateKey();
  cipher = Cipher.getInstance(algorithm);
  
 }
 private String getTimeKey() {
  SimpleDateFormat format0 = new SimpleDateFormat("MMddHH");
  Date now = new Date();
  // add 1 minute
  now.setTime(now.getTime() + 60 * 1000);
  String dtime = format0.format(now);
  return dtime;
 }
 public String encrypt(String key) throws Exception {
  byte[] encryptionBytes = encryptImpl(key);
  BASE64Encoder encoder = new BASE64Encoder();
  String encodeString = encoder.encode(encryptionBytes);
  return encodeString;
 }
 public String encrypt() throws Exception {
  byte[] encryptionBytes = encryptImpl(getTimeKey());
  BASE64Encoder encoder = new BASE64Encoder();
  String encodeString = encoder.encode(encryptionBytes);
  return encodeString;
 }
 public String decrypt(String encodedString) throws Exception {
  if (encodedString == null) {
   return null;
  }
  BASE64Decoder decoder = new BASE64Decoder();
  return decrypt(decoder.decodeBuffer(encodedString));
 }
 private static byte[] encryptImpl(String input) throws InvalidKeyException, BadPaddingException,
   IllegalBlockSizeException {
  cipher.init(Cipher.ENCRYPT_MODE, key);
  byte[] inputBytes = input.getBytes();
  return cipher.doFinal(inputBytes);
 }
 private static String decrypt(byte[] encryptionBytes) throws InvalidKeyException, BadPaddingException,
   IllegalBlockSizeException {
  cipher.init(Cipher.DECRYPT_MODE, key);
  byte[] recoveredBytes = cipher.doFinal(encryptionBytes);
  String recovered = new String(recoveredBytes);
  return recovered;
 }
}



반면, 네트웍을 통해서 대칭키를 가지고, 서로 통신해야 하는 경우라면, 다음을 사용해야 하는 것이 좋다.
즉, Key를 서로 공유할 수 있도록 하는 것이다.


public class SimpleCodec {
 private static Key key = null;
 private static Cipher cipher = null;
 
 byte[] symKey = {
  (byte)0xca, (byte)0x00, (byte)0x25, (byte)0x06,
  (byte)0x28, (byte)0xae, (byte)0xd2, (byte)0xbd,
  (byte)0x2b, (byte)0x7e, (byte)0x15, (byte)0x16,
  (byte)0x28, (byte)0xae, (byte)0xd2, (byte)0xa6,
  (byte)0x2c, (byte)0x7e, (byte)0x10, (byte)0x96,
  (byte)0x28, (byte)0xff, (byte)0xd2, (byte)0xa6,
 };
 public SimpleCodec() throws Exception {
  key = new SecretKeySpec(symKey, 0, symKey.length, "DESede");
  cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");

 }
 private String getTimeKey() {
  SimpleDateFormat format0 = new SimpleDateFormat("MMddHH");
  Date now = new Date();
  // add 1 minute
  now.setTime(now.getTime() + 60 * 1000);
  String dtime = format0.format(now);
  return dtime;
 }
 public String encrypt(String key) throws Exception {
  byte[] encryptionBytes = encryptImpl(key);
  BASE64Encoder encoder = new BASE64Encoder();
  String encodeString = encoder.encode(encryptionBytes);
  return encodeString;
 }
 public String encrypt() throws Exception {
  byte[] encryptionBytes = encryptImpl(getTimeKey());
  BASE64Encoder encoder = new BASE64Encoder();
  String encodeString = encoder.encode(encryptionBytes);
  return encodeString;
 }
 public String decrypt(String encodedString) throws Exception {
  if (encodedString == null) {
   return null;
  }
  BASE64Decoder decoder = new BASE64Decoder();
  return decrypt(decoder.decodeBuffer(encodedString));
 }
 private static byte[] encryptImpl(String input) throws InvalidKeyException, BadPaddingException,
   IllegalBlockSizeException {
  cipher.init(Cipher.ENCRYPT_MODE, key);
  byte[] inputBytes = input.getBytes();
  return cipher.doFinal(inputBytes);
 }
 private static String decrypt(byte[] encryptionBytes) throws InvalidKeyException, BadPaddingException,
   IllegalBlockSizeException {
  cipher.init(Cipher.DECRYPT_MODE, key);
  byte[] recoveredBytes = cipher.doFinal(encryptionBytes);
  String recovered = new String(recoveredBytes);
  return recovered;
 }
}



참고자료
http://blog.sdnkorea.com/blog/469
http://kr.sun.com/developers/techtips/c2004_01_16.htm

'java core' 카테고리의 다른 글

Java Memroy Model  (0) 2009.08.06
Java Pattern 활용하기  (0) 2009.07.23
URLConnection vs HTTPURLConnection  (0) 2009.07.20
Finally 범위  (0) 2009.07.15
How to get object size in java.  (0) 2009.05.29
Posted by '김용환'
,

URLConnection 객체를 쓸려거든, HTTPURLConnection으로 클래스타입 변환을 하고, 명시적으로 disconnect() 메소드를 날려주는 것이 좋습니다.

HttpURLConnection conn = (HttpURLConnection)(new URL("http://www.google.com").openConnection());

conn.disconnect();


 

 

http 프로토콜을 가지는 URL 객체를 이용하여 openConnection() 메소드를 얻는 객체는 rt.jar에 있는 sun.net.www.protocol.http.HttpURLConnection 객체를 얻어옵니다

사실 이 객체는 URLConnection  또는 HttpURLConnection 추상화 객체로 쓸 수 있습니다. 다만 큰 차이는 disconnect() 메소드를 호출할 수 있느냐 없는냐 수준입니다.

소스를 보면,  연결 후, 바로 끊도록 되어 있지만, keep alive때에 대해서 확인하는 절차가 있습니다.

 

 

URLConnection을 통해서 InputStream을 통해서 response를 다 읽어오면,  자연스럽게 접속이 끊기게 됩니다. 아시다시피 아파치 http 설정에 KeepAlive Off로 되어 있으면 그렇습니다.

만약 KeepAlive On으로 되어 있으면, 연결이 끊기지 않도록 되어 있지요.

 

결국은 아파치 설정이 KeepAlive On 설정으로 셋팅되어 있을 수 있기 때문에 HttpURLConnection객체를 써서 disconnect()를 써야 하는 상황이라고 생각하시면 좋을 듯 싶습니다.

 

아파치 설정에 KeepAlive Off로 되어 있으면, 그 서버와 통신하는 클라이언트의 URLConnection을 사용해도 아무런 문제가 없습니다.  한게임 웹은 무조건 그런 설정을 따라가도록 되어 있습니다.

 

첨부파일에 보시면, 제가 수십 번의 테스트를 통해서 나름 결론을 내린 두개의 tcpdump 분석 데이터가 있습니다.

아파치 웹 서버가 KeepAlive Off로 되어 있으면, 클라이언트에서 FIN을 보내서 종료하게 되고, KeepAlive On이면 대기하게 됩니다.  웹 서버가 KeepAlive On 상태인대, 계속 요청이 들어오게 되면, 연결이 많아져 점점 처리를 못하게 되어 ACK 통신이 어려워져 timeout 되어 FIN_WAIT로 이동할 것입니다. (아마도 거의 장애 상태에 부딪히게 됩니다. 이 상황은 보고된 장애 또는 도스 공격 상황와 매우 흡사한 상황입니다.)

 

 

'java core' 카테고리의 다른 글

Java Pattern 활용하기  (0) 2009.07.23
Symmetric Encryption by using java.security.  (0) 2009.07.22
Finally 범위  (0) 2009.07.15
How to get object size in java.  (0) 2009.05.29
How to get List comparator using Comparator class.  (0) 2009.05.13
Posted by '김용환'
,

Finally 범위

java core 2009. 7. 15. 15:12

코딩하다가 늘 깜박깜박해서.. 정리했다.

try-catch-finally 안에서 catch문안에 return이 있으면, finally안에 들어가지 않는다.
한편, exception이 발생하면, finally안으로 들어간다.

 public static void main(String[] args) throws Exception {
  try {
   System.out.println("1");
   throw new Exception();
  } catch (Exception e) {
   System.out.println("2");
   throw new Exception(e);
  } finally {
   System.out.println("3");
  }
 }

'java core' 카테고리의 다른 글

Symmetric Encryption by using java.security.  (0) 2009.07.22
URLConnection vs HTTPURLConnection  (0) 2009.07.20
How to get object size in java.  (0) 2009.05.29
How to get List comparator using Comparator class.  (0) 2009.05.13
JMX reference  (0) 2009.04.29
Posted by '김용환'
,

It is easy to use intrumentation.

Source
import java.lang.instrument.Instrumentation;
import java.util.Calendar;
import java.util.HashMap;
public class Test {
 private static Instrumentation inst;
 public static void premain(String options, Instrumentation inst) {
  Test.inst = inst;
 }
 public static long sizeOf(Object o) {
  assert inst != null;
  return inst.getObjectSize(o);
 }
 public static void main(String[] args) {
  System.out.println("Size of Object: " + sizeOf(new Object()));
  System.out.println("Size of String: " + sizeOf(new String()));
  System.out.println("Size of String111: " + sizeOf(new String("111.111.111.111")));
  System.out.println("Size of StringBuffer: " + sizeOf(new String()));
  System.out.println("Size of HashMap: " + sizeOf(new HashMap()));
  System.out.println("Size of direct subclass: " + sizeOf(new Test()));
  System.out.println("Size of Calendar: " + sizeOf(Calendar.getInstance()));
 }
}


manifest.mf

Manifest-Version: 1.0
Premain-Class: com.google.laputa.sms.sample.Test
Main-Class: com.google.laputa.sms.sample.Test

jaring
$ jar cvfm test.jar test-classes/MANIFEST.MF -C test-classes .

execution
$ java -ea -javaagent:test.jar -jar test.jar

Result
Size of Object: 8
Size of String: 24
Size of String111: 24
Size of StringBuffer: 24
Size of HashMap: 40
Size of direct subclass: 8
Size of Calendar: 112


'java core' 카테고리의 다른 글

URLConnection vs HTTPURLConnection  (0) 2009.07.20
Finally 범위  (0) 2009.07.15
How to get List comparator using Comparator class.  (0) 2009.05.13
JMX reference  (0) 2009.04.29
Effective Java Reload  (0) 2009.04.29
Posted by '김용환'
,


reference : java generic 


public static <E> Comparator<List<E>> listComparator(final Comparator<E> comp) {
return new Comparator<List<E>>() {
public int compare(List<E> list1, List<E> list2) {
int n1 = list1.size();
int n2 = list2.size();
for (int i = 0 ; i < Math.min(n1, n2) ; i++) {
int k = comp.compare(list1.get(i), list2.get(i));
if (k != 0) {
return k;
}
}
return (n1 < n2) ? -1 : (n1 == n2) ? 0 : 1;
}
};
}

'java core' 카테고리의 다른 글

Finally 범위  (0) 2009.07.15
How to get object size in java.  (0) 2009.05.29
JMX reference  (0) 2009.04.29
Effective Java Reload  (0) 2009.04.29
Rounding(Scaling) x postion of decimal point  (0) 2009.04.29
Posted by '김용환'
,

JMX reference

java core 2009. 4. 29. 21:07

http://java.sun.com/docs/books/tutorial/jmx/
http://java.sun.com/javase/6/docs/technotes/guides/management/agent.html#gdjou
http://java.sun.com/javase/6/docs/technotes/guides/management/mxbeans.html
http://java.sun.com/j2se/1.5.0/docs/guide/jmx/index.html
http://blog.naver.com/PostView.nhn?blogId=pecman&logNo=110015624171
http://www.ibm.com/developerworks/library/j-rtm1/index.html
https://cds.sun.com/is-bin/INTERSHOP.enfinity/WFS/CDS-CDS_JCP-Site/en_US/-/USD/ViewFilteredProducts-SimpleBundleDownload
http://lemonfish.egloos.com/4253102
http://www.chicdesign.co.kr/java/JMX/overview/appendixA.htm#wp1002189
http://chanwook.tistory.com/575
http://link.allblog.net/1228782/http://hanjava.net/call-151/2006/08/21/java%EB%A1%9C-physical-memory-%ED%81%AC%EA%B8%B0-%EC%95%8C%EC%95%84%EB%82%B4%EA%B8%B0/
http://link.allblog.net/14933961/http://judy98.tistory.com/entry/Creating-a-Custom-JMX-Client
http://link.allblog.net/15921220/http://adeveloper.tistory.com/107
http://link.allblog.net/12312721/http://bcho.tistory.com/entry/WebLogic%EC%97%90%EC%84%9C-Inflight-Transaction%EC%A7%84%ED%96%89%EC%A4%91%EC%9D%B8-%ED%8A%B8%EB%A0%8C%EC%A0%9D%EC%85%98-%EC%83%81%ED%83%9C-%EB%AA%A8%EB%8B%88%ED%84%B0%EB%A7%81-%ED%95%98%EA%B8%B0
http://weblogs.java.net/blog/emcmanus/archive/2007/05/making_a_jmx_co_1.html
http://weblogs.java.net/blog/emcmanus/
http://marxsoftware.blogspot.com/2008/08/remote-jmx-connectors-and-adapters.html
http://weblogs.java.net/blog/emcmanus/archive/performance/index.html
http://blogs.sun.com/jmxnetbeans/
http://forums.sun.com/forum.jspa?forumID=537
http://java.sun.com/javase/technologies/core/mntr-mgmt/javamanagement/download.jsp

MXBEAN
http://weblogs.java.net/blog/emcmanus/archive/2006/02/what_is_an_mxbe.html
http://java.sun.com/javase/technologies/core/mntr-mgmt/javamanagement/
http://weblogs.java.net/blog/emcmanus/archive/2006/11/a_real_example.html
http://blogs.sun.com/jmxetc/entry/how_to_retrieve_remote_jvm
http://blogs.sun.com/joel/entry/easily_modifying_and_rebuilding_jmx

'java core' 카테고리의 다른 글

How to get object size in java.  (0) 2009.05.29
How to get List comparator using Comparator class.  (0) 2009.05.13
Effective Java Reload  (0) 2009.04.29
Rounding(Scaling) x postion of decimal point  (0) 2009.04.29
How to get cpu usage in java.  (0) 2009.04.29
Posted by '김용환'
,

Effective Java Reload

java core 2009. 4. 29. 19:23

'java core' 카테고리의 다른 글

How to get List comparator using Comparator class.  (0) 2009.05.13
JMX reference  (0) 2009.04.29
Rounding(Scaling) x postion of decimal point  (0) 2009.04.29
How to get cpu usage in java.  (0) 2009.04.29
How to get hostname in http url in Java  (0) 2009.04.28
Posted by '김용환'
,