Example usage for java.util.jar JarEntry isDirectory

List of usage examples for java.util.jar JarEntry isDirectory

Introduction

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

Prototype

public boolean isDirectory() 

Source Link

Document

Returns true if this is a directory entry.

Usage

From source file:com.speed.ob.api.ClassStore.java

public void dump(File in, File out, Config config) throws IOException {
    if (in.isDirectory()) {
        for (ClassNode node : nodes()) {
            String[] parts = node.name.split("\\.");
            String dirName = node.name.substring(0, node.name.lastIndexOf("."));
            dirName = dirName.replace(".", "/");
            File dir = new File(out, dirName);
            if (!dir.exists()) {
                if (!dir.mkdirs())
                    throw new IOException("Could not make output dir: " + dir.getAbsolutePath());
            }/* w w  w  . j ava 2  s .  c o m*/
            ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS);
            node.accept(writer);
            byte[] data = writer.toByteArray();
            FileOutputStream fOut = new FileOutputStream(
                    new File(dir, node.name.substring(node.name.lastIndexOf(".") + 1)));
            fOut.write(data);
            fOut.flush();
            fOut.close();
        }
    } else if (in.getName().endsWith(".jar")) {
        File output = new File(out, in.getName());
        JarFile jf = new JarFile(in);
        HashMap<JarEntry, Object> existingData = new HashMap<>();
        if (output.exists()) {
            try {
                JarInputStream jarIn = new JarInputStream(new FileInputStream(output));
                JarEntry entry;
                while ((entry = jarIn.getNextJarEntry()) != null) {
                    if (!entry.isDirectory()) {
                        byte[] data = IOUtils.toByteArray(jarIn);
                        existingData.put(entry, data);
                        jarIn.closeEntry();
                    }
                }
                jarIn.close();
            } catch (IOException e) {
                Logger.getLogger(this.getClass().getName()).log(Level.SEVERE,
                        "Could not read existing output file, overwriting", e);
            }
        }
        FileOutputStream fout = new FileOutputStream(output);
        Manifest manifest = null;
        if (jf.getManifest() != null) {
            manifest = jf.getManifest();
            if (!config.getBoolean("ClassNameTransform.keep_packages")
                    && config.getBoolean("ClassNameTransform.exclude_mains")) {
                manifest = new Manifest(manifest);
                if (manifest.getMainAttributes().getValue("Main-Class") != null) {
                    String manifestName = manifest.getMainAttributes().getValue("Main-Class");
                    if (manifestName.contains(".")) {
                        manifestName = manifestName.substring(manifestName.lastIndexOf(".") + 1);
                        manifest.getMainAttributes().putValue("Main-Class", manifestName);
                    }
                }
            }
        }
        jf.close();
        JarOutputStream jarOut = manifest == null ? new JarOutputStream(fout)
                : new JarOutputStream(fout, manifest);
        Logger.getLogger(getClass().getName()).fine("Restoring " + existingData.size() + " existing files");
        if (!existingData.isEmpty()) {
            for (Map.Entry<JarEntry, Object> entry : existingData.entrySet()) {
                Logger.getLogger(getClass().getName()).fine("Restoring " + entry.getKey().getName());
                jarOut.putNextEntry(entry.getKey());
                jarOut.write((byte[]) entry.getValue());
                jarOut.closeEntry();
            }
        }
        for (ClassNode node : nodes()) {
            ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS);
            node.accept(writer);
            byte[] data = writer.toByteArray();
            int index = node.name.lastIndexOf("/");
            String fileName;
            if (index > 0) {
                fileName = node.name.substring(0, index + 1).replace(".", "/");
                fileName += node.name.substring(index + 1).concat(".class");
            } else {
                fileName = node.name.concat(".class");
            }
            JarEntry entry = new JarEntry(fileName);
            jarOut.putNextEntry(entry);
            jarOut.write(data);
            jarOut.closeEntry();
        }
        jarOut.close();
    } else {
        if (nodes().size() == 1) {
            File outputFile = new File(out, in.getName());
            ClassNode node = nodes().iterator().next();
            ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS);
            byte[] data = writer.toByteArray();
            FileOutputStream stream = new FileOutputStream(outputFile);
            stream.write(data);
            stream.close();
        }
    }
}

From source file:com.krikelin.spotifysource.AppInstaller.java

