JarScan j = new JarScan("C:/tmp");
j.search("umaUtils");
}
------------------------------

import java.io.File;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

public class JarScan {
	private String path = "";
	private String ptn = "";
	private int cnt = 0;
	public JarScan(String path) {
		this.path = path;
	}
	
	public void search(String findString) {
		this.ptn = findString;
		subScanDir(path);
		System.out.println("Complete: " + cnt + "Files");
	}
	
	private void subScanDir(String path) {
		File f = new File(path);
		File[] fileList = f.listFiles();
		if(fileList != null) {
			for(File fs : fileList) {
				if(fs.isDirectory()) {
				subScanDir(path + "/" + fs.getName());
			}else {
				String fileName = fs.getName().toLowerCase();
				if(fileName.lastIndexOf(".jar") != -1) {
					readJarFile(path + "/" + fs.getName());
				}
				}
			}
		}
	}
	
	private void readJarFile(String fileName) {
		JarFile jar = null;
		boolean flag = false;
		try {
			jar = new JarFile(fileName);
			if(jar != null) {
				Enumeration<JarEntry> entry = jar.entries();
				if(entry != null) {
					while(entry.hasMoreElements()) {
						JarEntry e = entry.nextElement();
						if(!e.isDirectory()) {
							if(e.getName().indexOf(this.ptn) != -1) {
								if(!flag) {
									System.out.println(++cnt + ") " + fileName);
									flag = true;
								}
								System.out.println("   " + e.getName());
							}
						}
					}
				}
			}
		}catch(Exception e) {
			e.printStackTrace();
		}finally {
			if(jar != null) try { if(jar != null) jar.close(); } catch(Exception e1) { }
		}
	}
}

"Completely Automated Public Turing test to tell Computers and Humans Apart"



Code1 


근데 말이지… 좀더 줄이고 다양하게 할 수 있을꺼 같은데…


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


<textarea name="code" class="brush:java;" style="margin: 0px; width: 561px; height: 195px;"> 

public static String getCode(int len) { 

byte[] wd = new byte[]{0x41,0x61,0x30,0x30}; 

int[] lwd = new int[]{26,26,10,10}; 

Random r = new Random(); 

String str = ""; 

for(int i = len; i-- &gt; 0;) 

str += (char)(wd[i&amp;0x03] + r.nextInt(lwd[i&amp;0x03])); 

return str; 

}

</textarea>


Code2


좀더 개선된 코드당.


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

<textarea name="code" class="brush:java;" style="margin: 0px; height: 186px; width: 913px;"> 

public static String getCode(int len) {

int[] RND_VAL = new int[]{48, 57, 65, 90, 97, 122};

Random r = new Random();

String str = "";

int k = 0;


while(len-- &gt; 0) {

k = r.nextInt(0xff);

k = (k + (~k &amp; 0x01)) % RND_VAL.length;

str += (char)(RND_VAL[k-1] + r.nextInt((RND_VAL[k]-RND_VAL[k-1]+1)));

}

return str;


}

</textarea>



Sample

위의 로직을 추가해서 이미지를 생성하는 샘플 임댜.

실행한 위치에 

out_{내용}.jpg 라는 파일들이 생성되요.

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

<textarea name="code" class="brush:java;"> 

public class GenImage {

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

int ptn[][] = new      int[][]{CaptchaText.RND_VAL_1,CaptchaText.RND_VAL_2,CaptchaText.RND_VAL_3,CaptchaText.RND_VAL_4};

String[] tit = new String[]{"문자(대+소)+숫자", "특수문자 + 영문자(대+소)+숫자", "영문자(대+소)", "숫자 "};

for(int i = 0; i &lt; 4; i++) {

createImage(200, 100,ptn[i], "out_" + tit[i] + ".jpg";

}

}


public static void createImage(int width, int height, int[] ptn, String fileName) {

CaptchaText ct = new CaptchaText(); 

BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);

Graphics g = img.getGraphics();

g.setColor(new Color(0xFFFFFF));

g.setFont(new Font("Serif", Font.BOLD, 20));

g.drawString(ct.getCode(10, ptn), 40, 50);

try {

ImageIO.write(img, "jpg", new File(fileName));

} catch (IOException e) {

e.printStackTrace();

}

}

}


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

