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.primeframework.mvc.util.ClassClasspathResolver.java

private Collection<Class<U>> loadFromJar(File f, Test<Class<U>> test, boolean recursive,
        Iterable<String> locators, boolean embeddable) throws IOException {
    Set<Class<U>> matches = new HashSet<Class<U>>();

    JarFile jarFile;/*w  w  w  .  j a v  a2  s. c o m*/
    try {
        jarFile = new JarFile(f);
    } catch (IOException e) {
        throw new IOException("Error opening JAR file [" + f.getAbsolutePath() + "]", e);
    }

    Enumeration<JarEntry> en = jarFile.entries();
    while (en.hasMoreElements()) {
        JarEntry entry = en.nextElement();
        String name = entry.getName();

        // Verify against the locators
        for (String locator : locators) {
            int index = name.indexOf(locator + "/");
            boolean match = (!embeddable && index == 0) || (embeddable && index >= 0);
            if (!match) {
                continue;
            }

            match = recursive || name.indexOf('/', index + locator.length() + 1) == -1;
            if (!match) {
                continue;
            }

            Testable<Class<U>> testable = test.prepare(f, jarFile, entry);
            if (testable != null && testable.passes()) {
                matches.add(testable.result());
                break;
            }
        }
    }

    jarFile.close();

    return matches;
}

From source file:JarEntryOutputStream.java

/**
 * Writes the entry to a the jar file.  This is done by creating a
 * temporary jar file, copying the contents of the existing jar to the
 * temp jar, skipping the entry named by this.jarEntryName if it exists.
 * Then, if the stream was written to, then contents are written as a
 * new entry.  Last, a callback is made to the EnhancedJarFile to
 * swap the temp jar in for the old jar.
 *///from  w  w w .  j a v a 2  s .c om
private void writeToJar() throws IOException {

    File jarDir = new File(this.jar.getName()).getParentFile();
    // create new jar
    File newJarFile = File.createTempFile("config", ".jar", jarDir);
    newJarFile.deleteOnExit();
    JarOutputStream jarOutputStream = new JarOutputStream(new FileOutputStream(newJarFile));

    try {
        Enumeration entries = this.jar.entries();

        // copy all current entries into the new jar
        while (entries.hasMoreElements()) {
            JarEntry nextEntry = (JarEntry) entries.nextElement();
            // skip the entry named jarEntryName
            if (!this.jarEntryName.equals(nextEntry.getName())) {
                // the next 3 lines of code are a work around for
                // bug 4682202 in the java.sun.com bug parade, see:
                // http://developer.java.sun.com/developer/bugParade/bugs/4682202.html
                JarEntry entryCopy = new JarEntry(nextEntry);
                entryCopy.setCompressedSize(-1);
                jarOutputStream.putNextEntry(entryCopy);

                InputStream intputStream = this.jar.getInputStream(nextEntry);
                // write the data
                for (int data = intputStream.read(); data != -1; data = intputStream.read()) {

                    jarOutputStream.write(data);
                }
            }
        }

        // write the new or modified entry to the jar
        if (size() > 0) {
            jarOutputStream.putNextEntry(new JarEntry(this.jarEntryName));
            jarOutputStream.write(super.buf, 0, size());
            jarOutputStream.closeEntry();
        }
    } finally {
        // close close everything up
        try {
            if (jarOutputStream != null) {
                jarOutputStream.close();
            }
        } catch (IOException ioe) {
            // eat it, just wanted to close stream
        }
    }

    // swap the jar
    this.jar.swapJars(newJarFile);
}

From source file:org.amanzi.awe.scripting.utils.ScriptUtils.java

/**
 * @param pluginName// w ww .j  a  v  a 2  s  . co  m
 * @param loadPath
 * @throws ScriptingException
 */
