Example usage for java.util.jar JarEntry getName

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

Introduction

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

Prototype

public String getName() 

Source Link

Document

Returns the name of the entry.

Usage

From source file:fll.xml.XMLUtils.java

/**
 * Get all challenge descriptors build into the software.
 *//*from  ww  w.j  a  v  a  2 s.co  m*/
public static Collection<URL> getAllKnownChallengeDescriptorURLs() {
    final String baseDir = "fll/resources/challenge-descriptors/";

    final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    final URL directory = classLoader.getResource(baseDir);
    if (null == directory) {
        LOGGER.warn("base dir for challenge descriptors not found");
        return Collections.emptyList();
    }

    final Collection<URL> urls = new LinkedList<URL>();
    if ("file".equals(directory.getProtocol())) {
        try {
            final URI uri = directory.toURI();
            final File fileDir = new File(uri);
            final File[] files = fileDir.listFiles();
            if (null != files) {
                for (final File file : files) {
                    if (file.getName().endsWith(".xml")) {
                        try {
                            final URL fileUrl = file.toURI().toURL();
                            urls.add(fileUrl);
                        } catch (final MalformedURLException e) {
                            LOGGER.error("Unable to convert file to URL: " + file.getAbsolutePath(), e);
                        }
                    }
                }
            }
        } catch (final URISyntaxException e) {
            LOGGER.error("Unable to convert URL to URI: " + e.getMessage(), e);
        }
    } else if (directory.getProtocol().equals("jar")) {
        final CodeSource src = XMLUtils.class.getProtectionDomain().getCodeSource();
        if (null != src) {
            final URL jar = src.getLocation();

            JarInputStream zip = null;
            try {
                zip = new JarInputStream(jar.openStream());

                JarEntry ze = null;
                while ((ze = zip.getNextJarEntry()) != null) {
                    final String entryName = ze.getName();
                    if (entryName.startsWith(baseDir) && entryName.endsWith(".xml")) {
                        // add 1 to baseDir to skip past the path separator
                        final String challengeName = entryName.substring(baseDir.length());

                        // check that the file really exists and turn it into a URL
                        final URL challengeUrl = classLoader.getResource(baseDir + challengeName);
                        if (null != challengeUrl) {
                            urls.add(challengeUrl);
                        } else {
                            // TODO could write the resource out to a temporary file if
                            // needed
                            // then mark the file as delete on exit
                            LOGGER.warn("URL doesn't exist for " + baseDir + challengeName + " entry: "
                                    + entryName);
                        }
                    }
                }

                zip.close();
            } catch (final IOException e) {
                LOGGER.error("Error reading jar file at: " + jar.toString(), e);
            } finally {
                IOUtils.closeQuietly(zip);
            }

        } else {
            LOGGER.warn("Null code source in protection domain, cannot get challenge descriptors");
        }
    } else {
        throw new UnsupportedOperationException("Cannot list files for URL " + directory);

    }

    return urls;

}

From source file:org.apache.cocoon.portal.pluto.Deploy.java

/**
 * Deploy the archive//  w ww .jav  a  2 s . c  om
 * Unpack the archive in the servlet engine context directory
 */
public static void deployArchive(final String webAppsDir, final String warFile, final String warFileName)
        throws IOException {
    System.out.println("Deploying '" + warFileName + "' ...");

    final String destination = webAppsDir + warFileName;

    if (debug) {
        System.out.println("  unpacking '" + warFile + "' ...");
    }
    final JarFile jarFile = new JarFile(warFile);
    final Enumeration files = jarFile.entries();
    while (files.hasMoreElements()) {
        JarEntry entry = (JarEntry) files.nextElement();

        File file = new File(destination, entry.getName());
        File dirF = new File(file.getParent());
        dirF.mkdirs();
        if (entry.isDirectory()) {
            file.mkdirs();
        } else {
            byte[] buffer = new byte[1024];
            int length = 0;
            InputStream fis = jarFile.getInputStream(entry);
            FileOutputStream fos = new FileOutputStream(file);
            while ((length = fis.read(buffer)) >= 0) {
                fos.write(buffer, 0, length);
            }
            fos.close();
        }

    }

    if (debug) {
        System.out.println("Finished!");
    }
}

