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:co.cask.cdap.internal.app.runtime.spark.SparkRuntimeService.java

/**
 * Updates the dependency jar packaged by the {@link ApplicationBundler#createBundle(Location, Iterable,
 * Iterable)} by moving the things inside classes, lib, resources a level up as expected by spark.
 *
 * @param dependencyJar {@link Location} of the job jar to be updated
 * @param context       {@link BasicSparkContext} of this job
 *///from www  .j a v a2  s. c  o  m
private Location updateDependencyJar(Location dependencyJar, BasicSparkContext context) throws IOException {

    final String[] prefixToStrip = { ApplicationBundler.SUBDIR_CLASSES, ApplicationBundler.SUBDIR_LIB,
            ApplicationBundler.SUBDIR_RESOURCES };

    Id.Program programId = context.getProgram().getId();

    Location updatedJar = locationFactory.create(String.format("%s.%s.%s.%s.%s.jar",
            ProgramType.SPARK.name().toLowerCase(), programId.getAccountId(), programId.getApplicationId(),
            programId.getId(), context.getRunId().getId()));

    // Creates Manifest
    Manifest manifest = new Manifest();
    manifest.getMainAttributes().put(ManifestFields.MANIFEST_VERSION, "1.0");
    JarOutputStream jarOutput = new JarOutputStream(updatedJar.getOutputStream(), manifest);

    try {
        JarInputStream jarInput = new JarInputStream(dependencyJar.getInputStream());

        try {
            JarEntry jarEntry = jarInput.getNextJarEntry();

            while (jarEntry != null) {
                boolean isDir = jarEntry.isDirectory();
                String entryName = jarEntry.getName();
                String newEntryName = entryName;

                for (String prefix : prefixToStrip) {
                    if (entryName.startsWith(prefix) && !entryName.equals(prefix)) {
                        newEntryName = entryName.substring(prefix.length());
                    }
                }

                jarEntry = new JarEntry(newEntryName);
                jarOutput.putNextEntry(jarEntry);
                if (!isDir) {
                    ByteStreams.copy(jarInput, jarOutput);
                }
                jarEntry = jarInput.getNextJarEntry();
            }
        } finally {
            jarInput.close();
            Locations.deleteQuietly(dependencyJar);
        }
    } finally {
        jarOutput.close();
    }
    return updatedJar;
}

From source file:org.guvnor.m2repo.backend.server.M2RepositoryServiceImplTest.java

@Test
public void testDeployArtifact() throws Exception {
    deployArtifact(gavBackend);//  w ww .j  a  v a2  s  .c o m

    Collection<File> files = repo.listFiles();

    boolean found = false;
    for (File file : files) {
        String fileName = file.getName();
        if (fileName.startsWith("guvnor-m2repo-editor-backend-0.0.1") && fileName.endsWith(".jar")) {
            found = true;
            String path = file.getPath();
            String jarPath = path.substring(GuvnorM2Repository.M2_REPO_DIR.length() + 1);
            String pom = GuvnorM2Repository.getPomText(jarPath);
            assertNotNull(pom);
            break;
        }
    }

    assertTrue("Did not find expected file after calling M2Repository.addFile()", found);

    // Test get artifact file
    File file = repo.getArtifactFileFromRepository(gavBackend);
    assertNotNull("Empty file for artifact", file);
    JarFile jarFile = new JarFile(file);
    int count = 0;

    String lastEntryName = null;
    for (Enumeration<JarEntry> entries = jarFile.entries(); entries.hasMoreElements();) {
        ++count;
        JarEntry entry = entries.nextElement();
        assertNotEquals("Endless loop.", lastEntryName, entry.getName());
    }
    assertTrue("Empty jar file!", count > 0);
}

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

/**
 * Writes a modified *.class file to the output JAR file.
 *//* ww w.  j  a  va  2  s  .  co  m*/
private void rewriteClass(JarEntry entry, InputStream inputStream, JarOutputStream outputStream)
        throws IOException {
    ClassReader classReader = new ClassReader(inputStream);
    ClassNode classNode = new ClassNode(Opcodes.ASM5);

    classReader.accept(classNode, EMPTY_FLAGS);

    modifyClass(classNode);

    ClassWriter classWriter = new ClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES);
    classNode.accept(classWriter);

    outputStream.putNextEntry(new ZipEntry(entry.getName()));
    outputStream.write(classWriter.toByteArray());
}

