맵핑정보를 static map 에 선언해 놓고 쓰고 싶다.

우선 static field를 선언했다.

 
public class Test{
    static private final Map<String, String> mappingFileds = new HashMap<String, String>();
}

초기화를 어떻게 할까??

구글링 하니 몇가지 방법이 나왔다.

1.  static initializer block

 private static final Map<Integer, String> myMap;
    static {
        Map<Integer, String> aMap = ....;
        aMap.put(1, "one");
        aMap.put(2, "two");
        myMap = Collections.unmodifiableMap(aMap);
    }

참고로 class block(instance block 이라고도 하던데..) 안에 brace로{}감싼 부분을 initialzer block이라고 하고
나중에 컴파일러는 이부분을 constructor에 복사해준다고 한다.
물론 static을 붙여주면 한번만 실행.

2. static method

private static final Map<Integer, String> MY_MAP = createMap();

    private static Map<Integer, String> createMap() {
        Map<Integer, String> result = new HashMap<Integer, String>();
        result.put(1, "one");
        result.put(2, "two");
        return Collections.unmodifiableMap(result);
    }

3. double brace initialization (anonymous class 이용한 trick)

private static final Map<Integer, String> CONSTANT_MAP = 
    Collections.unmodifiableMap(new HashMap<Integer, String>() {{ 
        put(1, "one");
        put(2, "two");
    }});



* ImmutableMap 사용하면 바로 값을 넣어줄 수도 있다

static final Map<Integer, String> MY_MAP = ImmutableMap.<Integer, String>builder()
    .put(1, "one")
    .put(2, "two")
    // ... 
    .put(15, "fifteen")
    .build();


ref    

http://stackoverflow.com/questions/507602/how-to-initialise-a-static-map-in-java

'program language > java' 카테고리의 다른 글

log4j 설정  (1) 2012.04.09
junit4 정리  (0) 2012.04.04
JAX-RS: Java API for RESTful Web Services  (0) 2012.03.26
JDO(Java Data Object)  (0) 2012.03.15
JSR(Java Specification Requests),JCP(Java Community Process)  (1) 2012.03.06
Posted by 뚜벅이조
,

web.xml

<listener>
    <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
<context-param>
    <param-name>log4jConfigLocation</param-name>
    <param-value>/WEB-INF/log4j.properties</param-value>
</context-param>

log4j.properties

log4j.rootLogger = DEBUG, stdout 

log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d [%5p] [%c{1}:%L] - %m%n

#log4j.appender.dailyfile.Threshold = DEBUG
#log4j.appender.dailyfile = org.apache.log4j.DailyRollingFileAppender
#log4j.appender.dailyfile.File = logfile.log
#log4j.appender.dailyfile.layout = org.apache.log4j.PatternLayout
#log4j.appender.dailyfile.layout.ConversionPattern=%5p ({%t} %F[%M]:%L) [%d] - %m%n

Layout pattern

C : 클래스명을 출력한다. {1}과 같은 설정을 추가하여 클래스 이름 또는 특정 패키지 이상만 출력하도록 설정할 수 있다. 
d : 로그 시간을 출력한다. java.text.SimpleDateFormat에서 적절한 출력 포맷을 지정할 수 있다. 
F : 파일 이름을 출력한다. 로그시 수행한 메소드, 라인번호가 함께 출력된다.
L : 라인 번호만 출력한다.
m : 로그로 전달된 메시지를 출력한다.
M : 로그를 수행한 메소드명을 출력한다. 
n : 줄 바꿈
p : 로그 이벤트명 (DEBUG등)
r : 로그 처리시간 (milliseconds)


ref:

http://zemba.tistory.com/47

http://en.wikipedia.org/wiki/Log4j

http://logging.apache.org/log4j/

http://logging.apache.org/log4j/1.2/apidocs/index.html


Posted by 뚜벅이조
,
spring에서 testCase를 작성해보자.

junit4 annotation 종류
  • @After
    테스트시 매번 실행 후 호출되는 메소드
  • @AfterClass
    모든 테스트 후 한번 호출되는 메소드
  • @Before
    테스트시 매번 실행 전 호출되는 메소드
  • @BeforeClass
    모든 테스트 전 한번 호출되는 메소드
  • @Ignore
    skip되는 테스트 메소드
  • @Test
    테스트 메소드

