org.apache.cxf.common.classloader.ClassLoaderUtils.ClassLoaderHolder Java Examples

The following examples show how to use org.apache.cxf.common.classloader.ClassLoaderUtils.ClassLoaderHolder. 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 check out the related API usage on the sidebar.
Example #1
Source File: UndertowHTTPDestination.java    From wildfly-camel with Apache License 2.0 6 votes vote down vote up
@Override
public void service(ServletContext context, HttpServletRequest req, HttpServletResponse resp) throws IOException {

    ClassLoaderHolder origLoader = null;
    Bus origBus = BusFactory.getAndSetThreadDefaultBus(bus);
    try {
        if (loader != null) {
            origLoader = ClassLoaderUtils.setThreadContextClassloader(loader);
        }
        invoke(null, context, req, resp);
    } finally {
        if (origBus != bus) {
            BusFactory.setThreadDefaultBus(origBus);
        }
        if (origLoader != null) {
            origLoader.reset();
        }
    }
}
 
Example #2
Source File: JaxWsServerFactoryBean.java    From cxf with Apache License 2.0 6 votes vote down vote up
public Server create() {
    ClassLoaderHolder orig = null;
    try {
        if (bus != null) {
            ClassLoader loader = bus.getExtension(ClassLoader.class);
            if (loader != null) {
                orig = ClassLoaderUtils.setThreadContextClassloader(loader);
            }
        }

        Server server = super.create();
        initializeResourcesAndHandlerChain(server);
        checkPrivateEndpoint(server.getEndpoint());

        return server;
    } finally {
        if (orig != null) {
            orig.reset();
        }
    }
}
 
Example #3
Source File: JMSContinuation.java    From cxf with Apache License 2.0 6 votes vote down vote up
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();
        }
    }
}
 
Example #4
Source File: CXFNonSpringServlet.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Override
protected void invoke(HttpServletRequest request, HttpServletResponse response) throws ServletException {
    ClassLoaderHolder origLoader = null;
    Bus origBus = null;
    try {
        if (loader != null) {
            origLoader = ClassLoaderUtils.setThreadContextClassloader(loader);
        }
        if (bus != null) {
            origBus = BusFactory.getAndSetThreadDefaultBus(bus);
        }
        controller.invoke(request, response);
    } finally {
        if (origBus != bus) {
            BusFactory.setThreadDefaultBus(origBus);
        }
        if (origLoader != null) {
            origLoader.reset();
        }
    }
}
 
Example #5
Source File: AbstractWSS4JInterceptor.java    From steady with Apache License 2.0 5 votes vote down vote up
@Override
protected Crypto loadCryptoFromPropertiesFile(
    String propFilename, 
    RequestData reqData
) throws WSSecurityException {
    ClassLoaderHolder orig = null;
    try {
        try {
            URL url = ClassLoaderUtils.getResource(propFilename, this.getClass());
            if (url == null) {
                ResourceManager manager = ((Message)reqData.getMsgContext()).getExchange()
                        .getBus().getExtension(ResourceManager.class);
                ClassLoader loader = manager.resolveResource("", ClassLoader.class);
                if (loader != null) {
                    orig = ClassLoaderUtils.setThreadContextClassloader(loader);
                }
                url = manager.resolveResource(propFilename, URL.class);
            }
            if (url != null) {
                Properties props = new Properties();
                InputStream in = url.openStream(); 
                props.load(in);
                in.close();
                return CryptoFactory.getInstance(props,
                                                 this.getClassLoader(reqData.getMsgContext()));
            }
        } catch (Exception e) {
            //ignore
        } 
        return CryptoFactory.getInstance(propFilename, this.getClassLoader(reqData.getMsgContext()));
    } finally {
        if (orig != null) {
            orig.reset();
        }
    }
}
 
