Search in sources :

Example 16 with MessageObserver

use of org.apache.cxf.transport.MessageObserver in project cxf by apache.

the class ClientRequestFilterInterceptor method handleMessage.

public void handleMessage(Message outMessage) throws Fault {
    ClientProviderFactory pf = ClientProviderFactory.getInstance(outMessage);
    if (pf == null) {
        return;
    }
    // create an empty proxy output stream that the filter can interact with
    // and save a reference for later
    ProxyOutputStream pos = new ProxyOutputStream();
    outMessage.setContent(OutputStream.class, pos);
    outMessage.setContent(ProxyOutputStream.class, pos);
    List<ProviderInfo<ClientRequestFilter>> filters = pf.getClientRequestFilters();
    if (!filters.isEmpty()) {
        final Exchange exchange = outMessage.getExchange();
        final ClientRequestContext context = new ClientRequestContextImpl(outMessage, false);
        for (ProviderInfo<ClientRequestFilter> filter : filters) {
            InjectionUtils.injectContexts(filter.getProvider(), filter, outMessage);
            try {
                filter.getProvider().filter(context);
                @SuppressWarnings("unchecked") Map<String, List<Object>> headers = CastUtils.cast((Map<String, List<Object>>) outMessage.get(Message.PROTOCOL_HEADERS));
                HttpUtils.convertHeaderValuesToString(headers, false);
                Response response = outMessage.getExchange().get(Response.class);
                if (response != null) {
                    outMessage.getInterceptorChain().abort();
                    Message inMessage = new MessageImpl();
                    inMessage.setExchange(exchange);
                    inMessage.put(Message.RESPONSE_CODE, response.getStatus());
                    inMessage.put(Message.PROTOCOL_HEADERS, response.getMetadata());
                    exchange.setInMessage(inMessage);
                    MessageObserver observer = exchange.get(MessageObserver.class);
                    observer.onMessage(inMessage);
                    return;
                }
            } catch (IOException ex) {
                throw new ProcessingException(ex);
            }
        }
    }
}
Also used : ClientRequestContext(javax.ws.rs.client.ClientRequestContext) ClientRequestFilter(javax.ws.rs.client.ClientRequestFilter) MessageObserver(org.apache.cxf.transport.MessageObserver) Message(org.apache.cxf.message.Message) IOException(java.io.IOException) ClientProviderFactory(org.apache.cxf.jaxrs.client.ClientProviderFactory) Exchange(org.apache.cxf.message.Exchange) Response(javax.ws.rs.core.Response) ProviderInfo(org.apache.cxf.jaxrs.model.ProviderInfo) ProxyOutputStream(org.apache.cxf.transport.http.ProxyOutputStream) List(java.util.List) MessageImpl(org.apache.cxf.message.MessageImpl) ProcessingException(javax.ws.rs.ProcessingException)

Example 17 with MessageObserver

use of org.apache.cxf.transport.MessageObserver in project cxf by apache.

the class JettyHTTPDestinationTest method setUpDestination.

