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:com.betfair.cougar.test.socket.app.JarRunner.java

private void init() throws IOException {
    JarFile jar = new JarFile(jarFile);
    ZipEntry entry = jar.getEntry("META-INF/maven/com.betfair.cougar/socket-tester/pom.properties");
    Properties props = new Properties();
    props.load(jar.getInputStream(entry));
    version = props.getProperty("version");
    jar.close();/*  w ww. j  a va2  s .  com*/
}

From source file:com.seleniumtests.util.FileUtility.java

public static void extractJar(final String storeLocation, final Class<?> clz) throws IOException {
    File firefoxProfile = new File(storeLocation);
    String location = clz.getProtectionDomain().getCodeSource().getLocation().getFile();

    try (JarFile jar = new JarFile(location);) {
        logger.info("Extracting jar file::: " + location);
        firefoxProfile.mkdir();/* w w  w  .j a va2s . c o  m*/

        Enumeration<?> jarFiles = jar.entries();
        while (jarFiles.hasMoreElements()) {
            ZipEntry entry = (ZipEntry) jarFiles.nextElement();
            String currentEntry = entry.getName();
            File destinationFile = new File(storeLocation, currentEntry);
            File destinationParent = destinationFile.getParentFile();

            // create the parent directory structure if required
            destinationParent.mkdirs();
            if (!entry.isDirectory()) {
                BufferedInputStream is = new BufferedInputStream(jar.getInputStream(entry));
                int currentByte;

                // buffer for writing file
                byte[] data = new byte[BUFFER];

                // write the current file to disk
                try (FileOutputStream fos = new FileOutputStream(destinationFile);) {
                    BufferedOutputStream destination = new BufferedOutputStream(fos, BUFFER);

                    // read and write till last byte
                    while ((currentByte = is.read(data, 0, BUFFER)) != -1) {
                        destination.write(data, 0, currentByte);
                    }

                    destination.flush();
                    destination.close();
                    is.close();
                }
            }
        }
    }

    FileUtils.deleteDirectory(new File(storeLocation + "\\META-INF"));
    if (OSUtility.isWindows()) {
        new File(storeLocation + "\\" + clz.getCanonicalName().replaceAll("\\.", "\\\\") + ".class").delete();
    } else {
        new File(storeLocation + "/" + clz.getCanonicalName().replaceAll("\\.", "/") + ".class").delete();
    }
}

From source file:org.apache.servicemix.war.deployer.WarDeploymentListener.java

public boolean canHandle(File artifact) {
    try {//from   www .  j a  v a2 s  .  c  o m
        JarFile jar = new JarFile(artifact);
        JarEntry entry = jar.getJarEntry("WEB-INF/web.xml");
        // Only handle WAR artifacts
        if (entry == null) {
            return false;
        }
        // Only handle non OSGi bundles
        Manifest m = jar.getManifest();
        if (m.getMainAttributes().getValue(new Attributes.Name("Bundle-SymbolicName")) != null
                && m.getMainAttributes().getValue(new Attributes.Name("Bundle-Version")) != null) {
            return false;
        }
        return true;
    } catch (Exception e) {
        return false;
    }
}

From source file:eu.leads.processor.planner.ClassUtil.java

private static void findClasses(Set<Class> matchedClassSet, File root, File file, boolean includeJars,
        Class type, String packageFilter) {
    if (file.isDirectory()) {
        for (File child : file.listFiles()) {
            findClasses(matchedClassSet, root, child, includeJars, type, packageFilter);
        }/*from   w  w  w  . ja  v a  2  s.c  o  m*/
    } else {
        if (file.getName().toLowerCase().endsWith(".jar") && includeJars) {
            JarFile jar = null;
            try {
                jar = new JarFile(file);
            } catch (Exception ex) {
                LOG.error(ex.getMessage(), ex);
                return;
            }
            Enumeration<JarEntry> entries = jar.entries();
            while (entries.hasMoreElements()) {
                JarEntry entry = entries.nextElement();
                String name = entry.getName();
                int extIndex = name.lastIndexOf(".class");
                if (extIndex > 0) {
                    String qualifiedClassName = name.substring(0, extIndex).replace("/", ".");
                    if (qualifiedClassName.indexOf(packageFilter) >= 0 && !isTestClass(qualifiedClassName)) {
                        try {
                            Class clazz = Class.forName(qualifiedClassName);

                            if (!clazz.isInterface() && isMatch(type, clazz)) {
                                matchedClassSet.add(clazz);
                            }
                        } catch (ClassNotFoundException e) {
                            LOG.error(e.getMessage(), e);
                        }
                    }
                }
            }
        } else if (file.getName().toLowerCase().endsWith(".class")) {
            String qualifiedClassName = createClassName(root, file);
            // if (qualifiedClassName.indexOf(packageFilter) >= 0 && !isTestClass(qualifiedClassName)) {
            try {
                Class clazz = Class.forName(qualifiedClassName);
                if (!clazz.isInterface() && isMatch(type, clazz)) {
                    matchedClassSet.add(clazz);
                }
            } catch (ClassNotFoundException e) {
                LOG.error(e.getMessage(), e);
            }
            // }
        }
    }
}