Example #6
Source File: XPathUtils.java    From cxf with Apache License 2.0 5 votes vote down vote up
public Object getValue(String xpathExpression, Node node, QName type) {
    ClassLoaderHolder loader
        = ClassLoaderUtils.setThreadContextClassloader(getClassLoader(xpath.getClass()));
    try {
        return xpath.evaluate(xpathExpression, node, type);
    } catch (Exception e) {
        return null;
    } finally {
        if (loader != null) {
            loader.reset();
        }
    }
}
 
Example #7
Source File: NettyHttpDestination.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected void doService(ServletContext context,
                         HttpServletRequest req,
                         HttpServletResponse resp) throws IOException {
    if (context == null) {
        context = servletContext;
    }

    if (getServer().isSetRedirectURL()) {
        resp.sendRedirect(getServer().getRedirectURL());
        resp.flushBuffer();
        return;
    }

    // REVISIT: service on executor if associated with endpoint
    ClassLoaderHolder origLoader = null;
    Bus origBus = BusFactory.getAndSetThreadDefaultBus(bus);
    try {
        if (loader != null) {
            origLoader = ClassLoaderUtils.setThreadContextClassloader(loader);
        }
        invoke(null, context, req, resp);
    } finally {
        if (origBus != bus) {
            BusFactory.setThreadDefaultBus(origBus);
        }
        if (origLoader != null) {
            origLoader.reset();
        }
    }
}
 
Example #8
Source File: UndertowHTTPDestination.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected void doService(ServletContext context,
                         HttpServletRequest req,
                         HttpServletResponse resp) throws IOException {
    if (context == null) {
        context = servletContext;
    }
    HTTPServerPolicy sp = getServer();
    if (sp.isSetRedirectURL()) {
        resp.sendRedirect(sp.getRedirectURL());
        resp.flushBuffer();
        return;
    }

    ClassLoaderHolder origLoader = null;
    Bus origBus = BusFactory.getAndSetThreadDefaultBus(bus);
    try {
        if (loader != null) {
            origLoader = ClassLoaderUtils.setThreadContextClassloader(loader);
        }
        invoke(null, context, req, resp);
    } finally {
        if (origBus != bus) {
            BusFactory.setThreadDefaultBus(origBus);
        }
        if (origLoader != null) {
            origLoader.reset();
        }
    }
}
 
Example #9
Source File: JettyHTTPDestination.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected void doService(ServletContext context,
                         HttpServletRequest req,
                         HttpServletResponse resp) throws IOException {
    if (context == null) {
        context = servletContext;
    }
    Request baseRequest = (req instanceof Request)
        ? (Request)req : getCurrentRequest();

    HTTPServerPolicy sp = getServer();
    if (sp.isSetRedirectURL()) {
        resp.sendRedirect(sp.getRedirectURL());
        resp.flushBuffer();
        baseRequest.setHandled(true);
        return;
    }

    // REVISIT: service on executor if associated with endpoint
    ClassLoaderHolder origLoader = null;
    Bus origBus = BusFactory.getAndSetThreadDefaultBus(bus);
    try {
        if (loader != null) {
            origLoader = ClassLoaderUtils.setThreadContextClassloader(loader);
        }
        invoke(null, context, req, resp);
    } finally {
        if (origBus != bus) {
            BusFactory.setThreadDefaultBus(origBus);
        }
        if (origLoader != null) {
            origLoader.reset();
        }
    }
}
 
Example #10
Source File: CXFNonSpringServlet.java    From cxf with Apache License 2.0 5 votes vote down vote up
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
    throws IOException, ServletException {
    ClassLoaderHolder origLoader = null;
    Bus origBus = null;
    if (request instanceof HttpServletRequest && response instanceof HttpServletResponse) {
        try {
            if (loader != null) {
                origLoader = ClassLoaderUtils.setThreadContextClassloader(loader);
            }
            if (bus != null) {
                origBus = BusFactory.getAndSetThreadDefaultBus(bus);
            }
            HttpServletRequest httpRequest = (HttpServletRequest)request;
            if (controller.filter(new HttpServletRequestFilter(httpRequest,
                                                               super.getServletName()),
                                  (HttpServletResponse)response)) {
                return;
            }
        } finally {
            if (origBus != bus) {
                BusFactory.setThreadDefaultBus(origBus);
            }
            if (origLoader != null) {
                origLoader.reset();
            }
        }
    }
    chain.doFilter(request, response);
}
 
