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.jeeframework.util.resource.ResolverUtil.java

/**
 * Finds matching classes within a jar files that contains a folder structure
 * matching the package structure.  If the File is not a JarFile or does not exist a warning
 * will be logged, but no error will be raised.
 *
 * @param test a Test used to filter the classes that are discovered
 * @param parent the parent package under which classes must be in order to be considered
 * @param jarfile the jar file to be examined for classes
 *//*from w  w  w.ja v  a 2  s. c  o m*/
private void loadImplementationsInJar(Test test, String parent, File jarfile) {

    try {
        JarEntry entry;
        JarInputStream jarStream = new JarInputStream(new FileInputStream(jarfile));

        while ((entry = jarStream.getNextJarEntry()) != null) {
            String name = entry.getName();
            if (!entry.isDirectory() && name.startsWith(parent) && name.endsWith(".class")) {
                addIfMatching(test, name);
            }
        }
    } catch (IOException ioe) {
        log.error("Could not search jar file '" + jarfile + "' for classes matching criteria: " + test
                + " due to an IOException", ioe);
    }
}

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

private void serveFileFromJarFile(HttpServletResponse response, File jar, String subPath) throws IOException {
    JarFile jarFile = null;//ww w  . ja  va  2 s  . 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.openspaces.maven.plugin.CreatePUProjectMojo.java

/**
 * Extracts the project files to the project directory.
 *///from   w w w  .j a  va  2  s . c o  m
private void extract(URL url) throws Exception {
    packageDirs = packageName.replaceAll("\\.", "/");
    String puTemplate = DIR_TEMPLATES + "/" + template + "/";
    int length = puTemplate.length() - 1;
    BufferedInputStream bis = new BufferedInputStream(url.openStream());
    JarInputStream jis = new JarInputStream(bis);
    JarEntry je;
    byte[] buf = new byte[1024];
    int n;
    while ((je = jis.getNextJarEntry()) != null) {
        String jarEntryName = je.getName();
        PluginLog.getLog().debug("JAR entry: " + jarEntryName);
        if (je.isDirectory() || !jarEntryName.startsWith(puTemplate)) {
            continue;
        }
        String targetFileName = projectDir + jarEntryName.substring(length);

        // convert the ${gsGroupPath} to directory
        targetFileName = StringUtils.replace(targetFileName, FILTER_GROUP_PATH, packageDirs);
        PluginLog.getLog().debug("Extracting entry " + jarEntryName + " to " + targetFileName);

        // read the bytes to the buffer
        ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
        while ((n = jis.read(buf, 0, 1024)) > -1) {
            byteStream.write(buf, 0, n);
        }

        // replace property references with the syntax ${property_name}
        // to their respective property values.
        String data = byteStream.toString();
        data = StringUtils.replace(data, FILTER_GROUP_ID, packageName);
        data = StringUtils.replace(data, FILTER_ARTIFACT_ID, projectDir.getName());
        data = StringUtils.replace(data, FILTER_GROUP_PATH, packageDirs);

        // write the entire converted file content to the destination file.
        File f = new File(targetFileName);
        File dir = f.getParentFile();
        if (!dir.exists()) {
            dir.mkdirs();
        }
        FileWriter writer = new FileWriter(f);
        writer.write(data);
        jis.closeEntry();
        writer.close();
    }
    jis.close();
}

From source file:se.sics.kompics.p2p.experiment.dsl.SimulationScenario.java

/**
 * Gets the resources from jar./*w w  w .  j a  v a2s  .  c om*/
 * 
 * @param jar
 *            the jar
 * 
 * @return the resources from jar
 * 
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
private static LinkedList<String> getResourcesFromJar(File jar) throws IOException {
    JarFile j = new JarFile(jar);

    LinkedList<String> list = new LinkedList<String>();

    Enumeration<JarEntry> entries = j.entries();
    while (entries.hasMoreElements()) {
        JarEntry entry = entries.nextElement();

        if (!entry.getName().endsWith(".class") && !entry.isDirectory()
                && !entry.getName().startsWith("META-INF")) {
            String resourceName = entry.getName();
            list.add(resourceName);
        }
    }
    return list;
}

From source file:co.cask.cdap.internal.app.runtime.spark.SparkRuntimeService.java

/**
 * Updates the dependency jar packaged by the {@link ApplicationBundler#createBundle(Location, Iterable,
 * Iterable)} by moving the things inside classes, lib, resources a level up as expected by spark.
 *
 * @param dependencyJar {@link Location} of the job jar to be updated
 * @param context       {@link BasicSparkContext} of this job
 *//*from  w  w w  .ja  v  a2s . com*/
private Location updateDependencyJar(Location dependencyJar, BasicSparkContext context) throws IOException {

    final String[] prefixToStrip = { ApplicationBundler.SUBDIR_CLASSES, ApplicationBundler.SUBDIR_LIB,
            ApplicationBundler.SUBDIR_RESOURCES };

    Id.Program programId = context.getProgram().getId();

    Location updatedJar = locationFactory.create(String.format("%s.%s.%s.%s.%s.jar",
            ProgramType.SPARK.name().toLowerCase(), programId.getAccountId(), programId.getApplicationId(),
            programId.getId(), context.getRunId().getId()));

    // Creates Manifest
    Manifest manifest = new Manifest();
    manifest.getMainAttributes().put(ManifestFields.MANIFEST_VERSION, "1.0");
    JarOutputStream jarOutput = new JarOutputStream(updatedJar.getOutputStream(), manifest);

    try {
        JarInputStream jarInput = new JarInputStream(dependencyJar.getInputStream());

        try {
            JarEntry jarEntry = jarInput.getNextJarEntry();

            while (jarEntry != null) {
                boolean isDir = jarEntry.isDirectory();
                String entryName = jarEntry.getName();
                String newEntryName = entryName;

                for (String prefix : prefixToStrip) {
                    if (entryName.startsWith(prefix) && !entryName.equals(prefix)) {
                        newEntryName = entryName.substring(prefix.length());
                    }
                }

                jarEntry = new JarEntry(newEntryName);
                jarOutput.putNextEntry(jarEntry);
                if (!isDir) {
                    ByteStreams.copy(jarInput, jarOutput);
                }
                jarEntry = jarInput.getNextJarEntry();
            }
        } finally {
            jarInput.close();
            Locations.deleteQuietly(dependencyJar);
        }
    } finally {
        jarOutput.close();
    }
    return updatedJar;
}

From source file:com.datatorrent.stram.client.StramAppLauncher.java

private void init(String tmpName) throws Exception {
    File baseDir = StramClientUtils.getUserDTDirectory();
    baseDir = new File(new File(baseDir, "appcache"), tmpName);
    baseDir.mkdirs();//from  ww  w  .  j a  va 2 s  .  c o  m
    LinkedHashSet<URL> clUrls;
    List<String> classFileNames = new ArrayList<String>();

    if (jarFile != null) {
        JarFileContext jfc = new JarFileContext(new java.util.jar.JarFile(jarFile), mvnBuildClasspathOutput);
        jfc.cacheDir = baseDir;

        java.util.Enumeration<JarEntry> entriesEnum = jfc.jarFile.entries();
        while (entriesEnum.hasMoreElements()) {
            java.util.jar.JarEntry jarEntry = entriesEnum.nextElement();
            if (!jarEntry.isDirectory()) {
                if (jarEntry.getName().endsWith("pom.xml")) {
                    jfc.pomEntry = jarEntry;
                } else if (jarEntry.getName().endsWith(".app.properties")) {
                    File targetFile = new File(baseDir, jarEntry.getName());
                    FileUtils.copyInputStreamToFile(jfc.jarFile.getInputStream(jarEntry), targetFile);
                    appResourceList.add(new PropertyFileAppFactory(targetFile));
                } else if (jarEntry.getName().endsWith(".class")) {
                    classFileNames.add(jarEntry.getName());
                }
            }
        }

        URL mainJarUrl = new URL("jar", "", "file:" + jarFile.getAbsolutePath() + "!/");
        jfc.urls.add(mainJarUrl);

        deployJars = Sets.newLinkedHashSet();
        // add all jar files from same directory
        Collection<File> jarFiles = FileUtils.listFiles(jarFile.getParentFile(), new String[] { "jar" }, false);
        for (File lJarFile : jarFiles) {
            jfc.urls.add(lJarFile.toURI().toURL());
            deployJars.add(lJarFile);
        }

        // resolve dependencies
        List<Resolver> resolvers = Lists.newArrayList();

        String resolverConfig = this.propertiesBuilder.conf.get(CLASSPATH_RESOLVERS_KEY_NAME, null);
        if (!StringUtils.isEmpty(resolverConfig)) {
            resolvers = new ClassPathResolvers().createResolvers(resolverConfig);
        } else {
            // default setup if nothing was configured
            String manifestCp = jfc.jarFile.getManifest().getMainAttributes()
                    .getValue(ManifestResolver.ATTR_NAME);
            if (manifestCp != null) {
                File repoRoot = new File(System.getProperty("user.home") + "/.m2/repository");
                if (repoRoot.exists()) {
                    LOG.debug("Resolving manifest attribute {} based on {}", ManifestResolver.ATTR_NAME,
                            repoRoot);
                    resolvers.add(new ClassPathResolvers.ManifestResolver(repoRoot));
                } else {
                    LOG.warn("Ignoring manifest attribute {} because {} does not exist.",
                            ManifestResolver.ATTR_NAME, repoRoot);
                }
            }
        }

        for (Resolver r : resolvers) {
            r.resolve(jfc);
        }

        jfc.jarFile.close();

        URLConnection urlConnection = mainJarUrl.openConnection();
        if (urlConnection instanceof JarURLConnection) {
            // JDK6 keeps jar file shared and open as long as the process is running.
            // we want the jar file to be opened on every launch to pick up latest changes
            // http://abondar-howto.blogspot.com/2010/06/howto-unload-jar-files-loaded-by.html
            // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4167874
            ((JarURLConnection) urlConnection).getJarFile().close();
        }
        clUrls = jfc.urls;
    } else {
        clUrls = new LinkedHashSet<URL>();
    }

    // add the jar dependencies
    /*
        if (cp == null) {
          // dependencies from parent loader, if classpath can't be found from pom
          ClassLoader baseCl = StramAppLauncher.class.getClassLoader();
          if (baseCl instanceof URLClassLoader) {
            URL[] baseUrls = ((URLClassLoader)baseCl).getURLs();
            // launch class path takes precedence - add first
            clUrls.addAll(Arrays.asList(baseUrls));
          }
        }
    */

    String libjars = propertiesBuilder.conf.get(LIBJARS_CONF_KEY_NAME);
    if (libjars != null) {
        processLibJars(libjars, clUrls);
    }

    for (URL baseURL : clUrls) {
        LOG.debug("Dependency: {}", baseURL);
    }

    this.launchDependencies = clUrls;

    // we have the classpath dependencies, scan for java configurations
    findAppConfigClasses(classFileNames);

}

From source file:com.github.ithildir.liferay.mobile.go.GoSDKBuilder.java

protected void copyJarResource(JarURLConnection jarConnection, File destinationDir) throws IOException {

    String jarConnectionEntryName = jarConnection.getEntryName();
    JarFile jarFile = jarConnection.getJarFile();

    Enumeration<JarEntry> enu = jarFile.entries();

    while (enu.hasMoreElements()) {
        JarEntry jarEntry = enu.nextElement();
        String jarEntryName = jarEntry.getName();

        if (jarEntryName.startsWith(jarConnectionEntryName)) {
            String fileName = jarEntryName;

            if (fileName.startsWith(jarConnectionEntryName)) {
                fileName = fileName.substring(jarConnectionEntryName.length());
            }//from w w  w.  j ava 2 s  .  c  o m

            File file = new File(destinationDir, fileName);

            if (jarEntry.isDirectory()) {
                file.mkdirs();
            } else {
                InputStream is = null;

                try {
                    is = jarFile.getInputStream(jarEntry);

                    FileUtils.copyInputStreamToFile(is, file);
                } finally {
                    IOUtils.closeQuietly(is);
                }
            }
        }
    }
}

From source file:org.apache.struts2.convention.DefaultClassFinder.java

private List<String> jar(JarInputStream jarStream) throws IOException {
    List<String> classNames = new ArrayList<>();

    JarEntry entry;
    while ((entry = jarStream.getNextJarEntry()) != null) {
        if (entry.isDirectory() || !entry.getName().endsWith(".class")) {
            continue;
        }//from  w w  w.  j a  v a2s  .  com
        String className = entry.getName();
        className = className.replaceFirst(".class$", "");

        //war files are treated as .jar files, so takeout WEB-INF/classes
        className = StringUtils.removeStart(className, "WEB-INF/classes/");

        className = className.replace('/', '.');
        classNames.add(className);
    }

    return classNames;
}

From source file:org.jasig.portal.plugin.deployer.AbstractExtractingEarDeployer.java

/**
 * Reads the specified {@link JarEntry} from the {@link JarFile} assuming that the
 * entry represents another a JAR file. The files in the {@link JarEntry} will be
 * extracted using the contextDir as the base directory. 
 * // w ww  .  j a va  2s.  co m
 * @param earFile The JarEntry for the JAR to read from the archive.
 * @param earEntry The JarFile to get the {@link InputStream} for the file from.
 * @param contextDir The directory to extract the JAR to.
 * @throws IOException If the extracting of data from the JarEntry fails.
 */
protected void extractWar(JarFile earFile, final JarEntry earEntry, final File contextDir)
        throws MojoFailureException {
    if (this.getLogger().isInfoEnabled()) {
        this.getLogger().info("Extracting EAR entry '" + earFile.getName() + "!" + earEntry.getName() + "' to '"
                + contextDir + "'");
    }

    if (!contextDir.exists()) {
        if (this.getLogger().isDebugEnabled()) {
            this.getLogger().debug("Creating context directory entry '" + contextDir + "'");
        }

        try {
            FileUtils.forceMkdir(contextDir);
        } catch (IOException e) {
            throw new MojoFailureException("Failed to create '" + contextDir + "' to extract '"
                    + earEntry.getName() + "' out of '" + earFile.getName() + "' into", e);
        }
    }

    JarInputStream warInputStream = null;
    try {
        warInputStream = new JarInputStream(earFile.getInputStream(earEntry));

        // Write out the MANIFEST.MF file to the target directory
        Manifest manifest = warInputStream.getManifest();
        if (manifest != null) {
            FileOutputStream manifestFileOutputStream = null;
            try {
                final File manifestFile = new File(contextDir, MANIFEST_PATH);
                manifestFile.getParentFile().mkdirs();
                manifestFileOutputStream = new FileOutputStream(manifestFile);
                manifest.write(manifestFileOutputStream);
            } catch (Exception e) {
                this.getLogger().error("Failed to copy the MANIFEST.MF file for ear entry '"
                        + earEntry.getName() + "' out of '" + earFile.getName() + "'", e);
                throw new MojoFailureException("Failed to copy the MANIFEST.MF file for ear entry '"
                        + earEntry.getName() + "' out of '" + earFile.getName() + "'", e);
            } finally {
                try {
                    if (manifestFileOutputStream != null) {
                        manifestFileOutputStream.close();
                    }
                } catch (Exception e) {
                    this.getLogger().warn("Error closing the OutputStream for MANIFEST.MF in warEntry:  "
                            + earEntry.getName());
                }
            }
        }

        JarEntry warEntry;
        while ((warEntry = warInputStream.getNextJarEntry()) != null) {
            final File warEntryFile = new File(contextDir, warEntry.getName());

            if (warEntry.isDirectory()) {
                if (this.getLogger().isDebugEnabled()) {
                    this.getLogger().debug("Creating WAR directory entry '" + earEntry.getName() + "!"
                            + warEntry.getName() + "' as '" + warEntryFile + "'");
                }

                FileUtils.forceMkdir(warEntryFile);
            } else {
                if (this.getLogger().isDebugEnabled()) {
                    this.getLogger().debug("Extracting WAR entry '" + earEntry.getName() + "!"
                            + warEntry.getName() + "' to '" + warEntryFile + "'");
                }

                FileUtils.forceMkdir(warEntryFile.getParentFile());

                final FileOutputStream jarEntryFileOutputStream = new FileOutputStream(warEntryFile);
                try {
                    IOUtils.copy(warInputStream, jarEntryFileOutputStream);
                } finally {
                    IOUtils.closeQuietly(jarEntryFileOutputStream);
                }
            }
        }
    } catch (IOException e) {
        throw new MojoFailureException("Failed to extract EAR entry '" + earEntry.getName() + "' out of '"
                + earFile.getName() + "' to '" + contextDir + "'", e);
    } finally {
        IOUtils.closeQuietly(warInputStream);
    }
}

From source file:org.apache.camel.impl.DefaultPackageScanClassResolver.java

/**
 * Finds matching classes within a jar files that contains a folder
 * structure matching the package structure. If the File is not a JarFile or
 * does not exist a warning will be logged, but no error will be raised.
 *
 * @param test    a Test used to filter the classes that are discovered
 * @param parent  the parent package under which classes must be in order to
 *                be considered/*w  w  w. ja va  2 s . c o m*/
 * @param stream  the inputstream of the jar file to be examined for classes
 * @param urlPath the url of the jar file to be examined for classes
 */
private void loadImplementationsInJar(PackageScanFilter test, String parent, InputStream stream, String urlPath,
        Set<Class<?>> classes) {
    JarInputStream jarStream = null;
    try {
        jarStream = new JarInputStream(stream);

        JarEntry entry;
        while ((entry = jarStream.getNextJarEntry()) != null) {
            String name = entry.getName();
            if (name != null) {
                name = name.trim();
                if (!entry.isDirectory() && name.startsWith(parent) && name.endsWith(".class")) {
                    addIfMatching(test, name, classes);
                }
            }
        }
    } catch (IOException ioe) {
        log.warn("Cannot search jar file '" + urlPath + "' for classes matching criteria: " + test
                + " due to an IOException: " + ioe.getMessage(), ioe);
    } finally {
        IOHelper.close(jarStream, urlPath, log);
    }
}