From source file:com.kantenkugel.discordbot.jdocparser.JDocParser.java

static Map<String, ClassDocumentation> parse() {
    JDocUtil.LOG.debug("Parsing jda-docs-files");
    Map<String, ClassDocumentation> docs = new HashMap<>();
    try (final JarFile file = new JarFile(JDocUtil.LOCAL_DOC_PATH.toFile())) {
        file.stream().filter(entry -> !entry.isDirectory() && entry.getName().startsWith(JDocUtil.JDA_CODE_BASE)
                && entry.getName().endsWith(".html")).forEach(entry -> {
                    try {
                        parse(JDocUtil.JDOCBASE, entry.getName(), file.getInputStream(entry), docs);
                    } catch (final IOException e) {
                        JDocUtil.LOG.error("Error while parsing doc file {}", entry.getName(), e);
                    }/*w ww.  ja v a2s.  c om*/
                });
        JDocUtil.LOG.debug("Done parsing jda-docs-files");
    } catch (final Exception e) {
        JDocUtil.LOG.error("Error reading the jdoc jarfile", e);
    }
    return docs;
}

From source file:net.fabricmc.installer.installer.ClientInstaller.java

public static void install(File mcDir, String version, IInstallerProgress progress, File fabricJar)
        throws IOException {
    progress.updateProgress(Translator.getString("gui.installing") + ": " + version, 0);
    JarFile jarFile = new JarFile(fabricJar);
    Attributes attributes = jarFile.getManifest().getMainAttributes();

    String id = "fabric-" + attributes.getValue("FabricVersion");

    System.out.println(Translator.getString("gui.installing") + " " + id);
    File versionsFolder = new File(mcDir, "versions");
    File fabricVersionFolder = new File(versionsFolder, id);
    File mcVersionFolder = new File(versionsFolder, version);
    File fabricJsonFile = new File(fabricVersionFolder, id + ".json");

    File tempWorkDir = new File(fabricVersionFolder, "temp");
    ZipUtil.unpack(fabricJar, tempWorkDir, name -> {
        if (name.startsWith(Reference.INSTALLER_METADATA_FILENAME)) {
            return name;
        } else {//from  w w w .j  a  v  a 2s .c  o  m
            return null;
        }
    });
    InstallerMetadata metadata = new InstallerMetadata(tempWorkDir);

    File mcJarFile = new File(mcVersionFolder, version + ".jar");
    if (fabricVersionFolder.exists()) {
        progress.updateProgress(Translator.getString("install.client.removeOld"), 10);
        FileUtils.deleteDirectory(fabricVersionFolder);
    }
    fabricVersionFolder.mkdirs();

    progress.updateProgress(Translator.getString("install.client.createJson"), 20);

    String mcJson = FileUtils.readFileToString(mcJarFile, Charset.defaultCharset());

    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    JsonObject versionJson = new JsonObject();
    versionJson.addProperty("id", id);
    versionJson.addProperty("type", "release");
    versionJson.addProperty("time", Utils.ISO_8601.format(fabricJar.lastModified()));
    versionJson.addProperty("releaseTime", Utils.ISO_8601.format(fabricJar.lastModified()));
    versionJson.addProperty("mainClass", metadata.getMainClass());
    versionJson.addProperty("inheritsFrom", version);

    JsonArray gameArgs = new JsonArray();
    JsonObject arguments = new JsonObject();

    List<String> metadataTweakers = metadata.getTweakers("client", "common");
    if (metadataTweakers.size() > 1) {
        throw new RuntimeException("Not supporting > 1 tweaker yet!");
    }

    metadata.getArguments("client", "common").forEach(gameArgs::add);
    gameArgs.add("--tweakClass");
    gameArgs.add(metadataTweakers.get(0));

    arguments.add("game", gameArgs);
    versionJson.add("arguments", arguments);

    JsonArray libraries = new JsonArray();

    addDep(Reference.PACKAGE_FABRIC + ":" + Reference.NAME_FABRIC_LOADER + ":"
            + attributes.getValue("FabricVersion"), "http://maven.modmuss50.me/", libraries);

    for (InstallerMetadata.LibraryEntry entry : metadata.getLibraries("client", "common")) {
        libraries.add(entry.toVanillaEntry());
    }

    versionJson.add("libraries", libraries);

    FileUtils.write(fabricJsonFile, gson.toJson(versionJson), "UTF-8");
    jarFile.close();
    progress.updateProgress(Translator.getString("install.client.cleanDir"), 90);
    FileUtils.deleteDirectory(tempWorkDir);

    progress.updateProgress(Translator.getString("install.success"), 100);
}

