2011년 5월 18일 수요일

CXF stringListProvider

cxf config file

---
<bean id="stringListProvider" class="com.archnal.util.StringListBodyWriter"/>
---

Java 구현 클래스
---
package com.archnal.util;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.MessageBodyWriter;

@Produces( { MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public class StringListBodyWriter implements MessageBodyWriter<List<String>> {

  public long getSize(List<String> t, java.lang.Class<?> type,
      java.lang.reflect.Type genericType,
      java.lang.annotation.Annotation[] annotations,
      javax.ws.rs.core.MediaType mediaType) {

    Iterator<String> i = t.iterator();
    long size = 0;
    while (i.hasNext()) {
      size += i.next().length();
    }

    return size;
  };

  @Override
  public boolean isWriteable(Class<?> type, Type genericType,
      Annotation[] annotations, MediaType mediaType) {
    return type.equals(ArrayList.class)
        && (mediaType.equals(MediaType.TEXT_PLAIN_TYPE)
            || mediaType.equals(MediaType.TEXT_XML_TYPE) || mediaType
            .equals(MediaType.APPLICATION_JSON_TYPE));
  }

  @Override
  public void writeTo(List<String> t, Class<?> type, Type genericType,
      Annotation[] annotations, MediaType mediaType,
      MultivaluedMap<String, Object> httpHeaders,
      OutputStream entityStream) throws IOException,
      WebApplicationException {

    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
        entityStream));
    String ts = null;
    for (String aT : t) {
      ts += aT;
    }
    bw.write(ts);
    bw.flush();

  }
}
---

댓글 없음:

댓글 쓰기