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:bs.java

private static void loadable(String filename) {
    File file = new File(filename);

    JarInputStream is;/*from   w w w  .ja  v a  2s  .com*/
    try {
        ClassLoader loader = URLClassLoader.newInstance(new URL[] { file.toURI().toURL() });
        is = new JarInputStream(new FileInputStream(file));
        JarEntry entry;
        while ((entry = is.getNextJarEntry()) != null) {
            if (entry.getName().endsWith(".class") && !entry.getName().contains("/")) {
                Class<?> cls = Class.forName(FilenameUtils.removeExtension(entry.getName()), false, loader);
                for (Class<?> i : cls.getInterfaces()) {
                    if (i.equals(Loadable.class)) {
                        Loadable l = (Loadable) cls.newInstance();
                        Bs.addModule(l);
                    }
                }
            }
        }
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }

}

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

public static void copyJarContents(String prefix, String pathToJar) throws IOException {
    LOG.info("Copying jar (location: " + pathToJar + ") to prefix " + prefix);

    JarFile jar = null;/*from   w  ww .  jav  a2s .  co  m*/
    jar = new JarFile(pathToJar);
    Enumeration<JarEntry> enumr = jar.entries();
    byte[] bytes = new byte[1024];
    while (enumr.hasMoreElements()) {
        JarEntry entry = enumr.nextElement();
        if (entry.getName().startsWith(prefix)) {
            if (entry.isDirectory()) {
                File cr = new File(entry.getName());
                cr.mkdirs();
                continue;
            }
            InputStream inStream = jar.getInputStream(entry);
            File outFile = new File(entry.getName());
            if (outFile.exists()) {
                throw new RuntimeException("File unexpectedly exists");
            }
            FileOutputStream outputStream = new FileOutputStream(outFile);
            int read = 0;
            while ((read = inStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, read);
            }
            inStream.close();
            outputStream.close();
        }
    }
    jar.close();
}

From source file:info.dolezel.fatrat.plugins.helpers.NativeHelpers.java

private static Set<Class> findClasses(File directory, String packageName, Class annotation)
        throws ClassNotFoundException, IOException {
    Set<Class> classes = new HashSet<Class>();
    if (!directory.exists()) {

        String fullPath = directory.toString();
        String jarPath = fullPath.replaceFirst("[.]jar[!].*", ".jar").replaceFirst("file:", "");
        JarFile jarFile = new JarFile(jarPath);
        Enumeration<JarEntry> entries = jarFile.entries();
        while (entries.hasMoreElements()) {
            JarEntry entry = entries.nextElement();
            String entryName = entry.getName();
            if (entryName.endsWith(".class") && !entryName.contains("$")) {
                String className = entryName.replace('/', '.').replace('\\', '.').replace(".class", "");
                Class cls = loader.loadClass(className);

                if (annotation == null || cls.isAnnotationPresent(annotation))
                    classes.add(cls);//from w w w . j  av  a2s . c  o  m
            }
        }
    } else {
        File[] files = directory.listFiles();
        for (File file : files) {
            if (file.isDirectory()) {
                assert !file.getName().contains(".");
                classes.addAll(findClasses(file, packageName + "." + file.getName(), annotation));
            } else if (file.getName().endsWith(".class")) {
                Class cls = loader.loadClass(
                        packageName + '.' + file.getName().substring(0, file.getName().length() - 6));

                if (annotation == null || cls.isAnnotationPresent(annotation))
                    classes.add(cls);
            }
        }
    }
    return classes;
}

From source file:ie.deri.unlp.javaservices.topicextraction.topicextractor.gate.TopicExtractorGate.java

/**
 * /*from  w  ww.jav  a2 s.  c  o m*/
 * Extract a directory in a JAR on the classpath to an output folder.
 * 
 * Note: User's responsibility to ensure that the files are actually in a JAR.
 * 
 * @param classInJar A class in the JAR file which is on the classpath
 * @param resourceDirectory Path to resource directory in JAR
 * @param outputDirectory Directory to write to  
 * @return String containing the path to the outputDirectory
 * @throws IOException
 */
private static String extractDirectoryFromClasspathJAR(Class<?> classInJar, String resourceDirectory,
        String outputDirectory) throws IOException {

    resourceDirectory = StringUtils.strip(resourceDirectory, "\\/") + File.separator;

    URL jar = classInJar.getProtectionDomain().getCodeSource().getLocation();
    JarFile jarFile = new JarFile(new File(jar.getFile()));

    byte[] buf = new byte[1024];
    Enumeration<JarEntry> jarEntries = jarFile.entries();
    while (jarEntries.hasMoreElements()) {
        JarEntry jarEntry = jarEntries.nextElement();
        if (jarEntry.isDirectory() || !jarEntry.getName().startsWith(resourceDirectory)) {
            continue;
        }

        String outputFileName = FilenameUtils.concat(outputDirectory, jarEntry.getName());
        //Create directories if they don't exist
        new File(FilenameUtils.getFullPath(outputFileName)).mkdirs();

        //Write file
        FileOutputStream fileOutputStream = new FileOutputStream(outputFileName);
        int n;
        InputStream is = jarFile.getInputStream(jarEntry);
        while ((n = is.read(buf, 0, 1024)) > -1) {
            fileOutputStream.write(buf, 0, n);
        }
        is.close();
        fileOutputStream.close();
    }
    jarFile.close();

    String fullPath = FilenameUtils.concat(outputDirectory, resourceDirectory);
    return fullPath;
}