Example #11
Source File: ClientMessageObserver.java    From cxf with Apache License 2.0 5 votes vote down vote up
public void onMessage(Message m) {

        Message message = cfg.getConduitSelector().getEndpoint().getBinding().createMessage(m);
        message.put(Message.REQUESTOR_ROLE, Boolean.TRUE);
        message.put(Message.INBOUND_MESSAGE, Boolean.TRUE);
        PhaseInterceptorChain chain = AbstractClient.setupInInterceptorChain(cfg);
        message.setInterceptorChain(chain);
        message.getExchange().setInMessage(message);
        Bus bus = cfg.getBus();
        Bus origBus = BusFactory.getAndSetThreadDefaultBus(bus);
        ClassLoaderHolder origLoader = null;
        try {
            if (loader != null) {
                origLoader = ClassLoaderUtils.setThreadContextClassloader(loader);
            }
            // execute chain
            chain.doIntercept(message);
        } finally {
            if (origBus != bus) {
                BusFactory.setThreadDefaultBus(origBus);
            }
            if (origLoader != null) {
                origLoader.reset();
            }
            synchronized (message.getExchange()) {
                message.getExchange().notifyAll();
            }
        }
    }
 
Example #12
Source File: WebClient.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected Response doChainedInvocation(String httpMethod, //NOPMD
                                       MultivaluedMap<String, String> headers,
                                       Object body,
                                       Class<?> requestClass,
                                       Type inType,
                                       Annotation[] inAnns,
                                       Class<?> respClass,
                                       Type outType,
                                       Exchange exchange,
                                       Map<String, Object> invContext) {
//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 m = finalizeMessage(httpMethod, headers, body, requestClass, inType,
                                    inAnns, respClass, outType, exchange, invContext);
        doRunInterceptorChain(m);
        return doResponse(m, respClass, outType);
    } finally {
        if (origLoader != null) {
            origLoader.reset();
        }
        if (origBus != configuredBus) {
            BusFactory.setThreadDefaultBus(origBus);
        }
    }
}
 
Example #13
Source File: JaxWsProxyFactoryBean.java    From cxf with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a JAX-WS proxy that can be used to make remote invocations.
 *
 * @return the proxy. You must cast the returned object to the approriate class
 * before making remote calls
 */
@Override
public synchronized Object create() {
    ClassLoaderHolder orig = null;
    try {
        if (getBus() != null) {
            ClassLoader loader = getBus().getExtension(ClassLoader.class);
            if (loader != null) {
                orig = ClassLoaderUtils.setThreadContextClassloader(loader);
            }
        }

        Object obj = super.create();
        Service service = getServiceFactory().getService();
        if (needWrapperClassInterceptor(service.getServiceInfos().get(0))) {
            List<Interceptor<? extends Message>> in = super.getInInterceptors();
            List<Interceptor<? extends Message>> out = super.getOutInterceptors();
            in.add(new WrapperClassInInterceptor());
            in.add(new HolderInInterceptor());
            out.add(new WrapperClassOutInterceptor());
            out.add(new HolderOutInterceptor());
        }
        return obj;
    } finally {
        if (orig != null) {
            orig.reset();
        }
    }
}
 
