Java源码示例:org.apache.cxf.message.Exchange
示例1
/**
* Called when a Conduit is actually required.
*
* @param message
* @return the Conduit to use for mediation of the message
*/
public synchronized Conduit selectConduit(Message message) {
Conduit c = message.get(Conduit.class);
if (c != null) {
return c;
}
Exchange exchange = message.getExchange();
String key = String.valueOf(System.identityHashCode(exchange));
InvocationContext invocation = getInvocationContext(key);
if ((invocation != null) && !invocation.getContext().containsKey(IS_DISTRIBUTED)) {
Endpoint target = getDistributionTarget(exchange, invocation);
if (target != null) {
setEndpoint(target);
message.put(Message.ENDPOINT_ADDRESS, target.getEndpointInfo().getAddress());
message.put(CONDUIT_COMPARE_FULL_URL, Boolean.TRUE);
overrideAddressProperty(invocation.getContext());
invocation.getContext().put(IS_DISTRIBUTED, null);
}
}
return getSelectedConduit(message);
}
示例2
protected void checkClientException(Message outMessage, Exception ex) throws Exception {
Throwable actualEx = ex instanceof Fault ? ((Fault)ex).getCause() : ex;
Exchange exchange = outMessage.getExchange();
Integer responseCode = getResponseCode(exchange);
if (actualEx instanceof ResponseProcessingException) {
throw (ResponseProcessingException)actualEx;
} else if (responseCode == null
|| responseCode < 300 && !(actualEx instanceof IOException)
|| actualEx instanceof IOException && exchange.get("client.redirect.exception") != null) {
if (actualEx instanceof ProcessingException) {
throw (RuntimeException)actualEx;
} else if (actualEx != null) {
Object useProcExProp = exchange.get("wrap.in.processing.exception");
if (actualEx instanceof RuntimeException
&& useProcExProp != null && PropertyUtils.isFalse(useProcExProp)) {
throw (Exception)actualEx;
}
throw new ProcessingException(actualEx);
} else if (!exchange.isOneWay() || cfg.isResponseExpectedForOneway()) {
waitForResponseCode(exchange);
}
}
}
示例3
@Test
public void transformInboundInterceptorInputStream() {
// Arrange
Message message = new MessageImpl();
ByteArrayInputStream inputStream =
new ByteArrayInputStream(ORIG_LOGGING_CONTENT.getBytes(StandardCharsets.UTF_8));
message.setContent(InputStream.class, inputStream);
Exchange exchange = new ExchangeImpl();
message.setExchange(exchange);
LogEventSenderMock logEventSender = new LogEventSenderMock();
LoggingInInterceptor interceptor = new TransformLoggingInInterceptor(logEventSender);
// Act
Collection<PhaseInterceptor<? extends Message>> interceptors = interceptor.getAdditionalInterceptors();
for (PhaseInterceptor intercept : interceptors) {
intercept.handleMessage(message);
}
interceptor.handleMessage(message);
// Verify
LogEvent event = logEventSender.getLogEvent();
assertNotNull(event);
assertEquals(TRANSFORMED_LOGGING_CONTENT, event.getPayload()); // only the first byte is read!
}
示例4
@Test(expected = SoapFault.class)
public void testTwoWayRequestWithReplyToNone() throws Exception {
Message message = new MessageImpl();
Exchange exchange = new ExchangeImpl();
exchange.setOutMessage(message);
message.setExchange(exchange);
setUpMessageProperty(message,
REQUESTOR_ROLE,
Boolean.FALSE);
AddressingProperties maps = new AddressingProperties();
EndpointReferenceType replyTo = new EndpointReferenceType();
replyTo.setAddress(ContextUtils.getAttributedURI(Names.WSA_NONE_ADDRESS));
maps.setReplyTo(replyTo);
AttributedURIType id =
ContextUtils.getAttributedURI("urn:uuid:12345");
maps.setMessageID(id);
maps.setAction(ContextUtils.getAttributedURI(""));
setUpMessageProperty(message,
ADDRESSING_PROPERTIES_OUTBOUND,
maps);
setUpMessageProperty(message,
"org.apache.cxf.ws.addressing.map.fault.name",
"NoneAddress");
aggregator.mediate(message, false);
}
示例5
@Test
public void testCreateWebServiceContext() {
Exchange exchange = new ExchangeImpl();
Message inMessage = new MessageImpl();
Message outMessage = new MessageImpl();
inMessage.putAll(message);
exchange.setInMessage(inMessage);
exchange.setOutMessage(outMessage);
MessageContext ctx = new WrappedMessageContext(exchange.getInMessage(), Scope.APPLICATION);
Object requestHeader = ctx.get(MessageContext.HTTP_REQUEST_HEADERS);
assertNotNull("the request header should not be null", requestHeader);
assertEquals("we should get the request header", requestHeader, HEADER);
Object responseHeader = ctx.get(MessageContext.HTTP_RESPONSE_HEADERS);
assertNull("the response header should be null", responseHeader);
Object outMessageHeader = outMessage.get(Message.PROTOCOL_HEADERS);
assertEquals("the outMessage PROTOCOL_HEADERS should be update", responseHeader, outMessageHeader);
Object inAttachments = ctx.get(MessageContext.INBOUND_MESSAGE_ATTACHMENTS);
assertNotNull("inbound attachments object must be initialized", inAttachments);
assertTrue("inbound attachments must be in a Map", inAttachments instanceof Map);
assertTrue("no inbound attachments expected", ((Map<?, ?>)inAttachments).isEmpty());
}
示例6
@Test
public void usingClientProxyStopIsCalledWhenServerReturnsNotFound() throws Exception {
final JAXRSClientFactoryBean factory = new JAXRSClientFactoryBean();
factory.setResourceClass(Library.class);
factory.setAddress("http://localhost:" + wireMockRule.port() + "/");
factory.setFeatures(Arrays.asList(new MetricsFeature(provider)));
factory.setProvider(JacksonJsonProvider.class);
stubFor(get(urlEqualTo("/books/10"))
.willReturn(aResponse()
.withStatus(404)));
try {
final Library client = factory.create(Library.class);
expectedException.expect(NotFoundException.class);
client.getBook(10);
} finally {
Mockito.verify(resourceContext, times(1)).start(any(Exchange.class));
Mockito.verify(resourceContext, times(1)).stop(anyLong(), anyLong(), anyLong(), any(Exchange.class));
Mockito.verify(endpointContext, times(1)).start(any(Exchange.class));
Mockito.verify(endpointContext, times(1)).stop(anyLong(), anyLong(), anyLong(), any(Exchange.class));
Mockito.verifyNoInteractions(operationContext);
}
}
示例7
public Object invoke(Exchange exchange, Object o) {
Object result;
String methodname = this.getTargetMethod(exchange).getName();
try {
result = this.underlying.invoke(exchange, o);
return result;
}
catch (Exception e) {
if (meters.containsKey(methodname)) {
ExceptionMeter meter = meters.get(methodname);
if (meter.getExceptionClass().isAssignableFrom(e.getClass()) ||
(e.getCause() != null &&
meter.getExceptionClass().isAssignableFrom(e.getCause().getClass()))) {
meter.getMeter().mark();
}
}
this.<RuntimeException>rethrow(e); // unchecked rethrow
return null; // avoid compiler warning
}
}
示例8
protected void updateHeader(Exchange exchange, MessageContext ctx) {
if (ctx.containsKey(Header.HEADER_LIST)
&& ctx.get(Header.HEADER_LIST) instanceof List<?>) {
List<?> list = (List<?>) ctx.get(Header.HEADER_LIST);
if (list != null && !list.isEmpty()) {
SoapMessage sm = (SoapMessage) createResponseMessage(exchange);
if (sm != null) {
Iterator<?> iter = list.iterator();
while (iter.hasNext()) {
Header header = (Header) iter.next();
if (header.getDirection() != Header.Direction.DIRECTION_IN
&& !header.getName().getNamespaceURI().
equals("http://docs.oasis-open.org/wss/2004/01/"
+ "oasis-200401-wss-wssecurity-secext-1.0.xsd")
&& !header.getName().getNamespaceURI().
equals("http://docs.oasis-open.org/"
+ "wss/oasis-wss-wssecurity-secext-1.1.xsd")) {
//don't copy over security header, out interceptor chain will take care of it.
sm.getHeaders().add(header);
}
}
}
}
}
}
示例9
private void doCancel(
Exchange exchange,
SecurityToken cancelToken,
W3CDOMStreamWriter writer,
String prefix,
String namespace
) throws Exception {
if (STSUtils.WST_NS_05_12.equals(namespace)) {
writer.writeStartElement(prefix, "RequestSecurityTokenResponseCollection", namespace);
}
writer.writeStartElement(prefix, "RequestSecurityTokenResponse", namespace);
TokenStore store = (TokenStore)exchange.get(Endpoint.class).getEndpointInfo()
.getProperty(TokenStore.class.getName());
store.remove(cancelToken.getId());
writer.writeEmptyElement(prefix, "RequestedTokenCancelled", namespace);
writer.writeEndElement();
if (STSUtils.WST_NS_05_12.equals(namespace)) {
writer.writeEndElement();
}
}
示例10
private static Message createMessage() {
ProviderFactory factory = ServerProviderFactory.getInstance();
Message m = new MessageImpl();
m.put("org.apache.cxf.http.case_insensitive_queries", false);
Exchange e = new ExchangeImpl();
m.setExchange(e);
e.setInMessage(m);
Endpoint endpoint = EasyMock.mock(Endpoint.class);
EasyMock.expect(endpoint.getEndpointInfo()).andReturn(null).anyTimes();
EasyMock.expect(endpoint.get(Application.class.getName())).andReturn(null);
EasyMock.expect(endpoint.size()).andReturn(0).anyTimes();
EasyMock.expect(endpoint.isEmpty()).andReturn(true).anyTimes();
EasyMock.expect(endpoint.get(ServerProviderFactory.class.getName())).andReturn(factory).anyTimes();
EasyMock.replay(endpoint);
e.put(Endpoint.class, endpoint);
return m;
}
示例11
@Override
protected Message createMessage(Object body,
OperationResourceInfo ori,
MultivaluedMap<String, String> headers,
URI currentURI,
Exchange exchange,
Map<String, Object> invocationContext,
boolean proxy) {
Method m = ori.getMethodToInvoke();
Message msg = super.createMessage(body, ori, headers, currentURI, exchange, invocationContext, proxy);
@SuppressWarnings("unchecked")
Map<String, Object> filterProps = (Map<String, Object>) msg.getExchange()
.get("jaxrs.filter.properties");
if (filterProps == null) {
filterProps = new HashMap<>();
msg.getExchange().put("jaxrs.filter.properties", filterProps);
}
filterProps.put("org.eclipse.microprofile.rest.client.invokedMethod", m);
return msg;
}
示例12
@Test
public void usingClientProxyStopIsCalledWhenServerReturnsNotFound() throws Exception {
final JAXRSClientFactoryBean factory = new JAXRSClientFactoryBean();
factory.setResourceClass(Library.class);
factory.setAddress("http://localhost:" + PORT + "/");
factory.setProvider(JacksonJsonProvider.class);
try {
final Library client = factory.create(Library.class);
expectedException.expect(NotFoundException.class);
client.getBook(10);
} finally {
Mockito.verify(resourceContext, times(1)).start(any(Exchange.class));
Mockito.verify(resourceContext, times(1)).stop(anyLong(), anyLong(), anyLong(), any(Exchange.class));
Mockito.verify(endpointContext, times(1)).start(any(Exchange.class));
Mockito.verify(endpointContext, times(1)).stop(anyLong(), anyLong(), anyLong(), any(Exchange.class));
Mockito.verifyNoInteractions(operationContext);
}
}
示例13
@Test
public void testSignature() throws Exception {
SOAPMessage saaj = readSAAJDocument("wsse-request-clean.xml");
WSS4JOutInterceptor ohandler = new WSS4JOutInterceptor();
PhaseInterceptor<SoapMessage> handler = ohandler.createEndingInterceptor();
SoapMessage msg = new SoapMessage(new MessageImpl());
Exchange ex = new ExchangeImpl();
ex.setInMessage(msg);
msg.setContent(SOAPMessage.class, saaj);
msg.put(WSHandlerConstants.ACTION, WSHandlerConstants.SIGNATURE);
msg.put(WSHandlerConstants.SIG_PROP_FILE, "outsecurity.properties");
msg.put(WSHandlerConstants.USER, "myAlias");
msg.put("password", "myAliasPassword");
handler.handleMessage(msg);
SOAPPart doc = saaj.getSOAPPart();
assertValid("//wsse:Security", doc);
assertValid("//wsse:Security/ds:Signature", doc);
}
示例14
@Test
public void transformInboundInterceptorReader() {
// Arrange
Message message = new MessageImpl();
StringReader stringReader = new StringReader(ORIG_LOGGING_CONTENT);
message.setContent(Reader.class, stringReader);
Exchange exchange = new ExchangeImpl();
message.setExchange(exchange);
LogEventSenderMock logEventSender = new LogEventSenderMock();
LoggingInInterceptor interceptor = new TransformLoggingInInterceptor(logEventSender);
// Act
Collection<PhaseInterceptor<? extends Message>> interceptors = interceptor.getAdditionalInterceptors();
for (PhaseInterceptor intercept : interceptors) {
intercept.handleMessage(message);
}
interceptor.handleMessage(message);
// Verify
LogEvent event = logEventSender.getLogEvent();
assertNotNull(event);
assertEquals(TRANSFORMED_LOGGING_CONTENT, event.getPayload()); // only the first byte is read!
}
示例15
private void setUpRebase(Message message, Exchange exchange, Endpoint endpoint)
throws Exception {
setUpMessageProperty(message,
"org.apache.cxf.ws.addressing.partial.response.sent",
Boolean.FALSE);
Binding binding = control.createMock(Binding.class);
endpoint.getBinding();
EasyMock.expectLastCall().andReturn(binding).anyTimes();
Message partialResponse = getMessage();
binding.createMessage(EasyMock.isA(Message.class));
EasyMock.expectLastCall().andReturn(partialResponse);
Destination target = control.createMock(Destination.class);
setUpMessageDestination(message, target);
Conduit backChannel = control.createMock(Conduit.class);
target.getBackChannel(EasyMock.eq(message));
EasyMock.expectLastCall().andReturn(backChannel);
// REVISIT test interceptor chain setup & send
}
示例16
public void handleMessage(Message message) {
Exchange ex = message.getExchange();
Set<Endpoint> endpoints = CastUtils.cast((Set<?>)ex.get(MultipleEndpointObserver.ENDPOINTS));
Endpoint ep = selectEndpoint(message, endpoints);
if (ep == null) {
return;
}
ex.put(Endpoint.class, ep);
ex.put(Binding.class, ep.getBinding());
ex.put(Service.class, ep.getService());
InterceptorChain chain = message.getInterceptorChain();
chain.add(ep.getInInterceptors());
chain.add(ep.getBinding().getInInterceptors());
chain.add(ep.getService().getInInterceptors());
chain.setFaultObserver(ep.getOutFaultObserver());
}
示例17
public static void closeConduit(Exchange exchange) throws IOException {
ConduitSelector conduitSelector = null;
synchronized (exchange) {
conduitSelector = exchange.get(ConduitSelector.class);
if (conduitSelector != null) {
exchange.remove(ConduitSelector.class.getName());
}
}
Conduit selectedConduit = null;
Message message = exchange.getInMessage() == null ? exchange
.getOutMessage() : exchange.getInMessage();
if (conduitSelector != null && message != null) {
selectedConduit = conduitSelector.selectConduit(message);
selectedConduit.close(message);
}
//TODO the line below was removed, check the impact on the protobuffer importer/exporter
//selectedConduit.close(message);
}
示例18
@SuppressWarnings("UnusedDeclaration")
public static void bind(final Exchange exchange) {
if (exchange == null) {
return;
}
final ClassResourceInfo cri = exchange.get(OperationResourceInfo.class).getClassResourceInfo();
// binding context fields
final Set<Class<?>> types = new HashSet<>();
for (final Field field : cri.getContextFields()) {
types.add(field.getType());
}
bind(exchange, types);
}
示例19
/**
* Try to correlate the incoming message with some timeout as it may have been
* added to the map after the message was sent
*
* @param correlationId
* @return exchange for correlationId or null if none was found
*/
private Exchange getExchange(String correlationId) {
int count = 0;
Exchange exchange = null;
while (exchange == null && count < 100) {
exchange = correlationMap.remove(correlationId);
if (exchange == null) {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
throw new RuntimeException("Interrupted while correlating", e);
}
}
count++;
}
return exchange;
}
示例20
@Test
public void testSuspendedException() throws Throwable {
Exception originalException = new RuntimeException();
ContinuationService serviceObject =
new ContinuationService(originalException);
Method serviceMethod = ContinuationService.class.getMethod("invoke", new Class[]{});
Exchange ex = new ExchangeImpl();
Message inMessage = new MessageImpl();
ex.setInMessage(inMessage);
inMessage.setExchange(ex);
inMessage.put(Message.REQUESTOR_ROLE, Boolean.TRUE);
JAXWSMethodInvoker jaxwsMethodInvoker = prepareJAXWSMethodInvoker(ex, serviceObject, serviceMethod);
try {
jaxwsMethodInvoker.invoke(ex, new MessageContentsList(new Object[]{}));
fail("Suspended invocation swallowed");
} catch (SuspendedInvocationException suspendedEx) {
assertSame(suspendedEx, serviceObject.getSuspendedException());
assertSame(originalException, suspendedEx.getRuntimeException());
}
}
示例21
public Object invoke(Exchange exchange, Object o) {
Object result = null;
String methodname = this.getTargetMethod(exchange).getName();
if (timers.containsKey(methodname)) {
Timer timer = timers.get(methodname);
final Timer.Context context = timer.time();
try {
result = this.underlying.invoke(exchange, o);
}
finally {
context.stop();
}
}
else {
result = this.underlying.invoke(exchange, o);
}
return result;
}
示例22
@Before
public void setup() {
exchange = mock(Exchange.class);
BindingOperationInfo boi = mock(BindingOperationInfo.class);
when(exchange.getBindingOperationInfo()).thenReturn(boi);
OperationInfo oi = mock(OperationInfo.class);
when(boi.getOperationInfo()).thenReturn(oi);
invokerBuilder = new UnitOfWorkInvokerFactory();
fooService = new FooService();
sessionFactory = mock(SessionFactory.class);
session = mock(Session.class);
when(sessionFactory.openSession()).thenReturn(session);
transaction = mock(Transaction.class);
when(session.getTransaction()).thenReturn(transaction);
when(transaction.getStatus()).thenReturn(TransactionStatus.ACTIVE);
}
示例23
/**
* When a message is received on the reply destination the correlation map is searched for the
* correlationId. If it is found the message is converted to a CXF message and the thread sending the
* request is notified {@inheritDoc}
*/
public void onMessage(javax.jms.Message jmsMessage) {
try {
String correlationId = jmsMessage.getJMSCorrelationID();
LOG.log(Level.FINE, "Received reply message with correlation id " + correlationId);
Exchange exchange = getExchange(correlationId);
if (exchange == null) {
LOG.log(Level.WARNING, "Could not correlate message with correlationId " + correlationId);
} else {
processReplyMessage(exchange, jmsMessage);
}
} catch (JMSException e) {
throw JMSUtil.convertJmsException(e);
}
}
示例24
@SuppressWarnings({ "rawtypes", "unchecked" })
@Test
public void truncatedInboundInterceptorInputStream() throws IOException {
Message message = new MessageImpl();
ByteArrayInputStream inputStream = new ByteArrayInputStream("TestMessage".getBytes(StandardCharsets.UTF_8));
message.setContent(InputStream.class, inputStream);
Exchange exchange = new ExchangeImpl();
message.setExchange(exchange);
LogEventSenderMock logEventSender = new LogEventSenderMock();
LoggingInInterceptor interceptor = new LoggingInInterceptor(logEventSender);
interceptor.setLimit(1); // set limit to 1 byte in order to get a truncated message!
Collection<PhaseInterceptor<? extends Message>> interceptors = interceptor.getAdditionalInterceptors();
for (PhaseInterceptor intercept : interceptors) {
intercept.handleMessage(message);
}
interceptor.handleMessage(message);
LogEvent event = logEventSender.getLogEvent();
assertNotNull(event);
assertEquals("T", event.getPayload()); // only the first byte is read!
assertTrue(event.isTruncated());
}
示例25
private void doCancel(
Exchange exchange,
SecurityToken cancelToken,
W3CDOMStreamWriter writer,
String prefix,
String namespace
) throws Exception {
if (STSUtils.WST_NS_05_12.equals(namespace)) {
writer.writeStartElement(prefix, "RequestSecurityTokenResponseCollection", namespace);
}
writer.writeStartElement(prefix, "RequestSecurityTokenResponse", namespace);
TokenStore store = (TokenStore)exchange.get(Endpoint.class).getEndpointInfo()
.getProperty(TokenStore.class.getName());
store.remove(cancelToken.getId());
writer.writeEmptyElement(prefix, "RequestedTokenCancelled", namespace);
writer.writeEndElement();
if (STSUtils.WST_NS_05_12.equals(namespace)) {
writer.writeEndElement();
}
}
示例26
/**
* Get the failover target endpoint, if a suitable one is available.
*
* @param exchange the current Exchange
* @param invocation the current InvocationContext
* @return a failover endpoint if one is available
*/
protected Endpoint getFailoverTarget(Exchange exchange,
InvocationContext invocation) {
List<String> alternateAddresses = updateContextAlternatives(exchange, invocation);
Endpoint failoverTarget = null;
if (alternateAddresses != null) {
String alternateAddress =
getStrategy().selectAlternateAddress(alternateAddresses);
if (alternateAddress != null) {
// re-use current endpoint
//
failoverTarget = getEndpoint();
failoverTarget.getEndpointInfo().setAddress(alternateAddress);
}
} else {
failoverTarget = getStrategy().selectAlternateEndpoint(
invocation.getAlternateEndpoints());
}
return failoverTarget;
}
示例27
private void invokeCustomerMethod(ClassResourceInfo cri,
Customer customer, Server server) throws Exception {
OperationResourceInfo ori = cri.getMethodDispatcher().getOperationResourceInfo(
Customer.class.getMethod("test", new Class[]{}));
JAXRSInvoker invoker = new JAXRSInvoker();
Exchange exc = new ExchangeImpl();
exc.put(Endpoint.class, server.getEndpoint());
Message inMessage = new MessageImpl();
exc.setInMessage(inMessage);
exc.put(OperationResourceInfo.class, ori);
invoker.invoke(exc, Collections.emptyList(), customer);
}
示例28
/**
* Creates a {@link SoapMessage} from the contents of a document.
* @param doc the document containing the SOAP content.
*/
protected SoapMessage getSoapMessageForDom(Document doc) throws SOAPException {
SOAPMessage saajMsg = MessageFactory.newInstance().createMessage();
SOAPPart part = saajMsg.getSOAPPart();
part.setContent(new DOMSource(doc));
saajMsg.saveChanges();
SoapMessage msg = new SoapMessage(new MessageImpl());
Exchange ex = new ExchangeImpl();
ex.setInMessage(msg);
msg.setContent(SOAPMessage.class, saajMsg);
return msg;
}
示例29
@Override
public synchronized Conduit selectConduit(Message message) {
Conduit c = message.get(Conduit.class);
if (c != null) {
return c;
}
Exchange exchange = message.getExchange();
String key = String.valueOf(System.identityHashCode(exchange));
InvocationContext invocation = getInvocationContext(key);
if (invocation != null && !invocation.getContext().containsKey(IS_SELECTED)) {
final String address = (String) message.get(Message.ENDPOINT_ADDRESS);
if (isFailoverRequired(address)) {
Endpoint target = getFailoverTarget(exchange, invocation);
if (target == null) {
throw new Fault(new FailoverFailedException(
"None of alternative addresses are available at the moment"));
}
if (isEndpointChanged(address, target)) {
setEndpoint(target);
message.put(Message.ENDPOINT_ADDRESS, target.getEndpointInfo().getAddress());
overrideAddressProperty(invocation.getContext());
invocation.getContext().put(IS_SELECTED, null);
}
}
}
return getSelectedConduit(message);
}
示例30
private void unmapSecurityProps(Message message) {
Exchange ex = message.getExchange();
for (String s : SecurityConstants.ALL_PROPERTIES) {
Object v = message.getContextualProperty(s);
if (v != null) {
ex.put(s, v);
}
}
}