Search in sources :

Example 31 with ClassLoaderHolder

use of org.apache.cxf.common.classloader.ClassLoaderUtils.ClassLoaderHolder in project cxf by apache.

the class JMSDestination method onMessage.

/**
 * Convert JMS message received by ListenerThread to CXF message and inform incomingObserver that a
 * message was received. The observer will call the service and then send the response CXF message by
 * using the BackChannelConduit
 *
 * @param message
 * @throws IOException
 */
public void onMessage(javax.jms.Message message) {
    ClassLoaderHolder origLoader = null;
    Bus origBus = null;
    try {
        if (loader != null) {
            origLoader = ClassLoaderUtils.setThreadContextClassloader(loader);
        }
        getLogger().log(Level.FINE, "JMS destination received message " + message + " on " + jmsConfig.getTargetDestination());
        Message inMessage = JMSMessageUtils.asCXFMessage(message, JMSConstants.JMS_SERVER_REQUEST_HEADERS);
        if (jmsConfig.isCreateSecurityContext()) {
            SecurityContext securityContext = SecurityContextFactory.buildSecurityContext(message, jmsConfig);
            inMessage.put(SecurityContext.class, securityContext);
        }
        inMessage.put(JMSConstants.JMS_SERVER_RESPONSE_HEADERS, new JMSMessageHeadersType());
        inMessage.put(JMSConstants.JMS_REQUEST_MESSAGE, message);
        ((MessageImpl) inMessage).setDestination(this);
        if (jmsConfig.getMaxSuspendedContinuations() != 0) {
            JMSContinuationProvider cp = new JMSContinuationProvider(bus, inMessage, incomingObserver, suspendedContinuations);
            inMessage.put(ContinuationProvider.class.getName(), cp);
        }
        origBus = BusFactory.getAndSetThreadDefaultBus(bus);
        // handle the incoming message
        incomingObserver.onMessage(inMessage);
        if (inMessage.getExchange() != null) {
            processExceptions(inMessage.getExchange());
        }
    } catch (SuspendedInvocationException ex) {
        getLogger().log(Level.FINE, "Request message has been suspended");
    } catch (UnsupportedEncodingException ex) {
        getLogger().log(Level.WARNING, "can't get the right encoding information. " + ex);
    } catch (JMSException e) {
        throw JMSUtil.convertJmsException(e);
    } finally {
        if (origBus != bus) {
            BusFactory.setThreadDefaultBus(origBus);
        }
        if (origLoader != null) {
            origLoader.reset();
        }
    }
}
Also used : Bus(org.apache.cxf.Bus) JMSContinuationProvider(org.apache.cxf.transport.jms.continuations.JMSContinuationProvider) ContinuationProvider(org.apache.cxf.continuations.ContinuationProvider) Message(org.apache.cxf.message.Message) SecurityContext(org.apache.cxf.security.SecurityContext) ClassLoaderHolder(org.apache.cxf.common.classloader.ClassLoaderUtils.ClassLoaderHolder) UnsupportedEncodingException(java.io.UnsupportedEncodingException) JMSContinuationProvider(org.apache.cxf.transport.jms.continuations.JMSContinuationProvider) JMSException(javax.jms.JMSException) SuspendedInvocationException(org.apache.cxf.continuations.SuspendedInvocationException) MessageImpl(org.apache.cxf.message.MessageImpl)

Example 32 with ClassLoaderHolder

use of org.apache.cxf.common.classloader.ClassLoaderUtils.ClassLoaderHolder in project cxf by apache.

the class JMSContinuation method doResume.

protected void doResume() {
    suspendendContinuations.decrementAndGet();
    ClassLoaderHolder origLoader = null;
    Bus origBus = BusFactory.getAndSetThreadDefaultBus(bus);
    try {
        if (loader != null) {
            origLoader = ClassLoaderUtils.setThreadContextClassloader(loader);
        }
        incomingObserver.onMessage(inMessage);
    } finally {
        isPending = false;
        if (origBus != bus) {
            BusFactory.setThreadDefaultBus(origBus);
        }
        if (origLoader != null) {
            origLoader.reset();
        }
    }
}
Also used : Bus(org.apache.cxf.Bus) ClassLoaderHolder(org.apache.cxf.common.classloader.ClassLoaderUtils.ClassLoaderHolder)

