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");
자세한 내용은 오류 발생 시 XML 요청/응답 추적 질문을 참조하십시오.
다음은 raw code의 해결책입니다(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을에 "Tomcat"을 합니다.JAVA_OPTSLinux ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★」톰캣은 '요청 및 응답'에서할 수 .catalina.outfilename을 클릭합니다.
export JAVA_OPTS="$JAVA_OPTS -Dcom.sun.xml.ws.transport.http.client.HttpTransportPipe.dump=true"
「」를 SOAPHandler와 응답을 할 수 .SOAP の soap soap soap soap soap soap soap soap soap soap soap soap 。
Programmatic을 사용한 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")주석을 추가합니다.
핸들러.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) {
}
}
다음 시스템 속성을 설정하면 xml 로깅이 활성화됩니다.Java 또는 Configuration파일로 설정할 수 있습니다.
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
--------------------------------------
다른 답변에서 설명한 바와 같이 프로그래밍 방식으로 이를 수행하는 방법은 다양하지만 상당히 침습적인 메커니즘입니다.다만, JAX-WS RI(일명 「Metro」)를 사용하고 있는 것을 알고 있는 경우는, 이것을 설정 레벨로 실행할 수 있습니다.이 조작 방법에 대해서는, 여기를 참조해 주세요.어플리케이션을 조작할 필요가 없습니다.
// 이 솔루션은 XML 설정을 사용하지 않고 웹 서비스에 핸들러를 프로그래밍 방식으로 추가하는 방법을 제공합니다.
// 자세한 내용은http://http://docs.oracle.com/cd/E17904_01//web.1111/e13734/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) {
}
}
// Log Message Handler 프로그램 추가
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);
Antonio가 제공한 답변에 대해 코멘트를 할 만한 충분한 평판이 없기 때문에 새로운 답변을 게시합니다(https://stackoverflow.com/a/1957777) 참조).
SOAP 메시지를 파일(예를 들어 Log4j 경유)로 인쇄하려면 다음을 사용할 수 있습니다.
OutputStream os = new ByteArrayOutputStream();
javax.xml.soap.SOAPMessage soapMsg = context.getMessage();
soapMsg.writeTo(os);
Logger LOG = Logger.getLogger(SOAPLoggingHandler.class); // Assuming SOAPLoggingHandler is the class name
LOG.info(os.toString());
특정 상황에서는 writeTo() 메서드가 예상대로 작동하지 않을 수 있습니다(https://community.oracle.com/thread/1123104?tstart=0 또는 https://www.java.net/node/691073), 참조). 따라서 다음 코드가 이 기능을 수행합니다.
javax.xml.soap.SOAPMessage soapMsg = context.getMessage();
com.sun.xml.ws.api.message.Message msg = new com.sun.xml.ws.message.saaj.SAAJMessage(soapMsg);
com.sun.xml.ws.api.message.Packet packet = new com.sun.xml.ws.api.message.Packet(msg);
Logger LOG = Logger.getLogger(SOAPLoggingHandler.class); // Assuming SOAPLoggingHandler is the class name
LOG.info(packet.toString());
javax.xml.ws.http://javax.xml.ws 를 실장할 필요가 있습니다.다음으로 이 핸들러를 핸들러 컨피규레이션파일로 참조해야 합니다.이 파일은 서비스 엔드포인트(인터페이스 또는 구현)의 @HandlerChain 주석으로 참조됩니다.그런 다음 시스템을 통해 메시지를 출력할 수 있습니다.out 또는 logger를 지정합니다.
봐
http://java.sun.com/mailers/techtips/enterprise/2006/TechTips_June06.html
문항은 하는 내용입니다.SOAPHandler완전히 정확합니다.SOAPHandler는 JAX-WS 사양의 일부이기 때문에 이 접근방식의 이점은 JAX-WS 구현과 함께 사용할 수 있다는 것입니다.는 XML 입니다.이로 인해 메모리 사용량이 증가할 수 있습니다.JAX-WS의 다양한 실장에서는 이에 대한 독자적인 회피책이 추가되었습니다.대규모 요청 또는 대규모 응답을 사용하는 경우 독점적 접근 방식 중 하나를 검토해야 합니다.
'JDK 1.5 이상'에 대해 질문하셨기 때문에 JDK에 포함되어 있는 JAX-WS RI(메트로)라고 하는 정식 명칭에 대해 답변하겠습니다.
JAX-WS RI는 메모리 사용률 면에서 매우 효율적인 특정 솔루션을 제공합니다.
https://javaee.github.io/metro/doc/user-guide/ch02.html#efficient-handlers-in-jax-ws-ri 를 참조해 주세요.유감스럽게도 그 링크는 현재 파손되어 있습니다만, WayBack Machine에서 찾을 수 있습니다.주요 내용은 다음과 같습니다.
2007년에 메트로 경찰에서 핸들러 타입을 추가 도입했습니다.MessageHandler<MessageHandlerContext>지하철 더 효율적이다.SOAPHandler<SOAPMessageContext>모표내내 DOM 표지지지 않기않않 않않 다않 。
다음은 원본 블로그 기사의 중요한 텍스트입니다.
메시지 핸들러:
가능한 프레임워크와 RI에서의 메시지 하여 JAX-WS Specification이라는 했습니다.
MessageHandler웹 서비스 응용 프로그램을 확장합니다.이 MessageHandler SOAPHandler에 수 점이 .MessageHandlerContext(메시지 컨텍스트).Message Handler Context message 、 Message API 、 Message API 、 Message 、 Message 。블로그 제목에 입력했듯이, 이 핸들러를 사용하면 메시지에서 작업할 수 있습니다.이 핸들러는 DOM 기반 메시지뿐만 아니라 메시지에 액세스/처리하는 효율적인 방법을 제공합니다.핸들러의 프로그래밍 모델은 동일하며 메시지핸들러는 표준 논리 핸들러 및 SOAP 핸들러와 혼재할 수 있습니다.JAX-WS RI 2.1.3 메시지 핸들러이 샘플의 일부를 다음에 나타냅니다.
public class LoggingHandler implements MessageHandler<MessageHandlerContext> {
public boolean handleMessage(MessageHandlerContext mhc) {
Message m = mhc.getMessage().copy();
XMLStreamWriter writer = XMLStreamWriterFactory.create(System.out);
try {
m.writeTo(writer);
} catch (XMLStreamException e) {
e.printStackTrace();
return false;
}
return true;
}
public boolean handleFault(MessageHandlerContext mhc) {
.....
return true;
}
public void close(MessageContext messageContext) { }
public Set getHeaders() {
return null;
}
}
(2007년 블로그 투고에서 인용)
핸들러는 필요도 없습니다.LoggingHandler이 예에서는 를 핸들러 체인에 추가해야 합니다.은 다른 것과 .Handler그 방법에 대해서는, 이 페이지의 다른 회답을 참조해 주세요.
Metro GitHub repo에서 완전한 예를 찾을 수 있습니다.
logback.xml 컨피규레이션파일을 사용하면 다음 작업을 수행할 수 있습니다.
<logger name="com.sun.xml.internal.ws.transport.http.client.HttpTransportPipe" level="trace" additivity="false">
<appender-ref ref="STDOUT"/>
</logger>
다음과 같이 요구와 응답이 기록됩니다(로그 출력 설정에 따라 다름).
09:50:23.266 [qtp1068445309-21] DEBUG c.s.x.i.w.t.h.c.HttpTransportPipe - ---[HTTP request - http://xyz:8081/xyz.svc]---
Accept: application/soap+xml, multipart/related
Content-Type: application/soap+xml; charset=utf-8;action="http://xyz.Web.Services/IServiceBase/GetAccessTicket"
User-Agent: JAX-WS RI 2.2.9-b130926.1035 svn-revision#5f6196f2b90e9460065a4c2f4e30e065b245e51e
<?xml version="1.0" ?><S:Envelope xmlns:S="http://www.w3.org/2003/05/soap-envelope">[CONTENT REMOVED]</S:Envelope>--------------------
09:50:23.312 [qtp1068445309-21] DEBUG c.s.x.i.w.t.h.c.HttpTransportPipe - ---[HTTP response - http://xyz:8081/xyz.svc - 200]---
null: HTTP/1.1 200 OK
Content-Length: 792
Content-Type: application/soap+xml; charset=utf-8
Date: Tue, 12 Feb 2019 14:50:23 GMT
Server: Microsoft-IIS/10.0
X-Powered-By: ASP.NET
<s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope" xmlns:a="http://www.w3.org/2005/08/addressing">[CONTENT REMOVED]</s:Envelope>--------------------
번 .ServletFilter웹 서비스 앞에서 서비스를 수신하거나 서비스에서 반환되는 요청 및 응답을 검사합니다.
특별히 프록시를 요구하지는 않았지만, tcptrace로 접속 상황을 알 수 있는 경우가 있습니다.이 툴은 단순한 툴로 설치가 필요 없습니다.데이터 스트림을 표시하고 파일에 쓸 수도 있습니다.
실행 시 간단히 실행할 수 있습니다.
com.sun.xml.internal.ws.transport.http.client.HttpTransportPipe.dump = true
as dump는 클래스에서 다음과 같이 정의된 퍼블릭 변수입니다.
public static boolean dump;
raw XML 메시지를 변경/액세스 하고 싶다고 이해해도 될까요?
이 경우 JAXWS의 일부인 프로바이더인터페이스를 참조해 주세요.클라이언트의 대응은 「디스패치」클래스를 사용해 주세요.어쨌든 핸들러나 인터셉터를 추가할 필요는 없습니다.물론 지금도 할 수 있죠단점은 SOAP Message 구축은 전적으로 당신이 책임져야 한다는 것입니다만, 그것이 당신이 원하는 것이라면(저처럼) 이것은 완벽합니다.
서버측의 예를 다음에 나타냅니다(약간 서투른 것은, 단지 실험용이었습니다).
@WebServiceProvider(portName="Provider1Port",serviceName="Provider1",targetNamespace = "http://localhost:8123/SoapContext/SoapPort1")
@ServiceMode(value=Service.Mode.MESSAGE)
public class Provider1 implements Provider<SOAPMessage>
{
public Provider1()
{
}
public SOAPMessage invoke(SOAPMessage request)
{ try{
File log= new File("/home/aneeshb/practiceinapachecxf/log.txt");//creates file object
FileWriter fw=new FileWriter(log);//creates filewriter and actually creates file on disk
fw.write("Provider has been invoked");
fw.write("This is the request"+request.getSOAPBody().getTextContent());
MessageFactory mf = MessageFactory.newInstance();
SOAPFactory sf = SOAPFactory.newInstance();
SOAPMessage response = mf.createMessage();
SOAPBody respBody = response.getSOAPBody();
Name bodyName = sf.createName("Provider1Insertedmainbody");
respBody.addBodyElement(bodyName);
SOAPElement respContent = respBody.addChildElement("provider1");
respContent.setValue("123.00");
response.saveChanges();
fw.write("This is the response"+response.getSOAPBody().getTextContent());
fw.close();
return response;}catch(Exception e){return request;}
}
}
SEI처럼 발표하면
public class ServerJSFB {
protected ServerJSFB() throws Exception {
System.out.println("Starting Server");
System.out.println("Starting SoapService1");
Object implementor = new Provider1();//create implementor
String address = "http://localhost:8123/SoapContext/SoapPort1";
JaxWsServerFactoryBean svrFactory = new JaxWsServerFactoryBean();//create serverfactorybean
svrFactory.setAddress(address);
svrFactory.setServiceBean(implementor);
svrFactory.create();//create the server. equivalent to publishing the endpoint
System.out.println("Starting SoapService1");
}
public static void main(String args[]) throws Exception {
new ServerJSFB();
System.out.println("Server ready...");
Thread.sleep(10 * 60 * 1000);
System.out.println("Server exiting");
System.exit(0);
}
}
또는 Endpoint 클래스를 사용할 수 있습니다.그것이 도움이 되었기를 바랍니다.
그리고, 만약 당신이 헤더와 같은 것들을 다룰 필요가 없다면, 만약 당신이 서비스 모드를 PAYLOAD로 바꾸면, 당신은 Soap Body만 얻을 것입니다.
웹 서비스 비누 요청과 응답을 기록하기 위해 며칠 동안 프레임워크 라이브러리를 찾고 있었습니다.아래 코드로 문제가 해결되었습니다.
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");
한 가지 방법은 코드를 사용하지 않고 Etheral이나 WireShark와 같은 네트워크 패킷 스니퍼를 사용하는 것입니다.이러한 스니퍼는 XML 메시지가 포함된 HTTP 패킷을 payload로 캡처할 수 있으며 파일에 계속 로깅할 수 있습니다.
그러나 보다 정교한 방법은 메시지 핸들러를 직접 작성하는 것입니다.여기서 보실 수 있습니다.
정말로.HttpClientTransport의 소스를 살펴보면 java.util.logging에도 메시지를 쓰고 있음을 알 수 있습니다.로거, 그 말은 당신 로그에도 그 메시지들이 있다는 뜻이죠
예를 들어 Log4J2를 사용하는 경우 필요한 작업은 다음과 같습니다.
- 클래스 경로에 JUL-Log4J2 브리지 추가
- com.sun.xml.internal.ws.disc.client 패키지의 TRACE 레벨을 설정합니다.
- 추가 -Djava.util.logging.manager=syslog.apache.log4j.jul.응용 프로그램 시작 명령줄에 대한 LogManager 시스템 속성
이러한 절차를 수행한 후 로그에 SOAP 메시지가 표시되기 시작합니다.
SoapHandlers 。SoapHandlers가 메시지를 수정하는 경우 합니다.writeTo(out)호출됩니다.
SOAPMessage 호출writeTo(out)메서드는 자동으로 호출됩니다.saveChanges()메서드도 있습니다.그 결과, 메시지에 첨부되어 있는 모든 MTOM/XOP 바이너리 데이터가 없어집니다.
왜 이런 일이 일어나는지는 모르겠지만 문서화된 기능인 것 같습니다.
또한 이 메서드는 모든 구성 요소 AttachmentPart 개체의 데이터를 메시지로 가져오는 지점을 표시합니다.
https://docs.oracle.com/javase/7/docs/api/javax/xml/soap/SOAPMessage.html#saveChanges()
IBM Liberty 앱 서버를 실행하는 경우, ws-bnd.xml을 WEB-INF 디렉토리에 추가하십시오.
<?xml version="1.0" encoding="UTF-8"?>
<webservices-bnd
xmlns="http://websphere.ibm.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://websphere.ibm.com/xml/ns/javaee http://websphere.ibm.com/xml/ns/javaee/ibm-ws-bnd_1_0.xsd"
version="1.0">
<webservice-endpoint-properties
enableLoggingInOutInterceptor="true" />
</webservices-bnd>
글라스피시/파야라용 솔루션
로거 설정에 다음 항목 추가(로그 수준)FINER):
- com.sun.xml.ws.disc.client.HttpTransportPipe
- com.sun.xml.ws.disc.discl.discl을 참조하십시오.HttpAdapter(HttpAdapter)
여기서 찾았습니다.
언급URL : https://stackoverflow.com/questions/1945618/tracing-xml-request-responses-with-jax-ws
'programing' 카테고리의 다른 글
| Vue 데이터 모델 속성 기반 속성 이름의 값을 가져오시겠습니까? (0) | 2022.07.29 |
|---|---|
| 부팅에 실패했습니다.이진수를 찾을 수 없습니다.이클립스 헬리오스의 CDT (0) | 2022.07.29 |
| Recycleer View - 특정 위치에서 보기 (0) | 2022.07.29 |
| 기능을 속성으로 Vue 구성 요소에 전달 (0) | 2022.07.29 |
| Eclipse - Java (JRE) / (JDK) ... 가상 머신 없음 (0) | 2022.07.29 |