2011년 5월 24일 화요일

JAX-RS: Java™ API for RESTful Web Services - 3

AddressList 개발해 보기
1. URI 구성
URI
Method
내용
/addresslist/all.xml
GET
XML 형태로 주소 List 반환
/addresslist/all.json
GET
Json 형태로 주소 List 반환
/addresslist
PUT
주소록에 주소 추가
/addressist/{addressId}
DELETE
주소록에서 ID addressId 주소를 삭제


2. Class Diagram

3. Address.java
package com.naver.blog.inter999.jaxrs.address;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
@XmlAccessorType(XmlAccessType.FIELD)
public class Address {
@XmlAttribute
protected String id;
@XmlAttribute
protected String name;
@XmlAttribute
protected String address;
@XmlAttribute
protected String phoneNumber;
public Address(){};
public Address(String id, String name, String address, String phoneNumber) {
this.id = id;
this.name = name;
this.address = address;
this.phoneNumber = phoneNumber;
}
}


4. Addresses.java
package com.naver.blog.inter999.jaxrs.address;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name="", propOrder={"address"})
@XmlRootElement(name="addressList")
public class Addresses {
@XmlElement(required=true)
protected List<Address> address;
public List<Address> getAddress() {
if(address == null) {
address = new ArrayList<Address>();
}
return address;
}
}


5. AddressesFactory.java
package com.naver.blog.inter999.jaxrs.address;
public class AddressesFactory {
private static AddressesFactory addressesFactory;
private AddressesFactory() {
}
public static synchronized AddressesFactory getInstance() {
if (addressesFactory == null)
addressesFactory = new AddressesFactory();
return addressesFactory;
}
public Addresses createAddresses() {
Addresses addresses = new Addresses();
addresses.getAddress().add(new Address("1","홍길동","서울","02-332-2212"));
addresses.getAddress().add(new Address("2","이순신","인천","032-232-2211"));
return addresses;
}
}


6. AddressList.java
package com.naver.blog.inter999.jaxrs.address;
import java.util.ArrayList;
import java.util.List;
import javax.ws.rs.ConsumeMime;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.ProduceMime;
import com.sun.ws.rest.spi.resource.Singleton;
@Path("/addresslist")
@Singleton
public class AddressList {
private Addresses addresses;
public AddressList() {
this.addresses = AddressesFactory.getInstance().createAddresses();
}
@GET
@Path(value="/all.xml")
@ProduceMime("application/xml")
public synchronized Addresses getAddressesListXML() {
return addresses;
}
@GET
@Path(value="/all.json")
@ProduceMime("application/json")
public synchronized Addresses getAddressesListJSON() {
return addresses;
}
@PUT
@ConsumeMime({"application/xml", "application/json"})
public synchronized void addAddressXML(Addresses addresses) {
List<Address> addList = addresses.getAddress();
for(Address address : addList) {
this.addresses.getAddress().add(address);
}
}
@DELETE
@Path("/{addressId}")
public synchronized void deleteAddress(@PathParam("addressId") String addressId) {
List<Address> list = addresses.getAddress();
List<Integer> indexs = new ArrayList<Integer>();
for(Address address : list) {
if(address.id.equals(addressId)) {
indexs.add(list.indexOf(address));
}
}
for(int index : indexs) {
addresses.getAddress().remove(index);
}
}
}


7. Client – MyContentHandlerFactory.java
package com.naver.blog.inter999.jaxrs.address.client;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.ContentHandler;
import java.net.ContentHandlerFactory;
import java.net.URLConnection;
import org.codehaus.jettison.json.JSONArray;
public class MyContentHandlerFactory implements ContentHandlerFactory {
class JSONObjectContentHandler extends ContentHandler {
public Object getContent(URLConnection con) {
try {
InputStream is = con.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
baos.write('[');
byte[] buf = new byte[1024];
int read;
while ((read = is.read(buf)) != -1) {
baos.write(buf, 0, read);
}
baos.write(']');
return new JSONArray(baos.toString()).get(0);
} catch (Exception ioe) {
ioe.printStackTrace(System.err);
return null;
}
}
}
class StringContentHandler extends ContentHandler {
public Object getContent(URLConnection con) {
try {
InputStream is = con.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int read;
while ((read = is.read(buf)) != -1) {
baos.write(buf, 0, read);
}
return baos.toString();
} catch (Exception ioe) {
ioe.printStackTrace(System.err);
return null;
}
}
}
public MyContentHandlerFactory() {
}
public ContentHandler createContentHandler(String mimetype) {
if ("application/json".equals(mimetype)) {
return new JSONObjectContentHandler();
} else if ("application/xml".equals(mimetype)) {
return new StringContentHandler();
}
return null;
}
}


