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:org.apache.pluto.util.assemble.ear.ComplexEarAssemblerTest.java

protected void validateEarAssembly(File earFile) throws Exception {
    assertTrue("EAR archive [" + earFile.getAbsolutePath() + "] cannot be found or cannot be read",
            earFile.exists() && earFile.canRead());

    PortletAppDescriptorService portletSvc = new PortletAppDescriptorServiceImpl();
    PortletApplicationDefinition portletApp = null;

    PlutoWebXmlRewriter webXmlRewriter = null;

    List<String> portletWarEntries = Arrays.asList(testWarEntryNames);
    List<String> unassembledWarEntries = Arrays.asList(unassembledWarEntryName);
    List<String> testPortlets = Arrays.asList(testPortletNames);

    int earEntryCount = 0;
    int totalWarEntryCount = 0;
    int portletWarEntryCount = 0;

    JarInputStream earIn = new JarInputStream(new FileInputStream(earFile));

    JarEntry earEntry;
    JarEntry warEntry;/*from ww  w .  j  ava2s.c o m*/

    while ((earEntry = earIn.getNextJarEntry()) != null) {
        earEntryCount++;

        if (earEntry.getName().endsWith(".war")) {
            totalWarEntryCount++;
            JarInputStream warIn = new JarInputStream(earIn);

            while ((warEntry = warIn.getNextJarEntry()) != null) {
                if (Assembler.PORTLET_XML.equals(warEntry.getName())) {
                    portletApp = portletSvc.read("test", "/test",
                            new ByteArrayInputStream(IOUtils.toByteArray(warIn)));
                }
                if (Assembler.SERVLET_XML.equals(warEntry.getName())) {
                    webXmlRewriter = new PlutoWebXmlRewriter(
                            new ByteArrayInputStream(IOUtils.toByteArray(warIn)));
                }
            }

            if (portletWarEntries.contains(earEntry.getName())) {
                portletWarEntryCount++;
                assertNotNull("WAR archive did not contain a portlet.xml", portletApp);
                assertNotNull("WAR archive did not contain a servlet.xml", webXmlRewriter);
                assertTrue("WAR archive did not contain any servlets", webXmlRewriter.hasServlets());
                assertTrue("WAR archive did not contain any servlet mappings",
                        webXmlRewriter.hasServletMappings());
                assertTrue("WAR archive did not contain any portlets", portletApp.getPortlets().size() > 0);

                for (Iterator<? extends PortletDefinition> iter = portletApp.getPortlets().iterator(); iter
                        .hasNext();) {
                    PortletDefinition portlet = iter.next();
                    if (!testPortlets.contains(portlet.getPortletName())) {
                        fail("Unexpected test portlet name encountered: [" + portlet.getPortletName() + "]");
                    }
                    String servletClassName = webXmlRewriter.getServletClass(portlet.getPortletName());
                    assertNotNull("web.xml does not contain assembly for test portlet", servletClassName);
                    assertEquals("web.xml does not contain correct dispatch servet",
                            Assembler.DISPATCH_SERVLET_CLASS, servletClassName);
                }

            }

            webXmlRewriter = null;
            portletApp = null;

        }

    }

    assertTrue("EAR archive did not contain any entries", earEntryCount > 0);
    assertEquals("EAR archive did not contain the expected test war entries.", portletWarEntries.size(),
            portletWarEntryCount);
    assertEquals("WAR archive did not contain the correct number of entries",
            portletWarEntries.size() + unassembledWarEntries.size(), totalWarEntryCount);

}

From source file:com.flexive.testRunner.FxTestRunnerThread.java

/**
 * {@inheritDoc}/*from   ww w .ja  v  a2s . c o  m*/
 */
