Example usage for java.util.jar Manifest getMainAttributes

List of usage examples for java.util.jar Manifest getMainAttributes

Introduction

In this page you can find the example usage for java.util.jar Manifest getMainAttributes.

Prototype

public Attributes getMainAttributes() 

Source Link

Document

Returns the main Attributes for the Manifest.

Usage

From source file:org.springframework.boot.loader.tools.RepackagerTests.java

@Test
public void noMainClassAndLayoutIsNoneWithNoMain() throws Exception {
    this.testJarFile.addClass("a/b/C.class", ClassWithoutMainMethod.class);
    File file = this.testJarFile.getFile();
    Repackager repackager = new Repackager(file);
    repackager.setLayout(new Layouts.None());
    repackager.repackage(file, NO_LIBRARIES);
    Manifest actualManifest = getManifest(file);
    assertThat(actualManifest.getMainAttributes().getValue("Main-Class")).isNull();
    assertThat(hasLauncherClasses(file)).isFalse();
}

From source file:org.springframework.boot.loader.tools.RepackagerTests.java

@Test
public void mainClassFound() throws Exception {
    this.testJarFile.addClass("a/b/C.class", ClassWithMainMethod.class);
    File file = this.testJarFile.getFile();
    Repackager repackager = new Repackager(file);
    repackager.repackage(NO_LIBRARIES);//w w w  .j av  a 2s. co m
    Manifest actualManifest = getManifest(file);
    assertThat(actualManifest.getMainAttributes().getValue("Main-Class"))
            .isEqualTo("org.springframework.boot.loader.JarLauncher");
    assertThat(actualManifest.getMainAttributes().getValue("Start-Class")).isEqualTo("a.b.C");
    assertThat(hasLauncherClasses(file)).isTrue();
}

From source file:org.springframework.boot.loader.tools.RepackagerTests.java

@Test
public void executableJarLayoutAttributes() throws Exception {
    this.testJarFile.addClass("a/b/C.class", ClassWithMainMethod.class);
    File file = this.testJarFile.getFile();
    Repackager repackager = new Repackager(file);
    repackager.repackage(NO_LIBRARIES);//from   w  ww . j a  v  a  2s . co m
    Manifest actualManifest = getManifest(file);
    assertThat(actualManifest.getMainAttributes()).containsEntry(new Attributes.Name("Spring-Boot-Lib"),
            "BOOT-INF/lib/");
    assertThat(actualManifest.getMainAttributes()).containsEntry(new Attributes.Name("Spring-Boot-Classes"),
            "BOOT-INF/classes/");
}

From source file:org.springframework.boot.loader.tools.RepackagerTests.java

@Test
public void executableWarLayoutAttributes() throws Exception {
    this.testJarFile.addClass("WEB-INF/classes/a/b/C.class", ClassWithMainMethod.class);
    File file = this.testJarFile.getFile("war");
    Repackager repackager = new Repackager(file);
    repackager.repackage(NO_LIBRARIES);//from  w  ww  .  ja v a2  s  .c o m
    Manifest actualManifest = getManifest(file);
    assertThat(actualManifest.getMainAttributes()).containsEntry(new Attributes.Name("Spring-Boot-Lib"),
            "WEB-INF/lib/");
    assertThat(actualManifest.getMainAttributes()).containsEntry(new Attributes.Name("Spring-Boot-Classes"),
            "WEB-INF/classes/");
}

From source file:org.springframework.boot.loader.tools.RepackagerTests.java

@Test
public void specificMainClass() throws Exception {
    this.testJarFile.addClass("a/b/C.class", ClassWithoutMainMethod.class);
    File file = this.testJarFile.getFile();
    Repackager repackager = new Repackager(file);
    repackager.setMainClass("a.b.C");
    repackager.repackage(NO_LIBRARIES);// w  w  w  .  j a  va  2s  . co  m
    Manifest actualManifest = getManifest(file);
    assertThat(actualManifest.getMainAttributes().getValue("Main-Class"))
            .isEqualTo("org.springframework.boot.loader.JarLauncher");
    assertThat(actualManifest.getMainAttributes().getValue("Start-Class")).isEqualTo("a.b.C");
    assertThat(hasLauncherClasses(file)).isTrue();
}

From source file:org.springframework.boot.loader.tools.RepackagerTests.java

