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:net.rim.ejde.internal.packaging.PackagingJob.java

/**
 * If the cod file represented by the given <code>codFilePath</code> contains sibling cod file, un-zip it and copy all sibling
 * cod files to the <code>destinationFolderPath</code>. If the cod file is a single cod file, just copy it to the
 * <code>destinationFolderPath</code>.
 *
 * @param codFilePath// w ww.  j  a  v  a 2 s  .  c om
 * @param destinationFolderPath
 * @throws CoreException
 */
private void copySiblingCod(IPath codFilePath, IPath destinationFolderPath) throws CoreException {
    boolean hasSiblingCod = false;
    File codFile = codFilePath.toFile();
    try {
        JarFile zipFile = new JarFile(codFile);
        Enumeration<JarEntry> entries = zipFile.entries();
        if (entries.hasMoreElements()) {
            hasSiblingCod = true;
            JarEntry entry;
            for (; entries.hasMoreElements();) {
                entry = entries.nextElement();
                if (entry.isDirectory()) {
                    // this should not happen
                    continue;
                }
                InputStream is = zipFile.getInputStream(entry);
                File outputFile = destinationFolderPath.append(entry.getName()).toFile();
                PackagingManager.copyInputStream(is,
                        new BufferedOutputStream(new FileOutputStream(outputFile)));
            }
        } else {
            hasSiblingCod = false;
        }
    } catch (IOException e) {
        if (codFile.exists()) {
            // if the cod file does not contain any sibling file, we get IOException
            hasSiblingCod = false;
        } else {
            _log.error(e);
        }
    } finally {
        if (!hasSiblingCod) {
            // if the cod file is a single cod file, copy it to the destination
            DeploymentHelper.executeCopy(codFile, destinationFolderPath.append(codFile.getName()).toFile());
        }
    }
}

From source file:ca.weblite.xmlvm.XMLVM.java

/**
 * Finds all of the classes from a given collection of class names that reside in a 
 * given path.  It also copies the found classes into a specified destination directory.
 * @param p The path to search.//from   w w w .  j  ava2 s  .c o  m
 * @param classNames The class names to search for.
 * @param found The class names that were found in that path.
 * @param destDir The directory where found classes will be copied to.
 * @throws IOException 
 */
public void findClassesInPath(Path p, Collection<String> classNames, Set<String> found, File destDir)
        throws IOException {
    for (String part : p.list()) {
        File f = new File(part);
        if (f.isDirectory()) {
            // We have a directory
            findClassesInPath(f, f, classNames, found, destDir);
        } else if (f.getName().endsWith(".jar")) {
            // We have a jar file
            JarFile jf = new JarFile(f);
            Enumeration<JarEntry> entries = jf.entries();

            Expand expand = (Expand) getProject().createTask("unzip");
            expand.setSrc(f);
            expand.setDest(destDir);
            boolean emptySet = true;

            while (entries.hasMoreElements()) {
                JarEntry nex = entries.nextElement();
                if (nex.getName().endsWith(".class")) {
                    String foundClassName = nex.getName().replaceAll("/", ".").replaceAll("\\.class$", "");
                    if (classNames.contains(foundClassName) && !found.contains(foundClassName)) {
                        found.add(foundClassName);
                        FilenameSelector sel = new FilenameSelector();
                        sel.setName(nex.getName());
                        ZipFileSet fs = new ZipFileSet();
                        fs.setFullpath(nex.getName());
                        expand.addFileset(fs);
                        emptySet = false;
                    }
                }
            }

            if (!emptySet) {
                expand.execute();
            }

        }
    }
}

From source file:org.apache.tomcat.maven.plugin.tomcat7.run.AbstractExecWarMojo.java

/**
 * return file can be deleted//from www .j  a v a 2  s .  c o  m
 */
protected File addContextXmlToWar(File contextXmlFile, File warFile) throws IOException, ArchiveException {
    ArchiveOutputStream os = null;
    OutputStream warOutputStream = null;
    File tmpWar = File.createTempFile("tomcat", "war-exec");
    tmpWar.deleteOnExit();

    try {
        warOutputStream = new FileOutputStream(tmpWar);
        os = new ArchiveStreamFactory().createArchiveOutputStream(ArchiveStreamFactory.JAR, warOutputStream);
        os.putArchiveEntry(new JarArchiveEntry("META-INF/context.xml"));
        IOUtils.copy(new FileInputStream(contextXmlFile), os);
        os.closeArchiveEntry();

        JarFile jarFile = new JarFile(warFile);
        extractJarToArchive(jarFile, os, null);
        os.flush();
    } finally {
        IOUtils.closeQuietly(os);
        IOUtils.closeQuietly(warOutputStream);
    }
    return tmpWar;
}