@Override
public void run() {
    synchronized (lock) {
        if (testInProgress)
            return;
        testInProgress = true;
    }
    try {
        ClassLoader cl = Thread.currentThread().getContextClassLoader();
        URL jar = cl.getResource("lib/flexive-tests.jar");

        //build a list of all test classes
        List<Class> testClasses = new ArrayList<Class>(100);
        try {
            JarInputStream jin = new JarInputStream(jar.openStream());
            while (jin.available() != 0) {
                JarEntry je = jin.getNextJarEntry();
                if (je == null)
                    continue;

                final String name = je.getName();
                //only classes, no inner classes, abstract or mock classes
                if (name.endsWith(".class") && !(name.indexOf('$') > 0) && !(name.indexOf("Abstract") > 0)
                        && !(name.indexOf("Mock") > 0)) {
                    boolean ignore = false;
                    //check ignore package
                    for (String pkg : FxTestRunner.ignorePackages)
                        if (name.indexOf(pkg) > 0) {
                            ignore = true;
                            break;
                        }
                    if (ignore)
                        continue;
                    final String className = name.substring(name.lastIndexOf('/') + 1);
                    //check ignore classes
                    for (String cls : FxTestRunner.ignoreTests)
                        if (className.indexOf(cls) > 0) {
                            ignore = true;
                            break;
                        }
                    if (ignore)
                        continue;
                    final String fqn = name.replaceAll("\\/", ".").substring(0, name.lastIndexOf('.'));
                    try {
                        testClasses.add(Class.forName(fqn));
                    } catch (ClassNotFoundException e) {
                        LOG.error("Could not find test class: " + fqn);
                    }
                }
            }
        } catch (IOException e) {
            LOG.error(e);
        }
        TestNG testng = new TestNG();
        testng.setTestClasses(testClasses.toArray(new Class[testClasses.size()]));
        // skip.ear groups have to be excluded, else tests that include these will be skipped as well (like ContainerBootstrap which is needed)
        testng.setExcludedGroups("skip.ear");
        System.setProperty("flexive.tests.ear", "1");
        TestListenerAdapter tla = new TestListenerAdapter();
        testng.addListener(tla);

        if (callback != null) {
            FxTestRunnerListener trl = new FxTestRunnerListener(callback);
            testng.addListener(trl);
        }

        testng.setThreadCount(4);
        testng.setVerbose(0);
        testng.setDefaultSuiteName("EARTestSuite");
        testng.setOutputDirectory(outputPath);
        if (callback != null)
            callback.resetTestInfo();
        try {
            testng.run();
        } catch (Exception e) {
            LOG.error(e);
            new FxFacesMsgErr("TestRunner.err.testNG", e.getMessage()).addToContext();
        }
        if (callback != null) {
            callback.setRunning(false);
            callback.setResultsAvailable(true);
        }
    } finally {
        synchronized (lock) {
            testInProgress = false;
        }
    }
}

From source file:com.netflix.nicobar.core.archive.JarScriptArchive.java

protected JarScriptArchive(ScriptModuleSpec moduleSpec, Path jarPath, String moduleSpecEntry, long createTime)
        throws IOException {
    this.createTime = createTime;
    this.moduleSpec = Objects.requireNonNull(moduleSpec, "moduleSpec");
    Objects.requireNonNull(jarPath, "jarFile");
    if (!jarPath.isAbsolute())
        throw new IllegalArgumentException("jarPath must be absolute.");

    // initialize the index
    JarFile jarFile = new JarFile(jarPath.toFile());
    Set<String> indexBuilder;
    try {//from  w w  w.  j a  va2  s.  c  om
        Enumeration<JarEntry> jarEntries = jarFile.entries();
        indexBuilder = new HashSet<String>();
        while (jarEntries.hasMoreElements()) {
            JarEntry jarEntry = jarEntries.nextElement();
            // Skip adding moduleSpec to archive entries
            if (jarEntry.getName().equals(moduleSpecEntry)) {
                continue;
            }

            if (!jarEntry.isDirectory()) {
                indexBuilder.add(jarEntry.getName());
            }
        }
    } finally {
        jarFile.close();
    }

    entryNames = Collections.unmodifiableSet(indexBuilder);

    rootUrl = jarPath.toUri().toURL();
}

From source file:appeng.recipes.loader.RecipeResourceCopier.java

/**
 * List directory contents for a resource folder. Not recursive. This is basically a brute-force implementation. Works for regular files and also JARs.
 *
 * @param clazz Any java class that lives in the same place as the resources you want.
 * @param path Should end with "/", but not start with one.
 *
 * @return Just the name of each member item, not the full paths.
 *
 * @throws URISyntaxException            if it is a file path and the URL can not be converted to URI
 * @throws IOException                   if jar path can not be decoded
 * @throws UnsupportedOperationException if it is neither in jar nor in file path
 *//*from ww  w . jav  a 2 s .c om*/