Example #14
Source File: AbstractWSS4JInterceptor.java    From steady with Apache License 2.0 5 votes vote down vote up
@Override
protected Crypto loadCryptoFromPropertiesFile(
    String propFilename, 
    RequestData reqData
) throws WSSecurityException {
    ClassLoaderHolder orig = null;
    try {
        try {
            URL url = ClassLoaderUtils.getResource(propFilename, this.getClass());
            if (url == null) {
                ResourceManager manager = ((Message)reqData.getMsgContext()).getExchange()
                        .getBus().getExtension(ResourceManager.class);
                ClassLoader loader = manager.resolveResource("", ClassLoader.class);
                if (loader != null) {
                    orig = ClassLoaderUtils.setThreadContextClassloader(loader);
                }
                url = manager.resolveResource(propFilename, URL.class);
            }
            if (url != null) {
                Properties props = new Properties();
                InputStream in = url.openStream(); 
                props.load(in);
                in.close();
                return CryptoFactory.getInstance(props,
                                                 this.getClassLoader(reqData.getMsgContext()));
            }
        } catch (Exception e) {
            //ignore
        } 
        return CryptoFactory.getInstance(propFilename, this.getClassLoader(reqData.getMsgContext()));
    } finally {
        if (orig != null) {
            orig.reset();
        }
    }
}
 
Example #15
Source File: AbstractWSS4JInterceptor.java    From steady with Apache License 2.0 5 votes vote down vote up
@Override
protected Crypto loadCryptoFromPropertiesFile(
    String propFilename, 
    RequestData reqData
) throws WSSecurityException {
    ClassLoaderHolder orig = null;
    try {
        try {
            URL url = ClassLoaderUtils.getResource(propFilename, this.getClass());
            if (url == null) {
                ResourceManager manager = ((Message)reqData.getMsgContext()).getExchange()
                        .getBus().getExtension(ResourceManager.class);
                ClassLoader loader = manager.resolveResource("", ClassLoader.class);
                if (loader != null) {
                    orig = ClassLoaderUtils.setThreadContextClassloader(loader);
                }
                url = manager.resolveResource(propFilename, URL.class);
            }
            if (url != null) {
                Properties props = new Properties();
                InputStream in = url.openStream(); 
                props.load(in);
                in.close();
                return CryptoFactory.getInstance(props,
                                                 this.getClassLoader(reqData.getMsgContext()));
            }
        } catch (Exception e) {
            //ignore
        } 
        return CryptoFactory.getInstance(propFilename, this.getClassLoader(reqData.getMsgContext()));
    } finally {
        if (orig != null) {
            orig.reset();
        }
    }
}
 
Example #16
Source File: AbstractWSS4JInterceptor.java    From steady with Apache License 2.0 5 votes vote down vote up
@Override
protected Crypto loadCryptoFromPropertiesFile(
    String propFilename, 
    RequestData reqData
) throws WSSecurityException {
    ClassLoaderHolder orig = null;
    try {
        try {
            URL url = ClassLoaderUtils.getResource(propFilename, this.getClass());
            if (url == null) {
                ResourceManager manager = ((Message)reqData.getMsgContext()).getExchange()
                        .getBus().getExtension(ResourceManager.class);
                ClassLoader loader = manager.resolveResource("", ClassLoader.class);
                if (loader != null) {
                    orig = ClassLoaderUtils.setThreadContextClassloader(loader);
                }
                url = manager.resolveResource(propFilename, URL.class);
            }
            if (url != null) {
                Properties props = new Properties();
                InputStream in = url.openStream(); 
                props.load(in);
                in.close();
                return CryptoFactory.getInstance(props,
                                                 this.getClassLoader(reqData.getMsgContext()));
            }
        } catch (Exception e) {
            //ignore
        } 
        return CryptoFactory.getInstance(propFilename, this.getClassLoader(reqData.getMsgContext()));
    } finally {
        if (orig != null) {
            orig.reset();
        }
    }
}
 
Example #17
Source File: ClientProxyImpl.java    From cxf with Apache License 2.0 4 votes vote down vote up
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);
        }
    }

}
 
