Beispiel #1
1
 /**
  * 获取版本号
  *
  * @param clazz
  * @param defaultVersion
  * @return
  */
 public static String getVersion(Class clazz, String defaultVersion) {
   try {
     // 首先查找MANIFEST.MF规范中的版本号
     String version = clazz.getPackage().getImplementationVersion();
     if (version == null || version.length() == 0) {
       version = clazz.getPackage().getSpecificationVersion();
     }
     if (version == null || version.length() == 0) {
       // 如果MANIFEST.MF规范中没有版本号,基于jar包名获取版本号
       String file = clazz.getProtectionDomain().getCodeSource().getLocation().getFile();
       if (file != null && file.length() > 0 && file.endsWith(".jar")) {
         Matcher matcher = VERSION_PATTERN.matcher(file);
         while (matcher.find() && matcher.groupCount() > 0) {
           version = matcher.group(1);
         }
       }
     }
     // 返回版本号,如果为空返回缺省版本号
     return version == null || version.length() == 0 ? defaultVersion : version;
   } catch (Throwable e) { // 防御性容错
     // 忽略异常,返回缺省版本号
     logger.error(e.getMessage(), e);
     return defaultVersion;
   }
 }
Beispiel #2
0
  public static ClassReader readClass(Class<?> theClass)
      throws IOException, BenignClassReadException {
    if (theClass.isArray()) {
      throw new BenignClassReadException(theClass.getName() + " is an array");
    }
    if (Proxy.isProxyClass(theClass)) {
      throw new BenignClassReadException(theClass.getName() + " is a Proxy class");
    }
    if (isRMIStubOrProxy(theClass)) {
      throw new BenignClassReadException(theClass.getName() + " is an RMI Stub or Proxy class");
    }
    if (theClass.getName().startsWith("sun.reflect.")) {
      throw new BenignClassReadException(theClass.getName() + " is a reflection class");
    }
    if (isJAXBClass(theClass)) {
      throw new BenignClassReadException(theClass.getName() + " is a JAXB accessor class");
    }
    if ((theClass.getProtectionDomain().getCodeSource() != null)
        && (theClass.getProtectionDomain().getCodeSource().getLocation() == null)) {
      throw new BenignClassReadException(theClass.getName() + " is a generated class");
    }
    URL resource = getClassResource(theClass.getClassLoader(), Type.getInternalName(theClass));
    if (resource == null) {
      ClassReader reader =
          ServiceFactory.getClassTransformerService()
              .getContextManager()
              .getClassWeaverService()
              .getClassReader(theClass);

      if (reader != null) {
        return reader;
      }
    }
    return getClassReaderFromResource(theClass.getName(), resource);
  }
Beispiel #3
0
  public static LinkedHashSet<String> findJars(LogicalPlan dag, Class<?>[] defaultClasses) {
    List<Class<?>> jarClasses = new ArrayList<Class<?>>();

    for (String className : dag.getClassNames()) {
      try {
        Class<?> clazz = Thread.currentThread().getContextClassLoader().loadClass(className);
        jarClasses.add(clazz);
      } catch (ClassNotFoundException e) {
        throw new IllegalArgumentException("Failed to load class " + className, e);
      }
    }

    for (Class<?> clazz : Lists.newArrayList(jarClasses)) {
      // process class and super classes (super does not require deploy annotation)
      for (Class<?> c = clazz; c != Object.class && c != null; c = c.getSuperclass()) {
        // LOG.debug("checking " + c);
        jarClasses.add(c);
        jarClasses.addAll(Arrays.asList(c.getInterfaces()));
      }
    }

    jarClasses.addAll(Arrays.asList(defaultClasses));

    if (dag.isDebug()) {
      LOG.debug("Deploy dependencies: {}", jarClasses);
    }

    LinkedHashSet<String> localJarFiles = new LinkedHashSet<String>(); // avoid duplicates
    HashMap<String, String> sourceToJar = new HashMap<String, String>();

    for (Class<?> jarClass : jarClasses) {
      if (jarClass.getProtectionDomain().getCodeSource() == null) {
        // system class
        continue;
      }
      String sourceLocation =
          jarClass.getProtectionDomain().getCodeSource().getLocation().toString();
      String jar = sourceToJar.get(sourceLocation);
      if (jar == null) {
        // don't create jar file from folders multiple times
        jar = JarFinder.getJar(jarClass);
        sourceToJar.put(sourceLocation, jar);
        LOG.debug("added sourceLocation {} as {}", sourceLocation, jar);
      }
      if (jar == null) {
        throw new AssertionError("Cannot resolve jar file for " + jarClass);
      }
      localJarFiles.add(jar);
    }

    String libJarsPath = dag.getValue(LogicalPlan.LIBRARY_JARS);
    if (!StringUtils.isEmpty(libJarsPath)) {
      String[] libJars = StringUtils.splitByWholeSeparator(libJarsPath, LIB_JARS_SEP);
      localJarFiles.addAll(Arrays.asList(libJars));
    }

    LOG.info("Local jar file dependencies: " + localJarFiles);

    return localJarFiles;
  }
