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.google.gdt.eclipse.designer.util.Utils.java

/**
 * @return the default version of GWT, configured in preferences.
 *///from www.ja  v  a2  s.c  om
public static Version getDefaultVersion() {
    String userLocation = Activator.getGWTLocation() + "/gwt-user.jar";
    File userFile = new File(userLocation);
    if (userFile.exists()) {
        try {
            JarFile jarFile = new JarFile(userFile);
            try {
                if (hasClassEntry(jarFile, "com.google.gwt.user.cellview.client.RowHoverEvent")) {
                    return GWT_2_5;
                }
                if (hasClassEntry(jarFile, "com.google.gwt.user.cellview.client.DataGrid")) {
                    return GWT_2_4;
                }
                if (hasClassEntry(jarFile, "com.google.gwt.canvas.client.Canvas")) {
                    return GWT_2_2;
                }
                if (hasClassEntry(jarFile, "com.google.gwt.user.client.ui.DirectionalTextHelper")) {
                    return GWT_2_1_1;
                }
                if (hasClassEntry(jarFile, "com.google.gwt.cell.client.Cell")) {
                    return GWT_2_1;
                }
                if (hasClassEntry(jarFile, "com.google.gwt.user.client.ui.LayoutPanel")) {
                    return GWT_2_0;
                }
            } finally {
                jarFile.close();
            }
        } catch (Throwable e) {
        }
    }
    // default version
    return GWT_2_4;
}

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

public static void processJarFile(String jarFileName, JarFileProcessor processor) {
    try {/*w w  w .j a va  2s .co m*/
        JarFile exportedFile = new JarFile(jarFileName);
        for (Enumeration<JarEntry> jarEntryEnumeration = exportedFile.entries(); jarEntryEnumeration
                .hasMoreElements();) {
            JarEntry jarEntry = jarEntryEnumeration.nextElement();
            logger.debug("Trying to process entry {} ", jarEntry);
            processor.process(exportedFile, jarEntry);
        }
        logger.debug("Processed all the jar entries");
    } catch (Exception exception) {
        throw new OIMAdminException("Failed to open the jar file " + jarFileName, exception);
    }
}

From source file:edu.cornell.med.icb.io.ResourceFinder.java

/**
 * List directory contents for a resource folder. Not recursive, does not return
 * directory entries. Works for regular files and also JARs.
 *
 * @param clazz Any java class that lives in the same place as the resources you want.
 * @param pathVal the path to find files for
 * @return Each member item (no path information)
 * @throws URISyntaxException bad URI syntax
 * @throws IOException error reading//from ww w .  j  a v a 2s.  c  o  m
 */
public String[] getResourceListing(final Class clazz, final String pathVal)
        throws URISyntaxException, IOException {
    // Enforce all paths are separated by "/", they do not start with "/" and
    // the DO end with "/".
    String path = pathVal.replace("\\", "/");
    if (!path.endsWith("/")) {
        path += "/";
    }
    while (path.startsWith("/")) {
        path = path.substring(1);
    }
    URL dirURL = findResource(path);
    if (dirURL != null && dirURL.getProtocol().equals("file")) {
        /* A file path: easy enough */
        return new File(dirURL.toURI()).list();
    }

    if (dirURL == null) {
        /*
         * In case of a jar file, we can't actually find a directory.
         * Have to assume the same jar as clazz.
         */
        final String classFilename = clazz.getName().replace(".", "/") + ".class";
        dirURL = findResource(classFilename);
    }

    if (dirURL.getProtocol().equals("jar")) {
        /* A JAR path */
        String jarPath = dirURL.getPath().substring(5, dirURL.getPath().indexOf('!'));
        if (jarPath.charAt(2) == ':') {
            jarPath = jarPath.substring(1);
        }
        jarPath = URLDecoder.decode(jarPath, "UTF-8");
        final JarFile jar = new JarFile(jarPath);
        final Enumeration<JarEntry> entries = jar.entries();
        final Set<String> result = new HashSet<String>();
        while (entries.hasMoreElements()) {
            final String name = entries.nextElement().getName();
            //filter according to the path
            if (name.startsWith(path)) {
                final String entry = name.substring(path.length());
                if (entry.length() == 0) {
                    // Skip the directory entry for path
                    continue;
                }
                final int checkSubdir = entry.indexOf('/');
                if (checkSubdir >= 0) {
                    // Skip sub dirs
                    continue;
                }
                result.add(entry);
            }
        }
        return result.toArray(new String[result.size()]);
    }
    throw new UnsupportedOperationException("Cannot list files for URL " + dirURL);
}

