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.gargoylesoftware.htmlunit.javascript.configuration.JavaScriptConfigurationTest.java

/**
 * Return the classes inside the specified package and its sub-packages.
 * @param klass a class inside that package
 * @return a list of class names/*w  w w. ja va  2  s . c  om*/
 */
public static List<String> getClassesForPackage(final Class<?> klass) {
    final List<String> list = new ArrayList<>();

    File directory = null;
    final String relPath = klass.getName().replace('.', '/') + ".class";

    final URL resource = JavaScriptConfiguration.class.getClassLoader().getResource(relPath);

    if (resource == null) {
        throw new RuntimeException("No resource for " + relPath);
    }
    final String fullPath = resource.getFile();

    try {
        directory = new File(resource.toURI()).getParentFile();
    } catch (final URISyntaxException e) {
        throw new RuntimeException(klass.getName() + " (" + resource + ") does not appear to be a valid URL",
                e);
    } catch (final IllegalArgumentException e) {
        directory = null;
    }

    if (directory != null && directory.exists()) {
        addClasses(directory, klass.getPackage().getName(), list);
    } else {
        try {
            String jarPath = fullPath.replaceFirst("[.]jar[!].*", ".jar").replaceFirst("file:", "");
            if (System.getProperty("os.name").toLowerCase(Locale.ROOT).contains("win")) {
                jarPath = jarPath.replace("%20", " ");
            }
            final JarFile jarFile = new JarFile(jarPath);
            for (final Enumeration<JarEntry> entries = jarFile.entries(); entries.hasMoreElements();) {
                final String entryName = entries.nextElement().getName();
                if (entryName.endsWith(".class")) {
                    list.add(entryName.replace('/', '.').replace('\\', '.').replace(".class", ""));
                }
            }
            jarFile.close();
        } catch (final IOException e) {
            throw new RuntimeException(klass.getPackage().getName() + " does not appear to be a valid package",
                    e);
        }
    }
    return list;
}

From source file:org.eclipse.winery.generators.ia.Generator.java

/**
 * Generates the IA project.//from  www.j a  v a  2s  .  c om
 * 
 * @return The ZIP file containing the maven/eclipse project to be
 *         downloaded by the user.
 */