Beispiel #4
0
 /**
  * From http://stackoverflow.com/questions/320542/how-to-get-the-path-of-a- running-jar-file
  *
  * <p>Used to get all classes in the specified package.
  *
  * @param caller The class that requests
  * @param pckgname The package name.
  * @return The classes contained by the specified package.
  * @throws ClassNotFoundException
  */
 private static Class<?>[] getClasses(Class<?> caller, String pckgname)
     throws ClassNotFoundException {
   String source = caller.getProtectionDomain().getCodeSource().getLocation().getPath();
   if (source.toLowerCase().endsWith(".jar"))
     try {
       return getClassesFromJARFile(
           caller.getProtectionDomain().getCodeSource().getLocation().toURI(), pckgname);
     } catch (URISyntaxException e) {
       throw new AssertionError(e);
     }
   else return getClassesLocal(pckgname);
 }
  public Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
    log.debug("calling loadClass boolean with class " + name + ".  I am " + this);

    // reverse the logic. try myself first, then delgate:
    Class c = findLoadedClass(name);
    if (c == null) {
      try {
        c = findClass(name);
        log.debug("Yes!  classloader" + this + " did have " + name);
      } catch (ClassNotFoundException cnfe) {
        log.debug("No!  classloader" + this + " didn't have " + name + " delegating to parent!");
        c = super.loadClass(name, resolve);
      }
    }
    if (resolve) {
      resolveClass(c);
    }
    log.debug(
        "found class "
            + name
            + ".  I am "
            + this
            + " it's classloader is "
            + c.getClassLoader()
            + " it's codesource it "
            + c.getProtectionDomain().getCodeSource());

    return c;
  }
  public ClassMeta getClassInfo(Class<?> cls) {
    final Package pkg = cls.getPackage();

    URL loadedFrom = null;

    try {
      loadedFrom = cls.getProtectionDomain().getCodeSource().getLocation();
    } catch (Throwable t) {
      Log.warn(t, "Failed to get source for %s", cls);
    }

    final API apiAnnotation = pkg.getAnnotation(API.class);
    final ApiInfo apiInfo = apiAnnotation != null ? new ApiInfo(apiAnnotation) : null;

    Map<File, Set<String>> mods = Maps.newHashMap();
    for (ModCandidate candidate : table.getCandidatesFor(pkg.getName())) {
      if (!candidate.getClassList().contains(cls.getName().replace('.', '/'))) continue;

      final File candidateFile = candidate.getModContainer();

      Set<String> modIds = Sets.newHashSet();
      mods.put(candidateFile, modIds);
      for (ModContainer mod : candidate.getContainedMods()) modIds.add(mod.getModId());
    }

    return new ClassMeta(cls, loadedFrom, apiInfo, mods);
  }
  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;
  }