exemple (spring 연동)

import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.sec.ams.controller.apk.TotalApkContoller;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:springmvc-servlet.xml" })
public class ApkServiceTest {
@Autowired
TotalApkContoller totalApkContoller;

@Test
public void test() {

String totalView = totalApkContoller.getTotalView();
assertEquals("apk/total", totalView);
// fail("Not yet implemented");

}
}


ref:

http://junit.sourceforge.net/javadoc/index.html

http://www.junit.org/

Posted by 뚜벅이조
,

JAX-RS(Java™ API for RESTful Web Services)는 자바 플랫폼에서 경량화된 REST 방식의 웹 애플리케이션 구현을 지원하는 자바 API이다.

SOAP기반의 SOA 연동은 자바 애플리케이션을 무겁게 한다는 비판과 함께, 최근 웹 애플리케이션의 경향인 AJAX기반으로 JSON이나 RSS와 같이 간결한 프로토콜을 사용한 연동이 보편화되면서 쉽게 구현할 수 있도록 Java EE에 JAX-RS 라는 사양이 포함되고 있다.

구현 플랫폼

 

Specification

JAX-RS provides some annotations to aid in mapping a resource class (a POJO) as a web resource. The annotations include:

  • @Path specifies the relative path for a resource class or method.
  • @GET@PUT@POST@DELETE and @HEAD specify the HTTP request type of a resource.
  • @Produces specifies the response MIME media types.
  • @Consumes specifies the accepted request media types.

In addition, it provides further annotations to method parameters to pull information out of the request. All the @*Param annotations take a key of some form which is used to look up the value required.

  • @PathParam binds the parameter to a path segment.
  • @QueryParam binds the parameter to the value of an HTTP query parameter.
  • @MatrixParam binds the parameter to the value of an HTTP matrix parameter.
  • @HeaderParam binds the parameter to an HTTP header value.
  • @CookieParam binds the parameter to a cookie value.
  • @FormParam binds the parameter to a form value.
  • @DefaultValue specifies a default value for the above bindings when the key is not found.
 

ref:
http://ko.wikipedia.org/wiki/JAX-RS 
http://en.wikipedia.org/wiki/Java_API_for_RESTful_Web_Services  

'program language > java' 카테고리의 다른 글

log4j 설정  (1) 2012.04.09
junit4 정리  (0) 2012.04.04
JDO(Java Data Object)  (0) 2012.03.15
JSR(Java Specification Requests),JCP(Java Community Process)  (1) 2012.03.06
anotation  (0) 2011.09.21
Posted by 뚜벅이조
,
Project builder

Project natures


네이처(nature)는 한 프로젝트가 갖는 일부 성질들에 대한 추상성을 제공한다.
한 프로젝트는 여러개의 네이처를 가질 수 있다.

주요 임무
  • 프로젝트가 해당 특성을 같기 위해 필요한 자원의 준비와 해제


ref:
http://www.eclipse.org/articles/Article-Builders/builders.html
http://eclipse.or.kr/wiki/Nature 
http://eclipse.or.kr/wiki/Builder 
Posted by 뚜벅이조
,

오라클 사이트에서 일부 인용.

The Java Data Objects (JDO) API is a standard interface-based Java model abstraction of persistence, developed under the auspices of the Java Community Process. The original JDO 1.0 is Java Specification Request 12 ( JSR 12), and the current JDO 2.0 is Java Specification Request 243 (JSR 243). Beginning with JDO 2.0, the development of the API and the Technology Compatibility Kit (TCK) takes place within the Apache JDO open-source project. 


현재 버전은 3.0 이다.
RDB에서 부터 noSql, file storage등 범용적인 데이터 입출력을 감싸는 스펙인 듯 하다.

구현체중 datanucleus 를 살펴보고 있다.
RDBMS, XML, LDAP, MongoDB, HBase..... 등 다양한 connectivity를 제공한다.

