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:azkaban.jobtype.connectors.teradata.TeraDataWalletInitializer.java

/**
 * As of TDCH 1.4.1, integration with Teradata wallet only works with hadoop jar command line command.
 * This is mainly because TDCH depends on the behavior of hadoop jar command line which extracts jar file
 * into hadoop tmp folder.//  w  ww  .jav  a 2  s .c  om
 *
 * This method will extract tdchJarfile and place it into temporary folder, and also add jvm shutdown hook
 * to delete the directory when JVM shuts down.
 * @param tdchJarFile TDCH jar file.
 */
public static void initialize(File tmpDir, File tdchJarFile) {
    synchronized (TeraDataWalletInitializer.class) {
        if (tdchJarExtractedDir != null) {
            return;
        }

        if (tdchJarFile == null) {
            throw new IllegalArgumentException("TDCH jar file cannot be null.");
        }
        if (!tdchJarFile.exists()) {
            throw new IllegalArgumentException(
                    "TDCH jar file does not exist. " + tdchJarFile.getAbsolutePath());
        }
        try {
            //Extract TDCH jar.
            File unJarDir = createUnjarDir(
                    new File(tmpDir.getAbsolutePath() + File.separator + UNJAR_DIR_NAME));
            JarFile jar = new JarFile(tdchJarFile);
            Enumeration<JarEntry> enumEntries = jar.entries();

            while (enumEntries.hasMoreElements()) {
                JarEntry srcFile = enumEntries.nextElement();
                File destFile = new File(unJarDir + File.separator + srcFile.getName());
                if (srcFile.isDirectory()) { // if its a directory, create it
                    destFile.mkdir();
                    continue;
                }

                InputStream is = jar.getInputStream(srcFile);
                BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(destFile));
                IOUtils.copy(is, os);
                close(os);
                close(is);
            }
            jar.close();
            tdchJarExtractedDir = unJarDir;
        } catch (IOException e) {
            throw new RuntimeException("Failed while extracting TDCH jar file.", e);
        }
    }
    logger.info("TDCH jar has been extracted into directory: " + tdchJarExtractedDir.getAbsolutePath());
}

From source file:net.sourceforge.tess4j.util.LoadLibs.java

/**
 * Copies resources from the jar file of the current thread and extract it
 * to the destination path.// w w  w.j a v a  2s  .  c o  m
 *
 * @param jarConnection
 * @param destPath destination file or directory
 */
static void copyJarResourceToPath(JarURLConnection jarConnection, File destPath) {
    try {
        JarFile jarFile = jarConnection.getJarFile();
        String jarConnectionEntryName = jarConnection.getEntryName();

        /**
         * Iterate all entries in the jar file.
         */
        for (Enumeration<JarEntry> e = jarFile.entries(); e.hasMoreElements();) {
            JarEntry jarEntry = e.nextElement();
            String jarEntryName = jarEntry.getName();

            /**
             * Extract files only if they match the path.
             */
            if (jarEntryName.startsWith(jarConnectionEntryName)) {
                String filename = jarEntryName.substring(jarConnectionEntryName.length());
                File currentFile = new File(destPath, filename);

                if (jarEntry.isDirectory()) {
                    currentFile.mkdirs();
                } else {
                    currentFile.deleteOnExit();
                    InputStream is = jarFile.getInputStream(jarEntry);
                    OutputStream out = FileUtils.openOutputStream(currentFile);
                    IOUtils.copy(is, out);
                    is.close();
                    out.close();
                }
            }
        }
    } catch (IOException e) {
        logger.log(Level.SEVERE, e.getMessage(), e);
    }
}

From source file:io.fabric8.vertx.maven.plugin.utils.WebJars.java

/**
 * Checks whether the given file is a WebJar or not (http://www.webjars.org/documentation).
 * The check is based on the presence of {@literal META-INF/resources/webjars/} directory in the jar file.
 *
 * @param file the file.//from  ww w .j a  va 2s  .c  o m
 * @return {@literal true} if it's a bundle, {@literal false} otherwise.
 */
