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:com.streamsets.datacollector.cluster.TestTarFileCreator.java

private static void readJar(TarInputStream tis) throws IOException {
    TarEntry fileEntry = readFile(tis);/*from  ww  w .  j a va 2  s  .  c o m*/
    byte[] buffer = new byte[8192 * 8];
    int read = IOUtils.read(tis, buffer);
    JarInputStream jar = new JarInputStream(new ByteArrayInputStream(buffer, 0, read));
    JarEntry entry = jar.getNextJarEntry();
    Assert.assertNotNull(Utils.format("Read {} bytes and found a null entry", read), entry);
    Assert.assertEquals("sample.txt", entry.getName());
    read = IOUtils.read(jar, buffer);
    Assert.assertEquals(FilenameUtils.getBaseName(fileEntry.getName()),
            new String(buffer, 0, read, StandardCharsets.UTF_8));
}

From source file:org.apache.hadoop.hbase.util.RunTrigger.java

public static void unJar(File jarFile, File toDir) throws IOException {
    JarFile jar = new JarFile(jarFile);
    try {//from  w  ww . j  a  v  a 2  s . co  m
        Enumeration entries = jar.entries();
        while (entries.hasMoreElements()) {
            JarEntry entry = (JarEntry) entries.nextElement();
            if (!entry.isDirectory()) {
                InputStream in = jar.getInputStream(entry);
                try {
                    File file = new File(toDir, entry.getName());
                    if (!file.getParentFile().mkdirs()) {
                        if (!file.getParentFile().isDirectory()) {
                            throw new IOException("Mkdirs failed to create " + file.getParentFile().toString());
                        }
                    }
                    OutputStream out = new FileOutputStream(file);
                    try {
                        byte[] buffer = new byte[8192];
                        int i;
                        while ((i = in.read(buffer)) != -1) {
                            out.write(buffer, 0, i);
                        }
                    } finally {
                        out.close();
                    }
                } finally {
                    in.close();
                }
            }
        }
    } finally {
        jar.close();
    }
}

From source file:org.datavyu.util.NativeLoader.java

/**
 * Unpacks a native application to a temporary location so that it can be
 * utilized from within java code.//w  w w  . ja  v  a 2s.  c  o m
 *
 * @param appJar The jar containing the native app that you want to unpack.
 * @return The path of the native app as unpacked to a temporary location.
 *
 * @throws Exception If unable to unpack the native app to a temporary
 * location.
 */
public static String unpackNativeApp(final String appJar) throws Exception {
    final String nativeLibraryPath;

    if (nativeLibFolder == null) {
        nativeLibraryPath = System.getProperty("java.io.tmpdir") + UUID.randomUUID().toString() + "nativelibs";
        nativeLibFolder = new File(nativeLibraryPath);

        if (!nativeLibFolder.exists()) {
            nativeLibFolder.mkdir();
        }
    }

    // Search the class path for the application jar.
    JarFile jar = null;

    // BugID: 26178921 -- We need to inspect the surefire test class path as
    // well as the regular class path property so that we can scan dependencies
    // during tests.
    String searchPath = System.getProperty("surefire.test.class.path") + File.pathSeparator
            + System.getProperty("java.class.path");

    for (String s : searchPath.split(File.pathSeparator)) {
        // Success! We found a matching jar.
        if (s.endsWith(appJar + ".jar") || s.endsWith(appJar)) {
            jar = new JarFile(s);
        }
    }

    // If we found a jar - it should contain the desired application.
    // decompress as needed.
    if (jar != null) {
        Enumeration<JarEntry> entries = jar.entries();

        while (entries.hasMoreElements()) {
            JarEntry inFile = entries.nextElement();
            File outFile = new File(nativeLibFolder, inFile.getName());

            // If the file from the jar is a directory, create it.
            if (inFile.isDirectory()) {
                outFile.mkdir();

                // The file from the jar is regular - decompress it.
            } else {
                InputStream in = jar.getInputStream(inFile);

                // Create a temporary output location for the library.
                FileOutputStream out = new FileOutputStream(outFile);
                BufferedOutputStream dest = new BufferedOutputStream(out, BUFFER);
                int count;
                byte[] data = new byte[BUFFER];

                while ((count = in.read(data, 0, BUFFER)) != -1) {
                    dest.write(data, 0, count);
                }

                dest.flush();
                dest.close();
                out.close();
                in.close();
            }

            loadedLibs.add(outFile);
        }

        // Unable to find jar file - abort decompression.
    } else {
        System.err.println("Unable to find jar file for unpacking: " + appJar + ". Java classpath is:");

        for (String s : System.getProperty("java.class.path").split(File.pathSeparator)) {
            System.err.println("    " + s);
        }

        throw new Exception("Unable to find '" + appJar + "' for unpacking.");
    }

    return nativeLibFolder.getAbsolutePath();
}