ref:
http://db.apache.org/jdo/ 
http://www.oracle.com/technetwork/java/index-jsp-135919.html  
http://www.jcp.org/en/jsr/detail?id=243  
http://www.datanucleus.org/  

'program language > java' 카테고리의 다른 글

log4j 설정  (1) 2012.04.09
junit4 정리  (0) 2012.04.04
JAX-RS: Java API for RESTful Web Services  (0) 2012.03.26
JSR(Java Specification Requests),JCP(Java Community Process)  (1) 2012.03.06
anotation  (0) 2011.09.21
Posted by 뚜벅이조
,

* JCP
는 Java Community Process 의 약자입니다. 자바기술의 기술 스펙 표준을 제정하는 단체이다.

* 300여개가 넘는 JSRs

*JCP EC(Executive Committee)
커뮤니티 안에서 자바 규격 요청서(JSR)라는 문서 내용을 검토하고 승인하는 업무를 담당하는 조직이다. 커랜 의장은 "매월 컨퍼런스콜을 진행하며 1년에 3번 정도는 직접 모인다"며 "이달초 한국 회원사 SK텔레콤이 주최하고 삼성전자도 참여하는 형태로 열린 회의에 참석했다"고 밝혔다.

 

그가 언급한 JSR은 자바 관련 표준을 제정하기 위해 커뮤니티 회원 누구나 제안할 수 있는 규격 문서다. 특정한 자바 기술이 어느 플랫폼에 들어갔을 때 어떻게 작동하는지에 대한 메커니즘을 정의하는 내용을 담는다. 이를 개발하는 업무는 '스펙 리드'라는 전문가가 주도한다. 각 스펙 리드를 지원하기 위해 규격마다 관심을 가진 사람들이 모인 '엑스퍼트 그룹'이 형성된다.  

커랜 의장은 "JSR 프로젝트는 정의된 JSR 규격 자체, 레퍼런스 구현체(RI), 규격 테스트를 위한 기술 호환성 키트(TCK), 이렇게 3가지 결과물을 갖춰야 한다"며 "이들은 상호 의존적으로 개발되며 프로젝트를 진행할수록 서로 발전해 나간다"고 설명했다. 

 

이날 그는 오픈JDK 프로젝트 참여 주체와 차세대 자바 기업용 에디션(EE)에 대한 언급에 이어 최근 강조되는 클라우드 컴퓨팅으로 기회가 늘었다는 전망을 내놨다. 또 다소 부정적 인식이 남아 있는 개발자 커뮤니티 발전을 약속하는 한편 프로젝트에 참여하는 회원사들의 역할이 중요하다고 강조했다.  

ref:
http://www.zdnet.co.kr/news/news_view.asp?artice_id=20110504233406
http://en.wikipedia.org/wiki/Java_Community_Process

'program language > java' 카테고리의 다른 글

log4j 설정  (1) 2012.04.09
junit4 정리  (0) 2012.04.04
JAX-RS: Java API for RESTful Web Services  (0) 2012.03.26
JDO(Java Data Object)  (0) 2012.03.15
anotation  (0) 2011.09.21
Posted by 뚜벅이조
,
2011년 10월28일 지인의 추천으로 go언어 세미나에 참석하게 되었다
앞으로 주목할만한 언어가 아닐까 하는 생각에 동감하게 되었다.
이제 부터 시간이 날때마다 go언어에 대해 공부하고 정리해 볼 생각이다.

세미나에서 주요했던 내용들.

첫번째 발표.
 

GO 언어 개발 팀
 - Robert Griesemer, Ken Thompson, Rob Pike, Ian Lance Tayloer, Russ Cox 
 - 컴파일러, 언어, 운영체제, 동시성, 자바 핫스팟의 전문가들이다.

GO는 C의 버전업이다.
 - C Syntax refactoring
 - C가 나온지 40년이 되었다 개선안이 필요하다.

디펜던시 문제
 - GO에서는 fmt 하나만 읽으면 된다.

정적 타입인데 동적타입 언어처럼 쓸 수 있다.

Garbage collection & Parallel Computation
 - GC가 되어서 Parallel Computation이 쉽다.(용량은 GC가 들어간 만큼 커졌다)