public static boolean isWebJar(Log log, File file) {
    if (file == null) {
        return false;
    }
    Set<String> found = new LinkedHashSet<>();
    if (file.isFile() && file.getName().endsWith(".jar")) {
        JarFile jar = null;
        try {
            jar = new JarFile(file);

            // Fast return if the base structure is not there
            if (jar.getEntry(WEBJAR_LOCATION) == null) {
                return false;
            }

            Enumeration<JarEntry> entries = jar.entries();
            while (entries.hasMoreElements()) {
                JarEntry entry = entries.nextElement();
                Matcher matcher = WEBJAR_REGEX.matcher(entry.getName());
                if (matcher.matches()) {
                    found.add(matcher.group(1) + "-" + matcher.group(2));
                }
            }
        } catch (IOException e) {
            log.error("Cannot check if the file " + file.getName() + " is a webjar, cannot open it", e);
            return false;
        } finally {
            final JarFile finalJar = jar;
            IOUtils.closeQuietly(() -> {
                if (finalJar != null) {
                    finalJar.close();
                }
            });
        }

        for (String lib : found) {
            log.info("Web Library found in " + file.getName() + " : " + lib);
        }

        return !found.isEmpty();
    }

    return false;
}

From source file:net.lightbody.bmp.proxy.jetty.util.JarResource.java

public static void extract(Resource resource, File directory, boolean deleteOnExit) throws IOException {
    if (log.isDebugEnabled())
        log.debug("Extract " + resource + " to " + directory);
    JarInputStream jin = new JarInputStream(resource.getInputStream());
    JarEntry entry = null;
    while ((entry = jin.getNextJarEntry()) != null) {
        File file = new File(directory, entry.getName());
        if (entry.isDirectory()) {
            // Make directory
            if (!file.exists())
                file.mkdirs();//w  w  w .  ja  va 2 s.  c  o  m
        } else {
            // make directory (some jars don't list dirs)
            File dir = new File(file.getParent());
            if (!dir.exists())
                dir.mkdirs();

            // Make file
            FileOutputStream fout = null;
            try {
                fout = new FileOutputStream(file);
                IO.copy(jin, fout);
            } finally {
                IO.close(fout);
            }

            // touch the file.
            if (entry.getTime() >= 0)
                file.setLastModified(entry.getTime());
        }
        if (deleteOnExit)
            file.deleteOnExit();
    }
}

From source file:org.jiemamy.utils.ResourceTraversal.java

/**
 * ???/*  w  ww . j  av a  2 s  .c o  m*/
 * 
 * @param jarFile JarFile
 * @param handler ?
 * @throws IOException ????
 * @throws TraversalHandlerException ??????? 
 * @throws IllegalArgumentException ?{@code null}???
 */
public static void forEach(JarFile jarFile, ResourceHandler handler)
        throws IOException, TraversalHandlerException {
    Validate.notNull(jarFile);
    Validate.notNull(handler);
    Enumeration<JarEntry> enumeration = jarFile.entries();
    while (enumeration.hasMoreElements()) {
        JarEntry entry = enumeration.nextElement();
        if (!entry.isDirectory()) {
            String entryName = entry.getName().replace('\\', '/');
            InputStream is = jarFile.getInputStream(entry);
            try {
                handler.processResource(entryName, is);
            } finally {
                IOUtils.closeQuietly(is);
            }
        }
    }
}

From source file:org.jdesktop.wonderland.modules.service.ModuleManagerUtils.java

/**
 * Expands a jar file into a given directory, given the jar file and the
 * directory into which the contents should be written.
 * //from w  w  w  .j a v a2 s .c o  m
 * @throw IOException Upon error expanding the Jar file
 */