From source file:org.squidy.manager.scanner.PackageScanner.java

/**
 * @param thePackagePattern/* w ww  .  j a va  2 s  .  c  o m*/
 * @param file
 * @return
 */
private static Collection<? extends String> findAllClassesInJarContainedBy(String thePackagePattern,
        File file) {
    List<String> classes = new ArrayList<String>();

    try {
        if (!file.exists()) {
            // if (LOG.isDebugEnabled()) {
            // LOG.debug("Jar file does not exist. Skipping " + file);
            // }
            return classes;
        }

        JarFile jarFile = new JarFile(file);
        Enumeration<JarEntry> jarEntries = jarFile.entries();
        while (jarEntries.hasMoreElements()) {
            JarEntry jarEntry = jarEntries.nextElement();
            if (jarEntry.getName().matches(thePackagePattern)) {
                String fileName = jarEntry.getName().substring(0, jarEntry.getName().lastIndexOf(".class"));

                fileName = fileName.replace('/', '.');
                classes.add(fileName);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return classes;
}

From source file:org.hecl.jarhack.JarHack.java

/**
 * The <code>substHecl</code> method takes the filenames of two
 * .jar's - one as input, the second as output, in addition to the
 * name of the application.  Where it counts, the old name (Hecl,
 * usually) is overridden with the new name, and the new .jar file
 * is written to the specified outfile.  Via the iconname argument
 * it is also possible to specify a new icon file to use.
 *
 * @param infile a <code>FileInputStream</code> value
 * @param outfile a <code>String</code> value
 * @param newname a <code>String</code> value
 * @param iconname a <code>String</code> value
 * @exception IOException if an error occurs
 *///  w ww. j a va2s .  com
public static void substHecl(InputStream infile, String outfile, String newname, String iconname,
        String scriptfile) throws IOException {

    JarInputStream jif = new JarInputStream(infile);
    Manifest mf = jif.getManifest();
    Attributes attrs = mf.getMainAttributes();

    Set keys = attrs.keySet();
    Iterator it = keys.iterator();
    while (it.hasNext()) {
        Object key = it.next();
        Object value = attrs.get(key);
        String keyname = key.toString();

        /* These are the three cases that interest us in
         * particular, where we need to make changes. */
        if (keyname.equals("MIDlet-Name")) {
            attrs.putValue(keyname, newname);
        } else if (keyname.equals("MIDlet-1")) {
            String valuestr = value.toString();
            /* FIXME - the stringsplit method is used for older
             * versions of GCJ.  Once newer versions are common,
             * it can go away.  Or not - it works just fine. */
            String properties[] = stringsplit(valuestr, ", ");
            attrs.putValue(keyname, newname + ", " + properties[1] + ", " + properties[2]);
        } else if (keyname.equals("MicroEdition-Configuration")) {
            cldcversion = value.toString();
        } else if (keyname.equals("MicroEdition-Profile")) {
            midpversion = value.toString();
        } else if (keyname.equals("MIDlet-Jar-URL")) {
            attrs.put(key, newname + ".jar");
        }
    }

    JarOutputStream jof = new JarOutputStream(new FileOutputStream(outfile), mf);

    byte[] buf = new byte[4096];

    /* Go through the various entries. */
    JarEntry entry;
    int read;
    while ((entry = jif.getNextJarEntry()) != null) {

        /* Don't copy the manifest file. */
        if ("META-INF/MANIFEST.MF".equals(entry.getName()))
            continue;

        /* Insert our own icon */
        if (iconname != null && "Hecl.png".equals(entry.getName())) {
            jof.putNextEntry(new JarEntry("Hecl.png"));
            FileInputStream inf = new FileInputStream(iconname);
            while ((read = inf.read(buf)) != -1) {
                jof.write(buf, 0, read);
            }
            inf.close();
        }
        /* Insert our own copy of the script file. */
        else if ("script.hcl".equals(entry.getName())) {
            jof.putNextEntry(new JarEntry("script.hcl"));
            FileInputStream inf = new FileInputStream(scriptfile);
            while ((read = inf.read(buf)) != -1) {
                jof.write(buf, 0, read);
            }
            inf.close();
        } else {
            /* Otherwise, just copy the entry. */
            jof.putNextEntry(entry);
            while ((read = jif.read(buf)) != -1) {
                jof.write(buf, 0, read);
            }
        }

        jof.closeEntry();
    }

    jof.flush();
    jof.close();
    jif.close();
}

From source file:WarUtil.java

/**
 * WAR???????????/*from   www. j  a va  2s .com*/
 * 
 * @param warFile
 * @param directory
 * @throws IOException
 */
public static void extractWar(File warFile, File directory) throws IOException {
    try {
        long timestamp = warFile.lastModified();
        File warModifiedTimeFile = new File(directory, LAST_MODIFIED_FILE);
        long lastModified = readLastModifiled(warModifiedTimeFile);

        if (timestamp == lastModified) {
            //      log.info("war file " + warFile.getName() + " not modified.");
            return;
        }
        if (directory.exists()) {
            //         IOUtil.forceRemoveDirectory(directory);
            directory.mkdir();
        }

        //         log.info("war extract start. warfile=" + warFile.getName());

        JarInputStream jin = new JarInputStream(new BufferedInputStream(new FileInputStream(warFile)));
        JarEntry entry = null;

        while ((entry = jin.getNextJarEntry()) != null) {
            File file = new File(directory, entry.getName());

            if (entry.isDirectory()) {
                if (!file.exists()) {
                    file.mkdirs();
                }
            } else {
                File dir = new File(file.getParent());
                if (!dir.exists()) {
                    dir.mkdirs();
                }

                FileOutputStream fout = null;
                try {
                    fout = new FileOutputStream(file);
                    ResourceUtil.copyStream(jin, fout);
                } finally {
                    fout.flush();
                    fout.close();
                    fout = null;
                }

                if (entry.getTime() >= 0) {
                    file.setLastModified(entry.getTime());
                }
            }
        }

        writeLastModifiled(warModifiedTimeFile, timestamp);

        //log.info("war extract success. lastmodified=" + timestamp);
    } catch (IOException ioe) {
        //log.info("war extract fail.");
        throw ioe;
    }
}

From source file:de.xirp.plugin.PluginLoader.java

/**
 * Looks for plugins in the plugins directory. Plugins which needs
 * are not full filled are not accepted.
 * //from  ww  w .j a  v a2  s. com
 * @param manager
 *            instance of the plugin manager which is used for
 *            notifying the application about the loading
 *            progress.
 */
protected static void searchPlugins(PluginManager manager) {
    logClass.info(I18n.getString("PluginLoader.log.searchPlugins")); //$NON-NLS-1$
    // Get all Files in the Plugin Directory with
    // Filetype jar
    File pluginDir = new File(Constants.PLUGIN_DIR);
    File[] fileList = pluginDir.listFiles(new FilenameFilter() {

        public boolean accept(@SuppressWarnings("unused") File dir, String filename) {
            return filename.endsWith(".jar"); //$NON-NLS-1$
        }

    });

    if (fileList != null) {
        double perFile = 1.0 / fileList.length;
        double cnt = 0;
        try {
            // Iterate over all jars and try to find
            // the plugin.properties file
            // The file is loaded and Information
            // extracted to PluginInfo
            // Plugin is added to List of Plugins
            for (File f : fileList) {
                String path = f.getAbsolutePath();
                if (!plugins.containsKey(path)) {
                    manager.throwLoaderProgressEvent(
                            I18n.getString("PluginLoader.progress.searchingInFile", f.getName()), cnt); //$NON-NLS-1$
                    JarFile jar = new JarFile(path);
                    JarEntry entry = jar.getJarEntry("plugin.properties"); //$NON-NLS-1$
                    if (entry != null) {
                        InputStream input = jar.getInputStream(entry);
                        Properties props = new Properties();
                        props.load(input);
                        String mainClass = props.getProperty("plugin.mainclass"); //$NON-NLS-1$
                        PluginInfo info = new PluginInfo(path, mainClass, props);
                        String packageName = ClassUtils.getPackageName(mainClass) + "." //$NON-NLS-1$
                                + AbstractPlugin.DEFAULT_BUNDLE_NAME;
                        String bundleBaseName = packageName.replaceAll("\\.", "/"); //$NON-NLS-1$  //$NON-NLS-2$
                        for (Enumeration<JarEntry> entries = jar.entries(); entries.hasMoreElements();) {
                            JarEntry ent = entries.nextElement();
                            String name = ent.getName();
                            if (name.indexOf(bundleBaseName) != -1) {
                                String locale = name
                                        .substring(name.indexOf(AbstractPlugin.DEFAULT_BUNDLE_NAME));
                                locale = locale.replaceAll(AbstractPlugin.DEFAULT_BUNDLE_NAME + "_", //$NON-NLS-1$
                                        ""); //$NON-NLS-1$
                                locale = locale.substring(0, locale.indexOf(".properties")); //$NON-NLS-1$
                                Locale loc = new Locale(locale);
                                info.addAvailableLocale(loc);
                            }
                        }
                        PluginManager.extractAll(info);
                        if (isPlugin(info)) {
                            plugins.put(mainClass, info);
                        }
                    }
                }
                cnt += perFile;

            }
        } catch (IOException e) {
            logClass.error(
                    I18n.getString("PluginLoader.log.errorSearchingforPlugins") + Constants.LINE_SEPARATOR, e); //$NON-NLS-1$
        }
    }
    checkAllNeeds();
    logClass.info(I18n.getString("PluginLoader.log.searchPluginsCompleted") + Constants.LINE_SEPARATOR); //$NON-NLS-1$
}

From source file:com.jhash.oimadmin.Utils.java

public static void extractJarFile(String directory, String jarFileName) {
    File baseDir = new File(directory);
    if (baseDir.exists()) {
        if (!baseDir.isDirectory()) {
            throw new InvalidParameterException("Destination directory " + directory + " to expand Jar file "
                    + jarFileName + " is not a directory");
        }//www .  j  a v a  2  s  . c  o  m
        if (!baseDir.canWrite() || !baseDir.canWrite() || !baseDir.canExecute()) {
            throw new InvalidParameterException("Destination directory " + directory + " to expand Jar file "
                    + jarFileName + " does not have rwx access for user");
        }
    } else {
        baseDir.mkdirs();
    }
    try (JarFile jar = new JarFile(jarFileName)) {
        Enumeration enumEntries = jar.entries();
        while (enumEntries.hasMoreElements()) {
            JarEntry file = (JarEntry) enumEntries.nextElement();
            File f = new File(directory + File.separator + file.getName());
            if (file.isDirectory()) { // if its a directory, create it
                f.mkdirs();
                continue;
            }
            try (java.io.InputStream is = jar.getInputStream(file);
                    java.io.FileOutputStream fos = new java.io.FileOutputStream(f)) {
                // get the input stream
                while (is.available() > 0) { // write contents of 'is' to 'fos'
                    fos.write(is.read());
                }
                fos.close();
                is.close();
            } catch (Exception exception) {
                throw new OIMAdminException("Failed to write the jar file entry " + file + " to location " + f,
                        exception);
            }
        }
    } catch (Exception exception) {
        throw new OIMAdminException("Failed to extract jar file " + jarFileName + " to directory " + directory,
                exception);
    }
}

From source file:org.spoutcraft.launcher.util.Utils.java

public static void extractJar(JarFile jar, File dest, List<String> ignores) throws IOException {
    if (!dest.exists()) {
        dest.mkdirs();/*from w  ww. ja v  a2s. c  o m*/
    } else {
        if (!dest.isDirectory()) {
            throw new IllegalArgumentException("The destination was not a directory");
        }
        FileUtils.cleanDirectory(dest);
    }
    Enumeration<JarEntry> entries = jar.entries();

    while (entries.hasMoreElements()) {
        JarEntry entry = entries.nextElement();
        File file = new File(dest, entry.getName());
        if (ignores != null) {
            boolean skip = false;
            for (String path : ignores) {
                if (entry.getName().startsWith(path)) {
                    skip = true;
                    break;
                }
            }
            if (skip) {
                continue;
            }
        }

        if (entry.getName().endsWith("/")) {
            if (!file.mkdir()) {
                if (ignores == null) {
                    ignores = new ArrayList<String>();
                }
                ignores.add(entry.getName());
            }
            continue;
        }

        if (file.exists()) {
            file.delete();
        }

        file.createNewFile();

        InputStream in = new BufferedInputStream(jar.getInputStream(entry));
        OutputStream out = new BufferedOutputStream(new FileOutputStream(file));

        byte buffer[] = new byte[1024];
        int len;
        while ((len = in.read(buffer)) > 0) {
            out.write(buffer, 0, len);
        }
        out.close();
        in.close();
    }
    jar.close();
}

From source file:JarUtil.java

/**
 * Extracts the given jar-file to the specified directory. The target
 * directory will be cleaned before the jar-file will be extracted.
 * //from  ww w  . j a  v  a 2 s  .co m
 * @param jarFile
 *            The jar file which should be unpacked
 * @param targetDir
 *            The directory to which the jar-content should be extracted.
 * @throws FileNotFoundException
 *             when the jarFile does not exist
 * @throws IOException
 *             when a file could not be written or the jar-file could not
 *             read.
 */
public static void unjar(File jarFile, File targetDir) throws FileNotFoundException, IOException {
    // clear target directory:
    if (targetDir.exists()) {
        targetDir.delete();
    }
    // create new target directory:
    targetDir.mkdirs();
    // read jar-file:
    String targetPath = targetDir.getAbsolutePath() + File.separatorChar;
    byte[] buffer = new byte[1024 * 1024];
    JarFile input = new JarFile(jarFile, false, ZipFile.OPEN_READ);
    Enumeration<JarEntry> enumeration = input.entries();
    for (; enumeration.hasMoreElements();) {
        JarEntry entry = enumeration.nextElement();
        if (!entry.isDirectory()) {
            // do not copy anything from the package cache:
            if (entry.getName().indexOf("package cache") == -1) {
                String path = targetPath + entry.getName();
                File file = new File(path);
                if (!file.getParentFile().exists()) {
                    file.getParentFile().mkdirs();
                }
                FileOutputStream out = new FileOutputStream(file);
                InputStream in = input.getInputStream(entry);
                int read;
                while ((read = in.read(buffer)) != -1) {
                    out.write(buffer, 0, read);
                }
                in.close();
                out.close();
            }
        }
    }

}

From source file:JarUtil.java

/**
 * Extracts the given resource from a jar-file to the specified directory.
 * //from   w  w w . j av a  2 s . c  om
 * @param jarFile
 *            The jar file which should be unpacked
 * @param resource
 *            The name of a resource in the jar
 * @param targetDir
 *            The directory to which the jar-content should be extracted.
 * @throws FileNotFoundException
 *             when the jarFile does not exist
 * @throws IOException
 *             when a file could not be written or the jar-file could not
 *             read.
 */
public static void unjar(File jarFile, String resource, File targetDir)
        throws FileNotFoundException, IOException {
    // clear target directory:
    if (targetDir.exists()) {
        targetDir.delete();
    }
    // create new target directory:
    targetDir.mkdirs();
    // read jar-file:
    String targetPath = targetDir.getAbsolutePath() + File.separatorChar;
    byte[] buffer = new byte[1024 * 1024];
    JarFile input = new JarFile(jarFile, false, ZipFile.OPEN_READ);
    Enumeration<JarEntry> enumeration = input.entries();
    for (; enumeration.hasMoreElements();) {
        JarEntry entry = enumeration.nextElement();
        if (!entry.isDirectory()) {
            // do not copy anything from the package cache:
            if (entry.getName().equals(resource)) {
                String path = targetPath + entry.getName();
                File file = new File(path);
                if (!file.getParentFile().exists()) {
                    file.getParentFile().mkdirs();
                }
                FileOutputStream out = new FileOutputStream(file);
                InputStream in = input.getInputStream(entry);
                int read;
                while ((read = in.read(buffer)) != -1) {
                    out.write(buffer, 0, read);
                }
                in.close();
                out.close();
            }
        }
    }
}