private void makePluginLoadName(final String pluginName, final List<String> loadPath)
        throws ScriptingException {
    if (StringUtils.isEmpty(pluginName)) {
        LOGGER.warn("Plugin name is empty");
        return;
    }
    String pluginPath = getPluginRoot(pluginName);
    if (StringUtils.isEmpty(pluginPath)) {
        LOGGER.warn("Plugin not found");
        return;
    }
    // loadPath.add(pluginPath);
    JarFile jarFile = null;
    if (pluginPath.startsWith(PREFIX_FILE) && pluginPath.endsWith(POSTFIX_JAR)) {
        String path = prepareJarPath(pluginPath);
        try {
            jarFile = new JarFile(path);
        } catch (IOException e) {
            LOGGER.error("can't find jar file", e);
        }
    }
    if (jarFile == null) {
        File rootFolder = new File(pluginPath + JRUBY_PLUGI_LIB);
        if (rootFolder.exists()) {
            for (File file : rootFolder.listFiles()) {
                if (file.isDirectory()) {
                    loadPath.add(file.getAbsolutePath());
                }
            }
        }

    } else {
        JarEntry entry;
        for (Enumeration<JarEntry> entries = jarFile.entries(); entries.hasMoreElements();) {
            entry = entries.nextElement();
            LOGGER.info(entry.getName());
            if (entry.isDirectory() && entry.getName().contains(JRUBY_PLUGI_LIB)) {
                loadPath.add(entry.getName().substring(0, entry.getName().length() - 1));
                LOGGER.info("initialized with jar entry " + entry.getName());
            }
        }
    }

    loadPath.add(JRUBY_PLUGI_LIB);
}

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

/**
 * Initializes the class loader by pointing it to folder holding managed JAR files
 * @param componentFolder//from  w  ww.j a  v  a2 s.  c  om
 * @throws IOException
 * @throws RequiredInputMissingException
 */
public void initialize(final String componentFolder) 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 [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.byteCode.put(jarEntryName, loadBytes(jarInputStream));
                    } else {
                        // ...and add a mapping for resource to jar file as well
                        this.resources.put(jarEntryName, loadBytes(jarInputStream));
                    }
                }
            } 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());
                }
            }
        }
    }

    logger.info("Analyzing " + this.byteCode.size() + " classes for component annotation");

    // load classes from jars marked component files and extract the deployment descriptors
    for (String cjf : this.byteCode.keySet()) {

        try {
            Class<?> c = loadClass(cjf);
            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 (Throwable e) {
            //logger.info("Failed to load class '"+cjf+"'. Error: " + e.getMessage());
        }
    }
}

