public void recordTimestamp(String className, ClassLoader loader) {
    if (!(loader instanceof ModuleClassLoader)) {
      return;
    }
    Map<String, Long> stamps = null;
    final ModuleClassLoader moduleClassLoader = (ModuleClassLoader) loader;
    final ModuleIdentifier moduleIdentifier = moduleClassLoader.getModule().getIdentifier();
    if (loadersByModuleIdentifier.containsKey(moduleIdentifier)) {
      final ModuleClassLoader oldLoader = loadersByModuleIdentifier.get(moduleIdentifier);
      if (oldLoader != moduleClassLoader) {
        loadersByModuleIdentifier.put(moduleIdentifier, moduleClassLoader);
        timestamps.put(moduleClassLoader, stamps = new ConcurrentHashMap<String, Long>());
      } else {
        stamps = timestamps.get(moduleClassLoader);
      }
    } else {
      loadersByModuleIdentifier.put(moduleIdentifier, moduleClassLoader);
      timestamps.put(moduleClassLoader, stamps = new ConcurrentHashMap<String, Long>());
    }

    final URL file = loader.getResource(className.replace(".", "/") + ".class");
    className = className.replace("/", ".");
    if (file != null) {
      URLConnection connection = null;
      try {
        connection = file.openConnection();
        stamps.put(className, connection.getLastModified());
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
 @Test
 public void testAccessFromCamelComponentModule() throws Exception {
   ModuleLoader moduleLoader = Module.getCallerModuleLoader();
   ModuleIdentifier modid = ModuleIdentifier.create("org.apache.camel.component");
   ModuleClassLoader classLoader = moduleLoader.loadModule(modid).getClassLoader();
   URL resurl = classLoader.getResource("META-INF/cxf/cxf.xml");
   Assert.assertNotNull("URL not null", resurl);
 }
 private List<ResourceLoaderInfo> doGetResourceLoaders(final Module module) {
   final ModuleClassLoader classLoader = module.getClassLoaderPrivate();
   final ResourceLoader[] loaders = classLoader.getResourceLoaders();
   final ArrayList<ResourceLoaderInfo> list = new ArrayList<ResourceLoaderInfo>(loaders.length);
   for (ResourceLoader resourceLoader : loaders) {
     list.add(
         new ResourceLoaderInfo(
             resourceLoader.getClass().getName(),
             new ArrayList<String>(resourceLoader.getPaths())));
   }
   return list;
 }
  /** {@inheritDoc} */
  @Override
  public void deploy(final DeploymentPhaseContext phaseContext)
      throws DeploymentUnitProcessingException {
    final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
    final Module module = deploymentUnit.getAttachment(Attachments.MODULE);
    final ServicesAttachment servicesAttachment =
        deploymentUnit.getAttachment(Attachments.SERVICES);
    if (module != null && servicesAttachment != null) {
      final ModuleClassLoader classLoader = module.getClassLoader();
      final List<String> driverNames =
          servicesAttachment.getServiceImplementations(Driver.class.getName());
      for (String driverClassName : driverNames) {
        try {
          final Class<? extends Driver> driverClass =
              classLoader.loadClass(driverClassName).asSubclass(Driver.class);
          final Constructor<? extends Driver> constructor = driverClass.getConstructor();
          final Driver driver = constructor.newInstance();
          final int majorVersion = driver.getMajorVersion();
          final int minorVersion = driver.getMinorVersion();
          final boolean compliant = driver.jdbcCompliant();
          if (compliant) {
            log.infof(
                "Deploying JDBC-compliant driver %s (version %d.%d)",
                driverClass, Integer.valueOf(majorVersion), Integer.valueOf(minorVersion));
          } else {
            log.infof(
                "Deploying non-JDBC-compliant driver %s (version %d.%d)",
                driverClass, Integer.valueOf(majorVersion), Integer.valueOf(minorVersion));
          }
          String driverName = deploymentUnit.getName();
          InstalledDriver driverMetadata =
              new InstalledDriver(
                  driverName, driverClass.getName(), null, majorVersion, minorVersion, compliant);
          DriverService driverService = new DriverService(driverMetadata, driver);
          phaseContext
              .getServiceTarget()
              .addService(
                  ServiceName.JBOSS.append("jdbc-driver", driverName.replaceAll(".", "_")),
                  driverService)
              .addDependency(
                  ConnectorServices.JDBC_DRIVER_REGISTRY_SERVICE,
                  DriverRegistry.class,
                  driverService.getDriverRegistryServiceInjector())
              .setInitialMode(Mode.ACTIVE)
              .install();

        } catch (Exception e) {
          log.warnf("Unable to instantiate driver class \"%s\": %s", driverClassName, e);
        }
      }
    }
  }
Beispiel #5
0
 static {
   final Enumeration<URL> resources;
   String jarName = "(unknown)";
   String versionString = "(unknown)";
   try {
     final ClassLoader classLoader = Main.class.getClassLoader();
     resources =
         classLoader == null
             ? ModuleClassLoader.getSystemResources("META-INF/MANIFEST.MF")
             : classLoader.getResources("META-INF/MANIFEST.MF");
     while (resources.hasMoreElements()) {
       final URL url = resources.nextElement();
       try {
         final InputStream stream = url.openStream();
         if (stream != null)
           try {
             final Manifest manifest = new Manifest(stream);
             final Attributes mainAttributes = manifest.getMainAttributes();
             if (mainAttributes != null
                 && "JBoss Modules".equals(mainAttributes.getValue("Specification-Title"))) {
               jarName = mainAttributes.getValue("Jar-Name");
               versionString = mainAttributes.getValue("Jar-Version");
             }
           } finally {
             StreamUtil.safeClose(stream);
           }
       } catch (IOException ignored) {
       }
     }
   } catch (IOException ignored) {
   }
   JAR_NAME = jarName;
   VERSION_STRING = versionString;
 }
  @Override
  public Class<?> loadClassLocal(String className, boolean resolve) {

    List<XPackageRequirement> matchingPatterns = findMatchingPatterns(className);
    if (matchingPatterns.isEmpty()) return null;

    String pathName = className.replace('.', '/') + ".class";
    Module module = findModuleDynamically(pathName, matchingPatterns);
    if (module == null) return null;

    ModuleClassLoader moduleClassLoader = module.getClassLoader();
    try {
      return moduleClassLoader.loadClass(className);
    } catch (ClassNotFoundException ex) {
      log.tracef("Cannot load class [%s] from module: %s", className, module);
      return null;
    }
  }
  @Test
  public void testServiceLoaderFails() throws Exception {

    // The {@link ModularURLStreamHandlerFactory} follows a pattern similar to this.
    SystemBundleState systemBundle = getBundleManager().getSystemBundle();
    ModuleManager plugin = getFrameworkState().getModuleManager();
    Module frameworkModule = plugin.loadModule(systemBundle.getModuleIdentifier());
    assertNotNull("Framework module not null", frameworkModule);

    // Test resource access
    ModuleClassLoader classLoader = frameworkModule.getClassLoader();
    URL resource =
        classLoader.getResource("META-INF/services/" + URLStreamHandlerFactory.class.getName());
    assertNull("Resource URL null", resource);

    // Test ServiceLoader access
    Iterator<URLStreamHandlerFactory> iterator =
        frameworkModule.loadService(URLStreamHandlerFactory.class).iterator();
    assertFalse("No more URLStreamHandlerFactory", iterator.hasNext());
  }
  public Set<Class> getUpdatedClasses(
      final String deploymentName, Map<String, Long> updatedClasses) {

    final ModuleIdentifier moduleId = getModuleIdentifier(deploymentName);
    final ModuleClassLoader loader = loadersByModuleIdentifier.get(moduleId);
    if (loader == null) {
      return Collections.emptySet();
    }
    final Map<String, Long> timestamps = this.timestamps.get(loader);

    final Set<Class> ret = new HashSet<Class>();
    for (Map.Entry<String, Long> entry : updatedClasses.entrySet()) {
      if (timestamps.containsKey(entry.getKey())
          && timestamps.get(entry.getKey()) < entry.getValue()) {
        try {
          ret.add(loader.loadClass(entry.getKey()));
          timestamps.put(entry.getKey(), entry.getValue());
        } catch (ClassNotFoundException e) {
          System.err.println("Could not load class " + entry);
        }
      }
    }
    return ret;
  }
    @Override
    public void run() {
      /*
       This resolves a know deadlock that can occur if one thread is in the process of defining a package as part of
       defining a class, and another thread is defining the system package that can result in loading a class.  One holds
       the Package.pkgs lock and one holds the Classloader lock.
      */
      Package.getPackages();

      final Queue<LoadRequest> queue = LoaderThreadHolder.REQUEST_QUEUE;
      for (; ; ) {
        try {
          LoadRequest request;
          synchronized (queue) {
            while ((request = queue.poll()) == null) {
              queue.wait();
            }
          }

          final ModuleClassLoader loader = request.requester;
          Class<?> result = null;
          synchronized (loader) {
            try {
              result = loader.performLoadClass(request.className, request.exportsOnly);
            } finally {
              // no matter what, the requester MUST be notified
              request.result = result;
              request.done = true;
              loader.notifyAll();
            }
          }
        } catch (Throwable t) {
          // ignore
        }
      }
    }
  private static StandaloneServer create(
      ModuleLoader moduleLoader, File jbossHomeDir, String bundlePath, String[] cmdargs) {

    setupBundlePath(bundlePath);
    setupVfsModule(moduleLoader);
    setupLoggingSystem(moduleLoader);

    // Embedded Server wants this, too. Seems redundant, but supply it.
    WildFlySecurityManager.setPropertyPrivileged(
        SYSPROP_KEY_JBOSS_HOME_DIR, jbossHomeDir.getAbsolutePath());

    // Load the Embedded Server Module
    final Module embeddedModule;
    try {
      embeddedModule = moduleLoader.loadModule(ModuleIdentifier.create(MODULE_ID_EMBEDDED));
    } catch (final ModuleLoadException mle) {
      throw EmbeddedLogger.ROOT_LOGGER.moduleLoaderError(mle, MODULE_ID_EMBEDDED, moduleLoader);
    }

    // Load the Embedded Server Factory via the modular environment
    final ModuleClassLoader embeddedModuleCL = embeddedModule.getClassLoader();
    final Class<?> embeddedServerFactoryClass;
    final Class<?> standaloneServerClass;
    try {
      embeddedServerFactoryClass =
          embeddedModuleCL.loadClass(EmbeddedStandAloneServerFactory.class.getName());
      standaloneServerClass = embeddedModuleCL.loadClass(StandaloneServer.class.getName());
    } catch (final ClassNotFoundException cnfe) {
      throw EmbeddedLogger.ROOT_LOGGER.cannotLoadEmbeddedServerFactory(
          cnfe, EmbeddedStandAloneServerFactory.class.getName());
    }

    // Get a handle to the method which will create the server
    final Method createServerMethod;
    try {
      createServerMethod =
          embeddedServerFactoryClass.getMethod(
              "create",
              File.class,
              ModuleLoader.class,
              Properties.class,
              Map.class,
              String[].class);
    } catch (final NoSuchMethodException nsme) {
      throw EmbeddedLogger.ROOT_LOGGER.cannotGetReflectiveMethod(
          nsme, "create", embeddedServerFactoryClass.getName());
    }

    // Create the server
    Object standaloneServerImpl;
    try {
      Properties sysprops = WildFlySecurityManager.getSystemPropertiesPrivileged();
      Map<String, String> sysenv = WildFlySecurityManager.getSystemEnvironmentPrivileged();
      String[] args = cmdargs != null ? cmdargs : new String[0];
      standaloneServerImpl =
          createServerMethod.invoke(null, jbossHomeDir, moduleLoader, sysprops, sysenv, args);
    } catch (final InvocationTargetException ite) {
      throw EmbeddedLogger.ROOT_LOGGER.cannotCreateStandaloneServer(
          ite.getCause(), createServerMethod);
    } catch (final IllegalAccessException iae) {
      throw EmbeddedLogger.ROOT_LOGGER.cannotCreateStandaloneServer(iae, createServerMethod);
    }
    return new StandaloneServerIndirection(standaloneServerClass, standaloneServerImpl);
  }
    @Override
    public Iterable<JavaFileObject> list(
        Location location, String packageName, Set<Kind> kinds, boolean recurse)
        throws IOException {
      if (location == StandardLocation.PLATFORM_CLASS_PATH) {
        return standardJavaFileManager.list(location, packageName, kinds, recurse);
      }
      List<JavaFileObject> ret = new ArrayList<>();
      if (kinds.contains(Kind.CLASS) && location.equals(StandardLocation.CLASS_PATH)) {
        if (classLoader instanceof ModuleClassLoader) {
          ModuleClassLoader mcl = (ModuleClassLoader) classLoader;
          final String packageWithSlashes = packageName.replace(".", "/");
          try {
            Iterator<Resource> resources =
                mcl.getModule()
                    .iterateResources(
                        new PathFilter() {
                          @Override
                          public boolean accept(String path) {
                            if (recurse) {
                              return path.startsWith(packageWithSlashes);
                            } else {
                              return path.equals(packageWithSlashes);
                            }
                          }
                        });
            while (resources.hasNext()) {
              Resource res = resources.next();
              if (!res.getName().endsWith(".class")) {
                continue;
              }
              String binaryName =
                  res.getName().replace("/", ".").substring(0, res.getName().length() - 6);
              try {
                ret.add(
                    new ZipJavaFileObject(
                        org.fakereplace.util.FileReader.readFileBytes(res.openStream()),
                        binaryName,
                        res.getURL().toURI()));
              } catch (URISyntaxException e) {
                e.printStackTrace();
              }
            }
          } catch (ModuleLoadException e) {
            e.printStackTrace();
          }
        } else {
          URL res = classLoader.getResource(packageName.replace(".", "/"));
          if (res != null) {
            if (res.getProtocol().equals("file")) {
              Path dirPath = Paths.get(res.getFile());
              listDir(packageName, dirPath, recurse, ret);
            } else if (res.getProtocol().equals("jar")) {
              JarURLConnection connection = (JarURLConnection) res.openConnection();
              Enumeration<JarEntry> entryEnum = connection.getJarFile().entries();
              while (entryEnum.hasMoreElements()) {
                JarEntry entry = entryEnum.nextElement();
                String name = entry.getName();
                if (name.endsWith(".class") && !entry.isDirectory()) {
                  if (name.startsWith(packageName.replace(".", "/"))) {
                    String rem = name.substring(packageName.length());
                    if (rem.startsWith("/")) {
                      rem = rem.substring(1);
                    }
                    if (!recurse) {
                      if (rem.contains("/")) {
                        continue;
                      }
                    }
                    String binaryName =
                        entry
                            .getName()
                            .replace("/", ".")
                            .substring(0, entry.getName().length() - 6);
                    try {
                      URI uri = new URI(res.toExternalForm() + "/" + rem);
                      ret.add(
                          new ZipJavaFileObject(
                              org.fakereplace.util.FileReader.readFileBytes(
                                  uri.toURL().openStream()),
                              binaryName,
                              uri));
                    } catch (Exception e) {
                      e.printStackTrace();
                    }
                  }
                }
              }
            } else {
              System.err.println(
                  "Could not find package "
                      + packageName
                      + " in "
                      + classLoader
                      + " unknown protocol "
                      + res.getProtocol());
            }
          } else {
            return standardJavaFileManager.list(location, packageName, kinds, recurse);
          }
        }
      } else {
        return standardJavaFileManager.list(location, packageName, kinds, recurse);
      }

      return ret;
    }