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

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

참조 : http://www.ibm.com/developerworks/library/x-axiom/ </div>

Axis2에서 MTOM 방식으로 첨부파일 가져오기#

서비스 클래스#

package kr.or.openframework.service;

import java.io.File;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;

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.axiom.om.OMText;
import org.apache.axis2.AxisFault;

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

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

  public OMElement getFile(OMElement elementthrows Exception {
    File file = null;
    checkResourceDir(file);
    String fileName = element.getFirstElement().getText();

    System.out.println("============> file name : " + fileName);
    System.out.println("============> full file name : " + fileDir + File.separator + fileName);

    file = new File(fileDir + File.separator + fileName);
    checkResourceDir(file);
    OMFactory fac = OMAbstractFactory.getOMFactory();
    OMNamespace omNs = fac.createOMNamespace(nameSpace, "mtom");
    OMElement fileElement = fac.createOMElement("file", omNs);
    file = new File(fileDir + File.separator + fileName);
    DataSource dataSource = new FileDataSource(file);
    DataHandler dataHandler = new DataHandler(dataSource);
    OMText textData = fac.createOMText(dataHandler, true);
    fileElement.addChild(textData);

    System.out.println("============> success  ");

    return fileElement;
  }
}

service.xml 파일#

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

<service name="MtomService">
  <description>Axis2에서 MTOM을 사용하여 첨부파일 처리하기</description>

  <parameter name="enableMTOM" 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.MtomService
  </parameter>
  <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에 해당되는 값이나 MTOM을 활성화 시키기 위한 파라미터 셋팅을 위해 선택해주는 방법이 좋다.
5.png
  • AAR 파일 저장 위치 지정
6.png

위 과정을 거치고 나서 http://localhost:8080/axis2/axis2-admin/upload 에 접근하여 AAR파일을 업로드 한다.

클라이언트 코드#

package client;

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

import javax.activation.DataHandler;

import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMNamespace;
import org.apache.axiom.om.OMText;
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 MTOMClient {

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

  @SuppressWarnings("unchecked")
  public static void main(String[] argsthrows Exception {
    // 첨부파일 다운로드
     getFile("testresult.txt");
  }
  
  public static void getFile(String fileNamethrows Exception {
    ServiceClient sender = getServiceClient("getFile");
    OperationClient mepClient = sender.createClient(ServiceClient.ANON_OUT_IN_OP);
    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 ele = body.getFirstElement();
    OMText binaryNode = (OMTextele.getFirstOMChild();

    // 첨부파일 아이디로 Attachment Part 가져오기
    DataHandler dataHandler = (DataHandlerbinaryNode.getDataHandler();

    // 실제 데이터를 클라이언트로 파일로 저장하기
    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 ServiceClient getServiceClient(String operationNamethrows AxisFault {
    Options options = new Options();
    // 큰 첨부파일을 받을때 타임아웃값을 증가시켜야 한다.
    options.setTimeOutInMilliSeconds(10000);
    // SOAP with Attachment 를 위한 프라퍼티를  true로 지정
    options.setProperty(Constants.Configuration.ENABLE_MTOM, Constants.VALUE_TRUE);
    // SOAP 버전 지정
    options.setSoapVersionURI(SOAP12Constants.SOAP_ENVELOPE_NAMESPACE_URI);
    // 웹서비스 Endpoint URL을 지정한다. 
    options.setTo(targetEPR);
    // 사용할 operation 지정
    options.setAction("urn:" + operationName);

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

    ServiceClient sender = new ServiceClient(configContext, null);
    sender.setOptions(options);

    return sender;
  }
}

7.png

SOAP 메시지#

파일 다운로드

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

23c
--MIMEBoundaryurn_uuid_205EE84D85F3857E871186361662109
Content-Type: application/xop+xml; charset=UTF-8; type="application/soap+xml"
Content-Transfer-Encoding: binary
Content-ID: <0.urn:uuid:205EE84D85F3857E871186361662110@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_205EE84D85F3857E871186361662109--0
==== Response ====
HTTP/1.1 200 OK
Content-Type: multipart/related; boundary=MIMEBoundaryurn_uuid_C664BCA4929A5111A31186361662320; type="application/xop+xml"; start="0.urn:uuid:C664BCA4929A5111A31186361662321@apache.org"; start-info="application/soap+xml"; action="urn:getFileResponse";charset=UTF-8
Transfer-Encoding: chunked
Date: Mon, 06 Aug 2007 00:54:22 GMT
Server: Apache-Coyote/1.1

25e
--MIMEBoundaryurn_uuid_C664BCA4929A5111A31186361662320
Content-Type: application/xop+xml; charset=UTF-8; type="application/soap+xml"
Content-Transfer-Encoding: binary
Content-ID: <0.urn:uuid:C664BCA4929A5111A31186361662321@apache.org>
   <?xml version='1.0' encoding='UTF-8'?>
      <soapenv:Envelope xmlns:soapenv="http://www.w3.org/2003/05/soap-envelope">
         <soapenv:Body>
            <mtom:file xmlns:mtom="http://service.openframework.or.kr/xsd">
               <xop:Include href="cid:1.urn:uuid:C664BCA4929A5111A31186361662322@apache.org" xmlns:xop="http://www.w3.org/2004/08/xop/include" />
            </mtom:file>
         </soapenv:Body>
      </soapenv:Envelope>
38

--MIMEBoundaryurn_uuid_C664BCA4929A5111A31186361662320
a5

Content-Type: text/plain
Content-Transfer-Encoding: binary
Content-ID: 
      <1.urn:uuid:C664BCA4929A5111A31186361662322@apache.org>this is test documenthahaha
38

--MIMEBoundaryurn_uuid_C664BCA4929A5111A31186361662320
2
--
0


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

예제소스#

Axis2AttachmentMTOM.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.7 kB 1 06-Aug-2007 12:28 DongGukLee
png
2.png 11.3 kB 1 06-Aug-2007 12:28 DongGukLee
png
3.png 10.2 kB 1 06-Aug-2007 12:28 DongGukLee
png
4.png 9.9 kB 1 06-Aug-2007 12:28 DongGukLee
png
5.png 11.0 kB 1 06-Aug-2007 12:28 DongGukLee
png
6.png 10.9 kB 1 06-Aug-2007 12:28 DongGukLee
png
7.png 21.4 kB 1 06-Aug-2007 12:30 DongGukLee
zip
Axis2AttachmentMTOM.zip 8.3 kB 1 06-Aug-2007 12:30 DongGukLee
« This page (revision-5) was last changed on 06-Aug-2007 12:32 by DongGukLee