JAVA2013. 9. 26. 18:31

출처-[http://tazz.tistory.com/30]

// 1. bad ( param null 일때 오류 발생)
if (param.equals("cust_id")) {}


// 2. good
if (param != null && param.equals("cust_id")) {}

// 3. good, too
if ("cust_id".equals(param)) {}

 

Posted by 선한열심
JAVA2013. 7. 19. 10:16
Posted by 선한열심
JAVA2013. 7. 16. 18:40

http://www.mopas.go.kr/gpms/ns/mogaha/user/userlayout/bulletin/userBtView.action?userBtBean.ctxCd=1002&userBtBean.ctxType=21010006&userBtBean.bbsSeq=1012662

 

행정기관등이 안전한 소프트웨어를 개발하여 각종 사이버위협으로부터 예방ㆍ대응코자 함
SW 개발단계부터 보안약점을 제거하는 ‘SW 개발보안’ 의무제가 2012년 12월부터 시행되며 이에 따른
관련 가이드를 보급하오니 적극 활용하시기 바랍니다.

ㅇ 가이드 내역(2종)
- (개발시 참고) 소프트웨어 개발보안 가이드
. (언어별 시큐어코딩 가이드) JAVA, C, Android-JAVA
- (점검시 참고) 소프트웨어 보안약점 진단가이드

※ SW 개발보안 반영한 “정보시스템 구축ㆍ운영 지침(행안부 고시)” 개정(6월)

ㅇ 활용 : (개발보안) 행정ㆍ공공기관 정보시스템 개발자 및 유지보수자, 담당공무원,
     (진단) 진단원 및 감리원, 사업자 자체 SW보안약점 잔존여부 진단 등

ㅇ 첨부파일 :
붙임1. 소프트웨어 개발보안 가이드(3판)
붙임2. 소프트웨어 보안약점 진단가이드(1판)
붙임3. JAVA 시큐어 코딩 가이드(3판)
붙임4. C 시큐어 코딩 가이드(3판)
붙임5. Android-JAVA 시큐어 코딩가이드(2판)
(참고) 2012년 SW 개발보안 및 진단원 양성과정 연간 교육일정

'JAVA' 카테고리의 다른 글

스트링 비교  (0) 2013.09.26
[JAVA] 공부 ,유용한 사이트  (0) 2013.07.19
[펌] 리스트 순환중에 특정 객체 삭제하기  (0) 2013.07.15
[Configuration] 설정  (0) 2013.07.01
Http 송수신 HttpClient  (0) 2013.06.28
Posted by 선한열심
JAVA2013. 7. 15. 19:31

아이군의 블로그 - [Java] 리스트 순환중에 특정 객체 삭제하기

 

List<String> list = new ArrayList<String>();

list
.add("AAAA");
list
.add("BBBB");
list
.add("CCCC");
list
.add("DDDD");
list
.add("EEEE");
list
.add("FFFF");
list
.add("GGGG");

for(Iterator<String> it = list.iterator() ; it.hasNext() ; )
{
        String value = it.next();
       
        if(value.startsWith("C"))
        {
                it.remove();
        }
}

System.out.println("Result: " + list);

Posted by 선한열심
JAVA2013. 7. 1. 15:18

Configuration 재정립...

Posted by 선한열심
JAVA2013. 6. 28. 11:25

출처-Http 송수신 HttpClient 

 

POST 방식 예제

01 import org.apache.commons.httpclient.HttpClient;
02 import org.apache.commons.httpclient.HttpStatus;
03 import org.apache.commons.httpclient.methods.PostMethod;
04
05 import java.io.BufferedReader;
06 import java.io.InputStreamReader;
07
08 public class PostMethodExample {
09 public static void main(String args[]) {
10 HttpClient client = new HttpClient();
11 client.getParams().setParameter("http.useragent", "Test Client");
12 BufferedReader br = null;
13 PostMethod method = new PostMethod("http://search.yahoo.com/search");
14 method.addParameter("p", "\"java2s\"");
15 try{
16 int returnCode = client.executeMethod(method);
17
18 if(returnCode == HttpStatus.SC_NOT_IMPLEMENTED) {
19 System.err.println("The Post method is not implemented by this URI");
20 // still consume the response body
21 method.getResponseBodyAsString(); 
22 } else {
23 br = new BufferedReader(newInputStreamReader(method.getResponseBodyAsStream()));
24 String readLine;
25 while(((readLine = br.readLine()) != null)) {
26 System.err.println(readLine);
27 }
28 }
29 } catch (Exception e) {
30 System.err.println(e);
31 } finally {
32 method.releaseConnection();
33 if(br != null) try { br.close(); } catch (Exception fe) {}
34 }
35 }

결과 받는 다른 예제)

byte[] responseBody = method.getResponseBody();
   method.getRequestEntity();
   String xml = new String(responseBody);

   SAXBuilder builder = new SAXBuilder();
   Document doc = builder.build(new StringReader(xml));
   Element root = doc.getRootElement();

String ResponseValue = root.getChild("ResponseValue").getValue();
   

Posted by 선한열심
JAVA2013. 6. 26. 17:41

 

[출처] System.getProperty(시스템 환경변수)|작성자 joypheonix

1. set

1) System.getProperty(key, defaultvalue.) 사용    : key 가 null 일때 defaultvalue값을 가져옴 

 ( 참고 : http://www.tutorialspoint.com/java/lang/system_getproperty_string_def.htm )

2) was(tomcat, jeus...)별로 <command-option>에

