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.nuclos.server.customcode.codegenerator.NuclosJavaCompilerComponent.java

private synchronized void jar(Map<String, byte[]> javacresult, List<CodeGenerator> generators) {
    try {/*from ww  w.j a  v a2s. c om*/
        final boolean oldExists = moveJarToOld();
        if (javacresult.size() > 0) {
            final Set<String> entries = new HashSet<String>();
            final JarOutputStream jos = new JarOutputStream(
                    new BufferedOutputStream(new FileOutputStream(JARFILE)), getManifest());

            try {
                for (final String key : javacresult.keySet()) {
                    entries.add(key);
                    byte[] bytecode = javacresult.get(key);

                    // create entry for directory (required for classpath scanning)
                    if (key.contains("/")) {
                        String dir = key.substring(0, key.lastIndexOf('/') + 1);
                        if (!entries.contains(dir)) {
                            entries.add(dir);
                            jos.putNextEntry(new JarEntry(dir));
                            jos.closeEntry();
                        }
                    }

                    // call postCompile() (weaving) on compiled sources
                    for (CodeGenerator generator : generators) {
                        if (!oldExists || generator.isRecompileNecessary()) {
                            for (JavaSourceAsString src : generator.getSourceFiles()) {
                                final String name = src.getFQName();
                                if (key.startsWith(name.replaceAll("\\.", "/"))) {
                                    LOG.debug("postCompile (weaving) " + key);
                                    bytecode = generator.postCompile(key, bytecode);
                                    // Can we break here???
                                    // break outer;
                                }
                            }
                        }
                    }
                    jos.putNextEntry(new ZipEntry(key));
                    LOG.debug("writing to " + key + " to jar " + JARFILE);
                    jos.write(bytecode);
                    jos.closeEntry();
                }

                if (oldExists) {
                    final JarInputStream in = new JarInputStream(
                            new BufferedInputStream(new FileInputStream(JARFILE_OLD)));
                    final byte[] buffer = new byte[2048];
                    try {
                        int size;
                        JarEntry entry;
                        while ((entry = in.getNextJarEntry()) != null) {
                            if (!entries.contains(entry.getName())) {
                                jos.putNextEntry(entry);
                                LOG.debug("copying " + entry.getName() + " from old jar " + JARFILE_OLD);
                                while ((size = in.read(buffer, 0, buffer.length)) != -1) {
                                    jos.write(buffer, 0, size);
                                }
                                jos.closeEntry();
                            }
                            in.closeEntry();
                        }
                    } finally {
                        in.close();
                    }
                }
            } finally {
                jos.close();
            }
        }
    } catch (IOException ex) {
        throw new NuclosFatalException(ex);
    }
}

From source file:org.drools.guvnor.server.contenthandler.ModelContentHandler.java

private Set<String> getImportsFromJar(AssetItem assetItem) throws IOException {

    Set<String> imports = new HashSet<String>();
    Map<String, String> nonCollidingImports = new HashMap<String, String>();
    String assetPackageName = assetItem.getModuleName();

    //Setup class-loader to check for class visibility
    JarInputStream cljis = new JarInputStream(assetItem.getBinaryContentAttachment());
    List<JarInputStream> jarInputStreams = new ArrayList<JarInputStream>();
    jarInputStreams.add(cljis);/*from  w  w  w. j  a  v a 2  s  .c  o  m*/
    ClassLoaderBuilder clb = new ClassLoaderBuilder(jarInputStreams);
    ClassLoader cl = clb.buildClassLoader();

    //Reset stream to read classes
    JarInputStream jis = new JarInputStream(assetItem.getBinaryContentAttachment());
    JarEntry entry = null;

    //Get Class names from JAR, only the first occurrence of a given Class leaf name will be inserted. Thus 
    //"org.apache.commons.lang.NumberUtils" will be imported but "org.apache.commons.lang.math.NumberUtils"
    //will not, assuming it follows later in the JAR structure.
    while ((entry = jis.getNextJarEntry()) != null) {
        if (!entry.isDirectory()) {
            if (entry.getName().endsWith(".class") && !entry.getName().endsWith("package-info.class")) {
                final String fullyQualifiedName = convertPathToName(entry.getName());
                final String fullyQualifiedClassName = convertPathToClassName(entry.getName());
                if (isClassVisible(cl, fullyQualifiedClassName, assetPackageName)) {
                    String leafName = getLeafName(fullyQualifiedName);
                    if (!nonCollidingImports.containsKey(leafName)) {
                        nonCollidingImports.put(leafName, fullyQualifiedName);
                    }
                }
            }
        }
    }

    //Build list of imports
    for (String value : nonCollidingImports.values()) {
        String line = "import " + value;
        imports.add(line);
    }

    return imports;
}

