Example usage for java.util.jar JarFile JarFile

List of usage examples for java.util.jar JarFile JarFile

Introduction

In this page you can find the example usage for java.util.jar JarFile JarFile.

Prototype

public JarFile(File file) throws IOException 

Source Link

Document

Creates a new JarFile to read from the specified File object.

Usage

From source file:azkaban.jobtype.connectors.teradata.TeraDataWalletInitializer.java

/**
 * As of TDCH 1.4.1, integration with Teradata wallet only works with hadoop jar command line command.
 * This is mainly because TDCH depends on the behavior of hadoop jar command line which extracts jar file
 * into hadoop tmp folder.//from  w  ww . ja va  2  s .  c  om
 *
 * This method will extract tdchJarfile and place it into temporary folder, and also add jvm shutdown hook
 * to delete the directory when JVM shuts down.
 * @param tdchJarFile TDCH jar file.
 */
public static void initialize(File tmpDir, File tdchJarFile) {
    synchronized (TeraDataWalletInitializer.class) {
        if (tdchJarExtractedDir != null) {
            return;
        }

        if (tdchJarFile == null) {
            throw new IllegalArgumentException("TDCH jar file cannot be null.");
        }
        if (!tdchJarFile.exists()) {
            throw new IllegalArgumentException(
                    "TDCH jar file does not exist. " + tdchJarFile.getAbsolutePath());
        }
        try {
            //Extract TDCH jar.
            File unJarDir = createUnjarDir(
                    new File(tmpDir.getAbsolutePath() + File.separator + UNJAR_DIR_NAME));
            JarFile jar = new JarFile(tdchJarFile);
            Enumeration<JarEntry> enumEntries = jar.entries();

            while (enumEntries.hasMoreElements()) {
                JarEntry srcFile = enumEntries.nextElement();
                File destFile = new File(unJarDir + File.separator + srcFile.getName());
                if (srcFile.isDirectory()) { // if its a directory, create it
                    destFile.mkdir();
                    continue;
                }

                InputStream is = jar.getInputStream(srcFile);
                BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(destFile));
                IOUtils.copy(is, os);
                close(os);
                close(is);
            }
            jar.close();
            tdchJarExtractedDir = unJarDir;
        } catch (IOException e) {
            throw new RuntimeException("Failed while extracting TDCH jar file.", e);
        }
    }
    logger.info("TDCH jar has been extracted into directory: " + tdchJarExtractedDir.getAbsolutePath());
}

From source file:com.samczsun.helios.handler.addons.JarLauncher.java

