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.mentawai.annotations.ApplicationManagerWithAnnotations.java

@SuppressWarnings("rawtypes")
private void findAnnotatedClasses(String resources) throws IOException {
    ClassLoader cl = Thread.currentThread().getContextClassLoader();
    Enumeration<URL> urls = cl.getResources(resources);
    while (urls.hasMoreElements()) {
        URL url = urls.nextElement();
        if (url.getProtocol().equals("file")) {
            File file = new File(url.getFile());
            findAnnotatedClass(file);// w w w .  j  a  v a 2 s .c o  m
        } else if (url.getProtocol().equals("jar")) {
            URL urlJar = new URL(url.getFile().split("\\!")[0]);
            JarFile jarFile;
            try {
                jarFile = new JarFile(new File(urlJar.toURI().getPath()));
            } catch (URISyntaxException ex) {
                Logger.getLogger(ApplicationManagerWithAnnotations.class.getName()).log(Level.SEVERE, null, ex);
                continue;
            }
            Enumeration<JarEntry> entries = jarFile.entries();
            while (entries.hasMoreElements()) {
                JarEntry entry = entries.nextElement();
                if (getPackageTestJar().matcher(entry.getName()).matches()
                        && entry.getName().endsWith(".class")) {
                    String className = entry.getName().replace('/', '.').substring(0,
                            entry.getName().length() - 6);
                    try {
                        Class klass = Class.forName(className);
                        if (BaseAction.class.isAssignableFrom(klass)) {
                            System.out.println("Add Annotated Class:" + className);
                            annotatedClasses.add(klass);
                        }
                    } catch (Exception e) {
                        System.out.println("error! this class was not started:" + entry.getName());
                    }
                }
            }
        }
    }
}

From source file:com.tasktop.c2c.server.hudson.configuration.service.HudsonServiceConfigurator.java

@Override
public void configure(ProjectServiceConfiguration configuration) {

    // Get a reference to our template WAR, and make sure it exists.
    File hudsonTemplateWar = new File(warTemplateFile);

    if (!hudsonTemplateWar.exists() || !hudsonTemplateWar.isFile()) {
        String message = "The given Hudson template WAR [" + hudsonTemplateWar
                + "] either did not exist or was not a file!";
        LOG.error(message);//from  ww w .j a  v  a2  s. c o m
        throw new IllegalStateException(message);
    }

    String deployLocation = hudsonWarNamingStrategy.getWarFilePath(configuration);

    File hudsonDeployFile = new File(deployLocation);

    if (hudsonDeployFile.exists()) {
        String message = "When trying to deploy new WARfile [" + hudsonDeployFile.getAbsolutePath()
                + "] a file or directory with that name already existed! Continuing with provisioning.";
        LOG.info(message);
        return;
    }

    try {
        // Get a reference to our template war
        JarFile hudsonTemplateWarJar = new JarFile(hudsonTemplateWar);

        // Extract our web.xml from this war
        JarEntry webXmlEntry = hudsonTemplateWarJar.getJarEntry(webXmlFilename);
        String webXmlContents = IOUtils.toString(hudsonTemplateWarJar.getInputStream(webXmlEntry));

        // Update the web.xml to contain the correct HUDSON_HOME value
        String updatedXml = applyDirectoryToWebXml(webXmlContents, configuration);

        File tempDirFile = new File(tempDir);
        if (!tempDirFile.exists()) {
            tempDirFile.mkdirs();
        }

        // Put the web.xml back into the war
        File updatedHudsonWar = File.createTempFile("hudson", ".war", tempDirFile);

        JarOutputStream jarOutStream = new JarOutputStream(new FileOutputStream(updatedHudsonWar),
                hudsonTemplateWarJar.getManifest());

        // Loop through our existing zipfile and add in all of the entries to it except for our web.xml
        JarEntry curEntry = null;
        Enumeration<JarEntry> entries = hudsonTemplateWarJar.entries();
        while (entries.hasMoreElements()) {
            curEntry = entries.nextElement();

            // If this is the manifest, skip it.
            if (curEntry.getName().equals("META-INF/MANIFEST.MF")) {
                continue;
            }

            if (curEntry.getName().equals(webXmlEntry.getName())) {
                JarEntry newEntry = new JarEntry(curEntry.getName());
                jarOutStream.putNextEntry(newEntry);

                // Substitute our edited entry content.
                IOUtils.write(updatedXml, jarOutStream);
            } else {
                jarOutStream.putNextEntry(curEntry);
                IOUtils.copy(hudsonTemplateWarJar.getInputStream(curEntry), jarOutStream);
            }
        }

        // Clean up our resources.
        jarOutStream.close();

        // Move the war into it's deployment location so that it can be picked up and deployed by Tomcat.
        FileUtils.moveFile(updatedHudsonWar, hudsonDeployFile);
    } catch (IOException ioe) {
        // Log this exception and rethrow wrapped in a RuntimeException
        LOG.error(ioe.getMessage());
        throw new RuntimeException(ioe);
    }
}