Example 33 with ClassLoaderHolder

use of org.apache.cxf.common.classloader.ClassLoaderUtils.ClassLoaderHolder in project tomee by apache.

the class ClientProxyImpl method doChainedInvocation.

// CHECKSTYLE:OFF
protected Object doChainedInvocation(URI uri, MultivaluedMap<String, String> headers, OperationResourceInfo ori, Object[] methodParams, Object body, int bodyIndex, Exchange exchange, Map<String, Object> invocationContext) throws Throwable {
    // CHECKSTYLE:ON
    Bus configuredBus = getConfiguration().getBus();
    Bus origBus = BusFactory.getAndSetThreadDefaultBus(configuredBus);
    ClassLoaderHolder origLoader = null;
    try {
        ClassLoader loader = configuredBus.getExtension(ClassLoader.class);
        if (loader != null) {
            origLoader = ClassLoaderUtils.setThreadContextClassloader(loader);
        }
        Message outMessage = createMessage(body, ori, headers, uri, exchange, invocationContext, true);
        if (bodyIndex != -1) {
            outMessage.put(Type.class, ori.getMethodToInvoke().getGenericParameterTypes()[bodyIndex]);
        }
        outMessage.getExchange().setOneWay(ori.isOneway());
        setSupportOnewayResponseProperty(outMessage);
        outMessage.setContent(OperationResourceInfo.class, ori);
        setPlainOperationNameProperty(outMessage, ori.getMethodToInvoke().getName());
        outMessage.getExchange().put(Method.class, ori.getMethodToInvoke());
        outMessage.put(Annotation.class.getName(), getMethodAnnotations(ori.getAnnotatedMethod(), bodyIndex));
        outMessage.getExchange().put(Message.SERVICE_OBJECT, proxy);
        if (methodParams != null) {
            outMessage.put(List.class, Arrays.asList(methodParams));
        }
        if (body != null) {
            outMessage.put(PROXY_METHOD_PARAM_BODY_INDEX, bodyIndex);
        }
        outMessage.getInterceptorChain().add(bodyWriter);
        Map<String, Object> reqContext = getRequestContext(outMessage);
        reqContext.put(OperationResourceInfo.class.getName(), ori);
        reqContext.put(PROXY_METHOD_PARAM_BODY_INDEX, bodyIndex);
        // execute chain
        InvocationCallback<Object> asyncCallback = checkAsyncCallback(ori, reqContext, outMessage);
        if (asyncCallback != null) {
            return doInvokeAsync(ori, outMessage, asyncCallback);
        }
        doRunInterceptorChain(outMessage);
        Object[] results = preProcessResult(outMessage);
        if (results != null && results.length == 1) {
            return results[0];
        }
        try {
            return handleResponse(outMessage, ori.getClassResourceInfo().getServiceClass());
        } finally {
            completeExchange(outMessage.getExchange(), true);
        }
    } finally {
        if (origLoader != null) {
            origLoader.reset();
        }
        if (origBus != configuredBus) {
            BusFactory.setThreadDefaultBus(origBus);
        }
    }
}
Also used : Bus(org.apache.cxf.Bus) Message(org.apache.cxf.message.Message) ClassLoaderHolder(org.apache.cxf.common.classloader.ClassLoaderUtils.ClassLoaderHolder) OperationResourceInfo(org.apache.cxf.jaxrs.model.OperationResourceInfo) Annotation(java.lang.annotation.Annotation)

Example 34 with ClassLoaderHolder

use of org.apache.cxf.common.classloader.ClassLoaderUtils.ClassLoaderHolder in project tomee by apache.

the class JAXRSServerFactoryBean method create.

/**
 * Creates the JAX-RS Server instance
 * @return the server
 */