8. Client – AddressListClient.java
package com.naver.blog.inter999.jaxrs.address.client;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Map;
public class AddressListClient {
static final String UrlBase = "http://localhost:8080/AddressList/addresslist";
static final class HttpResponse {
Object content;
int code;
String message;
}
static HttpResponse makeHttpRequest(String method, String url, Map<String, String> headers, InputStream is)
throws Exception {
HttpResponse response = new HttpResponse();
URL urlAddress = new URL(url);
HttpURLConnection huc = (HttpURLConnection) urlAddress.openConnection();
huc.setRequestMethod(method);
if (null != is) {
huc.setDoOutput(true);
for (String key : headers.keySet()) {
huc.setRequestProperty(key, headers.get(key));
}
OutputStream os = huc.getOutputStream();
byte[] buf = new byte[1024];
int read;
while ((read = is.read(buf)) != -1) {
os.write(buf, 0, read);
}
}
response.code = huc.getResponseCode();
response.message = huc.getResponseMessage();
if (HttpURLConnection.HTTP_NO_CONTENT != response.code) {
response.content = huc.getContent();
}
return response;
}
static HttpResponse makeHttpRequest(String method, String url, String contentType, String content)
throws Exception {
Map<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", contentType);
return makeHttpRequest(method, url, headers, new ByteArrayInputStream(content.getBytes("UTF-8")));
}
static HttpResponse makeHttpRequest(String method, String url)
throws Exception {
return makeHttpRequest(method, url, null, (InputStream) null);
}
public static void main(String[] args) {
HttpURLConnection.setContentHandlerFactory(new MyContentHandlerFactory());
Map<String, String> acceptXmlHeaders = new HashMap<String, String>();
acceptXmlHeaders.put("Accept", "application/xml");
HttpResponse response;
try {
System.out.println("Getting list of AddressList(XML):");
response = makeHttpRequest("GET", UrlBase + "/all.xml");
System.out.println(new Formatter().format("Address found:\n%s", response.content));
System.out.println("-----");
System.out.println("Getting list of AddressList(JSON):");
response = makeHttpRequest("GET", UrlBase + "/all.json");
System.out.println(new Formatter().format("Address found:\n%s", response.content));
System.out.println("-----");
String addXMLAddress = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><addressList><address phoneNumber=\"02-332-2212\" address=\"SEOUL\" name=\"HURUKKU\" id=\"3\"/></addressList>";
System.out.println("Add Address (XML):");
response = makeHttpRequest(
"PUT",
UrlBase,
"application/xml",
addXMLAddress);
System.out.println("-----");
System.out.println("Getting list of AddressList(XML):");
response = makeHttpRequest("GET", UrlBase + "/all.xml");
System.out.println(new Formatter().format("Address found:\n%s", response.content));
System.out.println("-----");
System.out.println("Delete address 3 :");
response = makeHttpRequest("DELETE", UrlBase + "/3");
System.out.println(new Formatter().format("Address found:\n%s", response.content));
System.out.println("-----");
System.out.println("Getting list of AddressList(XML):");
response = makeHttpRequest("GET", UrlBase + "/all.xml");
System.out.println(new Formatter().format("Address found:\n%s", response.content));
System.out.println("-----");
} catch (Exception e) {
System.out.println("TEST FAILED! :-(");
e.printStackTrace(System.out);
}
}
}


9. WEB-INF/web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<servlet>
<servlet-name>Jersey Web Application</servlet-name>
<servlet-class>com.sun.ws.rest.spi.container.servlet.ServletContainer</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey Web Application</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>