From source file:com.moss.nomad.core.packager.Packager.java

private static String[] listJarPaths(File file) throws Exception {

    JarFile jar = new JarFile(file);
    Enumeration<JarEntry> e = jar.entries();
    List<String> paths = new ArrayList<String>();

    while (e.hasMoreElements()) {
        JarEntry entry = e.nextElement();
        paths.add(entry.getName());
    }/*from ww  w .ja v a  2 s. co  m*/

    return paths.toArray(new String[0]);
}

From source file:ch.rasc.embeddedtc.plugin.PackageTcWarMojo.java

private static void extractJarToArchive(JarFile file, ArchiveOutputStream aos) throws IOException {
    Enumeration<? extends JarEntry> entries = file.entries();
    while (entries.hasMoreElements()) {
        JarEntry j = entries.nextElement();
        if (!"META-INF/MANIFEST.MF".equals(j.getName())) {
            aos.putArchiveEntry(new JarArchiveEntry(j.getName()));
            IOUtils.copy(file.getInputStream(j), aos);
            aos.closeArchiveEntry();/*from   w ww .  ja  v a 2s .c  o  m*/
        }
    }
}

From source file:io.tempra.AppServer.java

public static void copyJarResourceToFolder(JarURLConnection jarConnection, File destDir) {

    try {//w  w w.  java2s  .c o m
        JarFile jarFile = jarConnection.getJarFile();

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

            JarEntry jarEntry = e.nextElement();
            String jarEntryName = jarEntry.getName();
            String jarConnectionEntryName = jarConnection.getEntryName();

            /**
             * Extract files only if they match the path.
             */
            if (jarEntryName.startsWith(jarConnectionEntryName)) {

                String filename = jarEntryName.startsWith(jarConnectionEntryName)
                        ? jarEntryName.substring(jarConnectionEntryName.length())
                        : jarEntryName;
                File currentFile = new File(destDir, filename);

                if (jarEntry.isDirectory()) {
                    currentFile.mkdirs();
                } else {
                    InputStream is = jarFile.getInputStream(jarEntry);
                    OutputStream out = FileUtils.openOutputStream(currentFile);
                    IOUtils.copy(is, out);
                    is.close();
                    out.close();
                }
            }
        }
    } catch (IOException e) {
        // TODO add logger
        e.printStackTrace();
    }

}

From source file:net.ftb.util.FileUtils.java

/**
 * deletes the META-INF/* www .  j  a  v a 2s  .c o m*/
 */
public static void killMetaInf() {
    File inputFile = new File(Settings.getSettings().getInstallPath() + "/" + ModPack.getSelectedPack().getDir()
            + "/minecraft/bin", "minecraft.jar");
    File outputTmpFile = new File(Settings.getSettings().getInstallPath() + "/"
            + ModPack.getSelectedPack().getDir() + "/minecraft/bin", "minecraft.jar.tmp");
    try {
        JarInputStream input = new JarInputStream(new FileInputStream(inputFile));
        JarOutputStream output = new JarOutputStream(new FileOutputStream(outputTmpFile));
        JarEntry entry;

        while ((entry = input.getNextJarEntry()) != null) {
            if (entry.getName().contains("META-INF")) {
                continue;
            }
            output.putNextEntry(entry);
            byte buffer[] = new byte[1024];
            int amo;
            while ((amo = input.read(buffer, 0, 1024)) != -1) {
                output.write(buffer, 0, amo);
            }
            output.closeEntry();
        }

        input.close();
        output.close();

        if (!inputFile.delete()) {
            Logger.logError("Failed to delete Minecraft.jar.");
            return;
        }
        outputTmpFile.renameTo(inputFile);
    } catch (FileNotFoundException e) {
        Logger.logError("Error while killing META-INF", e);
    } catch (IOException e) {
        Logger.logError("Error while killing META-INF", e);
    }
}