From source file:org.ebayopensource.turmeric.plugins.maven.resources.ResourceLocator.java

private URI findFileResource(File path, String pathref) {
    if (path.isFile()) {
        // Assume its an archive.
        String extn = FilenameUtils.getExtension(path.getName());
        if (StringUtils.isBlank(extn)) {
            log.debug("No extension found for file: " + path);
            return null;
        }//from www  .  j  a  va 2 s . c o  m

        extn = extn.toLowerCase();
        if ("jar".equals(extn)) {
            log.debug("looking inside of jar file: " + path);
            JarFile jar = null;
            try {
                jar = new JarFile(path);
                JarEntry entry = jar.getJarEntry(pathref);
                if (entry == null) {
                    log.debug("JarEntry not found: " + pathref);
                    return null;
                }

                String uripath = String.format("jar:%s!/%s", path.toURI(), entry.getName());
                try {
                    return new URI(uripath);
                } catch (URISyntaxException e) {
                    log.debug("Unable to create URI reference: " + path, e);
                    return null;
                }
            } catch (JarException e) {
                log.debug("Unable to open archive: " + path, e);
                return null;
            } catch (IOException e) {
                log.debug("Unable to open archive: " + path, e);
                return null;
            } finally {
                if (jar != null) {
                    try {
                        jar.close();
                    } catch (IOException e) {
                        log.debug("Unable to close jar: " + path, e);
                    }
                }
            }
        }

        log.debug("Unsupported archive file: " + path);
        return null;
    }

    if (path.isDirectory()) {
        File testFile = new File(path, FilenameUtils.separatorsToSystem(pathref));
        if (testFile.exists() && testFile.isFile()) {
            return testFile.toURI();
        }

        log.debug("Not found in directory: " + testFile);
        return null;
    }

    log.debug("Unable to handle non-file, non-directory " + File.class.getName() + " objects: " + path);
    return null;
}

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

/**
 * Find class inside managed jars or hand over the parent
 * @see java.lang.ClassLoader#findClass(java.lang.String)
 *//*from w w  w.  ja  v a  2  s. co m*/
protected Class<?> findClass(String name) throws ClassNotFoundException {

    // find in already loaded classes to make things shorter
    Class<?> clazz = findLoadedClass(name);
    if (clazz != null)
        return clazz;

    // check if the class searched for is contained inside managed jars,
    // otherwise hand over the request to the parent class loader
    String jarFileName = this.classesJarMapping.get(name);
    if (StringUtils.isBlank(jarFileName)) {
        super.findClass(name);
    }

    // try to find class inside jar the class name is associated with
    JarInputStream jarInput = null;
    try {
        // open a stream on jar which contains the class
        jarInput = new JarInputStream(new FileInputStream(jarFileName));
        // ... and iterate through all entries
        JarEntry jarEntry = null;
        while ((jarEntry = jarInput.getNextJarEntry()) != null) {

            // extract the name of the jar entry and check if it has suffix '.class' and thus contains
            // the search for implementation
            String entryFileName = jarEntry.getName();
            if (entryFileName.endsWith(".class")) {

                // replace slashes by dots, remove suffix and compare the result with the searched for class name 
                entryFileName = entryFileName.substring(0, entryFileName.length() - 6).replace('/', '.');
                if (name.equalsIgnoreCase(entryFileName)) {

                    // load bytes from jar entry and define a class over it
                    byte[] data = loadBytes(jarInput);
                    if (data != null) {
                        return defineClass(name, data, 0, data.length);
                    }

                    // if the jar entry does not contain any data, throw an exception
                    throw new ClassNotFoundException("Class '" + name + "' not found");
                }
            }
        }
    } catch (IOException e) {
        // if any io error occurs: throw an exception
        throw new ClassNotFoundException("Class '" + name + "' not found");
    } finally {
        try {
            jarInput.close();
        } catch (IOException e) {
            logger.error("Failed to close open JAR file '" + jarFileName + "'. Error: " + e.getMessage());
        }
    }

    // if no such class exists, throw an exception
    throw new ClassNotFoundException("Class [" + name + "] not found");

}

From source file:org.dspace.installer_edm.InstallerEDMConfEDMExport.java

/**
 * Recorre el war para escribir los archivos web.xml, la api de dspace y los jar de lucene
 *
 * @throws IOException/* www.  j  av  a2s. c  o m*/
 * @throws TransformerException
 */