From source file:com.util.InstallUtil.java

private Properties getDefaultProperties() throws IOException {
    String os = System.getProperty("os.name");

    String jar = ServerUtil.getPath() + "/install/installer.jar";
    String fileName = "data/installDefaultValues.properties";

    if (os.startsWith("Linux")) {
        fileName = "data/installDefaultValuesNoUI.properties";
    }/*from   w  ww  .j av a2s  .  co  m*/

    JarFile jarFile = new JarFile(jar);
    JarEntry entry = jarFile.getJarEntry(fileName);
    InputStream input = jarFile.getInputStream(entry);

    Properties p = new Properties();
    p.load(input);

    jarFile.close();
    return p;
}

From source file:com.qmetry.qaf.automation.core.ConfigurationManager.java

private static Map<String, String> getBuildInfo() {
    Manifest manifest = null;/*w  ww .jav  a 2s .c  o m*/
    Map<String, String> buildInfo = new HashMap<String, String>();
    JarFile jar = null;
    try {
        URL url = ConfigurationManager.class.getProtectionDomain().getCodeSource().getLocation();
        File file = new File(url.toURI());
        jar = new JarFile(file);
        manifest = jar.getManifest();
    } catch (NullPointerException ignored) {
    } catch (URISyntaxException ignored) {
    } catch (IOException ignored) {
    } catch (IllegalArgumentException ignored) {
    } finally {
        if (null != jar)
            try {
                jar.close();
            } catch (IOException e) {
                log.warn(e.getMessage());
            }
    }

    if (manifest == null) {
        return buildInfo;
    }

    try {
        Attributes attributes = manifest.getAttributes("Build-Info");
        Set<Entry<Object, Object>> entries = attributes.entrySet();
        for (Entry<Object, Object> e : entries) {
            buildInfo.put(String.valueOf(e.getKey()), String.valueOf(e.getValue()));
        }
    } catch (NullPointerException e) {
        // Fall through
    }

    return buildInfo;
}

From source file:UnpackedJarFile.java

public static String readAll(URL url) throws IOException {
    Reader reader = null;//from  w  w  w . jav a 2 s.c o m
    JarFile jarFile = null;
    try {
        if (url.getProtocol().equalsIgnoreCase("jar")) {
            // url.openStream() locks the jar file and does not release the lock even after the stream is closed.
            // This problem is avoided by using JarFile APIs.
            File file = new File(url.getFile().substring(5, url.getFile().indexOf("!/")));
            String path = url.getFile().substring(url.getFile().indexOf("!/") + 2);
            jarFile = new JarFile(file);
            JarEntry jarEntry = jarFile.getJarEntry(path);
            if (jarEntry != null) {
                reader = new InputStreamReader(jarFile.getInputStream(jarEntry));
            } else {
                throw new FileNotFoundException("JarEntry " + path + " not found in " + file);
            }
        } else {
            reader = new InputStreamReader(url.openStream());
        }
        char[] buffer = new char[4000];
        StringBuffer out = new StringBuffer();
        for (int count = reader.read(buffer); count >= 0; count = reader.read(buffer)) {
            out.append(buffer, 0, count);
        }
        return out.toString();
    } finally {
        close(reader);
        close(jarFile);
    }
}

From source file:com.iflytek.edu.cloud.frame.doc.ServiceDocBuilder.java

