/** @param className Interface or abstract class that class to load should extend or implement */ public Class<?> loadAndResolve(String className, byte[] byteCode) throws IllegalArgumentException { // First things first: just to be sure; maybe we have already loaded it? Class<?> old = findLoadedClass(className); if (old != null) { return old; } Class<?> impl; // First: let's try calling it directly on parent, to be able to access protected/package-access // stuff: if (_cfgUseParentLoader) { try { Method method = ClassLoader.class.getDeclaredMethod( "defineClass", new Class[] {String.class, byte[].class, int.class, int.class}); method.setAccessible(true); return (Class<?>) method.invoke(getParent(), className, byteCode, 0, byteCode.length); } catch (Exception e) { } } // but if that doesn't fly, try to do it from our own class loader try { impl = defineClass(className, byteCode, 0, byteCode.length); } catch (LinkageError e) { throw new IllegalArgumentException( "Failed to load class '" + className + "': " + e.getMessage(), e); } // important: must also resolve the class... resolveClass(impl); return impl; }
private void buildIncrementally( final IncrementalBuildResults results, final String... destinationPath) { try { final IncrementalResults incrementalResults = ((InternalKieBuilder) kieBuilder).createFileSet(destinationPath).build(); results.addAllAddedMessages(convertMessages(incrementalResults.getAddedMessages(), handles)); results.addAllRemovedMessages( convertMessages(incrementalResults.getRemovedMessages(), handles)); // Tidy-up removed message handles for (Message message : incrementalResults.getRemovedMessages()) { handles.remove(Handles.RESOURCE_PATH + "/" + getBaseFileName(message.getPath())); } } catch (LinkageError e) { final String msg = MessageFormat.format(ERROR_CLASS_NOT_FOUND, e.getLocalizedMessage()); logger.warn(msg); results.addAddedMessage(makeWarningMessage(msg)); } catch (Throwable e) { final String msg = e.getLocalizedMessage(); logger.error(msg, e); results.addAddedMessage(makeErrorMessage(msg)); } }
private SOAPVersion( String httpBindingId, String nsUri, String contentType, String implicitRole, String roleAttributeName, String saajFactoryString, QName faultCodeMustUnderstand, String faultCodeClientLocalName, String faultCodeServerLocalName, Set<String> requiredRoles) { this.httpBindingId = httpBindingId; this.nsUri = nsUri; this.contentType = contentType; this.implicitRole = implicitRole; this.implicitRoleSet = Collections.singleton(implicitRole); this.roleAttributeName = roleAttributeName; try { saajMessageFactory = MessageFactory.newInstance(saajFactoryString); saajSoapFactory = SOAPFactory.newInstance(saajFactoryString); } catch (SOAPException e) { throw new Error(e); } catch (NoSuchMethodError e) { // SAAJ 1.3 is not in the classpath LinkageError x = new LinkageError("You are loading old SAAJ from " + Which.which(MessageFactory.class)); x.initCause(e); throw x; } this.faultCodeMustUnderstand = faultCodeMustUnderstand; this.requiredRoles = requiredRoles; this.faultCodeClient = new QName(nsUri, faultCodeClientLocalName); this.faultCodeServer = new QName(nsUri, faultCodeServerLocalName); }
static { try { Class clazz = Class.forName("java.lang.UNIXProcess"); DESTROY_PROCESS = clazz.getDeclaredMethod("destroyProcess", new Class[] {int.class}); DESTROY_PROCESS.setAccessible(true); } catch (Exception e) { LinkageError x = new LinkageError("Couldn't get method java.lang.UNIXProcess.destroyProcess(int)"); x.initCause(e); } }
private void diagnoseFailedLoad(Exception cause) { Process proc = process.getProcess(); try { int val = proc.exitValue(); new RuntimeException("Jenkins died loading. Exit code " + val, cause); } catch (IllegalThreadStateException _) { // Process alive } // Try to get stacktrace Class<?> clazz; Field pidField; try { clazz = Class.forName("java.lang.UNIXProcess"); pidField = clazz.getDeclaredField("pid"); pidField.setAccessible(true); } catch (Exception e) { LinkageError x = new LinkageError(); x.initCause(e); throw x; } if (clazz.isAssignableFrom(proc.getClass())) { int pid; try { pid = (int) pidField.get(proc); } catch (IllegalArgumentException | IllegalAccessException e) { throw new AssertionError(e); } try { Process jstack = new ProcessBuilder("jstack", String.valueOf(pid)).start(); if (jstack.waitFor() == 0) { StringWriter writer = new StringWriter(); IOUtils.copy(jstack.getInputStream(), writer); RuntimeException ex = new RuntimeException( cause.getMessage() + "\n\n" + writer.toString() ); ex.setStackTrace(cause.getStackTrace()); throw ex; } } catch (IOException | InterruptedException e) { throw new AssertionError(e); } } throw new Error(cause); }
public boolean browse(URL url) { try { return browseImpl(url); } catch (DesktopException e) { if (logger.isDebugEnabled()) { logger.error("Backend error starting browser", e); } else { logger.error(e.getMessage()); } return false; } catch (LinkageError e) { logger.error("Linkage error starting browser: " + e.getMessage()); return false; } }
private static boolean loadHdf5Lib() { try { Class.forName(H5_CLASS_NAME); return true; } catch (ClassNotFoundException ignored) { // no logging here, H5 class may not be provided by intention return false; } catch (LinkageError e) { // warning here, because H5 class exists, but native libs couldn't be loaded SystemUtils.LOG.warning( MessageFormat.format( "{0}: HDF-5 library not available: {1}: {2}", Hdf5ProductWriterPlugIn.class, e.getClass(), e.getMessage())); return false; } }
/** * Test a doubled class that extends the base class, but is okay since it doesn't override the * base class method. */ static void testExtendOkay(ClassLoader loader) { Class doubledExtendOkayClass; Object obj; /* get the "alternate" version of DoubledExtendOkay */ try { doubledExtendOkayClass = loader.loadClass("DoubledExtendOkay"); } catch (ClassNotFoundException cnfe) { System.err.println("loadClass failed: " + cnfe); return; } /* instantiate */ try { obj = doubledExtendOkayClass.newInstance(); } catch (InstantiationException ie) { System.err.println("newInstance failed: " + ie); return; } catch (IllegalAccessException iae) { System.err.println("newInstance failed: " + iae); return; } catch (LinkageError le) { System.err.println("Got unexpected LinkageError on DEO"); le.printStackTrace(); return; } /* use the base class reference to get a CL-specific instance */ BaseOkay baseRef = (BaseOkay) obj; DoubledExtendOkay de = baseRef.getExtended(); /* try to call through it */ try { String result; result = BaseOkay.doStuff(de); System.out.println("Got DEO result " + result); } catch (LinkageError le) { System.err.println("Got unexpected LinkageError on DEO"); le.printStackTrace(); return; } }
public static IRScope loadScriptFromFile( Ruby runtime, InputStream inStream, File resourcePath, String resourceName, boolean isAbsolute) { String name = getFilenameFromPathAndName(resourcePath, resourceName, isAbsolute); try { Class clazz = loadCompiledScriptFromClass(runtime, inStream); try { Method method = clazz.getMethod("loadIR", Ruby.class, String.class); return (IRScope) method.invoke(null, runtime, name); } catch (Exception e) { if (runtime.getDebug().isTrue()) { e.printStackTrace(); } throw runtime.newLoadError( name + " is not compiled Ruby; use java_import to load normal classes"); } } catch (IOException e) { throw runtime.newIOErrorFromException(e); } catch (LinkageError le) { if (runtime.getDebug().isTrue()) { le.printStackTrace(); } throw runtime.newLoadError( "Linkage error loading compiled script; you may need to recompile '" + name + "': " + le); } finally { try { inStream.close(); } catch (IOException ioe) { throw runtime.newIOErrorFromException(ioe); } } }
PluginManager(Config serverConfig, Iterable<ServerPlugin> plugins, LogProvider logProvider) { Map<String, Pair<ServerPlugin, ServerExtender>> extensions = new HashMap<String, Pair<ServerPlugin, ServerExtender>>(); Log log = logProvider.getLog(getClass()); for (ServerPlugin plugin : plugins) { PluginPointFactory factory = new PluginPointFactoryImpl(); final ServerExtender extender = new ServerExtender(factory); try { plugin.loadServerExtender(extender); } catch (Exception ex) { log.warn("Failed to load plugin [%s]: %s", plugin.toString(), ex.getMessage()); continue; } catch (LinkageError err) { log.warn("Failed to load plugin [%s]: %s", plugin.toString(), err.getMessage()); continue; } Pair<ServerPlugin, ServerExtender> old = extensions.put(plugin.name, Pair.of(plugin, extender)); if (old != null) { log.warn( String.format( "Extension naming conflict \"%s\" between \"%s\" and \"%s\"", plugin.name, old.first().getClass(), plugin.getClass())); } } for (Pair<ServerPlugin, ServerExtender> extension : extensions.values()) { log.info(String.format("Loaded server plugin \"%s\"", extension.first().name)); for (PluginPoint point : extension.other().all()) { log.info( String.format( " %s.%s: %s", point.forType().getSimpleName(), point.name(), point.getDescription())); } this.extensions.put(extension.first().name, extension.other()); } }
/** @tests java.lang.LinkageError#LinkageError(java.lang.String) */ public void test_ConstructorLjava_lang_String() { LinkageError e = new LinkageError("fixture"); assertEquals("fixture", e.getMessage()); assertNull(e.getCause()); }
/** @tests java.lang.LinkageError#LinkageError() */ public void test_Constructor() { LinkageError e = new LinkageError(); assertNull(e.getMessage()); assertNull(e.getLocalizedMessage()); assertNull(e.getCause()); }
@Override protected synchronized Class<?> loadClass(String class_name, boolean resolve) throws ClassNotFoundException { // System.out.println(" load :"+class_name); if (alreadyFailed.contains(class_name)) throw new ClassNotFoundException(class_name); deferTo = getParent(); try { ClassNotFoundException classNotFound = null; loading.push(class_name); try { if (debug) {; // System.out.println(indentation // + "? entered " + // class_name + " " + // resolve); indentation += " "; } Class loaded = previous.get(class_name); if (loaded == null) if (!shouldLoadLocal(class_name)) { try { loaded = getParent().loadClass(class_name); } catch (ClassNotFoundException ex) { classNotFound = ex; if (debug) ; // System.out.println(ANSIColorUtils.red("-- class not found <" // + // class_name // + // ">")); } } if (loaded == null) { loaded = checkHasBeenLoaded(class_name); } if (classNotFound == null) if (loaded == null) { deferTo = getParent(); byte[] bytes = instrumentClass(this, class_name); if (bytes != null) { if (class_name.lastIndexOf(".") != -1) { String packageName = class_name.substring(0, class_name.lastIndexOf(".")); if (!knownPackages.contains(packageName)) { try { definePackage(packageName, null, null, null, null, null, null, null); } catch (IllegalArgumentException e) { // e.printStackTrace(); } knownPackages.add(packageName); } } loaded = reloadingSupport.delegate(class_name, bytes); if (loaded == null) { try { loaded = defineClass(class_name, bytes, 0, bytes.length); } catch (LinkageError le) { le.printStackTrace(); return null; } // ;//System.out.println(" // >> // about // to // resolve // <"+class_name+"> // <"+resolve+">"); if (resolve) resolveClass(loaded); previous.put(class_name, loaded); } else {; // System.out.println(" loaded <" // + // class_name // + // "> in RS classloader"); } } // ;//System.out.println(" // >> // loaded // <"+class_name+">"); } if (classNotFound == null) if (loaded == null) { try { loaded = Class.forName(class_name); // recent change previous.put(class_name, loaded); } catch (ClassNotFoundException ex) { classNotFound = ex; if (debug) {; // System.out.println(ANSIColorUtils.red("-- class not found <" // + // class_name // + // ">")); ex.printStackTrace(); } } } if (debug) { indentation = indentation.substring(1); ; // System.out.println(indentation // + "?" + class_name + // " complete"); // assert // popped.equals(class_name); } if (classNotFound != null) { if (debug) { System.err.println( "exception (" + classNotFound.getClass() + "): while trying to load <" + class_name + " / <" + loading + ">"); new Exception().printStackTrace(); } alreadyFailed.add(class_name); throw classNotFound; } already.put(class_name, loaded); if (loaded.isAnnotationPresent( Notable .class)) {; // System.out.println(" CLASS IS NOTABLE :"+loaded+" "+notifications); for (ClassLoadedNotification n : notifications) { n.notify(loaded); } } return loaded; } finally { String popped = loading.pop(); } } catch (ClassNotFoundException e) { throw e; } catch (Throwable t) { t.printStackTrace(); ; // System.out.println(" unexpected trouble loading <" // + loading + ">"); return null; } }
public BuildResults build() { synchronized (kieFileSystem) { // KieBuilder is not re-usable for successive "full" builds kieBuilder = createKieBuilder(kieFileSystem); // Record RTEs from KieBuilder - that can fail if a rule uses an inaccessible class final BuildResults results = new BuildResults(projectGAV); try { final Results kieResults = kieBuilder.buildAll().getResults(); results.addAllBuildMessages(convertMessages(kieResults.getMessages(), handles)); } catch (LinkageError e) { final String msg = MessageFormat.format(ERROR_CLASS_NOT_FOUND, e.getLocalizedMessage()); logger.warn(msg); results.addBuildMessage(makeWarningMessage(msg)); } catch (Throwable e) { final String msg = e.getLocalizedMessage(); logger.error(msg, e); results.addBuildMessage(makeErrorMessage(msg)); } finally { pomModelCache.setEntry(project, ((KieBuilderImpl) kieBuilder).getPomModel()); } // Add validate messages from external helpers for (Map.Entry<Path, BuildValidationHelper> e : nonKieResourceValidationHelpers.entrySet()) { final org.uberfire.backend.vfs.Path vfsPath = Paths.convert(e.getKey()); final List<ValidationMessage> validationMessages = e.getValue().validate(vfsPath); nonKieResourceValidationHelperMessages.put(e.getKey(), validationMessages); results.addAllBuildMessages(convertValidationMessages(validationMessages)); } // Check external imports are available. These are loaded when a DMO is requested, but it's // better to report them early final org.uberfire.java.nio.file.Path nioExternalImportsPath = projectRoot.resolve("project.imports"); if (Files.exists(nioExternalImportsPath)) { final org.uberfire.backend.vfs.Path externalImportsPath = Paths.convert(nioExternalImportsPath); final ProjectImports projectImports = importsService.load(externalImportsPath); final Imports imports = projectImports.getImports(); for (final Import item : imports.getImports()) { final String fullyQualifiedClassName = item.getType(); try { Class clazz = this.getClass().getClassLoader().loadClass(item.getType()); } catch (ClassNotFoundException cnfe) { logger.warn(cnfe.getMessage()); final String msg = MessageFormat.format(ERROR_CLASS_NOT_FOUND, fullyQualifiedClassName); results.addBuildMessage(makeWarningMessage(msg)); } } } // At the end we are interested to ensure that external .jar files referenced as dependencies // don't have // referential inconsistencies. We will at least provide a basic algorithm to ensure that if // an external class // X references another external class Y, Y is also accessible by the class loader. final KieModuleMetaData kieModuleMetaData = KieModuleMetaData.Factory.newKieModuleMetaData( ((InternalKieBuilder) kieBuilder).getKieModuleIgnoringErrors()); final Set<String> packageNamesWhiteList = packageNameWhiteList.filterPackageNames(project, kieModuleMetaData.getPackages()); // store the project dependencies ClassLoader for optimization purposes. updateDependenciesClassLoader(project, kieModuleMetaData); for (final String packageName : kieModuleMetaData.getPackages()) { if (packageNamesWhiteList.contains(packageName)) { for (final String className : kieModuleMetaData.getClasses(packageName)) { final String fullyQualifiedClassName = packageName + "." + className; try { final Class clazz = kieModuleMetaData.getClass(packageName, className); if (clazz != null) { final TypeSource typeSource = getClassSource(kieModuleMetaData, clazz); if (TypeSource.JAVA_DEPENDENCY == typeSource) { verifyExternalClass(clazz); } } else { final String msg = MessageFormat.format(ERROR_EXTERNAL_CLASS_VERIFICATON, fullyQualifiedClassName); logger.warn(msg); } } catch (Throwable e) { final String msg = MessageFormat.format(ERROR_EXTERNAL_CLASS_VERIFICATON, fullyQualifiedClassName); logger.warn(msg); results.addBuildMessage(makeWarningMessage(msg)); } } } } return results; } }