private void writeNewJar() throws IOException, TransformerException {
    final int BUFFER_SIZE = 1024;
    // directorio de trabajo
    File jarDir = new File(this.eDMExportWarJarFile.getName()).getParentFile();
    // archivo temporal del nuevo war
    File newJarFile = File.createTempFile("EDMExport", ".jar", jarDir);
    newJarFile.deleteOnExit();
    // flujo de escritura para el nuevo war
    JarOutputStream jarOutputStream = new JarOutputStream(new FileOutputStream(newJarFile));

    try {
        // recorrer los archivos del war
        Enumeration<JarEntry> entries = eDMExportWarJarFile.entries();
        // libreras de lucene
        Pattern luceneLibPattern = Pattern.compile("^WEB-INF/lib/(lucene-.+?)-\\d+.+\\.jar$");
        boolean newApiCopied = false;
        if (dspaceApi == null)
            newApiCopied = true;
        boolean replace = false;
        // recorrer
        while (entries.hasMoreElements()) {
            replace = false;
            installerEDMDisplay.showProgress('.');
            JarEntry entry = entries.nextElement();
            InputStream intputStream = null;
            // todos menos web.xml
            if (!entry.getName().equals("WEB-INF/web.xml")) {
                // api de dspace, se muestra la actual y la de dspace para pedir si se copia
                if (!newApiCopied && entry.getName().matches("^WEB-INF/lib/dspace-api-\\d+.+\\.jar$")) {
                    String response = null;
                    do {
                        installerEDMDisplay.showLn();
                        installerEDMDisplay.showQuestion(currentStepGlobal, "writeNewJar.replace.question",
                                new String[] { entry.getName(), "WEB-INF/lib/" + dspaceApi.getName(),
                                        dspaceApi.getAbsolutePath() });
                        response = br.readLine();
                        if (response == null)
                            continue;
                        response = response.trim();
                        if (response.isEmpty() || response.equalsIgnoreCase(answerYes)) {
                            replace = true;
                            break;
                        } else if (response.equalsIgnoreCase("n")) {
                            break;
                        }
                    } while (true);
                    // se reemplaza por la de dspace
                    if (replace) {
                        JarEntry newJarEntry = new JarEntry("WEB-INF/lib/" + dspaceApi.getName());
                        newJarEntry.setCompressedSize(-1);
                        jarOutputStream.putNextEntry(newJarEntry);
                        intputStream = new FileInputStream(dspaceApi);
                        newApiCopied = true;
                        if (debug) {
                            installerEDMDisplay.showLn();
                            installerEDMDisplay.showQuestion(currentStepGlobal, "writeNewJar.replace",
                                    new String[] { entry.getName(), "WEB-INF/lib/" + dspaceApi.getName(),
                                            dspaceApi.getAbsolutePath() });
                            installerEDMDisplay.showLn();
                        }
                    }
                } else {
                    // libreras de lucene
                    Matcher luceneLibMatcher = luceneLibPattern.matcher(entry.getName());
                    if (luceneLibMatcher.find()) {
                        String prefixLuceneLib = luceneLibMatcher.group(1);
                        File luceneLibFile = null;
                        String patternFile = prefixLuceneLib + "-\\d+.+\\.jar";
                        for (File file : luceneLibs) {
                            if (file.getName().matches(patternFile)) {
                                luceneLibFile = file;
                                break;
                            }
                        }
                        if (luceneLibFile != null) {
                            String response = null;
                            do {
                                installerEDMDisplay.showLn();
                                installerEDMDisplay.showQuestion(currentStepGlobal,
                                        "writeNewJar.replace.question",
                                        new String[] { entry.getName(),
                                                "WEB-INF/lib/" + luceneLibFile.getName(),
                                                luceneLibFile.getAbsolutePath() });
                                response = br.readLine();
                                if (response == null)
                                    continue;
                                response = response.trim();
                                if (response.isEmpty() || response.equalsIgnoreCase(answerYes)) {
                                    replace = true;
                                    break;
                                } else if (response.equalsIgnoreCase("n")) {
                                    break;
                                }
                            } while (true);
                            // se reemplaza por la de dspace
                            if (replace) {
                                JarEntry newJarEntry = new JarEntry("WEB-INF/lib/" + luceneLibFile.getName());
                                newJarEntry.setCompressedSize(-1);
                                jarOutputStream.putNextEntry(newJarEntry);
                                intputStream = new FileInputStream(luceneLibFile);
                                if (debug) {
                                    installerEDMDisplay.showLn();
                                    installerEDMDisplay.showQuestion(currentStepGlobal, "writeNewJar.replace",
                                            new String[] { entry.getName(),
                                                    "WEB-INF/lib/" + luceneLibFile.getName(),
                                                    luceneLibFile.getAbsolutePath() });
                                    installerEDMDisplay.showLn();
                                }
                            }
                        }
                        // si no era la api de dspace o las libreras de lucene se copia tal cual
                    } else if (!replace) {
                        JarEntry entryOld = new JarEntry(entry);
                        entryOld.setCompressedSize(-1);
                        jarOutputStream.putNextEntry(entryOld);
                        intputStream = eDMExportWarJarFile.getInputStream(entry);
                    }
                }
                if (intputStream == null) {
                    if (debug)
                        installerEDMDisplay.showQuestion(currentStepGlobal, "writeNewJar.notIS",
                                new String[] { entry.getName() });
                    continue;
                }
                // se lee el archivo y se copia al flujo de escritura del war
                int count;
                byte data[] = new byte[BUFFER_SIZE];
                while ((count = intputStream.read(data, 0, BUFFER_SIZE)) != -1) {
                    jarOutputStream.write(data, 0, count);
                }
                intputStream.close();
            }
        }
        installerEDMDisplay.showLn();
        // se aade web.xml al war
        addNewWebXml(jarOutputStream);
        // cerramos el archivo jar y borramos el war
        eDMExportWarJarFile.close();
        eDMExportWarWorkFile.delete();
        // sustituimos el viejo por el temporal
        try {
            /*if (newJarFile.renameTo(eDMExportWarWorkFile) && eDMExportWarWorkFile.setExecutable(true, true)) {
            eDMExportWarWorkFile = new File(myInstallerWorkDirPath + fileSeparator + eDMExportWarFile.getName());
            } else {
            throw new IOException();
            }*/
            if (jarOutputStream != null)
                jarOutputStream.close();
            FileUtils.moveFile(newJarFile, eDMExportWarWorkFile);
            //newJarFile.renameTo(eDMExportWarWorkFile);
            eDMExportWarWorkFile.setExecutable(true, true);
            eDMExportWarWorkFile = new File(
                    myInstallerWorkDirPath + fileSeparator + eDMExportWarFile.getName());
        } catch (Exception io) {
            io.printStackTrace();
            throw new IOException();
        }
    } finally {
        if (jarOutputStream != null) {
            jarOutputStream.close();
        }
    }
}

