Exemplo n.º 1
1
  public static void main(String[] args) throws Exception {
    System.setSecurityManager(new SecurityManager());

    // Create an uninitialized class loader
    try {
      new ClassLoader(null) {
        @Override
        protected void finalize() {
          loader = this;
        }
      };
    } catch (SecurityException exc) {
      // Expected
    }
    System.gc();
    System.runFinalization();

    // if 'loader' isn't null, need to ensure that it can't be used as
    // parent
    if (loader != null) {
      try {
        // Create a class loader with 'loader' being the parent
        URLClassLoader child = URLClassLoader.newInstance(new URL[0], loader);
        throw new RuntimeException("Test Failed!");
      } catch (SecurityException se) {
        System.out.println("Test Passed: Exception thrown");
      }
    } else {
      System.out.println("Test Passed: Loader is null");
    }
  }
  public static ClassLoader newClassLoader(final Class... userClasses) throws Exception {

    Set<URL> userClassUrls = new HashSet<>();
    for (Class anyUserClass : userClasses) {
      ProtectionDomain protectionDomain = anyUserClass.getProtectionDomain();
      CodeSource codeSource = protectionDomain.getCodeSource();
      URL classLocation = codeSource.getLocation();
      userClassUrls.add(classLocation);
    }
    StringTokenizer tokenString =
        new StringTokenizer(System.getProperty("java.class.path"), File.pathSeparator);
    String pathIgnore = System.getProperty("java.home");
    if (pathIgnore == null) {
      pathIgnore = userClassUrls.iterator().next().toString();
    }

    List<URL> urls = new ArrayList<>();
    while (tokenString.hasMoreElements()) {
      String value = tokenString.nextToken();
      URL itemLocation = new File(value).toURI().toURL();
      if (!userClassUrls.contains(itemLocation)
          && itemLocation.toString().indexOf(pathIgnore) >= 0) {
        urls.add(itemLocation);
      }
    }
    URL[] urlArray = urls.toArray(new URL[urls.size()]);

    ClassLoader masterClassLoader = URLClassLoader.newInstance(urlArray, null);
    ClassLoader appClassLoader =
        URLClassLoader.newInstance(userClassUrls.toArray(new URL[0]), masterClassLoader);
    return appClassLoader;
  }
Exemplo n.º 3
0
  public NationClassLoader(URL[] urls, Vector nations) {
    super(urls);

    for (int i = 0; i < urls.length; i++) {
      file = urls[i].getFile();
      fileTmp = new File(file);
      System.out.println(
          "NationClassLoader - Does " + fileTmp.toString() + " exists : " + fileTmp.exists());
      name = file.substring(file.lastIndexOf("/") + 1, file.lastIndexOf("."));

      runtimeObject = null;
      try {
        jarLoader = URLClassLoader.newInstance(new URL[] {urls[i]});
        System.out.println(
            "NationClassLoader - JARloader trying : " + jarLoader.getURLs()[0].toString());
        runtimeObject = jarLoader.loadClass(name + "/" + name).newInstance();
      } catch (Exception e) {
        System.err.println("NationClassLoader - Stinking error : " + e);
      }

      if (runtimeObject != null) {
        natFile = (nationFile2) runtimeObject;
        nations.addElement(natFile);
      }
    }
  }
Exemplo n.º 4
0
 private URLClassLoader buildClassLoader() throws PluginException {
   ClassLoader parent = JarPluginProviderLoader.class.getClassLoader();
   try {
     final URL url = getCachedJar().toURI().toURL();
     final URL[] urlarray;
     if (null != getDepLibs() && getDepLibs().size() > 0) {
       final ArrayList<URL> urls = new ArrayList<URL>();
       urls.add(url);
       for (final File extlib : getDepLibs()) {
         urls.add(extlib.toURI().toURL());
       }
       urlarray = urls.toArray(new URL[urls.size()]);
     } else {
       urlarray = new URL[] {url};
     }
     URLClassLoader loaded =
         loadLibsFirst
             ? LocalFirstClassLoader.newInstance(urlarray, parent)
             : URLClassLoader.newInstance(urlarray, parent);
     classLoaders.put(getCachedJar(), loaded);
     return loaded;
   } catch (MalformedURLException e) {
     throw new PluginException("Error creating classloader for " + cachedJar, e);
   }
 }
