'soap'에 해당되는 글 3건

  1. 2011.04.05 [SOAP강좌] Java 서버 - Delphi 클라이언트
  2. 2011.04.05 JAVA로 SOAP을 구현하려면?
  3. 2011.04.05 Soap이란?
SOAP2011. 4. 5. 15:41

▶ SOAP

SOAP(Simple Object Access Protocol)에 대한 설명은 다른 사이트에 잘 나와 있으니 찾아 보세요.
여기에서는 Java로 SOAP 서버를 만들고, Tomcat으로 Web 서비스 하여, 클라이언트는 Delphi로 만들어 보겠습니다.
이와 같은 예가 외국 사이트를 찾아 보아도 별로 없더군요. 그래서 허접한 설명이지만 도움이 될까 해서 올립니다.
(기회가 되면 배열이나, Dataset도 구현 하고 싶지만 시간이 없어서...)

일부 소스와 내용은 에어콘 출판사의 차세대 자바 SOAP AXUS을 참조 했습니다.

▶ 준비물

JDK 1.4.x 이상 (http://java.sun.com)
Tomcat 4.1.36 (http://tomcat.apache.org/)
AXIS 1.4 (http://ws.apache.org/axis/)
Delphi 7 (http://www.borland.com)

▶ SOAP Web 서비스 설치

여기에서 JDK, Tomcat의 설치는 따로 하지 않겠습니다. 이것도 다른 사이트를 참조하세요.

1. axis-bin-1_4.zip 압축 풀기

Apache에서 받은 axis-bin-1_4.zip을 압축을 특정 폴더에 풀어 주세요. 저는 C:\SOAP\axis-1_4 에 풀었습니다.
앞으로 설명은 C:\SOAP\axis-1_4 으로 하겠습니다.

2. %tomcat_home%\conf\server.xml

아래 내용을 추가해서 AXIS 가상 경로를 추가 Tomcat을 다시 실행 시켜주세요.

<!-- Tomcat SOAP Context -->
<Context path="/axis" docBase="C:\SOAP\axis-1_4\webapps\axis" debug="0"
         reloadable="true" crossContext="true">
</Context>

▶ Java로 SOAP 서버 만들기

아래와 내용과 같이 HelloWorld.java을 만들고, 이 파일을 C:\SOAP\axis-1_4\webapps\axis 디렉토리에 확장자가 .jws로 수정 HelloWorld.jws을 C:\SOAP\axis-1_4\webapps\axis 복사해주세요.

HelloWorld.java 파일

public class HelloWorld {

  public HelloWorld() {
  }
 
  public String getHelloWorldMessage(String name) {
    return "Hello World to " + name;
  }
}

확인하기

지금까지 잘 하셨다면 브라우저에서 http://localhost:8080/axis/HelloWorld.jws 주소로 보시면 아래와 같이 나올 것입니다.

사용자 삽입 이미지















▶ WSDL 파일 만들기


SOAP의 WSDL 파일이 어떤 일을 하는지도 다른 사이트에 자세히 나와 있으니 이것도 다른 사이트에서 찾아보세요.
여기에서는 WSDL 파일을 AXIS을 이용해서 만들고, Delphi로 사용하는 방법만 설명하겠습니다.

브라우저에서 http://localhost:8080/axis/HelloWorld.jws 페이지를 열어서 Click to see the WSDL을 선택하시면 아래와 같이 나올 것입니다.

사용자 삽입 이미지


























이 내용을 복사해서 메모장에 붙여 넣은 후 HelloWorld.wsdl로 저장합니다.

▶ Delphi 로 Client 만들기

1. 새로운 프로젝트을 만들어 주세요.

2  File > New > Other... 선택 WebServices 창에서 WSDL Importer 아이콘을 더블 클릭

사용자 삽입 이미지




















3. HelloWorld.wsdl 선택하고, [Next] 버튼 선택

사용자 삽입 이미지
























4. [Finish] 버튼 선택

사용자 삽입 이미지
























지금까지 하셨으면 HelloWorld1.pas 파일이 만들어 졌을 것입니다.

5. Unit1.pas을 열어서 Button 과 Edit Box을 추가 해주세요

6. Unit1.pas 아래와 같이 코딩 해주세요. 추가된 코드는 파란색으로 표시 해두었습니다.

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, HelloWorld1;

type
  TForm1 = class(TForm)
    Button1: TButton;
    Edit1: TEdit;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
    FHelloWorld : HelloWorld;
  public
    { Public declarations }
    function GetHelloWorldService(): HelloWorld;
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

function TForm1.GetHelloWorldService(): HelloWorld;
begin
  if FHelloWorld = nil then begin
    FHelloWorld := GetHelloWorld();
  end;
  Result := FHelloWorld;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  Edit1.Text := GetHelloWorld().getHelloWorldMessage('AXIS');
end;


end.

▶ 실행 결과

사용자 삽입 이미지







- 출처 : http://bluexmas.tistory.com/20 크리스

'SOAP' 카테고리의 다른 글

JAVA로 SOAP 구축하기(2)  (0) 2011.04.05
JAVA로 SOAP 구축하기(1)  (0) 2011.04.05
기본 XML Web Services - MSDN  (0) 2011.04.05
JAVA로 SOAP을 구현하려면?  (0) 2011.04.05
Soap이란?  (0) 2011.04.05
Posted by 아로나
SOAP2011. 4. 5. 15:29

Tip: SOAP attachments와 JAX-RPC

 

 


난이도 : 중급

Russell Butek, 소프트웨어 엔지니어, IBM

2004 년 2 월 27 일

JAX-RPC는 SOAP with attachments를 지원한다. JAX-RPC API를 사용하여 MIME attachments를 보내는 방법을 이 글에서 설명한다.

SOAP 메시징 프로토콜은 SOAP 메시지들을 통해 MIME attachments를 보낼 수 있도록 한다. WSDL은 이 attachment의 디스크립션을 제공한다. JAX-RPC는 attachment의 WSDL 디스크립션을 자바로 매핑한다. 이 글에서 JAX-RPC 매핑을 사용하여 SOAP 메시지에서 attachment를 보내는 방법을 설명한다.

WSDL

attachment의 WSDL 디스크립션은 그다지 단순하지가 않다. Listing 1의 WSDL을 보자.


Listing 1. WSDL with attachments
<?xml version="1.0" encoding="utf-8"?>
<definitions
    xmlns="http://schemas.xmlsoap.org/wsdl/"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
    xmlns:mime="http://schemas.xmlsoap.org/wsdl/mime/"
    targetNamespace="urn:attachment.tip"
    xmlns:tns="urn:attachment.tip">
  <message name="empty"/>
  <message name="imageMsg">
    <part name="image" type="xsd:hexBinary"/>
  </message>
  <message name="octetMsg">
    <part name="octet" type="xsd:hexBinary"/>
  </message>

  <portType name="AttachmentTip">
    <operation name="sendImage">
      <input message="tns:imageMsg"/>
      <output message="tns:empty"/>
    </operation>
    <operation name="sendOctet">
      <input message="tns:octetMsg"/>
      <output message="tns:empty"/>
    </operation>
  </portType>

  <binding name="AttachmentBinding" type="tns:AttachmentTip">
    <soap:binding style="rpc"
                  transport="http://schemas.xmlsoap.org/soap/http"/>
    <operation name="sendImage">
      <soap:operation soapAction=""/>
      <input>
        <mime:multipartRelated>
          <mime:part>
            <soap:body use="literal"/>
          </mime:part>
          <mime:part>
            <mime:content part="image" type="image/jpeg"/>
          </mime:part>
        </mime:multipartRelated>
      </input>
      <output>
        <soap:body use="literal"/>
      </output>
    </operation>
    <operation name="sendOctet">
      <soap:operation soapAction=""/>
      <input>
        <mime:multipartRelated>
          <mime:part>
            <soap:body use="literal"/>
          </mime:part>
          <mime:part>
            <mime:content part="octet" type="application/octet-stream"/>
          </mime:part>
        </mime:multipartRelated>
      </input>
      <output>
        <soap:body use="literal"/>
      </output>
    </operation>
  </binding>

  <service name="AttachmentService">
    <port name="AttachmentTip" binding="tns:AttachmentBinding">
      <soap:address
          location="http://localhost:9080/attachment/services/AttachmentTip"/>
    </port>
  </service>

</definitions>

WS-I와 attachments


MIME 유형은 WSDL의 '인터페이스'로 정의될 수 없다. WS-I organization (참고자료)은 모든 MIME 유형을 위한 새로운 XML 유형을 도입하여 부분적이라도 이러한 단점을 보완을 시도하고 있다: wsi:swaRef. 이 글을 쓰는 당시에는 이 유형은 작업중에 있었으며 표준화된 자바 바인딩이 존재하지 않았음을 밝힌다.

우선 기억해야 할 것은 항상 바인딩에 대처하기 전까지는 어떤 MIME 정보도 없다는 것이다. 한 순간이라도 바인딩을 무시하고 WSDL의 '인터페이스'(portType과 메시지)만을 본다면 두 개의 오퍼레이션인 sendImagesendOctet를 보게 될 것이다. 이들 각각은 hexBinary 인풋을 갖고 있다. hexBinarybyte[]로 매핑한다. 단지 이 정보만을 이용하여 이 portType이 Java language Service Endpoint Interface (SEI)로 매핑되는 것을 짐직할 수 있다. 이것은 두 개의 메소드를 갖고 있는데 각각 하나의 byte[] 매개변수를 갖고있다. 이는 MIME 유형을 제외한 모든 것에 알맞은 생각이다. 하지만 MIME 유형의 경우 실제 매개변수 유형을 결정하려면 바인딩을 살펴보아야한다.

바인딩에서 오퍼레이션용 인풋이 실제로 MIME 콘텐트 유형인 image/jpegapplication/octet-stream이라는 것을 알 수 있다. hexBinary가 아니다. JAX-RPC는 이들을 java.awt.Imagejavax.activation.DataHandler에 매핑하도록 정의한다.




위로


Service Endpoint Interface

Listing 2에는 Listing 1의 WSDL에서 만들어진 Java language SEI가 포함되어 있다.


Listing 2. AttachmentTip SEI
package tip.attachment;

import java.awt.Image;
import java.rmi.Remote;
import java.rmi.RemoteException;
import javax.activation.DataHandler;

public interface AttachmentTip extends Remote {
    public void sendImage(Image image) throws RemoteException;
    public void sendOctet(DataHandler octet) throws RemoteException;
}

WSDL의 sendImage 오퍼페이션은 java.awt.Image 매개변수를 이용하여 자바 프로그램 메소드가 된다. 매우 단순하고 깔끔하다. 표 1은 MIME 유형을 자바 유형으로 매핑한 리스트이다.

표 1 - JAX-RPC 매핑

MIME Type Java Type
image/gif, image/jpeg java.awt.Image
text/plain java.lang.String
multipart/* javax.mail.internet.MimeMultipart
text/xml, application/xml javax.xml.transform.Source



위로


클라이언트 구현

JAX-RPC 구현을 사용하여 AttachmentTip WSDL에서 모든 클라이언트 쪽 매핑을 만든다고 가정한다. 클라이언트 구현은 이 매핑에 의존할 것이고 특히 Listing 2의 AttachmentTip SEI를 의존한다.

attachments의 클라이언트 구현은 우선 Service에서 SEI의 구현을 얻는 것으로 시작한다.(Listing 3).

sendImage 메소드 호출하기

SEI 구현을 갖게 되면 attachment로 이 메소드를 호출할 수 있다. sendImage의 경우, 이 attachment는 java.awt.Image 이다. 이 뿐이다. JAX-RPC 구현은 모든 이미지가 attachment로서 보내지는 것을 알고 있고 이에 따라 SOAP 메시지를 만든다. 클라이언트 프로그래머는 attachment가 개입되었는지를 알 필요가 없다. (Listing 3).


Listing 3. AttachmentTip 클라이언트 구현과 sendImage 호출
package tip.attachment;

import java.awt.Image;
import java.awt.Toolkit;

import java.net.URL;

import java.rmi.RemoteException;

import javax.xml.namespace.QName;

import javax.xml.rpc.Service;
import javax.xml.rpc.ServiceFactory;

public class AttachmentTipClient {

    static AttachmentTip getTip() throws Exception {
        QName serviceName = new QName(
                "urn:attachment.tip",
                "AttachmentService");
        URL wsdlLocation = new URL(
                "http://localhost:9080/attachment/services/AttachmentTip?wsdl");
        ServiceFactory factory = ServiceFactory.newInstance();
        Service service = factory.createService(wsdlLocation, serviceName);
        QName portName = new QName("", "AttachmentTip");
        return (AttachmentTip) service.getPort(
                portName,
                AttachmentTip.class);
    }

    static void sendImage(AttachmentTip tip, String fileName)
            throws RemoteException {
        Toolkit toolkit = Toolkit.getDefaultToolkit();
        Image image = toolkit.createImage(fileName);
        tip.sendImage(image);
    }

    public static void main(String[] args) {
        try {
            AttachmentTip tip = getTip();
            sendImage(tip, args[0]);
        }
        catch (Throwable t) {
            t.printStackTrace();
        }
    }
}

sendOctet 메소드 호출하기

비 지정 MIME 유형을 매핑할 때 유의할 점


JAX-RPC는 표 1에 나타나지 않은 MIME 유형을 지원하는 구현을 필요로하지 않는다. 구현은 비 지정 MIME 유형을 DataHandler로 매핑하지 않을 수도 있다. 예를 들어, WebSphere 웹 서비스는 Application Server 6.0 버전이 나오기 전까지는 이 매핑을 지원하지 않는다.

JAX-RPC가 매핑을 정의한 몇 가지 MIME 유형이 있다는 것은 다행이다. (표 1 참조). For those MIME types for which there is no explicit 뚜렷한 JAX-RPC 매핑이 없는 MIME 유형의 경우 javax.activation.DataHandler 객체와 함께 남아있다. 이 클래스는 Java Activation Framework (JAF -- 참고자료)의 일부이다. 따라서 JAF에 대해 알아야한다. 그다지 어렵지 않다. DataHandler에는 javax.activation.DataSource가 포함되어 있고 인풋과 아웃풋 스트림이 포함되어 있다. 대부분의 자바 프로그래밍 유형은 이 스트림에서 매우 쉽게 변환된다. 게다가 활성화 프레임웍도 도움이 된다. attachment 데이터가 파일에 있으면 활성화 프레이웍은 javax.activation.FileDataSource 클래스를 제공하고 따라서 스트림 단계를 우회할 수 있다.(Listing 4) .


Listing 4. 완전한 AttachmentTip 클라이언트 구현
package tip.attachment;

import java.awt.Image;
import java.awt.Toolkit;

import java.net.URL;

import java.rmi.RemoteException;

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

import javax.xml.namespace.QName;

import javax.xml.rpc.Service;
import javax.xml.rpc.ServiceFactory;

public class AttachmentTipClient {

    static AttachmentTip getTip() throws Exception {
        QName serviceName = new QName(
                "urn:attachment.tip",
                "AttachmentService");
        URL wsdlLocation = new URL(
                "http://localhost:9080/attachment/services/AttachmentTip?wsdl");
        ServiceFactory factory = ServiceFactory.newInstance();
        Service service = factory.createService(wsdlLocation, serviceName);
        QName portName = new QName("", "AttachmentTip");
        return (AttachmentTip) service.getPort(
                portName,
                AttachmentTip.class);
    }

    static void sendImage(AttachmentTip tip, String fileName)
            throws RemoteException {
        Toolkit toolkit = Toolkit.getDefaultToolkit();
        Image image = toolkit.createImage(fileName);
        tip.sendImage(image);
    }

    static void sendOctet(AttachmentTip tip, String fileName)
            throws RemoteException {
        FileDataSource fds = new FileDataSource(fileName);
        DataHandler dh = new DataHandler(fds);
        tip.sendOctet(dh);
    }

    public static void main(String[] args) {
        try {
            AttachmentTip tip = getTip();
            sendImage(tip, args[0]);
            sendOctet(tip, args[0]);
        }
        catch (Throwable t) {
            t.printStackTrace();
        }
    }
}

두 개의 attachment 작동에 대한 데이터로 같은 파일을 사용했지만 어디까지나 이것은 sendOctet에 한해서였다는 것을 기억하라. 이를 고려하지 않는다면 상상에 맡기겠다. application/octet-streamFileDataSource용 디폴트 콘텐트 유형이다. 이것이 바로 내가 이를 사용한 이유이다. 파일에 데이터를 갖고 있지 않다면 application/octet-stream 말고 다른 것으로 보내야한다. DataSource의 구현을 만들어야 하지만 이는 간단한 인터페이스이기 때문에 많은 노력이 필요하지는 않다.




위로


참고자료




위로


필자소개

Russell Butek: IBM WebSphere Web services engine 개발자. IBM JAX-RPC Java Specification Request (JSR) 전문가 그룹 대표.



- 출처 : http://www.ibm.com/developerworks/kr/webservices/library/ws-tip-soapjax.html#N100EA -

'SOAP' 카테고리의 다른 글

JAVA로 SOAP 구축하기(2)  (0) 2011.04.05
JAVA로 SOAP 구축하기(1)  (0) 2011.04.05
[SOAP강좌] Java 서버 - Delphi 클라이언트  (0) 2011.04.05
기본 XML Web Services - MSDN  (0) 2011.04.05
Soap이란?  (0) 2011.04.05
Posted by 아로나
SOAP2011. 4. 5. 14:17

1. Soap이란?

 

-SOAP(Simple Object Access Protocol)은 일반적으로 널리 알려진 HTTP,HTTPS,SMTP등을 사용하여 XML기반의 메시지를 컴퓨터 네트워크 상에서 교환하는 형태의 프로토콜

 

-SOAP은 웹 서비스(Web Service)에서 기본적인 메시지를 전달하는 기반

 

2. Soap 작동원리

 대다수의 방화벽이 웹 포트인 80 포트만 허용하기 때문에 SOAP은 대부분 HTTP에 의존하여 메시징 처리가 이루어진다. SOAP이 인터넷을 통한 메시징 처리의 표준으로 자리 잡을 수 있었던 이유는 HTTP 위에 SOAP이 올라갈 수 있기 때문이다. HTTP위에 SOAP이 올라간다는 것은 HTTP의 요청과 응답에 메시지에 SOAP 메시지가 포함될 수 있다는 것을 의미한다.

 SOAP 스펙은 SOAP 메시지들이 단방향(one-way)이 아니라 양방향(two-way)이라고 말하고 있다 서버뿐 아니라 클라이언트도 SOAP메시지를 해석할 수 있어야 한다.

 

SOAP에 HTTP를 이용하는 이유
·          HTTP는 이미 널리 구현되어 있으며, 이해하기 쉬운 프로토콜이다.
·          그 자체가 가지고 있는 요청/응답 패러다임이 RPC와 잘 들어 맞는다.
·          이미 대부분의 방화벽이 HTTP에서 작업할 수 있도록 설정되어 있다.
·          HTTP보안 소켓 레이어(Secure Sockets Layer, SSL)를 이용하여 쉽게 보안을 구축 할 수 있다.
·        현재의 주 컴포넌트 기술로 일컬어지는 JAVA, CORBA, COM 등은 목적은 비슷하지만 목적을 구현하는 방법은 매우 다르므로 호환성을 기대하기 어렵다.
 
SOAP TCP HTTP뿐만 아니라 SMTP 같은 다양한 프로토콜과도 함께 사용할 수 있는 것이다. 메시징 서버를 사용해서 메시지 처리를 할 때와 마찬가지로, SOAP은 기본적으로 단방향으로 메시지를 보낸다. 송신자는 메시지를 보내지만, 수신자로부터 메시지를 받지는 않는다. 하지만 송신자가 메시지를 보내고 그 결과로 다시 SOAP 프로토콜을 통해 메시지를 받는 것은 가능하다.
 

 

 
3. Soap 메시지 구조
 SOAP 메시지는 크게 SOAP Envelope, SOAP Header, SOAP Body, SOAP Fault로 구성되어있다.
 

 

·           SOAP Envelope : EnvelopeSOAP 메시지를 감싸는 가장 상위의 요소이다. EnvelopeHeaderBody를 가질 수 있다.
 
·           SOAP Header : Header는 메시지에서 필수적인 요소는 아니지만 SOAP 메시지에 기능을 추가 하는 역할을 담당한다. 여러 가지 정보를 헤더에 담기 위해 여러 개의 블록으로 구성되어 있으며, HeaderEnvelope 태그 다음에 가장 먼저 나오는 항목이어야 한다. 보통 Header는 인코딩, 인증, 트랜잭션 같은 관리적인 문제에 사용된다.
 
·           SOAP Body : BodySOAP을 통해 전송할 데이터로 채워진다. 여러 개의 블록으로 구성될 수 있으며, 요청할 때 요청할 웹 서비스의 이름과 매개변수로 채워지고, 응답할 때는 결과로 채워진다.
 
·           SOAP Fault : SOAP 처리를 한 후 발생하는 에러 처리 메시지가 이 영역에 채워진다. SOAP Fault는 에러에 대한 자세한 내용을 기술할 수 있도록 다음과 같이 여러 개의 요소를 지원한다.
 
-         <faultcode> : 에러의 종류를 코드로 구분할 수 있도록 해준다. 웹 서비스 소비자는 이 코드를 보고 어떤 종류의 에러가 발생했는지 알 수 있다. SOAP에는 SOAP 메시징에서 일어날 수 있는 기본 코드를 정의하고 있고 웹 서비스 제공자가 별도로 정의할 수도 있다.
-         <faultstring> : 코드가 기계적인 내용인 데 반해, 스트링은 사람이 에러에 대한 내용을 읽고 이해할 수 있도록 해준다.
-         <faultactor> : 메시징 처리를 하는 중에 어떤 부분에서 에러가 발생했는지 알릴 때 사용된다.
-         <detail> : Body에 관련된 데이터 때문에 SOAP 메시징이 성공하지 못했을 경우에 사용된다. 만약 에러가 발생했는데 <detail> 부분이 없다면, Body와 관련된 부분에서 에러가 발생하지 않았다는 것을 알 수 있다.
 
 
 4. Soap의 데이터베이스 접근방법
 
         The SOAP developer's approach to such a problem is to encapsulate the database request logic for the service in a method (or function) in C or VB or Java etc, then set up a process that listens for requests to the service; such requests being in SOAP format and containing the service name and any required parameters. As mentioned, the transport layer might be HTTP though it could just as easily be SMTP or something else. Now, the listener process, which for simplicity is typically written in the same language as the service method, decodes the incoming SOAP request and transforms it into an invocation of the method. It then takes the result of the method call, encodes it into a SOAP message (response) and sends it back to the requester. Conceptually, this arrangement looks like the following:
 
 
 
예 ) ORACLE 

 

 

5. Soap Message Packet

 

 

Client code makes a service call by invoking the appropriate method in the SOAP package (1). The

SOAP package's SOAP serializer converts this invocation into a SOAP request and sends that to t

e HTTP encoder (2). The HTTP encoder wraps the SOAP message in a HTTP request and sends it

o the SOAP server (3). The response is received from the SOAP server by the HTTP encoder/deco

er module(4) which decodes it and extracts the SOAP response which it hands to the SOAP deser

alizer(5). The SOAP deserializer deserializes the message and passes the result to the client code

(6) as the return value to the orginal invocation (1).

 

 

 

 

 

 Appserver process receives a HTTP request from the SOAP Client at the SOAP service's URL (1) and passes it accordingly to the SOAP servlet (2). The SOAP servlet uses the package-supplied HTTP and SOAP decoding functionality to extract the details of the services call (3 and 4), ie. the method name and method parameters. Once armed with these the SOAP servlet can invoke the method (5 and 6), encode the response (7 and 8) and supply the HTTP response to the HTTP Request handler (9) which in turn replies to the SOAP Client (10). Note that the Servlet Thread box simply indicates what is running in the Servlet's VM.

'SOAP' 카테고리의 다른 글

JAVA로 SOAP 구축하기(2)  (0) 2011.04.05
JAVA로 SOAP 구축하기(1)  (0) 2011.04.05
[SOAP강좌] Java 서버 - Delphi 클라이언트  (0) 2011.04.05
기본 XML Web Services - MSDN  (0) 2011.04.05
JAVA로 SOAP을 구현하려면?  (0) 2011.04.05
Posted by 아로나