/** * The TypeReference class is a sun specific class that is found in two different locations * depending on environment. In IBM JDK the class is not available at all. So we have to load it * at runtime. * * @param n * @param cls * @return initiated TypeReference */ private static Object createTypeReference(QName n, Class<?> cls) { Class<?> refClass = null; try { refClass = ClassLoaderUtils.loadClass( "com.sun.xml.bind.api.TypeReference", JAXBContextInitializer.class); } catch (Throwable ex) { try { refClass = ClassLoaderUtils.loadClass( "com.sun.xml.internal.bind.api.TypeReference", JAXBContextInitializer.class); } catch (Throwable ex2) { // ignore } } if (refClass != null) { try { return refClass .getConstructor(QName.class, Type.class, new Annotation[0].getClass()) .newInstance(n, cls, new Annotation[0]); } catch (Throwable e) { // ignore } } return null; }
private static UserOperation getOperationFromElement(Element e) { UserOperation op = new UserOperation(); op.setName(e.getAttribute("name")); op.setVerb(e.getAttribute("verb")); op.setPath(e.getAttribute("path")); op.setOneway(Boolean.parseBoolean(e.getAttribute("oneway"))); op.setConsumes(e.getAttribute("consumes")); op.setProduces(e.getAttribute("produces")); List<Element> paramEls = DOMUtils.findAllElementsByTagNameNS(e, "http://cxf.apache.org/jaxrs", "param"); List<Parameter> params = new ArrayList<Parameter>(paramEls.size()); for (int i = 0; i < paramEls.size(); i++) { Element paramEl = paramEls.get(i); Parameter p = new Parameter(paramEl.getAttribute("type"), i, paramEl.getAttribute("name")); p.setEncoded(Boolean.valueOf(paramEl.getAttribute("encoded"))); p.setDefaultValue(paramEl.getAttribute("defaultValue")); String pClass = paramEl.getAttribute("class"); if (!StringUtils.isEmpty(pClass)) { try { p.setJavaType(ClassLoaderUtils.loadClass(pClass, ResourceUtils.class)); } catch (Exception ex) { throw new RuntimeException(ex); } } params.add(p); } op.setParameters(params); return op; }
private static Class<?> loadClass(String cName) { try { return ClassLoaderUtils.loadClass(cName.trim(), ResourceUtils.class); } catch (ClassNotFoundException ex) { throw new RuntimeException("No class " + cName.trim() + " can be found", ex); } }
public JaxWsWebServicePublisherBeanPostProcessor() throws SecurityException, NoSuchMethodException, ClassNotFoundException { try { servletClass = ClassLoaderUtils.loadClass(CXF_SERVLET_CLASS_NAME, getClass()); } catch (ClassNotFoundException e) { Message message = new Message("SERVLET_CLASS_MISSING", LOG, CXF_SERVLET_CLASS_NAME); LOG.severe(message.toString()); throw e; } servletGetBusMethod = servletClass.getMethod("getBus"); }
static { Class<?> cls = SpringEndpointImpl.class; try { if (ProviderImpl.isJaxWs22()) { cls = ClassLoaderUtils.loadClass( "org.apache.cxf.jaxws22.spring.JAXWS22SpringEndpointImpl", EndpointDefinitionParser.class); } } catch (Throwable t) { cls = SpringEndpointImpl.class; } EP_CLASS = cls; }
static { boolean b = false; try { // JAX-WS 2.2 would have the HttpContext class in the classloader Class<?> cls = ClassLoaderUtils.loadClass("javax.xml.ws.spi.http.HttpContext", ProviderImpl.class); // In addition to that, the Endpoint class we pick up on the classloader // should have a publish method that uses it. Otherwise, we MAY be // be getting the HttpContext from the 2.2 jaxws-api jar, but the Endpoint // class from the 2.1 JRE Method m = Endpoint.class.getMethod("publish", cls); b = m != null; } catch (Throwable ex) { b = false; } JAXWS_22 = b; }
public void initializeRhino() { rhinoContextFactory = new ContextFactory(); if (System.getProperty("cxf.jsdebug") != null && !rhinoDebuggerUp) { try { Class<?> debuggerMain = ClassLoaderUtils.loadClass("org.mozilla.javascript.tools.debugger.Main", getClass()); if (debuggerMain != null) { Method mainMethod = debuggerMain.getMethod( "mainEmbedded", ContextFactory.class, Scriptable.class, String.class); mainMethod.invoke(null, rhinoContextFactory, rhinoScope, "Debug embedded JavaScript."); rhinoDebuggerUp = true; } } catch (Exception e) { LOG.log(Level.WARNING, "Failed to launch Rhino debugger", e); } } rhinoContext = rhinoContextFactory.enterContext(); rhinoScope = rhinoContext.initStandardObjects(); try { ScriptableObject.defineClass(rhinoScope, JsAssert.class); ScriptableObject.defineClass(rhinoScope, Trace.class); ScriptableObject.defineClass(rhinoScope, Notifier.class); ScriptableObject.defineClass(rhinoScope, CountDownNotifier.class); // so that the stock test for IE can gracefully fail. rhinoContext.evaluateString(rhinoScope, "var window = new Object();", "<internal>", 0, null); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InstantiationException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } finally { Context.exit(); } JsSimpleDomNode.register(rhinoScope); JsSimpleDomParser.register(rhinoScope); JsNamedNodeMap.register(rhinoScope); JsXMLHttpRequest.register(rhinoScope); }
protected Templates getTemplatesFromAnnotation(Class<?> cls, Annotation[] anns, MediaType mt) { Templates t = null; XSLTTransform ann = getXsltTransformAnn(anns, mt); if (ann != null) { t = annotationTemplates.get(ann.value()); if (t == null || refreshTemplates) { String path = ann.value(); final String cp = "classpath:"; if (!path.startsWith(cp)) { path = cp + path; } t = createTemplates(path); if (t == null) { createTemplates(ClassLoaderUtils.getResource(ann.value(), cls)); } if (t != null) { annotationTemplates.put(ann.value(), t); } } } return t; }
/** * Finds the base file URI that 'contains' the given URI. If the URI can not be resolved to a file * URI then the original URI is returned. This method currently attempts to resolve only * "classpath" and "jar" URIs. * * @param uri the URI to resolve * @return uri a file URI if the original URI is contained in a file, otherwise the original URI */ protected URI getBaseFileURI(URI uri) { if ("classpath".equals(uri.getScheme())) { URL resource = ClassLoaderUtils.getResource(uri.toString().substring(10), getClass()); if (resource != null) { try { return getBaseFileURI(resource.toURI()); } catch (URISyntaxException e) { // ignore } } } else if ("jar".equals(uri.getScheme())) { String jarUrl = uri.toString(); int embeddedUrlEndIndex = jarUrl.lastIndexOf("!/"); if (embeddedUrlEndIndex != -1) { String embeddedUrl = jarUrl.substring(4, embeddedUrlEndIndex); try { return getBaseFileURI(new URI(embeddedUrl)); } catch (URISyntaxException e) { // ignore } } } return uri; }
public static URL getClasspathResourceURL(String path, Class<?> callingClass, Bus bus) { URL url = ClassLoaderUtils.getResource(path, callingClass); return url == null ? getResource(path, URL.class, bus) : url; }
public static InputStream getClasspathResourceStream( String path, Class<?> callingClass, Bus bus) { InputStream is = ClassLoaderUtils.getResourceAsStream(path, callingClass); return is == null ? getResource(path, InputStream.class, bus) : is; }
public synchronized ServerImpl getServer(String addr) { if (server == null) { checkProperties(); ClassLoaderHolder loader = null; try { if (bus != null) { ClassLoader newLoader = bus.getExtension(ClassLoader.class); if (newLoader != null) { loader = ClassLoaderUtils.setThreadContextClassloader(newLoader); } } // Initialize the endpointName so we can do configureObject QName origEpn = endpointName; if (endpointName == null) { JaxWsImplementorInfo implInfo = new JaxWsImplementorInfo(getImplementorClass()); endpointName = implInfo.getEndpointName(); } if (serviceFactory != null) { serverFactory.setServiceFactory(serviceFactory); } /*if (serviceName != null) { serverFactory.getServiceFactory().setServiceName(serviceName); }*/ configureObject(this); endpointName = origEpn; // Set up the server factory serverFactory.setAddress(addr); serverFactory.setStart(false); serverFactory.setEndpointName(endpointName); serverFactory.setServiceBean(implementor); serverFactory.setBus(bus); serverFactory.setFeatures(getFeatures()); serverFactory.setInvoker(invoker); serverFactory.setSchemaLocations(schemaLocations); if (serverFactory.getProperties() != null) { serverFactory.getProperties().putAll(properties); } else { serverFactory.setProperties(properties); } // Be careful not to override any serverfactory settings as a user might // have supplied their own. if (getWsdlLocation() != null) { serverFactory.setWsdlURL(getWsdlLocation()); } if (bindingUri != null) { serverFactory.setBindingId(bindingUri); } if (serviceName != null) { serverFactory.getServiceFactory().setServiceName(serviceName); } if (implementorClass != null) { serverFactory.setServiceClass(implementorClass); } if (executor != null) { serverFactory.getServiceFactory().setExecutor(executor); } if (handlers.size() > 0) { serverFactory.addHandlers(handlers); } configureObject(serverFactory); server = serverFactory.create(); org.apache.cxf.endpoint.Endpoint endpoint = getEndpoint(); if (in != null) { endpoint.getInInterceptors().addAll(in); } if (out != null) { endpoint.getOutInterceptors().addAll(out); } if (inFault != null) { endpoint.getInFaultInterceptors().addAll(inFault); } if (outFault != null) { endpoint.getOutFaultInterceptors().addAll(outFault); } if (properties != null) { endpoint.putAll(properties); } configureObject(endpoint.getService()); configureObject(endpoint); this.service = endpoint.getService(); if (getWsdlLocation() == null) { // hold onto the wsdl location so cache won't clear till we go away setWsdlLocation(serverFactory.getWsdlURL()); } if (serviceName == null) { setServiceName(serverFactory.getServiceFactory().getServiceQName()); } if (endpointName == null) { endpointName = endpoint.getEndpointInfo().getName(); } } finally { if (loader != null) { loader.reset(); } } } return (ServerImpl) server; }
/** * 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().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(); } } }
public static void doHacks() { if (skipHack("org.apache.cxf.JDKBugHacks.all")) { return; } try { // Use the system classloader as the victim for all this // ClassLoader pinning we're about to do. ClassLoaderHolder orig = ClassLoaderUtils.setThreadContextClassloader(ClassLoader.getSystemClassLoader()); try { try { // Trigger a call to sun.awt.AppContext.getAppContext() if (!skipHack("org.apache.cxf.JDKBugHacks.imageIO")) { ImageIO.getCacheDirectory(); } } catch (Throwable t) { // ignore } try { // DocumentBuilderFactory seems to SOMETIMES pin the classloader if (!skipHack("org.apache.cxf.JDKBugHacks.documentBuilderFactory")) { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.newDocumentBuilder(); } } catch (Throwable e) { // ignore } // Several components end up calling: // sun.misc.GC.requestLatency(long) // // Those libraries / components known to trigger memory leaks due to // eventual calls to requestLatency(long) are: // - javax.management.remote.rmi.RMIConnectorServer.start() try { if (!skipHack("org.apache.cxf.JDKBugHacks.gcRequestLatency")) { Class<?> clazz = Class.forName("sun.misc.GC"); Method method = clazz.getDeclaredMethod("currentLatencyTarget"); Long l = (Long) method.invoke(null); if (l != null && l.longValue() == 0) { // something already set it, move on method = clazz.getDeclaredMethod("requestLatency", new Class[] {Long.TYPE}); method.invoke(null, Long.valueOf(36000000)); } } } catch (Throwable e) { // ignore } // Calling getPolicy retains a static reference to the context // class loader. try { // Policy.getPolicy(); if (!skipHack("org.apache.cxf.JDKBugHacks.policy")) { Class<?> policyClass = Class.forName("javax.security.auth.Policy"); Method method = policyClass.getMethod("getPolicy"); method.invoke(null); } } catch (Throwable e) { // ignore } try { // Initializing javax.security.auth.login.Configuration retains a static reference // to the context class loader. if (!skipHack("org.apache.cxf.JDKBugHacks.authConfiguration")) { Class.forName( "javax.security.auth.login.Configuration", true, ClassLoader.getSystemClassLoader()); } } catch (Throwable e) { // Ignore } // Creating a MessageDigest during web application startup // initializes the Java Cryptography Architecture. Under certain // conditions this starts a Token poller thread with TCCL equal // to the web application class loader. if (!skipHack("org.apache.cxf.JDKBugHacks.securityProviders")) { java.security.Security.getProviders(); } try { // Several components end up opening JarURLConnections without first // disabling caching. This effectively locks the file. // JAXB does this and thus affects us pretty badly. // Doesn't matter that this JAR doesn't exist - just as long as // the URL is well-formed if (!skipHack("org.apache.cxf.JDKBugHacks.defaultUsesCaches")) { URL url = new URL("jar:file://dummy.jar!/"); URLConnection uConn = new URLConnection(url) { @Override public void connect() throws IOException { // NOOP } }; uConn.setDefaultUseCaches(false); } } catch (Throwable e) { // ignore } } finally { if (orig != null) { orig.reset(); } } } catch (Throwable t) { // ignore } }
private Object doChainedInvocation( URI uri, MultivaluedMap<String, String> headers, OperationResourceInfo ori, Object body, int bodyIndex, Exchange exchange, Map<String, Object> invocationContext) throws Throwable { 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.getHttpMethod(), 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)); if (body != null) { outMessage.put("BODY_INDEX", bodyIndex); } outMessage.getInterceptorChain().add(bodyWriter); Map<String, Object> reqContext = getRequestContext(outMessage); reqContext.put(OperationResourceInfo.class.getName(), ori); reqContext.put("BODY_INDEX", bodyIndex); // execute chain 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); } } }