private void doServiceJavaSource(String jarFileUrl) throws IOException {
    JarFile jarFile = new JarFile(jarFileUrl);
    try {/*from   w w  w  . j  a  v a2 s .  c o m*/
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Looking for matching resources in jar file [" + jarFileUrl + "]");
        }

        for (Enumeration<JarEntry> entries = jarFile.entries(); entries.hasMoreElements();) {
            JarEntry entry = entries.nextElement();

            String entryPath = entry.getName();
            if (entryPath.endsWith(".java")) {
                InputStream inputStream = jarFile.getInputStream(entry);
                builder.addSource(new InputStreamReader(inputStream, "UTF-8"));
            }
        }
    } finally {
        jarFile.close();
    }
}

From source file:com.infosupport.ellison.core.archive.ApplicationArchive.java

/**
 * Helper function for {@link #unpackJar()}. This does all the actual work, without caching anything.
 *
 * @param jarFile/* w ww  .j a v  a  2s  .  com*/
 *     the file to unpack
 *
 * @return a {@code File} pointing to the temporary directory the JAR was extracted to
 *
 * @throws IOException
 *     when: <ul><li>the temporary directory to unpack the JAR into could not be created</li> <li>the application
 *     archive could not be read as a JAR</li> <li>a file in the archive could not be read</li> <li>a file in the
 *     archive could not be unpacked (write error)</li></ul>
 */
protected File unpackJarHelper(File jarFile) throws IOException {
    File destination = Files.createTempDirectory(Constants.TEMP_DIR_PREFIX + jarFile.getName()).toFile();
    destination.deleteOnExit();
    try (JarFile jar = new JarFile(jarFile)) {
        Enumeration<JarEntry> jarEntries = jar.entries();

        while (jarEntries.hasMoreElements()) {
            unpackJarEntry(destination, jar, jarEntries.nextElement());
        }
    }

    return destination;
}

From source file:edu.stanford.muse.email.JarDocCache.java

public Map<Integer, Document> getAllHeaders(String prefix) throws IOException, ClassNotFoundException {
    Map<Integer, Document> result = new LinkedHashMap<Integer, Document>();
    JarFile jarFile = null;/*  ww w  . j  a v  a 2  s . c  o  m*/
    String fname = baseDir + File.separator + prefix + ".headers";
    try {
        jarFile = new JarFile(fname);
    } catch (Exception e) {
        log.info("No Jar file exists: " + fname);
    }
    if (jarFile == null)
        return result;

    Enumeration<JarEntry> entries = jarFile.entries();
    String suffix = ".header";
    while (entries.hasMoreElements()) {
        JarEntry je = entries.nextElement();
        String s = je.getName();
        if (!s.endsWith(suffix))
            continue;
        String idx_str = s.substring(0, s.length() - suffix.length());
        int index = -1;
        try {
            index = Integer.parseInt(idx_str);
        } catch (Exception e) {
            log.error("Funny file in header: " + index);
        }

        ObjectInputStream ois = new ObjectInputStream(jarFile.getInputStream(je));
        Document ed = (Document) ois.readObject();
        ois.close();
        result.put(index, ed);
    }
    return result;
}

From source file:JarEntryOutputStream.java

/**
 * Utility method used to swap the underlying jar file out for the new one.
 * This method closes the old jar file, deletes it, moves the new jar
 * file to the location where the old one used to be and opens it.
 * <p>/*from w  w  w. j  a va 2  s.com*/
 * This is used when modifying the jar (removal, addition, or changes
 * of entries)
 *
 * @param newJarFile the file object pointing to the new jar file
 */
void swapJars(File newJarFile) throws IOException {
    File oldJarFile = new File(getName());
    this.jar.close();
    oldJarFile.delete();
    if (newJarFile.renameTo(oldJarFile)) {
        this.jar = new JarFile(oldJarFile);
    } else {
        throw new IOException();
    }
}