[java] JAX-WS로 XML 요청 / 응답 추적

JAX-WS 참조 구현 (JDK 1.5 이상에 포함 된)으로 게시 된 웹 서비스에 대한 원시 요청 / 응답 XML에 액세스하는 쉬운 방법 (일명 프록시 사용 안 함)이 있습니까? 코드를 통해이를 수행 할 수 있어야합니다. 영리한 로깅 구성으로 파일에 기록하는 것만으로도 충분할 것입니다.

나는 그렇게 할 수있는 더 복잡하고 완전한 다른 프레임 워크가 존재한다는 것을 알고 있지만 가능한 한 간단하게 유지하고 싶습니다. 축, cxf 등은 모두 피하고 싶은 상당한 오버 헤드를 추가합니다.

감사!



답변

다음 옵션을 사용하면 콘솔에 대한 모든 통신을 로깅 할 수 있습니다 (기술적으로는이 중 하나만 필요하지만 사용하는 라이브러리에 따라 다르므로 4 개를 모두 설정하는 것이 더 안전한 옵션입니다). 예를 들어 코드에서 또는 -D를 사용하는 명령 줄 매개 변수 또는 Upendra가 작성한 환경 변수로 설정할 수 있습니다.

System.setProperty("com.sun.xml.ws.transport.http.client.HttpTransportPipe.dump", "true");
System.setProperty("com.sun.xml.internal.ws.transport.http.client.HttpTransportPipe.dump", "true");
System.setProperty("com.sun.xml.ws.transport.http.HttpAdapter.dump", "true");
System.setProperty("com.sun.xml.internal.ws.transport.http.HttpAdapter.dump", "true");
System.setProperty("com.sun.xml.internal.ws.transport.http.HttpAdapter.dumpTreshold", "999999");

자세한 내용은 오류 발생시 JAX-WS로 XML 요청 / 응답 추적 질문 을 참조하십시오.


답변

다음은 원시 코드의 솔루션입니다 (stjohnroe 및 Shamik 덕분에 함께 제공).

Endpoint ep = Endpoint.create(new WebserviceImpl());
List<Handler> handlerChain = ep.getBinding().getHandlerChain();
handlerChain.add(new SOAPLoggingHandler());
ep.getBinding().setHandlerChain(handlerChain);
ep.publish(publishURL);

SOAPLoggingHandler가있는 곳 (링크 된 예제에서 추출) :

package com.myfirm.util.logging.ws;

import java.io.PrintStream;
import java.util.Map;
import java.util.Set;

import javax.xml.namespace.QName;
import javax.xml.soap.SOAPMessage;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.handler.soap.SOAPHandler;
import javax.xml.ws.handler.soap.SOAPMessageContext;

/*
 * This simple SOAPHandler will output the contents of incoming
 * and outgoing messages.
 */
public class SOAPLoggingHandler implements SOAPHandler<SOAPMessageContext> {

    // change this to redirect output if desired
    private static PrintStream out = System.out;

    public Set<QName> getHeaders() {
        return null;
    }

    public boolean handleMessage(SOAPMessageContext smc) {
        logToSystemOut(smc);
        return true;
    }

    public boolean handleFault(SOAPMessageContext smc) {
        logToSystemOut(smc);
        return true;
    }

    // nothing to clean up
    public void close(MessageContext messageContext) {
    }

    /*
     * Check the MESSAGE_OUTBOUND_PROPERTY in the context
     * to see if this is an outgoing or incoming message.
     * Write a brief message to the print stream and
     * output the message. The writeTo() method can throw
     * SOAPException or IOException
     */
    private void logToSystemOut(SOAPMessageContext smc) {
        Boolean outboundProperty = (Boolean)
            smc.get (MessageContext.MESSAGE_OUTBOUND_PROPERTY);

        if (outboundProperty.booleanValue()) {
            out.println("\nOutbound message:");
        } else {
            out.println("\nInbound message:");
        }

        SOAPMessage message = smc.getMessage();
        try {
            message.writeTo(out);
            out.println("");   // just to add a newline
        } catch (Exception e) {
            out.println("Exception in handler: " + e);
        }
    }
}


답변

Tomcat을 시작하기 전에 JAVA_OPTSLinux 환경에서 아래와 같이 설정 하십시오. 그런 다음 Tomcat을 시작하십시오. catalina.out파일 에 요청 및 응답이 표시 됩니다.

export JAVA_OPTS="$JAVA_OPTS -Dcom.sun.xml.ws.transport.http.client.HttpTransportPipe.dump=true"


답변

다음 시스템 속성을 설정하면 XML 로깅이 활성화됩니다. Java 또는 구성 파일에서 설정할 수 있습니다.

