<div class="information"> 이 예제는 Axis2 1.3RC2, Tomcat 6.0.13 에서 테스트되었습니다.

개인적으로 Axis2 1.2 에서는 첨부파일 다운로드시 버그가 있어서 처리가 되지 않았습니다. </div>

Axis2에서 SOAP With Attachment 방식으로 첨부파일 처리하기#

서비스 클래스#

package kr.or.openframework.service;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.xml.namespace.QName;

import org.apache.axiom.attachments.Attachments;
import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMFactory;
import org.apache.axiom.om.OMNamespace;
import org.apache.axis2.AxisFault;
import org.apache.axis2.context.MessageContext;
import org.apache.axis2.context.OperationContext;
import org.apache.axis2.wsdl.WSDLConstants;

public class AttachmentService {
  private String fileDir = "c:";
  private String nameSpace = "http://service.openframework.or.kr/xsd";

  private void checkResourceDir(File filethrows AxisFault {
    file = new File(fileDir);
    if (!file.isDirectory() || !file.exists()) {
      throw new AxisFault("Server's Attachment file folder is not exists! ");
    }
  }

  public OMElement uploadFile(OMElement elementthrows AxisFault {
    File file = null;
    checkResourceDir(file);
    String fileName = element.getFirstChildWithName(new QName(nameSpace, "name")).getText();
    String attchmentID = element.getFirstChildWithName(new QName(nameSpace, "attchmentID")).getText();
    System.out.println("==============> fileName : " + fileName);
    System.out.println("==============> full fileName : " + fileDir + fileName);
    System.out.println("==============> attchmentID : " + attchmentID);

    MessageContext inMessageContext = MessageContext.getCurrentMessageContext();
    Attachments attachment = inMessageContext.getAttachmentMap();
    DataHandler dataHandler = attachment.getDataHandler(attchmentID);
    file = new File(fileDir + fileName);
    FileOutputStream fileOutputStream = null;

    try {
      fileOutputStream = new FileOutputStream(file);
      dataHandler.writeTo(fileOutputStream);
      fileOutputStream.flush();
      fileOutputStream.close();
    catch (FileNotFoundException e) {
      e.printStackTrace();
    catch (IOException e) {
      e.printStackTrace();
    }

    return createUploadFileElement("File saved succesfully.");
  }

  private OMElement createUploadFileElement(String message) {
    OMFactory factory = OMAbstractFactory.getOMFactory();
    OMNamespace omNs = factory.createOMNamespace(nameSpace, "swa");
    OMElement wrapperElement = factory.createOMElement("uploadFileResponse", omNs);
    OMElement messageElement = factory.createOMElement("message", omNs, wrapperElement);
    messageElement.setText(message);

    return wrapperElement;
  }

  public OMElement getFile(OMElement elementthrows AxisFault {
    FileDataSource graphImageDataSource = null;
    DataHandler graphImageDataHandler = null;

    File file = null;
    checkResourceDir(file);
    MessageContext inMessageContext = MessageContext.getCurrentMessageContext();
    OperationContext operationContext = inMessageContext.getOperationContext();
    MessageContext outMessageContext = 
    operationContext.getMessageContext(WSDLConstants.MESSAGE_LABEL_OUT_VALUE);

    String fileName = element.getFirstElement().getText();
    graphImageDataSource = new FileDataSource(fileDir + File.separator + fileName);
    if (graphImageDataSource.getFile().exists()) {
      System.out.println("==============> server's file is exist : " + fileDir + File.separator + fileName);
    else {
      System.out.println("==============> server's file is not exist ");
    }

    graphImageDataHandler = new DataHandler(graphImageDataSource);
    String graphImageID = outMessageContext.addAttachment(graphImageDataHandler);

    return createGetFileElement(graphImageID);
  }

  private OMElement createGetFileElement(String graphCID) {
    OMFactory factory = OMAbstractFactory.getOMFactory();
    OMNamespace omNs = factory.createOMNamespace(nameSpace, "swa");
    OMElement wrapperElement = factory.createOMElement("getFileResponse", omNs);
    OMElement graphElement = factory.createOMElement("graph", omNs, wrapperElement);
    graphCID = "cid:" + graphCID;
    graphElement.addAttribute("href", graphCID, null);

    return wrapperElement;
  }
}

service.xml 파일#

여기서 messageReceiver로 RawXMLINOutMessageReceiver를 사용하게 되면 스펙상 서비스 클래스의 operation 메소드를 OMElement 메소드명(OMElement인자) 의 형태로 구현해야만 한다.

<service name="AttachmentService">
  <description>Axis2에서 SOAP With Attachment를 사용하여 첨부파일 처리하기</description>

  <parameter name="enableSwA" locked="false">true</parameter>
    <parameter name="cacheAttachments">true</parameter>
    <parameter name="attachmentDIR">c:\\TEMP\\Attachment</parameter>
    <parameter name="sizeThreshold">4000</parameter>
      
  <parameter name="ServiceClass" locked="false">
    kr.or.openframework.service.AttachmentService
  </parameter>
  <operation name="uploadFile">
    <actionMapping>urn:uploadFile</actionMapping>
    <messageReceiver
      class="org.apache.axis2.receivers.RawXMLINOutMessageReceiver" />
  </operation>
  <operation name="getFile">
    <actionMapping>urn:getFile</actionMapping>
    <messageReceiver
      class="org.apache.axis2.receivers.RawXMLINOutMessageReceiver" />     
  </operation>
</service>

Service Archive Wizard 사용하기#

  • 마법사 시작하기
1.png
  • 클래스의 경로를 지정해야 한다.
2.png
  • WSDL 선택하기. 대개는 자동으로 생성되는 WSDL을 사용하리라 생각된다.
3.png
  • 첨부파일 처리를 위해 추가적으로 요구되는 jar파일을 지정한다.
4.png
  • service.xml 파일의 위치를 지정한다. 물론 자동으로 생성해도 되나 messageReceiver에 해당되는 값이나 SWA를 활성화 시키기 위한 파라미터 셋팅을 위해 선택해주는 방법이 좋다.
5.png
  • AAR 파일 저장 위치 지정
6.png

위 과정을 거치고 나서 http://localhost:8080/axis2/axis2-admin/upload 에 접근하여 AAR파일을 업로드 한다. 정상적으로 처리되면 Available Service메뉴에서 다음처럼 서비스를 확인할수 있다.

8.png

클라이언트 코드#

package client;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.xml.namespace.QName;

import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMNamespace;
import org.apache.axiom.soap.SOAP12Constants;
import org.apache.axiom.soap.SOAPBody;
import org.apache.axiom.soap.SOAPEnvelope;
import org.apache.axiom.soap.SOAPFactory;
import org.apache.axis2.AxisFault;
import org.apache.axis2.Constants;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.client.OperationClient;
import org.apache.axis2.client.Options;
import org.apache.axis2.client.ServiceClient;
import org.apache.axis2.context.ConfigurationContext;
import org.apache.axis2.context.ConfigurationContextFactory;
import org.apache.axis2.context.MessageContext;
import org.apache.axis2.wsdl.WSDLConstants;

public class SWAClient {

  private static EndpointReference targetEPR = new EndpointReference(
      "http://localhost:9000/axis2/services/AttachmentService");
  private static String nameSpace = "http://service.openframework.or.kr/xsd";

  @SuppressWarnings("unchecked")
  public static void main(String[] argsthrows Exception {
    // 첨부파일 업로드
    File file = new File("d:/test.txt");
    if (file.exists()) {
      transferFile(file, "testresult.txt");
    else {
      throw new FileNotFoundException();
    }
    
    // 첨부파일 다운로드
    getFile("testresult.txt");
  }

  public static void transferFile(File file, String destinationFilethrows Exception {
    OperationClient mepClient = getOperationClient();
    MessageContext mc = new MessageContext();

    // Attachment Part 추가
    FileDataSource fileDataSource = new FileDataSource(file);
    DataHandler dataHandler = new DataHandler(fileDataSource);
    String attachmentID = mc.addAttachment(dataHandler);

    // SOAP Envelope 추가
    SOAPFactory fac = OMAbstractFactory.getSOAP12Factory();
    SOAPEnvelope env = fac.getDefaultEnvelope();
    OMNamespace omNs = fac.createOMNamespace(nameSpace, "swa");
    OMElement uploadFile = fac.createOMElement("uploadFile", omNs);
    OMElement nameEle = fac.createOMElement("name", omNs);
    nameEle.setText(destinationFile);
    OMElement idEle = fac.createOMElement("attchmentID", omNs);
    idEle.setText(attachmentID);
    uploadFile.addChild(nameEle);
    uploadFile.addChild(idEle);
    env.getBody().addChild(uploadFile);
    mc.setEnvelope(env);
    mepClient.addMessageContext(mc);

    // 실행
    mepClient.execute(true);

    // 응답 처리
    MessageContext response = mepClient.getMessageContext(WSDLConstants.MESSAGE_LABEL_IN_VALUE);
    SOAPBody body = response.getEnvelope().getBody();
    OMElement element = body.getFirstElement().getFirstChildWithName(new QName(nameSpace, "message"));

    System.out.println("uploadFile Operation success.. => " + element.getFirstElement().getText());
  }

  public static void getFile(String fileNamethrows Exception {
    OperationClient mepClient = getOperationClient();
    MessageContext mc = new MessageContext();

    // SOAP Envelope 추가
    SOAPFactory fac = OMAbstractFactory.getSOAP12Factory();
    SOAPEnvelope env = fac.getDefaultEnvelope();
    OMNamespace omNs = fac.createOMNamespace(nameSpace, "swa");
    OMElement getFile = fac.createOMElement("getFile", omNs);
    OMElement nameEle = fac.createOMElement("name", omNs);
    nameEle.setText(fileName);
    getFile.addChild(nameEle);
    env.getBody().addChild(getFile);
    mc.setEnvelope(env);
    mepClient.addMessageContext(mc);

    // 실행
    mepClient.execute(true);

    // 응답 처리
    MessageContext response = mepClient.getMessageContext(WSDLConstants.MESSAGE_LABEL_IN_VALUE);
    SOAPBody body = response.getEnvelope().getBody();
    OMElement element = body.getFirstElement().getFirstChildWithName(new QName(nameSpace, "graph"));

    // 첨부파일 아이디 가져오기
    String graphImageID = element.getAttributeValue(new QName("href"));
    graphImageID = graphImageID.substring(4);
    // 첨부파일 아이디로 Attachment Part 가져오기
    DataHandler dataHandler = response.getAttachment(graphImageID);

    // 실제 데이터를 클라이언트로 파일로 저장하기
    if (dataHandler != null) {
      File graphFile = new File("c:/TEMP/Attachment/" + fileName);
      FileOutputStream outputStream = new FileOutputStream(graphFile);
      dataHandler.writeTo(outputStream);
      outputStream.flush();
    }

    System.out.println("getFile Operation success");
  }

  private static OperationClient getOperationClient() throws AxisFault {
    Options options = new Options();
    // 큰 첨부파일을 받을때 타임아웃값을 증가시켜야 한다.
    options.setTimeOutInMilliSeconds(10000);
    // SOAP with Attachment 를 위한 프라퍼티를  true로 지정
    options.setProperty(Constants.Configuration.ENABLE_SWA, Constants.VALUE_TRUE);
    // SOAP 버전 지정
    options.setSoapVersionURI(SOAP12Constants.SOAP_ENVELOPE_NAMESPACE_URI);
    // 웹서비스 Endpoint URL을 지정한다. 
    options.setTo(targetEPR);
    // 사용할 operation 지정
    options.setAction("urn:getFile");

    ConfigurationContext configContext = ConfigurationContextFactory.createConfigurationContextFromFileSystem(
        "D:/apache/axis2/WEB-INF"null);

    ServiceClient sender = new ServiceClient(configContext, null);
    sender.setOptions(options);
    OperationClient mepClient = sender.createClient(ServiceClient.ANON_OUT_IN_OP);

    return mepClient;
  }
}

7.png

SOAP 메시지#

파일 업로드

==============
Listen Port: 9000
Target Host: 127.0.0.1
Target Port: 8080
==== Request ====
POST /axis2/services/AttachmentService HTTP/1.1
Content-Type: multipart/related; boundary=MIMEBoundaryurn_uuid_86A62696AD98CEB0FE1186319508792; 
type="application/soap+xml"; start="<0.urn:uuid:86A62696AD98CEB0FE1186319508793@apache.org>"
charset=UTF-8; action="urn:uploadFile"
User-Agent: Axis2
Host: 127.0.0.1:9000
Transfer-Encoding: chunked

32b
--MIMEBoundaryurn_uuid_86A62696AD98CEB0FE1186319508792
Content-Type: application/soap+xml; charset=UTF-8
Content-Transfer-Encoding: 8bit
Content-ID: <0.urn:uuid:86A62696AD98CEB0FE1186319508793@apache.org>
   <?xml version='1.0' encoding='UTF-8'?>
      <soapenv:Envelope xmlns:soapenv="http://www.w3.org/2003/05/soap-envelope">
         <soapenv:Body>
            <swa:uploadFile xmlns:swa="http://service.openframework.or.kr/xsd">
               <swa:name>testresult.txt</swa:name>
               <swa:attchmentID>urn:uuid:86A62696AD98CEB0FE1186319508696</swa:attchmentID>
            </swa:uploadFile>
         </soapenv:Body>
      </soapenv:Envelope>--MIMEBoundaryurn_uuid_86A62696AD98CEB0FE1186319508792
      Content-Type: text/plainContent-Transfer-Encoding: binaryContent-ID: 
      <urn:uuid:86A62696AD98CEB0FE1186319508696>hahahahah
      --MIMEBoundaryurn_uuid_86A62696AD98CEB0FE1186319508792--0
==== Response ====
HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Content-Type: multipart/related; boundary=MIMEBoundaryurn_uuid_FD6CD3275633CFB09C1186319508977; 
type="application/soap+xml"; start="0.urn:uuid:FD6CD3275633CFB09C1186319508978@apache.org"
action="urn:uploadFileResponse";charset=UTF-8
Transfer-Encoding: chunked
Date: Sun, 05 Aug 2007 13:11:48 GMT

209
--MIMEBoundaryurn_uuid_FD6CD3275633CFB09C1186319508977
Content-Type: application/soap+xml; charset=UTF-8
Content-Transfer-Encoding: 8bit
Content-ID: <0.urn:uuid:FD6CD3275633CFB09C1186319508978@apache.org>
   <?xml version='1.0' encoding='UTF-8'?>
      <soapenv:Envelope xmlns:soapenv="http://www.w3.org/2003/05/soap-envelope">
         <soapenv:Body>
            <swa:uploadFileResponse xmlns:swa="http://service.openframework.or.kr/xsd">
               <swa:message>File saved succesfully.</swa:message>
            </swa:uploadFileResponse>
         </soapenv:Body>
      </soapenv:Envelope>
38

--MIMEBoundaryurn_uuid_FD6CD3275633CFB09C1186319508977
2
--
0


==============

파일 다운로드

==============
Listen Port: 9000
Target Host: 127.0.0.1
Target Port: 8080
==== Request ====
POST /axis2/services/AttachmentService HTTP/1.1
Content-Type: multipart/related; boundary=MIMEBoundaryurn_uuid_9C7C76D3DAD79E01231186319531650; 
type="application/soap+xml"; start="<0.urn:uuid:9C7C76D3DAD79E01231186319531651@apache.org>";
charset=UTF-8; action="urn:getFile"
User-Agent: Axis2
Host: 127.0.0.1:9000
Transfer-Encoding: chunked

21e
--MIMEBoundaryurn_uuid_9C7C76D3DAD79E01231186319531650
Content-Type: application/soap+xml; charset=UTF-8
Content-Transfer-Encoding: 8bit
Content-ID: <0.urn:uuid:9C7C76D3DAD79E01231186319531651@apache.org>
   <?xml version='1.0' encoding='UTF-8'?>
      <soapenv:Envelope xmlns:soapenv="http://www.w3.org/2003/05/soap-envelope">
         <soapenv:Body>
            <swa:getFile xmlns:swa="http://service.openframework.or.kr/xsd">
               <swa:name>testresult.txt</swa:name>
            </swa:getFile>
         </soapenv:Body>
      </soapenv:Envelope>--MIMEBoundaryurn_uuid_9C7C76D3DAD79E01231186319531650--0
==== Response ====
HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Content-Type: multipart/related; boundary=MIMEBoundaryurn_uuid_FD6CD3275633CFB09C1186319531842; 
type="application/soap+xml"; start="0.urn:uuid:FD6CD3275633CFB09C1186319531843@apache.org"
action="urn:getFileResponse";charset=UTF-8
Transfer-Encoding: chunked
Date: Sun, 05 Aug 2007 13:12:11 GMT

212
--MIMEBoundaryurn_uuid_FD6CD3275633CFB09C1186319531842
Content-Type: application/soap+xml; charset=UTF-8
Content-Transfer-Encoding: 8bit
Content-ID: <0.urn:uuid:FD6CD3275633CFB09C1186319531843@apache.org>
   <?xml version='1.0' encoding='UTF-8'?>
      <soapenv:Envelope xmlns:soapenv="http://www.w3.org/2003/05/soap-envelope">
         <soapenv:Body>
            <swa:getFileResponse xmlns:swa="http://service.openframework.or.kr/xsd">
               <swa:graph href="cid:urn:uuid:FD6CD3275633CFB09C1186319531841" />
            </swa:getFileResponse>
         </soapenv:Body>
      </soapenv:Envelope>
      38--MIMEBoundaryurn_uuid_FD6CD3275633CFB09C1186319531842b0
      Content-Type: text/plainContent-Transfer-Encoding: binaryContent-ID: 
      <urn:uuid:FD6CD3275633CFB09C1186319531841>hahahahahhjahahalkdhflkahdslfkjaldkjsfljasd38
      --MIMEBoundaryurn_uuid_FD6CD3275633CFB09C11863195318422--0

==============

예제소스#

Axis2AttachmentSWA.zip(info)

Add new attachment

Only authorized users are allowed to upload new attachments.

List of attachments

Kind Attachment Name Size Version Date Modified Author Change note
png
1.png 13.8 kB 1 05-Aug-2007 22:02 DongGukLee
png
2.png 11.1 kB 1 05-Aug-2007 22:03 DongGukLee
png
3.png 10.0 kB 1 05-Aug-2007 22:03 DongGukLee
png
4.png 11.3 kB 1 05-Aug-2007 22:03 DongGukLee
png
5.png 10.6 kB 1 05-Aug-2007 22:03 DongGukLee
png
6.png 10.8 kB 1 05-Aug-2007 22:03 DongGukLee
png
7.png 11.3 kB 1 05-Aug-2007 22:17 DongGukLee
png
8.png 71.2 kB 1 05-Aug-2007 22:25 DongGukLee
zip
Axis2AttachmentSWA.zip 15.8 kB 1 05-Aug-2007 22:27 DongGukLee
« This page (revision-5) was last changed on 05-Aug-2007 22:28 by DongGukLee