From source file:com.azurenight.maven.TroposphereMojo.java

private Collection<File> extractAllFiles(File outputDirectory, ZipFile ja, Enumeration<JarEntry> en)
        throws MojoExecutionException {
    List<File> files = new ArrayList<File>();
    while (en.hasMoreElements()) {
        JarEntry el = en.nextElement();
        if (!el.isDirectory()) {
            File destFile = new File(outputDirectory, el.getName());
            if (OVERRIDE || !destFile.exists()) {
                destFile.getParentFile().mkdirs();
                try {
                    FileOutputStream fo = new FileOutputStream(destFile);
                    IOUtils.copy(ja.getInputStream(el), fo);
                    fo.close();/*from   w w w. j  a v  a 2  s  .c  o  m*/
                } catch (IOException e) {
                    throw new MojoExecutionException(
                            "extracting " + el.getName() + " from jython artifact jar failed", e);
                }
            }
            files.add(destFile);
        }
    }
    return files;
}

From source file:org.deventropy.shared.utils.DirectoryArchiverUtilTest.java

private void checkJarArchive(final File archiveFile, final File sourceDirectory, final String pathPrefix)
        throws IOException {

    JarFile jarFile = null;/*  www  .j  av  a 2 s.  c o  m*/
    try {
        jarFile = new JarFile(archiveFile);

        final Manifest manifest = jarFile.getManifest();
        assertNotNull("Manifest should be present", manifest);
        assertEquals("Manifest version should be 1.0", "1.0",
                manifest.getMainAttributes().getValue(Attributes.Name.MANIFEST_VERSION));

        final ArchiveEntries archiveEntries = createArchiveEntries(sourceDirectory, pathPrefix);

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

        while (entries.hasMoreElements()) {
            final JarEntry jarEntry = entries.nextElement();
            if (MANIFEST_FILE_ENTRY_NAME.equalsIgnoreCase(jarEntry.getName())) {
                // It is the manifest file, not added by use
                continue;
            }
            if (jarEntry.isDirectory()) {
                assertTrue("Directory in jar should be from us [" + jarEntry.getName() + "]",
                        archiveEntries.dirs.contains(jarEntry.getName()));
                archiveEntries.dirs.remove(jarEntry.getName());
            } else {
                assertTrue("File in jar should be from us [" + jarEntry.getName() + "]",
                        archiveEntries.files.containsKey(jarEntry.getName()));
                final byte[] inflatedMd5 = getMd5Digest(jarFile.getInputStream(jarEntry), false);
                assertArrayEquals("MD5 hash of files should equal [" + jarEntry.getName() + "]",
                        archiveEntries.files.get(jarEntry.getName()), inflatedMd5);
                archiveEntries.files.remove(jarEntry.getName());
            }
        }

        // Check that all files and directories have been accounted for
        assertTrue("All directories should be in the jar", archiveEntries.dirs.isEmpty());
        assertTrue("All files should be in the jar", archiveEntries.files.isEmpty());
    } finally {
        if (null != jarFile) {
            jarFile.close();
        }
    }
}

From source file:com.ottogroup.bi.asap.repository.ComponentClassloader.java

/**
 * Initializes the class loader by pointing it to folder holding managed JAR files
 * @param componentFolder/*from   w  w w.  j a  va2 s.  c om*/
 * @param componentJarIdentifier file to search for in component JAR which identifies it as component JAR 
 * @throws IOException
 * @throws RequiredInputMissingException
 */
