Example #1
0
  public String readFileFromJAR(String filepath) {

    String out = "";

    try {

      // setup input buffer
      ClassLoader cl = this.getClass().getClassLoader();
      InputStream instream = cl.getResourceAsStream(filepath);
      BufferedReader filereader = new BufferedReader(new InputStreamReader(instream));

      // read lines
      String line = filereader.readLine();
      while (line != null) {
        out += "\n" + line;
        line = filereader.readLine();
      }

      filereader.close();

    } catch (Exception e) {
      // e.printStackTrace();
    }

    return out;
  }
Example #2
0
  public About() {
    cl = ClassLoader.getSystemClassLoader();

    // ----------------------------------------CENTER--------------------------------//
    imgAbout = new ImageIcon(cl.getResource("om.png"));

    lblAbout = new JLabel(imgAbout);

    lblAbout.setBounds(0, 0, 450, 263);

    JPanel pnlCenter = new JPanel();
    pnlCenter.setLayout(null);
    pnlCenter.add(lblAbout);

    btnOk = new JButton(new ImageIcon(cl.getResource("ok.png")));
    btnOk.setBounds(390, 215, 40, 30);
    pnlCenter.add(btnOk);
    btnOk.addActionListener(this);

    // -----------------------------------CONTAINER----------------------------------//
    Container c = getContentPane();
    c.setLayout(new BorderLayout());
    c.add(pnlCenter, BorderLayout.CENTER);
    setSize(450, 280);
    setVisible(true);
    setResizable(false);
    setLocation(580, 280);
    // setDefaultCloseOperation(EXIT_ON_CLOSE);

  }
  /**
   * Returns an input stream to the resource.
   *
   * @param resource The path leading to the resource. Can be an URL, a path leading to a class
   *     resource or a {@link File}.
   * @return InputStream instance.
   * @throws IOException If the resource could not be found or opened.
   */
  public static InputStream openInputStream(String resource) throws IOException {
    try {
      // See if the resource is an URL first.
      final URL url = new URL(resource);
      // success, load the resource.
      return url.openStream();
    } catch (MalformedURLException e) {
      // No luck. Fallback to class loader paths.
    }

    // Try current thread's class loader first.
    final ClassLoader ldr = Thread.currentThread().getContextClassLoader();

    InputStream is;
    if (ldr != null && (is = ldr.getResourceAsStream(resource)) != null) {
      return is;
    } else if ((is = ResourceUtils.class.getResourceAsStream(resource)) != null) {
      return is;
    } else if ((is = ClassLoader.getSystemResourceAsStream(resource)) != null) {
      return is;
    }

    // Try file path
    final File f = new File(resource);
    if (f.exists() && f.isFile() && f.canRead()) {
      return new FileInputStream(f);
    }

    throw new IOException("Could not locate resource: " + resource);
  }
Example #4
0
 static {
   Attributes m = null;
   final URL loc = Prop.LOCATION;
   if (loc != null) {
     final String jar = loc.getFile();
     try {
       final ClassLoader cl = JarManifest.class.getClassLoader();
       final Enumeration<URL> list = cl.getResources("META-INF/MANIFEST.MF");
       while (list.hasMoreElements()) {
         final URL url = list.nextElement();
         if (!url.getFile().contains(jar)) continue;
         final InputStream in = url.openStream();
         try {
           m = new Manifest(in).getMainAttributes();
           break;
         } finally {
           in.close();
         }
       }
     } catch (final IOException ex) {
       Util.errln(ex);
     }
   }
   MAP = m;
 }
 private ClassLoader getRootLoader() {
   ClassLoader ret;
   for (ret = this.getClass().getClassLoader();
       ret != null && ret.getParent() != null;
       ret = ret.getParent()) {}
   return ret;
 }
 public static void main(String[] args) throws Exception {
   ClassLoader parent = ExcludingClassLoader.class.getClassLoader();
   String excName = ExcludingClassLoader.class.getName();
   Collection4 excluded = new Collection4();
   ClassLoader incLoader = new ExcludingClassLoader(parent, excluded);
   System.out.println(incLoader.loadClass(excName));
   excluded.add(excName);
   try {
     System.out.println(incLoader.loadClass(excName));
   } catch (ClassNotFoundException exc) {
     System.out.println("Ok, not found.");
   }
 }