Beispiel #8
0
  /**
   * Format a string buffer containing the Class, Interfaces, CodeSource, and ClassLoader
   * information for the given object clazz.
   *
   * @param clazz the Class
   * @param results, the buffer to write the info to
   */
  public static void displayClassInfo(Class clazz, StringBuffer results) {
    // Print out some codebase info for the ProbeHome
    ClassLoader cl = clazz.getClassLoader();
    results.append("\n" + clazz.getName() + ".ClassLoader=" + cl);
    ClassLoader parent = cl;
    while (parent != null) {
      results.append("\n.." + parent);
      URL[] urls = getClassLoaderURLs(parent);
      int length = urls != null ? urls.length : 0;
      for (int u = 0; u < length; u++) {
        results.append("\n...." + urls[u]);
      }
      if (parent != null) parent = parent.getParent();
    }
    CodeSource clazzCS = clazz.getProtectionDomain().getCodeSource();
    if (clazzCS != null) results.append("\n++++CodeSource: " + clazzCS);
    else results.append("\n++++Null CodeSource");

    results.append("\nImplemented Interfaces:");
    Class[] ifaces = clazz.getInterfaces();
    for (int i = 0; i < ifaces.length; i++) {
      results.append("\n++" + ifaces[i]);
      ClassLoader loader = ifaces[i].getClassLoader();
      results.append("\n++++ClassLoader: " + loader);
      ProtectionDomain pd = ifaces[i].getProtectionDomain();
      CodeSource cs = pd.getCodeSource();
      if (cs != null) results.append("\n++++CodeSource: " + cs);
      else results.append("\n++++Null CodeSource");
    }
  }
  /**
   * @param args
   * @throws IOException
   */
  public static void main(String[] args) throws IOException {
    // TODO Auto-generated method stub

    MyClassLocation myLocation = new MyClassLocation();

    File file = myLocation.getClassLocationFile(Aladin.class);

    System.out.println("Result form my location: " + file);

    Class theClass = Aladin.class;
    String classResourceName = theClass.getName().replace('.', '/') + ".class";
    URL resource = theClass.getResource("/" + classResourceName);
    System.out.println("resource: " + resource);

    URL codeSource = theClass.getProtectionDomain().getCodeSource().getLocation();

    System.out.println("code source: " + codeSource);

    // it returns the path to the class that is running
    System.out.println(
        "Class loader 1: " + ClassLoader.getSystemClassLoader().getResource(".").getPath());
    System.out.println(
        "Class loader 2: "
            + ClassLoader.getSystemClassLoader().getResource(classResourceName).getPath());
    resource = Aladin.class.getClassLoader().getResource("/" + classResourceName);
    System.out.println("Class loader 3: " + resource);
  }
  public static String getSourceLocation(final Class<?> cls) {

    String exMsg = null;
    java.security.CodeSource codeSource = null;

    try {
      codeSource = cls.getProtectionDomain().getCodeSource();

    } catch (final Exception e) {
      exMsg = e.toString();
    }

    final URL classURL = codeSource == null ? getSourceURL(cls) : codeSource.getLocation();

    if (classURL == null) {
      return cls.getName() + ": (missing codeSource and classLoader)";
    }

    final String path = classURL.getPath();
    final File file = new File(path);

    if (!file.isFile()) {
      return cls.getName() + ": " + path + " (not a file)" + (exMsg == null ? "" : "; " + exMsg);
    }

    return String.format(
        "%s (SN: %s): %s (MD5: %s)%s",
        cls.getName(),
        getSerialVersionUID(cls),
        path,
        MD5Kit.md5sum(file),
        exMsg == null ? "" : "; " + exMsg);
  }
Beispiel #11
0
 /**
  * 获取类的class文件位置的URL
  *
  * @param cls
  * @return
  */
 private static URL getClassLocationURL(final Class cls) {
   if (cls == null) throw new IllegalArgumentException("null input: cls");
   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;
 }