public Server create() {
    ClassLoaderHolder origLoader = null;
    try {
        Bus bus = getBus();
        ClassLoader loader = bus.getExtension(ClassLoader.class);
        if (loader != null) {
            origLoader = ClassLoaderUtils.setThreadContextClassloader(loader);
        }
        serviceFactory.setBus(bus);
        checkResources(true);
        if (serviceFactory.getService() == null) {
            serviceFactory.create();
        }
        Endpoint ep = createEndpoint();
        getServiceFactory().sendEvent(FactoryBeanListener.Event.PRE_SERVER_CREATE, server);
        server = new ServerImpl(getBus(), ep, getDestinationFactory(), getBindingFactory());
        Invoker invoker = serviceFactory.getInvoker();
        if (invoker == null) {
            ep.getService().setInvoker(createInvoker());
        } else {
            ep.getService().setInvoker(invoker);
        }
        ServerProviderFactory factory = setupFactory(ep);
        ep.put(Application.class.getName(), appProvider);
        factory.setRequestPreprocessor(new RequestPreprocessor(languageMappings, extensionMappings));
        ep.put(Bus.class.getName(), getBus());
        if (documentLocation != null) {
            ep.put(JAXRSUtils.DOC_LOCATION, documentLocation);
        }
        if (rc != null) {
            ep.put("org.apache.cxf.jaxrs.comparator", rc);
        }
        checkPrivateEndpoint(ep);
        applyBusFeatures(getBus());
        applyFeatures();
        updateClassResourceProviders(ep);
        injectContexts(factory, (ApplicationInfo) ep.get(Application.class.getName()));
        factory.applyDynamicFeatures(getServiceFactory().getClassResourceInfo());
        getServiceFactory().sendEvent(FactoryBeanListener.Event.SERVER_CREATED, server, null, null);
        if (start) {
            try {
                server.start();
            } catch (RuntimeException re) {
                if (!(re instanceof ServiceConstructionException && re.getMessage().startsWith("There is an endpoint already running on"))) {
                    // avoid destroying another server on the same endpoint url
                    // prevent resource leak if server really started by itself
                    server.destroy();
                }
                throw re;
            }
        }
    } catch (Exception e) {
        throw new ServiceConstructionException(e);
    } finally {
        if (origLoader != null) {
            origLoader.reset();
        }
    }
    return server;
}
Also used : ServerProviderFactory(org.apache.cxf.jaxrs.provider.ServerProviderFactory) Bus(org.apache.cxf.Bus) RequestPreprocessor(org.apache.cxf.jaxrs.impl.RequestPreprocessor) Endpoint(org.apache.cxf.endpoint.Endpoint) ServerImpl(org.apache.cxf.endpoint.ServerImpl) Invoker(org.apache.cxf.service.invoker.Invoker) ClassLoaderHolder(org.apache.cxf.common.classloader.ClassLoaderUtils.ClassLoaderHolder) ServiceConstructionException(org.apache.cxf.service.factory.ServiceConstructionException) Application(javax.ws.rs.core.Application) ServiceConstructionException(org.apache.cxf.service.factory.ServiceConstructionException)

Example 35 with ClassLoaderHolder

use of org.apache.cxf.common.classloader.ClassLoaderUtils.ClassLoaderHolder in project tomee by apache.

the class ClientImpl method doInvoke.