public class CaptchaText {

/** 범위 설정 - 영문자(대+소)+숫자 */

public final static int[] RND_VAL_1 = new int[]{48, 57, 65, 90, 97, 122};

/** 범위 설정 - ascii 특수문자 + 영문자(대+소)+숫자 */

public final static int[] RND_VAL_2 = new int[]{33, 33, 35, 38, 40, 43, 45, 62, 64, 90, 97, 126};

/** 범위 설정 - 영문자(대+소) */

public final static int[] RND_VAL_3 = new int[]{65, 90, 97, 122};

/** 범위 설정 - 숫자 */

public final static int[] RND_VAL_4 = new int[]{48, 57};

/**

* &lt;pre&gt;

* 기본 형

* - RND_VAL_1

* &lt;/pre&gt;

* @param len

* @return

*/

public String getCode(int len) {

return getCode(len, RND_VAL_1);

}

/**

* &lt;pre&gt;

* 확장 형

* - RND_VAL_1 ~ RND_VAL_4

* &lt;/pre&gt;

* @param len

* @param RND_VAL

* @return

*/

public String getCode(int len, int[] RND_VAL) {

Random r = new Random();

String str = "";

int k = 0;

while(len-- &gt; 0) {

k = r.nextInt(0xff);

k = (k + (~k &amp; 0x01)) % RND_VAL.length;

str += (char)(RND_VAL[k-1] + r.nextInt((RND_VAL[k]-RND_VAL[k-1]+1)));

}

return str;

}

}

</textarea>

'내꺼' 카테고리의 다른 글

스마트 입찰예가 자동계산 앱 (iOS, Android)  (0) 2020.05.28
css 디버깅 툴  (0) 2012.07.09
Host 정보 변경 파이썬 코드  (0) 2009.07.21
host 정보를 바꿔봐~  (2) 2009.06.25
귀찮을때 쓰는 hosts 바꿔치기 batch...  (0) 2009.06.16
 
package com.umaking;

import java.security.Key;
import java.security.NoSuchAlgorithmException;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;

/**
* 3DES 암호화로 암호화 복호화를 한다.
* @author ChangYeol.Kim
*
*/
public class CryptoUtil {
	private static Key key = null;

	static {
		if(key == null) {
			// Key 초기화
			KeyGenerator keyGenerator;
			try {
				keyGenerator = KeyGenerator.getInstance("TripleDES");
				keyGenerator.init(168);
				key = keyGenerator.generateKey();
			} catch (NoSuchAlgorithmException e) {
				e.printStackTrace();
			}
		}
	}

	public static String Encode(String inStr) {
		StringBuffer sb = null;
		try {
			Cipher cipher = Cipher.getInstance("TripleDES/ECB/PKCS5Padding");
			cipher.init(Cipher.ENCRYPT_MODE, key);
			byte[] plaintext = inStr.getBytes("UTF8");
			byte[] ciphertext = cipher.doFinal(plaintext);

			sb = new StringBuffer(ciphertext.length * 2);
			for(int i = 0; i < ciphertext.length; i++) {
			String hex = "0" + Integer.toHexString(0xff & ciphertext[i]); 
			sb.append(hex.substring(hex.length()-2));
		}
		}catch(Exception e) {
			e.printStackTrace();
		}
		
		return sb.toString();
	}

	public static String Decode(String inStr) {
	String text = null;
	try {
		byte[] b = new byte[inStr.length()/2];
		Cipher cipher = Cipher.getInstance("TripleDES/ECB/PKCS5Padding");
		cipher.init(Cipher.DECRYPT_MODE, key);
		for(int i = 0; i < b.length; i++) {
			b[i] = (byte)Integer.parseInt(inStr.substring(2*i, 2*i+2), 16);
		}
		byte[] decryptedText = cipher.doFinal(b);
		text = new String(decryptedText,"UTF8");
	}catch(Exception e) {
		e.printStackTrace();
	}
	
	return text;
	}
}

'코드' 카테고리의 다른 글

GNUstep Make파일을 만들다.  (0) 2009.10.22
AWK - 디스크 용량 분석  (0) 2009.10.13
TrayIcon - TaskbarCreated 신호시....  (0) 2009.07.12
JSTL - customTag를 만들어 보자.  (0) 2009.03.16
prototype 1.6에서 SelectBOX 생성  (0) 2009.03.07
1. setDomainEnv.cmd 파일 상단에 추가
    set JAVA_OPTIONS=%JAVA_OPTIONS% -agentlib:JPIBootLoader=JPIAgent:server=enabled;CGProf
   CGProf  :  Execution time analysis
   HeapProf  :  Memory analysis
   ThreadProf  :  Thread analysis

2. TPTP Controller Agent를 다운 받아 임의의 디렉토리에 풀어놓기.
    (예: C:\DevTools\tptp\tptpdc\win_ia32)

3. 환경 변수에 추가하기
    TPTP_AC_HOME=C:\DevTools\tptp\tptpdc\win_ia32
    JAVA_PROFILER_HOME=C:\DevTools\tptp\tptpdc\win_ia32\plugins\org.eclipse.tptp.javaprofiler

4. Path에 추가하기
    PATH=%PATH%;%TPTP_AC_HOME%\bin;%JAVA_PROFILER_HOME%

5. Weblogic 실행

6. Profiler



구성 파일은 아래와 같다.
- java.com.umaking.MyTag.java
- /WEB-INF/tld/mytags.tld
- web.xml설정
- jsp페이지 설정

tag의 변수는 var, message로 정하였으며
tag내에 내용과 message를 같은 데이터로 취급하였다
a. tag내의 내용이 존재하면 message내용은 무시하도록 하였다.