Beispiel #12
0
 private static String getUnmigrationCommandLine(File jenkinsHome) {
   StringBuilder cp = new StringBuilder();
   for (Class<?> c :
       new Class<?>[] {
         RunIdMigrator.class, /* TODO how to calculate transitive dependencies automatically? */
         Charsets.class,
         WriterOutputStream.class,
         BuildException.class,
         FastDateFormat.class
       }) {
     URL location = c.getProtectionDomain().getCodeSource().getLocation();
     String locationS = location.toString();
     if (location.getProtocol().equals("file")) {
       try {
         locationS = new File(location.toURI()).getAbsolutePath();
       } catch (URISyntaxException x) {
         // never mind
       }
     }
     if (cp.length() > 0) {
       cp.append(File.pathSeparator);
     }
     cp.append(locationS);
   }
   return String.format(
       "java -classpath \"%s\" %s \"%s\"", cp, RunIdMigrator.class.getName(), jenkinsHome);
 }
 public URL locateCodeSource(Class<?> clz) {
   if (clz == null) {
     throw new IllegalArgumentException("null class");
   }
   ProtectionDomain protectionDomain = null;
   try {
     protectionDomain = clz.getProtectionDomain();
   } catch (SecurityException e) {
     // got security error
     if (reportErrorNoPermission) {
       throw e;
     } else {
       return null;
     }
   }
   if (protectionDomain != null && protectionDomain.getCodeSource() != null) {
     return protectionDomain.getCodeSource().getLocation();
   }
   if (clz.getClassLoader() == null) {
     // bootstrap loader
     String name = Util.resolveName(clz.getName());
     URL resourceURL = Util.getDummyLoader().getResource(name);
     return Util.extractBaseURL(resourceURL, name);
   }
   return null;
 }
 public TestResourceLoaderBuilder addClass(final Class<?> aClass) throws Exception {
   final ClassSpec classSpec = new ClassSpec();
   classSpec.setCodeSource(aClass.getProtectionDomain().getCodeSource());
   final byte[] classBytes = getClassBytes(aClass);
   classSpec.setBytes(classBytes);
   addClassSpec(aClass.getName(), classSpec);
   return this;
 }
  private static String getSourcePathFromClass(Class<?> containedClass) {
    File file =
        new File(containedClass.getProtectionDomain().getCodeSource().getLocation().getPath());

    if (!file.isDirectory() && file.getName().endsWith(".class")) {
      String name = containedClass.getName();
      StringTokenizer tokenizer = new StringTokenizer(name, ".");
      while (tokenizer.hasMoreTokens()) {
        tokenizer.nextElement();
        file = file.getParentFile();
      }

      return file.getPath();
    } else {
      return containedClass.getProtectionDomain().getCodeSource().getLocation().getPath();
    }
  }
  /**
   * Generate the XSD file. First argument is directory where the XSD file should be placed (it will
   * be named radargun-{version}.xsd.
   */
  public static void main(String[] args) {
    if (args.length < 1 || args[0] == null)
      throw new IllegalArgumentException("No schema location directory specified!");

    for (Class<? extends Stage> stage : StageHelper.getStages().values()) {
      stages.put(stage, stage.getProtectionDomain().getCodeSource().getLocation().getPath());
    }
    new ConfigSchemaGenerator().generate(args[0], String.format("radargun-%s.xsd", VERSION));
  }
 protected static File basedir(Class<?> clazz) {
   try {
     ProtectionDomain protectionDomain = clazz.getProtectionDomain();
     return new File(new File(protectionDomain.getCodeSource().getLocation().getPath()), "../..")
         .getCanonicalFile();
   } catch (IOException e) {
     return new File(".");
   }
 }
  /**
   * Ce qui charge les natives
   *
   * @param c une classe
   */
  private static void loadNatives(Class c) {
    final File jarFile = new File(c.getProtectionDomain().getCodeSource().getLocation().getPath());
    final String path = "res/native/";

    if (jarFile.isFile()) {
      try {
        // Run with JAR file
        final JarFile jar = new JarFile(jarFile);

        final Enumeration<JarEntry> entries = jar.entries(); // gives ALL entries in jar
        final String nativeFolderPath = jarFile.getParent() + "/native/";
        final File nativeFolder = new File(nativeFolderPath);
        nativeFolder.delete();
        nativeFolder.mkdir();

        while (entries.hasMoreElements()) {
          final String name = entries.nextElement().getName();

          if (name.startsWith(path)) { // filter according to the path
            Object temp = null;

            InputStream is = c.getResourceAsStream("/" + name);
            String nativeName = name.replace(path, "");
            File nativePath = new File(nativeFolderPath + nativeName);
            if (!nativeName.isEmpty()) {
              System.out.println("Extracting: " + nativeName);
              OutputStream os = null;
              try {
                os = new FileOutputStream(nativePath);
                byte[] buffer = new byte[1024];
                int length;
                while ((length = is.read(buffer)) > 0) {
                  os.write(buffer, 0, length);
                }
              } finally {
                is.close();
                os.close();
              }
            }
          }
        }
        jar.close();

        System.setProperty("org.lwjgl.librarypath", nativeFolderPath);
      } catch (IOException ex) {
        Logger.getLogger(c.getName()).log(Level.SEVERE, null, ex);
      }
    } else {
      try {
        System.setProperty(
            "org.lwjgl.librarypath", new File(c.getResource("/" + path).toURI()).getAbsolutePath());
      } catch (URISyntaxException ex) {
        Logger.getLogger(c.getName()).log(Level.SEVERE, null, ex);
      }
    }
  }
  /**
   * This static method uses a system property to find and instantiate (via a public constructor) a
   * provider spe- cific factory implementation class. The name of the provider specific factory
   * implementation class is obtained from the value of the system property,
   *
   * <pre>
   * javax.security.jacc.PolicyConfigurationFactory.provider.
   * </pre>
   *
   * @return the singleton instance of the provider specific PolicyConfigurationFactory
   *     implementation class.
   * @throws SecurityException - when called by an AccessControlContext that has not been granted
   *     the “setPolicy” SecurityPermission.
   * @throws ClassNotFoundException - when the class named by the system property could not be found
   *     including because the value of the system property has not be set.
   * @throws PolicyContextException - if the implementation throws a checked exception that has not
   *     been accounted for by the getPolicyConfigurationFactory method signature. The exception
   *     thrown by the implementation class will be encapsulated (during construction) in the thrown
   *     PolicyContextException
   */
  public static PolicyConfigurationFactory getPolicyConfigurationFactory()
      throws ClassNotFoundException, PolicyContextException {
    // Validate the caller permission
    SecurityManager sm = System.getSecurityManager();
    if (sm != null) sm.checkPermission(new SecurityPermission("setPolicy"));

    synchronized (PolicyConfigurationFactory.class) {
      if (factory == null) {
        String factoryName = null;
        Class<?> clazz = null;
        try {
          LoadAction action = new LoadAction();
          try {
            clazz = AccessController.doPrivileged(action);
            factoryName = action.getName();
          } catch (PrivilegedActionException ex) {
            factoryName = action.getName();
            Exception e = ex.getException();
            if (e instanceof ClassNotFoundException) throw (ClassNotFoundException) e;
            else
              throw new PolicyContextException("Failure during load of class: " + factoryName, e);
          }
          factory = (PolicyConfigurationFactory) clazz.newInstance();
        } catch (ClassNotFoundException e) {
          String msg = "Failed to find PolicyConfigurationFactory : " + factoryName;
          throw new ClassNotFoundException(msg, e);
        } catch (IllegalAccessException e) {
          String msg = "Unable to access class : " + factoryName;
          throw new PolicyContextException(msg, e);
        } catch (InstantiationException e) {
          String msg = "Failed to create instance of: " + factoryName;
          throw new PolicyContextException(msg, e);
        } catch (ClassCastException e) {
          StringBuffer msg =
              new StringBuffer(factoryName + " Is not a PolicyConfigurationFactory, ");
          msg.append("PCF.class.CL: " + PolicyConfigurationFactory.class.getClassLoader());
          msg.append(
              "\nPCF.class.CS: "
                  + PolicyConfigurationFactory.class.getProtectionDomain().getCodeSource());
          msg.append(
              "\nPCF.class.hash: " + System.identityHashCode(PolicyConfigurationFactory.class));
          msg.append("\nclazz.CL: " + clazz.getClassLoader());
          msg.append("\nclazz.CS: " + clazz.getProtectionDomain().getCodeSource());
          msg.append("\nclazz.super.CL: " + clazz.getSuperclass().getClassLoader());
          msg.append(
              "\nclazz.super.CS: " + clazz.getSuperclass().getProtectionDomain().getCodeSource());
          msg.append("\nclazz.super.hash: " + System.identityHashCode(clazz.getSuperclass()));
          ClassCastException cce = new ClassCastException(msg.toString());
          cce.initCause(e);
          throw cce;
        }
      }
    }
    return factory;
  }