private Object[] doInvoke(final ClientCallback callback, BindingOperationInfo oi, Object[] params, Map<String, Object> context, Exchange exchange) throws Exception {
    Bus origBus = BusFactory.getAndSetThreadDefaultBus(bus);
    ClassLoaderHolder origLoader = null;
    Map<String, Object> resContext = null;
    try {
        ClassLoader loader = bus.getExtension(ClassLoader.class);
        if (loader != null) {
            origLoader = ClassLoaderUtils.setThreadContextClassloader(loader);
        }
        if (exchange == null) {
            exchange = new ExchangeImpl();
        }
        exchange.setSynchronous(callback == null);
        Endpoint endpoint = getEndpoint();
        if (LOG.isLoggable(Level.FINE)) {
            LOG.fine("Invoke, operation info: " + oi + ", params: " + Arrays.toString(params));
        }
        Message message = endpoint.getBinding().createMessage();
        // on message
        if (context == null) {
            context = new HashMap<>();
        }
        Map<String, Object> reqContext = CastUtils.cast((Map<?, ?>) context.get(REQUEST_CONTEXT));
        resContext = CastUtils.cast((Map<?, ?>) context.get(RESPONSE_CONTEXT));
        if (reqContext == null) {
            reqContext = new HashMap<>(getRequestContext());
            context.put(REQUEST_CONTEXT, reqContext);
        }
        if (resContext == null) {
            resContext = new ResponseContext(responseContext);
            context.put(RESPONSE_CONTEXT, resContext);
        }
        message.put(Message.INVOCATION_CONTEXT, context);
        setContext(reqContext, message);
        exchange.putAll(reqContext);
        setParameters(params, message);
        if (null != oi) {
            exchange.setOneWay(oi.getOutput() == null);
        }
        exchange.setOutMessage(message);
        exchange.put(ClientCallback.class, callback);
        setOutMessageProperties(message, oi);
        setExchangeProperties(exchange, endpoint, oi);
        PhaseInterceptorChain chain = setupInterceptorChain(endpoint);
        message.setInterceptorChain(chain);
        if (callback == null) {
            chain.setFaultObserver(outFaultObserver);
        } else {
            // We need to wrap the outFaultObserver if the callback is not null
            // calling the conduitSelector.complete to make sure the fail over feature works
            chain.setFaultObserver(new MessageObserver() {

                public void onMessage(Message message) {
                    Exception ex = message.getContent(Exception.class);
                    if (ex != null) {
                        completeExchange(message.getExchange());
                        if (message.getContent(Exception.class) == null) {
                            // handle the right response
                            Message inMsg = message.getExchange().getInMessage();
                            Map<String, Object> ctx = responseContext.get(Thread.currentThread());
                            List<Object> resList = CastUtils.cast(inMsg.getContent(List.class));
                            Object[] result = resList == null ? null : resList.toArray();
                            callback.handleResponse(ctx, result);
                            return;
                        }
                    }
                    outFaultObserver.onMessage(message);
                }
            });
        }
        prepareConduitSelector(message);
        // add additional interceptors and such
        modifyChain(chain, message, false);
        try {
            chain.doIntercept(message);
        } catch (Fault fault) {
            enrichFault(fault);
            throw fault;
        }
        if (callback != null) {
            return null;
        }
        return processResult(message, exchange, oi, resContext);
    } finally {
        // ensure ResponseContext has HTTP RESPONSE CODE
        if (null != exchange) {
            Integer responseCode = (Integer) exchange.get(Message.RESPONSE_CODE);
            resContext.put(MessageContext.HTTP_RESPONSE_CODE, responseCode);
            resContext.put(org.apache.cxf.message.Message.RESPONSE_CODE, responseCode);
            setResponseContext(resContext);
        }
        if (origLoader != null) {
            origLoader.reset();
        }
        if (origBus != bus) {
            BusFactory.setThreadDefaultBus(origBus);
        }
    }
}
Also used : Bus(org.apache.cxf.Bus) PhaseInterceptorChain(org.apache.cxf.phase.PhaseInterceptorChain) MessageObserver(org.apache.cxf.transport.MessageObserver) Message(org.apache.cxf.message.Message) ClassLoaderHolder(org.apache.cxf.common.classloader.ClassLoaderUtils.ClassLoaderHolder) Fault(org.apache.cxf.interceptor.Fault) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) UncheckedException(org.apache.cxf.common.i18n.UncheckedException) MessageContentsList(org.apache.cxf.message.MessageContentsList) List(java.util.List) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) WeakHashMap(java.util.WeakHashMap) ExchangeImpl(org.apache.cxf.message.ExchangeImpl)

Aggregations

ClassLoaderHolder (org.apache.cxf.common.classloader.ClassLoaderUtils.ClassLoaderHolder)36 Bus (org.apache.cxf.Bus)24 Message (org.apache.cxf.message.Message)15 IOException (java.io.IOException)7 Exchange (org.apache.cxf.message.Exchange)6 PhaseInterceptorChain (org.apache.cxf.phase.PhaseInterceptorChain)6 ServerImpl (org.apache.cxf.endpoint.ServerImpl)5 ExchangeImpl (org.apache.cxf.message.ExchangeImpl)5 Endpoint (org.apache.cxf.endpoint.Endpoint)4 URISyntaxException (java.net.URISyntaxException)3 List (java.util.List)3 Application (javax.ws.rs.core.Application)3 Fault (org.apache.cxf.interceptor.Fault)3 InterceptorChain (org.apache.cxf.interceptor.InterceptorChain)3 OperationResourceInfo (org.apache.cxf.jaxrs.model.OperationResourceInfo)3 Annotation (java.lang.annotation.Annotation)2 Method (java.lang.reflect.Method)2 URI (java.net.URI)2 URL (java.net.URL)2 HashMap (java.util.HashMap)2