@Test
public void jarIsOnlyRepackagedOnce() throws Exception {
    this.testJarFile.addClass("a/b/C.class", ClassWithMainMethod.class);
    File file = this.testJarFile.getFile();
    Repackager repackager = new Repackager(file);
    repackager.repackage(NO_LIBRARIES);//from w  w w  . j  a va 2 s  .c  o m
    repackager.repackage(NO_LIBRARIES);
    Manifest actualManifest = getManifest(file);
    assertThat(actualManifest.getMainAttributes().getValue("Main-Class"))
            .isEqualTo("org.springframework.boot.loader.JarLauncher");
    assertThat(actualManifest.getMainAttributes().getValue("Start-Class")).isEqualTo("a.b.C");
    assertThat(hasLauncherClasses(file)).isTrue();
}

From source file:org.sablo.specification.WebComponentPackage.java

public void appendGlobalTypesJSON(JSONObject allGlobalTypesFromAllPackages) throws IOException {
    Manifest mf = reader.getManifest();

    if (mf != null) {
        Attributes mainAttrs = mf.getMainAttributes();
        if (mainAttrs != null) {
            String globalTypesSpecPath = mainAttrs.getValue(GLOBAL_TYPES_MANIFEST_ATTR);
            if (globalTypesSpecPath != null) {
                try {
                    String specfileContent = reader.readTextFile(globalTypesSpecPath, Charset.forName("UTF8")); // TODO: check encoding
                    if (specfileContent != null) {
                        JSONObject json = new JSONObject(specfileContent);
                        Object types = json.get(WebComponentSpecification.TYPES_KEY);
                        if (types instanceof JSONObject) {
                            Iterator<String> typesIt = ((JSONObject) types).keys();
                            while (typesIt.hasNext()) {
                                String key = typesIt.next();
                                allGlobalTypesFromAllPackages.put(key, ((JSONObject) types).get(key));
                            }/*from   www . j  a  v  a2  s.  c o m*/
                        }
                    }
                } catch (Exception e) {
                    reader.reportError(globalTypesSpecPath, e);
                }
            }
        }
    }
}

From source file:org.eclipse.birt.build.mavenrepogen.RepoGen.java

private void createJar(final File jarFile, final File[] files) throws IOException {
    final Manifest manifest = new Manifest();
    final Attributes attributes = manifest.getMainAttributes();
    attributes.putValue("Manifest-Version", "1.0");
    attributes.putValue("Created-By", "RepoGen 1.0.0");
    final FileOutputStream fos = new FileOutputStream(jarFile);
    final JarOutputStream jos = new JarOutputStream(fos, manifest);
    for (final File file : files) {
        final ZipEntry entry = new ZipEntry(file.getName());
        jos.putNextEntry(entry);//  ww w  .j a  v  a  2s  . c o m
        final FileInputStream fis = new FileInputStream(file);
        pipeStream(fis, jos);
        fis.close();
    }
    jos.close();
}

From source file:org.orbisgis.framework.BundleTools.java

/**
 * Delete OSGi fragment bundles that are both in OSGi cache and in bundle sub-dir
 * @param bundleCache OSGi bundle cache  ex: ~/.Orbisgis/4.X/cache/
 *//*from   w  w  w  .  j  a  v  a2  s.  co m*/
public void deleteFragmentInCache(File bundleCache) {
    if (bundleCache.exists()) {
        // List bundles in the /bundle subdirectory
        File bundleFolder = new File(BUNDLE_DIRECTORY);
        if (!bundleFolder.exists()) {
            return;
        }
        File[] files = bundleFolder.listFiles();
        if (files != null) {
            List<String> fragmentBundlesArtifacts = new ArrayList<>(files.length);
            // Search for Fragment in /bundle/ subdir
            for (File file : files) {
                if (FilenameUtils.isExtension(file.getName(), "jar")) {
                    // Read Manifest
                    try (JarFile jar = new JarFile(file)) {
                        Manifest manifest = jar.getManifest();
                        if (manifest != null && manifest.getMainAttributes() != null) {
                            String artifact = manifest.getMainAttributes().getValue(Constants.FRAGMENT_HOST);
                            if (artifact != null) {
                                fragmentBundlesArtifacts.add(parseManifest(manifest, null).getArtifactId());
                            }
                        }
                    } catch (IOException ex) {
                        LOGGER.log(Logger.LOG_ERROR, "Error while reading Jar manifest:\n" + file.getPath());
                    }
                }
            }
            // Remove folders in bundle cache that contain a fragment cache
            File[] cacheFolders = bundleCache.listFiles((FileFilter) DirectoryFileFilter.DIRECTORY);
            if (cacheFolders != null) {
                for (File folder : cacheFolders) {
                    try {
                        // Get the first folder, may contain only one ex:"version0.0"
                        File[] cacheBundleFolder = folder.listFiles((FileFilter) DirectoryFileFilter.DIRECTORY);
                        if (cacheBundleFolder != null && cacheBundleFolder.length > 0) {
                            // Read Jar manifest
                            File jarBundle = new File(cacheBundleFolder[0], "bundle.jar");
                            if (jarBundle.exists()) {
                                // Read artifact
                                String artifact = parseJarManifest(jarBundle, null).getArtifactId();
                                if (fragmentBundlesArtifacts.contains(artifact)) {
                                    // Delete the cache folder
                                    int tryCount = 0;
                                    while (tryCount < DELETE_TRY_COUNT) {
                                        try {
                                            if (jarBundle.delete()) {
                                                FileUtils.deleteDirectory(folder);
                                            } else {
                                                throw new IOException("Could not delete jar file");
                                            }
                                            break;
                                        } catch (IOException ex) {
                                            tryCount++;
                                            try {
                                                Thread.sleep(WAIT_RETRY_DELETE);
                                            } catch (InterruptedException iex) {
                                                break;
                                            }
                                        }
                                    }
                                    if (folder.exists()) {
                                        LOGGER.log(Logger.LOG_ERROR,
                                                "Cannot delete a bundle cache folder, library may not be up to"
                                                        + " date, please delete the following folder and restart OrbisGIS:"
                                                        + "\n" + folder.getPath());
                                    } else {
                                        LOGGER.log(Logger.LOG_INFO,
                                                I18N.tr("Delete fragment bundle {0} in " + "cache directory",
                                                        artifact));
                                    }
                                }
                            }
                        }
                    } catch (IOException ex) {
                        LOGGER.log(Logger.LOG_ERROR, "Error while reading Jar manifest:\n" + folder.getPath(),
                                ex);
                    }
                }
            }
        }
    }
}