Beispiel #20
0
  /**
   * Get the protection domain for a class
   *
   * @param clazz the class
   * @return the protected domain or null if it doesn't have one
   */
  private static final ProtectionDomain getProtectionDomain(final Class<?> clazz) {
    SecurityManager sm = System.getSecurityManager();
    if (sm == null) return clazz.getProtectionDomain();

    return AccessController.doPrivileged(
        new PrivilegedAction<ProtectionDomain>() {
          public ProtectionDomain run() {
            return clazz.getProtectionDomain();
          }
        });
  }
 public void addClassDependency(Class<?> clazz) {
   CodeSource source = clazz.getProtectionDomain().getCodeSource();
   if (source == null) return;
   Path absolutePath = null;
   try {
     absolutePath = Paths.get(source.getLocation().toURI()).toAbsolutePath();
   } catch (URISyntaxException e) {
     e.printStackTrace();
   }
   globalDependencies.add(absolutePath);
 }
Beispiel #22
0
  /**
   * Returns JAR archive structure.
   *
   * @param jarClass any class within the JAR
   * @param allowedExtensions list of extension filters
   * @param allowedPackgages list of allowed packages
   * @param listener jar download listener
   * @return JAR archive structure
   */
  public static JarStructure getJarStructure(
      final Class jarClass,
      final List<String> allowedExtensions,
      final List<String> allowedPackgages,
      final FileDownloadListener listener) {
    try {
      final CodeSource src = jarClass.getProtectionDomain().getCodeSource();
      if (src != null) {
        // Creating structure

        // Source url
        final URL jarUrl = src.getLocation();
        final URI uri = jarUrl.toURI();

        // Source file
        final File jarFile;
        final String scheme = uri.getScheme();
        if (scheme != null && scheme.equalsIgnoreCase("file")) {
          // Local jar-file
          jarFile = new File(uri);
        } else {
          // Remote jar-file
          jarFile =
              FileUtils.downloadFile(
                  jarUrl.toString(), File.createTempFile("jar_file", ".tmp"), listener);
        }

        // Creating
        final JarEntry jarEntry = new JarEntry(JarEntryType.jarEntry, jarFile.getName());
        final JarStructure jarStructure = new JarStructure(jarEntry);
        jarStructure.setJarLocation(jarFile.getAbsolutePath());

        // Reading all entries and parsing them into structure
        final ZipInputStream zip = new ZipInputStream(jarUrl.openStream());
        ZipEntry zipEntry;
        while ((zipEntry = zip.getNextEntry()) != null) {
          final String entryName = zipEntry.getName();
          if (isAllowedPackage(entryName, allowedPackgages)
              && (zipEntry.isDirectory() || isAllowedExtension(entryName, allowedExtensions))) {
            parseElement(jarEntry, entryName, zipEntry);
          }
        }
        zip.close();

        return jarStructure;
      }
    } catch (final IOException e) {
      FlatLafLogger.error(ReflectUtils.class, e);
    } catch (final URISyntaxException e) {
      FlatLafLogger.error(ReflectUtils.class, e);
    }
    return null;
  }
 String getJarFromClass(Class<?> clz) {
   CodeSource source = clz.getProtectionDomain().getCodeSource();
   if (null == source) {
     throw new RuntimeException("Could not get CodeSource for class");
   }
   URL jarUrl = source.getLocation();
   String jar = jarUrl.getPath();
   if (!jar.endsWith(".jar")) {
     throw new RuntimeException("Need to have a jar to run mapreduce: " + jar);
   }
   return jar;
 }
 @Test
 public void testUsePhysicalCodeSource() throws ClassNotFoundException {
   Class<?> clazz = this.ejb.loadClass(TO_BE_FOUND_CLASS_NAME);
   Assert.assertTrue(
       clazz.getProtectionDomain().getCodeSource().getLocation().getProtocol().equals("jar"));
   Assert.assertTrue(
       ClassLoadingEJB.class
           .getProtectionDomain()
           .getCodeSource()
           .getLocation()
           .getProtocol()
           .equals("jar"));
 }
 public static File locationOf(Class clazz) {
   String path = clazz.getProtectionDomain().getCodeSource().getLocation().getPath();
   path = path.contains("!") ? path.substring(0, path.lastIndexOf('!')) : path;
   if (!path.isEmpty() && path.charAt(0) == '/') {
     path = "file:" + path;
   }
   try {
     return getRelativeFile(new File(new URL(path).toURI()), currentDir);
   } catch (Exception e) {
     Log.severe("", e);
     return getRelativeFile(new File(path), currentDir);
   }
 }