protected void extractJar(String destDir, String jarFile) throws IOException {
    File destination = new File(destDir);
    java.util.jar.JarFile jar = new java.util.jar.JarFile(jarFile);
    java.util.Enumeration<JarEntry> enu = jar.entries();
    while (enu.hasMoreElements()) {
        try {//from w  ww  . ja  v  a  2s .c o  m
            java.util.jar.JarEntry file = (java.util.jar.JarEntry) enu.nextElement();
            java.io.File f = new java.io.File(destDir + java.io.File.separator + file.getName());
            if (file.isDirectory()) { // if its a directory, create it
                f.mkdir();
                continue;
            }
            java.io.InputStream is = jar.getInputStream(file); // get the input stream
            if (!(destination.exists())) {
                destination.createNewFile();
            }

            java.io.FileOutputStream fos = new java.io.FileOutputStream(f);
            while (is.available() > 0) { // write contents of 'is' to 'fos'
                fos.write(is.read());
            }
            fos.close();
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:org.batfish.common.plugin.PluginConsumer.java

private void loadPluginJar(Path path) {
    /*//  w ww  .  j av  a 2 s  .  c  o  m
     * Adapted from
     * http://stackoverflow.com/questions/11016092/how-to-load-classes-at-
     * runtime-from-a-folder-or-jar Retrieved: 2016-08-31 Original Authors:
     * Kevin Crain http://stackoverflow.com/users/2688755/kevin-crain
     * Apfelsaft http://stackoverflow.com/users/1447641/apfelsaft License:
     * https://creativecommons.org/licenses/by-sa/3.0/
     */
    String pathString = path.toString();
    if (pathString.endsWith(".jar")) {
        try {
            URL[] urls = { new URL("jar:file:" + pathString + "!/") };
            URLClassLoader cl = URLClassLoader.newInstance(urls, _currentClassLoader);
            _currentClassLoader = cl;
            Thread.currentThread().setContextClassLoader(cl);
            JarFile jar = new JarFile(path.toFile());
            Enumeration<JarEntry> entries = jar.entries();
            while (entries.hasMoreElements()) {
                JarEntry element = entries.nextElement();
                String name = element.getName();
                if (element.isDirectory() || !name.endsWith(CLASS_EXTENSION)) {
                    continue;
                }
                String className = name.substring(0, name.length() - CLASS_EXTENSION.length()).replace("/",
                        ".");
                try {
                    cl.loadClass(className);
                    Class<?> pluginClass = Class.forName(className, true, cl);
                    if (!Plugin.class.isAssignableFrom(pluginClass)
                            || Modifier.isAbstract(pluginClass.getModifiers())) {
                        continue;
                    }
                    Constructor<?> pluginConstructor;
                    try {
                        pluginConstructor = pluginClass.getConstructor();
                    } catch (NoSuchMethodException | SecurityException e) {
                        throw new BatfishException(
                                "Could not find default constructor in plugin: '" + className + "'", e);
                    }
                    Object pluginObj;
                    try {
                        pluginObj = pluginConstructor.newInstance();
                    } catch (InstantiationException | IllegalAccessException | IllegalArgumentException
                            | InvocationTargetException e) {
                        throw new BatfishException(
                                "Could not instantiate plugin '" + className + "' from constructor", e);
                    }
                    Plugin plugin = (Plugin) pluginObj;
                    plugin.initialize(this);

                } catch (ClassNotFoundException e) {
                    jar.close();
                    throw new BatfishException("Unexpected error loading classes from jar", e);
                }
            }
            jar.close();
        } catch (IOException e) {
            throw new BatfishException("Error loading plugin jar: '" + path.toString() + "'", e);
        }
    }
}

From source file:org.nuxeo.osgi.JarBundleFile.java

@Override
public Enumeration<URL> findEntries(String name, String pattern, boolean recurse) {
    if (name.startsWith("/")) {
        name = name.substring(1);/*from  w w  w  .  ja  v a  2s. com*/
    }
    String prefix;
    if (name.length() == 0) {
        name = null;
        prefix = "";
    } else if (!name.endsWith("/")) {
        prefix = name + "/";
    } else {
        prefix = name;
    }
    int len = prefix.length();
    EntryFilter filter = EntryFilter.newFilter(pattern);
    Enumeration<JarEntry> entries = jarFile.entries();
    ArrayList<URL> result = new ArrayList<URL>();
    try {
        while (entries.hasMoreElements()) {
            JarEntry entry = entries.nextElement();
            if (entry.isDirectory()) {
                continue;
            }
            String ename = entry.getName();
            if (name != null && !ename.startsWith(prefix)) {
                continue;
            }
            int i = ename.lastIndexOf('/');
            if (!recurse) {
                if (i > -1) {
                    if (ename.indexOf('/', len) > -1) {
                        continue;
                    }
                }
            }
            String n = i > -1 ? ename.substring(i + 1) : ename;
            if (filter.match(n)) {
                result.add(getEntryUrl(ename));
            }
        }
    } catch (MalformedURLException e) {
        throw new RuntimeException(e);
    }
    return Collections.enumeration(result);
}

From source file:com.flexive.shared.FxDropApplication.java

/**
 * Load text resources packaged with the drop.
 *
 * @param pathPrefix    a path prefix (e.g. "scripts/")
 * @return              a map of filename (relative to the drop application package) -> file contents
 * @throws java.io.IOException  on I/O errors
 * @since 3.1/*from  ww w.  j a v a2  s.c  o  m*/
 */
public Map<String, String> loadTextResources(String pathPrefix) throws IOException {
    if (pathPrefix == null) {
        pathPrefix = "";
    } else if (pathPrefix.startsWith("/")) {
        pathPrefix = pathPrefix.substring(1);
    }
    if (isJarProtocol) {
        // read directly from jar file

        final Map<String, String> result = Maps.newHashMap();
        final JarInputStream stream = getJarStream();
        try {
            JarEntry entry;
            while ((entry = stream.getNextJarEntry()) != null) {

                if (!entry.isDirectory() && entry.getName().startsWith(pathPrefix)) {
                    try {
                        result.put(entry.getName(), FxSharedUtils.readFromJarEntry(stream, entry));
                    } catch (Exception e) {
                        if (LOG.isTraceEnabled()) {
                            LOG.trace(
                                    "Failed to read text JAR entry " + entry.getName() + ": " + e.getMessage(),
                                    e);
                        }
                        // ignore, continue reading
                    }

                }
            }
            return result;
        } finally {
            FxSharedUtils.close(stream);
        }
    } else {
        // read from filesystem

        final List<File> files = FxFileUtils.listRecursive(new File(resourceURL + File.separator + pathPrefix));
        final Map<String, String> result = Maps.newHashMapWithExpectedSize(files.size());
        for (File file : files) {
            try {
                result.put(StringUtils.replace(file.getPath(), resourceURL + File.separator, ""),
                        FxSharedUtils.loadFile(file));
            } catch (Exception e) {
                if (LOG.isTraceEnabled()) {
                    LOG.trace("Failed to read text file " + file.getPath() + ": " + e.getMessage(), e);
                }
            }
        }
        return result;
    }
}

From source file:io.fabric8.insight.log.support.LogQuerySupport.java

protected void addJarEntryToIndex(JarEntry entry, StringBuilder buffer) {
    // no need to show empty directories
    if (!entry.isDirectory()) {
        buffer.append(entry.getName());/* w w  w .j a v  a2 s  . c o  m*/
        buffer.append("\n");
    }
}

From source file:org.eclipse.jdt.ls.core.internal.codemanipulation.ImportOrganizeTest.java

private void addFilesFromJar(IJavaProject javaProject, File jarFile, String encoding)
        throws InvocationTargetException, CoreException, IOException {
    IFolder src = (IFolder) fSourceFolder.getResource();
    File targetFile = src.getLocation().toFile();
    try (JarFile file = new JarFile(jarFile)) {
        for (JarEntry entry : Collections.list(file.entries())) {
            if (entry.isDirectory()) {
                continue;
            }/*from w w  w. ja va 2  s .  c  o  m*/
            try (InputStream in = file.getInputStream(entry);
                    Reader reader = new InputStreamReader(in, encoding)) {
                File outFile = new File(targetFile, entry.getName());
                outFile.getParentFile().mkdirs();
                try (OutputStream out = new FileOutputStream(outFile);
                        Writer writer = new OutputStreamWriter(out, encoding)) {
                    IOUtils.copy(reader, writer);
                }
            }
        }
    }
    javaProject.getProject().refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor());
}

From source file:org.msec.rpc.ClassUtils.java

/**
 * package?Class/*  ww w  .  j ava  2s .c  o m*/
 * 
 * @param pack
 * @return
 */
public static void loadClasses(String pack) {
    // ?
    boolean recursive = true;
    // ??? ?
    String packageName = pack;
    String packageDirName = packageName.replace('.', '/');
    // ? ??things
    Enumeration<URL> dirs;
    try {
        dirs = Thread.currentThread().getContextClassLoader().getResources(packageDirName);
        // 
        while (dirs.hasMoreElements()) {
            // ?
            URL url = dirs.nextElement();
            // ????
            String protocol = url.getProtocol();
            // ???
            if ("file".equals(protocol)) {
                // ??
                String filePath = URLDecoder.decode(url.getFile(), "UTF-8");
                // ??? ?
                findAndAddClassesInPackageByFile(packageName, filePath, recursive);
            } else if ("jar".equals(protocol)) {
                // jar
                // JarFile
                JarFile jar;
                try {
                    // ?jar
                    jar = ((JarURLConnection) url.openConnection()).getJarFile();
                    // jar 
                    Enumeration<JarEntry> entries = jar.entries();
                    // ?
                    while (entries.hasMoreElements()) {
                        // ?jar ? jar META-INF
                        JarEntry entry = entries.nextElement();
                        String name = entry.getName();
                        // /
                        if (name.charAt(0) == '/') {
                            // ???
                            name = name.substring(1);
                        }
                        // ?????
                        if (name.startsWith(packageDirName)) {
                            int idx = name.lastIndexOf('/');
                            // "/" 
                            if (idx != -1) {
                                // ??? "/"??"."
                                packageName = name.substring(0, idx).replace('/', '.');
                            }
                            // ? 
                            if ((idx != -1) || recursive) {
                                // .class ?
                                if (name.endsWith(".class") && !entry.isDirectory()) {
                                    // ??".class" ???
                                    String className = name.substring(packageName.length() + 1,
                                            name.length() - 6);
                                    try {
                                        // classes
                                        Class.forName(packageName + '.' + className);
                                    } catch (ClassNotFoundException e) {
                                        // log
                                        // .error(" ?.class");
                                        e.printStackTrace();
                                    }
                                }
                            }
                        }
                    }
                } catch (IOException e) {
                    // log.error("??jar?");
                    e.printStackTrace();
                }
            }
        }
    } catch (Throwable e) {
        e.printStackTrace();
    }
}

From source file:com.netflix.nicobar.core.persistence.PathArchiveRepository.java

@Override
public void insertArchive(JarScriptArchive jarScriptArchive) throws IOException {
    Objects.requireNonNull(jarScriptArchive, "jarScriptArchive");
    ScriptModuleSpec moduleSpec = jarScriptArchive.getModuleSpec();
    ModuleId moduleId = moduleSpec.getModuleId();
    Path moduleDir = rootDir.resolve(moduleId.toString());
    if (Files.exists(moduleDir)) {
        FileUtils.deleteDirectory(moduleDir.toFile());
    }//from w  w  w. j a v  a2  s . com
    JarFile jarFile;
    try {
        jarFile = new JarFile(jarScriptArchive.getRootUrl().toURI().getPath());
    } catch (URISyntaxException e) {
        throw new IOException(e);
    }
    try {
        Enumeration<JarEntry> entries = jarFile.entries();
        while (entries.hasMoreElements()) {
            JarEntry jarEntry = entries.nextElement();
            Path entryName = moduleDir.resolve(jarEntry.getName());
            if (jarEntry.isDirectory()) {
                Files.createDirectories(entryName);
            } else {
                InputStream inputStream = jarFile.getInputStream(jarEntry);
                try {
                    Files.copy(inputStream, entryName);
                } finally {
                    IOUtils.closeQuietly(inputStream);
                }
            }
        }
    } finally {
        IOUtils.closeQuietly(jarFile);
    }
    // write the module spec
    String serialized = moduleSpecSerializer.serialize(moduleSpec);
    Files.write(moduleDir.resolve(moduleSpecSerializer.getModuleSpecFileName()),
            serialized.getBytes(Charsets.UTF_8));

    // update the timestamp on the module directory to indicate that the module has been updated
    Files.setLastModifiedTime(moduleDir, FileTime.fromMillis(jarScriptArchive.getCreateTime()));
}

From source file:org.teavm.maven.BuildJavascriptTestMojo.java

private void findTestClassesInJar(ClassLoader classLoader, JarFile jarFile) {
    Enumeration<JarEntry> entries = jarFile.entries();
    while (entries.hasMoreElements()) {
        JarEntry entry = entries.nextElement();
        if (entry.isDirectory() || !entry.getName().endsWith(".class")) {
            continue;
        }/*www .ja va 2  s . co  m*/
        String className = entry.getName().substring(0, entry.getName().length() - ".class".length())
                .replace('/', '.');
        addCandidate(classLoader, className);
    }
}