@Override
public void run(File file) {
    JarFile jarFile = null;// ww w.j  a va2  s. co  m
    InputStream inputStream = null;
    try {
        System.out.println("Loading addon: " + file.getAbsolutePath());
        jarFile = new JarFile(file);
        ZipEntry entry = jarFile.getEntry("addon.json");
        if (entry != null) {
            inputStream = jarFile.getInputStream(entry);
            JsonObject jsonObject = JsonObject
                    .readFrom(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
            String main = jsonObject.get("main").asString();
            URL[] url = new URL[] { file.toURI().toURL() };
            ClassLoader classLoader = AccessController
                    .doPrivileged((PrivilegedAction<ClassLoader>) () -> new URLClassLoader(url,
                            Helios.class.getClassLoader()));
            Class<?> clazz = Class.forName(main, true, classLoader);
            if (Addon.class.isAssignableFrom(clazz)) {
                Addon addon = Addon.class.cast(clazz.newInstance());
                registerAddon(addon.getName(), addon);
            } else {
                throw new IllegalArgumentException("Addon main does not extend Addon");
            }
        } else {
            throw new IllegalArgumentException("No addon.json found");
        }
    } catch (Exception e) {
        ExceptionHandler.handle(e);
    } finally {
        IOUtils.closeQuietly(jarFile);
        IOUtils.closeQuietly(inputStream);
    }
}

From source file:io.fabric8.vertx.maven.plugin.utils.WebJars.java

/**
 * Checks whether the given file is a WebJar or not (http://www.webjars.org/documentation).
 * The check is based on the presence of {@literal META-INF/resources/webjars/} directory in the jar file.
 *
 * @param file the file./*from   w  w  w.j av  a 2  s.  c  o  m*/
 * @return {@literal true} if it's a bundle, {@literal false} otherwise.
 */
public static boolean isWebJar(Log log, File file) {
    if (file == null) {
        return false;
    }
    Set<String> found = new LinkedHashSet<>();
    if (file.isFile() && file.getName().endsWith(".jar")) {
        JarFile jar = null;
        try {
            jar = new JarFile(file);

            // Fast return if the base structure is not there
            if (jar.getEntry(WEBJAR_LOCATION) == null) {
                return false;
            }

            Enumeration<JarEntry> entries = jar.entries();
            while (entries.hasMoreElements()) {
                JarEntry entry = entries.nextElement();
                Matcher matcher = WEBJAR_REGEX.matcher(entry.getName());
                if (matcher.matches()) {
                    found.add(matcher.group(1) + "-" + matcher.group(2));
                }
            }
        } catch (IOException e) {
            log.error("Cannot check if the file " + file.getName() + " is a webjar, cannot open it", e);
            return false;
        } finally {
            final JarFile finalJar = jar;
            IOUtils.closeQuietly(() -> {
                if (finalJar != null) {
                    finalJar.close();
                }
            });
        }

        for (String lib : found) {
            log.info("Web Library found in " + file.getName() + " : " + lib);
        }

        return !found.isEmpty();
    }

    return false;
}

From source file:com.navercorp.pinpoint.bootstrap.java9.module.JarFileAnalyzerTest.java

@Test
public void packageAnalyzer() throws IOException {
    URL url = CodeSourceUtils.getCodeLocation(Logger.class);

    JarFile jarFile = new JarFile(url.getFile());
    logger.debug("jarFile:{}", jarFile.getName());

    PackageAnalyzer packageAnalyzer = new JarFileAnalyzer(jarFile);
    PackageInfo packageInfo = packageAnalyzer.analyze();
    Set<String> packageSet = packageInfo.getPackage();

    logger.debug("package:{}", packageSet);

    Assert.assertEquals(packageSet, SLF4J_API_PACKAGE);
}

From source file:com.heliosdecompiler.helios.controller.addons.JarLauncher.java

@Override
public void run(File file) {
    JarFile jarFile = null;/* www  . j av a2 s  . c  o m*/
    InputStream inputStream = null;
    try {
        System.out.println("Loading addon: " + file.getAbsolutePath());
        jarFile = new JarFile(file);
        ZipEntry entry = jarFile.getEntry("addon.json");
        if (entry != null) {
            inputStream = jarFile.getInputStream(entry);
            JsonObject jsonObject = new Gson()
                    .fromJson(new InputStreamReader(inputStream, StandardCharsets.UTF_8), JsonObject.class);
            String main = jsonObject.get("main").getAsString();
            URL[] url = new URL[] { file.toURI().toURL() };
            ClassLoader classLoader = AccessController
                    .doPrivileged((PrivilegedAction<ClassLoader>) () -> new URLClassLoader(url,
                            Helios.class.getClassLoader()));
            Class<?> clazz = Class.forName(main, true, classLoader);
            if (Addon.class.isAssignableFrom(clazz)) {
                Addon addon = Addon.class.cast(clazz.newInstance());
                //                    registerAddon(addon.getName(), addon);
            } else {
                throw new IllegalArgumentException("Addon main does not extend Addon");
            }
        } else {
            throw new IllegalArgumentException("No addon.json found");
        }
    } catch (Exception e) {
        ExceptionHandler.handle(e);
    } finally {
        IOUtils.closeQuietly(jarFile);
        IOUtils.closeQuietly(inputStream);
    }
}

From source file:com.heliosdecompiler.helios.handler.addons.JarLauncher.java

@Override
public void run(File file) {
    JarFile jarFile = null;//w ww.  j av a2 s. c  om
    InputStream inputStream = null;
    try {
        System.out.println("Loading addon: " + file.getAbsolutePath());
        jarFile = new JarFile(file);
        ZipEntry entry = jarFile.getEntry("addon.json");
        if (entry != null) {
            inputStream = jarFile.getInputStream(entry);
            JsonObject jsonObject = Json.parse(new InputStreamReader(inputStream, StandardCharsets.UTF_8))
                    .asObject();
            String main = jsonObject.get("main").asString();
            URL[] url = new URL[] { file.toURI().toURL() };
            ClassLoader classLoader = AccessController
                    .doPrivileged((PrivilegedAction<ClassLoader>) () -> new URLClassLoader(url,
                            Helios.class.getClassLoader()));
            Class<?> clazz = Class.forName(main, true, classLoader);
            if (Addon.class.isAssignableFrom(clazz)) {
                Addon addon = Addon.class.cast(clazz.newInstance());
                registerAddon(addon.getName(), addon);
            } else {
                throw new IllegalArgumentException("Addon main does not extend Addon");
            }
        } else {
            throw new IllegalArgumentException("No addon.json found");
        }
    } catch (Exception e) {
        ExceptionHandler.handle(e);
    } finally {
        IOUtils.closeQuietly(jarFile);
        IOUtils.closeQuietly(inputStream);
    }
}

From source file:org.adscale.testtodoc.TestToDoc.java

void handleJar(String jarName, List<String> tests) throws Exception {
    JarFile jarFile = new JarFile(jarName);
    Enumeration<JarEntry> entries = jarFile.entries();
    URLClassLoader loader = createClassLoader(jarName);
    while (entries.hasMoreElements()) {
        JarEntry jarEntry = entries.nextElement();
        handleEntry(tests, loader, jarEntry);
    }//from  w  w  w.ja v a  2  s  .c o  m
}

From source file:i18nplugin.TranslationNode.java

/**
 * Create Tree//w  w  w.  jav a2s .c  o m
 * @param string Name of Tree-Node
 * @param file Jar-File with Properties
 */
public TranslationNode(String string, File file) {
    super(string);

    try {
        JarFile jarfile = new JarFile(file);

        Enumeration<JarEntry> entries = jarfile.entries();

        while (entries.hasMoreElements()) {
            JarEntry entry = entries.nextElement();

            if (entry.getName().endsWith(".properties")) {
                String name = entry.getName();

                name = name.substring(0, name.length() - 11);

                if (name.indexOf('/') >= 0) {
                    String dir = StringUtils.substringBeforeLast(name, "/");

                    if (dir.contains("/")) {
                        dir = StringUtils.substringAfterLast(dir, "/");
                    }

                    name = StringUtils.substringAfterLast(name, "/");

                    if (name.equals(dir)) {
                        addEntry(jarfile, entry);
                    }
                }
            }
        }

    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:de.Keyle.MyPet.util.locale.Locales.java

public Locales() {
    File pluginFile = MyPetPlugin.getPlugin().getFile();
    try {/*www . ja  v  a 2s . c  o  m*/
        jarFile = new JarFile(pluginFile);
    } catch (IOException ignored) {
        jarFile = null;
    }
    loadLocale("en");
    latestMyPetLocales = this;
}

From source file:de.micromata.tpsb.doc.sources.JarSourceFileRepository.java

@Override
public Collection<JavaSourceFileHolder> getSources() {
    List<JavaSourceFileHolder> fileContentList = new ArrayList<JavaSourceFileHolder>();

    for (String jarFileName : getLocations()) {
        try {/*from ww w. ja  va2 s. c o  m*/
            JarFile jarFile;
            jarFile = new JarFile(jarFileName);
            Enumeration<? extends ZipEntry> jarEntryEnum = jarFile.entries();

            while (jarEntryEnum.hasMoreElements()) {
                JarEntry jarEntry = (JarEntry) jarEntryEnum.nextElement();

                // nur Java-Dateien beachten
                if (jarEntry.isDirectory() || StringUtils.endsWith(jarEntry.getName(), ".java") == false) {
                    continue;
                }

                String javaFilename = jarEntry.getName();
                String javaFileContent = getContents(jarFile, jarEntry);

                if (StringUtils.isBlank(javaFileContent) == true) {
                    continue;
                }
                JavaSourceFileHolder fileHolder = new JavaSourceFileHolder(javaFilename, javaFileContent);
                fileHolder.setSource(Source.Jar);
                fileHolder.setOrigin(jarFileName);
                fileContentList.add(fileHolder);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return fileContentList;
}