From source file:net.sf.mavenjython.JythonMojo.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();
        // getLog().info(" > " + el);
        if (!el.isDirectory()) {
            File destFile = new File(outputDirectory, el.getName());
            // destFile = new File(outputDirectory, destFile.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  a2 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.apache.pluto.util.assemble.ear.EarAssembler.java

public void assembleInternal(AssemblerConfig config) throws UtilityException, IOException {

    File source = config.getSource();
    File dest = config.getDestination();

    JarInputStream earIn = new JarInputStream(new FileInputStream(source));
    JarOutputStream earOut = new JarOutputStream(new BufferedOutputStream(new FileOutputStream(dest), BUFLEN));

    try {//w  ww  . j  a  v a  2 s  .c  om

        JarEntry entry;

        // Iterate over entries in the EAR archive
        while ((entry = earIn.getNextJarEntry()) != null) {

            // If a war file is encountered, assemble it into a
            // ByteArrayOutputStream and write the assembled bytes
            // back to the EAR archive.
            if (entry.getName().toLowerCase().endsWith(".war")) {

                if (LOG.isDebugEnabled()) {
                    LOG.debug("Assembling war file " + entry.getName());
                }

                // keep a handle to the AssemblySink so we can write out
                // JarEntry metadata and the bytes later.
                AssemblySink warBytesOut = getAssemblySink(config, entry);
                JarOutputStream warOut = new JarOutputStream(warBytesOut);

                JarStreamingAssembly.assembleStream(new JarInputStream(earIn), warOut,
                        config.getDispatchServletClass());

                JarEntry warEntry = new JarEntry(entry);

                // Write out the assembled JarEntry metadata
                warEntry.setSize(warBytesOut.getByteCount());
                warEntry.setCrc(warBytesOut.getCrc());
                warEntry.setCompressedSize(-1);
                earOut.putNextEntry(warEntry);

                // Write out the assembled WAR file to the EAR
                warBytesOut.writeTo(earOut);

                earOut.flush();
                earOut.closeEntry();
                earIn.closeEntry();

            } else {

                earOut.putNextEntry(entry);
                IOUtils.copy(earIn, earOut);

                earOut.flush();
                earOut.closeEntry();
                earIn.closeEntry();

            }
        }

    } finally {

        earOut.close();
        earIn.close();

    }
}

From source file:org.openspaces.maven.plugin.CreatePUProjectMojo.java

/**
 * Returns a set containing all templates defined in this JAR file.
 *///from  w w w.ja v  a 2s . co m
public HashMap getJarTemplates(URL url) throws Exception {
    PluginLog.getLog().debug("retrieving all templates from jar file: " + url);
    String lookFor = DIR_TEMPLATES + "/";
    int length = lookFor.length();
    HashMap templates = new HashMap();
    BufferedInputStream bis = new BufferedInputStream(url.openStream());
    JarInputStream jis = new JarInputStream(bis);
    JarEntry je;
    Set temp = new HashSet();
    while ((je = jis.getNextJarEntry()) != null) {
        // find the template name
        String jarEntryName = je.getName();
        PluginLog.getLog().debug("Found entry: " + jarEntryName);
        if (jarEntryName.length() <= length || !jarEntryName.startsWith(lookFor)) {
            continue;
        }
        int nextSlashIndex = jarEntryName.indexOf("/", length);
        if (nextSlashIndex == -1) {
            continue;
        }
        String jarTemplate = jarEntryName.substring(length, nextSlashIndex);
        PluginLog.getLog().debug("Found template: " + jarTemplate);
        if (templates.containsKey(jarTemplate)) {
            continue;
        }
        if (jarEntryName.endsWith("readme.txt")) {
            // a description found - add to templates
            String description = getShortDescription(jis);
            templates.put(jarTemplate, description);
            // remove from temp
            temp.remove(jarTemplate);
        } else {
            // add to temp until a description is found
            temp.add(jarTemplate);
        }
    }
    // add all templates that has no description
    Iterator iter = temp.iterator();
    while (iter.hasNext()) {
        templates.put(iter.next(), "No description found.");
    }
    return templates;
}

From source file:mobac.mapsources.loader.MapPackManager.java

/**
 * Verifies the class file signatures of the specified map pack
 * /*from  w w  w  .  j  a  v  a2 s. com*/
 * @param mapPackFile
 * @throws IOException
 * @throws CertificateException
 */
public void testMapPack(File mapPackFile) throws IOException, CertificateException {
    String fileName = mapPackFile.getName();
    JarFile jf = new JarFile(mapPackFile, true);
    try {
        Enumeration<JarEntry> it = jf.entries();
        while (it.hasMoreElements()) {
            JarEntry entry = it.nextElement();
            // We verify only class files
            if (!entry.getName().endsWith(".class"))
                continue; // directory or other entry
            // Get the input stream (triggers) the signature verification for the specific class
            Utilities.readFully(jf.getInputStream(entry));
            if (entry.getCodeSigners() == null)
                throw new CertificateException("Unsigned class file found: " + entry.getName());
            CodeSigner signer = entry.getCodeSigners()[0];
            List<? extends Certificate> cp = signer.getSignerCertPath().getCertificates();
            if (cp.size() > 1)
                throw new CertificateException("Signature certificate not accepted: "
                        + "certificate path contains more than one certificate");
            // Compare the used certificate with the mapPack certificate
            if (!mapPackCert.equals(cp.get(0)))
                throw new CertificateException(
                        "Signature certificate not accepted: " + "not the MapPack signer certificate");
        }
        Manifest mf = jf.getManifest();
        Attributes a = mf.getMainAttributes();
        String mpv = a.getValue("MapPackVersion");
        if (mpv == null)
            throw new IOException("MapPackVersion info missing!");
        int mapPackVersion = Integer.parseInt(mpv);
        if (requiredMapPackVersion != mapPackVersion)
            throw new IOException("This pack \"" + fileName + "\" is not compatible with this MOBAC version.");
        ZipEntry entry = jf.getEntry("META-INF/services/mobac.program.interfaces.MapSource");
        if (entry == null)
            throw new IOException("MapSources services list is missing in file " + fileName);
    } finally {
        jf.close();
    }

}

From source file:org.apache.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 av a 2  s  .  c  om
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
                }
            }
        }
    }
}

From source file:org.eclipse.winery.generators.ia.Generator.java

/**
 * Generates the IA project.//from   w w  w  .j  av  a2 s  .c  o m
 * 
 * @return The ZIP file containing the maven/eclipse project to be
 *         downloaded by the user.
 */
