레이블이 단호박업무인 게시물을 표시합니다. 모든 게시물 표시
레이블이 단호박업무인 게시물을 표시합니다. 모든 게시물 표시

2010년 10월 28일 목요일

유닉스/리눅스 파일 안에서 특정 문자(열) 찾기

유닉스/리눅스 파일 안에서 특정 문자(열) 찾기

 

find . -type f -exec grep -l "mem_info_list start" {} \; -print

2010년 9월 17일 금요일

[Javascript] 파일 upload 전 확장자 / 이미지 크기 체크


  <input type="file" name="fileName" onChange="uploadImg_Change( this, 480,320 )" alt="480*320" >



function fileClear(obj){
obj.select();
document.selection.clear();
obj.blur();
}
function getFileExtension( filePath )
{
    var lastIndex = -1;
    lastIndex = filePath.lastIndexOf('.');
    var extension = "";

if ( lastIndex != -1 )
{
extension = filePath.substring( lastIndex+1, filePath.len );
} else {
extension = "";
}
    return extension;
}

//파일을 선택 후 포커스 이동시 호출
function uploadImg_Change( obj, iwidth, iheight )
{
var value = obj.value;
maxImageHeight=iheight;
maxImageWidth=iwidth;
    var src = getFileExtension(value);
    if (src == "") {
//        alert('올바른 파일을 입력하세요');
fileClear(obj);
        return;
    } else if ( !((src.toLowerCase() == "gif") || (src.toLowerCase() == "jpg") || (src.toLowerCase() == "jpeg")) ) {
        alert('gif 와 jpg 파일만 지원합니다.');
fileClear(obj);
        return;
    }

    LoadImg( obj);

}
function LoadImg(obj)
{
var value = obj.value;
    var imgInfo = new Image();
//    imgInfo.onload = img_Load;
    imgInfo.src = value;
var imgWidth = imgInfo.width;
var imgHeight = imgInfo.height;
if(imgWidth != maxImageWidth || imgHeight != maxImageHeight){
alert(maxImageWidth+"*"+maxImageHeight+"파일만 지원합니다");
fileClear(obj);
return false;
}
}

[Javascript] input type=file 값 초기화

<input type=file name=aaa>

function fileClear(obj){
obj.select();
document.selection.clear();
obj.blur();
}

폼 기본값 넣기

$(document).ready(function() {
   $('input[type=text]').focus(function() {
      if($(this).val() == $(this).attr('defaultValue')) {
         $(this).val('');
      }
   })
   .blur(function() {
      if($(this).val().length == 0) {
         $(this).val($(this).attr('defaultValue'));
      }
   });
});

위와 같은 코드를 넣어 주고.. 아래와 같은 코드를 사용하시면됨..

<input type="text" value="입력해주세요." />

disable/enable 전환



$(selector).disable(), $(selector).enable()

2010년 9월 15일 수요일

2010년 9월 14일 화요일

SELECT 값 유지하는 방법

게시판에서 검색기능 등을 사용할때..

<SELECT>
     <OPTION>제목</OPTION>
     <OPTION>내용</OPTION>
     <OPTION>제목+내용</OPTION>
</SELECT>

SELECT값을 계속 유지하고 싶을때 사용..

$("#kind > option[value='선택한값']").attr("selected","selected");

[clockpick]시간 설정

<link rel="stylesheet" href="/inc/css/jquery.clockpick.1.2.7.css" type="text/css">
<script type="text/javascript" src="/inc/js/jquery.clockpick.1.2.7.js"></script>

        $("#viewTime").clockpick();
        $(".clockpick").clockpick({
            valuefield : 'viewTime'
            });

참고 : http://www.oakcitygraphics.com/jquery/clockpick/trunk/ClockPick.cfm

JQuery Link

--JQuery 관련 링크 모음 (얼마나 될지 모름..)
출처 : http://www.cyworld.com/mengwi/2741267
jQuery Grid Plugin (***) : 게시판에서 정렬과 게시판 펼치기 접기 등의 기능을 도와주는 플러그인http://www.trirand.com/blog/?page_id=6 
 
그리드 (*) : 전체 페이징을 하지 않는 Ajax 게시판http://www.reconstrukt.com/ingrid/example2.html

 
 
팬시박스 (**) : 이미지 팝업창에 모달효과 약간의 에니메이션이 들어감.http://fancy.klade.lv/ (****)
예제 : http://fancy.klade.lv/example
 
jQuery Lightbox Plugin (balupton edition) (**) : 이미지 모달 팝업http://www.balupton.com/sandbox/jquery_lightbox/
 
imagebox : 이미지 모달 팝업http://www.intelliance.fr/jquery/imagebox/
 