public static void expandJar(JarFile jarFile, File root) throws IOException {
    /*
     * Loop through each entry, fetchs its input stream, and write to an
     * output stream for the file.
     */
    Enumeration<JarEntry> entries = jarFile.entries();
    while (entries.hasMoreElements() == true) {
        JarEntry entry = entries.nextElement();
        InputStream is = jarFile.getInputStream(entry);
        String entryName = entry.getName();

        /* Don't expand anything that beings with META-INF */
        if (entryName.startsWith("META-INF") == true) {
            continue;
        }

        /* Ignore if it is a directory, then create it */
        if (entryName.endsWith("/") == true) {
            File file = new File(root, entryName);
            file.mkdirs();
            continue;
        }

        /* Write out to a file in 'root' */
        File file = new File(root, entryName);
        FileOutputStream os = new FileOutputStream(file);
        byte[] b = new byte[CHUNK_SIZE];
        while (true) {
            int len = is.read(b);
            if (len == -1) {
                break;
            }
            os.write(b, 0, len);
        }
        is.close();
        os.close();
    }
}

From source file:com.katsu.dwm.reflection.JarUtils.java

/**
 * Return as stream a resource in a jar//from  w w  w . j av a 2  s.  co  m
 * @param jar
 * @param resource 
 */
public static InputStream getResourceAsStreamFromJar(File jar, String resource) {
    JarInputStream jis = null;
    try {
        jis = new JarInputStream(new FileInputStream(jar));
        JarEntry je;
        while ((je = jis.getNextJarEntry()) != null) {
            logger.trace(jar.getName() + " " + je.getName());
            if (je.getName().equals(resource)) {
                return jis;
            }
        }
    } catch (Exception ex) {
        logger.error(ex + " " + jar.getPath());
    } finally {
        if (jis != null) {
            try {
                jis.close();
            } catch (IOException e) {
                logger.error(e);
            }
        }
    }
    return null;
}

From source file:org.jsweet.transpiler.candies.CandyDescriptor.java

public static CandyDescriptor fromCandyJar(JarFile jarFile, String jsOutputDirPath) throws IOException {
    JarEntry pomEntry = null;// ww  w . j ava 2 s.c  o m
    Enumeration<JarEntry> entries = jarFile.entries();
    while (entries.hasMoreElements()) {
        JarEntry current = entries.nextElement();
        if (current.getName().endsWith("pom.xml")) {
            pomEntry = current;
        }
    }

    String pomContent = IOUtils.toString(jarFile.getInputStream(pomEntry));

    // take only general part
    int dependenciesIndex = pomContent.indexOf("<dependencies>");
    String pomGeneralPart = dependenciesIndex > 0 ? pomContent.substring(0, dependenciesIndex) : pomContent;

    // extract candy model version from <groupId></groupId>
    Matcher matcher = MODEL_VERSION_PATTERN.matcher(pomGeneralPart);
    String modelVersion = "unknown";
    if (matcher.find()) {
        modelVersion = matcher.group(1);
    }

    // extract name from <artifactId></artifactId>
    matcher = ARTIFACT_ID_PATTERN.matcher(pomGeneralPart);
    String name = "unknown";
    if (matcher.find()) {
        name = matcher.group(1);
    }

    matcher = VERSION_PATTERN.matcher(pomGeneralPart);
    String version = "unknown";
    if (matcher.find()) {
        version = matcher.group(1);
    }

    long lastUpdateTimestamp = jarFile.getEntry("META-INF/MANIFEST.MF").getTime();

    String transpilerVersion = null;

    ZipEntry metadataEntry = jarFile.getEntry("META-INF/candy-metadata.json");
    if (metadataEntry != null) {
        String metadataContent = IOUtils.toString(jarFile.getInputStream(metadataEntry));

        @SuppressWarnings("unchecked")
        Map<String, ?> metadata = gson.fromJson(metadataContent, Map.class);

        transpilerVersion = (String) metadata.get("transpilerVersion");
    }

    String jsDirPath = "META-INF/resources/webjars/" + name + "/" + version;
    ZipEntry jsDirEntry = jarFile.getEntry(jsDirPath);
    List<String> jsFilesPaths = new LinkedList<>();
    if (jsDirEntry != null) {
        // collects js files
        jarFile.stream() //
                .filter(entry -> entry.getName().startsWith(jsDirPath) && entry.getName().endsWith(".js")) //
                .map(entry -> entry.getName()) //
                .forEach(jsFilesPaths::add);
    }

    return new CandyDescriptor( //
            name, //
            version, //
            lastUpdateTimestamp, //
            modelVersion, //
            transpilerVersion, //
            jsOutputDirPath, //
            jsDirPath, //
            jsFilesPaths);
}