From source file:io.cloudslang.maven.compiler.CloudSlangMavenCompiler.java

private static Map<String, byte[]> getSourceFilesForDependencies(String dependency) throws IOException {
    Path path = Paths.get(dependency);
    if (!Files.exists(path) || !path.toString().toLowerCase().endsWith(".jar")) {
        return Collections.emptyMap();
    }// w ww  .j  ava 2  s. c o  m

    Map<String, byte[]> sources = new HashMap<>();

    try (JarFile jar = new JarFile(dependency)) {
        Enumeration enumEntries = jar.entries();
        while (enumEntries.hasMoreElements()) {
            JarEntry file = (JarEntry) enumEntries.nextElement();
            if ((file == null) || (file.isDirectory()) || (!file.getName().endsWith(".sl.yaml")
                    && !file.getName().endsWith(".sl") && !file.getName().endsWith(".sl.yml"))) {
                continue;
            }

            byte[] bytes;
            try (InputStream is = jar.getInputStream(file)) {
                bytes = IOUtils.toByteArray(is);
                sources.put(file.getName(), bytes);
            }
        }
    }

    return sources;
}

From source file:JarUtil.java

/**
 * Reads the package-names from the given jar-file.
 * /*from   ww  w. j a  v a2  s  .c  om*/
 * @param jarFile
 *            the jar file
 * @return an array with all found package-names
 * @throws IOException
 *             when the jar-file could not be read
 */
public static String[] getPackageNames(File jarFile) throws IOException {
    HashMap<String, String> packageNames = new HashMap<String, String>();
    JarFile input = new JarFile(jarFile, false, ZipFile.OPEN_READ);
    Enumeration<JarEntry> enumeration = input.entries();
    for (; enumeration.hasMoreElements();) {
        JarEntry entry = enumeration.nextElement();
        String name = entry.getName();
        if (name.endsWith(".class")) {
            int endPos = name.lastIndexOf('/');
            boolean isWindows = false;
            if (endPos == -1) {
                endPos = name.lastIndexOf('\\');
                isWindows = true;
            }
            name = name.substring(0, endPos);
            name = name.replace('/', '.');
            if (isWindows) {
                name = name.replace('\\', '.');
            }
            packageNames.put(name, name);
        }
    }
    return (String[]) packageNames.values().toArray(new String[packageNames.size()]);
}

From source file:com.eucalyptus.upgrade.TestHarness.java

@SuppressWarnings("unchecked")
private static Multimap<Class, Method> getTestMethods() throws Exception {
    final Multimap<Class, Method> testMethods = ArrayListMultimap.create();
    List<Class> classList = Lists.newArrayList();
    for (File f : new File(System.getProperty("euca.home") + "/usr/share/eucalyptus").listFiles()) {
        if (f.getName().startsWith("eucalyptus") && f.getName().endsWith(".jar")
                && !f.getName().matches(".*-ext-.*")) {
            try {
                JarFile jar = new JarFile(f);
                Enumeration<JarEntry> jarList = jar.entries();
                for (JarEntry j : Collections.list(jar.entries())) {
                    if (j.getName().matches(".*\\.class.{0,1}")) {
                        String classGuess = j.getName().replaceAll("/", ".").replaceAll("\\.class.{0,1}", "");
                        try {
                            Class candidate = ClassLoader.getSystemClassLoader().loadClass(classGuess);
                            for (final Method m : candidate.getDeclaredMethods()) {
                                if (Iterables.any(testAnnotations,
                                        new Predicate<Class<? extends Annotation>>() {
                                            public boolean apply(Class<? extends Annotation> arg0) {
                                                return m.getAnnotation(arg0) != null;
                                            }
                                        })) {
                                    System.out.println("Added test class: " + candidate.getCanonicalName());
                                    testMethods.put(candidate, m);
                                }/*from   w w w. j a va  2s.c o  m*/
                            }
                        } catch (ClassNotFoundException e) {
                        }
                    }
                }
                jar.close();
            } catch (Exception e) {
                System.out.println(e.getMessage());
                continue;
            }
        }
    }
    return testMethods;
}