Exemplo n.º 5
0
  private static JavaCompiler getCompiler() {
    if (JavaLanguage.compiler == null) {
      JavaCompiler compiler = null;

      final String loc = "com.sun.tools.javac.api.JavacTool";

      File file = new File(CONFIG_DATA.get("jdk.location") + "/lib/tools.jar");

      try {
        URL[] urls = {file.toURI().toURL()};

        ClassLoader cl = URLClassLoader.newInstance(urls);

        compiler = Class.forName(loc, false, cl).asSubclass(JavaCompiler.class).newInstance();
      } catch (MalformedURLException e) {
        e.printStackTrace();
      } catch (IllegalAccessException e) {
        e.printStackTrace();
      } catch (InstantiationException e) {
        e.printStackTrace();
      } catch (ClassNotFoundException e) {
        e.printStackTrace();
      }

      JavaLanguage.compiler = compiler;
    }

    return JavaLanguage.compiler;
  }
Exemplo n.º 6
0
 public static boolean isClassInJar(String className, String jarFilePath) {
   ClassLoader prevClassLoader = Thread.currentThread().getContextClassLoader();
   ClassLoader urlClassLoader = null;
   ClassLoader currentClassLoader = null;
   URL url = null;
   URL[] urls = null;
   // Faut d'abord remonter le jar
   File currentJarFile = new File(jarFilePath);
   try {
     // Convert File to a URL
     url = currentJarFile.toURI().toURL(); // file:/c:/myclasses/
   } catch (MalformedURLException e) {
     return false;
   }
   urls = new URL[] {url};
   prevClassLoader = Thread.currentThread().getContextClassLoader();
   // Create the class loader by using the given URL
   // Use prevCl as parent to maintain current visibility
   urlClassLoader = URLClassLoader.newInstance(urls, prevClassLoader);
   // Create a new class loader with the directory
   // ClassLoader classLoader = new URLClassLoader( urls );
   Thread.currentThread().setContextClassLoader(urlClassLoader);
   currentClassLoader = Thread.currentThread().getContextClassLoader();
   if (currentClassLoader != null) {
     try {
       currentClassLoader.loadClass(className);
     } catch (ClassNotFoundException e1) {
       return false;
     }
   } // end if
   return true;
 } // end method isClassInJar
Exemplo n.º 7
0
    private void load(File jarFile) {
      ClassLoader loader;
      try {
        loader =
            URLClassLoader.newInstance(
                new URL[] {jarFile.toURI().toURL()}, getClass().getClassLoader());
      } catch (MalformedURLException e) {
        Application.LOGGER.error(
            "Error while loading plugin file - " + jarFile.getAbsolutePath(), e);
        return;
      }

      InputStream stream = loader.getResourceAsStream(MANIFEST_FILE);
      Properties properties = new Properties();
      try {
        properties.load(stream);
      } catch (IOException e) {
        Application.LOGGER.error(
            "Manifest file - "
                + MANIFEST_FILE
                + " not found in the plugin jar - "
                + jarFile.getAbsolutePath(),
            e);
        return;
      }

      String pluginClassName = properties.getProperty("plugin.class");
      if (!properties.containsKey("plugin.class")) {
        Application.LOGGER.error(
            "plugin.class not defined in the manifest file in the plugin jar - "
                + jarFile.getAbsolutePath());
        return;
      }

      Class<?> clazz;
      try {
        clazz = Class.forName(pluginClassName, true, loader);
      } catch (ClassNotFoundException e) {
        Application.LOGGER.error(
            "Plugin main class - "
                + pluginClassName
                + " defined in manifest not found in the plugin jar - "
                + jarFile.getAbsolutePath(),
            e);
        return;
      }

      if (!Plugin.class.isAssignableFrom(clazz)) {
        Application.LOGGER.error(
            "Plugin class - "
                + clazz
                + " is not a Plugin, in the plugin jar - "
                + jarFile.getAbsolutePath());
      }

      load((Class<? extends Plugin>) clazz, properties);
    }
Exemplo n.º 8
0
  public static Class<?> getProviderClass(
      String fullPathOfProviderPackage, String providerClassName) throws Exception {
    URLClassLoader urlcl =
        URLClassLoader.newInstance(
            new URL[] {new URL("file:////F:/connector/jmsprovider/activemq-all-5.9.1.jar")});

    Class<?> clazz = urlcl.loadClass(providerClassName);
    return clazz;
  }
