Search in sources :

Example 86 with JarEntry

use of java.util.jar.JarEntry in project hbase by apache.

the class ClassLoaderTestHelper method createJarArchive.

/**
   * Jar a list of files into a jar archive.
   *
   * @param archiveFile the target jar archive
   * @param tobejared a list of files to be jared
   */
private static boolean createJarArchive(File archiveFile, File[] tobeJared) {
    try {
        byte[] buffer = new byte[BUFFER_SIZE];
        // Open archive file
        FileOutputStream stream = new FileOutputStream(archiveFile);
        JarOutputStream out = new JarOutputStream(stream, new Manifest());
        for (int i = 0; i < tobeJared.length; i++) {
            if (tobeJared[i] == null || !tobeJared[i].exists() || tobeJared[i].isDirectory()) {
                continue;
            }
            // Add archive entry
            JarEntry jarAdd = new JarEntry(tobeJared[i].getName());
            jarAdd.setTime(tobeJared[i].lastModified());
            out.putNextEntry(jarAdd);
            // Write file to archive
            FileInputStream in = new FileInputStream(tobeJared[i]);
            while (true) {
                int nRead = in.read(buffer, 0, buffer.length);
                if (nRead <= 0)
                    break;
                out.write(buffer, 0, nRead);
            }
            in.close();
        }
        out.close();
        stream.close();
        LOG.info("Adding classes to jar file completed");
        return true;
    } catch (Exception ex) {
        LOG.error("Error: " + ex.getMessage());
        return false;
    }
}
Also used : FileOutputStream(java.io.FileOutputStream) JarOutputStream(java.util.jar.JarOutputStream) Manifest(java.util.jar.Manifest) JarEntry(java.util.jar.JarEntry) FileInputStream(java.io.FileInputStream)

Example 87 with JarEntry

use of java.util.jar.JarEntry in project hbase by apache.

the class ClassFinder method findClassesFromJar.

private Set<Class<?>> findClassesFromJar(String jarFileName, String packageName, boolean proceedOnExceptions) throws IOException, ClassNotFoundException, LinkageError {
    JarInputStream jarFile = null;
    try {
        jarFile = new JarInputStream(new FileInputStream(jarFileName));
    } catch (IOException ioEx) {
        LOG.warn("Failed to look for classes in " + jarFileName + ": " + ioEx);
        throw ioEx;
    }
    Set<Class<?>> classes = new HashSet<>();
    JarEntry entry = null;
    try {
        while (true) {
            try {
                entry = jarFile.getNextJarEntry();
            } catch (IOException ioEx) {
                if (!proceedOnExceptions) {
                    throw ioEx;
                }
                LOG.warn("Failed to get next entry from " + jarFileName + ": " + ioEx);
                break;
            }
            if (entry == null) {
                // loop termination condition
                break;
            }
            String className = entry.getName();
            if (!className.endsWith(CLASS_EXT)) {
                continue;
            }
            int ix = className.lastIndexOf('/');
            String fileName = (ix >= 0) ? className.substring(ix + 1) : className;
            if (null != this.fileNameFilter && !this.fileNameFilter.isCandidateFile(fileName, className)) {
                continue;
            }
            className = className.substring(0, className.length() - CLASS_EXT.length()).replace('/', '.');
            if (!className.startsWith(packageName)) {
                continue;
            }
            Class<?> c = makeClass(className, proceedOnExceptions);
            if (c != null) {
                if (!classes.add(c)) {
                    LOG.warn("Ignoring duplicate class " + className);
                }
            }
        }
        return classes;
    } finally {
        jarFile.close();
    }
}
Also used : JarInputStream(java.util.jar.JarInputStream) IOException(java.io.IOException) JarEntry(java.util.jar.JarEntry) FileInputStream(java.io.FileInputStream) HashSet(java.util.HashSet)

Example 88 with JarEntry

use of java.util.jar.JarEntry in project hbase by apache.

the class TestClassFinder method packageAndLoadJar.

/**
   * Makes a jar out of some class files. Unfortunately it's very tedious.
   * @param filesInJar Files created via compileTestClass.
   * @return path to the resulting jar file.
   */
