public static int byteToInt(byte[] src) {

        int newValue = 0;

        newValue |= (((int)src[0])<<24)&0xFF000000;
        newValue |= (((int)src[1])<<16)&0xFF0000;
        newValue |= (((int)src[2])<<8)&0xFF00;
        newValue |= (((int)src[3]))&0xFF;

        DebugPrint.writeDebug("aaaa : " + newValue);
      
        return newValue;
}

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

[java] - 타입 변환  (0) 2010.06.30
[java] - 외부 프로그램 실행하기..  (0) 2010.06.29
[java] - int to byte array  (0) 2010.06.29
[java] - Big Endian to Little Endian  (0) 2010.06.29
[java] - Little Endian to Big Endian  (0) 2010.06.29
Posted by 짱가쟁이
public static byte[] intTobyte(int value) {
        byte[] bytes=new byte[4];
        bytes[0]=(byte)((value&0xFF000000)>>24);
        bytes[1]=(byte)((value&0x00FF0000)>>16);
        bytes[2]=(byte)((value&0x0000FF00)>>8);
        bytes[3]=(byte) (value&0x000000FF);


        return bytes;

}

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

[java] - 외부 프로그램 실행하기..  (0) 2010.06.29
[java] - byte array to int  (0) 2010.06.29
[java] - Big Endian to Little Endian  (0) 2010.06.29
[java] - Little Endian to Big Endian  (0) 2010.06.29
[java] - float to byte array  (1) 2010.06.29
Posted by 짱가쟁이
public static int swapLittleEndian(byte[] bytes) {
     
        int newValue = 0;
        newValue |= (((int)bytes[3])<<24)&0xFF000000;
        newValue |= (((int)bytes[2])<<16)&0xFF0000;
        newValue |= (((int)bytes[1])<<8)&0xFF00;
        newValue |= (((int)bytes[0]))&0xFF;


        return newValue;

}

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

[java] - byte array to int  (0) 2010.06.29
[java] - int to byte array  (0) 2010.06.29
[java] - Little Endian to Big Endian  (0) 2010.06.29
[java] - float to byte array  (1) 2010.06.29
[java] - byte array to float  (0) 2010.06.29
Posted by 짱가쟁이
public static int swapBigEndian(String args) {

        int value=Integer.parseInt(args);

        // all java integer is BIG-ENDIAN(network byte-order)
        byte[] bytes=new byte[4];
        bytes[3]=(byte)((value&0xFF000000)>>24);
        bytes[2]=(byte)((value&0x00FF0000)>>16);
        bytes[1]=(byte)((value&0x0000FF00)>>8);
        bytes[0]=(byte) (value&0x000000FF);


        int newValue = 0;
        newValue |= (((int)bytes[0])<<24)&0xFF000000;
        newValue |= (((int)bytes[1])<<16)&0xFF0000;
        newValue |= (((int)bytes[2])<<8)&0xFF00;
        newValue |= (((int)bytes[3]))&0xFF;

        return newValue;
}

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

[java] - int to byte array  (0) 2010.06.29
[java] - Big Endian to Little Endian  (0) 2010.06.29
[java] - float to byte array  (1) 2010.06.29
[java] - byte array to float  (0) 2010.06.29
[java] - byte array to short  (0) 2010.06.29
Posted by 짱가쟁이
public static byte[] float2bytes(float value) {
      
        byte[] array = new byte[4];
      
        int intBits=Float.floatToIntBits(value);
      
        array[0]=(byte)((intBits&0x000000ff)>>0);
        array[1]=(byte)((intBits&0x0000ff00)>>8);
        array[2]=(byte)((intBits&0x00ff0000)>>16);
        array[3]=(byte)((intBits&0xff000000)>>24);
      
        return array;
}