Exemplo n.º 9
0
  /**
   * Get the view configuration from the given archive file.
   *
   * @param archiveFile the archive file
   * @return the associated view configuration
   */
  public ViewConfig getViewConfigFromArchive(File archiveFile)
      throws MalformedURLException, JAXBException {
    ClassLoader cl = URLClassLoader.newInstance(new URL[] {archiveFile.toURI().toURL()});

    InputStream configStream = cl.getResourceAsStream(VIEW_XML);
    JAXBContext jaxbContext = JAXBContext.newInstance(ViewConfig.class);
    Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();

    return (ViewConfig) jaxbUnmarshaller.unmarshal(configStream);
  }
  public BootstrapSrcDBEventReader(
      DataSource dataSource,
      BootstrapEventBuffer eventBuffer,
      StaticConfig config,
      List<OracleTriggerMonitoredSourceInfo> sources,
      Map<String, Long> lastRows,
      Map<String, String> lastKeys,
      long sinceSCN)
      throws Exception {
    super("BootstrapSrcDBEventReader");
    List<OracleTriggerMonitoredSourceInfo> sourcesTemp =
        new ArrayList<OracleTriggerMonitoredSourceInfo>();
    sourcesTemp.addAll(sources);
    _sources = Collections.unmodifiableList(sourcesTemp);
    _dataSource = dataSource;
    _bootstrapSeedWriter = eventBuffer;
    _keyTxnFilesMap = new HashMap<String, File>();
    _numRowsPerQuery = config.getNumRowsPerQuery();
    _keyTxnBufferSizeMap = config.getKeyTxnBufferSizeMap();

    Map<String, String> keyTxnFiles = config.getKeyTxnFilesMap();

    Iterator<Entry<String, String>> itr = keyTxnFiles.entrySet().iterator();

    while (itr.hasNext()) {
      Entry<String, String> entry = itr.next();
      LOG.info("Adding KeyTxnMapFile Entry :" + entry);
      _keyTxnFilesMap.put(entry.getKey(), new File(entry.getValue()));
    }

    _enableNumRowsQuery = config.isEnableNumRowsQuery();
    _commitInterval = config.getCommitInterval();
    _numRowsPrefetch = config.getNumRowsPrefetch();
    _LOBPrefetchSize = config.getLOBPrefetchSize();
    _numRetries = config.getNumRetries();
    _sinceSCN = sinceSCN;
    _lastRows = new HashMap<String, Long>(lastRows);
    _lastKeys = new HashMap<String, String>(lastKeys);
    _pKeyNameMap = config.getPKeyNameMap();
    _pKeyTypeMap = config.getPKeyTypeMap();
    _pKeyIndexMap = config.getPKeyIndexMap();
    _queryHintMap = config.getQueryHintMap();
    _eventQueryMap = config.getEventQueryMap();
    _beginSrcKeyMap = config.getBeginSrcKeyMap();
    _endSrcKeyMap = config.getEndSrcKeyMap();

    File file = new File("ojdbc6-11.2.0.2.0.jar");
    URL ojdbcJarFile = file.toURL();
    URLClassLoader cl = URLClassLoader.newInstance(new URL[] {ojdbcJarFile});
    _oraclePreparedStatementClass = cl.loadClass("oracle.jdbc.OraclePreparedStatement");
    _setLobPrefetchSizeMethod =
        _oraclePreparedStatementClass.getMethod("setLobPrefetchSize", int.class);

    validate();
  }
Exemplo n.º 11
0
  /**
   * This method returns a new ClassLoader object that can be used to load classes from files
   * contained by the specified directory.
   *
   * @param directory - the path of the directory the ClassLoader should load from
   * @return a ClassLoader that can be used to load classes and resources from files in the
   *     specified directory
   * @throws IOException
   * @throws URISyntaxException
   * @throws IOException
   * @see ClassLoader
   */
  public static ClassLoader createDirectoryLoader(String directory)
      throws URISyntaxException, IOException {
    Collection<URL> urls = new ArrayList<URL>();
    File dir = new File(directory);
    File[] files = dir.listFiles();
    for (File f : files) {
      System.out.println(f.getCanonicalPath());
      urls.add(f.toURI().toURL());
    }

    return URLClassLoader.newInstance(urls.toArray(new URL[urls.size()]));
  }
Exemplo n.º 12
0
  private static Class<?> getClassFromJar(String pathToJar, String pkg, String classToGet)
      throws IOException, ClassNotFoundException, SecurityException, InstantiationException,
          IllegalAccessException, NoSuchMethodException, IllegalArgumentException,
          InvocationTargetException {

    JarFile jarFile = new JarFile(pathToJar);
    Enumeration e = jarFile.entries();

    URL[] urls = {new URL("jar:file:" + pathToJar + "!/")};
    ClassLoader cl = URLClassLoader.newInstance(urls);

    Class<?> c = Class.forName(pkg + "." + classToGet, true, cl);

    return c;
  }