Example #7
0
  public static void main(String[] args) throws Exception {
    Class thisClass = MethodResultTest.class;
    Class exoticClass = Exotic.class;
    String exoticClassName = Exotic.class.getName();
    ClassLoader testClassLoader = thisClass.getClassLoader();
    if (!(testClassLoader instanceof URLClassLoader)) {
      System.out.println("TEST INVALID: Not loaded by a " + "URLClassLoader: " + testClassLoader);
      System.exit(1);
    }

    URLClassLoader tcl = (URLClassLoader) testClassLoader;
    URL[] urls = tcl.getURLs();
    ClassLoader shadowLoader =
        new ShadowLoader(
            urls,
            testClassLoader,
            new String[] {
              exoticClassName, ExoticMBeanInfo.class.getName(), ExoticException.class.getName()
            });
    Class cl = shadowLoader.loadClass(exoticClassName);
    if (cl == exoticClass) {
      System.out.println(
          "TEST INVALID: Shadow class loader loaded " + "same class as test class loader");
      System.exit(1);
    }
    Thread.currentThread().setContextClassLoader(shadowLoader);

    ObjectName on = new ObjectName("a:b=c");
    MBeanServer mbs = MBeanServerFactory.newMBeanServer();
    mbs.createMBean(Thing.class.getName(), on);

    final String[] protos = {"rmi", "iiop", "jmxmp"};

    boolean ok = true;
    for (int i = 0; i < protos.length; i++) {
      try {
        ok &= test(protos[i], mbs, on);
        System.out.println();
      } catch (Exception e) {
        System.out.println("TEST FAILED WITH EXCEPTION:");
        e.printStackTrace(System.out);
        ok = false;
      }
    }

    if (ok) System.out.println("Test passed");
    else {
      System.out.println("TEST FAILED");
      System.exit(1);
    }
  }
 private void installAuthKit() {
   boolean usingJWS = false;
   final ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader();
   if (originalClassLoader.toString().toLowerCase().indexOf("jnlp") != -1) usingJWS = true;
   if (usingJWS) return;
   try {
     File tempFile = new File(jarFolder, "libAuthKit.jnilib");
     tempFile.deleteOnExit();
     InstallUtil.copyResourceToFile(
         "/gnu/io/installer/resources/macosx/lib/libAuthKit.jnilib", tempFile);
   } catch (Throwable t) {
     System.out.println("installAuthKit Throwable " + t);
   }
 }
  private void initDriverList() {
    try {
      Thread thread = Thread.currentThread();
      ClassLoader loader = thread.getContextClassLoader();

      Enumeration iter = loader.getResources("META-INF/services/java.sql.Driver");
      while (iter.hasMoreElements()) {
        URL url = (URL) iter.nextElement();

        ReadStream is = null;
        try {
          is = Vfs.lookup(url.toString()).openRead();

          String filename;

          while ((filename = is.readLine()) != null) {
            int p = filename.indexOf('#');

            if (p >= 0) filename = filename.substring(0, p);

            filename = filename.trim();
            if (filename.length() == 0) continue;

            try {
              Class cl = Class.forName(filename, false, loader);
              Driver driver = null;

              if (Driver.class.isAssignableFrom(cl)) driver = (Driver) cl.newInstance();

              if (driver != null) {
                log.fine(L.l("DatabaseManager adding driver '{0}'", driver.getClass().getName()));

                _driverList.add(driver);
              }
            } catch (Exception e) {
              log.log(Level.FINE, e.toString(), e);
            }
          }
        } catch (Exception e) {
          log.log(Level.FINE, e.toString(), e);
        } finally {
          if (is != null) is.close();
        }
      }
    } catch (Exception e) {
      log.log(Level.FINE, e.toString(), e);
    }
  }