From source file:org.codehaus.plexus.archiver.jar.JarArchiver.java

/**
 * Create the index list to speed up classloading.
 * This is a JDK 1.3+ specific feature and is enabled by default. See
 * <a href="http://java.sun.com/j2se/1.3/docs/guide/jar/jar.html#JAR%20Index">
 * the JAR index specification</a> for more details.
 *
 * @param zOut the zip stream representing the jar being built.
 * @throws IOException thrown if there is an error while creating the
 *                     index and adding it to the zip stream.
 * @throws org.codehaus.plexus.archiver.ArchiverException
 *                     ./*from   ww  w  .  jav a2s  .c o m*/
 */
private void createIndexList(ConcurrentJarCreator zOut) throws IOException, ArchiverException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    // encoding must be UTF8 as specified in the specs.
    PrintWriter writer = new PrintWriter(new OutputStreamWriter(baos, "UTF8"));

    // version-info blankline
    writer.println("JarIndex-Version: 1.0");
    writer.println();

    // header newline
    writer.println(getDestFile().getName());

    // filter out META-INF if it doesn't contain anything other than the index and manifest.
    // this is what sun.misc.JarIndex does, guess we ought to be consistent.
    Set<String> filteredDirs = addedDirs.allAddedDirs();
    // our added dirs always have a trailing slash
    if (filteredDirs.contains(META_INF_NAME + '/')) {
        boolean add = false;
        for (String entry : entries.keySet()) {
            if (entry.startsWith(META_INF_NAME + '/') && !entry.equals(INDEX_NAME)
                    && !entry.equals(MANIFEST_NAME)) {
                add = true;
                break;
            }
        }
        if (!add) {
            filteredDirs.remove(META_INF_NAME + '/');
        }
    }
    writeIndexLikeList(new ArrayList<String>(filteredDirs), rootEntries, writer);
    writer.println();

    if (indexJars != null) {
        java.util.jar.Manifest mf = createManifest();
        String classpath = mf.getMainAttributes().getValue(ManifestConstants.ATTRIBUTE_CLASSPATH);
        String[] cpEntries = null;
        if (classpath != null) {
            StringTokenizer tok = new StringTokenizer(classpath, " ");
            cpEntries = new String[tok.countTokens()];
            int c = 0;
            while (tok.hasMoreTokens()) {
                cpEntries[c++] = tok.nextToken();
            }
        }

        for (String indexJar : indexJars) {
            String name = findJarName(indexJar, cpEntries);
            if (name != null) {
                ArrayList<String> dirs = new ArrayList<String>();
                ArrayList<String> files = new ArrayList<String>();
                grabFilesAndDirs(indexJar, dirs, files);
                if (dirs.size() + files.size() > 0) {
                    writer.println(name);
                    writeIndexLikeList(dirs, files, writer);
                    writer.println();
                }
            }
        }
    }

    writer.flush();

    ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());

    super.zipFile(createInputStreamSupplier(bais), zOut, INDEX_NAME, System.currentTimeMillis(), null,
            DEFAULT_FILE_MODE, null);
}