Exemplo n.º 13
0
  public static void runLobby(Risk risk) {

    try {

      if (lobbyURL != null) {

        URLClassLoader ucl =
            URLClassLoader.newInstance(
                new URL[] {new URL("jar:" + lobbyURL + "/LobbyClient.jar!/")});

        Class lobbyclass = ucl.loadClass("org.lobby.client.LobbyClientGUI");

        // TODO: should be like this
        // lobbyclass.newInstance();

        final javax.swing.JPanel panel =
            (javax.swing.JPanel)
                lobbyclass
                    .getConstructor(new Class[] {URL.class})
                    .newInstance(new Object[] {new URL(lobbyURL)});

        javax.swing.JFrame gui = new javax.swing.JFrame("yura.net Lobby");
        gui.setContentPane(panel);
        gui.setSize(800, 600);
        gui.setVisible(true);

        gui.addWindowListener(
            new java.awt.event.WindowAdapter() {
              public void windowClosing(java.awt.event.WindowEvent evt) {
                panel.setVisible(false);
              }
            });
        panel.setVisible(true);

      }
      // else if (lobbyAppletURL!=null) {
      else {

        // on older clients open URL
        RiskUtil.openURL(new URL(lobbyAppletURL));
      }

    } catch (Exception e) {

      risk.showMessageDialog("unable to run the lobby: " + e.toString());
    }
  }
Exemplo n.º 14
0
  public static Object worker(String pathToJar, String className, String methodName) {
    JarFile jarFile = null;
    try {
      jarFile = new JarFile(pathToJar);
    } catch (IOException e) {
      e.printStackTrace();
    }

    if (jarFile != null) {
      Enumeration e = jarFile.entries();
      while (e.hasMoreElements()) {
        try {
          URL[] urls;
          urls = new URL[] {new URL("jar:file:" + pathToJar + "!/")};
          URLClassLoader cl = URLClassLoader.newInstance(urls);
          JarEntry je = (JarEntry) e.nextElement();
          if (je.isDirectory() || !je.getName().endsWith(".class")) {
            continue;
          }
          // -6 because of .class
          String tempClassName = je.getName().substring(0, je.getName().length() - 6);
          tempClassName = tempClassName.replace('/', '.');
          if (className.equals(tempClassName)) {
            Class<?> myClass = cl.loadClass(className);
            Object whatInstance = myClass.newInstance();
            Method myMethod = myClass.getMethod(methodName, new Class[] {});
            return myMethod.invoke(whatInstance);
          }
        } catch (ClassNotFoundException
            | NoSuchMethodException
            | InstantiationException
            | MalformedURLException
            | IllegalAccessException
            | InvocationTargetException e1) {
          System.err.println(e1);
        } finally {
          try {
            jarFile.close();
          } catch (IOException e1) {
            e1.printStackTrace();
          }
        }
      }
    }
    return null;
  }
Exemplo n.º 15
0
 public void loadModuleJar(String moduleType) {
   String jars =
       module_root + File.separator + moduleType + File.separator + "lib" + File.separator;
   List<URL> list = new ArrayList<URL>();
   URL[] urls = new URL[0];
   try {
     File module_lib_dir = new File(jars);
     File[] module_lib_jars = module_lib_dir.listFiles(new JarFileNameFilter());
     for (File jar : module_lib_jars) {
       URL url = toURL(jar);
       list.add(url);
     }
     urls = list.toArray(urls);
   } catch (MalformedURLException e) {
     e.printStackTrace();
   }
   urlClassLoader = URLClassLoader.newInstance(urls, urlClassLoader);
 }
Exemplo n.º 16
0
  /* (non-Javadoc)
   * @see java.util.concurrent.Callable#call()
   */
  @SuppressWarnings("unchecked")
  @Override
  public Void call() throws Exception {
    try {
      File jarFile = new File(queue.getJar());
      URL[] urls = {jarFile.toURI().toURL()};
      ClassLoader loader = URLClassLoader.newInstance(urls);
      Class<Tool> clazz = (Class<Tool>) loader.loadClass(queue.getClazz());

      ToolRunner.run(jobConf, clazz.newInstance(), queue.getArguments());
    } catch (Exception e) {
      queue.setMessage(e.toString());
      QueueUtils.registerQueue(queuePath, queue);
      e.printStackTrace();
      log.error(e);
    }

    return null;
  }
Exemplo n.º 17
0
 /**
  * @param jarFileToAddInClassPath
  * @return
  * @throws MalformedURLException
  */
 public static ClassLoader setGoodClassLoader(String jarFileToAddInClassPath)
     throws MalformedURLException {
   ClassLoader prevClassLoader = Thread.currentThread().getContextClassLoader();
   ClassLoader urlClassLoader = null;
   ClassLoader currentClassLoader = null;
   URL url = null;
   URL[] urls = null;
   // Faut d'abord remonter le jar
   File file = new File(jarFileToAddInClassPath);
   // Convert File to a URL
   url = file.toURI().toURL(); // file:/c:/myclasses/
   urls = new URL[] {url};
   // Create the class loader by using the given URL
   // Use prevCl as parent to maintain current visibility
   urlClassLoader = URLClassLoader.newInstance(urls, prevClassLoader);
   // Create a new class loader with the directory
   // ClassLoader classLoader = new URLClassLoader( urls );
   Thread.currentThread().setContextClassLoader(urlClassLoader);
   currentClassLoader = Thread.currentThread().getContextClassLoader();
   return currentClassLoader;
 } // end method setGoodClassLoader