Example #10
0
 /**
  * Get the current thread's context class loader which is set to the CommonClassLoader by
  * ApplicationServer
  *
  * @return the thread's context classloader if it exists; else the system class loader.
  */
 public static ClassLoader getClassLoader() {
   if (Thread.currentThread().getContextClassLoader() != null) {
     return Thread.currentThread().getContextClassLoader();
   } else {
     return ClassLoader.getSystemClassLoader();
   }
 }
Example #11
0
  public static ClassLoader extendClassLoader(ClassLoader root, ClassLoader classLoader, URL url) {
    // URL classloader doesn't seem to delegate to parent classloader properly
    // so if you get a chain of them then it fails to find things. Here we
    // make sure that all of our added URLs end up within a single URLClassloader
    // with its parent being the one that loaded this class itself

    if (classLoader instanceof URLClassLoader) {

      URL[] old = ((URLClassLoader) classLoader).getURLs();

      URL[] new_urls = new URL[old.length + 1];

      System.arraycopy(old, 0, new_urls, 1, old.length);

      new_urls[0] = url;

      classLoader =
          new URLClassLoader(new_urls, classLoader == root ? classLoader : classLoader.getParent());
    } else {

      classLoader = new URLClassLoader(new URL[] {url}, classLoader);
    }

    return (classLoader);
  }
Example #12
0
 private static synchronized String getJavascript() {
   if (jstext == null) {
     InputStream istr = null;
     try {
       ClassLoader loader = Thread.currentThread().getContextClassLoader();
       istr = loader.getResourceAsStream(JAVASCRIPT_RESOURCE);
       jstext = StringUtil.fromInputStream(istr);
       istr.close();
     } catch (Exception e) {
       log.error("Can't load javascript", e);
     } finally {
       IOUtil.safeClose(istr);
     }
   }
   return jstext;
 }
