Spring MVC로 작업중 입려된 파라미터 검증이 필요하면 공통 성질을 뽑아 aspect로 작업해도 괜찮을 듯 싶다. 공통 성질로는 파라미터 타입, 사이즈, 널체크 등이 있겠지만.. 우선은 널 체크만 작업해보자.


1. @annotation 생성

- 입력값이 필수인 필드명을 array로 받는 단순한 annotation을 생성하자.


사용예) 

@HPNullCheck(parameters={"name", "id", "password"})

public ModelAndView DEMO01(HttpServletRequest request, HttpServletResponse response) {

    ...............

}


@annotation 클래스)

import java.lang.annotation.ElementType;


import java.lang.annotation.Retention;

import java.lang.annotation.RetentionPolicy;

import java.lang.annotation.Target;


@Retention(RetentionPolicy.RUNTIME)

@Target(ElementType.METHOD)

public @interface HPNullCheck {


String[] parameters();

}


2. @annotation 구현 클래스

- Reflection 기능을 사용하여 @annotation 클래스 기능(널 체크)을 구현한다.


RequestFacade 처리)

- 요청 객체가 RequestFacade 이면 아래와 같이 처리한다.

public void requestFacadeNullCheck(RequestFacade request) throws BizException {

Method[] methods = delcaringClass.getMethods();

for(Method method : methods) {

if(method.getName().equals(methodName)) {

HPNullCheck hpNullCheck = (HPNullCheck) method.getAnnotation(HPNullCheck.class);

if(hpNullCheck != null) {

String[] parameters = hpNullCheck.parameters();        

                        if(parameters == null) return;

     

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

                          if(!parameters[i].equals("")) {

                  String value = request.getParameter(parameters[i]);        

                                    

                                    if(StringUtils.isEmpty(value)) {

                                        throw new BizException("ERO001", "["+parameters[i]+"] 값을 확인하세요.");

                                    }

                                }

    }

}

}

}

}


MultipartHttpServletRequest 처리)

- 요쳥 객체가 DefaultMultipartHttpServletRequest 이면 아래와 같이 처리한다.

public void defaultMultipartHttpServletRequestNullCheck(MultipartHttpServletRequest request) throws BizException {

Method[] methods = delcaringClass.getMethods();

for(Method method : methods) {

HPNullCheck hpNullCheck = (HPNullCheck) method.getAnnotation(HPNullCheck.class);

if(hpNullCheck != null) {

String[] parameters = hpNullCheck.parameters();        

if(parameters == null) return;

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

if(!parameters[i].equals("")) {

String value = request.getParameter(parameters[i]);        

if(StringUtils.isEmpty(value)) {

throw new BizException("ERO001", "["+parameters[i]+"] 값을 확인하세요.");

}

}

}

}

}

}


Aspect로 Controller 클래스의 메소드를 @Around로 걸고 요청객체의 타입에 따라 위와 같이 Reflect를 활용하여 처리한다.


Posted by 짱가쟁이

update A set

    value = '6'

from

table A,

    (select state, type from table where id = 231) B

where 

A.state = B.state

and A.type = B.type


업데이트 구문이 지랄 맞기는 하지만 서두 저 따위로 사용할 필요성이 있다. 쩌ㅃ~
Posted by 짱가쟁이
뭐... 요넘도 마찮가지로 byte array에서 ip4 header만 추출하는 넘임..

Ip4Header.java
- source ip, destination ip, protocol 을 추출

import org.jnetpcap.packet.format.FormatUtils;