Pointer에 대한 가감이 불가능 하다.

두번째 발표.
문법적인 부분. 차후에 자세히 공부할 예정.

달리나음님의 발표요약
https://workflowy.com/shared/2280cbff-97da-d0e6-c224-9110671f8acd/

go lang 번역 사이트: http://code.google.com/p/golang-korea 
go lang groups : http://groups.google.com/group/golang-korea
go lang : http://golang.org/ 
go tour : http://code.google.com/p/go-tour/
gophertimes : http://gophertimes.com 
go tutorials : http://gotutorials.blogspot.com
A Tour of GO : http://go-tour-kr.appspot.com 
weekly go : http://weekly.golang.org 
go 예제들 :  https://github.com/nf
projecteuler(프로그램 문제 풀기) : 
http://projecteuler.net 
Posted by 뚜벅이조
,

anotation

program language/java 2011. 9. 21. 16:44
http://en.wikipedia.org/wiki/Java_annotation

An annotation, in the Java computer programming language, is a special form of syntactic metadata that can be added to Java source code. Classes, methods, variables, parameters and packages may be annotated. Unlike Javadoc tags, Java annotations can be reflective in that they can be embedded in class files generated by the compiler and may be retained by the Java VM to be made retrievable at run-time.

http://www.gurubee.net/display/WEBSTUDY/Annotation  

Annotation 이란

  • 메타데이터, 한 마디로 데이터의 데이터다
  • 어노테이션이 나오기 전까지 메타데이터는 프로퍼티 파일과 XML파일을 활용하였다.
  • 어노테이션은 주로 데이터를 문서화하거나, 컴파일 타임이나 런타임시에 원하는 동작을 수행할 수 있도록 하는 데 사용된다.
  • 닷넷프레임워크 1.0에서 어트리뷰트라는 기능을 제공하자, 자바에서 어노테이션을 통한 메타데이터 활용 기술을 제공했다.

Annotation의 장점

  • 코드의 가독성 증대
    • 관련 코드 곁에 메타데이터를 설정할 수 있으므로 코드의 가독성 증대 된다.
  • 개발 효율성 증대
    • 복잡한 XML 스키마를 파악하지 않아도 되며, 개발시 개발 툴과 컴파일러의 도움을 받을 수 있으므로 개발 효율성이 증대 된다.
  • 별도의 파서를 적용하지 않고도 간단히 런타임 시에 활용할 수 있는 편리함이 있다.
  • JUnit, Framework, Permission Module 에서 사용

Annotation을 반대하는 사람들의 의견

  • 메타정보와 소스의 결합자체를 못마땅하다.
  • 메타데이터는 그 자체로 코드에 독립적이어야 하며 한 곳에 모여져서 어플리케이션의 구성을 한눈에 알 수 있어야 바람직하다는 주장.
  • 어노테이션은 코드를 이용해서 검증하는게 가능하지만 XML의 DTD나 스키마를 이용하는 검증 방식에 비해서 훨씬 불편하다.

Annotation의 단점

  • 어노테이션 처리시 리플렉션을 통해 해당 클래스를 분석해야 하는 오버헤드가 있다.
    • XML 파일을 이용하는 방법도 오버헤드가 있으므로, 경우에 따라서 어노테이션이 더 빠를 수도 있음.
  • 어노테이션은 모듈이나 어플리케이션 전반적인 메타데이터를 설정할 수 없다.
    • 어노테이션의 범위는 클래스나 패키지 레벨로 한정되기 때문에 여러 클래스에 걸친 공통적인 설정이나 모듈레벨 설정이 어렵다.
    • 웹 어플리케이션 개발시 서블릿 필터나, 인터셉터를 이용해서 문제 해결이 가능함.
 

'program language > java' 카테고리의 다른 글

log4j 설정  (1) 2012.04.09
junit4 정리  (0) 2012.04.04
JAX-RS: Java API for RESTful Web Services  (0) 2012.03.26
JDO(Java Data Object)  (0) 2012.03.15
JSR(Java Specification Requests),JCP(Java Community Process)  (1) 2012.03.06
Posted by 뚜벅이조
,