public void initialize(final String componentFolder, final String componentJarIdentifier)
        throws IOException, RequiredInputMissingException {

    ///////////////////////////////////////////////////////////////////
    // validate input
    if (StringUtils.isBlank(componentFolder))
        throw new RequiredInputMissingException("Missing required value for parameter 'componentFolder'");

    File folder = new File(componentFolder);
    if (!folder.isDirectory())
        throw new IOException("Provided input '" + componentFolder + "' does not reference a valid folder");

    File[] jarFiles = folder.listFiles();
    if (jarFiles == null || jarFiles.length < 1)
        throw new RequiredInputMissingException("No JAR files found in folder '" + componentFolder + "'");
    //
    ///////////////////////////////////////////////////////////////////

    logger.info("Initializing component classloader [componentJarIdentifier=" + componentJarIdentifier
            + ", folder=" + componentFolder + "]");

    // step through jar files, ensure it is a file and iterate through its contents
    for (File jarFile : jarFiles) {
        if (jarFile.isFile()) {

            JarInputStream jarInputStream = null;
            try {
                jarInputStream = new JarInputStream(new FileInputStream(jarFile));
                JarEntry jarEntry = null;
                while ((jarEntry = jarInputStream.getNextJarEntry()) != null) {
                    String jarEntryName = jarEntry.getName();
                    // if the current file references a class implementation, replace slashes by dots, strip 
                    // away the class suffix and add a reference to the classes-2-jar mapping 
                    if (StringUtils.endsWith(jarEntryName, ".class")) {
                        jarEntryName = jarEntryName.substring(0, jarEntryName.length() - 6).replace('/', '.');
                        this.classesJarMapping.put(jarEntryName, jarFile.getAbsolutePath());
                    } else {
                        // if the current file references a resource, check if it is the identifier file which
                        // marks this jar to contain component implementation                     
                        if (StringUtils.equalsIgnoreCase(jarEntryName, componentJarIdentifier))
                            this.componentJarFiles.add(jarFile.getAbsolutePath());
                        // ...and add a mapping for resource to jar file as well                     
                        this.resourcesJarMapping.put(jarEntryName, jarFile.getAbsolutePath());
                    }
                }
            } catch (Exception e) {
                logger.error("Failed to read from JAR file '" + jarFile.getAbsolutePath() + "'. Error: "
                        + e.getMessage());
            } finally {
                try {
                    jarInputStream.close();
                } catch (Exception e) {
                    logger.error("Failed to close open JAR file '" + jarFile.getAbsolutePath() + "'. Error: "
                            + e.getMessage());
                }
            }
        }
    }

    // load classes from jars marked component files and extract the deployment descriptors
    for (String cjf : this.componentJarFiles) {
        logger.info("Attempting to load pipeline components located in '" + cjf + "'");

        // open JAR file and iterate through it's contents
        JarInputStream jarInputStream = null;
        try {
            jarInputStream = new JarInputStream(new FileInputStream(cjf));
            JarEntry jarEntry = null;
            while ((jarEntry = jarInputStream.getNextJarEntry()) != null) {

                // fetch name of current entry and ensure it is a class file
                String jarEntryName = jarEntry.getName();
                if (jarEntryName.endsWith(".class")) {
                    // replace slashes by dots and strip away '.class' suffix
                    jarEntryName = jarEntryName.substring(0, jarEntryName.length() - 6).replace('/', '.');
                    Class<?> c = loadClass(jarEntryName);
                    AsapComponent pc = c.getAnnotation(AsapComponent.class);
                    if (pc != null) {
                        this.managedComponents.put(getManagedComponentKey(pc.name(), pc.version()),
                                new ComponentDescriptor(c.getName(), pc.type(), pc.name(), pc.version(),
                                        pc.description()));
                        logger.info("pipeline component found [type=" + pc.type() + ", name=" + pc.name()
                                + ", version=" + pc.version() + "]");
                        ;
                    }
                }
            }
        } catch (Exception e) {
            logger.error("Failed to read from JAR file '" + cjf + "'. Error: " + e.getMessage());
        } finally {
            try {
                jarInputStream.close();
            } catch (Exception e) {
                logger.error("Failed to close open JAR file '" + cjf + "'. Error: " + e.getMessage());
            }
        }
    }
}

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

/**
 * Reads the specified {@link JarEntry} from the {@link JarFile} and writes its contents
 * to the specified {@link File}./*from  ww  w  .  jav  a 2  s  .c o  m*/
 * 
 * @param earEntry The JarEntry for the file to read from the archive.
 * @param earFile The JarFile to get the {@link InputStream} for the file from.
 * @param destinationFile The File to write to, all parent directories should exist and no file should already exist at this location.
 * @throws IOException If the copying of data from the JarEntry to the File fails.
 */