이미지 회전 :  이미지의 회전이 가능하게 한다.
http://www.piksite.com/mRotate/mRotate.html
 
jQuery sliding gallery demo : 이미지 애니메이션 슬라이드 http://phplug.net/components/javascript/jquery-gallery.html
 
이미지 슬라이딩 : 좌 우로 움직임http://www.maxb.net/scripts/ycodaslider-2.0/include/demo/#10
 
이미지 공간감 효과 (***)  :  여러 이미지를 레이어 겹쳐 놓음으로써 3D 효과를 준다. 
http://webdev.stephband.info/parallax.html
 
디자이너를 위한 jquery (**) : 태그 조작과 에니메이션 효과와 관련된 사이트http://www.webdesignerwall.com/demo/jquery/(****)
 AutoScroll (*) : 컨트롤 키 누른 채로 mouse 움직였을 때, 자동 스크롤이 가능하게끔http://jdsharp.us/jQuery/plugins/AutoScroll/demo.php (****)
 drag and drop (*) : 드래그 드랍 예제http://host.sonspring.com/dragdrop/ (***)
 
JQuery 예제 모음 사이트 (*****) 
http://www.ajaxrain.com/tag?tag=jquery 
 컬럭 Picker (****)  :  PhotoShop의 색 선택 기능이 가능.http://www.intelliance.fr/jquery/color_picker/

 jQuery MultiSelect (**) : custom 셀렉트 박스, 셀렉트 박스에 체크박스가 추가 되어 여러개를 선택 가능한 박스.http://abeautifulsite.net/notebook_files/62/demo/jqueryMultiSelect.html

 "jQuery checkbox v.1.0.0" demo (**)  : custom 디자인 체크박스http://widowmaker.kiev.ua/checkbox/
 
jQuery Treeview Plugin Demo (**) : 트리 컨트롤러 1
http://jquery.bassistance.de/treeview/demo/
 
jQuery File Tree Demo (***) : JQuery 트리 컨트롤로 2http://abeautifulsite.net/notebook_files/58/demo/
 
jQuery columnManager plugin (*) : 테이블의 컬럼을 추가 삭제등의 기능 제공http://p.sohei.org/stuff/jquery/columnmanager/demo/demo.html
jQuery AIR (***) : ajax를 이용한 항공 좌석 예약.http://www.digital-web.com/extras/jquery_crash_course/
Masked Input Plugin (**) : 입력상자에 exel과 같은 서식 적용.http://digitalbush.com/projects/masked-input-plugin

Watermark Input Plugin (*): 입력상자에 워터마크 표시http://digitalbush.com/projects/watermark-input-plugin
 
ClockPick (***): 입력상자에 시간을 선택해서 넣을 수 있다.http://www.oakcitygraphics.com/jquery/clockpick/trunk/ClockPick.cfm
chart : JQuery를 이용한 차트 http://www.reach1to1.com/sandbox/jquery/jqchart/

 
달력 http://tedserbinski.com/jcalendar/index.html#demo
 
3D로테이션 : 글자들이 xy 좌표에서 3D효과로 회전함.http://www.willjessup.com/sandbox/jquery/rotator/rotator.html
스크롤중 데이터가져오기 : http://www.webresourcesdepot.com/dnspinger/http://www.webresourcesdepot.com/load-content-while-scrolling-with-jquery/
Query Flash Plugin - Basic Example : flash 삽입 플러그인http://jquery.lukelutman.com/plugins/flash/example-basic.html
 jquery combobox demo : custom 콤보박스 ie 7.0으로 보면 깨져나온다.
http://jquery.sanchezsalvador.com/samples/example.htm
scrollable table : 테이블에 스크롤바가 붙어있다-_-;;http://www.webtoolkit.info/demo/jquery/scrollable/demo.html
 
accordion-madnesshttp://www.learningjquery.com/2007/03/accordion-madness
 
jQuery Multimedia Portfoliohttp://www.openstudio.fr/jquery/
 
체크박스 이동http://sanisoft-demo.com/jquery/plugins/shiftcheckbox/demo.html
위지윅에디터http://projects.bundleweb.com.ar/jWYSIWYG/
크랍http://remysharp.com/2007/03/19/a-few-more-jquery-plugins-crop-labelover-and-pluck/#crop
슬라이딩 퍼즐http://www.bennadel.com/blog/1009-jQuery-Demo-Creating-A-Sliding-Image-Puzzle-Plug-In.htm
 
날짜픽업http://kelvinluck.com/assets/jquery/datePicker/v2/demo/
레이팅http://php.scripts.psu.edu/rja171/widgets/rating.php
JQuery Curvy Corners Demo pagehttp://blue-anvil.com/jquerycurvycorners/test.html
 