From source file:com.googlecode.onevre.utils.ServerClassLoader.java

private void indexJar(URL url, File jar) throws IOException {
    JarFile jarFile = new JarFile(jar);
    Enumeration<JarEntry> entries = jarFile.entries();
    while (entries.hasMoreElements()) {
        JarEntry entry = entries.nextElement();
        cachedFiles.put(entry.getName(), url);
    }/*from   w  w w  .j  av a 2 s .  c o m*/
    jarFile.close();
    cachedJars.put(url, jar);
}

From source file:edu.stanford.muse.email.JarDocCache.java

public void exportAsMbox(String outFilename, String prefix, Collection<EmailDocument> selectedDocs,
        boolean append) throws IOException, GeneralSecurityException, ClassNotFoundException {
    PrintWriter mbox = new PrintWriter(new FileOutputStream("filename", append));
    Map<Integer, Document> allHeadersMap = getAllHeaders(prefix);
    Map<Integer, Document> selectedHeadersMap = new LinkedHashMap<Integer, Document>();
    Set<EmailDocument> selectedDocsSet = new LinkedHashSet<EmailDocument>(selectedDocs);

    for (Integer I : allHeadersMap.keySet()) {
        EmailDocument ed = (EmailDocument) allHeadersMap.get(I);
        if (selectedDocsSet.contains(ed))
            selectedHeadersMap.put(I, ed);
    }//from w w w  . j  av a 2s  . co m

    JarFile contentJar = null;
    try {
        contentJar = new JarFile(baseDir + File.separator + prefix + ".contents");
    } catch (Exception e) {
        Util.print_exception(e, log);
        return;
    }

    Enumeration<JarEntry> contentEntries = contentJar.entries();
    String suffix = ".content";
    while (contentEntries.hasMoreElements()) {
        JarEntry c_je = contentEntries.nextElement();
        String s = c_je.getName();
        if (!s.endsWith(suffix))
            continue;
        int index = -1;
        String idx_str = s.substring(0, s.length() - suffix.length());
        try {
            index = Integer.parseInt(idx_str);
        } catch (Exception e) {
            log.error("Funny file in header: " + index);
        }

        EmailDocument ed = (EmailDocument) selectedHeadersMap.get(index);
        if (ed == null)
            continue; // not selected

        byte[] b = Util.getBytesFromStream(contentJar.getInputStream(c_je));
        String contents = new String(b, "UTF-8");
        EmailUtils.printHeaderToMbox(ed, mbox);
        EmailUtils.printBodyAndAttachmentsToMbox(contents, ed, mbox, null);
        mbox.println(contents);
    }
}

From source file:com.egreen.tesla.server.api.component.Component.java

private void init() throws FileNotFoundException, IOException, ConfigurationException {

    //Init url/*from  w  w  w .j av  a2  s .c o  m*/
    this.jarFile = new URL("jar", "", "file:" + file.getAbsolutePath() + "!/");

    final FileInputStream fileInputStream = new FileInputStream(file);
    JarInputStream jarFile = new JarInputStream(fileInputStream);
    JarFile jf = new JarFile(file);

    setConfiguraton(jf);//Configuration load

    jf.getEntry(TESLAR_WIDGET_MAINIFIESTXML);

    JarEntry jarEntry;

    while (true) {
        jarEntry = jarFile.getNextJarEntry();
        if (jarEntry == null) {
            break;
        }
        if (jarEntry.getName().endsWith(".class") && !jarEntry.getName().contains("$")) {
            final String JarNameClass = jarEntry.getName().replaceAll("/", "\\.");
            String className = JarNameClass.replace(".class", "");
            LOGGER.info(className);
            controllerClassMapper.put(className, className);

        } else if (jarEntry.getName().startsWith("webapp")) {
            final String JarNameClass = jarEntry.getName();
            LOGGER.info(JarNameClass);
            saveEntry(jf.getInputStream(jarEntry), JarNameClass);
        }
    }
}

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