public File generateProject() {

    try {
        Path workingDirPath = this.workingDir.toPath();
        Files.createDirectories(workingDirPath);

        // directory to store the template files to generate the java files from
        Path javaTemplateDir = workingDirPath.resolve("../java");
        Files.createDirectories(javaTemplateDir);

        // Copy template project and template java files
        String s = this.getClass().getResource("").getPath();
        if (s.contains("jar!")) {
            Generator.logger.trace("we work on a jar file");
            Generator.logger.trace("Location of the current class: {}", s);

            // we have a jar file
            // format: file:/location...jar!...path-in-the-jar
            // we only want to have location :)
            int excl = s.lastIndexOf("!");
            s = s.substring(0, excl);
            s = s.substring("file:".length());

            try (JarFile jf = new JarFile(s);) {
                Enumeration<JarEntry> entries = jf.entries();
                while (entries.hasMoreElements()) {
                    JarEntry je = entries.nextElement();
                    String name = je.getName();
                    if (name.startsWith(Generator.TEMPLATE_PROJECT_FOLDER + "/")
                            && (name.length() > (Generator.TEMPLATE_PROJECT_FOLDER.length() + 1))) {
                        // strip "template/" from the beginning to have paths without "template" starting relatively from the working dir
                        name = name.substring(Generator.TEMPLATE_PROJECT_FOLDER.length() + 1);
                        if (je.isDirectory()) {
                            // directory found
                            Path dir = workingDirPath.resolve(name);
                            Files.createDirectory(dir);
                        } else {
                            Path file = workingDirPath.resolve(name);
                            try (InputStream is = jf.getInputStream(je);) {
                                Files.copy(is, file, StandardCopyOption.REPLACE_EXISTING);
                            }
                        }
                    } else if (name.startsWith(Generator.TEMPLATE_JAVA_FOLDER + "/")
                            && (name.length() > (Generator.TEMPLATE_JAVA_FOLDER.length() + 1))) {
                        if (!je.isDirectory()) {
                            // we copy the file directly into javaTemplateDir
                            File f = new File(name);
                            Path file = javaTemplateDir.resolve(f.getName());
                            try (InputStream is = jf.getInputStream(je);) {
                                Files.copy(is, file, StandardCopyOption.REPLACE_EXISTING);
                            }
                        }
                    }
                }
            }
        } else {
            // we're running in debug mode, we can work on the plain file system
            File templateProjectDir = new File(
                    this.getClass().getResource("/" + Generator.TEMPLATE_PROJECT_FOLDER).getFile());
            FileUtils.copyDirectory(templateProjectDir, this.workingDir);

            File javaTemplatesDir = new File(
                    this.getClass().getResource("/" + Generator.TEMPLATE_JAVA_FOLDER).getFile());
            FileUtils.copyDirectory(javaTemplatesDir, javaTemplateDir.toFile());
        }

        // Create Java Code Folder
        String[] splitPkg = this.javaPackage.split("\\.");
        String javaFolderString = this.workingDir.getAbsolutePath() + File.separator + "src" + File.separator
                + "main" + File.separator + "java";
        for (int i = 0; i < splitPkg.length; i++) {
            javaFolderString += File.separator + splitPkg[i];
        }

        // Copy TEMPLATE_JAVA_ABSTRACT_IA_SERVICE
        Path templateAbstractIAService = javaTemplateDir.resolve(Generator.TEMPLATE_JAVA_ABSTRACT_IA_SERVICE);
        File javaAbstractIAService = new File(javaFolderString + File.separator + "AbstractIAService.java");
        Files.createDirectories(javaAbstractIAService.toPath().getParent());
        Files.copy(templateAbstractIAService, javaAbstractIAService.toPath(),
                StandardCopyOption.REPLACE_EXISTING);

        // Copy and rename TEMPLATE_JAVA_TEMPLATE_SERVICE
        Path templateJavaService = javaTemplateDir.resolve(Generator.TEMPLATE_JAVA_TEMPLATE_SERVICE);
        File javaService = new File(javaFolderString + File.separator + this.name + ".java");
        Files.createDirectories(javaService.toPath().getParent());
        Files.copy(templateJavaService, javaService.toPath(), StandardCopyOption.REPLACE_EXISTING);

        this.generateJavaFile(javaService);
        this.updateFilesRecursively(this.workingDir);
        return this.packageProject();

    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}