private JettyHTTPDestination setUpDestination(boolean contextMatchOnStem, boolean mockedBus) throws Exception {
    policy = new HTTPServerPolicy();
    address = getEPR("bar/foo");
    transportFactory = new HTTPTransportFactory();
    final ConduitInitiator ci = new ConduitInitiator() {

        public Conduit getConduit(EndpointInfo targetInfo, Bus b) throws IOException {
            return decoupledBackChannel;
        }

        public Conduit getConduit(EndpointInfo localInfo, EndpointReferenceType target, Bus b) throws IOException {
            return decoupledBackChannel;
        }

        public List<String> getTransportIds() {
            return null;
        }

        public Set<String> getUriPrefixes() {
            return new HashSet<>(Collections.singletonList("http"));
        }
    };
    ConduitInitiatorManager mgr = new ConduitInitiatorManager() {

        public void deregisterConduitInitiator(String name) {
        }

        public ConduitInitiator getConduitInitiator(String name) throws BusException {
            return null;
        }

        public ConduitInitiator getConduitInitiatorForUri(String uri) {
            return ci;
        }

        public void registerConduitInitiator(String name, ConduitInitiator factory) {
        }
    };
    if (!mockedBus) {
        bus = new ExtensionManagerBus();
        bus.setExtension(mgr, ConduitInitiatorManager.class);
    } else {
        bus = EasyMock.createMock(Bus.class);
        bus.getExtension(EndpointResolverRegistry.class);
        EasyMock.expectLastCall().andReturn(null);
        bus.getExtension(ContinuationProviderFactory.class);
        EasyMock.expectLastCall().andReturn(null).anyTimes();
        bus.getExtension(PolicyDataEngine.class);
        EasyMock.expectLastCall().andReturn(null).anyTimes();
        bus.hasExtensionByName("org.apache.cxf.ws.policy.PolicyEngine");
        EasyMock.expectLastCall().andReturn(false);
        bus.getExtension(ClassLoader.class);
        EasyMock.expectLastCall().andReturn(this.getClass().getClassLoader());
        EasyMock.replay(bus);
    }
    engine = EasyMock.createNiceMock(JettyHTTPServerEngine.class);
    ServiceInfo serviceInfo = new ServiceInfo();
    serviceInfo.setName(new QName("bla", "Service"));
    endpointInfo = new EndpointInfo(serviceInfo, "");
    endpointInfo.setName(new QName("bla", "Port"));
    endpointInfo.setAddress(NOWHERE + "bar/foo");
    endpointInfo.addExtensor(policy);
    engine.addServant(EasyMock.eq(new URL(NOWHERE + "bar/foo")), EasyMock.isA(JettyHTTPHandler.class));
    EasyMock.expectLastCall();
    engine.getContinuationsEnabled();
    EasyMock.expectLastCall().andReturn(true);
    EasyMock.replay(engine);
    JettyHTTPDestination dest = new EasyMockJettyHTTPDestination(bus, transportFactory.getRegistry(), endpointInfo, null, engine);
    dest.retrieveEngine();
    policy = dest.getServer();
    observer = new MessageObserver() {

        public void onMessage(Message m) {
            inMessage = m;
            threadDefaultBus = BusFactory.getThreadDefaultBus();
        }
    };
    dest.setMessageObserver(observer);
    return dest;
}
Also used : Bus(org.apache.cxf.Bus) ExtensionManagerBus(org.apache.cxf.bus.extension.ExtensionManagerBus) HTTPServerPolicy(org.apache.cxf.transports.http.configuration.HTTPServerPolicy) EndpointReferenceType(org.apache.cxf.ws.addressing.EndpointReferenceType) MessageObserver(org.apache.cxf.transport.MessageObserver) Message(org.apache.cxf.message.Message) QName(javax.xml.namespace.QName) HTTPTransportFactory(org.apache.cxf.transport.http.HTTPTransportFactory) URL(java.net.URL) ServiceInfo(org.apache.cxf.service.model.ServiceInfo) EndpointInfo(org.apache.cxf.service.model.EndpointInfo) ConduitInitiatorManager(org.apache.cxf.transport.ConduitInitiatorManager) ConduitInitiator(org.apache.cxf.transport.ConduitInitiator) ExtensionManagerBus(org.apache.cxf.bus.extension.ExtensionManagerBus) HashSet(java.util.HashSet)

Example 18 with MessageObserver

use of org.apache.cxf.transport.MessageObserver in project cxf by apache.

the class JettyHTTPDestinationTest method testSuspendedException.

@Test
public void testSuspendedException() throws Exception {
    destination = setUpDestination(false, false);
    setUpDoService(false);
    final RuntimeException ex = new RuntimeException();
    observer = new MessageObserver() {

        public void onMessage(Message m) {
            throw new SuspendedInvocationException(ex);
        }
    };
    destination.setMessageObserver(observer);
    try {
        destination.doService(request, response);
        fail("Suspended invocation swallowed");
    } catch (RuntimeException runtimeEx) {
        assertSame("Original exception is not preserved", ex, runtimeEx);
    }
}
Also used : MessageObserver(org.apache.cxf.transport.MessageObserver) Message(org.apache.cxf.message.Message) SuspendedInvocationException(org.apache.cxf.continuations.SuspendedInvocationException) Test(org.junit.Test)

Example 19 with MessageObserver

use of org.apache.cxf.transport.MessageObserver in project cxf by apache.

the class HTTPConduitURLEasyMockTest method setUpConduit.