@Nonnull
private String[] getResourceListing(@Nonnull final Class<?> clazz, @Nonnull final String path)
        throws URISyntaxException, IOException {
    assert clazz != null;
    assert path != null;

    final ClassLoader classLoader = clazz.getClassLoader();
    if (classLoader == null) {
        throw new IllegalStateException(
                "ClassLoader was not found. It was probably loaded at a inappropriate time");
    }

    URL dirURL = classLoader.getResource(path);
    if (dirURL != null) {
        final String protocol = dirURL.getProtocol();
        if (protocol.equals(FILE_PROTOCOL)) {
            // A file path: easy enough

            final URI uriOfURL = dirURL.toURI();
            final File fileOfURI = new File(uriOfURL);
            final String[] filesAndDirectoriesOfURI = fileOfURI.list();

            if (filesAndDirectoriesOfURI == null) {
                throw new IllegalStateException(
                        "Files and Directories were illegal. Either an abstract pathname does not denote a directory, or an I/O error occured.");
            } else {
                return filesAndDirectoriesOfURI;
            }
        }
    }

    if (dirURL == null) {
        /*
         * In case of a jar file, we can't actually find a directory.
         * Have to assume the same jar as clazz.
         */
        final String className = clazz.getName();
        final Matcher matcher = DOT_COMPILE_PATTERN.matcher(className);
        final String me = matcher.replaceAll("/") + CLASS_EXTENSION;
        dirURL = classLoader.getResource(me);
    }

    if (dirURL != null) {
        final String protocol = dirURL.getProtocol();
        if (protocol.equals(JAR_PROTOCOL)) {
            /* A JAR path */
            final String dirPath = dirURL.getPath();
            final String jarPath = dirPath.substring(5, dirPath.indexOf('!')); // strip out only
            // the JAR file
            final JarFile jar = new JarFile(URLDecoder.decode(jarPath, UTF_8_ENCODING));
            try {
                final Enumeration<JarEntry> entries = jar.entries(); // gives ALL entries in jar
                final Collection<String> result = new HashSet<String>(INITIAL_RESOURCE_CAPACITY); // avoid duplicates

                // in case it is a
                // subdirectory
                while (entries.hasMoreElements()) {
                    final JarEntry entry = entries.nextElement();
                    final String entryFullName = entry.getName();
                    if (entryFullName.startsWith(path)) { // filter according to the path
                        String entryName = entryFullName.substring(path.length());
                        final int checkSubDir = entryName.indexOf('/');
                        if (checkSubDir >= 0) {
                            // if it is a subdirectory, we just return the directory name
                            entryName = entryName.substring(0, checkSubDir);
                        }
                        result.add(entryName);
                    }
                }

                return result.toArray(new String[result.size()]);
            } finally {
                jar.close();
            }
        }
    }

    throw new UnsupportedOperationException("Cannot list files for URL " + dirURL);
}

From source file:javadepchecker.Main.java

/**
 * Scan jar for classes to be processed by ASM
 *
 * @param jar jar file to be processed/*from www  .  j a  v  a 2 s .  com*/
 * @throws IOException
 */