줌http://www.mind-projects.it/blog/jqzoom_v10
 
LavaLamp for jQuery lovers!http://gmarwaha.com/blog/?cat=8
 
컬러http://www.jnathanson.com/blog/client/jquery/heatcolor/index.cfm#examples
 
비쥬얼 쿼리http://visualjquery.com/1.1.2.html
 
jQuery "Highlight" Demohttp://www.keyframesandcode.com/resources/javascript/jQuery/demos/highlight-demo.html
 
 
Hot Key Testinghttp://jshotkeys.googlepages.com/test-static.html
 
 
accordion menuhttp://www.i-marco.nl/weblog/jquery-accordion-menu-redux/
 
jQuery easyThumbhttp://www.hverven.net/div/easyThumb/
갤러리http://www.flyerstop.ca/ui/apps/gallery_advanced/
 
thickboxhttp://jquery.com/demo/thickbox/
 
마우스휠 플러그인http://www.ogonek.net/mousewheel/jquery-demo.htmlhttp://www.ogonek.net/mousewheel/demo.html
휴먼메세지http://binarybonsai.com/misc/humanmsg/
 
jQuery - LinkedSelecthttp://www.msxhost.com/jquery/linked-selects/json/
 
jQuery » iFrame Sizing http://host.sonspring.com/iframe/
jQuery for Designers - Ajax Form Validation Examplehttp://jqueryfordesigners.com/demo/ajax-validation.php
폰트크기 바꾸기http://www.lllcolor.com/jQuery/demo/demo01b.html
dimensionhttp://brandonaaron.net/docs/dimensions/#code-samples
portlet 데모http://www.rymix.co.uk/jquery/d15/sortables2.html
FX데모http://magalies.net/downloads/Jquery/Interface%20examples/demos/ifx.html#pulsate-fx
오픈윈도우http://magalies.net/downloads/Jquery/Interface%20examples/demos/windows.html
JQuery tricks: using Greybox + form plugin for a modal dialog boxhttp://corky.net/dotan/programming/jquery.dialog/dialog-demo.html
 
FaceBoox style autosuggest with jQueryhttp://web2ajax.fr/examples/facebook_searchengine/
Auto-Growing Textarea Demohttp://www.aclevercookie.com/demos/autogrow_textarea.html
jQuery Helper for Komodo Media CSS Star Rater (Redux)http://www.m3nt0r.de/devel/raterDemo/
에디터http://avidansoft.com/dsrte/
 
jQuery Keyboard Navigation Pluginhttp://amountaintop.com/project/keynav/
텝http://jqueryfordesigners.com/demo/tabs.html
jQuery AccessKey Demohttp://methvin.com/jquery/jq-access.html
Semi-transparent rollover effect using jQueryhttp://coderseye.com/files/demos/pngrollover/index.html
Revealing Photo Sliderhttp://css-tricks.com/examples/RevealingPhotoSlider/
Simple jQuery form validationhttp://www.willjessup.com/sandbox/jquery/form_validator/form_validate.html
after callback demohttp://jsdesigning.com/gal/gal.php?top=10&id_pic=9&id_album=2
 
갤러리http://devkick.com/lab/galleria/demo_01.htm#img/ladybug.jpg
 
SWF Uploadhttp://www.alexandremagno.net/blog/wp-content/uploads/swfupload/index.htm
jQuery gradient - Visual Testhttp://brandonaaron.net/jquery/plugins/gradient/test/
tEditable :: In place table editing for jQueryhttp://joshhundley.com/teditable/index.html
 
 
 
 
sorthttp://interface.eyecon.ro/demos/sort.html
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
http://geeknation.blinklist.com/tag/jQuery/
 
http://www.nalanta.com/node/7http://www.noupe.com/jquery/50-amazing-jquery-examples-part1.htmlhttp://www.blinklist.com/mungkey/jquery/
 
 
http://geekswithblogs.net/AzamSharp/archive/2008/02/21/119882.aspx
http://www.learningjquery.com/2006/12/multiple-fancy-drop-caps
http://www.trirand.com/blog/?page_id=5
 
http://people.iola.dk/olau/flot/examples/selection.html(챠트 선택)
http://www.mootools.net/dragdrop/
http://plugins.jquery.com/project/Plugins/category/21
 