private Collection<File> generateFirstDexJar(List<String> mainDexList, Collection<File> files)
        throws IOException {

    List<File> jarList = new ArrayList<>();
    List<File> folderList = new ArrayList<>();
    for (File file : files) {
        if (file.isDirectory()) {
            folderList.add(file);/*w w w .ja  v a2  s.  com*/
        } 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.toPath());
        for (File folder : folderList) {
            jarMerger.addDirectory(folder.toPath());
        }
        jarMerger.close();
        if (mergedJar.length() > 0) {
            jarList.add(mergedJar);
        }
    }

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

    JarOutputStream mainJarOuputStream = new JarOutputStream(
            new BufferedOutputStream(new FileOutputStream(maindexJar)));

    //First order
    Collections.sort(jarList, new NameComparator());

    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();

        List<String> pathList = new ArrayList<>();
        while (jarFileEntries.hasMoreElements()) {
            JarEntry ze = jarFileEntries.nextElement();
            String pathName = ze.getName();
            if (mainDexList.contains(pathName)) {
                copyStream(jarFile.getInputStream(ze), mainJarOuputStream, ze, pathName);
                pathList.add(pathName);
            }
        }

        if (!pathList.isEmpty()) {
            jarFileEntries = jarFile.entries();
            while (jarFileEntries.hasMoreElements()) {
                JarEntry ze = jarFileEntries.nextElement();
                String pathName = ze.getName();
                if (!pathList.contains(pathName)) {
                    copyStream(jarFile.getInputStream(ze), jos, ze, pathName);
                }
            }
        }

        jarFile.close();
        IOUtils.closeQuietly(jos);

        if (pathList.isEmpty()) {
            FileUtils.copyFile(jar, outJar);
        }
        if (!appVariantContext.getAtlasExtension().getTBuildConfig().isFastProguard() && files.size() == 1) {
            JarUtils.splitMainJar(result, outJar, 1, MAX_CLASSES);
        }
    }

    IOUtils.closeQuietly(mainJarOuputStream);

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

    result.add(0, maindexJar);

    return result;
}

From source file:com.cloudera.sqoop.orm.TestClassWriter.java

/**
 * Run a test to verify that we can generate code and it emits the output
 * files where we expect them./* w ww  .j  a  v  a  2  s . c  o m*/
 */
private void runGenerationTest(String[] argv, String classNameToCheck) {
    File codeGenDirFile = new File(CODE_GEN_DIR);
    File classGenDirFile = new File(JAR_GEN_DIR);

    try {
        options = new ImportTool().parseArguments(argv, null, options, true);
    } catch (Exception e) {
        LOG.error("Could not parse options: " + e.toString());
    }

    CompilationManager compileMgr = new CompilationManager(options);
    ClassWriter writer = new ClassWriter(options, manager, HsqldbTestServer.getTableName(), compileMgr);

    try {
        writer.generate();
        compileMgr.compile();
        compileMgr.jar();
    } catch (IOException ioe) {
        LOG.error("Got IOException: " + ioe.toString());
        fail("Got IOException: " + ioe.toString());
    }

    String classFileNameToCheck = classNameToCheck.replace('.', File.separatorChar);
    LOG.debug("Class file to check for: " + classFileNameToCheck);

    // Check that all the files we expected to generate (.java, .class, .jar)
    // exist.
    File tableFile = new File(codeGenDirFile, classFileNameToCheck + ".java");
    assertTrue("Cannot find generated source file for table!", tableFile.exists());
    LOG.debug("Found generated source: " + tableFile);

    File tableClassFile = new File(classGenDirFile, classFileNameToCheck + ".class");
    assertTrue("Cannot find generated class file for table!", tableClassFile.exists());
    LOG.debug("Found generated class: " + tableClassFile);

    File jarFile = new File(compileMgr.getJarFilename());
    assertTrue("Cannot find compiled jar", jarFile.exists());
    LOG.debug("Found generated jar: " + jarFile);

    // check that the .class file made it into the .jar by enumerating 
    // available entries in the jar file.
    boolean foundCompiledClass = false;
    try {
        JarInputStream jis = new JarInputStream(new FileInputStream(jarFile));

        LOG.debug("Jar file has entries:");
        while (true) {
            JarEntry entry = jis.getNextJarEntry();
            if (null == entry) {
                // no more entries.
                break;
            }

            if (entry.getName().equals(classFileNameToCheck + ".class")) {
                foundCompiledClass = true;
                LOG.debug(" * " + entry.getName());
            } else {
                LOG.debug("   " + entry.getName());
            }
        }

        jis.close();
    } catch (IOException ioe) {
        fail("Got IOException iterating over Jar file: " + ioe.toString());
    }

    assertTrue("Cannot find .class file " + classFileNameToCheck + ".class in jar file", foundCompiledClass);

    LOG.debug("Found class in jar - test success!");
}