static{
        System.setProperty("com.sun.xml.ws.transport.http.client.HttpTransportPipe.dump", "true");
        System.setProperty("com.sun.xml.ws.transport.http.HttpAdapter.dump", "true");
        System.setProperty("com.sun.xml.internal.ws.transport.http.client.HttpTransportPipe.dump", "true");
        System.setProperty("com.sun.xml.internal.ws.transport.http.HttpAdapter.dump", "true");
        System.setProperty("com.sun.xml.internal.ws.transport.http.HttpAdapter.dumpTreshold", "999999");
    }

콘솔 로그 :

INFO: Outbound Message
---------------------------
ID: 1
Address: http://localhost:7001/arm-war/castService
Encoding: UTF-8
Http-Method: POST
Content-Type: text/xml
Headers: {Accept=[*/*], SOAPAction=[""]}
Payload: xml
--------------------------------------
INFO: Inbound Message
----------------------------
ID: 1
Response-Code: 200
Encoding: UTF-8
Content-Type: text/xml; charset=UTF-8
Headers: {content-type=[text/xml; charset=UTF-8], Date=[Fri, 20 Jan 2017 11:30:48 GMT], transfer-encoding=[chunked]}
Payload: xml
--------------------------------------


답변

SOAPHandler엔드 포인트 인터페이스에 주입하십시오 . SOAP 요청과 응답을 추적 할 수 있습니다

프로그래밍 방식으로 SOAPHandler 구현

ServerImplService service = new ServerImplService();
Server port = imgService.getServerImplPort();
/**********for tracing xml inbound and outbound******************************/
Binding binding = ((BindingProvider)port).getBinding();
List<Handler> handlerChain = binding.getHandlerChain();
handlerChain.add(new SOAPLoggingHandler());
binding.setHandlerChain(handlerChain);

@HandlerChain(file = "handlers.xml")엔드 포인트 인터페이스에 주석을 추가하여 선언적 입니다.

handlers.xml

<?xml version="1.0" encoding="UTF-8"?>
<handler-chains xmlns="http://java.sun.com/xml/ns/javaee">
    <handler-chain>
        <handler>
            <handler-class>SOAPLoggingHandler</handler-class>
        </handler>
    </handler-chain>
</handler-chains>

SOAPLoggingHandler.java

/*
 * This simple SOAPHandler will output the contents of incoming
 * and outgoing messages.
 */


public class SOAPLoggingHandler implements SOAPHandler<SOAPMessageContext> {
    public Set<QName> getHeaders() {
        return null;
    }

    public boolean handleMessage(SOAPMessageContext context) {
        Boolean isRequest = (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
        if (isRequest) {
            System.out.println("is Request");
        } else {
            System.out.println("is Response");
        }
        SOAPMessage message = context.getMessage();
        try {
            SOAPEnvelope envelope = message.getSOAPPart().getEnvelope();
            SOAPHeader header = envelope.getHeader();
            message.writeTo(System.out);
        } catch (SOAPException | IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return true;
    }

    public boolean handleFault(SOAPMessageContext smc) {
        return true;
    }

    // nothing to clean up
    public void close(MessageContext messageContext) {
    }

}


답변

다른 답변에서 설명한 것처럼 프로그래밍 방식 으로이 작업을 수행하는 다양한 방법이 있지만 상당히 침습적 인 메커니즘입니다. 그러나 JAX-WS RI (일명 “Metro”)를 사용중인 경우 구성 레벨에서이를 수행 할 수 있습니다. 이 작업을 수행하는 방법에 대한 지침은 여기를 참조하십시오 . 응용 프로그램을 망칠 필요가 없습니다.


답변

//이 솔루션은 XML 설정없이 웹 서비스 clien에 핸들러를 프로그래밍 방식으로 추가하는 방법을 제공합니다.

// 여기에서 전체 문서를 참조하십시오 : http://docs.oracle.com/cd/E17904_01//web.1111/e13734/handlers.htm#i222476

// SOAPHandler를 구현하는 새 클래스를 만듭니다.

public class LogMessageHandler implements SOAPHandler<SOAPMessageContext> {

@Override
public Set<QName> getHeaders() {
    return Collections.EMPTY_SET;
}

@Override
public boolean handleMessage(SOAPMessageContext context) {
    SOAPMessage msg = context.getMessage(); //Line 1
    try {
        msg.writeTo(System.out);  //Line 3
    } catch (Exception ex) {
        Logger.getLogger(LogMessageHandler.class.getName()).log(Level.SEVERE, null, ex);
    }
    return true;
}

@Override
public boolean handleFault(SOAPMessageContext context) {
    return true;
}

@Override
public void close(MessageContext context) {
}
}

// 프로그래밍 방식으로 LogMessageHandler 추가

   com.csd.Service service = null;
    URL url = new URL("https://service.demo.com/ResService.svc?wsdl");

    service = new com.csd.Service(url);

    com.csd.IService port = service.getBasicHttpBindingIService();
    BindingProvider bindingProvider = (BindingProvider)port;
    Binding binding = bindingProvider.getBinding();
    List<Handler> handlerChain = binding.getHandlerChain();
    handlerChain.add(new LogMessageHandler());
    binding.setHandlerChain(handlerChain);