-Dkey값 = value값 설정

예) jeus

-->

<engine-container>
<name>container6</name>
<command-option>-Xms256m -Xmx512m
-Djplug.home=D:/eclipse_workspace/FFI/WebContent/jplugreport/license
</command-option>
<engine-command>
<type>servlet</type>
<name>engine6</name>
</engine-command>
</engine-container>

 예) JBOSS 서버 예

1) 이클립스 서버더블클릭

2) Open launch configuration 클릭

3) Arguments 에   -Dkey값 = value값 설정

 

 

2. get

// Get the value of the system property
String prop = System.getProperty("jplug.home);
// my value

3. 기본 저장 키

System.getProperty("java.version") : java.version=1.6.0_17

System.getProperty("java.home") : java.home=C:\jdk1.6.0_17\jre

System.getProperty("java.vendor") : java.vendor=Sun Microsystems Inc.

System.getProperty("java.specification.version") : java.specification.version=1.6

System.getProperty("os.name") : os.name=Windows 7

System.getProperty("os.arch") : os.arch=x86

System.getProperty("user.country") : user.country=KR

System.getProperty("user.name") : user.name=saint

System.getProperty("user.language") : user.language=ko

System.getProperty("file.encoding") : file.encoding=MS949

System.getProperty("file.separator") : file.separator=\

System.getProperty("path.separator") : path.separator=;

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

Property 정보를 확인하는 자바 소스

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

import java.util.Enumeration;
import java.util.Properties;

public class TestProperty {
public static void main(String[] args) {
Properties sysprops = System.getProperties();
for (Enumeration e = sysprops.propertyNames(); e.hasMoreElements();) {
String key = (String) e.nextElement();
String value = sysprops.getProperty(key);
System.out.println(key + "=" + value);
}
}
}

 

'JAVA' 카테고리의 다른 글

[Configuration] 설정  (0) 2013.07.01
Http 송수신 HttpClient  (0) 2013.06.28
for문 ":" 정리  (0) 2013.06.25
[펌]xpath 를 이용, java 에서 xml 문서 쉽게 파싱하기  (0) 2013.06.13
Log4j 로그 두번찍히는 문제  (0) 2013.06.05
Posted by 선한열심
JAVA2013. 6. 25. 11:09

핵심 : for 문에서 countryList 루프를 돌때

         countryVO.setCarriers 하면 countryList에 추가하여 countryList.get(0).getCarriers() 값이 추가된다

       주소값을 전달해서 그런거 같다

 

예제)
        List<CountryVO> countryList = DAO.getCountry(ID);        

List<String> countryCodeList = new ArrayList<String>();
if ( countryList != null ) {

       for ( CountryVO countryVO : countryList ) 
       {
            if ( countryVO.getCarrierCount() > 0 ) { 
              countryVO.setCarriers(this.DAO.getCountryCarriersNew(CountryVO.getCountryCode(), CountryVO.getID()));
                }
        }
 }

Posted by 선한열심
JAVA2013. 6. 13. 13:53

출처 - xpath 를 이용, java 에서 xml 문서 쉽게 파싱하기




xpath 를 이용할수 있다는 걸 알기전에는 무식하게도 Document 클래스의 getElementById() 나 getElementsByTagName() 메소드를 이용해서 