private HTTPConduit setUpConduit(boolean send, boolean autoRedirect, String method) throws Exception {
    endpointInfo = new EndpointInfo();
    endpointInfo.setAddress(NOWHERE + "bar/foo");
    connectionFactory = control.createMock(HttpsURLConnectionFactory.class);
    if (send) {
        // proxy = control.createMock(Proxy.class);
        proxy = Proxy.NO_PROXY;
        connection = control.createMock(HttpURLConnection.class);
        connection.getURL();
        EasyMock.expectLastCall().andReturn(new URL(NOWHERE + "bar/foo")).anyTimes();
        connectionFactory.createConnection((TLSClientParameters) EasyMock.isNull(), EasyMock.eq(proxy), EasyMock.eq(new URL(NOWHERE + "bar/foo")));
        EasyMock.expectLastCall().andReturn(connection);
        connection.setDoOutput(true);
        EasyMock.expectLastCall();
        connection.setRequestMethod(method);
        EasyMock.expectLastCall();
        if (!autoRedirect && "POST".equals(method)) {
            connection.setChunkedStreamingMode(-1);
            EasyMock.expectLastCall();
        }
        connection.getRequestMethod();
        EasyMock.expectLastCall().andReturn(method).anyTimes();
        connection.setInstanceFollowRedirects(false);
        EasyMock.expectLastCall().times(1);
        connection.setConnectTimeout(303030);
        EasyMock.expectLastCall();
        connection.setReadTimeout(404040);
        EasyMock.expectLastCall();
        connection.setUseCaches(false);
        EasyMock.expectLastCall();
    }
    ExtensionManagerBus bus = new ExtensionManagerBus();
    control.replay();
    HTTPConduit conduit = new HTTPTestConduit(bus, endpointInfo, null, connectionFactory);
    conduit.finalizeConfig();
    if (send) {
        conduit.getClient().setConnectionTimeout(303030);
        conduit.getClient().setReceiveTimeout(404040);
        conduit.getClient().setAutoRedirect(autoRedirect);
        if (!autoRedirect) {
            conduit.getClient().setAllowChunking(true);
            conduit.getClient().setChunkingThreshold(0);
        }
    }
    observer = new MessageObserver() {

        public void onMessage(Message m) {
            inMessage = m;
        }
    };
    conduit.setMessageObserver(observer);
    return conduit;
}
Also used : EndpointInfo(org.apache.cxf.service.model.EndpointInfo) HttpsURLConnectionFactory(org.apache.cxf.transport.https.HttpsURLConnectionFactory) HttpURLConnection(java.net.HttpURLConnection) MessageObserver(org.apache.cxf.transport.MessageObserver) Message(org.apache.cxf.message.Message) ExtensionManagerBus(org.apache.cxf.bus.extension.ExtensionManagerBus) URL(java.net.URL)

Example 20 with MessageObserver

use of org.apache.cxf.transport.MessageObserver in project cxf by apache.

the class InternalContextUtils method rebaseResponse.

/**
 * Rebase response on replyTo
 *
 * @param reference the replyTo reference
 * @param inMAPs the inbound MAPs
 * @param inMessage the current message
 */