From source file:org.shept.util.JarUtils.java

/**
 * Copy resources from a classPath, typically within a jar file 
 * to a specified destination, typically a resource directory in
 * the projects webApp directory (images, sounds, e.t.c. )
 * // ww  w.  j  a  v a2 s.  c  o m
 * Copies resources only if the destination file does not exist and
 * the specified resource is available.
 * 
 * The ClassPathResource will be scanned for all resources in the path specified by the resource.
 * For example  a path like:
 *    new ClassPathResource("resource/images/pager/", SheptBaseController.class);
 * takes all the resources in the path 'resource/images/pager' (but not in sub-path)
 * from the specified clazz 'SheptBaseController'
 * 
 * @param cpr ClassPathResource specifying the source location on the classPath (maybe within a jar)
 * @param webAppDestPath Full path String to the fileSystem destination directory   
 * @throws IOException when copying on copy error
 * @throws URISyntaxException 
 */
public static void copyResources(ClassPathResource cpr, String webAppDestPath)
        throws IOException, URISyntaxException {
    String dstPath = webAppDestPath; //  + "/" + jarPathInternal(cpr.getURL());
    File dir = new File(dstPath);
    dir.mkdirs();

    URL url = cpr.getURL();
    // jarUrl is the URL of the containing lib, e.g. shept.org in this case
    URL jarUrl = ResourceUtils.extractJarFileURL(url);
    String urlFile = url.getFile();
    String resPath = "";
    int separatorIndex = urlFile.indexOf(ResourceUtils.JAR_URL_SEPARATOR);
    if (separatorIndex != -1) {
        // just copy the the location path inside the jar without leading separators !/
        resPath = urlFile.substring(separatorIndex + ResourceUtils.JAR_URL_SEPARATOR.length());
    } else {
        return; // no resource within jar to copy
    }

    File f = new File(ResourceUtils.toURI(jarUrl));
    JarFile jf = new JarFile(f);

    Enumeration<JarEntry> entries = jf.entries();
    while (entries.hasMoreElements()) {
        JarEntry entry = entries.nextElement();
        String path = entry.getName();
        if (path.startsWith(resPath) && entry.getSize() > 0) {
            String fileName = path.substring(path.lastIndexOf("/"));
            File dstFile = new File(dstPath, fileName); //  (StringUtils.applyRelativePath(dstPath, fileName));
            Resource fileRes = cpr.createRelative(fileName);
            if (!dstFile.exists() && fileRes.exists()) {
                FileOutputStream fos = new FileOutputStream(dstFile);
                FileCopyUtils.copy(fileRes.getInputStream(), fos);
                logger.info("Successfully copied file " + fileName + " from " + cpr.getPath() + " to "
                        + dstFile.getPath());
            }
        }
    }

    if (jf != null) {
        jf.close();
    }

}

From source file:org.mrgeo.utils.ClassLoaderUtil.java

public static List<URL> loadJar(String path, URL resource) throws IOException {
    JarURLConnection conn = (JarURLConnection) resource.openConnection();
    JarFile jarFile = conn.getJarFile();
    Enumeration<JarEntry> entries = jarFile.entries();
    List<URL> result = new LinkedList<URL>();

    String p = path;//from  w  ww .j  a  v  a  2s .  co  m
    if (p.endsWith("/") == false) {
        p = p + "/";
    }

    while (entries.hasMoreElements()) {
        JarEntry entry = entries.nextElement();
        if ((!entry.getName().equals(p))
                && (entry.getName().startsWith(p) || entry.getName().startsWith("WEB-INF/classes/" + p))) {
            URL url = new URL("jar:" + new URL("file", null, jarFile.getName() + "!/" + entry.getName()));
            result.add(url);
        }
    }

    return result;
}