http://mohamedshaiful.googlepages.com/add_remove_form.htm
http://www.chazzuka.com/Portofolio/
http://dev.jquery.com/view/tags/ui/1.5b2/demos/ui.sortable.html
 
 
http://hooney.net/code/2007/08/UnobtrusiveTabNav/tabNav03.html
http://jqueryfordesigners.com/coda-slider-effect/
http://benjaminsterling.com/jquery-jqgalview-photo-gallery/
http://www.mind-projects.it/blog/jqzoom_v10
http://www.reach1to1.com/sandbox/jquery/jqchart/
http://jquery.lukelutman.com/plugins/flash/
http://leandrovieira.com/projects/jquery/lightbox/
http://marcgrabanski.com/code/ui-datepicker/
http://www.noupe.com/ajax/37-more-shocking-jquery-plugins.html
http://www.webdesignerwall.com/demo/jquery/
http://www.gcmingati.net/wordpress/wp-content/lab/jquery/imagestrip/imageslide-plugin.html
http://cssglobe.com/post/1695/easiest-tooltip-and-image-preview-using-jquery
http://www.gcmingati.net/wordpress/wp-content/lab/jquery/imagestrip/imageslide-plugin.html
http://jquery.glyphix.com/
http://www.balupton.com/sandbox/jquery_lightbox/
챠트http://www.filamentgroup.com/lab/creating_accessible_charts_using_canvas_and_jquery/
http://sorgalla.com/projects/jcarousel/
http://designreviver.com/tutorials/jquery-examples-horizontal-accordion
http://host.sonspring.com/portlets/
http://www.webdesignerwall.com/tutorials/jquery-tutorials-for-designers/
http://www.digital-web.com/extras/jquery_crash_course/
 
http://www.blinklist.com/codearachnid/jquery/
http://drupalmodules.com/module/image-enhanced-scaling
http://www.ajaxdaddy.com/store
 
http://www.ajaxrain.com/tag.php?tag=image&page=2(모음)http://www.spicyexpress.net/general/jquerry-at-it-best-downloadable-jquerry-plugins-and-widgets-for-you-2/(예제모음)
http://mike.teczno.com/giant/pan/(pan)

2010년 3월 29일 월요일

Http Post 방식으로 header 설정 및 xml 데이터 전송

http post 방식으로 header를 설정한 후 xml 데이터를 서버에 전달 후

그 결과를 받는다.

첨부된 파일을 압축을 풀면 lib 디렉토리 안의 jar 파일들을

%CATALINA_HOME%\common\lib 에 위치시키거나

CALSSPASS를 잡아준 후 이용하면 된다.


<%@ page import="org.apache.commons.httpclient.HttpClient" %>
<%@ page import="org.apache.commons.httpclient.methods.PostMethod" %>
<%@ page import ="java.net.*" %>
<%@ page import ="java.io.*" %>

<%

    String orgMsg="abcdefg";
    String encMsg = null;
    String header1 = "header1";
    String header2 = "header2";
    String header3 = "header3";
    String ContentsType="text/xml";
    

    AES256 aes = new AES256();
    encMsg = aes.encrypt(msg);

      String xmldata = "<? xml version=\"1.0\" encoding=\"euc-kr\"?> "
                            +"<! DOCTYPE lgtpims:schema>"
                            +"<schema targetns=\"http://www.aaa.com\""
                    +"version=\"1.0\" xmlns=\"http://www.w3.org/2000/10/XMLSchema\">"
                        +"<parameter method=\"add\">"
                            +"<element-value name=\"addelement\">aaaaa</element-value>"
                            +"<element-value name=\"addelementtype\">bbbbb</element-value>"
                        +"</parameter>"
                    +"</schema>" ;

        String strURL = "http://www.aaa.com/aaa";
        PostMethod post = new PostMethod(strURL);
        post.setRequestHeader("Content-type", "text/xml; charset=ISO-8859-1");
        post.setRequestHeader("header1","header1");
        post.setRequestHeader("header2",header2);
        post.setRequestHeader("header3",header3");
        post.setRequestHeader("Content-Length",Integer.toString(xmldata.length()));
        post.setRequestBody(xmldata);

        HttpClient httpclient = new HttpClient();            

        try {
            int result = httpclient.executeMethod(post);
            // Display status code
            out.println("<br>Response status code: " + result);
            // Display response
             out.println("<br>Response header: "+post.getResponseHeader("Status-Line"));
            out.println("<br>Response body: ");
            out.println(post.getResponseBodyAsString());
        } finally {
            // Release current connection to the connection pool once you are done
            post.releaseConnection();
        }


%>

JAVA AES 256 암호화

aes256 암호화

import sun.misc.BASE64Encoder;
import sun.misc.BASE64Decoder;
 
import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.security.NoSuchAlgorithmException;
 
public class AES256 {
  public static SecretKeySpec getKeySpec() throws IOException, NoSuchAlgorithmException {
        byte[] bytes = new byte[32];
        SecretKey key = null;
        SecretKeySpec spec = null;
/* 
        File f = new File("aes_key");
        if (f.exists()) {
          new FileInputStream(f).read(bytes);
        } else {
           KeyGenerator kgen = KeyGenerator.getInstance("AES");
           kgen.init(256);
           key = kgen.generateKey();
           bytes1 = key.getEncoded();
           new FileOutputStream(f).write(bytes1);
        }
*/
        String keyStr="암호화된 대칭키";
        bytes = Base64Utils.base64Decode(keyStr);

        spec = new SecretKeySpec(bytes,"AES");
        return spec;
  }


  public String encrypt(String text) throws Exception {
        SecretKeySpec spec = getKeySpec();
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, spec);
        BASE64Encoder enc = new BASE64Encoder();

        return enc.encode(cipher.doFinal(text.getBytes())).toString();
  }
  public String decrypt(String text) throws Exception {
        SecretKeySpec spec = getKeySpec();
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, spec);
        BASE64Decoder dec = new BASE64Decoder();
        return new String(cipher.doFinal(dec.decodeBuffer(text)));
  }
  public static void main(String[] args) throws Exception {
        String mode = "encrypt";
        String text = "!mpluse0218";
        String encText = "";
        String decText = "";
        AES256 aes = new AES256();
        encText=aes.encrypt(text);
        System.out.println("5ClhQFro0UAI+LrZkilamw==");
          System.out.println("enc::"+encText);
        decText = aes.decrypt(encText);
        System.out.println("dec::"+decText);
  }
}