From source file:net.sf.keystore_explorer.crypto.signing.JarSigner.java

private static String getDigestManifestAttrs(JarFile jar, JarEntry jarEntry, DigestType digestType)
        throws IOException, CryptoException {

    InputStream jis = null;//from www  .j a v a2 s.  c  om

    try {
        // Get input stream to JAR entry's content
        jis = jar.getInputStream(jarEntry);

        // Get the digest of content in Base64
        byte[] md = DigestUtil.getMessageDigest(jis, digestType);
        byte[] md64 = Base64.encode(md);
        String md64Str = new String(md64);

        // Write manifest entries for JARs digest
        StringBuilder sbManifestEntry = new StringBuilder();
        sbManifestEntry.append(createAttributeText(NAME_ATTR, jarEntry.getName()));
        sbManifestEntry.append(CRLF);
        sbManifestEntry
                .append(createAttributeText(MessageFormat.format(DIGEST_ATTR, digestType.jce()), md64Str));
        sbManifestEntry.append(CRLF);
        sbManifestEntry.append(CRLF);

        return sbManifestEntry.toString();
    } finally {
        IOUtils.closeQuietly(jis);
    }
}

From source file:org.teavm.classlib.impl.report.JCLComparisonBuilder.java

private List<JCLPackage> buildModel() throws IOException {
    Map<String, JCLPackage> packageMap = new HashMap<>();
    URL url = classLoader.getResource("java/lang/Object" + CLASS_SUFFIX);
    String path = url.toString();
    if (!path.startsWith(JAR_PREFIX) || !path.endsWith(JAR_SUFFIX)) {
        throw new RuntimeException("Can't find JCL classes");
    }//from   w w  w  .j a  v a2 s.c o m
    ClasspathClassHolderSource classSource = new ClasspathClassHolderSource(classLoader);
    path = path.substring(JAR_PREFIX.length(), path.length() - JAR_SUFFIX.length());
    File outDir = new File(outputDirectory).getParentFile();
    if (!outDir.exists()) {
        outDir.mkdirs();
    }
    path = URLDecoder.decode(path, "UTF-8");
    try (JarInputStream jar = new JarInputStream(new FileInputStream(path))) {
        visitor = new JCLComparisonVisitor(classSource, packageMap);
        while (true) {
            JarEntry entry = jar.getNextJarEntry();
            if (entry == null) {
                break;
            }
            if (validateName(entry.getName())) {
                compareClass(jar);
            }
            jar.closeEntry();
        }
    }
    return new ArrayList<>(packageMap.values());
}

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

/**
 * Extracts the project files to the project directory.
 */// ww w .  j  a v a  2  s .  com
private void extract(URL url) throws Exception {
    packageDirs = packageName.replaceAll("\\.", "/");
    String puTemplate = DIR_TEMPLATES + "/" + template + "/";
    int length = puTemplate.length() - 1;
    BufferedInputStream bis = new BufferedInputStream(url.openStream());
    JarInputStream jis = new JarInputStream(bis);
    JarEntry je;
    byte[] buf = new byte[1024];
    int n;
    while ((je = jis.getNextJarEntry()) != null) {
        String jarEntryName = je.getName();
        PluginLog.getLog().debug("JAR entry: " + jarEntryName);
        if (je.isDirectory() || !jarEntryName.startsWith(puTemplate)) {
            continue;
        }
        String targetFileName = projectDir + jarEntryName.substring(length);

        // convert the ${gsGroupPath} to directory
        targetFileName = StringUtils.replace(targetFileName, FILTER_GROUP_PATH, packageDirs);
        PluginLog.getLog().debug("Extracting entry " + jarEntryName + " to " + targetFileName);

        // read the bytes to the buffer
        ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
        while ((n = jis.read(buf, 0, 1024)) > -1) {
            byteStream.write(buf, 0, n);
        }

        // replace property references with the syntax ${property_name}
        // to their respective property values.
        String data = byteStream.toString();
        data = StringUtils.replace(data, FILTER_GROUP_ID, packageName);
        data = StringUtils.replace(data, FILTER_ARTIFACT_ID, projectDir.getName());
        data = StringUtils.replace(data, FILTER_GROUP_PATH, packageDirs);

        // write the entire converted file content to the destination file.
        File f = new File(targetFileName);
        File dir = f.getParentFile();
        if (!dir.exists()) {
            dir.mkdirs();
        }
        FileWriter writer = new FileWriter(f);
        writer.write(data);
        jis.closeEntry();
        writer.close();
    }
    jis.close();
}