public File generateProject() {

    try {
        Path workingDirPath = this.workingDir.toPath();
        Files.createDirectories(workingDirPath);

        // directory to store the template files to generate the java files from
        Path javaTemplateDir = workingDirPath.resolve("../java");
        Files.createDirectories(javaTemplateDir);

        // Copy template project and template java files
        String s = this.getClass().getResource("").getPath();
        if (s.contains("jar!")) {
            Generator.logger.trace("we work on a jar file");
            Generator.logger.trace("Location of the current class: {}", s);

            // we have a jar file
            // format: file:/location...jar!...path-in-the-jar
            // we only want to have location :)
            int excl = s.lastIndexOf("!");
            s = s.substring(0, excl);
            s = s.substring("file:".length());

            try (JarFile jf = new JarFile(s);) {
                Enumeration<JarEntry> entries = jf.entries();
                while (entries.hasMoreElements()) {
                    JarEntry je = entries.nextElement();
                    String name = je.getName();
                    if (name.startsWith(Generator.TEMPLATE_PROJECT_FOLDER + "/")
                            && (name.length() > (Generator.TEMPLATE_PROJECT_FOLDER.length() + 1))) {
                        // strip "template/" from the beginning to have paths without "template" starting relatively from the working dir
                        name = name.substring(Generator.TEMPLATE_PROJECT_FOLDER.length() + 1);
                        if (je.isDirectory()) {
                            // directory found
                            Path dir = workingDirPath.resolve(name);
                            Files.createDirectory(dir);
                        } else {
                            Path file = workingDirPath.resolve(name);
                            try (InputStream is = jf.getInputStream(je);) {
                                Files.copy(is, file, StandardCopyOption.REPLACE_EXISTING);
                            }
                        }
                    } else if (name.startsWith(Generator.TEMPLATE_JAVA_FOLDER + "/")
                            && (name.length() > (Generator.TEMPLATE_JAVA_FOLDER.length() + 1))) {
                        if (!je.isDirectory()) {
                            // we copy the file directly into javaTemplateDir
                            File f = new File(name);
                            Path file = javaTemplateDir.resolve(f.getName());
                            try (InputStream is = jf.getInputStream(je);) {
                                Files.copy(is, file, StandardCopyOption.REPLACE_EXISTING);
                            }
                        }
                    }
                }
            }
        } else {
            // we're running in debug mode, we can work on the plain file system
            File templateProjectDir = new File(
                    this.getClass().getResource("/" + Generator.TEMPLATE_PROJECT_FOLDER).getFile());
            FileUtils.copyDirectory(templateProjectDir, this.workingDir);

            File javaTemplatesDir = new File(
                    this.getClass().getResource("/" + Generator.TEMPLATE_JAVA_FOLDER).getFile());
            FileUtils.copyDirectory(javaTemplatesDir, javaTemplateDir.toFile());
        }

        // Create Java Code Folder
        String[] splitPkg = this.javaPackage.split("\\.");
        String javaFolderString = this.workingDir.getAbsolutePath() + File.separator + "src" + File.separator
                + "main" + File.separator + "java";
        for (int i = 0; i < splitPkg.length; i++) {
            javaFolderString += File.separator + splitPkg[i];
        }

        // Copy TEMPLATE_JAVA_ABSTRACT_IA_SERVICE
        Path templateAbstractIAService = javaTemplateDir.resolve(Generator.TEMPLATE_JAVA_ABSTRACT_IA_SERVICE);
        File javaAbstractIAService = new File(javaFolderString + File.separator + "AbstractIAService.java");
        Files.createDirectories(javaAbstractIAService.toPath().getParent());
        Files.copy(templateAbstractIAService, javaAbstractIAService.toPath(),
                StandardCopyOption.REPLACE_EXISTING);

        // Copy and rename TEMPLATE_JAVA_TEMPLATE_SERVICE
        Path templateJavaService = javaTemplateDir.resolve(Generator.TEMPLATE_JAVA_TEMPLATE_SERVICE);
        File javaService = new File(javaFolderString + File.separator + this.name + ".java");
        Files.createDirectories(javaService.toPath().getParent());
        Files.copy(templateJavaService, javaService.toPath(), StandardCopyOption.REPLACE_EXISTING);

        this.generateJavaFile(javaService);
        this.updateFilesRecursively(this.workingDir);
        return this.packageProject();

    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

From source file:JarEntryOutputStream.java

/**
 * @see java.util.jar.JarFile#JarFile(java.io.File)
 *///from   w  ww  . j av a2 s .c  om
public EnhancedJarFile(File file) throws IOException {

    this.jar = new JarFile(file);
}

From source file:org.amanzi.awe.scripting.utils.ScriptUtils.java

/**
 * try determine ruby version jruby.version property was not set. Default to "1.8"
 * /*from   w ww. j a v a 2 s.c o  m*/
 * @throws IOException
 */
private String findJRubyVersion(final String jRubyHome) throws ScriptingException, IOException {
    String result = null;
    JarFile jarFile = null;
    if (jRubyHome.startsWith(PREFIX_FILE) && jRubyHome.endsWith(POSTFIX_JAR)) {
        String path = prepareJarPath(jRubyHome);
        jarFile = new JarFile(path);
    }
    for (String version : JRUBY_VERSIONS) {
        if (checkFileExisting(jarFile, jRubyHome, LIB_PATH + version)) {
            result = version;
            break;
        }
    }
    LOGGER.info("Jruby version set to < " + result + " >");
    return result;
}

From source file:au.com.addstar.objects.Plugin.java

/**
 * Adds the Spigot.ver file to the jar/*from  w w  w.j ava 2s . c o m*/
 *
 * @param ver
 */
public void addSpigotVer(String ver) {
    if (latestFile == null)
        return;
    File newFile = new File(latestFile.getParentFile(),
            SpigotUpdater.getFormat().format(Calendar.getInstance().getTime()) + "-" + ver + "-s.jar");
    File spigotFile = new File(latestFile.getParentFile(), "spigot.ver");
    if (spigotFile.exists())
        FileUtils.deleteQuietly(spigotFile);
    try {
        JarFile oldjar = new JarFile(latestFile);
        if (oldjar.getEntry("spigot.ver") != null)
            return;
        JarOutputStream tempJarOutputStream = new JarOutputStream(new FileOutputStream(newFile));
        try (Writer wr = new FileWriter(spigotFile); BufferedWriter writer = new BufferedWriter(wr)) {
            writer.write(ver);
            writer.newLine();
        }
        try (FileInputStream stream = new FileInputStream(spigotFile)) {
            byte[] buffer = new byte[1024];
            int bytesRead = 0;
            JarEntry je = new JarEntry(spigotFile.getName());
            tempJarOutputStream.putNextEntry(je);
            while ((bytesRead = stream.read(buffer)) != -1) {
                tempJarOutputStream.write(buffer, 0, bytesRead);
            }
            stream.close();
        }
        Enumeration jarEntries = oldjar.entries();
        while (jarEntries.hasMoreElements()) {
            JarEntry entry = (JarEntry) jarEntries.nextElement();
            InputStream entryInputStream = oldjar.getInputStream(entry);
            tempJarOutputStream.putNextEntry(entry);
            byte[] buffer = new byte[1024];
            int bytesRead = 0;
            while ((bytesRead = entryInputStream.read(buffer)) != -1) {
                tempJarOutputStream.write(buffer, 0, bytesRead);
            }
            entryInputStream.close();
        }
        tempJarOutputStream.close();
        oldjar.close();
        FileUtils.deleteQuietly(latestFile);
        FileUtils.deleteQuietly(spigotFile);
        FileUtils.moveFile(newFile, latestFile);
        latestFile = newFile;

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

From source file:com.netflix.nicobar.core.archive.JarScriptArchive.java

protected JarScriptArchive(ScriptModuleSpec moduleSpec, Path jarPath, String moduleSpecEntry, long createTime)
        throws IOException {
    this.createTime = createTime;
    this.moduleSpec = Objects.requireNonNull(moduleSpec, "moduleSpec");
    Objects.requireNonNull(jarPath, "jarFile");
    if (!jarPath.isAbsolute())
        throw new IllegalArgumentException("jarPath must be absolute.");

    // initialize the index
    JarFile jarFile = new JarFile(jarPath.toFile());
    Set<String> indexBuilder;
    try {/*from w w  w  .java 2 s . c om*/
        Enumeration<JarEntry> jarEntries = jarFile.entries();
        indexBuilder = new HashSet<String>();
        while (jarEntries.hasMoreElements()) {
            JarEntry jarEntry = jarEntries.nextElement();
            // Skip adding moduleSpec to archive entries
            if (jarEntry.getName().equals(moduleSpecEntry)) {
                continue;
            }

            if (!jarEntry.isDirectory()) {
                indexBuilder.add(jarEntry.getName());
            }
        }
    } finally {
        jarFile.close();
    }

    entryNames = Collections.unmodifiableSet(indexBuilder);

    rootUrl = jarPath.toUri().toURL();
}

From source file:com.rbmhtechnology.apidocserver.controller.ApiDocController.java

private void serveFileFromJarFile(HttpServletResponse response, File jar, String subPath) throws IOException {
    JarFile jarFile = null;/*from  w  ww .j av a2s . co  m*/
    try {
        jarFile = new JarFile(jar);
        JarEntry entry = jarFile.getJarEntry(subPath);

        if (entry == null) {
            response.sendError(404);
            return;
        }

        // fallback for requesting a directory without a trailing /
        // this leads to a jarentry which is not null, and not a directory and of size 0
        // this shouldn't be
        if (!entry.isDirectory() && entry.getSize() == 0) {
            if (!subPath.endsWith("/")) {
                JarEntry entryWithSlash = jarFile.getJarEntry(subPath + "/");
                if (entryWithSlash != null && entryWithSlash.isDirectory()) {
                    entry = entryWithSlash;
                }
            }
        }

        if (entry.isDirectory()) {
            for (String indexFile : DEFAULT_INDEX_FILES) {
                entry = jarFile.getJarEntry((subPath.endsWith("/") ? subPath : subPath + "/") + indexFile);
                if (entry != null) {
                    break;
                }
            }
        }

        if (entry == null) {
            response.sendError(404);
            return;
        }

        response.setContentLength((int) entry.getSize());
        String mimetype = getMimeType(entry.getName());
        response.setContentType(mimetype);
        InputStream input = jarFile.getInputStream(entry);
        try {
            ByteStreams.copy(input, response.getOutputStream());
        } finally {
            input.close();
        }
    } finally {
        if (jarFile != null) {
            jarFile.close();
        }
    }
}

From source file:org.elasticsearch.bootstrap.JarHell.java

/**
 * Checks the set of URLs for duplicate classes
 * @throws IllegalStateException if jar hell was found
 *//*  w  w  w.j av a 2  s.c om*/
@SuppressForbidden(reason = "needs JarFile for speed, just reading entries")
public static void checkJarHell(URL urls[]) throws Exception {
    ESLogger logger = Loggers.getLogger(JarHell.class);
    // we don't try to be sneaky and use deprecated/internal/not portable stuff
    // like sun.boot.class.path, and with jigsaw we don't yet have a way to get
    // a "list" at all. So just exclude any elements underneath the java home
    String javaHome = System.getProperty("java.home");
    logger.debug("java.home: {}", javaHome);
    final Map<String, Path> clazzes = new HashMap<>(32768);
    Set<Path> seenJars = new HashSet<>();
    for (final URL url : urls) {
        final Path path = PathUtils.get(url.toURI());
        // exclude system resources
        if (path.startsWith(javaHome)) {
            logger.debug("excluding system resource: {}", path);
            continue;
        }
        if (path.toString().endsWith(".jar")) {
            if (!seenJars.add(path)) {
                logger.debug("excluding duplicate classpath element: {}", path);
                continue; // we can't fail because of sheistiness with joda-time
            }
            logger.debug("examining jar: {}", path);
            try (JarFile file = new JarFile(path.toString())) {
                Manifest manifest = file.getManifest();
                if (manifest != null) {
                    checkManifest(manifest, path);
                }
                // inspect entries
                Enumeration<JarEntry> elements = file.entries();
                while (elements.hasMoreElements()) {
                    String entry = elements.nextElement().getName();
                    if (entry.endsWith(".class")) {
                        // for jar format, the separator is defined as /
                        entry = entry.replace('/', '.').substring(0, entry.length() - 6);
                        checkClass(clazzes, entry, path);
                    }
                }
            }
        } else {
            logger.debug("examining directory: {}", path);
            // case for tests: where we have class files in the classpath
            final Path root = PathUtils.get(url.toURI());
            final String sep = root.getFileSystem().getSeparator();
            Files.walkFileTree(root, new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    String entry = root.relativize(file).toString();
                    if (entry.endsWith(".class")) {
                        // normalize with the os separator
                        entry = entry.replace(sep, ".").substring(0, entry.length() - 6);
                        checkClass(clazzes, entry, path);
                    }
                    return super.visitFile(file, attrs);
                }
            });
        }
    }
}

From source file:com.photon.phresco.util.PhrescoDynamicLoader.java

public InputStream getResourceAsStream(String fileName) throws PhrescoException {
    InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream(fileName);
    if (resourceAsStream != null) {
        return resourceAsStream;
    }/*from  w ww.j  av  a2s  .com*/
    List<Artifact> artifacts = new ArrayList<Artifact>();
    Artifact foundArtifact = null;
    String destFile = "";
    JarFile jarfile = null;
    for (ArtifactGroup plugin : plugins) {
        List<ArtifactInfo> versions = plugin.getVersions();
        for (ArtifactInfo artifactInfo : versions) {

            foundArtifact = createArtifact(plugin.getGroupId(), plugin.getArtifactId(), "jar",
                    artifactInfo.getVersion());
            artifacts.add(foundArtifact);
        }
    }
    try {
        URL artifactURLs = MavenArtifactResolver.resolveSingleArtifact(repoInfo.getGroupRepoURL(),
                repoInfo.getRepoUserName(), repoInfo.getRepoPassword(), artifacts);
        File jarFile = new File(artifactURLs.toURI());
        if (jarFile.getName().equals(foundArtifact.getArtifactId() + "-" + foundArtifact.getVersion() + "."
                + foundArtifact.getType())) {
            jarfile = new JarFile(jarFile);
            for (Enumeration<JarEntry> em = jarfile.entries(); em.hasMoreElements();) {
                JarEntry jarEntry = em.nextElement();
                if (jarEntry.getName().endsWith(fileName)) {
                    destFile = jarEntry.getName();
                }
            }
        }
        if (StringUtils.isNotEmpty(destFile)) {
            ZipEntry entry = jarfile.getEntry(destFile);
            return jarfile.getInputStream(entry);
        }
    } catch (Exception e) {
        e.printStackTrace();
        throw new PhrescoException(e);
    }
    return null;
}

From source file:org.b3log.latke.ioc.ClassPathResolver.java

/**
 * scan the jar to get the URLS of the Classes.
 *
 * @param rootDirResource which is "Jar"
 * @param subPattern      subPattern/*  ww  w .  j  a v  a 2s .  co m*/
 * @return the URLs of all the matched classes
 */
private static Collection<? extends URL> doFindPathMatchingJarResources(final URL rootDirResource,
        final String subPattern) {

    final Set<URL> result = new LinkedHashSet<URL>();

    JarFile jarFile = null;
    String jarFileUrl;
    String rootEntryPath = null;
    URLConnection con;
    boolean newJarFile = false;

    try {
        con = rootDirResource.openConnection();

        if (con instanceof JarURLConnection) {
            final JarURLConnection jarCon = (JarURLConnection) con;

            jarCon.setUseCaches(false);
            jarFile = jarCon.getJarFile();
            jarFileUrl = jarCon.getJarFileURL().toExternalForm();
            final JarEntry jarEntry = jarCon.getJarEntry();

            rootEntryPath = jarEntry != null ? jarEntry.getName() : "";
        } else {
            // No JarURLConnection -> need to resort to URL file parsing.
            // We'll assume URLs of the format "jar:path!/entry", with the
            // protocol
            // being arbitrary as long as following the entry format.
            // We'll also handle paths with and without leading "file:"
            // prefix.
            final String urlFile = rootDirResource.getFile();
            final int separatorIndex = urlFile.indexOf(JAR_URL_SEPARATOR);

            if (separatorIndex != -1) {
                jarFileUrl = urlFile.substring(0, separatorIndex);
                rootEntryPath = urlFile.substring(separatorIndex + JAR_URL_SEPARATOR.length());
                jarFile = getJarFile(jarFileUrl);
            } else {
                jarFile = new JarFile(urlFile);
                jarFileUrl = urlFile;
                rootEntryPath = "";
            }
            newJarFile = true;

        }

    } catch (final IOException e) {
        LOGGER.log(Level.ERROR, "reslove jar File error", e);
        return result;
    }
    try {
        if (!"".equals(rootEntryPath) && !rootEntryPath.endsWith("/")) {
            // Root entry path must end with slash to allow for proper
            // matching.
            // The Sun JRE does not return a slash here, but BEA JRockit
            // does.
            rootEntryPath = rootEntryPath + "/";
        }
        for (final Enumeration<JarEntry> entries = jarFile.entries(); entries.hasMoreElements();) {
            final JarEntry entry = (JarEntry) entries.nextElement();
            final String entryPath = entry.getName();

            String relativePath = null;

            if (entryPath.startsWith(rootEntryPath)) {
                relativePath = entryPath.substring(rootEntryPath.length());

                if (AntPathMatcher.match(subPattern, relativePath)) {
                    if (relativePath.startsWith("/")) {
                        relativePath = relativePath.substring(1);
                    }
                    result.add(new URL(rootDirResource, relativePath));
                }
            }
        }
        return result;
    } catch (final IOException e) {
        LOGGER.log(Level.ERROR, "parse the JarFile error", e);
    } finally {
        // Close jar file, but only if freshly obtained -
        // not from JarURLConnection, which might cache the file reference.
        if (newJarFile) {
            try {
                jarFile.close();
            } catch (final IOException e) {
                LOGGER.log(Level.WARN, " occur error when closing jarFile", e);
            }
        }
    }
    return result;
}