public void processJar(JarFile jar) throws IOException {
    Collections.list(jar.entries()).stream()
            .filter((JarEntry entry) -> (!entry.isDirectory() && entry.getName().endsWith("class")))
            .forEach((JarEntry entry) -> {
                InputStream is = null;
                try {
                    Main.this.mCurrent.add(entry.getName());
                    is = jar.getInputStream(entry);
                    new ClassReader(is).accept(Main.this, 0);
                } catch (IOException ex) {
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                } finally {
                    try {
                        if (is != null)
                            is.close();
                    } catch (IOException ex) {
                        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            });
}

From source file:goja.initialize.ctxbox.ClassSearcher.java

/**
 * jarclass/*from www  .  jav a2  s . c o m*/
 */
private List<String> findjarFiles(String baseDirName) {
    List<String> classFiles = Lists.newArrayList();
    File baseDir = new File(baseDirName);
    if (!baseDir.exists() || !baseDir.isDirectory()) {
        LOG.error("file search error:" + baseDirName + " is not a dir?");
    } else {
        File[] files = baseDir.listFiles();
        if (files == null) {
            return Collections.EMPTY_LIST;
        }
        for (File file : files) {
            if (file.isDirectory()) {
                classFiles.addAll(findjarFiles(file.getAbsolutePath()));
            } else {
                if (includeAllJarsInLib || includeJars.contains(file.getName())) {
                    JarFile localJarFile = null;
                    try {
                        localJarFile = new JarFile(new File(baseDirName + File.separator + file.getName()));
                        Enumeration<JarEntry> entries = localJarFile.entries();
                        while (entries.hasMoreElements()) {
                            JarEntry jarEntry = entries.nextElement();
                            String entryName = jarEntry.getName();
                            if (scanPackages.isEmpty()) {
                                if (!jarEntry.isDirectory() && entryName.endsWith(".class")) {
                                    String className = StringUtils.replace(entryName, StringPool.SLASH, ".")
                                            .substring(0, entryName.length() - 6);
                                    classFiles.add(className);
                                }
                            } else {
                                for (String scanPackage : scanPackages) {
                                    scanPackage = scanPackage.replaceAll("\\.", "\\" + File.separator);
                                    if (!jarEntry.isDirectory() && entryName.endsWith(".class")
                                            && entryName.startsWith(scanPackage)) {
                                        String className = StringUtils.replace(entryName, File.separator, ".")
                                                .substring(0, entryName.length() - 6);
                                        classFiles.add(className);
                                    }
                                }
                            }
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally {
                        try {
                            if (localJarFile != null) {
                                localJarFile.close();
                            }
                        } catch (IOException e) {
                            LOG.error("close jar file has error!", e);
                        }
                    }
                }
            }

        }
    }
    return classFiles;
}

From source file:com.eucalyptus.simpleworkflow.common.client.WorkflowClientStandalone.java

private void processJar(File f) throws Exception {
    final JarFile jar = new JarFile(f);
    final Properties props = new Properties();
    final List<JarEntry> jarList = Collections.list(jar.entries());
    LOG.trace("-> Trying to load component info from " + f.getAbsolutePath());
    for (final JarEntry j : jarList) {
        try {//from  w  w w .j  a  v a2  s  .c  om
            if (j.getName().matches(".*\\.class.{0,1}")) {
                handleClassFile(f, j);
            }
        } catch (RuntimeException ex) {
            LOG.error(ex, ex);
            jar.close();
            throw ex;
        }
    }
    jar.close();
}

From source file:org.bimserver.plugins.JarClassLoader.java

private void loadSubJars(byte[] byteArray) {
    try {//from ww w . ja  va2s  .co m
        JarInputStream jarInputStream = new JarInputStream(new ByteArrayInputStream(byteArray));
        JarEntry entry = jarInputStream.getNextJarEntry();
        while (entry != null) {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            IOUtils.copy(jarInputStream, byteArrayOutputStream);
            map.put(entry.getName(), byteArrayOutputStream.toByteArray());
            entry = jarInputStream.getNextJarEntry();
        }
        jarInputStream.close();
    } catch (IOException e) {
        LOGGER.error("", e);
    }
}

From source file:com.android.builder.testing.MockableJarGenerator.java

public void createMockableJar(File input, File output) throws IOException {
    Preconditions.checkState(output.createNewFile(), "Output file [%s] already exists.",
            output.getAbsolutePath());// w  w w.  jav  a2 s.  c  om

    JarFile androidJar = null;
    JarOutputStream outputStream = null;
    try {
        androidJar = new JarFile(input);
        outputStream = new JarOutputStream(new FileOutputStream(output));

        for (JarEntry entry : Collections.list(androidJar.entries())) {
            InputStream inputStream = androidJar.getInputStream(entry);

            if (entry.getName().endsWith(".class")) {
                if (!skipClass(entry.getName().replace("/", "."))) {
                    rewriteClass(entry, inputStream, outputStream);
                }
            } else {
                outputStream.putNextEntry(entry);
                ByteStreams.copy(inputStream, outputStream);
            }

            inputStream.close();
        }
    } finally {
        if (androidJar != null) {
            androidJar.close();
        }
        if (outputStream != null) {
            outputStream.close();
        }
    }
}

From source file:com.ebay.cloud.cms.metadata.dataloader.MetadataDataLoader.java

private void loadMetaClassesFromPath(String pathName) {
    try {/*from   w  w w .  ja v  a2  s  .c  o  m*/

        URL url = MetadataDataLoader.class.getResource(pathName);
        URI uri = url.toURI();
        BasicDBList metas = new BasicDBList();

        if (uri.isOpaque()) {
            JarURLConnection connection = (JarURLConnection) url.openConnection();
            JarFile jar = connection.getJarFile();
            Enumeration<JarEntry> entries = jar.entries();

            while (entries.hasMoreElements()) {
                JarEntry entry = entries.nextElement();
                if (entry.getName().startsWith(pathName.substring(1)) && entry.getName().endsWith(".json")) {
                    InputStream is = jar.getInputStream(entry);
                    readMetaClass(is, metas);
                }
            }

        } else {
            File dir = new File(url.toURI());
            Collection<File> files = FileUtils.listFiles(dir, new String[] { "json" }, true);
            for (File f : files) {
                InputStream is = new FileInputStream(f);
                readMetaClass(is, metas);
            }
        }

        loadMetaClasses(metas);

    } catch (Exception e) {
        logger.error("error in loading metadata: ", e);
    }
}