// CHECKSTYLE:OFF Max executable statement count limitation
public static void rebaseResponse(EndpointReferenceType reference, AddressingProperties inMAPs, final Message inMessage) {
    String namespaceURI = inMAPs.getNamespaceURI();
    if (!ContextUtils.retrievePartialResponseSent(inMessage)) {
        ContextUtils.storePartialResponseSent(inMessage);
        Exchange exchange = inMessage.getExchange();
        Message fullResponse = exchange.getOutMessage();
        Message partialResponse = ContextUtils.createMessage(exchange);
        ensurePartialResponseMAPs(partialResponse, namespaceURI);
        // ensure the inbound MAPs are available in the partial response
        // message (used to determine relatesTo etc.)
        ContextUtils.propogateReceivedMAPs(inMAPs, partialResponse);
        Destination target = inMessage.getDestination();
        if (target == null) {
            return;
        }
        try {
            if (reference == null) {
                reference = ContextUtils.getNoneEndpointReference();
            }
            Conduit backChannel = target.getBackChannel(inMessage);
            Exception exception = inMessage.getContent(Exception.class);
            // TODO:Look at how to refactor
            if (backChannel != null && !inMessage.getExchange().isOneWay() && ContextUtils.isFault(inMessage)) {
                // send the fault message to faultTo Endpoint
                exchange.setOutMessage(ContextUtils.createMessage(exchange));
                exchange.put(ConduitSelector.class, new NullConduitSelector());
                exchange.put("org.apache.cxf.http.no_io_exceptions", true);
                Destination destination = createDecoupledDestination(exchange, reference);
                exchange.setDestination(destination);
                if (ContextUtils.retrieveAsyncPostResponseDispatch(inMessage)) {
                    DelegatingInputStream in = inMessage.getContent(DelegatingInputStream.class);
                    if (in != null) {
                        in.cacheInput();
                    }
                    inMessage.getInterceptorChain().reset();
                    // cleanup pathinfo
                    if (inMessage.get(Message.PATH_INFO) != null) {
                        inMessage.remove(Message.PATH_INFO);
                    }
                    inMessage.getInterceptorChain().doIntercept(inMessage);
                }
                // send the partial response to requester
                partialResponse.put("forced.faultstring", "The server sent HTTP status code :" + inMessage.getExchange().get(Message.RESPONSE_CODE));
                partialResponse.setContent(Exception.class, exception);
                partialResponse.put(org.apache.cxf.message.Message.PROTOCOL_HEADERS, inMessage.get(Message.PROTOCOL_HEADERS));
                partialResponse.put(org.apache.cxf.message.Message.ENCODING, inMessage.get(Message.ENCODING));
                partialResponse.put(ContextUtils.ACTION, inMessage.get(ContextUtils.ACTION));
                partialResponse.put("javax.xml.ws.addressing.context.inbound", inMessage.get("javax.xml.ws.addressing.context.inbound"));
                partialResponse.put("javax.xml.ws.addressing.context.outbound", inMessage.get("javax.xml.ws.addressing.context.outbound"));
                exchange.setOutMessage(partialResponse);
                PhaseInterceptorChain newChian = ((PhaseInterceptorChain) inMessage.getInterceptorChain()).cloneChain();
                partialResponse.setInterceptorChain(newChian);
                exchange.setDestination(target);
                exchange.setOneWay(false);
                exchange.put(ConduitSelector.class, new PreexistingConduitSelector(backChannel, exchange.getEndpoint()));
                if (newChian != null && !newChian.doIntercept(partialResponse) && partialResponse.getContent(Exception.class) != null) {
                    if (partialResponse.getContent(Exception.class) instanceof Fault) {
                        throw (Fault) partialResponse.getContent(Exception.class);
                    }
                    throw new Fault(partialResponse.getContent(Exception.class));
                }
                return;
            }
            if (backChannel != null) {
                partialResponse.put(Message.PARTIAL_RESPONSE_MESSAGE, Boolean.TRUE);
                partialResponse.put(Message.EMPTY_PARTIAL_RESPONSE_MESSAGE, Boolean.TRUE);
                boolean robust = MessageUtils.getContextualBoolean(inMessage, Message.ROBUST_ONEWAY, false);
                if (robust) {
                    BindingOperationInfo boi = exchange.getBindingOperationInfo();
                    // insert the executor in the exchange to fool the OneWayProcessorInterceptor
                    exchange.put(Executor.class, getExecutor(inMessage));
                    // pause dispatch on current thread and resume...
                    inMessage.getInterceptorChain().pause();
                    inMessage.getInterceptorChain().resume();
                    MessageObserver faultObserver = inMessage.getInterceptorChain().getFaultObserver();
                    if (null != inMessage.getContent(Exception.class) && null != faultObserver) {
                        // return the fault over the response fault channel
                        inMessage.getExchange().setOneWay(false);
                        faultObserver.onMessage(inMessage);
                        return;
                    }
                    // restore the BOI for the partial response handling
                    exchange.put(BindingOperationInfo.class, boi);
                }
                // set up interceptor chains and send message
                InterceptorChain chain = fullResponse != null ? fullResponse.getInterceptorChain() : OutgoingChainInterceptor.getOutInterceptorChain(exchange);
                exchange.setOutMessage(partialResponse);
                partialResponse.setInterceptorChain(chain);
                exchange.put(ConduitSelector.class, new PreexistingConduitSelector(backChannel, exchange.getEndpoint()));
                if (ContextUtils.retrieveAsyncPostResponseDispatch(inMessage) && !robust) {
                    // need to suck in all the data from the input stream as
                    // the transport might discard any data on the stream when this
                    // thread unwinds or when the empty response is sent back
                    DelegatingInputStream in = inMessage.getContent(DelegatingInputStream.class);
                    if (in != null) {
                        in.cacheInput();
                    }
                }
                if (chain != null && !chain.doIntercept(partialResponse) && partialResponse.getContent(Exception.class) != null) {
                    if (partialResponse.getContent(Exception.class) instanceof Fault) {
                        throw (Fault) partialResponse.getContent(Exception.class);
                    }
                    throw new Fault(partialResponse.getContent(Exception.class));
                }
                if (chain != null) {
                    chain.reset();
                }
                exchange.put(ConduitSelector.class, new NullConduitSelector());
                if (fullResponse == null) {
                    fullResponse = ContextUtils.createMessage(exchange);
                }
                exchange.setOutMessage(fullResponse);
                Destination destination = createDecoupledDestination(exchange, reference);
                exchange.setDestination(destination);
                if (ContextUtils.retrieveAsyncPostResponseDispatch(inMessage) && !robust) {
                    // cleanup pathinfo
                    if (inMessage.get(Message.PATH_INFO) != null) {
                        inMessage.remove(Message.PATH_INFO);
                    }
                    // pause dispatch on current thread ...
                    inMessage.getInterceptorChain().pause();
                    try {
                        // ... and resume on executor thread
                        getExecutor(inMessage).execute(new Runnable() {

                            public void run() {
                                inMessage.getInterceptorChain().resume();
                            }
                        });
                    } catch (RejectedExecutionException e) {
                        LOG.warning("Executor queue is full, use the caller thread." + "  Users can specify a larger executor queue to avoid this.");
                        // only block the thread if the prop is unset or set to false, otherwise let it go
                        if (!MessageUtils.getContextualBoolean(inMessage, "org.apache.cxf.oneway.rejected_execution_exception")) {
                            // the executor queue is full, so run the task in the caller thread
                            inMessage.getInterceptorChain().resume();
                        }
                    }
                }
            }
        } catch (Exception e) {
            LOG.log(Level.WARNING, "SERVER_TRANSPORT_REBASE_FAILURE_MSG", e);
        }
    }
}
Also used : Destination(org.apache.cxf.transport.Destination) PhaseInterceptorChain(org.apache.cxf.phase.PhaseInterceptorChain) BindingOperationInfo(org.apache.cxf.service.model.BindingOperationInfo) MessageObserver(org.apache.cxf.transport.MessageObserver) Message(org.apache.cxf.message.Message) Fault(org.apache.cxf.interceptor.Fault) WebFault(javax.xml.ws.WebFault) PreexistingConduitSelector(org.apache.cxf.endpoint.PreexistingConduitSelector) RejectedExecutionException(java.util.concurrent.RejectedExecutionException) IOException(java.io.IOException) RejectedExecutionException(java.util.concurrent.RejectedExecutionException) NullConduitSelector(org.apache.cxf.endpoint.NullConduitSelector) Exchange(org.apache.cxf.message.Exchange) InterceptorChain(org.apache.cxf.interceptor.InterceptorChain) PhaseInterceptorChain(org.apache.cxf.phase.PhaseInterceptorChain) Conduit(org.apache.cxf.transport.Conduit) DelegatingInputStream(org.apache.cxf.io.DelegatingInputStream)

Aggregations

MessageObserver (org.apache.cxf.transport.MessageObserver)43 Message (org.apache.cxf.message.Message)34 EndpointInfo (org.apache.cxf.service.model.EndpointInfo)21 Conduit (org.apache.cxf.transport.Conduit)14 IOException (java.io.IOException)13 Exchange (org.apache.cxf.message.Exchange)12 ExchangeImpl (org.apache.cxf.message.ExchangeImpl)11 Test (org.junit.Test)11 MessageImpl (org.apache.cxf.message.MessageImpl)10 EndpointReferenceType (org.apache.cxf.ws.addressing.EndpointReferenceType)10 Bus (org.apache.cxf.Bus)8 QName (javax.xml.namespace.QName)7 ConduitInitiator (org.apache.cxf.transport.ConduitInitiator)6 Fault (org.apache.cxf.interceptor.Fault)5 Destination (org.apache.cxf.transport.Destination)5 URISyntaxException (java.net.URISyntaxException)4 URL (java.net.URL)4 HashMap (java.util.HashMap)4 List (java.util.List)4 ExtensionManagerBus (org.apache.cxf.bus.extension.ExtensionManagerBus)4