10. ANT build.xml
<?xml version="1.0" encoding="UTF-8"?>
<project basedir="." default="war.build" name="AddressList">
<property environment="env"/>
<property name="debuglevel" value="source,lines,vars"/>
<property name="target" value="1.5"/>
<property name="source" value="1.5"/>
<property name="build.path" value="./build" />
<property name="jersey.path" value="../../../library/jersey-0.8" />
<property name="library.path" value="${jersey.path}/lib" />
<path id="build.classpath">
<pathelement location="${build.path}/classes"/>
<pathelement location="${library.path}/activation.jar"/>
<pathelement location="${library.path}/asm-3.1.jar"/>
<pathelement location=".${library.path}/jaxb-api.jar"/>
<pathelement location="${library.path}/jaxb-impl.jar"/>
<pathelement location="${library.path}/jdom-1.0.jar"/>
<pathelement location="${library.path}/jettison-1.0-RC1.jar"/>
<pathelement location="${library.path}/jsr173_api.jar"/>
<pathelement location="${library.path}/jsr250-api.jar"/>
<pathelement location="${library.path}/jsr311-api.jar"/>
<pathelement location="${library.path}/mail.jar"/>
<pathelement location="${library.path}/rome-0.9.jar"/>
<pathelement location="${jersey.path}/dist/jersey.jar"/>
</path>
<target name="prepare">
<tstamp />
<mkdir dir="${build.path}" />
<mkdir dir="${build.path}/WEB-INF" />
<mkdir dir="${build.path}/WEB-INF/classes" />
<mkdir dir="${build.path}/WEB-INF/lib" />
</target>
<target name="clean">
<delete dir="${build.path}" />
</target>
<target depends="prepare" name="compile">
<javac debug="true" debuglevel="${debuglevel}" destdir="${build.path}/WEB-INF/classes" source="${source}" target="${target}">
<src path="./src"/>
<classpath refid="build.classpath"/>
</javac>
</target>
<target name="war.build" depends="compile">
<copy file="${library.path}/activation.jar" tofile="${build.path}/WEB-INF/lib/activation.jar" overwrite="true" />
<copy file="${library.path}/asm-3.1.jar" tofile="${build.path}/WEB-INF/lib/asm-3.1.jar" overwrite="true" />
<copy file="${library.path}/jaxb-api.jar" tofile="${build.path}/WEB-INF/lib/jaxb-api.jar" overwrite="true" />
<copy file="${library.path}/jaxb-impl.jar" tofile="${build.path}/WEB-INF/lib/jaxb-impl.jar" overwrite="true" />
<copy file="${library.path}/jdom-1.0.jar" tofile="${build.path}/WEB-INF/lib/jdom-1.0.jar" overwrite="true" />
<copy file="${library.path}/jettison-1.0-RC1.jar" tofile="${build.path}/WEB-INF/lib/jettison-1.0-RC1.jar" overwrite="true" />
<copy file="${library.path}/jsr173_api.jar" tofile="${build.path}/WEB-INF/lib/jsr173_api.jar" overwrite="true" />
<copy file="${library.path}/jsr250-api.jar" tofile="${build.path}/WEB-INF/lib/jsr250-api.jar" overwrite="true" />
<copy file="${library.path}/jsr311-api.jar" tofile="${build.path}/WEB-INF/lib/jsr311-api.jar" overwrite="true" />
<copy file="${library.path}/mail.jar" tofile="${build.path}/WEB-INF/lib/mail.jar" overwrite="true" />
<copy file="${library.path}/rome-0.9.jar" tofile="${build.path}/WEB-INF/lib/rome-0.9.jar" overwrite="true" />
<copy file="${jersey.path}/dist/jersey.jar" tofile="${build.path}/WEB-INF/lib/jersey.jar" overwrite="true" />
<copy file="./WEB-INF/web.xml" tofile="${build.path}/WEB-INF/web.xml" overwrite="true" />
<jar jarfile="${basedir}/${ant.project.name}.war">
<fileset dir="./build"/>
</jar>
</target>
</project>


11. Eclipse Directory 구조
12. Ant Build 실행 AddressList.war Tomcat Webapp Deploy
13. http://localhost:8080/AddressList/addresslist/all.xml 접근하여 정상적으로 Deploy 되었는지 확인할 있음
14. Eclipse에서 “AddressListClient” Run 실행, Console에서 출력된 로그를 확인할 있다.

댓글 없음:

댓글 쓰기

ETL 솔루션 환경

ETL 솔루션 환경 하둡은 대용량 데이터를 값싸고 빠르게 분석할 수 있는 길을 만들어줬다. 통계분석 엔진인 “R”역시 하둡 못지 않게 관심을 받고 있다. 빅데이터 역시 데이터라는 점을 볼때 분산처리와 분석 그 이전에 데이터 품질 등 데이...