Posted by 짱가쟁이
public static float arr2float (byte[] arr, int start) {

            int i = 0;
            int len = 4;
            int cnt = 0;
            byte[] tmp = new byte[len];

            for (i = start; i < (start + len); i++) {
                  tmp[cnt] = arr[i];
                  cnt++;
            }

            int accum = 0;
            i = 0;
            for ( int shiftBy = 0; shiftBy < 32; shiftBy += 8 ) {
                  accum |= ( (long)( tmp[i] & 0xff ) ) << shiftBy;
                  i++;
            }
            return Float.intBitsToFloat(accum);
}    

Posted by 짱가쟁이
public static int byteToShort(byte[] bytes) {
     
            int newValue = 0;
            newValue |= (((int)bytes[0])<<8)&0xFF00;
            newValue |= (((int)bytes[1]))&0xFF;

            return newValue;
}

Posted by 짱가쟁이
- java web start로 app.를 배포하려고 함.
- Launcher.jar 로 묶을때 설정파일 및 이미지 등이 classpath내(jar 파일 안에)에 존재해야함.
- 이미지 초기화 하는 모듈("images/" 디렉토리에서 모든 파일을 읽어와서 이미지 파일만 초기화 시킴)에서 해당 디렉토리를 찾을 수 없다는 오류와 몇몇가지 문제가 발생됨.

 문제점
    - 디렉토리 디코딩 문제
    - eclipse로 개발할때와 jar로 묶었을때 바라보는 경로가 다름.

해결책
- eclipse로 개발시
        if (dirURL != null && dirURL.getProtocol().equals("file")) {
             /* A file path: easy enough */
             return new File(dirURL.toURI()).list();
        }

- jar로 묶었을때
        if (dirURL.getProtocol().equals("jar")) {

            // 해당 디렉토리 내 파일목록을 가져옴.

        }

사용방법(sample 참조)
try {
   // path 디렉토리내의 파일 리스트를 가져온다.
   String[] fineList = getResourceListing(this.getClass(), path);
} catch(Exception e) {
   e.printStackTrace();
}



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

[java] - byte array to float  (0) 2010.06.29
[java] - byte array to short  (0) 2010.06.29
[Reflection] - Value Object 로그 만들자  (0) 2010.06.28
[XML] - Pretty XML print  (0) 2010.06.28
[java] - 가변인자(??)  (0) 2010.06.28
Posted by 짱가쟁이
웹 서비스 작업을 하면서 아쉽지만 Request를 각 서비스별로 생성하게 되었다. 유연하게 Request 객체를 하나만 생성해서 작업하면 좋것지만, Http binding(GET) 을 지원해야 한다는 제약 사항 때문에 이래저래 귀찮은 일이 좀 생긴듯.

여 기서 하나.. 각 request 별 입력값을 로그로 남겨야 하는데.. 각 value object 에 toString()을 구현하기가 참 귀찮다는 것이다. 그래서 생각한 것이 reflection 을 이용해서 한번에 해결하자 라는 취지로 만들게 되었음.

public class Test {