Base64Utils.java

AES 256암호화시 대칭키를 불러와서 암호화 하는데..암호화 결과가 자꾸 틀렸다..ㅡ_-;;

아놔..고민고민 끝에 암호화된 대칭키를 아래 모듈의 DECODE로 풀어서 넣었더니..되더라..음..


public class Base64Utils {
 
    private static byte[] mBase64EncMap, mBase64DecMap;
 
    /**
     * Class initializer. Initializes the Base64 alphabet (specified in RFC-2045).
     */
    static {
        byte[] base64Map = {
            (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F',
            (byte)'G', (byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L',
            (byte)'M', (byte)'N', (byte)'O', (byte)'P', (byte)'Q', (byte)'R',
            (byte)'S', (byte)'T', (byte)'U', (byte)'V', (byte)'W', (byte)'X',
            (byte)'Y', (byte)'Z',
            (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f',
            (byte)'g', (byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l',
            (byte)'m', (byte)'n', (byte)'o', (byte)'p', (byte)'q', (byte)'r',
            (byte)'s', (byte)'t', (byte)'u', (byte)'v', (byte)'w', (byte)'x',
            (byte)'y', (byte)'z',
            (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5',
            (byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'+', (byte)'/' };
        mBase64EncMap = base64Map;
        mBase64DecMap = new byte[128];
        for (int i=0; i<mBase64EncMap.length; i++)
            mBase64DecMap[mBase64EncMap[i]] = (byte) i;
    }
 
    /**
     * This class isn't meant to be instantiated.
     */
    private Base64Utils() {
    }
 
    /**
     * Encodes the given byte[] using the Base64-encoding,
     * as specified in RFC-2045 (Section 6.8).
     *
     * @param aData the data to be encoded
     * @return the Base64-encoded <var>aData</var>
     * @exception IllegalArgumentException if NULL or empty array is passed
     */
    public static String base64Encode(byte[] aData) {
        if ((aData == null) || (aData.length == 0))
            throw new IllegalArgumentException("Can not encode NULL or empty byte array.");
 
        byte encodedBuf[] = new byte[((aData.length+2)/3)*4];
 
        // 3-byte to 4-byte conversion
        int srcIndex, destIndex;
        for (srcIndex=0, destIndex=0; srcIndex < aData.length-2; srcIndex += 3) {
            encodedBuf[destIndex++] = mBase64EncMap[(aData[srcIndex] >>> 2) & 077];
            encodedBuf[destIndex++] = mBase64EncMap[(aData[srcIndex+1] >>> 4) & 017 |
                        (aData[srcIndex] << 4) & 077];
            encodedBuf[destIndex++] = mBase64EncMap[(aData[srcIndex+2] >>> 6) & 003 |
                        (aData[srcIndex+1] << 2) & 077];
            encodedBuf[destIndex++] = mBase64EncMap[aData[srcIndex+2] & 077];
        }
 
        // Convert the last 1 or 2 bytes
        if (srcIndex < aData.length) {
            encodedBuf[destIndex++] = mBase64EncMap[(aData[srcIndex] >>> 2) & 077];
            if (srcIndex < aData.length-1) {
                encodedBuf[destIndex++] = mBase64EncMap[(aData[srcIndex+1] >>> 4) & 017 |
                    (aData[srcIndex] << 4) & 077];
                encodedBuf[destIndex++] = mBase64EncMap[(aData[srcIndex+1] << 2) & 077];
            }
            else {
                encodedBuf[destIndex++] = mBase64EncMap[(aData[srcIndex] << 4) & 077];
            }
        }
 
        // Add padding to the end of encoded data
        while (destIndex < encodedBuf.length) {
            encodedBuf[destIndex] = (byte) '=';
            destIndex++;
        }
 
        String result = new String(encodedBuf);
        return result;
    }
 
 
    /**
     * Decodes the given Base64-encoded data,
     * as specified in RFC-2045 (Section 6.8).
     *
     * @param aData the Base64-encoded aData.
     * @return the decoded <var>aData</var>.
     * @exception IllegalArgumentException if NULL or empty data is passed
     */
    public static byte[] base64Decode(String aData) {
        if ((aData == null) || (aData.length() == 0))
            throw new IllegalArgumentException("Can not decode NULL or empty string.");
 
        byte[] data = aData.getBytes();
 
        // Skip padding from the end of encoded data
        int tail = data.length;
        while (data[tail-1] == '=')
            tail--;
 
        byte decodedBuf[] = new byte[tail - data.length/4];
 
        // ASCII-printable to 0-63 conversion
        for (int i = 0; i < data.length; i++)
            data[i] = mBase64DecMap[data[i]];
 
        // 4-byte to 3-byte conversion
        int srcIndex, destIndex;
        for (srcIndex = 0, destIndex=0; destIndex < decodedBuf.length-2;
                srcIndex += 4, destIndex += 3) {
            decodedBuf[destIndex] = (byte) ( ((data[srcIndex] << 2) & 255) |
                ((data[srcIndex+1] >>> 4) & 003) );
            decodedBuf[destIndex+1] = (byte) ( ((data[srcIndex+1] << 4) & 255) |
                ((data[srcIndex+2] >>> 2) & 017) );
            decodedBuf[destIndex+2] = (byte) ( ((data[srcIndex+2] << 6) & 255) |
                (data[srcIndex+3] & 077) );
        }
 
        // Handle last 1 or 2 bytes
        if (destIndex < decodedBuf.length)
            decodedBuf[destIndex] = (byte) ( ((data[srcIndex] << 2) & 255) |
                ((data[srcIndex+1] >>> 4) & 003) );
        if (++destIndex < decodedBuf.length)
            decodedBuf[destIndex] = (byte) ( ((data[srcIndex+1] << 4) & 255) |
                ((data[srcIndex+2] >>> 2) & 017) );
 
        return decodedBuf;
    }
 
}

AES 256 암호화 오류


JDK1.4 : java.lang.SecurityException : UnSupported keysize or algorithm parameters

JDK1.5 :  java.security.InvalidKeyException: Illegal key size or default parameters

첨부된 압축파일을 풀어서 local_policy.jar, US_export_policy.jar 파일을

%JAVA_HOME%\jre\lib\security 안에 복사하면 된다.

아..무진장 헤맸다..이것때문에..ㅡ_-;;

이 글을 포스팅 해 놓은 원문의 블로거님께 감사드립니다..(__);

[원문 : http://blog.naver.com/kimsumin75/20053382618]

2010년 3월 18일 목요일

AJAX이용한 XML 데이터 전송 및 전송된 XML 데이터 받기

1.xmlPostClient.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>Insert title here</title>
<script type="text/javascript">
    var xmlHttp;
    function createXMLHttpRequest(){
        if(window.ActiveXObject){
            xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
        }else if(window.XMLHttpRequest){
            xmlHttp=new XMLHttpRequest();
        }
    }
    function sendXML(){
        createXMLHttpRequest();

        var xml="<VCOUPON><TEL_NO>0101234567</TEL_NO><AMOUNT>1000</AMOUNT><RETURNCODE>00</RETURNCODE></VCOUPON>";
        var url="http://localhost:8080/test/httpPostServer.jsp";
        xmlHttp.open("POST",url,true);
        xmlHttp.onreadystatechange=handleStateChange;
        xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded;");
        xmlHttp.setRequestHeader("aaa","aaa");
        xmlHttp.setRequestHeader("bbb","bbb");
        xmlHttp.send(xml);
    }

    function handleStateChange(){
        if(xmlHttp.readyState==4){
            if(xmlHttp.status==200){
                parseResults();
            }
        }
    }

    function parseResults(){
        var responseDiv=document.getElementById("response");
        if(responseDiv.hasChildNodes()){
            responseDiv.removeChild(responseDiv.childNodex[0]);
        }
        var responseText = document.createTextNode(xmlHttp.responseText);
        responseDiv.appendChild(responseText);
    }
</script>
</head>
<body>
<input type="button" value="보내기" onClick="sendXML();"><br>
<div id="response">

</div>
</body>
</html>

2.xmlPostServer.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%@ page import = "java.io.*" %>
<%@ page import = "javax.xml.parsers.DocumentBuilderFactory" %>
<%@ page import = "javax.xml.parsers.ParserConfigurationException" %>
<%@ page import = "org.w3c.dom.Document" %>
<%@ page import = "org.w3c.dom.NodeList" %>
<%@ page import = "org.xml.sax.SAXException" %>

<%!
    public String readXMLFromRequestBody(HttpServletRequest request){
        StringBuffer xml = new StringBuffer();
        String line = null;
        try{
            BufferedReader reader = request.getReader();
            while((line=reader.readLine())!=null){
                xml.append(line);
            }
        }catch(Exception e){
            System.out.println("Error reading XML:"+e.toString());
        }
        return xml.toString();
    }
%>
<%
    String xml=readXMLFromRequestBody(request);
    Document xmlDoc = null;
    try{
        xmlDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new ByteArrayInputStream(xml.getBytes()));
    }catch(ParserConfigurationException e){
        System.out.println("ParserConfigurationException : "+e);
    }catch(SAXException e){
        System.out.println("SAXException : "+e);
    }
    System.out.println("header aaa : "+request.getHeader("aaa"));
    System.out.println("header bbb : "+request.getHeader("bbb"));
    NodeList TEL_NO = xmlDoc.getElementsByTagName("TEL_NO");
    NodeList AMOUNT = xmlDoc.getElementsByTagName("AMOUNT");
    NodeList RETURNCODE = xmlDoc.getElementsByTagName("RETURNCODE");
    String telno = null;
    String amount = null;
    String returncode = null;
    String responseText = "request text : ";
    for(int i = 0; i < TEL_NO.getLength();i++){
        telno = TEL_NO.item(i).getFirstChild().getNodeValue();
        responseText = responseText+"TEL_NO : "+telno;
    }
    for(int i = 0; i < AMOUNT.getLength();i++){
        amount = AMOUNT.item(i).getFirstChild().getNodeValue();
        responseText = responseText+"AMOUNT : "+amount;
    }
    for(int i = 0; i < RETURNCODE.getLength();i++){
        returncode = RETURNCODE.item(i).getFirstChild().getNodeValue();
        responseText = responseText+"RETURNCODE : "+returncode;
    }   
   
    response.setContentType("text/xml");
    out.print(responseText);
%>

2010년 2월 23일 화요일

javascript 레이어 화면 따라다니기.

    function staticize(){
        var scontentmain = document.getElementById("divID");
        w2=document.documentElement.scrollLeft+150;
        scontentmain.style.left=w2;      //화면 가로로 따라다니기..
//        scontentmain.style.top=h2;   // 화면 세로로 따라다니기...
    }
    window.onscroll=staticize;

2010년 2월 3일 수요일

JSP 스트럿츠

[펌]원문 : http://sugame.tistory.com/273?srchid=BR1http%3A%2F%2Fsugame.tistory.com%2F273


<c:set var="${str}" scope="page">테스트</c:set>
<c:out value="하하하${str}" />


<%
member.setName("테스트");
member.setAge(30);
%>

<!-- 변수 선언 -->
<c:set var="str1" scope="page">는 학생입니다.</c:set>

<c:set var="str2" scope="page" value="는 회사원입니다." />


<!-- 출력문 -->
<c:out value="<b>${member.name}</b>${str1}" escapeXml="false" /><br>

<c:out value="${member.name}${str2}" /><br>


<!-- 빈 클래스에 값 넣기 -->
<c:set target="${member}" property="name">안닝하세요!!!</c:set>

<c:set target="${member}" property="name" value="hello!!" />

<c:out value="${member.name}" />

 


<c:set var="str1" value="${member.name}" />

<c:set target="${member}" property="name">오리!!</c:set>

<c:out value="${str1}" />

 

 

 

<%@ page language="java" contentType="text/html; charset=EUC-KR" pageEncoding="EUC-KR"%>
<%@ taglib uri="/WEB-INF/tld/struts-bean.tld" prefix="bean" %>
<%@ taglib uri="/WEB-INF/tld/struts-logic.tld" prefix="logic" %>
<%@ taglib uri="/WEB-INF/tld/struts-html.tld" prefix="html" %>
<%@ taglib uri="/WEB-INF/tld/c.tld" prefix="c" %>

<jsp:useBean id="member" class="com.test.CMember">
<jsp:setProperty name="member" property="*" />
</jsp:useBean>


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>스트럿츠 태그 라이브러리 테스트1</title>
</head>
<body>

 <!-- dan 파라메터가 없을 경우 -->
<logic:notPresent parameter="dan">
  <b>오류!! dan 파라메터가 null입니다.</b>
</logic:notPresent>

<logic:present parameter="dan">
  <!-- dan 파라메터에 값이 없을 경우 -->
  <logic:equal parameter="dan" value="">
   <b>dan 파라메터에 출력할 구구단의 단(숫자)을 입력하세요</b>
  </logic:equal>

 
  <logic:notEqual parameter="dan" value="">
 
   <c:set var="dan" value="<%= request.getParameter("dan") %>" />
   <c:if test="${dan > 0 and dan <= 99}">
    <c:out value="${dan}"/> 단입니다. <br/>
   
    <table border=1>
    <c:forEach var="i" begin="1" end="9" step="1">
     <tr>
      <td><c:out value="${dan} * ${i} = ${dan*i}"/></td>
     </tr>
    </c:forEach>
    </table>
   </c:if>
   
   <!-- else if 문법이 없다. -->
   <c:if test="${not (dan > 0 and dan <= 99)}">
    <c:out value="1 ~ 99단까지만 출력 가능합니다."/>
   </c:if>
   
  </logic:notEqual> 

</logic:present>

</body>
</html>


 

<%@ page language="java" contentType="text/html; charset=EUC-KR" pageEncoding="EUC-KR"%>
<%@ page import = "java.util.Iterator" %>
<%@ taglib uri="/WEB-INF/tld/struts-bean.tld" prefix="bean" %>
<%@ taglib uri="/WEB-INF/tld/struts-logic.tld" prefix="logic" %>
<%@ taglib uri="/WEB-INF/tld/struts-html.tld" prefix="html" %>
<%@ taglib uri="/WEB-INF/tld/c.tld" prefix="c" %>

<jsp:useBean id="member" class="com.test.CMember">
<jsp:setProperty name="member" property="*" />
</jsp:useBean>

 

forEach를 이용해 리스트 꺼내오기

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>스트럿츠 태그 라이브러리 테스트1</title>
</head>
<body>
<table border="1">
<tr>
  <td>번호</td><td>이름</td><td>나이</td>
</tr>
<c:forEach var = "item" items = "${member.memberList}" varStatus = "num">
<tr>
  <td><c:out value="${num.count}"/></td>
  <td><c:out value="${item.name}"/></td>
  <td><c:out value="${item.age}"/></td>
</tr>
</c:forEach>
</table>

 
</body>
</html>




if문에 보면 새로운 val 옵션이 있으며 그곳에 식이 참인지 거짓인지 저장된다.
<c:set var="name">홍길동aa</c:set>

<c:if test="${name == '홍길동'}" var="result">
당신은 홍길동입니다.
</c:if>
<c:if test="${not result}">
당신은 홍길동이 아니고 <b>${name}</b> 이군요!!
</c:if>

 

switch문
<c:set var="age" value="25"/>

<c:choose>
<c:when test="${age < 10}">
  당신은 어린 아이군요!
</c:when>
<c:when test="${age < 20}">
    당신은 팔팔한 10대군요!
</c:when>
<c:when test="${age < 30}">
    당신은 건장한 20대군요!
</c:when>
<c:when test="${age < 40}">
    당신은 30대군요!!
</c:when>
<c:otherwise>
    당신은 40대 이상입니다.
</c:otherwise>
</c:choose>

 

-------------------------------------------------------------------------------- setTest1.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR" import="java.util.*"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<%-- Map 종류가 아닐 경우 --%>
<c:set var="userLevel" scope="session">
Sheriff, Bartender, Cowgirl
</c:set>

<%-- Map 종류일 때 --%>
<%
Hashtable user = new Hashtable();
session.setAttribute("user", user);
%>
<c:set target="${user}" scope="session" property="Level" value="king"></c:set>

<jsp:forward page="setTest2.jsp"/>

-------------------------------------------------------------------------------- setTest2.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<%-- Map 종류가 아닐 경우 --%>
<c:forEach var="content" items="${userLevel}">
userLevle : ${content} <br>
</c:forEach>

<%-- Map 종류일 때 --%>
Map에 세팅한  user Level : ${user.Level}

2010년 1월 20일 수요일

MSSQL 한주의 시작일, 마지막일 구하기

특정날짜의 해당 주의 시작날짜, 마지막 날짜 구하기

 

 

1. CONVERT(VARCHAR(10), CONVERT(DATETIME, 'YYYYMMDD')-DATEPART(DW, 'YYYYMMDD')+1, 121) // 시작 날짜

2. CONVERT(VARCHAR(10), CONVERT(DATETIME, 'YYYYMMDD')-DATEPART(DW, 'YYYYMMDD')+7, 121) // 마지막 날짜