Java Code Examples for org.apache.cxf.message.Exchange

The following examples show how to use org.apache.cxf.message.Exchange. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: cxf   Source File: LoadDistributorTargetSelector.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example 2
Source Project: cxf   Source File: AbstractClient.java    License: Apache License 2.0 6 votes vote down vote up
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);
        }
    }
}
 
Example 3
Source Project: cxf   Source File: TransformTest.java    License: Apache License 2.0 6 votes vote down vote up
@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!
}
 
Example 4
Source Project: cxf   Source File: MAPAggregatorTest.java    License: Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example 5
Source Project: cxf   Source File: ContextPropertiesMappingTest.java    License: Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example 6
Source Project: cxf   Source File: JAXRSClientMetricsTest.java    License: Apache License 2.0 6 votes vote down vote up
@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);
    }
}
 
Example 7
Source Project: dropwizard-jaxws   Source File: InstrumentedInvokers.java    License: Apache License 2.0 6 votes vote down vote up
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
            }
        }
 
Example 8
Source Project: cxf   Source File: AbstractJAXWSMethodInvoker.java    License: Apache License 2.0 6 votes vote down vote up
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);
                    }
                }
            }
        }
    }
}
 
Example 9
Source Project: steady   Source File: STSInvoker.java    License: Apache License 2.0 6 votes vote down vote up
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();
    }
}
 
Example 10
Source Project: cxf   Source File: InjectionUtilsTest.java    License: Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 11
Source Project: cxf   Source File: MicroProfileClientProxyImpl.java    License: Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example 12
Source Project: cxf   Source File: JAXRSServerMetricsTest.java    License: Apache License 2.0 6 votes vote down vote up
@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);
    }
}
 
Example 13
Source Project: steady   Source File: WSS4JOutInterceptorTest.java    License: Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example 14
Source Project: cxf   Source File: TransformTest.java    License: Apache License 2.0 6 votes vote down vote up
@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!
}
 
Example 15
Source Project: cxf   Source File: MAPAggregatorTest.java    License: Apache License 2.0 6 votes vote down vote up
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
}
 
Example 16
Source Project: cxf   Source File: AbstractEndpointSelectionInterceptor.java    License: Apache License 2.0 6 votes vote down vote up
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());
}
 
Example 17
Source Project: fuchsia   Source File: ExchangeUtils.java    License: Apache License 2.0 6 votes vote down vote up
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);
}
 
Example 18
Source Project: tomee   Source File: Contexts.java    License: Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example 19
Source Project: cxf   Source File: JMSConduit.java    License: Apache License 2.0 6 votes vote down vote up
/**
 *  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;
}
 
Example 20
Source Project: cxf   Source File: JAXWSMethodInvokerTest.java    License: Apache License 2.0 6 votes vote down vote up
@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());
    }
}
 
Example 21
Source Project: dropwizard-jaxws   Source File: InstrumentedInvokers.java    License: Apache License 2.0 6 votes vote down vote up
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;
        }
 
Example 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);
}
 
Example 23
Source Project: cxf   Source File: JMSConduit.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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);
    }

}
 
Example 24
Source Project: cxf   Source File: TruncatedTest.java    License: Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example 25
Source Project: steady   Source File: STSInvoker.java    License: Apache License 2.0 6 votes vote down vote up
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();
    }
}
 
Example 26
Source Project: cxf   Source File: FailoverTargetSelector.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example 27
Source Project: cxf   Source File: JAXRSUtilsTest.java    License: Apache License 2.0 5 votes vote down vote up
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);
}
 
Example 28
Source Project: steady   Source File: AbstractSecurityTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example 29
Source Project: cxf   Source File: CircuitBreakerTargetSelector.java    License: Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example 30
Source Project: steady   Source File: SpnegoContextTokenInInterceptor.java    License: Apache License 2.0 5 votes vote down vote up
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);
        }
    }
}