    public String getRequestStringMethods(Object obj) {
  
        StringBuffer buffer = new StringBuffer();
      
        try {
            Class dymClass      = obj.getClass();
            Method[] methods = dymClass.getMethods();
          
            buffer.append(dymClass.getSimpleName());
            buffer.append(" : ");
            for(int i = 0;i<methods.length;i++) {
                String methodName = methods[i].getName();
                if("get".equals(methodName.substring(0, 3)) && !"getClass".equals(methodName)) {                
                    String value = (String)methods[i].invoke(obj, null);                  
                    buffer.append("[" + methodName.substring(3, 4).toLowerCase() + methodName.subSequence(4, methodName.length()) + "]");
                    buffer.append(":\"" + value + "\"");
                    buffer.append(" ");
                }
            }
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
      
        return buffer.toString();
    }
  
    public String getRequestStringFields(Object obj) {
      
        StringBuffer buffer = new StringBuffer();
      
        try {
            Class dymClass      = obj.getClass();
            Field[] fields      = dymClass.getDeclaredFields();
          
            buffer.append(dymClass.getSimpleName());
            buffer.append(" : ");
            for(int i = 0;i<fields.length;i++) {
                String methodName = "get" + fields[i].getName().substring(0, 1).toUpperCase() + fields[i].getName().substring(1, fields[i].getName().length());              
                Method method       = obj.getClass().getMethod(methodName, null);
                String value = (String)method.invoke(obj, null);                  
                buffer.append("[" + methodName.substring(3, 4).toLowerCase() + methodName.subSequence(4, methodName.length()) + "]");
                buffer.append(":\"" + value + "\"");
                buffer.append(" ");
            }
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
      
        return buffer.toString();
    }
  
    public static void main(String[] args) {
      
        TestVo vo = new TestVo();
        vo.setAge("33");
        vo.setId("service_01");
        vo.setMsg("message");
        vo.setName("bbaeggar");
        vo.setValue("value");
      
        vo.setValue1("value1");
        vo.setValue2("value2");
        vo.setValue3("value3");
        vo.setValue4("value4");
        vo.setValue5("value5");
        vo.setValue6("value6");
        vo.setValue7("value7");
        vo.setValue8("value8");
        vo.setValue9("value9");
        vo.setValue10("value10");
        System.out.println(new Test().getRequestStringFields(vo));
        System.out.println(new Test().getRequestStringMethods(vo));

    }
}

Result
TestVo : [id]:"service_01" [name]:"bbaeggar" [msg]:"message" [value]:"value" [age]:"33" [value1]:"value1" [value2]:"value2" [value3]:"value3" [value4]:"value4" [value5]:"value5" [value6]:"value6" [value7]:"value7" [value8]:"value8" [value9]:"value9" [value10]:"value10"

TestVo : [name]:"bbaeggar" [value]:"value" [id]:"service_01" [msg]:"message" [age]:"33" [value1]:"value1" [value2]:"value2" [value3]:"value3" [value4]:"value4" [value5]:"value5" [value6]:"value6" [value7]:"value7" [value8]:"value8" [value9]:"value9" [value10]:"value10"

getRequestStringFields() 메소드를 사용하면 필드를 선언한 순서대로 값을 가지고 온다.
getRequestStringMethods() 는 좀 멍청한 넘임.
Posted by 짱가쟁이
2010. 6. 28. 15:30
- http://archive.apache.org/dist/xml/xerces-j/
Xerces-J-bin.1.4.4.zip <- 다운로드

import org.apache.xml.serialize.OutputFormat;
import org.apache.xml.serialize.XMLSerializer;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;

public class XMLPrinter {

public String format(String unformattedXml) {
try {
final Document document = parseXmlFile(unformattedXml);

OutputFormat format = new OutputFormat(document);
format.setLineWidth(65);
format.setIndenting(true);
format.setIndent(2);
Writer out = new StringWriter();
XMLSerializer serializer = new XMLSerializer(out, format);
serializer.serialize(document);

return out.toString();
} catch (IOException e) {
throw new RuntimeException(e);
}
}

private Document parseXmlFile(String in) {
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource(new StringReader(in));
return db.parse(is);
} catch (ParserConfigurationException e) {
throw new RuntimeException(e);
} catch (SAXException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}

- xerces.jar 를 사용하다가 apache cxf 에서 참조하는 lib 랑 충돌이 발생. cast exception 어쩌구가 발생됨.

좀더 simple한 넘으로 찾음
import java.io.StringReader;
import java.io.StringWriter;

import javax.xml.transform.OutputKeys;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;



public static String prettyFormat(String input, int indent) {
try {
Source xmlInput = new StreamSource(new StringReader(input));
StringWriter stringWriter = new StringWriter();
StreamResult xmlOutput = new StreamResult(stringWriter);
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", String.valueOf(indent));
transformer.transform(xmlInput, xmlOutput);
return xmlOutput.getWriter().toString();
} catch (Exception e) {
throw new RuntimeException(e); // simple exception handling, please review it
}
}

public static String prettyFormat(String input) {
return prettyFormat(input, 2);
}


Posted by 짱가쟁이
이전버튼 1 2 3 이전버튼