From source file:com.aliyun.odps.local.common.utils.ArchiveUtils.java

@SuppressWarnings("rawtypes")
public static void unJar(File jarFile, File toDir) throws IOException {
    JarFile jar = new JarFile(jarFile);
    try {//  ww  w  . j  a  va2  s.c om
        Enumeration entries = jar.entries();
        while (entries.hasMoreElements()) {
            JarEntry entry = (JarEntry) entries.nextElement();
            if (!entry.isDirectory()) {
                InputStream in = jar.getInputStream(entry);
                try {
                    File file = new File(toDir, entry.getName());
                    if (!file.getParentFile().mkdirs()) {
                        if (!file.getParentFile().isDirectory()) {
                            throw new IOException("Mkdirs failed to create " + file.getParentFile().toString());
                        }
                    }
                    OutputStream out = new FileOutputStream(file);
                    try {
                        byte[] buffer = new byte[8192];
                        int i;
                        while ((i = in.read(buffer)) != -1) {
                            out.write(buffer, 0, i);
                        }
                    } finally {
                        out.close();
                    }
                } finally {
                    in.close();
                }
            }
        }
    } finally {
        jar.close();
    }
}

From source file:com.l2jfree.versionning.Version.java

public void loadInformation(Class<?> c) {
    File jarName = null;/*from w  w w  . j a v  a2s.co m*/
    try {
        jarName = Locator.getClassSource(c);
        try (JarFile jarFile = new JarFile(jarName);) {
            final Attributes attrs = jarFile.getManifest().getMainAttributes();

            setBuildTime(attrs);

            setBuildJdk(attrs);

            setRevisionNumber(attrs);

            setVersionNumber(attrs);
        }
    } catch (IOException e) {
        if (_log.isErrorEnabled())
            _log.error(
                    "Unable to get Soft information\nFile name '"
                            + (jarName == null ? "null" : jarName.getAbsolutePath()) + "' isn't a valid jar",
                    e);
    }

}

From source file:net.fabricmc.installer.installer.LocalVersionInstaller.java

public static void installServer(File mcDir, IInstallerProgress progress) throws Exception {
    JFileChooser fc = new JFileChooser();
    fc.setDialogTitle(Translator.getString("install.client.selectCustomJar"));
    fc.setFileFilter(new FileNameExtensionFilter("Jar Files", "jar"));
    if (fc.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
        File inputFile = fc.getSelectedFile();

        JarFile jarFile = new JarFile(inputFile);
        Attributes attributes = jarFile.getManifest().getMainAttributes();
        String fabricVersion = attributes.getValue("FabricVersion");
        jarFile.close();/*from   www  .j  a va  2s. co m*/
        File fabricJar = new File(mcDir, "fabric-" + fabricVersion + ".jar");
        if (fabricJar.exists()) {
            fabricJar.delete();
        }
        FileUtils.copyFile(inputFile, fabricJar);
        ServerInstaller.install(mcDir, fabricVersion, progress, fabricJar);
    } else {
        throw new Exception("Failed to find jar");
    }

}

From source file:io.reactiverse.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 ww .j  a  v  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")) {
        try (JarFile 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;
        }

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

        return !found.isEmpty();
    }

    return false;
}