Exemplo n.º 18
0
  /** Get the class loader representing this resource loader. */
  public synchronized ClassLoader getClassLoader() throws ManifoldCFException {
    if (classLoader == null) {
      // Mint a class loader on demand
      if (currentClasspath.size() == 0) classLoader = parent;
      else {
        URL[] elements = new URL[currentClasspath.size()];

        for (int j = 0; j < currentClasspath.size(); j++) {
          try {
            URL element = ((File) currentClasspath.get(j)).toURI().normalize().toURL();
            elements[j] = element;
          } catch (MalformedURLException e) {
            // Should never happen, but...
            throw new ManifoldCFException(e.getMessage(), e);
          }
        }
        classLoader = URLClassLoader.newInstance(elements, parent);
      }
    }
    return classLoader;
  }
Exemplo n.º 19
0
  @SuppressWarnings("unchecked")
  public void onModule(RepositoriesModule repositoriesModule) {
    String baseLib = detectLibFolder();
    List<URL> cp = getHadoopClassLoaderPath(baseLib);

    ClassLoader hadoopCL =
        URLClassLoader.newInstance(cp.toArray(new URL[cp.size()]), getClass().getClassLoader());

    Class<? extends Repository> repository = null;
    try {
      repository =
          (Class<? extends Repository>)
              hadoopCL.loadClass("org.elasticsearch.repositories.hdfs.HdfsRepository");
    } catch (ClassNotFoundException cnfe) {
      throw new IllegalStateException(
          "Cannot load plugin class; is the plugin class setup correctly?", cnfe);
    }

    repositoriesModule.registerRepository("hdfs", repository, BlobStoreIndexShardRepository.class);
    Loggers.getLogger(HdfsPlugin.class)
        .info("Loaded Hadoop [{}] libraries from {}", getHadoopVersion(hadoopCL), baseLib);
  }
Exemplo n.º 20
0
  public static client getClient() {
    if (client == null) {
      try {
        client =
            (client)
                URLClassLoader.newInstance(
                        new URL[] {NRBot.getLoader().getTransformedClient().toURI().toURL()})
                    .loadClass("client")
                    .newInstance();
      } catch (InstantiationException e) {
        e.printStackTrace();
      } catch (IllegalAccessException e) {
        e.printStackTrace();
      } catch (ClassNotFoundException e) {
        e.printStackTrace();
      } catch (MalformedURLException e) {
        e.printStackTrace();
      }
    }

    return client;
  }
Exemplo n.º 21
0
  private static ClassLoader createClassLoader() {
    try {
      String[] files =
          moduleFolder.list(
              new FilenameFilter() {

                @Override
                public boolean accept(File arg0, String arg1) {
                  return arg1.endsWith(".jar");
                }
              });

      URL[] urls = new URL[files.length];

      for (int i = 0; i < urls.length; i++) {
        urls[i] = new File(moduleFolder, files[i]).toURI().toURL();
      }

      return URLClassLoader.newInstance(urls);
    } catch (MalformedURLException e) {
      e.printStackTrace();
      return null;
    }
  }
  public void loadClass(File[] algorithmName) {

    for (int i = 0; i < algorithmName.length; i++) {

      try {
        URL classURL = new File(algorithmName[i].getPath()).toURI().toURL();
        ClassLoader loader =
            URLClassLoader.newInstance(new URL[] {classURL}, getClass().getClassLoader());
        String className = new String("algorithmsPackage." + algorithmName[i].getName());
        className = className.replaceAll(".jar", "");
        Class<?> calledClass = Class.forName(className, true, loader);
        try {
          addAlgorithm((AlgorithmInterface) calledClass.newInstance());
          logger.info("Loaded Class");
        } catch (InstantiationException | IllegalAccessException e) {
          logger.info("1 " + e.getStackTrace());
        }
      } catch (ClassNotFoundException e) {
        logger.info("Class forname ");
      } catch (MalformedURLException e1) {
        logger.info("URL error ");
      }
    }
  }
