Example usage for java.util.jar Manifest Manifest

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

Introduction

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

Prototype

public Manifest() 

Source Link

Document

Constructs a new, empty Manifest.

Usage

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

@Test
public void mainClassFromManifest() throws Exception {
    this.testJarFile.addClass("a/b/C.class", ClassWithoutMainMethod.class);
    Manifest manifest = new Manifest();
    manifest.getMainAttributes().putValue("Manifest-Version", "1.0");
    manifest.getMainAttributes().putValue("Main-Class", "a.b.C");
    this.testJarFile.addManifest(manifest);
    File file = this.testJarFile.getFile();
    Repackager repackager = new Repackager(file);
    repackager.repackage(NO_LIBRARIES);//from ww  w  . j  av a 2 s.  c o  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.zanata.ZanataInit.java

public void initZanata(ServletContext context) throws Exception {
    checkAppServerVersion();/*from   w ww.j  a  va  2s  .  co m*/
    String appServerHome = context.getRealPath("/");
    File manifestFile = new File(appServerHome, "META-INF/MANIFEST.MF");
    VersionInfo zanataVersion;
    Attributes atts = null;
    if (manifestFile.canRead()) {
        Manifest mf = new Manifest();
        try (FileInputStream fis = new FileInputStream(manifestFile)) {
            mf.read(fis);
        }
        atts = mf.getMainAttributes();
    }
    zanataVersion = VersionUtility.getVersionInfo(atts, ZanataInit.class);
    this.applicationConfiguration.setVersion(zanataVersion.getVersionNo());
    this.applicationConfiguration.setBuildTimestamp(zanataVersion.getBuildTimeStamp());
    this.applicationConfiguration.setScmDescribe(zanataVersion.getScmDescribe());
    this.applicationConfiguration.applyLoggingConfiguration();
    logBanner(zanataVersion);
    boolean authlogged = false;
    if (applicationConfiguration.isInternalAuth()) {
        log.info("Internal authentication: enabled");
        authlogged = true;
    }
    if (applicationConfiguration.isOpenIdAuth()) {
        log.info("OpenID authentication: enabled");
        authlogged = true;
    }
    if (applicationConfiguration.isKerberosAuth()) {
        log.info("SPNEGO/Kerberos authentication: enabled");
        authlogged = true;
    }
    if (!authlogged) {
        log.info("Using JAAS authentication");
    }
    log.info("Enable copyTrans: {}", this.applicationConfiguration.isCopyTransEnabled());
    String javamelodyDir = System.getProperty("javamelody.storage-directory");
    log.info("JavaMelody stats directory: " + javamelodyDir);
    String indexBase = applicationConfiguration.getHibernateSearchIndexBase();
    log.info("Lucene index directory: " + indexBase);
    if (indexBase != null) {
        checkLuceneLocks(new File(indexBase));
    }
    // Email server information
    log.info("Mail Session (JNDI): {}", EmailBuilder.MAIL_SESSION_JNDI);
    startupEvent.fire(new ServerStarted());
    log.info("Started Zanata...");
}

From source file:com.ikanow.aleph2.analytics.spark.services.SparkCompilerService.java

/** Compiles a scala class
 * @param script//from  w ww . j av a2  s .com
 * @param clazz_name
 * @return
 * @throws IOException
 * @throws InstantiationException
 * @throws IllegalAccessException
 * @throws ClassNotFoundException
 */
public Tuple2<ClassLoader, Object> buildClass(final String script, final String clazz_name,
        final Optional<IBucketLogger> logger)
        throws IOException, InstantiationException, IllegalAccessException, ClassNotFoundException {
    final String relative_dir = "./script_classpath/";
    new File(relative_dir).mkdirs();

    final File source_file = new File(relative_dir + clazz_name + ".scala");
    FileUtils.writeStringToFile(source_file, script);

    final String this_path = LiveInjector.findPathJar(this.getClass(), "./dummy.jar");
    final File f = new File(this_path);
    final File fp = new File(f.getParent());
    final String classpath = Arrays.stream(fp.listFiles()).map(ff -> ff.toString())
            .filter(ff -> ff.endsWith(".jar")).collect(Collectors.joining(":"));

    // Need this to make the URL classloader be used, not the system classloader (which doesn't know about Aleph2..)

    final Settings s = new Settings();
    s.classpath().value_$eq(System.getProperty("java.class.path") + classpath);
    s.usejavacp().scala$tools$nsc$settings$AbsSettings$AbsSetting$$internalSetting_$eq(true);
    final StoreReporter reporter = new StoreReporter();
    final Global g = new Global(s, reporter);
    final Run r = g.new Run();
    r.compile(JavaConverters.asScalaBufferConverter(Arrays.<String>asList(source_file.toString())).asScala()
            .toList());

    if (reporter.hasErrors() || reporter.hasWarnings()) {
        final String errors = "Compiler: Errors/warnings (**to get to user script line substract 22**): "
                + JavaConverters.asJavaSetConverter(reporter.infos()).asJava().stream()
                        .map(info -> info.toString()).collect(Collectors.joining(" ;; "));
        logger.ifPresent(l -> l.log(reporter.hasErrors() ? Level.ERROR : Level.DEBUG, false, () -> errors,
                () -> "SparkScalaInterpreterTopology", () -> "compile"));

        //ERROR:
        if (reporter.hasErrors()) {
            System.err.println(errors);
        }
    }
    // Move any class files (eg including sub-classes)
    Arrays.stream(fp.listFiles()).filter(ff -> ff.toString().endsWith(".class"))
            .forEach(Lambdas.wrap_consumer_u(ff -> {
                FileUtils.moveFile(ff, new File(relative_dir + ff.getName()));
            }));

    // Create a JAR file...

    Manifest manifest = new Manifest();
    manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
    final JarOutputStream target = new JarOutputStream(new FileOutputStream("./script_classpath.jar"),
            manifest);
    Arrays.stream(new File(relative_dir).listFiles()).forEach(Lambdas.wrap_consumer_i(ff -> {
        JarEntry entry = new JarEntry(ff.getName());
        target.putNextEntry(entry);
        try (BufferedInputStream in = new BufferedInputStream(new FileInputStream(ff))) {
            byte[] buffer = new byte[1024];
            while (true) {
                int count = in.read(buffer);
                if (count == -1)
                    break;
                target.write(buffer, 0, count);
            }
            target.closeEntry();
        }
    }));
    target.close();

    final String created = "Created = " + new File("./script_classpath.jar").toURI().toURL() + " ... "
            + Arrays.stream(new File(relative_dir).listFiles()).map(ff -> ff.toString())
                    .collect(Collectors.joining(";"));
    logger.ifPresent(l -> l.log(Level.DEBUG, true, () -> created, () -> "SparkScalaInterpreterTopology",
            () -> "compile"));

    final Tuple2<ClassLoader, Object> o = Lambdas.get(Lambdas.wrap_u(() -> {
        _cl.set(new java.net.URLClassLoader(
                Arrays.asList(new File("./script_classpath.jar").toURI().toURL()).toArray(new URL[0]),
                Thread.currentThread().getContextClassLoader()));
        Object o_ = _cl.get().loadClass("ScriptRunner").newInstance();
        return Tuples._2T(_cl.get(), o_);
    }));
    return o;
}

From source file:org.nuxeo.osgi.application.loader.FrameworkLoader.java

protected static boolean isBundle(File f) {
    Manifest mf;/*from   w ww.  ja  v  a 2  s  . c  o m*/
    try {
        if (f.isFile()) { // jar file
            JarFile jf = new JarFile(f);
            try {
                mf = jf.getManifest();
            } finally {
                jf.close();
            }
            if (mf == null) {
                return false;
            }
        } else if (f.isDirectory()) { // directory
            f = new File(f, "META-INF/MANIFEST.MF");
            if (!f.isFile()) {
                return false;
            }
            mf = new Manifest();
            FileInputStream input = new FileInputStream(f);
            try {
                mf.read(input);
            } finally {
                input.close();
            }
        } else {
            return false;
        }
    } catch (IOException e) {
        return false;
    }
    return mf.getMainAttributes().containsKey(SYMBOLIC_NAME);
}

From source file:org.codehaus.mojo.jspc.CompileMojo.java

protected void createJarArchive(File archiveFile, File tempJarDir) throws IOException {
    JarOutputStream jos = null;//from www  .ja v  a  2 s  .co  m
    try {
        jos = new JarOutputStream(new BufferedOutputStream(new FileOutputStream(archiveFile)), new Manifest());

        int pathLength = tempJarDir.getAbsolutePath().length() + 1;
        Collection<File> files = FileUtils.listFiles(tempJarDir, null, true);
        for (final File file : files) {
            if (!file.isFile()) {
                continue;
            }

            if (getLog().isDebugEnabled()) {
                getLog().debug("file: " + file.getAbsolutePath());
            }

            // Add entry
            String name = file.getAbsolutePath().substring(pathLength);
            // normalize path as the JspCompiler expects '/' as separator
            name = name.replace('\\', '/');
            JarEntry jarFile = new JarEntry(name);
            jos.putNextEntry(jarFile);

            FileUtils.copyFile(file, jos);
        }
    } finally {
        IOUtils.closeQuietly(jos);
    }
}

From source file:pxb.android.tinysign.TinySign.java

/**
 * create a signed jar from dir to out/*w  w  w.java  2s  .c  om*/
 * 
 * @param dir
 *            a folder contains file
 * @param out
 *            the output jar
 * @throws Exception
 */
public static void sign(File dir, OutputStream out) throws Exception {
    ZipOutputStream zos = new ZipOutputStream(out);
    zos.putNextEntry(new ZipEntry("META-INF/"));
    zos.closeEntry();
    // .MF
    Manifest manifest = new Manifest();
    String sha1Manifest = writeMF(dir, manifest, zos);

    // SF
    Manifest sf = generateSF(manifest);
    byte[] sign = writeSF(zos, sf, sha1Manifest);

    writeRSA(zos, sign);
    IOUtils.closeQuietly(zos);
}

From source file:com.facebook.buck.java.JarDirectoryStepTest.java

@Test
public void entriesFromTheGivenManifestShouldOverrideThoseInTheJars() throws IOException {
    String expected = "1.4";
    // Write the manifest, setting the implementation version
    Path tmp = folder.newFolder();

    Manifest manifest = new Manifest();
    manifest.getMainAttributes().putValue(MANIFEST_VERSION.toString(), "1.0");
    manifest.getMainAttributes().putValue(IMPLEMENTATION_VERSION.toString(), expected);
    Path manifestFile = tmp.resolve("manifest");
    try (OutputStream fos = Files.newOutputStream(manifestFile)) {
        manifest.write(fos);//w  ww . j  av  a2 s  . c  o  m
    }

    // Write another manifest, setting the implementation version to something else
    manifest = new Manifest();
    manifest.getMainAttributes().putValue(MANIFEST_VERSION.toString(), "1.0");
    manifest.getMainAttributes().putValue(IMPLEMENTATION_VERSION.toString(), "1.0");

    Path input = tmp.resolve("input.jar");
    try (CustomZipOutputStream out = ZipOutputStreams.newOutputStream(input)) {
        ZipEntry entry = new ZipEntry("META-INF/MANIFEST.MF");
        out.putNextEntry(entry);
        manifest.write(out);
    }

    Path output = tmp.resolve("output.jar");
    JarDirectoryStep step = new JarDirectoryStep(new ProjectFilesystem(tmp), Paths.get("output.jar"),
            ImmutableSet.of(Paths.get("input.jar")), /* main class */ null, Paths.get("manifest"),
            /* merge manifest */ true, /* blacklist */ ImmutableSet.<String>of());
    ExecutionContext context = TestExecutionContext.newInstance();
    assertEquals(0, step.execute(context));

    try (Zip zip = new Zip(output, false)) {
        byte[] rawManifest = zip.readFully("META-INF/MANIFEST.MF");
        manifest = new Manifest(new ByteArrayInputStream(rawManifest));
        String version = manifest.getMainAttributes().getValue(IMPLEMENTATION_VERSION);

        assertEquals(expected, version);
    }
}

From source file:org.sonatype.nexus.plugins.p2.repository.metadata.AbstractP2MetadataSource.java

private static StorageFileItem compressMetadataItem(final Repository repository, final String path,
        final StorageFileItem metadataXml) throws IOException {
    final Manifest manifest = new Manifest();
    manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");

    // this is a special one: once cached (hence consumed), temp file gets deleted
    final FileContentLocator fileContentLocator = new FileContentLocator("application/java-archive");

    try (OutputStream buffer = fileContentLocator.getOutputStream();
            ZipOutputStream out = new ZipOutputStream(buffer);
            InputStream in = metadataXml.getInputStream()) {
        out.putNextEntry(new JarEntry(metadataXml.getName()));
        IOUtils.copy(in, out);/*from   www. jav  a  2 s .c  o m*/
    }

    final DefaultStorageFileItem result = new DefaultStorageFileItem(repository, new ResourceStoreRequest(path),
            true /* isReadable */, false /* isWritable */, fileContentLocator);
    return result;
}

From source file:org.jahia.services.modulemanager.util.ModuleUtils.java

/**
 * Performs the transformation of the capability attributes in the MANIFEST.MF file of the supplied stream.
 *
 * @param sourceStream the source stream for the bundle, which manifest has to be adjusted w.r.t. module dependencies; the stream is
 *            closed after returning from this method
 * @return the transformed stream for the bundle with adjusted manifest
 * @throws IOException in case of I/O errors
 *//*from  www .j  a v  a 2s  .  c o m*/
public static InputStream addModuleDependencies(InputStream sourceStream) throws IOException {
    ByteArrayOutputStream out = new ByteArrayOutputStream();

    try (ZipInputStream zis = new ZipInputStream(sourceStream);
            ZipOutputStream zos = new ZipOutputStream(out);) {
        ZipEntry zipEntry = zis.getNextEntry();
        while (zipEntry != null) {
            zos.putNextEntry(new ZipEntry(zipEntry.getName()));
            if (JarFile.MANIFEST_NAME.equals(zipEntry.getName())) {
                // we read the manifest from the source stream
                Manifest mf = new Manifest();
                mf.read(zis);

                addCapabilities(mf.getMainAttributes());

                // write the manifest entry into the target output stream
                mf.write(zos);
            } else {
                IOUtils.copy(zis, zos);
            }
            zis.closeEntry();
            zipEntry = zis.getNextEntry();
        }
    }

    return new ByteArrayInputStream(out.toByteArray());
}

From source file:ai.h2o.servicebuilder.Util.java

/**
 * Create jar archive out of files list. Names in archive have paths starting from relativeToDir
 *
 * @param tobeJared     list of files//from   ww  w  .j  av  a 2  s . c  o  m
 * @param relativeToDir starting directory for paths
 * @return jar as byte array
 * @throws IOException
 */
public static byte[] createJarArchiveByteArray(File[] tobeJared, String relativeToDir) throws IOException {
    int BUFFER_SIZE = 10240;
    byte buffer[] = new byte[BUFFER_SIZE];
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    JarOutputStream out = new JarOutputStream(stream, new Manifest());

    for (File t : tobeJared) {
        if (t == null || !t.exists() || t.isDirectory()) {
            if (t != null && !t.isDirectory())
                logger.error("Can't add to jar {}", t);
            continue;
        }
        // Create jar entry
        String filename = t.getPath().replace(relativeToDir, "").replace("\\", "/");
        //      if (filename.endsWith("MANIFEST.MF")) { // skip to avoid duplicates
        //        continue;
        //      }
        JarEntry jarAdd = new JarEntry(filename);
        jarAdd.setTime(t.lastModified());
        out.putNextEntry(jarAdd);

        // Write file to archive
        FileInputStream in = new FileInputStream(t);
        while (true) {
            int nRead = in.read(buffer, 0, buffer.length);
            if (nRead <= 0)
                break;
            out.write(buffer, 0, nRead);
        }
        in.close();
    }

    out.close();
    stream.close();
    return stream.toByteArray();
}