Search in sources :

Example 81 with Message

use of org.apache.cxf.message.Message in project tomee by apache.

the class JAXRSInvoker method handleFault.

private Object handleFault(Fault ex, Message inMessage, ClassResourceInfo cri, Method methodToInvoke) {
    String errorMessage = ex.getMessage();
    if (errorMessage != null && cri != null && errorMessage.contains(PROXY_INVOCATION_ERROR_FRAGMENT)) {
        org.apache.cxf.common.i18n.Message errorM = new org.apache.cxf.common.i18n.Message("PROXY_INVOCATION_FAILURE", BUNDLE, methodToInvoke, cri.getServiceClass().getName());
        LOG.severe(errorM.toString());
    }
    Response excResponse = JAXRSUtils.convertFaultToResponse(ex.getCause() == null ? ex : ex.getCause(), inMessage);
    if (excResponse == null) {
        inMessage.getExchange().put(Message.PROPOGATE_EXCEPTION, ExceptionUtils.propogateException(inMessage));
        throw ex;
    }
    return new MessageContentsList(excResponse);
}
Also used : AsyncResponse(javax.ws.rs.container.AsyncResponse) Response(javax.ws.rs.core.Response) Message(org.apache.cxf.message.Message) MessageContentsList(org.apache.cxf.message.MessageContentsList)

Example 82 with Message

use of org.apache.cxf.message.Message in project tomee by apache.

the class ResponseImpl method doReadEntity.

public <T> T doReadEntity(Class<T> cls, Type t, Annotation[] anns) throws ProcessingException, IllegalStateException {
    checkEntityIsClosed();
    // according to javadoc, should close when is not buffered.
    boolean shouldClose = !entityBufferred && !JAXRSUtils.isStreamingOutType(cls);
    if (lastEntity != null && cls.isAssignableFrom(lastEntity.getClass()) && !(lastEntity instanceof InputStream)) {
        return cls.cast(lastEntity);
    }
    MediaType mediaType = getMediaType();
    if (mediaType == null) {
        mediaType = MediaType.WILDCARD_TYPE;
    }
    // the stream is available if entity is IS or
    // message contains XMLStreamReader or Reader
    boolean entityStreamAvailable = entityStreamAvailable();
    InputStream entityStream = null;
    if (!entityStreamAvailable) {
        // try create a stream if the entity is String or Number
        entityStream = convertEntityToStreamIfPossible();
        entityStreamAvailable = entityStream != null;
    } else if (entity instanceof InputStream) {
        entityStream = InputStream.class.cast(entity);
    } else {
        Message inMessage = getResponseMessage();
        Reader reader = inMessage.getContent(Reader.class);
        if (reader != null) {
            entityStream = InputStream.class.cast(new ReaderInputStream(reader));
        }
    }
    // we need to check for readers even if no IS is set - the readers may still do it
    List<ReaderInterceptor> readers = outMessage == null ? null : ProviderFactory.getInstance(outMessage).createMessageBodyReaderInterceptor(cls, t, anns, mediaType, outMessage, entityStreamAvailable, null);
    if (readers != null) {
        try {
            if (entityBufferred) {
                InputStream.class.cast(entity).reset();
            }
            Message responseMessage = getResponseMessage();
            responseMessage.put(Message.PROTOCOL_HEADERS, getHeaders());
            lastEntity = JAXRSUtils.readFromMessageBodyReader(readers, cls, t, anns, entityStream, mediaType, responseMessage);
            // close the entity after readEntity is called.
            T tCastLastEntity = castLastEntity();
            shouldClose = shouldClose && !(tCastLastEntity instanceof AutoCloseable) && !(tCastLastEntity instanceof Source);
            if (shouldClose) {
                close();
            }
            return tCastLastEntity;
        } catch (NoContentException ex) {
            // check if basic type. Basic type throw exception, else return null.
            if (isBasicType(cls)) {
                autoClose(cls, true);
                reportMessageHandlerProblem("MSG_READER_PROBLEM", cls, mediaType, ex);
            } else {
                if (shouldClose) {
                    close();
                }
                return null;
            }
        } catch (Exception ex) {
            autoClose(cls, true);
            reportMessageHandlerProblem("MSG_READER_PROBLEM", cls, mediaType, ex);
        } finally {
            ProviderFactory pf = ProviderFactory.getInstance(outMessage);
            if (pf != null) {
                pf.clearThreadLocalProxies();
            }
        }
    } else if (entity != null && cls.isAssignableFrom(entity.getClass())) {
        lastEntity = entity;
        return castLastEntity();
    } else if (entityStreamAvailable) {
        reportMessageHandlerProblem("NO_MSG_READER", cls, mediaType, null);
    }
    throw new IllegalStateException("The entity is not backed by an input stream, entity class is : " + (entity != null ? entity.getClass().getName() : cls.getName()));
}
Also used : ReaderInterceptor(javax.ws.rs.ext.ReaderInterceptor) Message(org.apache.cxf.message.Message) PushbackInputStream(java.io.PushbackInputStream) ReaderInputStream(org.apache.cxf.io.ReaderInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) XMLStreamReader(javax.xml.stream.XMLStreamReader) Reader(java.io.Reader) NoContentException(javax.ws.rs.core.NoContentException) Source(javax.xml.transform.Source) NoContentException(javax.ws.rs.core.NoContentException) IOException(java.io.IOException) ProcessingException(javax.ws.rs.ProcessingException) ResponseProcessingException(javax.ws.rs.client.ResponseProcessingException) ReaderInputStream(org.apache.cxf.io.ReaderInputStream) ProviderFactory(org.apache.cxf.jaxrs.provider.ProviderFactory) MediaType(javax.ws.rs.core.MediaType)

