Example usage for java.lang Class getProtectionDomain

List of usage examples for java.lang Class getProtectionDomain

Introduction

In this page you can find the example usage for java.lang Class getProtectionDomain.

Prototype

public java.security.ProtectionDomain getProtectionDomain() 

Source Link

Document

Returns the ProtectionDomain of this class.

Usage

From source file:com.glaf.core.util.ReflectUtils.java

public static String getCodeBase(Class<?> cls) {
    if (cls == null)
        return null;
    ProtectionDomain domain = cls.getProtectionDomain();
    if (domain == null)
        return null;
    CodeSource source = domain.getCodeSource();
    if (source == null)
        return null;
    URL location = source.getLocation();
    if (location == null)
        return null;
    return location.getFile();
}

From source file:com.relicum.ipsum.io.PropertyIO.java

/**
 * Gets all files in jar./*from  ww  w  . ja va 2 s  .  c  o m*/
 *
 * @param clazz the clazz
 * @return the list of files and paths in jar
 */
default List<String> getAllFilesInJar(Class<?> clazz) {

    List<String> list = new ArrayList<>();
    CodeSource src = clazz.getProtectionDomain().getCodeSource();
    if (src != null) {
        try {
            URL jar = src.getLocation();
            ZipInputStream zip = new ZipInputStream(jar.openStream());
            while (true) {
                ZipEntry e = zip.getNextEntry();
                if (e == null)
                    break;
                String name = e.getName();
                if (name.contains(".properties")) {
                    list.add(name);
                    System.out.println(name);
                }

            }
            zip.close();
            jar = null;
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    return list;
}

From source file:net.minecraftforge.fml.common.asm.FMLSanityChecker.java

@Override
public Void call() throws Exception {
    CodeSource codeSource = getClass().getProtectionDomain().getCodeSource();
    boolean goodFML = false;
    boolean fmlIsJar = false;
    if (codeSource.getLocation().getProtocol().equals("jar")) {
        fmlIsJar = true;/*from  w w  w  .  j a v  a2 s  .com*/
        Certificate[] certificates = codeSource.getCertificates();
        if (certificates != null) {

            for (Certificate cert : certificates) {
                String fingerprint = CertificateHelper.getFingerprint(cert);
                if (fingerprint.equals(FMLFINGERPRINT)) {
                    FMLRelaunchLog.info("Found valid fingerprint for FML. Certificate fingerprint %s",
                            fingerprint);
                    goodFML = true;
                } else if (fingerprint.equals(FORGEFINGERPRINT)) {
                    FMLRelaunchLog.info(
                            "Found valid fingerprint for Minecraft Forge. Certificate fingerprint %s",
                            fingerprint);
                    goodFML = true;
                } else {
                    FMLRelaunchLog.severe("Found invalid fingerprint for FML: %s", fingerprint);
                }
            }
        }
    } else {
        goodFML = true;
    }
    // Server is not signed, so assume it's good - a deobf env is dev time so it's good too
    boolean goodMC = FMLLaunchHandler.side() == Side.SERVER || !liveEnv;
    int certCount = 0;
    try {
        Class<?> cbr = Class.forName("net.minecraft.client.ClientBrandRetriever", false, cl);
        codeSource = cbr.getProtectionDomain().getCodeSource();
    } catch (Exception e) {
        // Probably a development environment, or the server (the server is not signed)
        goodMC = true;
    }
    JarFile mcJarFile = null;
    if (fmlIsJar && !goodMC && codeSource.getLocation().getProtocol().equals("jar")) {
        try {
            String mcPath = codeSource.getLocation().getPath().substring(5);
            mcPath = mcPath.substring(0, mcPath.lastIndexOf('!'));
            mcPath = URLDecoder.decode(mcPath, Charsets.UTF_8.name());
            mcJarFile = new JarFile(mcPath, true);
            mcJarFile.getManifest();
            JarEntry cbrEntry = mcJarFile.getJarEntry("net/minecraft/client/ClientBrandRetriever.class");
            InputStream mcJarFileInputStream = mcJarFile.getInputStream(cbrEntry);
            try {
                ByteStreams.toByteArray(mcJarFileInputStream);
            } finally {
                IOUtils.closeQuietly(mcJarFileInputStream);
            }
            Certificate[] certificates = cbrEntry.getCertificates();
            certCount = certificates != null ? certificates.length : 0;
            if (certificates != null) {

                for (Certificate cert : certificates) {
                    String fingerprint = CertificateHelper.getFingerprint(cert);
                    if (fingerprint.equals(MCFINGERPRINT)) {
                        FMLRelaunchLog.info("Found valid fingerprint for Minecraft. Certificate fingerprint %s",
                                fingerprint);
                        goodMC = true;
                    }
                }
            }
        } catch (Throwable e) {
            FMLRelaunchLog.log(Level.ERROR, e,
                    "A critical error occurred trying to read the minecraft jar file");
        } finally {
            Java6Utils.closeZipQuietly(mcJarFile);
        }
    } else {
        goodMC = true;
    }
    if (!goodMC) {
        FMLRelaunchLog.severe(
                "The minecraft jar %s appears to be corrupt! There has been CRITICAL TAMPERING WITH MINECRAFT, it is highly unlikely minecraft will work! STOP NOW, get a clean copy and try again!",
                codeSource.getLocation().getFile());
        if (!Boolean.parseBoolean(System.getProperty("fml.ignoreInvalidMinecraftCertificates", "false"))) {
            FMLRelaunchLog.severe(
                    "For your safety, FML will not launch minecraft. You will need to fetch a clean version of the minecraft jar file");
            FMLRelaunchLog.severe(
                    "Technical information: The class net.minecraft.client.ClientBrandRetriever should have been associated with the minecraft jar file, "
                            + "and should have returned us a valid, intact minecraft jar location. This did not work. Either you have modified the minecraft jar file (if so "
                            + "run the forge installer again), or you are using a base editing jar that is changing this class (and likely others too). If you REALLY "
                            + "want to run minecraft in this configuration, add the flag -Dfml.ignoreInvalidMinecraftCertificates=true to the 'JVM settings' in your launcher profile.");
            FMLCommonHandler.instance().exitJava(1, false);
        } else {
            FMLRelaunchLog.severe(
                    "FML has been ordered to ignore the invalid or missing minecraft certificate. This is very likely to cause a problem!");
            FMLRelaunchLog.severe(
                    "Technical information: ClientBrandRetriever was at %s, there were %d certificates for it",
                    codeSource.getLocation(), certCount);
        }
    }
    if (!goodFML) {
        FMLRelaunchLog.severe("FML appears to be missing any signature data. This is not a good thing");
    }
    return null;
}

From source file:eu.trentorise.opendata.josman.Josmans.java

/**
 * Extracts the directory at resource path to target directory. First
 * directory is searched in local "src/main/resources" so the thing also
 * works when developing in the IDE. If not found then searches in jar file.
 *//* w  ww.  ja v a 2 s  .c  o  m*/
public static void copyDirFromResource(Class clazz, String dirPath, File destDir) {
    String sep = File.separator;
    File sourceDir = new File("src" + sep + "main" + sep + "resources", dirPath);

    if (sourceDir.exists()) {
        LOG.log(Level.INFO, "Copying directory from {0} to {1}  ...",
                new Object[] { sourceDir.getAbsolutePath(), destDir.getAbsolutePath() });
        try {
            FileUtils.copyDirectory(sourceDir, destDir);
            LOG.log(Level.INFO, "Done copying directory");
        } catch (IOException ex) {
            throw new RuntimeException("Couldn't copy the directory!", ex);
        }
    } else {

        File jarFile = new File(clazz.getProtectionDomain().getCodeSource().getLocation().getPath());
        if (jarFile.isDirectory()
                && jarFile.getAbsolutePath().endsWith("target" + File.separator + "classes")) {
            LOG.info("Seems like you have Josman sources, will take resources from there");
            try {
                FileUtils.copyDirectory(
                        new File(jarFile.getAbsolutePath() + "/../../src/main/resources", dirPath), destDir);
                LOG.log(Level.INFO, "Done copying directory");
            } catch (IOException ex) {
                throw new RuntimeException("Couldn't copy the directory!", ex);
            }
        } else {
            LOG.log(Level.INFO, "Extracting jar {0} to {1}",
                    new Object[] { jarFile.getAbsolutePath(), destDir.getAbsolutePath() });
            copyDirFromJar(jarFile, destDir, dirPath);
            LOG.log(Level.INFO, "Done copying directory from JAR.");
        }

    }
}

From source file:io.stallion.plugins.PluginRegistry.java

private void doLoadJarPlugins(String targetPath) throws Exception {
    String jarFolderPath = targetPath + "/jars";
    Log.fine("Loading jars at {0}", jarFolderPath);
    File jarFolder = new File(jarFolderPath);
    if (!jarFolder.exists() || !jarFolder.isDirectory()) {
        Log.fine("No jar folder exists at {0}. No jar plugins will be loaded.", jarFolderPath);
        return;/*ww  w  .  j av  a  2s . com*/
    }
    File[] files = jarFolder.listFiles();
    ArrayList<URL> urls = new ArrayList<URL>();
    for (int i = 0; i < files.length; i++) {
        if (files[i].getName().endsWith(".jar")) {
            //urls.add(files[i].toURL());
            Log.fine("Loading plugin jar {0}", files[i].toURI());
            urls.add(files[i].toURI().toURL());
        }
    }

    String pluginBooterClass = "";

    for (URL jarUrl : urls) {
        // Add jars to the class loader
        getClassLoader().addURL(jarUrl);
    }

    for (URL jarUrl : urls) {
        // Load the booter class
        Manifest m = new JarFile(jarUrl.getFile()).getManifest();
        Log.finer("Found manifest for jar {0}", jarUrl);
        if (!StringUtils.isEmpty(m.getMainAttributes().getValue("pluginBooterClass"))) {
            pluginBooterClass = m.getMainAttributes().getValue("pluginBooterClass");
        }
        if (empty(pluginBooterClass)) {
            continue;
        }
        Log.fine("Load plugin class {0} from jar={1}", pluginBooterClass, jarUrl);
        Class booterClass = getClassLoader().loadClass(pluginBooterClass);
        Log.finer("Booter class was loaded from: {0} ",
                booterClass.getProtectionDomain().getCodeSource().getLocation());
        StallionJavaPlugin booter = (StallionJavaPlugin) booterClass.newInstance();
        loadPluginFromBooter(booter);
        DynamicSettings.instance().initGroup(booter.getPluginName());
    }
}

From source file:com.servicelibre.jxsl.scenario.XslScenario.java

private static String getImplementationInfo(Class<?> componentClass) {

    // TODO if Saxon, add info from productTitle. Otherwise check jar
    // manifest for Implementation-Version, Implementation-Vendor at least.
    /*/*from  www .  ja  va  2s  .  com*/
     * Name: org/apache/xalan/ 
     * Comment: Main Xalan engine implementing
     * TrAX/JAXP Specification-Title: Java API for XML Processing
     * Specification-Vendor: Sun Microsystems Inc. 
     * Specification-Version: 1.3 
     * Implementation-Title: org.apache.xalan 
     * Implementation-Version: 2.7.1 
     * Implementation-Vendor: Apache Software Foundation
     * Implementation-URL: http://xml.apache.org/xalan-j/
     */

    CodeSource source = componentClass.getProtectionDomain().getCodeSource();
    return MessageFormat.format("{0} [{1}]", componentClass.getName(),
            source == null ? "Java Runtime" : source.getLocation());
}

From source file:com.aliyun.odps.mapred.BridgeJobRunner.java

private void applyFrameworkResource(Class<?> clz, String alias, String padding, Set<String> added)
        throws OdpsException {
    String jarFilePath;//from  ww w .  j ava 2s  .c o  m
    try {
        jarFilePath = new File(clz.getProtectionDomain().getCodeSource().getLocation().toURI())
                .getAbsolutePath();
    } catch (URISyntaxException ex) {
        throw new OdpsException(ex);
    }
    if (added.contains(jarFilePath)) {
        return;
    }
    int trycount = 0;
    while (true) {
        try {
            aliasToTempResource.put(alias,
                    metaExplorer.addFileResourceWithRetry(jarFilePath, Resource.Type.JAR, padding, true));
            added.add(jarFilePath);
            return;
        } catch (Exception ex) {
            trycount++;
            if (trycount >= 3) {
                throw new OdpsException(ex);
            }
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
            }
        }
    }

}

From source file:org.kurento.test.grid.GridHandler.java

private File getJarPath(Class<?> aclass) {
    URL url;/*from   ww  w.  java2 s  . c  om*/
    try {
        url = aclass.getProtectionDomain().getCodeSource().getLocation();
    } catch (SecurityException ex) {
        url = aclass.getResource(aclass.getSimpleName() + ".class");
    }
    try {
        return new File(url.toURI());
    } catch (URISyntaxException ex) {
        return new File(url.getPath());
    }
}

From source file:net.minecraftforge.fml.common.FMLModContainer.java

@Subscribe
public void constructMod(FMLConstructionEvent event) {
    try {/*from  w ww .ja  va 2  s.  c o m*/
        BlamingTransformer.addClasses(getModId(), candidate.getClassList());
        ModClassLoader modClassLoader = event.getModClassLoader();
        modClassLoader.addFile(source);
        modClassLoader.clearNegativeCacheFor(candidate.getClassList());

        //Only place I could think to add this...
        MinecraftForge.preloadCrashClasses(event.getASMHarvestedData(), getModId(), candidate.getClassList());

        Class<?> clazz = Class.forName(className, true, modClassLoader);

        Certificate[] certificates = clazz.getProtectionDomain().getCodeSource().getCertificates();
        int len = 0;
        if (certificates != null) {
            len = certificates.length;
        }
        Builder<String> certBuilder = ImmutableList.builder();
        for (int i = 0; i < len; i++) {
            certBuilder.add(CertificateHelper.getFingerprint(certificates[i]));
        }

        ImmutableList<String> certList = certBuilder.build();
        sourceFingerprints = ImmutableSet.copyOf(certList);

        String expectedFingerprint = (String) descriptor.get("certificateFingerprint");

        fingerprintNotPresent = true;

        if (expectedFingerprint != null && !expectedFingerprint.isEmpty()) {
            if (!sourceFingerprints.contains(expectedFingerprint)) {
                Level warnLevel = Level.ERROR;
                if (source.isDirectory()) {
                    warnLevel = Level.TRACE;
                }
                FMLLog.log(getModId(), warnLevel,
                        "The mod %s is expecting signature %s for source %s, however there is no signature matching that description",
                        getModId(), expectedFingerprint, source.getName());
            } else {
                certificate = certificates[certList.indexOf(expectedFingerprint)];
                fingerprintNotPresent = false;
            }
        }

        @SuppressWarnings("unchecked")
        List<Map<String, Object>> props = (List<Map<String, Object>>) descriptor.get("customProperties");
        if (props != null) {
            com.google.common.collect.ImmutableMap.Builder<String, String> builder = ImmutableMap.builder();
            for (Map<String, Object> p : props) {
                builder.put((String) p.get("k"), (String) p.get("v"));
            }
            customModProperties = builder.build();
        } else {
            customModProperties = EMPTY_PROPERTIES;
        }

        Boolean hasDisableableFlag = (Boolean) descriptor.get("canBeDeactivated");
        boolean hasReverseDepends = !event.getReverseDependencies().get(getModId()).isEmpty();
        if (hasDisableableFlag != null && hasDisableableFlag) {
            disableability = hasReverseDepends ? Disableable.DEPENDENCIES : Disableable.YES;
        } else {
            disableability = hasReverseDepends ? Disableable.DEPENDENCIES : Disableable.RESTART;
        }
        Method factoryMethod = gatherAnnotations(clazz);
        modInstance = getLanguageAdapter().getNewInstance(this, clazz, modClassLoader, factoryMethod);
        NetworkRegistry.INSTANCE.register(this, clazz,
                (String) (descriptor.containsKey("acceptableRemoteVersions")
                        ? descriptor.get("acceptableRemoteVersions")
                        : null),
                event.getASMHarvestedData());
        if (fingerprintNotPresent) {
            eventBus.post(new FMLFingerprintViolationEvent(source.isDirectory(), source,
                    ImmutableSet.copyOf(this.sourceFingerprints), expectedFingerprint));
        }
        ProxyInjector.inject(this, event.getASMHarvestedData(), FMLCommonHandler.instance().getSide(),
                getLanguageAdapter());
        AutomaticEventSubscriber.inject(this, event.getASMHarvestedData(),
                FMLCommonHandler.instance().getSide());
        ConfigManager.load(this.getModId(), Config.Type.INSTANCE);

        processFieldAnnotations(event.getASMHarvestedData());
    } catch (Throwable e) {
        controller.errorOccurred(this, e);
    }
}