Example #18
Source File: ColocMessageObserver.java    From cxf with Apache License 2.0 4 votes vote down vote up
public void onMessage(Message m) {
    Bus origBus = BusFactory.getAndSetThreadDefaultBus(bus);
    ClassLoaderHolder origLoader = null;
    try {
        if (loader != null) {
            origLoader = ClassLoaderUtils.setThreadContextClassloader(loader);
        }
        if (LOG.isLoggable(Level.FINER)) {
            LOG.finer("Processing Message at collocated endpoint.  Request message: " + m);
        }
        Exchange ex = new ExchangeImpl();
        setExchangeProperties(ex, m);

        Message inMsg = endpoint.getBinding().createMessage();
        MessageImpl.copyContent(m, inMsg);

        //Copy Request Context to Server inBound Message
        //TODO a Context Filter Strategy required.
        inMsg.putAll(m);

        inMsg.put(COLOCATED, Boolean.TRUE);
        inMsg.put(Message.REQUESTOR_ROLE, Boolean.FALSE);
        inMsg.put(Message.INBOUND_MESSAGE, Boolean.TRUE);
        BindingOperationInfo boi = ex.getBindingOperationInfo();
        OperationInfo oi = boi != null ? boi.getOperationInfo() : null;
        if (oi != null) {
            inMsg.put(MessageInfo.class, oi.getInput());
        }
        ex.setInMessage(inMsg);
        inMsg.setExchange(ex);

        if (LOG.isLoggable(Level.FINEST)) {
            LOG.finest("Build inbound interceptor chain.");
        }

        //Add all interceptors between USER_LOGICAL and INVOKE.
        SortedSet<Phase> phases = new TreeSet<>(bus.getExtension(PhaseManager.class).getInPhases());
        ColocUtil.setPhases(phases, Phase.USER_LOGICAL, Phase.INVOKE);
        InterceptorChain chain = ColocUtil.getInInterceptorChain(ex, phases);
        chain.add(addColocInterceptors());
        inMsg.setInterceptorChain(chain);

        //Convert the coloc object type if necessary
        BindingOperationInfo bop = m.getExchange().getBindingOperationInfo();
        OperationInfo soi = bop != null ? bop.getOperationInfo() : null;
        if (soi != null && oi != null) {
            if (ColocUtil.isAssignableOperationInfo(soi, Source.class)
                && !ColocUtil.isAssignableOperationInfo(oi, Source.class)) {
                // converting source -> pojo
                ColocUtil.convertSourceToObject(inMsg);
            } else if (ColocUtil.isAssignableOperationInfo(oi, Source.class)
                && !ColocUtil.isAssignableOperationInfo(soi, Source.class)) {
                // converting pojo -> source
                ColocUtil.convertObjectToSource(inMsg);
            }
        }
        chain.doIntercept(inMsg);
        if (soi != null && oi != null) {
            if (ColocUtil.isAssignableOperationInfo(soi, Source.class)
                && !ColocUtil.isAssignableOperationInfo(oi, Source.class)
                && ex.getOutMessage() != null) {
                // converting pojo -> source
                ColocUtil.convertObjectToSource(ex.getOutMessage());
            } else if (ColocUtil.isAssignableOperationInfo(oi, Source.class)
                && !ColocUtil.isAssignableOperationInfo(soi, Source.class)
                && ex.getOutMessage() != null) {
                // converting pojo -> source
                ColocUtil.convertSourceToObject(ex.getOutMessage());
            }
        }
        //Set Server OutBound Message onto InBound Exchange.
        setOutBoundMessage(ex, m.getExchange());
    } finally {
        if (origBus != bus) {
            BusFactory.setThreadDefaultBus(origBus);
        }
        if (origLoader != null) {
            origLoader.reset();
        }
    }
}
 