protected void copyAndClose(JarEntry earEntry, JarFile earFile, File destinationFile)
        throws MojoFailureException {
    if (this.getLogger().isInfoEnabled()) {
        this.getLogger().info("Copying EAR entry '" + earFile.getName() + "!" + earEntry.getName() + "' to '"
                + destinationFile + "'");
    }

    InputStream jarEntryStream = null;
    try {
        jarEntryStream = earFile.getInputStream(earEntry);
        final OutputStream jarOutStream = new FileOutputStream(destinationFile);
        try {
            IOUtils.copy(jarEntryStream, jarOutStream);
        } finally {
            IOUtils.closeQuietly(jarOutStream);
        }
    } catch (IOException e) {
        throw new MojoFailureException("Failed to copy EAR entry '" + earEntry.getName() + "' out of '"
                + earFile.getName() + "' to '" + destinationFile + "'", e);
    } finally {
        IOUtils.closeQuietly(jarEntryStream);
    }
}

From source file:com.icesoft.jasper.compiler.TldLocationsCache.java

/**
 * Scans the given JarURLConnection for TLD files located in META-INF (or a
 * subdirectory of it), adding an implicit map entry to the taglib map for
 * any TLD that has a <uri> element.
 *
 * @param conn   The JarURLConnection to the JAR file to scan
 * @param ignore true if any exceptions raised when processing the given JAR
 *               should be ignored, false otherwise
 *///from  w w  w .j  a  v a 2  s.  com
private void scanJar(JarURLConnection conn, boolean ignore) throws JasperException {

    JarFile jarFile = null;
    String resourcePath = conn.getJarFileURL().toString();
    try {
        if (redeployMode) {
            conn.setUseCaches(false);
        }
        jarFile = conn.getJarFile();
        Enumeration entries = jarFile.entries();
        while (entries.hasMoreElements()) {
            JarEntry entry = (JarEntry) entries.nextElement();
            String name = entry.getName();
            if (!name.startsWith("META-INF/"))
                continue;
            if (!name.endsWith(".tld"))
                continue;
            InputStream stream = jarFile.getInputStream(entry);
            try {
                String uri = getUriFromTld(resourcePath, stream);
                // Add implicit map entry only if its uri is not already
                // present in the map
                if (uri != null && mappings.get(uri) == null) {
                    mappings.put(uri, new String[] { resourcePath, name });
                }
            } finally {
                if (stream != null) {
                    try {
                        stream.close();
                    } catch (IOException e) {
                        if (log.isDebugEnabled()) {
                            log.debug(e.getLocalizedMessage(), e);
                        }
                    }
                }
            }
        }
    } catch (IOException ex) {
        if (log.isDebugEnabled()) {
            log.debug(ex.getMessage(), ex);
        }
        if (!redeployMode) {
            // if not in redeploy mode, close the jar in case of an error
            if (jarFile != null) {
                try {
                    jarFile.close();
                } catch (IOException e) {
                    if (log.isDebugEnabled()) {
                        log.debug(e.getLocalizedMessage(), e);
                    }
                }
            }
        }
        if (!ignore) {
            throw new JasperException(ex);
        }
    } finally {
        if (redeployMode) {
            // if in redeploy mode, always close the jar
            if (jarFile != null) {
                try {
                    jarFile.close();
                } catch (IOException e) {
                    if (log.isDebugEnabled()) {
                        log.debug(e.getLocalizedMessage(), e);
                    }
                }
            }
        }
    }
}

From source file:com.vectorcast.plugins.vectorcastexecution.VectorCASTSetup.java

/**
 * Perform the build step. Copy the scripts from the archive/directory to the workspace
 * @param build build// ww  w. j  a va  2  s.c  om
 * @param workspace workspace
 * @param launcher launcher
 * @param listener  listener
 */