From source file:org.apache.maven.plugins.help.EvaluateMojo.java

/**
 * @param xstreamObject not null//  w  w w .j a  v a 2  s  .  c o  m
 * @param jarFile not null
 * @param packageFilter a package name to filter.
 */
private void addAlias(XStream xstreamObject, File jarFile, String packageFilter) {
    JarInputStream jarStream = null;
    try {
        jarStream = new JarInputStream(new FileInputStream(jarFile));
        JarEntry jarEntry = jarStream.getNextJarEntry();
        while (jarEntry != null) {
            if (jarEntry.getName().toLowerCase(Locale.ENGLISH).endsWith(".class")) {
                String name = jarEntry.getName().substring(0, jarEntry.getName().indexOf("."));
                name = name.replaceAll("/", "\\.");

                if (name.contains(packageFilter)) {
                    try {
                        Class<?> clazz = ClassUtils.getClass(name);
                        String alias = StringUtils.lowercaseFirstLetter(ClassUtils.getShortClassName(clazz));
                        xstreamObject.alias(alias, clazz);
                        if (!clazz.equals(Model.class)) {
                            xstreamObject.omitField(clazz, "modelEncoding"); // unnecessary field
                        }
                    } catch (ClassNotFoundException e) {
                        getLog().error(e);
                    }
                }
            }

            jarStream.closeEntry();
            jarEntry = jarStream.getNextJarEntry();
        }
    } catch (IOException e) {
        if (getLog().isDebugEnabled()) {
            getLog().debug("IOException: " + e.getMessage(), e);
        }
    } finally {
        IOUtil.close(jarStream);
    }
}

From source file:com.taobao.android.builder.tools.multidex.FastMultiDexer.java