Example #19
Source File: ServletController.java    From cxf with Apache License 2.0 4 votes vote down vote up
public boolean invoke(HttpServletRequest request, HttpServletResponse res, boolean returnErrors)
    throws ServletException {
    try {
        String pathInfo = request.getPathInfo() == null ? "" : request.getPathInfo();
        AbstractHTTPDestination d = destinationRegistry.getDestinationForPath(pathInfo, true);

        if (d == null) {
            if (!isHideServiceList && (request.getRequestURI().endsWith(serviceListRelativePath)
                || request.getRequestURI().endsWith(serviceListRelativePath + "/")
                || StringUtils.isEmpty(pathInfo)
                || "/".equals(pathInfo))) {
                if (isAuthServiceListPage) {
                    setAuthServiceListPageAttribute(request);
                }
                setBaseURLAttribute(request);
                serviceListGenerator.service(request, res);
            } else {
                d = destinationRegistry.checkRestfulRequest(pathInfo);
                if (d == null || d.getMessageObserver() == null) {
                    if (returnErrors) {
                        LOG.warning("Can't find the request for "
                            + request.getRequestURL() + "'s Observer ");
                        generateNotFound(request, res);
                    }
                    return false;
                }
            }
        }
        if (d != null && d.getMessageObserver() != null) {
            Bus bus = d.getBus();
            ClassLoaderHolder orig = null;
            try {
                if (bus != null) {
                    ClassLoader loader = bus.getExtension(ClassLoader.class);
                    if (loader == null) {
                        ResourceManager manager = bus.getExtension(ResourceManager.class);
                        if (manager != null) {
                            loader = manager.resolveResource("", ClassLoader.class);
                        }
                    }
                    if (loader != null) {
                        //need to set the context classloader to the loader of the bundle
                        orig = ClassLoaderUtils.setThreadContextClassloader(loader);
                    }
                }
                updateDestination(request, d);
                invokeDestination(request, res, d);
            } finally {
                if (orig != null) {
                    orig.reset();
                }
            }
        }
    } catch (IOException e) {
        throw new ServletException(e);
    }
    return true;
}
 
Example #20
Source File: JAXRSServerFactoryBean.java    From cxf with Apache License 2.0 4 votes vote down vote up
/**
 * 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) {
                server.destroy(); // prevent resource leak
                throw re;
            }
        }
    } catch (Exception e) {
        throw new ServiceConstructionException(e);
    } finally {
        if (origLoader != null) {
            origLoader.reset();
        }
    }

    return server;
}
 
Example #21
Source File: ClientProxyFactoryBean.java    From cxf with Apache License 2.0 4 votes vote down vote up
/**
 * Creates a proxy object that can be used to make remote invocations.
 *
 * @return the proxy. You must cast the returned object to the appropriate class before using it.
 */
public synchronized Object create() {
    ClassLoaderHolder orig = null;
    ClassLoader loader = null;
    try {
        if (getBus() != null) {
            loader = getBus().getExtension(ClassLoader.class);
            if (loader != null) {
                orig = ClassLoaderUtils.setThreadContextClassloader(loader);
            }
        }
        configureObject();

        if (properties == null) {
            properties = new HashMap<>();
        }

        if (username != null) {
            AuthorizationPolicy authPolicy = new AuthorizationPolicy();
            authPolicy.setUserName(username);
            authPolicy.setPassword(password);
            properties.put(AuthorizationPolicy.class.getName(), authPolicy);
        }

        initFeatures();
        clientFactoryBean.setProperties(properties);

        if (bus != null) {
            clientFactoryBean.setBus(bus);
        }

        if (dataBinding != null) {
            clientFactoryBean.setDataBinding(dataBinding);
        }

        Client c = clientFactoryBean.create();
        if (getInInterceptors() != null) {
            c.getInInterceptors().addAll(getInInterceptors());
        }
        if (getOutInterceptors() != null) {
            c.getOutInterceptors().addAll(getOutInterceptors());
        }
        if (getInFaultInterceptors() != null) {
            c.getInFaultInterceptors().addAll(getInFaultInterceptors());
        }
        if (getOutFaultInterceptors() != null) {
            c.getOutFaultInterceptors().addAll(getOutFaultInterceptors());
        }

        ClientProxy handler = clientClientProxy(c);

        Class<?>[] classes = getImplementingClasses();
        Object obj = ProxyHelper.getProxy(getClassLoader(clientFactoryBean.getServiceClass()),
                                          classes,
                                          handler);

        this.getServiceFactory().sendEvent(FactoryBeanListener.Event.PROXY_CREATED,
                                           classes, handler, obj);
        return obj;
    } finally {
        if (orig != null) {
            orig.reset();
        }
    }
}
 