Example 83 with Message

use of org.apache.cxf.message.Message in project tomee by apache.

the class JAXRSInInterceptor method processRequest.

private void processRequest(Message message, Exchange exchange) throws IOException {
    ServerProviderFactory providerFactory = ServerProviderFactory.getInstance(message);
    RequestPreprocessor rp = providerFactory.getRequestPreprocessor();
    if (rp != null) {
        rp.preprocess(message, new UriInfoImpl(message, null));
    }
    // Global pre-match request filters
    if (JAXRSUtils.runContainerRequestFilters(providerFactory, message, true, null)) {
        return;
    }
    // HTTP method
    String httpMethod = HttpUtils.getProtocolHeader(message, Message.HTTP_REQUEST_METHOD, HttpMethod.POST, true);
    // Path to match
    String rawPath = HttpUtils.getPathToMatch(message, true);
    Map<String, List<String>> protocolHeaders = CastUtils.cast((Map<?, ?>) message.get(Message.PROTOCOL_HEADERS));
    // Content-Type
    String requestContentType = null;
    List<String> ctHeaderValues = protocolHeaders.get(Message.CONTENT_TYPE);
    if (ctHeaderValues != null && !ctHeaderValues.isEmpty()) {
        requestContentType = ctHeaderValues.get(0);
        message.put(Message.CONTENT_TYPE, requestContentType);
    }
    if (requestContentType == null) {
        requestContentType = (String) message.get(Message.CONTENT_TYPE);
        if (requestContentType == null) {
            requestContentType = MediaType.WILDCARD;
        }
    }
    // Accept
    String acceptTypes = null;
    List<String> acceptHeaderValues = protocolHeaders.get(Message.ACCEPT_CONTENT_TYPE);
    if (acceptHeaderValues != null && !acceptHeaderValues.isEmpty()) {
        acceptTypes = acceptHeaderValues.get(0);
        message.put(Message.ACCEPT_CONTENT_TYPE, acceptTypes);
    }
    if (acceptTypes == null) {
        acceptTypes = HttpUtils.getProtocolHeader(message, Message.ACCEPT_CONTENT_TYPE, null);
        if (acceptTypes == null) {
            acceptTypes = "*/*";
            message.put(Message.ACCEPT_CONTENT_TYPE, acceptTypes);
        }
    }
    final List<MediaType> acceptContentTypes;
    try {
        acceptContentTypes = JAXRSUtils.sortMediaTypes(acceptTypes, JAXRSUtils.MEDIA_TYPE_Q_PARAM);
    } catch (IllegalArgumentException ex) {
        throw ExceptionUtils.toNotAcceptableException(null, null);
    }
    exchange.put(Message.ACCEPT_CONTENT_TYPE, acceptContentTypes);
    // 1. Matching target resource class
    List<ClassResourceInfo> resources = JAXRSUtils.getRootResources(message);
    Map<ClassResourceInfo, MultivaluedMap<String, String>> matchedResources = JAXRSUtils.selectResourceClass(resources, rawPath, message);
    if (matchedResources == null) {
        org.apache.cxf.common.i18n.Message errorMsg = new org.apache.cxf.common.i18n.Message("NO_ROOT_EXC", BUNDLE, message.get(Message.REQUEST_URI), rawPath);
        Level logLevel = JAXRSUtils.getExceptionLogLevel(message, NotFoundException.class);
        LOG.log(logLevel == null ? Level.FINE : logLevel, errorMsg.toString());
        Response resp = JAXRSUtils.createResponse(resources, message, errorMsg.toString(), Response.Status.NOT_FOUND.getStatusCode(), false);
        throw ExceptionUtils.toNotFoundException(null, resp);
    }
    MultivaluedMap<String, String> matchedValues = new MetadataMap<>();
    final OperationResourceInfo ori;
    try {
        ori = JAXRSUtils.findTargetMethod(matchedResources, message, httpMethod, matchedValues, requestContentType, acceptContentTypes, true, true);
        setExchangeProperties(message, exchange, ori, matchedValues, resources.size());
    } catch (WebApplicationException ex) {
        if (JAXRSUtils.noResourceMethodForOptions(ex.getResponse(), httpMethod)) {
            Response response = JAXRSUtils.createResponse(resources, null, null, 200, true);
            exchange.put(Response.class, response);
            return;
        }
        throw ex;
    }
    if (LOG.isLoggable(Level.FINE)) {
        LOG.fine("Request path is: " + rawPath);
        LOG.fine("Request HTTP method is: " + httpMethod);
        LOG.fine("Request contentType is: " + requestContentType);
        LOG.fine("Accept contentType is: " + acceptTypes);
        LOG.fine("Found operation: " + ori.getMethodToInvoke().getName());
    }
    // Global and name-bound post-match request filters
    if (!ori.isSubResourceLocator() && JAXRSUtils.runContainerRequestFilters(providerFactory, message, false, ori.getNameBindings())) {
        return;
    }
    // Process parameters
    List<Object> params = JAXRSUtils.processParameters(ori, matchedValues, message);
    message.setContent(List.class, params);
}
Also used : ServerProviderFactory(org.apache.cxf.jaxrs.provider.ServerProviderFactory) Message(org.apache.cxf.message.Message) WebApplicationException(javax.ws.rs.WebApplicationException) MetadataMap(org.apache.cxf.jaxrs.impl.MetadataMap) MediaType(javax.ws.rs.core.MediaType) MessageContentsList(org.apache.cxf.message.MessageContentsList) List(java.util.List) ClassResourceInfo(org.apache.cxf.jaxrs.model.ClassResourceInfo) Response(javax.ws.rs.core.Response) RequestPreprocessor(org.apache.cxf.jaxrs.impl.RequestPreprocessor) Level(java.util.logging.Level) OperationResourceInfo(org.apache.cxf.jaxrs.model.OperationResourceInfo) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) UriInfoImpl(org.apache.cxf.jaxrs.impl.UriInfoImpl)