Example #13
0
 /**
  * Loads a resource from the classloader (e.g. the .jar file) into a byte array.
  *
  * @param cl Classloader resource comes from
  * @param sPath Path of resource (must begin with /)
  * @return Byte array containing file in memory
  * @throws IOException If it doesn't exist or there is any other error loading
  */
 public static byte[] loadResource(ClassLoader cl, String sPath) throws IOException {
   if (!sPath.startsWith("/"))
     throw new FileNotFoundException("Resource must be absolute path: " + sPath);
   sPath = sPath.substring(1);
   URL u = cl.getResource(sPath);
   if (u == null) throw new FileNotFoundException("Resource not found: " + sPath);
   URLConnection uc = u.openConnection();
   uc.connect();
   int iLength = uc.getContentLength();
   if (iLength > -1) // Sometimes getContentLength returns -1, sometimes it doesn't
   {
     byte[] abContent = new byte[iLength];
     InputStream is = uc.getInputStream();
     int iStart = 0;
     while (true) {
       int iRead = is.read(abContent, iStart, abContent.length - iStart);
       if (iRead == 0) throw new IOException("Resource length mismatch");
       iStart += iRead;
       if (iStart == abContent.length) break;
     }
     is.close();
     return abContent;
   } else {
     ByteArrayOutputStream baos = new ByteArrayOutputStream();
     copy(uc.getInputStream(), baos, false);
     return baos.toByteArray();
   }
 }
  static Collection<URL> getClassLoaderUrls() {
    final ClassLoader classLoader = PluginManagerCore.class.getClassLoader();
    final Class<? extends ClassLoader> aClass = classLoader.getClass();
    try {
      @SuppressWarnings("unchecked")
      List<URL> urls = (List<URL>) aClass.getMethod("getUrls").invoke(classLoader);
      return urls;
    } catch (IllegalAccessException ignored) {
    } catch (InvocationTargetException ignored) {
    } catch (NoSuchMethodException ignored) {
    }

    if (classLoader instanceof URLClassLoader) {
      return Arrays.asList(((URLClassLoader) classLoader).getURLs());
    }

    return Collections.emptyList();
  }
  @SuppressWarnings({"HardCodedStringLiteral"})
  static Method getAddUrlMethod(final ClassLoader loader) throws NoSuchMethodException {
    if (loader instanceof URLClassLoader) {
      final Method addUrlMethod = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
      addUrlMethod.setAccessible(true);
      return addUrlMethod;
    }

    return loader.getClass().getDeclaredMethod("addURL", URL.class);
  }
  /** {@inheritDoc} */
  @Override
  public URL getResource(String name) {
    URL url = findResource(name);

    if (url == null) url = ClassLoader.getSystemResource(name);

    if (url == null) url = super.getResource(name);

    return url;
  }
    public SidebarOption(String labelTxt, String rsc) {
      label = new JLabel(labelTxt);
      label.setForeground(Color.WHITE);
      label.setFont(font);
      add(label);
      setOpaque(false);
      setMaximumSize(new Dimension(1000, label.getPreferredSize().height + 5));

      this.rsc = ClassLoader.getSystemClassLoader().getResource(rsc);
    }
 @SuppressWarnings("unchecked")
 public void addDefaultValue(String className, JSONObject oper) throws Exception {
   ObjectMapper defaultValueMapper = ObjectMapperFactory.getOperatorValueSerializer();
   Class<? extends Operator> clazz = (Class<? extends Operator>) classLoader.loadClass(className);
   if (clazz != null) {
     Operator operIns = clazz.newInstance();
     String s = defaultValueMapper.writeValueAsString(operIns);
     oper.put("defaultValue", new JSONObject(s).get(className));
   }
 }
  /** {@inheritDoc} */
  @Override
  public InputStream getResourceAsStream(String name) {
    // Find resource in GAR file first.
    InputStream in = getResourceAsStreamGarOnly(name);

    // Find resource in parent class loader.
    if (in == null) in = ClassLoader.getSystemResourceAsStream(name);

    if (in == null) in = super.getResourceAsStream(name);

    return in;
  }
 public OperatorDiscoverer(String[] jars) {
   URL[] urls = new URL[jars.length];
   for (int i = 0; i < jars.length; i++) {
     pathsToScan.add(jars[i]);
     try {
       urls[i] = new URL("file://" + jars[i]);
     } catch (MalformedURLException ex) {
       throw new RuntimeException(ex);
     }
   }
   classLoader = new URLClassLoader(urls, ClassLoader.getSystemClassLoader());
 }