Example #22
Source File: ServerFactoryBean.java    From cxf with Apache License 2.0 4 votes vote down vote up
public Server create() {
    ClassLoaderHolder orig = null;
    try {
        Server server = null;
        try {
            if (bus != null) {
                ClassLoader loader = bus.getExtension(ClassLoader.class);
                if (loader != null) {
                    orig = ClassLoaderUtils.setThreadContextClassloader(loader);
                }
            }

            if (getServiceFactory().getProperties() == null) {
                getServiceFactory().setProperties(getProperties());
            } else if (getProperties() != null) {
                getServiceFactory().getProperties().putAll(getProperties());
            }
            if (serviceBean != null && getServiceClass() == null) {
                setServiceClass(ClassHelper.getRealClass(bus, serviceBean));
            }
            if (invoker != null) {
                getServiceFactory().setInvoker(invoker);
            } else if (serviceBean != null) {
                invoker = createInvoker();
                getServiceFactory().setInvoker(invoker);
            }

            Endpoint ep = createEndpoint();

            getServiceFactory().sendEvent(FactoryBeanListener.Event.PRE_SERVER_CREATE, server, serviceBean,
                                          serviceBean == null
                                          ? getServiceClass() == null
                                              ? getServiceFactory().getServiceClass()
                                              : getServiceClass()
                                          : getServiceClass() == null
                                              ? ClassHelper.getRealClass(getBus(), getServiceBean())
                                              : getServiceClass());

            server = new ServerImpl(getBus(),
                                    ep,
                                    getDestinationFactory(),
                                    getBindingFactory());

            if (ep.getService().getInvoker() == null) {
                if (invoker == null) {
                    ep.getService().setInvoker(createInvoker());
                } else {
                    ep.getService().setInvoker(invoker);
                }
            }

        } catch (EndpointException | BusException | IOException e) {
            throw new ServiceConstructionException(e);
        }

        if (serviceBean != null) {
            Class<?> cls = ClassHelper.getRealClass(getServiceBean());
            if (getServiceClass() == null || cls.equals(getServiceClass())) {
                initializeAnnotationInterceptors(server.getEndpoint(), cls);
            } else {
                initializeAnnotationInterceptors(server.getEndpoint(), cls, getServiceClass());
            }
        } else if (getServiceClass() != null) {
            initializeAnnotationInterceptors(server.getEndpoint(), getServiceClass());
        }

        applyFeatures(server);

        getServiceFactory().sendEvent(FactoryBeanListener.Event.SERVER_CREATED, server, serviceBean,
                                      serviceBean == null
                                      ? getServiceClass() == null
                                          ? getServiceFactory().getServiceClass()
                                          : getServiceClass()
                                      : getServiceClass() == null
                                          ? ClassHelper.getRealClass(getServiceBean())
                                          : getServiceClass());

        if (start) {
            try {
                server.start();
            } catch (RuntimeException re) {
                server.destroy(); // prevent resource leak
                throw re;
            }
        }
        getServiceFactory().reset();

        return server;
    } finally {
        if (orig != null) {
            orig.reset();
        }
    }
}
 