몇 년 만에 찾아보니 참 그러하네...
오래된 기억을 다시 더듬어 보는 느낌 이랄까...
------------------------------------------------------------------------------------------
[com.umaking.MyTag.java]
 
package com.umaking;

import java.io.IOException;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.BodyTagSupport;

public class MyTag extends BodyTagSupport {
    private static final long serialVersionUID = 1L;
    private String message = "";
    private String var;
    
    public void setMessage(String message) {
        this.message = message;
    }

    public void setVar(String var) {
        this.var = var;
    }

    @Override
    public int doStartTag() throws JspException {    
        return this.EVAL_BODY_BUFFERED;
    }
    
    @Override
    public int doEndTag() throws JspException {
        JspWriter out = pageContext.getOut();
        
        if(getBodyContent() != null) {
            message = this.getBodyContent().getString();
        }
        
        try {
            out.println(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
        
        return this.EVAL_PAGE;
    }
}
------------------------------------------------------------------------------------------
[WEB-INF/tld/mytags.tld]
 
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE taglib
            PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN" 
            "http://java.sun.com/j2ee/dtds/web-jsptaglib_1_1.dtd">
 <taglib>
    <tlibversion>1.0</tlibversion>
    <jspversion>1.1</jspversion>
    <shortname>UmaUtils</shortname>
    <uri>http://www.umaking.com/taglibs/mytags</uri>
    <info></info>

    <tag>
      <name>umaTag</name>
      <tagclass>com.umaking.MyTag</tagclass>
      JSP</bodycontent>
      <attribute>
          <name>var</name>
        <required>false</required>
        <rtexprvalue>true</rtexprvalue>
      </attribute>
      <attribute>
          <name>message</name>
        <required>false</required>
        <rtexprvalue>true</rtexprvalue>
      </attribute>
    </tag>
</taglib>
------------------------------------------------------------------------------------------
[/WEB-INF/web.xml]
 
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>pp</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
   
    <!-- 추가 함 -->
    <taglib>
       <taglib-uri>
         http://www.umaking.com/taglibs/mytags
       </taglib-uri>
       <taglib-location>
         /WEB-INF/tld/mytags.tld
       </taglib-location>
    </taglib>

</web-app>
------------------------------------------------------------------------------------------
[/test.jsp]
 
<%@ page pageEncoding="euc-kr" %>
<%@ taglib uri="http://www.umaking.com/taglibs/mytags" prefix="m" %>
<m:umaTag var="test" message="aaa">
테스트 입니다.
</m:umaTag>

'코드' 카테고리의 다른 글

3DES  (0) 2009.09.03
TrayIcon - TaskbarCreated 신호시....  (0) 2009.07.12
prototype 1.6에서 SelectBOX 생성  (0) 2009.03.07
ServletFilter를 통한 URI 재구성 (Blog처럼)  (1) 2009.02.22
printStackTrace  (0) 2008.09.02
 
package com;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet Filter를 통한 URL 재구성
 *
 * @author ChangYeol.Kim
 * @date 2009.02.22
 *
 */
public class UmaFilter implements Filter {
    private    Map map;

    public UmaFilter() {
    }
    public void destroy() {
    }
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse)response;
        String uri = req.getServletPath();
        String jsp = "";

        String stri;
        Iterator i = map.keySet().iterator();
        while(i.hasNext()) {
            stri = (String)i.next();

            Pattern p = Pattern.compile(stri, Pattern.UNICODE_CASE|Pattern.CASE_INSENSITIVE|Pattern.MULTILINE);
            Matcher m = p.matcher(uri);

            if(m.find()) {
                jsp = m.replaceAll( (String) map.get(stri) );
                break;
            }
        }

        RequestDispatcher disp = request.getRequestDispatcher( jsp );
        if(disp != null) {
            disp.forward(request, response);
        }else
            chain.doFilter(request, response);
    }
    public void init(FilterConfig fConfig) throws ServletException {
        String name;
        map = new HashMap<String, String>();
        map.put("/blog/([0-9]+)$", "/uma.jsp?seq=$1");
    }
}
-------------------------------------------------------------------
 
 <display-name>UmaFilter</display-name>
    <filter-name>UmaFilter</filter-name>
    <filter-class>com.UmaFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>UmaFilter</filter-name>
    <url-pattern>/blog/*</url-pattern>
  </filter-mapping>
-------------------------------------------------------------------

암튼 대충 끝났다.


내용은 대충 이렇다.

http://www.umaking.com/blog/1

이렇게 해주면

Servlet Filter를 거치면서

http://www.umaking.com/uma.jsp?seq=1

이렇게 구성 되도록 하였다.

위의 붉은색 부분을 보면 알겠지만

정규식으로 해당 부분을 필터링해 전달한다.


글쿠 몇가지 생각해 볼 부분이 있는데 고민 중.


설정파일을 외부로 뺄까 생각 중인데


뭘로 뺄까!!



+ Recent posts