Beispiel #26
0
 public static String jarUsage(Class<?> main, String... params) {
   StringBuilder usage = new StringBuilder("USAGE: java [-cp ...] ");
   try {
     String jar = main.getProtectionDomain().getCodeSource().getLocation().getPath();
     usage.append("-jar ").append(jar);
   } catch (Exception ex) {
     // ignore
   }
   usage.append(' ').append(main.getCanonicalName());
   for (String param : params) {
     usage.append(' ').append(param);
   }
   return usage.toString();
 }
  @Test
  public void testProtectionDomainEquality() throws Exception {
    Bundle hostA = installBundle(getHostA());
    Bundle fragA = installBundle(getFragmentA());

    hostA.start();

    // Load class provided by the fragment
    assertLoadClass(hostA, FragBeanA.class.getName());
    Class<?> fragBeanClass = hostA.loadClass(FragBeanA.class.getName());
    ProtectionDomain fragDomain = fragBeanClass.getProtectionDomain();

    // Load a private class from host
    assertLoadClass(hostA, SubBeanA.class.getName());
    Class<?> hostBeanClass = hostA.loadClass(SubBeanA.class.getName());
    ProtectionDomain hostDomain = hostBeanClass.getProtectionDomain();

    // Assert ProtectionDomain
    assertNotSame(hostDomain, fragDomain);

    hostA.uninstall();
    fragA.uninstall();
  }
  private static String getContainerDetails() {
    StringBuilder result = new StringBuilder();

    Class containerClass;
    for (CdiContainer cdiContainer : ServiceLoader.load(CdiContainer.class)) {
      containerClass = cdiContainer.getClass();
      result.append(
          containerClass.getProtectionDomain().getCodeSource().getLocation().toExternalForm());
      result.append(containerClass.getName());

      result.append(System.getProperty("line.separator"));
    }

    return result.toString();
  }
  public Class<?> loadClass(String name) throws ClassNotFoundException {
    log.debug("calling loadClass with class " + name + ".  I am " + this);
    Class<?> ret = super.loadClass(name);
    log.debug(
        "found class "
            + name
            + ".  I am "
            + this
            + " it's classloader is "
            + ret.getClassLoader()
            + " it's codesource it "
            + ret.getProtectionDomain().getCodeSource());

    return ret;
  }
  /**
   * @param clazzToAddToServerCodebase a class that should be in the java.rmi.server.codebase
   *     property.
   */
  @SuppressWarnings("rawtypes")
  public RmiStarter(Class clazzToAddToServerCodebase) {

    System.setProperty(
        "java.rmi.server.codebase",
        clazzToAddToServerCodebase.getProtectionDomain().getCodeSource().getLocation().toString());

    System.setProperty("java.security.policy", PolicyFileLocator.getLocationOfPolicyFile());

    if (System.getSecurityManager() == null) {
      System.setSecurityManager(new SecurityManager());
    }

    handleRMI();
  }