@Override
public void perform(Run<?, ?> build, FilePath workspace, Launcher launcher, TaskListener listener) {
    FilePath destScriptDir = new FilePath(workspace, "vc_scripts");
    JarFile jFile = null;
    try {
        String path = null;
        String override_path = System.getenv("VCAST_VC_SCRIPTS");
        String extra_script_path = SCRIPT_DIR;
        Boolean directDir = false;
        if (override_path != null && !override_path.isEmpty()) {
            path = override_path;
            extra_script_path = "";
            directDir = true;
            String msg = "VectorCAST - overriding vc_scripts. Copying from '" + path + "'";
            Logger.getLogger(VectorCASTSetup.class.getName()).log(Level.ALL, msg);
        } else {
            path = VectorCASTSetup.class.getProtectionDomain().getCodeSource().getLocation().getPath();
            path = URLDecoder.decode(path, "utf-8");
        }
        File testPath = new File(path);
        if (testPath.isFile()) {
            // Have jar file...
            jFile = new JarFile(testPath);
            Enumeration<JarEntry> entries = jFile.entries();
            while (entries.hasMoreElements()) {
                JarEntry entry = entries.nextElement();
                if (entry.getName().startsWith("scripts")) {
                    String fileOrDir = entry.getName().substring(8); // length of scripts/
                    FilePath dest = new FilePath(destScriptDir, fileOrDir);
                    if (entry.getName().endsWith("/")) {
                        // Directory, create destination
                        dest.mkdirs();
                    } else {
                        // File, copy it
                        InputStream is = VectorCASTSetup.class.getResourceAsStream("/" + entry.getName());
                        dest.copyFrom(is);
                    }
                }
            }
        } else {
            // Have directory
            File scriptDir = new File(path + extra_script_path);
            processDir(scriptDir, "./", destScriptDir, directDir);
        }
    } catch (IOException ex) {
        Logger.getLogger(VectorCASTSetup.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InterruptedException ex) {
        Logger.getLogger(VectorCASTSetup.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        if (jFile != null) {
            try {
                jFile.close();
            } catch (IOException ex) {
                // Ignore
            }
        }
    }
}

From source file:ffx.FFXClassLoader.java

protected void listScripts() {
    if (extensionJars != null) {
        List<String> scripts = new ArrayList<>();
        for (JarFile extensionJar : extensionJars) {
            Enumeration<JarEntry> entries = extensionJar.entries();
            while (entries.hasMoreElements()) {
                JarEntry entry = entries.nextElement();
                String name = entry.getName();
                // System.out.println(name);
                if (name.startsWith("ffx") && name.endsWith(".groovy")) {
                    name = name.replace('/', '.');
                    name = name.replace("ffx.scripts.", "");
                    name = name.replace(".groovy", "");
                    scripts.add(name);/*from  w w w  .  j a v  a2  s.c om*/
                }
            }
        }

        String[] scriptArray = scripts.toArray(new String[scripts.size()]);
        Arrays.sort(scriptArray);
        for (String script : scriptArray) {
            System.out.println(" " + script);
        }
    }
}

From source file:org.apache.struts2.jasper.compiler.TldLocationsCache.java

/**
 * Scans the given JarURLConnection for TLD files located in META-INF
 * (or a subdirectory of it), adding an implicit map entry to the taglib
 * map for any TLD that has a <uri> element.
 *
 * @param conn The JarURLConnection to the JAR file to scan
 * @param ignore true if any exceptions raised when processing the given
 * JAR should be ignored, false otherwise
 *///  ww  w. j  a va 2  s .c  o m
private void scanJar(JarURLConnection conn, boolean ignore) throws JasperException {

    JarFile jarFile = null;
    String resourcePath = conn.getJarFileURL().toString();
    try {
        if (redeployMode) {
            conn.setUseCaches(false);
        }
        jarFile = conn.getJarFile();
        Enumeration entries = jarFile.entries();
        while (entries.hasMoreElements()) {
            JarEntry entry = (JarEntry) entries.nextElement();
            String name = entry.getName();
            if (!name.startsWith("META-INF/"))
                continue;
            if (!name.endsWith(".tld"))
                continue;
            InputStream stream = jarFile.getInputStream(entry);
            try {
                String uri = getUriFromTld(resourcePath, stream);
                // Add implicit map entry only if its uri is not already
                // present in the map
                if (uri != null && mappings.get(uri) == null) {
                    mappings.put(uri, new String[] { resourcePath, name });
                }
            } finally {
                if (stream != null) {
                    try {
                        stream.close();
                    } catch (Throwable t) {
                        // do nothing
                    }
                }
            }
        }
    } catch (Exception ex) {
        if (!redeployMode) {
            // if not in redeploy mode, close the jar in case of an error
            if (jarFile != null) {
                try {
                    jarFile.close();
                } catch (Throwable t) {
                    // ignore
                }
            }
        }
        if (!ignore) {
            throw new JasperException(ex);
        }
    } finally {
        if (redeployMode) {
            // if in redeploy mode, always close the jar
            if (jarFile != null) {
                try {
                    jarFile.close();
                } catch (Throwable t) {
                    // ignore
                }
            }
        }
    }
}