public class Ip4Header {


public final static int TCP = 6;

public final static int UDP = 17;

String version;

int     headerLength;

String srcIP;

String dstIP;

int protocol;


public String getVersion() {

return version;

}

public int getHeaderLength() {

return headerLength;

}

public String getSrcIP() {

return srcIP;

}

public String getDstIP() {

return dstIP;

}

public int getProtocol() {

return protocol;

}


public boolean makeHeader(byte[] buf) {

try {

byte[] bTmp = new byte[1];

System.arraycopy(buf, 14, bTmp, 0, bTmp.length);

if(!"4".equals(StringUtil.ascii2hexstr(bTmp).substring(0, 1))) return false;

this.version = StringUtil.ascii2hexstr(bTmp).substring(0, 1);

this.headerLength = Integer.parseInt(StringUtil.ascii2hexstr(bTmp).substring(1, 2)) * 4;

byte[] protocol = new byte[1];

byte[] dstIP = new byte[4];

byte[] srcIP = new byte[4];

System.arraycopy(buf, 23, protocol, 0, protocol.length);

System.arraycopy(buf, 26, srcIP, 0, srcIP.length);

System.arraycopy(buf, 30, dstIP, 0, dstIP.length);

this.protocol = protocol[0];

this.srcIP = FormatUtils.ip(srcIP);

this.dstIP = FormatUtils.ip(dstIP);

return true;

} catch(Exception e) {

e.printStackTrace();

return false;

}

}

}



캡쳐된 패킷 버퍼를 byte[] 로 전환해서 위 클래스에 할당하면 알아서 추출해준다.
byte[] dst = new byte[buffer.capacity()];
buffer.get(dst); 

 
Posted by 짱가쟁이

pcap lib 로 수집된 패킷을 mac address로 필터링을 하려고 하는데.. 이넘의 거지 같은 pcap lib가 thread에 안전하지 않더란 말이쥐.. 더럽게도 다중 쓰레드에서는 각 클래스에 스캔을 뜨는 이 편한 방법을 못쓰고 직접 바이트를 파싱해야 한다능..

그래서 필요한 넘만 직접 파싱해서 하나 만들었다.

EthernetHeader.java
- 패킷을 byte[]로 받아서 source mac, destination mac, type을 추출한다.

public class EthernetHeader {

public final static String IP = "0800";

byte[] srcMac = new byte[6];

byte[] dstMac = new byte[6];

byte[] type = new byte[2];

public byte[] getDstMac() {

return dstMac;

}


public byte[] getSrcMac() {

return srcMac;

}


public byte[] getType() {

return type;

}


public boolean makeHeader(byte[] buf) {

try {

System.arraycopy(buf, 0, dstMac, 0, dstMac.length);

System.arraycopy(buf, 6, srcMac, 0, srcMac.length);

System.arraycopy(buf, 12, type, 0, type.length);

return true;

} catch(Exception e) {

return false;

}

}

public boolean isIp() {

return IP.equals(StringUtil.ascii2hexstr(type));

}

}


 위 코드의 type이라는 넘은 하위 프로토콜의 타입을 의미하며 내는 IP 프로토콜만 사용했기 때문에 위처럼 고정해서 사용했음.

 

ByteBufferHandler 사용해서 패킷 캡쳐하는 부분
 

@Override