From source file:org.apache.axis2.jaxws.description.builder.JAXWSRIWSDLGenerator.java

/**
 * Walk the classloader hierarchy and add to the classpath
 *
 * @param cl//from w  ww .  j a  v  a 2s .  c om
 * @param classpath
 */
private static void fillClassPath(ClassLoader cl, HashSet classpath) {
    while (cl != null) {
        if (cl instanceof URLClassLoader) {
            URL[] urls = ((URLClassLoader) cl).getURLs();
            for (int i = 0; (urls != null) && i < urls.length; i++) {
                String path = urls[i].getPath();
                //If it is a drive letter, adjust accordingly.
                if (path.length() >= 3 && path.charAt(0) == '/' && path.charAt(2) == ':')
                    path = path.substring(1);
                addPath(classpath, URLDecoder.decode(path));

                // if its a jar extract Class-Path entries from manifest
                File file = new File(urls[i].getFile());
                if (file.isFile()) {
                    FileInputStream fis = null;
                    try {
                        fis = new FileInputStream(file);
                        if (isJar(fis)) {
                            JarFile jar = new JarFile(file);
                            Manifest manifest = jar.getManifest();
                            if (manifest != null) {
                                Attributes attributes = manifest.getMainAttributes();
                                if (attributes != null) {
                                    String s = attributes.getValue(Attributes.Name.CLASS_PATH);
                                    String base = file.getParent();
                                    if (s != null) {
                                        StringTokenizer st = new StringTokenizer(s, " ");
                                        while (st.hasMoreTokens()) {
                                            String t = st.nextToken();
                                            addPath(classpath, base + File.separatorChar + t);
                                        }
                                    }
                                }
                            }
                        }
                    } catch (IOException ioe) {
                    } finally {
                        if (fis != null) {
                            try {
                                fis.close();
                            } catch (IOException ioe2) {
                            }
                        }
                    }
                }
            }
        }
        cl = cl.getParent();
    }
}

From source file:org.apache.juddi.config.Install.java

private static List<String> getPublishers(Configuration config) throws ConfigurationException {
    List<String> publishers = new ArrayList<String>();
    String basePath = JUDDI_CUSTOM_INSTALL_DATA_DIR;
    URL url = ClassUtil.getResource(JUDDI_CUSTOM_INSTALL_DATA_DIR, Install.class);
    if (url == null) {
        url = ClassUtil.getResource(JUDDI_INSTALL_DATA_DIR, Install.class);
        basePath = JUDDI_INSTALL_DATA_DIR;
    }/* w  w  w.  jav  a  2  s . c om*/

    String path = null;
    if ("vfsfile".equals(url.getProtocol())) {
        try {
            path = url.toURI().getPath();
        } catch (URISyntaxException e) {
            throw new ConfigurationException(e);
        }
    } else {
        path = url.getPath();
    }

    File dir = new File(path);
    String rootPublisherStr = config.getString(Property.JUDDI_ROOT_PUBLISHER);
    if (dir.exists()) {
        log.debug("Discovering the Publisher XML data files in directory: " + path);
        File[] files = dir.listFiles(new PublisherFileFilter());
        for (File f : files) {
            String publisher = f.getName().substring(0, f.getName().indexOf(FILE_PUBLISHER));
            if (!rootPublisherStr.equalsIgnoreCase(publisher)) {
                publishers.add(publisher);
            }
        }
    } else {
        String[] paths = {};
        Enumeration<JarEntry> en = null;
        try {

            if (path.indexOf("!") > 0) {
                paths = path.split("!");
                en = new JarFile(new File(new URI(paths[0]))).entries();
            } else {
                // Handle Windows / jboss-5.1.0 case
                if (path.indexOf(".jar") > 0) {
                    paths = path.split(".jar");
                    paths[0] = paths[0] + ".jar";
                    en = new JarFile(new File(paths[0])).entries();
                }
            }
            if (paths.length > 0) {
                log.debug("Discovering the Publisher XML data files in jar: " + paths[0]);
                while (en.hasMoreElements()) {
                    String name = en.nextElement().getName();
                    if (name.startsWith(basePath) && name.endsWith(FILE_PUBLISHER)) {
                        log.debug("Found publisher file=" + name);
                        String publisher = name.substring(basePath.length(), name.indexOf(FILE_PUBLISHER));
                        if (!rootPublisherStr.equalsIgnoreCase(publisher)) {
                            publishers.add(publisher);
                        }
                    }
                }
            } else {
                log.info("No custom configuration files where found in " + path);
            }
        } catch (IOException e) {
            throw new ConfigurationException(e);
        } catch (URISyntaxException e) {
            throw new ConfigurationException(e);
        }
    }
    return publishers;
}