From source file:org.nickelproject.util.testUtil.ClasspathUtil.java

private static String getResourceName(final JarEntry pJarEntry) {
    return pJarEntry.getName().replaceAll("/", ".");
}

From source file:Zip.java

/**
 * Reads a Jar file, displaying the attributes in its manifest and dumping
 * the contents of each file contained to the console.
 *//*from  w  w w .  j  a v a2  s . c  om*/
public static void readJarFile(String fileName) {
    JarFile jarFile = null;
    try {
        // JarFile extends ZipFile and adds manifest information
        jarFile = new JarFile(fileName);
        if (jarFile.getManifest() != null) {
            System.out.println("Manifest Main Attributes:");
            Iterator iter = jarFile.getManifest().getMainAttributes().keySet().iterator();
            while (iter.hasNext()) {
                Attributes.Name attribute = (Attributes.Name) iter.next();
                System.out.println(
                        attribute + " : " + jarFile.getManifest().getMainAttributes().getValue(attribute));
            }
            System.out.println();
        }
        // use the Enumeration to dump the contents of each file to the console
        System.out.println("Jar file entries:");
        for (Enumeration e = jarFile.entries(); e.hasMoreElements();) {
            JarEntry jarEntry = (JarEntry) e.nextElement();
            if (!jarEntry.isDirectory()) {
                System.out.println(jarEntry.getName() + " contains:");
                BufferedReader jarReader = new BufferedReader(
                        new InputStreamReader(jarFile.getInputStream(jarEntry)));
                while (jarReader.ready()) {
                    System.out.println(jarReader.readLine());
                }
                jarReader.close();
            }
        }
    } catch (IOException ioe) {
        System.out.println("An IOException occurred: " + ioe.getMessage());
    } finally {
        if (jarFile != null) {
            try {
                jarFile.close();
            } catch (IOException ioe) {
            }
        }
    }
}

From source file:net.technicpack.launchercore.util.ZipUtils.java

public static void copyMinecraftJar(File minecraft, File output) throws IOException {
    String[] security = { "MOJANG_C.DSA", "MOJANG_C.SF", "CODESIGN.RSA", "CODESIGN.SF" };
    JarFile jarFile = new JarFile(minecraft);
    try {/* w ww.  j a v  a  2  s  .c  o m*/
        String fileName = jarFile.getName();
        String fileNameLastPart = fileName.substring(fileName.lastIndexOf(File.separator));

        JarOutputStream jos = new JarOutputStream(new FileOutputStream(output));
        Enumeration<JarEntry> entries = jarFile.entries();

        while (entries.hasMoreElements()) {
            JarEntry entry = entries.nextElement();
            if (containsAny(entry.getName(), security)) {
                continue;
            }
            InputStream is = jarFile.getInputStream(entry);

            //jos.putNextEntry(entry);
            //create a new entry to avoid ZipException: invalid entry compressed size
            jos.putNextEntry(new JarEntry(entry.getName()));
            byte[] buffer = new byte[4096];
            int bytesRead = 0;
            while ((bytesRead = is.read(buffer)) != -1) {
                jos.write(buffer, 0, bytesRead);
            }
            is.close();
            jos.flush();
            jos.closeEntry();
        }
        jos.close();
    } finally {
        jarFile.close();
    }

}

From source file:org.ebaysf.ostara.upgrade.util.NexusUtils.java