Example #23
Source File: EndpointImpl.java    From cxf with Apache License 2.0 4 votes vote down vote up
/**
 * Performs the publication action by setting up a {@link Server}
 * instance based on this endpoint's configuration.
 *
 * @param addr the optional endpoint address.
 *
 * @throws IllegalStateException if the endpoint cannot be published/republished
 * @throws SecurityException if permission checking is enabled and policy forbids publishing
 * @throws WebServiceException if there is an error publishing the endpoint
 *
 * @see #checkPublishPermission()
 * @see #checkPublishable()
 * @see #getServer(String)
 */
protected void doPublish(String addr) {
    checkPublishPermission();
    checkPublishable();

    ServerImpl serv = null;

    ClassLoaderHolder loader = null;
    try {
        if (bus != null) {
            ClassLoader newLoader = bus.getExtension(ClassLoader.class);
            if (newLoader != null) {
                loader = ClassLoaderUtils.setThreadContextClassloader(newLoader);
            }
        }
        serv = getServer(addr);
        if (addr != null) {
            EndpointInfo endpointInfo = serv.getEndpoint().getEndpointInfo();
            if (endpointInfo.getAddress() == null || !endpointInfo.getAddress().contains(addr)) {
                endpointInfo.setAddress(addr);
            }
            if (publishedEndpointUrl != null) {
                endpointInfo.setProperty(WSDLGetUtils.PUBLISHED_ENDPOINT_URL, publishedEndpointUrl);
            }
            if (publishedEndpointUrl != null && wsdlLocation != null) {
                //early update the publishedEndpointUrl so that endpoints in the same app sharing the same wsdl
                //do not require all of them to be queried for wsdl before the wsdl is finally fully updated
                Definition def = endpointInfo.getService()
                    .getProperty(WSDLServiceBuilder.WSDL_DEFINITION, Definition.class);
                if (def == null) {
                    def = bus.getExtension(WSDLManager.class).getDefinition(wsdlLocation);
                }
                new WSDLGetUtils().updateWSDLPublishedEndpointAddress(def, endpointInfo);
            }

            if (null != properties) {
                for (Entry<String, Object> entry : properties.entrySet()) {
                    endpointInfo.setProperty(entry.getKey(), entry.getValue());
                }
            }

            this.address = endpointInfo.getAddress();
        }
        serv.start();
        publishable = false;
    } catch (Exception ex) {
        try {
            stop();
        } catch (Exception e) {
            // Nothing we can do.
        }

        throw new WebServiceException(ex);
    } finally {
        if (loader != null) {
            loader.reset();
        }
    }
}
 
Example #24
Source File: AutomaticWorkQueueImpl.java    From cxf with Apache License 2.0 4 votes vote down vote up
public void execute(final Runnable command) {
    //Grab the context classloader of this thread.   We'll make sure we use that
    //on the thread the runnable actually runs on.

    final ClassLoader loader = Thread.currentThread().getContextClassLoader();
    Runnable r = new Runnable() {
        public void run() {
            ClassLoaderHolder orig = ClassLoaderUtils.setThreadContextClassloader(loader);
            try {
                command.run();
            } finally {
                if (orig != null) {
                    orig.reset();
                }
            }
        }
    };
    //The ThreadPoolExecutor in the JDK doesn't expand the number
    //of threads until the queue is full.   However, we would
    //prefer the number of threads to expand immediately and
    //only uses the queue if we've reached the maximum number
    //of threads.
    ThreadPoolExecutor ex = getExecutor();
    ex.execute(r);
    if (addWorkerMethod != null
        && !ex.getQueue().isEmpty()
        && this.approxThreadCount < highWaterMark
        && addThreadLock.tryLock()) {
        try {
            mainLock.lock();
            try {
                int ps = this.getPoolSize();
                int sz = executor.getQueue().size();
                int sz2 = this.getActiveCount();

                if ((sz + sz2) > ps) {
                    ReflectionUtil.setAccessible(addWorkerMethod).invoke(executor, addWorkerArgs);
                }
            } catch (Exception exc) {
                //ignore
            } finally {
                mainLock.unlock();
            }
        } finally {
            addThreadLock.unlock();
        }
    }
}