상당히 무식하게 난해한 코드로 xml 을 파싱하곤 했었다 -_-



어느날 문득 xpath 에 대해서 살짝 알게되고 나서 부터는 전에 쓰던 방법에 비해서는 아주 간결하고 이해하기 쉬운 코드로 xml 에서 원하는 데이터를 땡겨다 쓰는게 훨씬 수월해 졌다.




※ xpath 문법에 대해서 왠만한걸 쉽게 파악하기 위해서는 요 사이트에 가면 된다.

http://www.zvon.org/xxl/XPathTutorial/General/examples.html

요기 가서 보면 알겠지만 쉽게 쉽게 설명되있다. 

xpath 만 어느정도 쓸 수 있으면 xml 에서 원하는 데이터를 땡겨오는건 매우 쉬워지니 살짝 한번 연구해 보는걸 추천한다.





xpath를 이용해서 xml 에서 원하는 데이터를 파싱하는 예제코드를 작성해 보았다. 

xpath 를 사용하기 위해서 별다로 다른 라이브러리를 classpath 에 추가 안해도 된다.




예제 코드에서 사용된 xml

1
2
3
4
5
6
7
8
9
10
<root>
    <row>
        <col1 id="c1">값1</col1>
        <col2 id="c2" val="val2">값2</col2>
    </row>
    <row>
        <col1 id="c3">값3</col1>
        <col2 id="c4">값4</col2>
    </row>
</root>




예제 코드는 다음과 같다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import java.io.StringReader;
 
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
 
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
 
 
public class XPathTest{
    public static void main(String[] args) throws Exception {
        String xml = "<root><row><col1 id='c1'>값1</col1><col2 id='c2' val='val2'>값2</col2></row>" +
                             "<row><col1 id='c3'>값3</col1><col2 id='c4'>값4</col2></row></root>";
         
        // XML Document 객체 생성
        InputSource is = new InputSource(new StringReader(xml));
        Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(is);
 
        // 인터넷 상의 XML 문서는 요렇게 생성하면 편리함.
        //Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder()
        //                               .parse("http://www.example.com/test.xml");
         
         
         
        // xpath 생성
        XPath xpath = XPathFactory.newInstance().newXPath();
         
 
         
         
        // NodeList 가져오기 : row 아래에 있는 모든 col1 을 선택
        NodeList cols = (NodeList)xpath.evaluate("//row/col1", document, XPathConstants.NODESET);
        for( int idx=0; idx<cols.getLength(); idx++ ){
            System.out.println(cols.item(idx).getTextContent());
        }
        // 값1   값3  이 출력됨
         
         
         
         
         
        // id 가 c2 인 Node의 val attribute 값 가져오기
        Node col2 = (Node)xpath.evaluate("//*[@id='c2']", document, XPathConstants.NODE);
        System.out.println(col2.getAttributes().getNamedItem("val").getTextContent());
        // val2 출력
         
         
         
         
         
        // id 가 c3 인 Node 의 value 값 가져오기
        System.out.println(xpath.evaluate("//*[@id='c3']", document, XPathConstants.STRING));
        // 값3 출력
    }
}



전에 getElementById(), getElementsByTagName() 요걸 쓰던 코드에 비하면 코드도 쉽게 읽히고 심플하기도 서울역에 그지없다.

앞으로 xml 파싱할때는 xpath 를 주로 써야겠다.



※ evalueate() 메소드 맨 끝에 들어가는 파라메터로

XPathConstants.NODESET
XPathConstants.NODE
XPathConstants.BOOLEAN
XPathConstants.NUMBER
XPathConstants.STRING

요런걸 쓸 수 있다. 변수 이름을 보면 대충 어떨때 써야 할지 알 수 있을것이라 생각한다.


'JAVA' 카테고리의 다른 글

[출처] System.getProperty(시스템 환경변수)|작성자 joypheonix  (0) 2013.06.26
for문 ":" 정리  (0) 2013.06.25
Log4j 로그 두번찍히는 문제  (0) 2013.06.05
로그 성능 관련 isDebugEnabled  (0) 2013.06.04
자바 formatter  (0) 2013.05.21
Posted by 선한열심
JAVA2013. 6. 5. 13:02

 <logger name="com.tistiory.devyongsik.indexing" additivity="false">
<level value="debug" />
<appender-ref ref="CONSOLE" />
</logger>

Posted by 선한열심