Example 84 with Message

use of org.apache.cxf.message.Message in project tomee by apache.

the class ClientImpl method getConduit.

public Conduit getConduit() {
    Message message = new MessageImpl();
    Exchange exchange = new ExchangeImpl();
    message.setExchange(exchange);
    message.putAll(getRequestContext());
    setExchangeProperties(exchange, getEndpoint(), null);
    return getConduitSelector().selectConduit(message);
}
Also used : Exchange(org.apache.cxf.message.Exchange) Message(org.apache.cxf.message.Message) MessageImpl(org.apache.cxf.message.MessageImpl) ExchangeImpl(org.apache.cxf.message.ExchangeImpl)

Example 85 with Message

use of org.apache.cxf.message.Message in project tomee by apache.

the class ClientImpl method onMessage.

public void onMessage(Message message) {
    if (bus == null) {
        throw new IllegalStateException("Message received on a Client that has been closed or destroyed.");
    }
    Endpoint endpoint = message.getExchange().getEndpoint();
    if (endpoint == null) {
        // in this case correlation will occur outside the transport,
        // however there's a possibility that the endpoint may have been
        // rebased in the meantime, so that the response will be mediated
        // via a set of in interceptors provided by a *different* endpoint
        // 
        endpoint = getConduitSelector().getEndpoint();
        message.getExchange().put(Endpoint.class, endpoint);
    }
    message = endpoint.getBinding().createMessage(message);
    message.getExchange().setInMessage(message);
    message.put(Message.REQUESTOR_ROLE, Boolean.TRUE);
    message.put(Message.INBOUND_MESSAGE, Boolean.TRUE);
    PhaseManager pm = bus.getExtension(PhaseManager.class);
    List<Interceptor<? extends Message>> i1 = bus.getInInterceptors();
    if (LOG.isLoggable(Level.FINE)) {
        LOG.fine("Interceptors contributed by bus: " + i1);
    }
    List<Interceptor<? extends Message>> i2 = getInInterceptors();
    if (LOG.isLoggable(Level.FINE)) {
        LOG.fine("Interceptors contributed by client: " + i2);
    }
    List<Interceptor<? extends Message>> i3 = endpoint.getInInterceptors();
    if (LOG.isLoggable(Level.FINE)) {
        LOG.fine("Interceptors contributed by endpoint: " + i3);
    }
    List<Interceptor<? extends Message>> i4 = endpoint.getBinding().getInInterceptors();
    if (LOG.isLoggable(Level.FINE)) {
        LOG.fine("Interceptors contributed by binding: " + i4);
    }
    PhaseInterceptorChain chain;
    if (endpoint.getService().getDataBinding() instanceof InterceptorProvider) {
        InterceptorProvider p = (InterceptorProvider) endpoint.getService().getDataBinding();
        if (LOG.isLoggable(Level.FINE)) {
            LOG.fine("Interceptors contributed by databinding: " + p.getInInterceptors());
        }
        chain = inboundChainCache.get(pm.getInPhases(), i1, i2, i3, i4, p.getInInterceptors());
    } else {
        chain = inboundChainCache.get(pm.getInPhases(), i1, i2, i3, i4);
    }
    message.setInterceptorChain(chain);
    chain.setFaultObserver(outFaultObserver);
    modifyChain(chain, message, true);
    modifyChain(chain, message.getExchange().getOutMessage(), true);
    Bus origBus = BusFactory.getAndSetThreadDefaultBus(bus);
    // execute chain
    ClientCallback callback = message.getExchange().get(ClientCallback.class);
    try {
        if (callback != null) {
            if (callback.isCancelled()) {
                completeExchange(message.getExchange());
                return;
            }
            callback.start(message);
        }
        String startingAfterInterceptorID = (String) message.get(InterceptorChain.STARTING_AFTER_INTERCEPTOR_ID);
        String startingInterceptorID = (String) message.get(InterceptorChain.STARTING_AT_INTERCEPTOR_ID);
        if (startingAfterInterceptorID != null) {
            chain.doInterceptStartingAfter(message, startingAfterInterceptorID);
        } else if (startingInterceptorID != null) {
            chain.doInterceptStartingAt(message, startingInterceptorID);
        } else if (message.getContent(Exception.class) != null) {
            outFaultObserver.onMessage(message);
        } else {
            callback = message.getExchange().get(ClientCallback.class);
            if (callback != null && !isPartialResponse(message)) {
                try {
                    chain.doIntercept(message);
                } catch (Throwable error) {
                    // so that asyn callback handler get chance to
                    // handle non-runtime exceptions
                    message.getExchange().setInMessage(message);
                    Map<String, Object> resCtx = CastUtils.cast((Map<?, ?>) message.getExchange().getOutMessage().get(Message.INVOCATION_CONTEXT));
                    resCtx = CastUtils.cast((Map<?, ?>) resCtx.get(RESPONSE_CONTEXT));
                    if (resCtx != null) {
                        setResponseContext(resCtx);
                    }
                    // remove callback so that it won't be invoked twice
                    callback = message.getExchange().remove(ClientCallback.class);
                    if (callback != null) {
                        callback.handleException(resCtx, error);
                    }
                }
            } else {
                chain.doIntercept(message);
            }
        }
        callback = message.getExchange().get(ClientCallback.class);
        if (callback == null || isPartialResponse(message)) {
            return;
        }
        // remove callback so that it won't be invoked twice
        callback = message.getExchange().remove(ClientCallback.class);
        if (callback != null) {
            message.getExchange().setInMessage(message);
            Map<String, Object> resCtx = CastUtils.cast((Map<?, ?>) message.getExchange().getOutMessage().get(Message.INVOCATION_CONTEXT));
            resCtx = CastUtils.cast((Map<?, ?>) resCtx.get(RESPONSE_CONTEXT));
            if (resCtx != null && responseContext != null) {
                setResponseContext(resCtx);
            }
            try {
                Object[] obj = processResult(message, message.getExchange(), null, resCtx);
                callback.handleResponse(resCtx, obj);
            } catch (Throwable ex) {
                callback.handleException(resCtx, ex);
            }
        }
    } finally {
        if (origBus != bus) {
            BusFactory.setThreadDefaultBus(origBus);
        }
        synchronized (message.getExchange()) {
            if (!isPartialResponse(message) || message.getContent(Exception.class) != null) {
                message.getExchange().put(FINISHED, Boolean.TRUE);
                message.getExchange().setInMessage(message);
                message.getExchange().notifyAll();
            }
        }
    }
}
Also used : Bus(org.apache.cxf.Bus) PhaseInterceptorChain(org.apache.cxf.phase.PhaseInterceptorChain) PhaseManager(org.apache.cxf.phase.PhaseManager) Message(org.apache.cxf.message.Message) InterceptorProvider(org.apache.cxf.interceptor.InterceptorProvider) AbstractBasicInterceptorProvider(org.apache.cxf.interceptor.AbstractBasicInterceptorProvider) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) UncheckedException(org.apache.cxf.common.i18n.UncheckedException) Interceptor(org.apache.cxf.interceptor.Interceptor) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) WeakHashMap(java.util.WeakHashMap)

Aggregations

Message (org.apache.cxf.message.Message)1002 Test (org.junit.Test)507 MessageImpl (org.apache.cxf.message.MessageImpl)291 Exchange (org.apache.cxf.message.Exchange)199 ExchangeImpl (org.apache.cxf.message.ExchangeImpl)169 Endpoint (org.apache.cxf.endpoint.Endpoint)91 Interceptor (org.apache.cxf.interceptor.Interceptor)87 ClassResourceInfo (org.apache.cxf.jaxrs.model.ClassResourceInfo)85 ArrayList (java.util.ArrayList)83 EndpointInfo (org.apache.cxf.service.model.EndpointInfo)76 List (java.util.List)75 IOException (java.io.IOException)73 OperationResourceInfo (org.apache.cxf.jaxrs.model.OperationResourceInfo)73 Method (java.lang.reflect.Method)69 Bus (org.apache.cxf.Bus)69 QName (javax.xml.namespace.QName)62 SoapMessage (org.apache.cxf.binding.soap.SoapMessage)55 HashMap (java.util.HashMap)53 Fault (org.apache.cxf.interceptor.Fault)51 ByteArrayInputStream (java.io.ByteArrayInputStream)49