public static Properties extractBuildinfo(String url) {
    try {/*  ww w  .  java2  s  . c  o m*/
        String content = IOUtils.toString(new URL(url));
        int jarPos = content.indexOf(".pom\"");
        if (jarPos != -1) {
            String jarSuffix = ".jar\"";
            jarPos = 0;

            do {
                jarPos = content.indexOf(jarSuffix, jarPos);
                //TODO Any qualifier will mess up the scanning
                final String SOURCES_JAR_FLAG = "-sources";
                final String TESTS_JAR_FLAG = "-tests";

                if (jarPos != -1 && content.substring(jarPos - SOURCES_JAR_FLAG.length(), jarPos)
                        .equals(SOURCES_JAR_FLAG)) {
                    jarPos = content.indexOf(jarSuffix, jarPos + jarSuffix.length() - 1);
                    continue;
                }

                if (jarPos != -1
                        && content.substring(jarPos - TESTS_JAR_FLAG.length(), jarPos).equals(TESTS_JAR_FLAG)) {
                    jarPos = content.indexOf(jarSuffix, jarPos + jarSuffix.length() - 1);
                    continue;
                }

                final String JAVADOC_JAR_FLAG = "-javadoc";

                if (jarPos != -1 && jarPos > JAVADOC_JAR_FLAG.length() && content
                        .substring(jarPos - JAVADOC_JAR_FLAG.length(), jarPos).equals(JAVADOC_JAR_FLAG)) {
                    jarPos = content.indexOf(jarSuffix, jarPos + jarSuffix.length() - 1);
                    continue;
                }

                if (jarPos != -1) {
                    String jarUrl = getUrl(content, jarPos);

                    System.out.println("Identified JAR URL: " + jarUrl);

                    try (JarInputStream jis = new JarInputStream(new URL(jarUrl).openStream())) {
                        JarEntry je = null;

                        while ((je = jis.getNextJarEntry()) != null) {
                            if (je.getName().equals("buildinfo.properties")) {
                                Properties props = new Properties();
                                props.load(new ByteArrayInputStream(IOUtils.toByteArray(jis)));

                                return props;
                            }
                        }
                    } catch (IOException e) {
                        System.err.println("Failed to read JAR file contents");
                        e.printStackTrace();
                    }
                }

                break;
            } while (jarPos != -1);
        }
    } catch (IOException e) {
        LOG.warn(e.getMessage());
    }

    return null;
}

From source file:org.apache.tajo.util.ClassUtil.java

private static void findClasses(Set<Class> matchedClassSet, File root, File file, boolean includeJars,
        @Nullable Class type, String packageFilter, @Nullable Predicate predicate) {
    if (file.isDirectory()) {
        for (File child : file.listFiles()) {
            findClasses(matchedClassSet, root, child, includeJars, type, packageFilter, predicate);
        }//from ww w  . j a  v  a  2  s.c om
    } else {
        if (file.getName().toLowerCase().endsWith(".jar") && includeJars) {
            JarFile jar = null;
            try {
                jar = new JarFile(file);
            } catch (Exception ex) {
                LOG.error(ex.getMessage(), ex);
                return;
            }
            Enumeration<JarEntry> entries = jar.entries();
            while (entries.hasMoreElements()) {
                JarEntry entry = entries.nextElement();
                String name = entry.getName();
                int extIndex = name.lastIndexOf(".class");
                if (extIndex > 0) {
                    String qualifiedClassName = name.substring(0, extIndex).replace("/", ".");
                    if (qualifiedClassName.indexOf(packageFilter) >= 0 && !isTestClass(qualifiedClassName)) {
                        try {
                            Class clazz = Class.forName(qualifiedClassName);

                            if (isMatched(clazz, type, predicate)) {
                                matchedClassSet.add(clazz);
                            }
                        } catch (ClassNotFoundException e) {
                            LOG.error(e.getMessage(), e);
                        }
                    }
                }
            }

            try {
                jar.close();
            } catch (IOException e) {
                LOG.warn("Closing " + file.getName() + " was failed.");
            }
        } else if (file.getName().toLowerCase().endsWith(".class")) {
            String qualifiedClassName = createClassName(root, file);
            if (qualifiedClassName.indexOf(packageFilter) >= 0 && !isTestClass(qualifiedClassName)) {
                try {
                    Class clazz = Class.forName(qualifiedClassName);
                    if (isMatched(clazz, type, predicate)) {
                        matchedClassSet.add(clazz);
                    }
                } catch (ClassNotFoundException e) {
                    LOG.error(e.getMessage(), e);
                }
            }
        }
    }
}

From source file:org.talend.components.marketo.MarketoRuntimeInfoTest.java

static List<URL> extractDependencyFromStream(DependenciesReader dependenciesReader, String depTxtPath,
        JarInputStream jarInputStream) throws IOException {
    JarEntry nextJarEntry = jarInputStream.getNextJarEntry();
    while (nextJarEntry != null) {
        if (depTxtPath.equals(nextJarEntry.getName())) {// we got it so parse it.
            Set<String> dependencies = dependenciesReader.parseDependencies(jarInputStream);
            // convert the string to URL
            List<URL> result = new ArrayList<>(dependencies.size());
            for (String urlString : dependencies) {
                result.add(new URL(urlString));
                System.out.println("new URL(\"" + urlString + "\"),//");
            }//from   w  ww  .j  a  va 2  s .c om
            return result;
        }
        nextJarEntry = jarInputStream.getNextJarEntry();
    }
    throw new ComponentException(ComponentsApiErrorCode.COMPUTE_DEPENDENCIES_FAILED,
            ExceptionContext.withBuilder().put("path", depTxtPath).build());
}