Exemplo n.º 23
0
 private void executeClassMethods(File jarFile, String className, String libPath) {
   try {
     //			Set<String> jars = getJarsInDirectory(new File("/home/michael/.minecraft"));
     //			Set<String> jars = getJarsInDirectory(new File("/home/cuckoo/.minecraft"));
     Set<String> jars = getJarsInDirectory(new File(libPath));
     ArrayList<URL> urlList = new ArrayList<URL>();
     for (String jarLocation : jars) {
       urlList.add(new URL("jar:file:" + jarLocation + "!/"));
     }
     URL[] urls =
         new URL
             [urlList.size() + 1]; // = { new URL("jar:file:" + jarFile.getAbsolutePath()+"!/") };
     for (int i = 0; i < urlList.size(); i++) {
       urls[i] = urlList.get(i);
     }
     urls[urlList.size()] = new URL("jar:file:" + jarFile.getAbsolutePath() + "!/");
     URLClassLoader cl = URLClassLoader.newInstance(urls);
     Class c = cl.loadClass(className);
     HashSet<Method> methods = new HashSet<Method>();
     for (Method m : c.getMethods()) {
       methods.add(m);
     }
     for (Method m : c.getDeclaredMethods()) {
       methods.add(m);
     }
     for (Method m : methods) {
       m.setAccessible(true);
       int numParameters = m.getParameterTypes().length;
       if (numParameters == 0) {
         ClassMethodExecutor methodExecutorTask = new ClassMethodExecutor(c, m, className);
         executor.submit(methodExecutorTask);
         //					try {
         //						System.out.println("Attempting to execute method: "+m.getName());
         //						Object obj = c;
         //						if(Modifier.isStatic(m.getModifiers())){
         //							obj = null;
         //						}
         //						m.invoke(obj);
         //					} catch (IllegalAccessException e) {
         //						System.out.println("IllegalAccessException when executing method: "+m.getName()+"
         // in class: "+className);//+"\nError details:\n"+getStackTraceString(e));
         //					} catch (IllegalArgumentException e) {
         //						System.out.println("IllegalArgumentException when executing method:
         // "+m.getName()+" in class: "+className);//+"\nError details:\n"+getStackTraceString(e));
         //					} catch (InvocationTargetException e) {
         //						System.out.println("InvocationTargetException when executing method:
         // "+m.getName()+" in class: "+className);//+"\nError details:\n"+getStackTraceString(e));
         //					} catch (Exception e){
         //						System.out.println(e.getClass().getName()+" when executing method: "+m.getName()+"
         // in class: "+className);//+"\nError details:\n"+getStackTraceString(e));
         //					}
       }
     }
   } catch (MalformedURLException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   } catch (ClassNotFoundException | NoClassDefFoundError e) {
     // TODO Auto-generated catch block
     // e.printStackTrace();
     System.out.println("Could not find class. Error details: " + getStackTraceString(e));
     return;
   }
 }
  public static void main(String[] args) {

    System.err.println("\nRegression test for bug 4404702\n");

    /*
     * HACK: Work around the fact that java.util.logging.LogManager's
     * (singleton) construction also has this bug-- it will register a
     * "shutdown hook", i.e. a thread, which will inherit and pin the
     * current thread's context class loader for the lifetime of the VM--
     * by causing the LogManager to be initialized now, instead of by
     * RMI when our special context class loader is set.
     */
    java.util.logging.LogManager.getLogManager();

    /*
     * HACK: Work around the fact that the non-native, thread-based
     * SecureRandom seed generator (ThreadedSeedGenerator) seems to
     * have this bug too (which had been causing this test to fail
     * when run with jtreg on Windows XP-- see 4910382).
     */
    (new java.security.SecureRandom()).nextInt();

    RuntimeThreadInheritanceLeak obj = new RuntimeThreadInheritanceLeak();

    try {
      ClassLoader loader = URLClassLoader.newInstance(new URL[0]);
      ReferenceQueue refQueue = new ReferenceQueue();
      Reference loaderRef = new WeakReference(loader, refQueue);
      System.err.println("created loader: " + loader);

      Thread.currentThread().setContextClassLoader(loader);
      UnicastRemoteObject.exportObject(obj);
      Thread.currentThread().setContextClassLoader(ClassLoader.getSystemClassLoader());
      System.err.println("exported remote object with loader as context class loader");

      loader = null;
      System.err.println("nulled strong reference to loader");

      UnicastRemoteObject.unexportObject(obj, true);
      System.err.println("unexported remote object");

      /*
       * HACK: Work around the fact that the sun.misc.GC daemon thread
       * also has this bug-- it will have inherited our loader as its
       * context class loader-- by giving it a chance to pass away.
       */
      Thread.sleep(2000);
      System.gc();

      System.err.println("waiting to be notified of loader being weakly reachable...");
      Reference dequeued = refQueue.remove(TIMEOUT);
      if (dequeued == null) {
        System.err.println("TEST FAILED: loader not deteced weakly reachable");
        dumpThreads();
        throw new RuntimeException("TEST FAILED: loader not detected weakly reachable");
      }

      System.err.println("TEST PASSED: loader detected weakly reachable");
      dumpThreads();

    } catch (RuntimeException e) {
      throw e;
    } catch (Exception e) {
      throw new RuntimeException("TEST FAILED: unexpected exception", e);
    } finally {
      try {
        UnicastRemoteObject.unexportObject(obj, true);
      } catch (RemoteException e) {
      }
    }
  }