public void nextPacket(PcapHeader header, ByteBuffer buffer, Object arg2) {

try {

PcapDumper dumper = (PcapDumper) arg2;

    byte[] dst = new byte[buffer.capacity()];

    buffer.get(dst);

    EthernetHeader ethernetHeader = new EthernetHeader();

    if(!ethernetHeader.makeHeader(dst)) return;

    if(ethernetHeader.isIp()) { // IP 프로토콜

// packet 내의 시간 값 읽어 온다.

String timestampString = JNetPcapUtil.makeTimestampString("yyyyMMddHHmmssSSS", new Date(header.timestampInMillis()));
................
.......... 

 
뭐.. jNetpcap을 사용하면 편하게 패킷을 캡쳐할 수 있고, 필터링 할 수 있지만.. 다중 쓰레드에 안전하지 않다는 것임.
뭐 추후 버전은 concurrency에 안전하게 나올지 모르지만 현재 버전에서는 어쩔 수 없이 편한 방법을 사용하지 못하고 이렇듯 무식하게 직접 파싱을 해줘야 한다. 쩌ㅃ~





 

'framework > jNetPcap' 카테고리의 다른 글

[jnetpcap] - byte[] 에서 ip4 header 추출하기  (2) 2012.02.13
Posted by 짱가쟁이

블러킹 우선순위 큐를 만들어야 하는 상황이 발생. 직접 구현해야 하나 고민 하다 java concurrent 부분을 뒤적이니 좋은 놈이 있더라.

 PriorityBlockingQueue <- 임마를 기본으로 제공해주니.. 좋더란 말이쥐..

 간단한 사용 샘플을 올린다. 

PriorityBlockingJobQueue.java
- 별거 없이  PriorityBlockingQueue  임마를 싱글톤 패턴으로 래핑한 클래스

package queue;


import java.util.concurrent.PriorityBlockingQueue;


public class PriorityBlockingJobQueue {

final static PriorityBlockingJobQueue instance = new PriorityBlockingJobQueue();

PriorityBlockingQueue<PriorityJob> queue = new PriorityBlockingQueue<PriorityJob>(10, new CompareDescending());

public static PriorityBlockingJobQueue getInstance() {

return instance;

}

public void put(PriorityJob job){

queue.put(job);

}

public PriorityJob take() {

try {

return (PriorityJob) queue.take();

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

return null;

}

}

 

CompareDescending.java
- 내림차순으로 정렬 클래스

package queue;


import java.util.Comparator;


public class CompareDescending implements Comparator<PriorityJob>{


@Override

public int compare(PriorityJob o1, PriorityJob o2) {

return o2.getPriority().compareTo(o1.getPriority());

}


}

 

PriorityJob.java
- 우선순위 Job 클래스

package queue;


public class PriorityJob {


String priority; // 우선순위

Object job; // Job

public String getPriority() {

return priority;

}

public void setPriority(String priority) {

this.priority = priority;

}

public Object getJob() {

return job;

}

public void setJob(Object job) {

this.job = job;

}

}


 

PriorityBlockingQueueTest.java
- 테스트 클래스

package queue;


public class PriorityBlockingQueueTest {


public void excute() {

PriorityJob job1 = new PriorityJob();

job1.setPriority("1");

job1.setJob("1");

PriorityBlockingJobQueue.getInstance().put(job1);

PriorityJob job2 = new PriorityJob();

job2.setPriority("0");

job2.setJob("0");

PriorityBlockingJobQueue.getInstance().put(job2);

PriorityJob job3 = new PriorityJob();

job3.setPriority("3");

job3.setJob("3");

PriorityBlockingJobQueue.getInstance().put(job3);

PriorityJob job4 = new PriorityJob();

job4.setPriority("1");

job4.setJob("1");

PriorityBlockingJobQueue.getInstance().put(job4);

PriorityJob job5 = new PriorityJob();

job5.setPriority("5");

job5.setJob("5");

PriorityBlockingJobQueue.getInstance().put(job5);

PriorityJob job6 = new PriorityJob();

job6.setPriority("0");

job6.setJob("0");

PriorityBlockingJobQueue.getInstance().put(job6);

while(true) {

System.out.println(PriorityBlockingJobQueue.getInstance().take().getJob());

}

}

public static void main(String[] args) {

new PriorityBlockingQueueTest().excute();

}

}

 

결과 출력

5

3

1

1

0

0

 

Posted by 짱가쟁이

오류
 - java.security.InvalidKeyException: Illegal key size



AES 에서 256비트 키를 사용할 시 키 사이즈가 맞지 않다는 오류가 발생하면 아래와 같이 해결하면 된다.

http://www.oracle.com/technetwork/java/javase/downloads/index.html

위 경로에서 JDK 버전에 맞는 파일을 다운로드 받아 압축을 풀면 2개의 파일이 있다.

Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files 7
 

Local_policy.jar 

US_export_policy.jar


2개의 파일을 

경로 : %JAVA_HOME%\jre\lib\security 폴더에 복사

 위와 같이 파일을 해당 폴더에 복사하면 256비트 키를 사용할 수 있다.


 

'java > etc' 카테고리의 다른 글

Domain name to ip address  (0) 2012.05.15
[URL] - FTP 접속 URL  (0) 2012.05.15
[etc] - 테스트 유형  (0) 2010.12.21
[JavaService] - 자바 데몬 서비스 등록하자  (0) 2010.09.29
[jar] - JAR에 대해 모르고 있던 5가지 사항(??)  (0) 2010.08.31
Posted by 짱가쟁이

문자열 압축

public static byte[] compress(String src) throws IOException {

byte[] dataByte = src.getBytes();

Deflater deflater = new Deflater();

deflater.setLevel(Deflater.BEST_COMPRESSION);

deflater.setInput(dataByte);

deflater.finish();

ByteArrayOutputStream bao = new ByteArrayOutputStream(dataByte.length);

byte[] buf = new byte[1024];

while(!deflater.finished()) {

int compByte = deflater.deflate(buf);

bao.write(buf, 0, compByte);

}

bao.close();

deflater.end();

return bao.toByteArray();

}



문자열 압축 풀기

public static byte[] decompress(byte[] data) throws IOException, DataFormatException {

Inflater inflater = new Inflater();

inflater.setInput(data);

ByteArrayOutputStream bao = new ByteArrayOutputStream();

byte[] buf = new byte[1024];

while(!inflater.finished()) {

int compByte = inflater.inflate(buf);

bao.write(buf, 0, compByte);

}

bao.close();

inflater.end();


return bao.toByteArray();

}





'java > util' 카테고리의 다른 글

[정규식] - 핸드폰 번호 포맷 변경  (0) 2013.01.02
[util] - 특정 디렉토리 파일 목록 출력하자.  (0) 2011.06.17
[InputStream] - String to InputStream  (1) 2010.10.13
[util] - byte to hex string  (0) 2010.09.07
[java] - replaceNull  (0) 2010.07.05
Posted by 짱가쟁이

multipart/form-data로 파일 업로드 하자.

서버

interface

@POST

@Path("/TEST02")

@Consumes("multipart/form-data")

void TEST02(MultipartBody body) throws BizException;


implement

public void TEST02(MultipartBody body) throws BizException {


File file = null;

try {

file = FileUtil.makeFile(body.getAttachment("testFile").getDataHandler().getInputStream()

"D:/upload", body.getAttachmentObject("fileName", String.class) );

} catch (IOException e) {

e.printStackTrace();

}

}


 
inputStrem을 파일로 떨궈주면 땡.. 



클라이언트

public static void excute_post1(String url) throws ClientProtocolException, IOException {

    HttpClient httpclient = new DefaultHttpClient();

    HttpPost httppost = new HttpPost(url);

    httppost.setHeader("content", "multipart/form-data");

    httppost.addHeader("Accept", "application/json; charset=UTF-8" );

        

    FileBody filebody = new FileBody(new File("D:\\test.txt"));


    MultipartEntity reqEntity = new MultipartEntity();

    reqEntity.addPart("testFile", filebody);

    reqEntity.addPart("fileName", new StringBody("aaaa.txt"));

    httppost.setEntity(reqEntity);

    

    HttpResponse response = httpclient.execute(httppost);

    

    httppost.abort();    

    httpclient.getConnectionManager().shutdown();

}









Posted by 짱가쟁이

서버

@GET

@Path("/TEST01/{name}/{id}")

@Produces({"application/json", "application/xml"})

TEST01Res TEST01(@PathParam("name") String name, @PathParam("id") String id) throws BizException;

 
 @Produces({"application/json", "application/xml"}) 설정으로 응답값을 xml, json 스타일을 적용한다. 뭐 클라이언트는 원하는 스타일로 콜만 하면 됨.


클라이언트

 HttpGet httpget = new HttpGet(url);

 httpget.addHeader("Accept", "application/xml; charset=UTF-8" );

 
xml 요청 시
    - httpget.addHeader("Accept", "application/xml; charset=UTF-8" );
josn 요청 시  
    -   
httpget.addHeader("Accept", "application/json; charset=UTF-8" );
Posted by 짱가쟁이
2011. 7. 27. 14:41


'주아 > 사진' 카테고리의 다른 글

[주아] - 돌사진  (0) 2011.07.27
[주아] - 백일사진 추가  (0) 2010.08.03
[주아] - 백일  (3) 2010.07.31
[주아] - 땡깡쟁이  (0) 2010.07.19
[주아] -  (0) 2010.07.18
Posted by 짱가쟁이