From source file:org.apache.storm.utils.ServerUtils.java

public void extractDirFromJarImpl(String jarpath, String dir, File destdir) {
    try (JarFile jarFile = new JarFile(jarpath)) {
        Enumeration<JarEntry> jarEnums = jarFile.entries();
        while (jarEnums.hasMoreElements()) {
            JarEntry entry = jarEnums.nextElement();
            if (!entry.isDirectory() && entry.getName().startsWith(dir)) {
                File aFile = new File(destdir, entry.getName());
                aFile.getParentFile().mkdirs();
                try (FileOutputStream out = new FileOutputStream(aFile);
                        InputStream in = jarFile.getInputStream(entry)) {
                    IOUtils.copy(in, out);
                }/*w  w  w  .j a  v a 2s  .  c  om*/
            }
        }
    } catch (IOException e) {
        LOG.info("Could not extract {} from {}", dir, jarpath);
    }
}

From source file:eu.stratosphere.yarn.Client.java

private File generateDefaultConf(Path localJarPath) throws IOException, FileNotFoundException {
    JarFile jar = null;/*  ww w  . j a  va2  s. c o m*/
    try {
        jar = new JarFile(localJarPath.toUri().getPath());
    } catch (FileNotFoundException fne) {
        LOG.fatal("Unable to access jar file. Specify jar file or configuration file.", fne);
        System.exit(1);
    }
    InputStream confStream = jar.getInputStream(jar.getEntry("stratosphere-conf.yaml"));

    if (confStream == null) {
        LOG.warn("Given jar file does not contain yaml conf.");
        confStream = this.getClass().getResourceAsStream("stratosphere-conf.yaml");
        if (confStream == null) {
            throw new RuntimeException("Unable to find stratosphere-conf in jar file");
        }
    }
    File outFile = new File("stratosphere-conf.yaml");
    if (outFile.exists()) {
        throw new RuntimeException("File unexpectedly exists");
    }
    FileOutputStream outputStream = new FileOutputStream(outFile);
    int read = 0;
    byte[] bytes = new byte[1024];
    while ((read = confStream.read(bytes)) != -1) {
        outputStream.write(bytes, 0, read);
    }
    confStream.close();
    outputStream.close();
    jar.close();
    return outFile;
}

From source file:UnpackedJarFile.java

public NestedJarFile(JarFile jarFile, String path) throws IOException {
    super(DeploymentUtil.DUMMY_JAR_FILE);

    // verify that the jar actually contains that path
    JarEntry targetEntry = jarFile.getJarEntry(path + "/");
    if (targetEntry == null) {
        targetEntry = jarFile.getJarEntry(path);
        if (targetEntry == null) {
            throw new IOException("Jar entry does not exist: jarFile=" + jarFile.getName() + ", path=" + path);
        }//from   w  ww  .j av a  2 s . c om
    }

    if (targetEntry.isDirectory()) {
        if (targetEntry instanceof UnpackedJarEntry) {
            //unpacked nested module inside unpacked ear
            File targetFile = ((UnpackedJarEntry) targetEntry).getFile();
            baseJar = new UnpackedJarFile(targetFile);
            basePath = "";
        } else {
            baseJar = jarFile;
            if (!path.endsWith("/")) {
                path += "/";
            }
            basePath = path;
        }
    } else {
        if (targetEntry instanceof UnpackedJarEntry) {
            // for unpacked jars we don't need to copy the jar file
            // out to a temp directory, since it is already available
            // as a raw file
            File targetFile = ((UnpackedJarEntry) targetEntry).getFile();
            baseJar = new JarFile(targetFile);
            basePath = "";
        } else {
            tempFile = DeploymentUtil.toFile(jarFile, targetEntry.getName());
            baseJar = new JarFile(tempFile);
            basePath = "";
        }
    }
}

From source file:massbank.admin.VersionManager.java

/**
 * jart@Co?[W?/*w w w . ja  va  2s .  com*/
 * @param path t@CpX
 * @return o?[W?
 */
private VersionInfo getVerJarFile(String path) {
    VersionInfo verInfo = null;
    try {
        // }jtFXgo?[W?
        JarFile jar = new JarFile(new File(path));
        Manifest manifest = jar.getManifest();
        Attributes attributes = manifest.getMainAttributes();
        String item1 = attributes.getValue("Implementation-Version");
        if (item1 == null) {
            item1 = "-";
        }
        // Xy?[X?o?[Wt?o
        String[] item2 = item1.trim().split(" ");
        String ver = item2[0];
        String date = "-";
        if (item2.length > 1) {
            date = item2[1];
        }
        verInfo = new VersionInfo(null, ver, date);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return verInfo;
}