Exemplo n.º 25
0
  /**
   * A simple test method to determine if a file or directory, represented by a string, can be found
   * by the current Java environment. Uses the same tests as BinaryFile constructor for tracking
   * down a file.
   *
   * @param name A path to a file, a URL, or a path to a jar file entry.
   */
  public static boolean exists(final String name) {
    boolean exists = false;
    try {
      File file = null;
      URL url = null;

      if (!Environment.isApplet()) {
        file = new File(name);
      }

      if (file != null && file.exists()) {
        exists = true;
      } else {
        // url = ClassLoader.getSystemResource(name);
        url = Thread.currentThread().getContextClassLoader().getResource(name);

        // OK, now we want to look around for the file, in the
        // classpaths, and as a resource. It may be a file in
        // a classpath, available for direct access.
        if (url != null) {
          exists = true;
        } else if (Environment.isApplet()) {
          if (Debug.debugging("binaryfile")) {
            Debug.output(" As applet, checking codebase...");
          }
          // Look in the codebase for applets...
          final URL[] cba = new URL[1];
          cba[0] = Environment.getApplet().getCodeBase();

          final URLClassLoader ucl = URLClassLoader.newInstance(cba);
          if (ucl.getResource(name) != null) {
            exists = true;

            // This has been commented out because the
            // AppletDataNugget has been deprecated, and
            // is not needed.

            // } else {
            // url = AppletDataNugget.findResource(name);

            // if (url != null) {
            // exists = true;
            // }
          }
        }

        // It's not in the classpath, so try it as a URL to a
        // webserver.
        if (!exists && name.indexOf("http:") != -1) {

          try {
            final InputStream stream = new URL(name).openStream();
            stream.close();
            exists = true;
          } catch (final java.security.AccessControlException ace) {
            exists = false;
          }
        }
      }

    } catch (final IOException ioe) {
      Debug.message("binaryfile", "BinaryFile.exists() caught IOException");
      exists = false;
    }

    if (Debug.debugging("binaryfile")) {
      Debug.output("BinaryFile.exists(" + name + ") = " + exists);
    }

    return exists;
  }
Exemplo n.º 26
0
  /**
   * Returns a URL that names either a resource, a local file, or an internet URL.
   *
   * @param askingClass the class asking for the URL. Can be null.
   * @param name name of the resource, file or URL.
   * @throws java.net.MalformedURLException
   * @return URL
   */
  public static URL getResourceOrFileOrURL(Class askingClass, String name)
      throws java.net.MalformedURLException {

    boolean DEBUG = Debug.debugging("proputils");

    if (name == null) {
      if (DEBUG) Debug.output("PropUtils.getROFOU(): null file name");
      return null;
    }

    URL retval = null;
    if (DEBUG) Debug.output("PropUtils.getROFOU(): looking for " + name);

    if (askingClass != null) {
      // First see if we have a resource by that name
      if (DEBUG) Debug.output("PropUtils.getROFOU(): checking as resource");

      retval = askingClass.getResource(name);
    }
    if (retval == null) {
      // Check the general classpath...
      if (DEBUG) Debug.output("PropUtils.getROFOU(): checking in general classpath");
      retval = Thread.currentThread().getContextClassLoader().getResource(name);
    }
    if (retval == null && !Environment.isApplet()) {
      // Check the classpath plus the share directory, which may
      // be in the openmap.jar file or in the development
      // environment.
      if (DEBUG) Debug.output("PropUtils.getROFOU(): checking with ClassLoader");
      retval = ClassLoader.getSystemResource("share/" + name);
    }

    if (retval == null && Environment.isApplet()) {
      if (DEBUG) Debug.output("PropUtils.getROFOU(): checking with URLClassLoader");
      URL[] cba = new URL[1];
      cba[0] = Environment.getApplet().getCodeBase();
      URLClassLoader ucl = URLClassLoader.newInstance(cba);
      retval = ucl.getResource(name);
    }

    // If there was no resource by that name available
    if (retval == null) {
      if (DEBUG) Debug.output("PropUtils.getROFOU(): not found as resource");

      try {
        java.io.File file = new java.io.File(name);
        if (file.exists()) {
          retval = file.toURL();
          if (DEBUG) Debug.output("PropUtils.getROFOU(): found as file :)");
        } else {
          // Otherwise treat it as a raw URL.
          if (DEBUG) Debug.output("PropUtils.getROFOU(): Not a file, checking as URL");
          retval = new URL(name);
          java.io.InputStream is = retval.openStream();
          is.close();
          if (DEBUG) Debug.output("PropUtils.getROFOU(): OK as URL :)");
        }
      } catch (java.io.IOException ioe) {
        retval = null;
      } catch (java.security.AccessControlException ace) {
        Debug.error("PropUtils: AccessControlException trying to access " + name);
        retval = null;
      } catch (Exception e) {
        Debug.error("PropUtils: caught exception " + e.getMessage());
        retval = null;
      }
    }

    if (DEBUG) {
      if (retval != null) {
        Debug.output("Resource " + name + "=" + retval.toString());
      } else {
        Debug.output("Resource " + name + " can't be found...");
      }
    }

    return retval;
  }