Example #21
0
  /** 获取类的class文件位置的URL。这个方法是本类最基础的方法,供其它方法调用。 */
  public URL getClassLocationURL(final Class cls) {
    if (cls == null) {
      throw new IllegalArgumentException("class that input is null");
    }
    URL result = null;
    final String clsAsResource = cls.getName().replace('.', '/').concat(".class");
    final ProtectionDomain pd = cls.getProtectionDomain();
    if (pd != null) {
      final CodeSource cs = pd.getCodeSource();
      if (cs != null) {
        result = cs.getLocation();
      }
      if (result != null) {
        if ("file".equals(result.getProtocol())) {
          try {
            if (result.toExternalForm().endsWith(".jar")
                || result.toExternalForm().endsWith(".zip")) {
              result =
                  new URL(
                      "jar:".concat(result.toExternalForm()).concat("!/").concat(clsAsResource));
            } else if (new File(result.getFile()).isDirectory()) {
              result = new URL(result, clsAsResource);
            }
          } catch (MalformedURLException ignore) {
          }
        }
      }
    }

    if (result == null) {
      final ClassLoader clsLoader = cls.getClassLoader();
      result =
          clsLoader != null
              ? clsLoader.getResource(clsAsResource)
              : ClassLoader.getSystemResource(clsAsResource);
    }
    return result;
  }
    Sidebar() {
      super(BoxLayout.Y_AXIS);

      try {
        back =
            ImageIO.read(
                ClassLoader.getSystemClassLoader()
                    .getResource("org/madeirahs/editor/ui/help_sidebar.png"));
        scaleImage();
        setPreferredSize(new Dimension(back.getWidth(), back.getHeight()));
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
Example #23
0
 public static Properties getPropertiesFromFile(String file) throws IOException {
   InputStream is = ClassLoader.getSystemResourceAsStream(file);
   if (is != null) {
     Properties config = new Properties();
     config.load(is);
     return config;
   } else {
     String remoteclient = "/" + file;
     InputStream is2 = Utility.class.getResourceAsStream(remoteclient);
     Properties config = new Properties();
     config.load(is2);
     return config;
   }
 }
  @SuppressWarnings("unchecked")
  public Class<? extends Operator> getOperatorClass(String className)
      throws ClassNotFoundException {
    if (CollectionUtils.isEmpty(operatorClassNames)) {
      loadOperatorClass();
    }

    Class<?> clazz = classLoader.loadClass(className);

    if (!Operator.class.isAssignableFrom(clazz)) {
      throw new IllegalArgumentException("Argument must be a subclass of Operator class");
    }
    return (Class<? extends Operator>) clazz;
  }
Example #25
0
  /**
   * Enumerates the resouces in a give package name. This works even if the resources are loaded
   * from a jar file!
   *
   * <p>Adapted from code by mikewse on the java.sun.com message boards.
   * http://forum.java.sun.com/thread.jsp?forum=22&thread=30984
   *
   * @param packageName The package to enumerate
   * @return A Set of Strings for each resouce in the package.
   */
  public static Set getResoucesInPackage(String packageName) throws IOException {
    String localPackageName;
    if (packageName.endsWith("/")) {
      localPackageName = packageName;
    } else {
      localPackageName = packageName + '/';
    }

    Enumeration dirEnum = ClassLoader.getSystemResources(localPackageName);

    Set names = new HashSet();

    // Loop CLASSPATH directories
    while (dirEnum.hasMoreElements()) {
      URL resUrl = (URL) dirEnum.nextElement();

      // Pointing to filesystem directory
      if (resUrl.getProtocol().equals("file")) {
        File dir = new File(resUrl.getFile());
        File[] files = dir.listFiles();
        if (files != null) {
          for (int i = 0; i < files.length; i++) {
            File file = files[i];
            if (file.isDirectory()) continue;
            names.add(localPackageName + file.getName());
          }
        }

        // Pointing to Jar file
      } else if (resUrl.getProtocol().equals("jar")) {
        JarURLConnection jconn = (JarURLConnection) resUrl.openConnection();
        JarFile jfile = jconn.getJarFile();
        Enumeration entryEnum = jfile.entries();
        while (entryEnum.hasMoreElements()) {
          JarEntry entry = (JarEntry) entryEnum.nextElement();
          String entryName = entry.getName();
          // Exclude our own directory
          if (entryName.equals(localPackageName)) continue;
          String parentDirName = entryName.substring(0, entryName.lastIndexOf('/') + 1);
          if (!parentDirName.equals(localPackageName)) continue;
          names.add(entryName);
        }
      } else {
        // Invalid classpath entry
      }
    }

    return names;
  }
Example #26
0
 private static boolean loadProviderFromProperty() {
   String cn = System.getProperty("com.sun.net.httpserver.HttpServerProvider");
   if (cn == null) return false;
   try {
     @SuppressWarnings("deprecation")
     Object o = Class.forName(cn, true, ClassLoader.getSystemClassLoader()).newInstance();
     provider = (HttpServerProvider) o;
     return true;
   } catch (ClassNotFoundException
       | IllegalAccessException
       | InstantiationException
       | SecurityException x) {
     throw new ServiceConfigurationError(null, x);
   }
 }
Example #27
0
 private boolean testExecutionMode() {
   executionMode = false;
   JarFile file = null;
   try {
     file = new JarFile(getTangaraPath());
     ZipEntry entry = file.getEntry(EXECUTION_PROPERTIES_FILENAME);
     if (entry != null) {
       executionMode = true;
       System.out.println("execution mode detected");
       Properties executionProperties = new Properties();
       InputStream ips = ClassLoader.getSystemResourceAsStream(EXECUTION_PROPERTIES_FILENAME);
       executionProperties.load(ips);
       if (executionProperties.containsKey("main-program")) {
         String mainTangaraFile = executionProperties.getProperty("main-program");
         System.out.println("main tangara file: " + mainTangaraFile);
         properties.setProperty("main-program", mainTangaraFile);
       } else {
         System.err.println("error : main program not specified");
       }
       if (executionProperties.containsKey("language")) {
         String language = executionProperties.getProperty("language");
         properties.setProperty("language", language);
         System.out.println("language: " + language);
       } else {
         System.err.println("error : language not specified");
       }
       if (executionProperties.containsKey("resources")) {
         String resources = executionProperties.getProperty("resources");
         properties.setProperty("program.resources", resources);
         System.out.println("resources: " + resources);
       } else {
         System.err.println("error : resources not specified");
       }
     }
   } catch (IOException e) {
     e.printStackTrace();
   } finally {
     if (file != null) {
       try {
         file.close();
       } catch (IOException e) {
         System.err.println("error while closing tangara JAR file");
       }
     }
   }
   return executionMode;
 }
Example #28
0
 private static boolean loadProviderAsService() {
   Iterator<HttpServerProvider> i =
       ServiceLoader.load(HttpServerProvider.class, ClassLoader.getSystemClassLoader()).iterator();
   for (; ; ) {
     try {
       if (!i.hasNext()) return false;
       provider = i.next();
       return true;
     } catch (ServiceConfigurationError sce) {
       if (sce.getCause() instanceof SecurityException) {
         // Ignore the security exception, try the next provider
         continue;
       }
       throw sce;
     }
   }
 }
 private ExternalizableMap loadMap(String extMapName, ClassLoader loader)
     throws FileNotFoundException {
   String first = null;
   String next = extMapName;
   List<String> urls = new ArrayList<String>();
   ExternalizableMap res = null;
   while (next != null) {
     // convert the plugin class name to an xml file name
     String mapFile = next.replace('.', '/') + MAP_SUFFIX;
     URL url = loader.getResource(mapFile);
     if (url != null && urls.contains(url.toString())) {
       throw new PluginException.InvalidDefinition("Plugin inheritance loop: " + next);
     }
     // load into map
     ExternalizableMap oneMap = new ExternalizableMap();
     oneMap.loadMapFromResource(mapFile, loader);
     urls.add(url.toString());
     // apply overrides one plugin at a time in inheritance chain
     processOverrides(oneMap);
     if (res == null) {
       res = oneMap;
     } else {
       for (Map.Entry ent : oneMap.entrySet()) {
         String key = (String) ent.getKey();
         Object val = ent.getValue();
         if (!res.containsKey(key)) {
           res.setMapElement(key, val);
         }
       }
     }
     if (oneMap.containsKey(KEY_PLUGIN_PARENT)) {
       next = oneMap.getString(KEY_PLUGIN_PARENT);
     } else {
       next = null;
     }
   }
   loadedFromUrls = urls;
   return res;
 }
Example #30
0
 public Class<?> loadClass(String name) throws ClassNotFoundException {
   return loader.loadClass(name);
 }