@Override
public Collection<File> repackageJarList(Collection<File> files) throws IOException {

    List<String> mainDexList = getMainDexList(files);

    List<File> jarList = new ArrayList<>();
    List<File> folderList = new ArrayList<>();
    for (File file : files) {
        if (file.isDirectory()) {
            folderList.add(file);//ww w.  ja  va 2s  .  c  o  m
        } else {
            jarList.add(file);
        }
    }

    File dir = new File(appVariantContext.getScope().getGlobalScope().getIntermediatesDir(),
            "fastmultidex/" + appVariantContext.getVariantName());
    FileUtils.deleteDirectory(dir);
    dir.mkdirs();

    if (!folderList.isEmpty()) {
        File mergedJar = new File(dir, "jarmerging/combined.jar");
        mergedJar.getParentFile().mkdirs();
        mergedJar.delete();
        mergedJar.createNewFile();
        JarMerger jarMerger = new JarMerger(mergedJar);
        for (File folder : folderList) {
            jarMerger.addFolder(folder);
        }
        jarMerger.close();
        if (mergedJar.length() > 0) {
            jarList.add(mergedJar);
        }
    }

    List<File> result = new ArrayList<>();
    File maindexJar = new File(dir, "fastmaindex.jar");

    JarOutputStream mainJarOuputStream = new JarOutputStream(
            new BufferedOutputStream(new FileOutputStream(maindexJar)));
    for (File jar : jarList) {
        File outJar = new File(dir, FileNameUtils.getUniqueJarName(jar) + ".jar");
        result.add(outJar);
        JarFile jarFile = new JarFile(jar);
        JarOutputStream jos = new JarOutputStream(new BufferedOutputStream(new FileOutputStream(outJar)));
        Enumeration<JarEntry> jarFileEntries = jarFile.entries();
        while (jarFileEntries.hasMoreElements()) {
            JarEntry ze = jarFileEntries.nextElement();
            String pathName = ze.getName();
            if (mainDexList.contains(pathName)) {
                copyStream(jarFile.getInputStream(ze), mainJarOuputStream, ze, pathName);
            } else {
                copyStream(jarFile.getInputStream(ze), jos, ze, pathName);
            }
        }
        jarFile.close();
        IOUtils.closeQuietly(jos);
    }
    IOUtils.closeQuietly(mainJarOuputStream);

    Collections.sort(result, new NameComparator());

    result.add(0, maindexJar);

    return result;
}

From source file:ffx.FFXClassLoader.java

/**
 * {@inheritDoc}/*w  w  w . j a  va2  s . c o  m*/
 *
 * Returns the URL of the given resource searching first if it exists among
 * the extension JARs given in constructor.
 */
@Override
public URL findResource(String name) {
    if (!extensionsLoaded) {
        loadExtensions();
    }

    if (name.equals("List all scripts")) {
        listScripts();
    }

    if (extensionJars != null) {
        for (JarFile extensionJar : extensionJars) {
            JarEntry jarEntry = extensionJar.getJarEntry(name);
            if (jarEntry != null) {
                String path = "jar:file:" + extensionJar.getName() + "!/" + jarEntry.getName();
                try {
                    return new URL(path);
                } catch (MalformedURLException ex) {
                    System.out.println(path + "\n" + ex.toString());
                }
            }
        }
    }

    return super.findResource(name);
}

From source file:org.apache.tomcat.maven.plugin.tomcat7.run.AbstractExecWarMojo.java

/**
 * Copy the contents of a jar file to another archive
 *
 * @param file The input jar file/*  w w  w .  j  av  a 2 s  .co m*/
 * @param os   The output archive
 * @throws IOException
 */
protected void extractJarToArchive(JarFile file, ArchiveOutputStream os, String[] excludes) throws IOException {
    Enumeration<? extends JarEntry> entries = file.entries();
    while (entries.hasMoreElements()) {
        JarEntry j = entries.nextElement();

        if (excludes != null && excludes.length > 0) {
            for (String exclude : excludes) {
                if (SelectorUtils.match(exclude, j.getName())) {
                    continue;
                }
            }
        }

        if (StringUtils.equalsIgnoreCase(j.getName(), "META-INF/MANIFEST.MF")) {
            continue;
        }
        os.putArchiveEntry(new JarArchiveEntry(j.getName()));
        IOUtils.copy(file.getInputStream(j), os);
        os.closeArchiveEntry();
    }
    if (file != null) {
        file.close();
    }
}