Exemplo n.º 27
0
  /**
   * Constructs a new BinaryFile with the specified file as the input. The byte-order is undefined.
   * Reads start at the first byte of the file. This constructor looks for the file with the string
   * given, and will call the correct constructor as appropriate. If the string represents a file
   * available locally, then the BinaryFile will be accessed with a FileInputReader using a
   * RandomAccessFile. If it's only available as a resource, then a StreamInputReader will be used.
   * The name should be a path to a file, or the name of a resource that can be found in the
   * classpath, or a URL.
   *
   * @param name the name of the file to be opened for reading
   * @exception IOException pass-through errors from opening the file.
   */
  public BinaryFile(final String name) throws IOException {
    boolean showDebug = false;
    if (Debug.debugging("binaryfile")) {
      showDebug = true;
    }

    if (showDebug) {
      Debug.output("BinaryFile: trying to figure out how to handle " + name);
    }

    try {
      File file = null;
      URL url = null;

      if (!Environment.isApplet()) {
        file = new File(name);
      }

      if (file != null && file.exists()) {
        // If the string represents a file, then we want to
        // use the RandomAccessFile aspect of the BinaryFile.
        setInputReader(new FileInputReader(file));
      } else {
        // url = ClassLoader.getSystemResource(name);
        url = Thread.currentThread().getContextClassLoader().getResource(name);

        // OK, now we want to look around for the file, in the
        // classpaths, and as a resource. It may be a file in
        // a classpath, available for direct access.
        if (url != null) {

          final String newname = url.getFile();
          if (showDebug) {
            Debug.output("BinaryFile: looking for " + newname);
          }

          if (!Environment.isApplet()) {
            file = new File(newname);
          }

          if (file != null && file.exists()) {
            // It's still a file, available directly.
            // Access it with the RandomAccessFile
            setInputReader(new FileInputReader(file));
          } else {
            // Need to get it as a resource. Needs
            // special handling if it's coming in a jar
            // file. Jar file references have a "!" in
            // them
            if (!setJarInputReader(newname)) {
              if (showDebug) {
                Debug.output(" trying as url: " + url);
              }
              setInputReader(new URLInputReader(url));
            }
          }

        } else if (Environment.isApplet()) {
          if (showDebug) {
            Debug.output(" As applet, checking codebase...");
          }
          // Look in the codebase for applets...
          final URL[] cba = new URL[1];
          cba[0] = Environment.getApplet().getCodeBase();

          final URLClassLoader ucl = URLClassLoader.newInstance(cba);
          url = ucl.getResource(name);

          if (url != null) {
            setInputReader(new URLInputReader(url));
          }
        }

        // It's not in the classpath, so try it as a URL.
        if (inputReader == null) {

          if (showDebug) {
            Debug.output(" lastly, trying as URL: " + name);
          }
          try {
            setInputReader(new URLInputReader(new URL(name)));
          } catch (final java.security.AccessControlException ace) {
            Debug.output("BinaryFile: " + name + " couldn't be accessed.");
            throw new IOException("AccessControlException trying to fetch " + name + " as a URL");
          }
        }
      }

      if (inputReader == null) {
        throw new FileNotFoundException("BinaryFile can't find: " + name);
      }

    } catch (final IOException ioe) {
      throw ioe;
    }
  }
Exemplo n.º 28
0
 @Override
 protected void setUp() throws MalformedURLException {
   testLoader =
       URLClassLoader.newInstance(new URL[] {new File("target/classes").toURI().toURL()}, null);
 }