private static String packageAndLoadJar(FileAndPath... filesInJar) throws Exception {
    // First, write the bogus jar file.
    String path = basePath + "jar" + jarCounter.incrementAndGet() + ".jar";
    Manifest manifest = new Manifest();
    manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
    FileOutputStream fos = new FileOutputStream(path);
    JarOutputStream jarOutputStream = new JarOutputStream(fos, manifest);
    // Directory entries for all packages have to be added explicitly for
    // resources to be findable via ClassLoader. Directory entries must end
    // with "/"; the initial one is expected to, also.
    Set<String> pathsInJar = new HashSet<>();
    for (FileAndPath fileAndPath : filesInJar) {
        String pathToAdd = fileAndPath.path;
        while (pathsInJar.add(pathToAdd)) {
            int ix = pathToAdd.lastIndexOf('/', pathToAdd.length() - 2);
            if (ix < 0) {
                break;
            }
            pathToAdd = pathToAdd.substring(0, ix);
        }
    }
    for (String pathInJar : pathsInJar) {
        jarOutputStream.putNextEntry(new JarEntry(pathInJar));
        jarOutputStream.closeEntry();
    }
    for (FileAndPath fileAndPath : filesInJar) {
        File file = fileAndPath.file;
        jarOutputStream.putNextEntry(new JarEntry(fileAndPath.path + file.getName()));
        byte[] allBytes = new byte[(int) file.length()];
        FileInputStream fis = new FileInputStream(file);
        fis.read(allBytes);
        fis.close();
        jarOutputStream.write(allBytes);
        jarOutputStream.closeEntry();
    }
    jarOutputStream.close();
    fos.close();
    // Add the file to classpath.
    File jarFile = new File(path);
    assertTrue(jarFile.exists());
    URLClassLoader urlClassLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
    Method method = URLClassLoader.class.getDeclaredMethod("addURL", new Class[] { URL.class });
    method.setAccessible(true);
    method.invoke(urlClassLoader, new Object[] { jarFile.toURI().toURL() });
    return jarFile.getAbsolutePath();
}
Also used : JarOutputStream(java.util.jar.JarOutputStream) Method(java.lang.reflect.Method) Manifest(java.util.jar.Manifest) JarEntry(java.util.jar.JarEntry) FileInputStream(java.io.FileInputStream) FileOutputStream(java.io.FileOutputStream) URLClassLoader(java.net.URLClassLoader) File(java.io.File) HashSet(java.util.HashSet)

Example 89 with JarEntry

use of java.util.jar.JarEntry in project hadoop by apache.

the class TestFSDownload method createJarFile.

static LocalResource createJarFile(FileContext files, Path p, int len, Random r, LocalResourceVisibility vis) throws IOException, URISyntaxException {
    byte[] bytes = new byte[len];
    r.nextBytes(bytes);
    File archiveFile = new File(p.toUri().getPath() + ".jar");
    archiveFile.createNewFile();
    JarOutputStream out = new JarOutputStream(new FileOutputStream(archiveFile));
    out.putNextEntry(new JarEntry(p.getName()));
    out.write(bytes);
    out.closeEntry();
    out.close();
    LocalResource ret = recordFactory.newRecordInstance(LocalResource.class);
    ret.setResource(URL.fromPath(new Path(p.toString() + ".jar")));
    ret.setSize(len);
    ret.setType(LocalResourceType.ARCHIVE);
    ret.setVisibility(vis);
    ret.setTimestamp(files.getFileStatus(new Path(p.toString() + ".jar")).getModificationTime());
    return ret;
}
Also used : Path(org.apache.hadoop.fs.Path) FileOutputStream(java.io.FileOutputStream) JarOutputStream(java.util.jar.JarOutputStream) JarEntry(java.util.jar.JarEntry) File(java.io.File) LocalResource(org.apache.hadoop.yarn.api.records.LocalResource)

Example 90 with JarEntry

use of java.util.jar.JarEntry in project MinecraftForge by MinecraftForge.

the class FMLSanityChecker method call.

@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;
        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;
}
Also used : InputStream(java.io.InputStream) CodeSource(java.security.CodeSource) JarFile(java.util.jar.JarFile) JarEntry(java.util.jar.JarEntry) Certificate(java.security.cert.Certificate)

Aggregations

JarEntry (java.util.jar.JarEntry)594 JarFile (java.util.jar.JarFile)290 File (java.io.File)217 IOException (java.io.IOException)187 InputStream (java.io.InputStream)134 JarOutputStream (java.util.jar.JarOutputStream)112 FileOutputStream (java.io.FileOutputStream)109 FileInputStream (java.io.FileInputStream)92 URL (java.net.URL)87 JarInputStream (java.util.jar.JarInputStream)87 ArrayList (java.util.ArrayList)67 Manifest (java.util.jar.Manifest)58 JarURLConnection (java.net.JarURLConnection)53 Test (org.junit.Test)39 HashSet (java.util.HashSet)31 ZipEntry (java.util.zip.ZipEntry)31 ZipFile (java.util.zip.ZipFile)30 OutputStream (java.io.OutputStream)29 BufferedInputStream (java.io.BufferedInputStream)26 Enumeration (java.util.Enumeration)26