java.util.jar.Manifest Java Examples

The following examples show how to use java.util.jar.Manifest. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PluginClassLoader.java    From netbeans-mmd-plugin with Apache License 2.0 6 votes vote down vote up
public PluginClassLoader(@Nonnull final File pluginFile) throws IOException {
  super(new URL[] {Assertions.assertNotNull(pluginFile).toURI().toURL()}, PluginClassLoader.class.getClassLoader());
  this.pluginFile = pluginFile;
  this.connection = (JarURLConnection) new URL("jar", "", pluginFile.toURI() + "!/").openConnection();

  final Manifest manifest = this.connection.getManifest();
  Map<String, String> detectedAttributes = null;

  if (manifest != null) {
    final Attributes pluginAttributes = manifest.getEntries().get("nb-mindmap-plugin");
    if (pluginAttributes != null) {
      detectedAttributes = new HashMap<String, String>();
      for (final Object key : pluginAttributes.keySet()) {
        final String keyAsText = key.toString();
        detectedAttributes.put(keyAsText, pluginAttributes.getValue(keyAsText));
      }
    }
  }
  if (detectedAttributes == null) {
    throw new IllegalArgumentException("File is not a NB mind map plugin");
  }
  this.attributes = Collections.unmodifiableMap(detectedAttributes);
  this.apiVersion = new Version(this.attributes.get(Attribute.API.getAttrName()));
}
 
Example #2
Source File: VirtualDependenciesService.java    From component-runtime with Apache License 2.0 6 votes vote down vote up
private byte[] generateConfigurationJar(final String family, final Properties userConfiguration) {
    final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    final Manifest manifest = new Manifest();
    final Attributes mainAttributes = manifest.getMainAttributes();
    mainAttributes.put(Attributes.Name.MANIFEST_VERSION, "1.0");
    mainAttributes.putValue("Created-By", "Talend Component Kit Server");
    mainAttributes.putValue("Talend-Time", Long.toString(System.currentTimeMillis()));
    mainAttributes.putValue("Talend-Family-Name", family);
    try (final JarOutputStream jar = new JarOutputStream(new BufferedOutputStream(outputStream), manifest)) {
        jar.putNextEntry(new JarEntry("TALEND-INF/local-configuration.properties"));
        userConfiguration.store(jar, "Configuration of the family " + family);
        jar.closeEntry();
    } catch (final IOException e) {
        throw new IllegalStateException(e);
    }
    return outputStream.toByteArray();
}
 
Example #3
Source File: JarManifestParser.java    From flink with Apache License 2.0 6 votes vote down vote up
private static Optional<String> findFirstManifestAttribute(JarFile jarFile, String... attributes) throws IOException {
	Manifest manifest = jarFile.getManifest();
	if (manifest == null) {
		return Optional.empty();
	}

	Attributes mainAttributes = manifest.getMainAttributes();
	for (String attribute : attributes) {
		String value = mainAttributes.getValue(attribute);
		if (value != null) {
			return Optional.of(value);
		}
	}

	return Optional.empty();
}
 
Example #4
Source File: Demo.java    From picocli with Apache License 2.0 6 votes vote down vote up
public String[] getVersion() throws Exception {
    Enumeration<URL> resources = CommandLine.class.getClassLoader().getResources("META-INF/MANIFEST.MF");
    while (resources.hasMoreElements()) {
        URL url = resources.nextElement();
        try {
            Manifest manifest = new Manifest(url.openStream());
            if (isApplicableManifest(manifest)) {
                Attributes attributes = manifest.getMainAttributes();
                return new String[] { attributes.get(key("Implementation-Title")) + " version \"" + attributes.get(key("Implementation-Version")) + "\"" };
            }
        } catch (IOException ex) {
            return new String[] { "Unable to read from " + url + ": " + ex };
        }
    }
    return new String[0];
}
 
Example #5
Source File: Repackager.java    From sofa-ark with Apache License 2.0 6 votes vote down vote up
private void repackageModule() throws IOException {
    File destination = pluginModuleJar.getAbsoluteFile();
    destination.delete();

    JarFile jarFileSource = new JarFile(source);
    JarWriter writer = new JarWriter(destination);
    Manifest manifest = buildModuleManifest(jarFileSource);

    try {
        writer.writeManifest(manifest);
        writer.writeEntries(jarFileSource);
        writer.writeMarkEntry();
        writeNestedLibraries(standardLibraries, Layouts.Module.module(), writer);
    } finally {
        jarFileSource.close();
        try {
            writer.close();
        } catch (Exception ex) {
            // Ignore
        }
    }
}
 
Example #6
Source File: JarDirectoryStepTest.java    From buck with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldSortManifestAttributesAndEntries() throws InterruptedException, IOException {
  Manifest fromJar =
      createManifestWithExampleSection(ImmutableMap.of("foo", "bar", "baz", "waz"));
  Manifest fromUser =
      createManifestWithExampleSection(ImmutableMap.of("bar", "foo", "waz", "baz"));

  String seenManifest =
      new String(jarDirectoryAndReadManifestContents(fromJar, fromUser, true), UTF_8);

  assertEquals(
      Joiner.on("\r\n")
          .join(
              "Manifest-Version: 1.0",
              "",
              "Name: example",
              "bar: foo",
              "baz: waz",
              "foo: bar",
              "waz: baz",
              "",
              ""),
      seenManifest);
}
 
Example #7
Source File: ViewservletRepoGen.java    From birt with Eclipse Public License 1.0 6 votes vote down vote up
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);
		final FileInputStream fis = new FileInputStream(file);
		pipeStream(fis, jos);
		fis.close();
	}
	jos.close();
}
 
Example #8
Source File: AdapterUtils.java    From java-debug with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Generate the classpath parameters to a temporary classpath.jar.
 * @param classPaths - the classpath parameters
 * @return the file path of the generate classpath.jar
 * @throws IOException Some errors occur during generating the classpath.jar
 */
public static Path generateClasspathJar(String[] classPaths) throws IOException {
    List<String> classpathUrls = new ArrayList<>();
    for (String classpath : classPaths) {
        classpathUrls.add(AdapterUtils.toUrl(classpath));
    }

    Manifest manifest = new Manifest();
    Attributes attributes = manifest.getMainAttributes();
    attributes.put(Attributes.Name.MANIFEST_VERSION, "1.0");
    // In jar manifest, the absolute path C:\a.jar should be converted to the url style file:///C:/a.jar
    String classpathValue = String.join(" ", classpathUrls);
    attributes.put(Attributes.Name.CLASS_PATH, classpathValue);
    Path tempfile = createTempFile("cp_" + getMd5(classpathValue), ".jar");
    JarOutputStream jar = new JarOutputStream(new FileOutputStream(tempfile.toFile()), manifest);
    jar.close();

    return tempfile;
}
 
Example #9
Source File: NbProblemDisplayerTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testSimpleDepOnJava() throws Exception {
    StringBuilder writeTo = new StringBuilder();
    Set<ProblemModule> modules = new HashSet<ProblemModule>();

    {
        Manifest mf = new Manifest();
        mf.getMainAttributes().putValue("OpenIDE-Module", "root.module");
        ProblemModule pm = new ProblemModule(mf);
        pm.addProblem(Dependency.create(Dependency.TYPE_JAVA, "Java > 1.30"));
        pm.addAttr("OpenIDE-Module-Name", "RootModule");
        modules.add(pm);
    }
    
    NbProblemDisplayer.problemMessagesForModules(writeTo, modules, true);

    String msg = writeTo.toString();
    if (msg.indexOf("RootModule") == -1) {
        fail("There should be noted the root module: " + msg);
    }
}
 
Example #10
Source File: Main.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
private boolean updateManifest(Manifest m, ZipOutputStream zos)
    throws IOException
{
    addVersion(m);
    addCreatedBy(m);
    if (ename != null) {
        addMainClass(m, ename);
    }
    ZipEntry e = new ZipEntry(MANIFEST_NAME);
    e.setTime(System.currentTimeMillis());
    if (flag0) {
        crc32Manifest(e, m);
    }
    zos.putNextEntry(e);
    m.write(zos);
    if (vflag) {
        output(getMsg("out.update.manifest"));
    }
    return true;
}
 
Example #11
Source File: Installer.java    From QuickTheories with Apache License 2.0 6 votes vote down vote up
private void createJarFromClassPathResources(final FileOutputStream fos,
    final String location) throws IOException {
  final Manifest m = new Manifest();

  m.clear();
  final Attributes global = m.getMainAttributes();
  if (global.getValue(Attributes.Name.MANIFEST_VERSION) == null) {
    global.put(Attributes.Name.MANIFEST_VERSION, "1.0");
  }
  final File mylocation = new File(location);
  global.putValue(BOOT_CLASSPATH, getBootClassPath(mylocation));
  global.putValue(PREMAIN_CLASS, AGENT_CLASS_NAME);
  global.putValue(AGENT_CLASS, AGENT_CLASS_NAME);    
  global.putValue(CAN_REDEFINE_CLASSES, "true");
  global.putValue(CAN_RETRANSFORM_CLASSES, "true");
  global.putValue(CAN_SET_NATIVE_METHOD, "true");

  try(JarOutputStream jos = new JarOutputStream(fos, m)) {
    addClass(Agent.class, jos);
    addClass(CodeCoverageStore.class, jos);
    addClass(InvokeReceiver.class, jos);
  }
}
 
Example #12
Source File: CustomManifestSectionsThinJarTest.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@Test
public void testManifestEntries() throws Exception {
    assertThat(prodModeTestResults.getResults()).hasSize(1);
    Path jarPath = prodModeTestResults.getResults().get(0).getPath();

    try (InputStream fileInputStream = new FileInputStream(jarPath.toFile())) {
        try (JarInputStream stream = new JarInputStream(fileInputStream)) {
            Manifest manifest = stream.getManifest();
            assertThat(manifest).isNotNull();
            assertThat(manifest.getEntries().size()).isEqualTo(1);
            Attributes testAttributes = manifest.getEntries().get("Test-Information");
            assertThat(testAttributes).isNotNull();
            Attributes.Name testKey1 = new Attributes.Name("Test-Key-1");
            Assert.assertTrue("Custom Manifest Entry for Test-Key-1 is missing",
                    testAttributes.containsKey(testKey1));
            Assert.assertEquals("Custom Manifest Entry for Test-Key-1 value is not correct",
                    "Test Value 1", testAttributes.getValue(testKey1));
            Assert.assertTrue("Custom Manifest Entry for Test-Key-2 is missing",
                    testAttributes.containsKey(new Attributes.Name("Test-Key-2")));
        }
    }
}
 
Example #13
Source File: URLClassLoader.java    From jdk1.8-source-analysis with Apache License 2.0 6 votes vote down vote up
private Package getAndVerifyPackage(String pkgname,
                                    Manifest man, URL url) {
    Package pkg = getPackage(pkgname);
    if (pkg != null) {
        // Package found, so check package sealing.
        if (pkg.isSealed()) {
            // Verify that code source URL is the same.
            if (!pkg.isSealed(url)) {
                throw new SecurityException(
                    "sealing violation: package " + pkgname + " is sealed");
            }
        } else {
            // Make sure we are not attempting to seal the package
            // at this code source URL.
            if ((man != null) && isSealed(pkgname, man)) {
                throw new SecurityException(
                    "sealing violation: can't seal package " + pkgname +
                    ": already loaded");
            }
        }
    }
    return pkg;
}
 
Example #14
Source File: BundleMaker.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
/** Creates a temporary file with the given metadata */ 
public File createTempBundle(String nameHint, Manifest mf, Map<ZipEntry, InputStream> files) {
    File f2 = Os.newTempFile(nameHint, "zip");
    ZipOutputStream zout = null;
    ZipFile zf = null;
    try {
        zout = mf!=null ? new JarOutputStream(new FileOutputStream(f2), mf) : new ZipOutputStream(new FileOutputStream(f2));
        writeZipEntries(zout, files);
    } catch (IOException e) {
        throw Exceptions.propagateAnnotated("Unable to read/write for "+nameHint, e);
    } finally {
        Streams.closeQuietly(zf);
        Streams.closeQuietly(zout);
    }
    return f2;
}
 
Example #15
Source File: Metadata.java    From p4ic4idea with Apache License 2.0 6 votes vote down vote up
/**
    * Public main method, used solely for allowing customers to
    * print version and other metadata information from the enclosing
    * JAR file's manifest. This information is printed to stdout;
    * errors are printed to stderr.
    * 
    * @since 2011.1
    * @param args not used.
    */
public static void main(String[] args) {
	try {
		Manifest manifest = getManifest();
		Attributes attr = manifest.getMainAttributes();
		System.out.println(attr.getValue(Name.IMPLEMENTATION_TITLE));
		StringBuilder version = new StringBuilder(
				attr.getValue(Name.IMPLEMENTATION_VERSION));
		String changelist = attr.getValue("Build-Changelist");
		if (changelist != null) {
			version.append('/').append(changelist);
		}
		String type = attr.getValue("Build-Type");
		if (type != null) {
			version.append('/').append(type);
		}
		System.out.println(version);
	} catch (Exception exception) {
		System.err.println(exception.getLocalizedMessage());
	}
}
 
Example #16
Source File: BigJar.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
Manifest createMainClass(File javaFile) throws IOException {
    javaFile.delete();
    List<String> content = new ArrayList<>();
    content.add("public class " + baseName(javaFile) + "{");
    content.add("public static void main(String... args) {");
    content.add("System.out.println(\"Hello World\\n\");");
    content.add("System.exit(0);");
    content.add("}");
    content.add("}");
    createFile(javaFile, content);
    compile(javaFile.getName());
    Manifest manifest = new Manifest();
    manifest.clear();
    manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
    manifest.getMainAttributes().put(Attributes.Name.MAIN_CLASS, baseName(javaFile));
    System.out.println(manifest.getMainAttributes().keySet());
    System.out.println(manifest.getMainAttributes().values());
    return manifest;
}
 
Example #17
Source File: ManifestReaderTest.java    From spliceengine with GNU Affero General Public License v3.0 6 votes vote down vote up
public static ManifestFinder mockManifest(String releaseVersion) {

        Attributes attributes = new Attributes();
        attributes.putValue("Build-Time", "2014-05-27 12:52 -0500");
        attributes.putValue("Implementation-Version", "1d073ed3f6");
        attributes.putValue("Build-Jdk", "1.7.0_51");
        attributes.putValue("Built-By", "Jenkinson");
        attributes.putValue("Manifest-Version", "1.0");
        attributes.putValue("Created-By", "Apache Maven 3.1.1");
        attributes.putValue("Release", releaseVersion);
        attributes.putValue("URL", "http://www.splicemachine.com");
        attributes.putValue("Archiver-Version", "Plexus Archiver");

        Manifest spliceManifest = mock(Manifest.class);
        when(spliceManifest.getMainAttributes()).thenReturn(attributes);

        ManifestFinder mockFinder = mock(ManifestFinder.class);
        when(mockFinder.findManifest()).thenReturn(spliceManifest);

        return mockFinder;
    }
 
Example #18
Source File: ManifestClassPathProcessor.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
private static String[] getClassPathEntries(final ResourceRoot resourceRoot) {

        final Manifest manifest;
        try {
            manifest = VFSUtils.getManifest(resourceRoot.getRoot());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        if (manifest == null) {
            // no class path to process!
            return EMPTY_STRING_ARRAY;
        }
        final String classPathString = manifest.getMainAttributes().getValue(Attributes.Name.CLASS_PATH);
        if (classPathString == null) {
            // no entry
            return EMPTY_STRING_ARRAY;
        }
        return classPathString.split("\\s+");
    }
 
Example #19
Source File: RemoveWritablesTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private File createModuleJar(String manifest) throws IOException {
    // XXX use TestFileUtils.writeZipFile
    File jarFile = new File( getWorkDir(), "mymodule.jar" );
    
    JarOutputStream os = new JarOutputStream(new FileOutputStream(jarFile), new Manifest(
        new ByteArrayInputStream(manifest.getBytes())
    ));
    JarEntry entry = new JarEntry("foo/mf-layer.xml");
    os.putNextEntry( entry );
    
    File l3 = new File(new File(new File(getDataDir(), "layers"), "data"), "layer3.xml");
    InputStream is = new FileInputStream(l3);
    FileUtil.copy( is, os );
    is.close();
    os.close();
    
    return jarFile;
}
 
Example #20
Source File: Jadx.java    From Box with Apache License 2.0 6 votes vote down vote up
public static String getVersion() {
	try {
		ClassLoader classLoader = Jadx.class.getClassLoader();
		if (classLoader != null) {
			Enumeration<URL> resources = classLoader.getResources("META-INF/MANIFEST.MF");
			while (resources.hasMoreElements()) {
				try (InputStream is = resources.nextElement().openStream()) {
					Manifest manifest = new Manifest(is);
					String ver = manifest.getMainAttributes().getValue("jadx-version");
					if (ver != null) {
						return ver;
					}
				}
			}
		}
	} catch (Exception e) {
		LOG.error("Can't get manifest file", e);
	}
	return "dev";
}
 
Example #21
Source File: ApkPatch.java    From atlas with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("deprecation")
protected Manifest getMeta() {
    Manifest manifest = new Manifest();
    Attributes main = manifest.getMainAttributes();
    main.putValue("Manifest-Version", "1.0");
    main.putValue("Created-By", "1.0 (ApkPatch)");
    main.putValue("Created-Time", new Date(System.currentTimeMillis()).toGMTString());
    main.putValue("From-File", baseFiles.get(0).getName());
    main.putValue("To-File", newFiles.get(0).getName());
    main.putValue("Patch-Name", name);
    main.putValue(name + "-Patch-Classes", Formater.dotStringList(classes));
    main.putValue(name + "-Prepare-Classes", Formater.dotStringList(prepareClasses));
    main.putValue(name + "-Used-Methods", Formater.dotStringList(usedMethods));
    main.putValue(name + "-Modified-Classes", Formater.dotStringList(modifiedClasses));
    main.putValue(name + "-Used-Classes", Formater.dotStringList(usedClasses));
    main.putValue(name + "-add-classes", Formater.dotStringList(addClasses));

    return manifest;
}
 
Example #22
Source File: URLClassLoader.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
private void definePackageInternal(String pkgname, Manifest man, URL url)
{
    if (getAndVerifyPackage(pkgname, man, url) == null) {
        try {
            if (man != null) {
                definePackage(pkgname, man, url);
            } else {
                definePackage(pkgname, null, null, null, null, null, null, null);
            }
        } catch (IllegalArgumentException iae) {
            // parallel-capable class loaders: re-verify in case of a
            // race condition
            if (getAndVerifyPackage(pkgname, man, url) == null) {
                // Should never happen
                throw new AssertionError("Cannot find package " +
                                         pkgname);
            }
        }
    }
}
 
Example #23
Source File: Aegisthus.java    From aegisthus with Apache License 2.0 6 votes vote down vote up
private static void logAegisthusVersion() {
    String classPath = Aegisthus.class.getResource("Aegisthus.class").toString();
    String manifestPath = classPath.replace("com/netflix/Aegisthus.class", "META-INF/MANIFEST.MF");
    try (InputStream inputStream = new URL(manifestPath).openStream()) {
        Manifest manifest = new Manifest(inputStream);
        Attributes attr = manifest.getMainAttributes();
        System.out.println("Running Aegisthus version " +
                        attr.getValue("Implementation-Version") +
                        " built from change " +
                        attr.getValue("Change") +
                        " on host " +
                        attr.getValue("Build-Host") +
                        " on " +
                        attr.getValue("Build-Date") +
                        " with Java " +
                        attr.getValue("Build-Java-Version")
        );
    } catch (IOException ignored) {
        System.out.println("Unable to locate Aegisthus manifest file");
    }
}
 
Example #24
Source File: CommandLineProgram.java    From gatk with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * @return An abbreviated name of the toolkit for this tool. Looks for "Tool-Short-Name" in the manifest by default.
 *         Uses {@link #DEFAULT_TOOLKIT_SHORT_NAME} if the manifest is unavailable.
 * Subclasses may override to do something different.
 */
protected String getToolkitShortName() {
    final Manifest manifest = RuntimeUtils.getManifest(this.getClass());
    if( manifest != null){
        return manifest.getMainAttributes().getValue("Toolkit-Short-Name");
    } else {
        return DEFAULT_TOOLKIT_SHORT_NAME;
    }
}
 
Example #25
Source File: ConfigPackage.java    From Bats with Apache License 2.0 5 votes vote down vote up
/**
 * Creates an Config Package object.
 *
 * @param file
 * @throws java.io.IOException
 * @throws net.lingala.zip4j.exception.ZipException
 */
public ConfigPackage(File file) throws IOException, ZipException
{
  super(file);
  Manifest manifest = getManifest();
  if (manifest == null) {
    throw new IOException("Not a valid config package. MANIFEST.MF is not present.");
  }
  Attributes attr = manifest.getMainAttributes();
  configPackageName = attr.getValue(ATTRIBUTE_DT_CONF_PACKAGE_NAME);
  appPackageName = attr.getValue(ATTRIBUTE_DT_APP_PACKAGE_NAME);
  appPackageGroupId = attr.getValue(ATTRIBUTE_DT_APP_PACKAGE_GROUP_ID);
  appPackageMinVersion = attr.getValue(ATTRIBUTE_DT_APP_PACKAGE_MIN_VERSION);
  appPackageMaxVersion = attr.getValue(ATTRIBUTE_DT_APP_PACKAGE_MAX_VERSION);
  configPackageDescription = attr.getValue(ATTRIBUTE_DT_CONF_PACKAGE_DESCRIPTION);
  String classPathString = attr.getValue(ATTRIBUTE_CLASS_PATH);
  String filesString = attr.getValue(ATTRIBUTE_FILES);
  if (configPackageName == null) {
    throw new IOException("Not a valid config package.  DT-Conf-Package-Name is missing from MANIFEST.MF");
  }
  if (!StringUtils.isBlank(classPathString)) {
    classPath.addAll(Arrays.asList(StringUtils.split(classPathString, " ")));
  }
  if (!StringUtils.isBlank(filesString)) {
    files.addAll(Arrays.asList(StringUtils.split(filesString, " ")));
  }

  ZipFile zipFile = new ZipFile(file);
  if (zipFile.isEncrypted()) {
    throw new ZipException("Encrypted conf package not supported yet");
  }
  File newDirectory = Files.createTempDirectory("dt-configPackage-").toFile();
  newDirectory.mkdirs();
  directory = newDirectory.getAbsolutePath();
  zipFile.extractAll(directory);
  processPropertiesXml();
  processAppDirectory(new File(directory, "app"));
}
 
Example #26
Source File: LauncherHelper.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
static String getMainClassFromJar(String jarname) {
    String mainValue = null;
    try (JarFile jarFile = new JarFile(jarname)) {
        Manifest manifest = jarFile.getManifest();
        if (manifest == null) {
            abort(null, "java.launcher.jar.error2", jarname);
        }
        Attributes mainAttrs = manifest.getMainAttributes();
        if (mainAttrs == null) {
            abort(null, "java.launcher.jar.error3", jarname);
        }
        mainValue = mainAttrs.getValue(MAIN_CLASS);
        if (mainValue == null) {
            abort(null, "java.launcher.jar.error3", jarname);
        }

        /*
         * Hand off to FXHelper if it detects a JavaFX application
         * This must be done after ensuring a Main-Class entry
         * exists to enforce compliance with the jar specification
         */
        if (mainAttrs.containsKey(
                new Attributes.Name(FXHelper.JAVAFX_APPLICATION_MARKER))) {
            return FXHelper.class.getName();
        }

        return mainValue.trim();
    } catch (IOException ioe) {
        abort(ioe, "java.launcher.jar.error1", jarname);
    }
    return null;
}
 
Example #27
Source File: JarFileExportOperation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private void saveManifest() throws CoreException, IOException {
	ByteArrayOutputStream manifestOutput= new ByteArrayOutputStream();
	Manifest manifest= fJarPackage.getManifestProvider().create(fJarPackage);
	manifest.write(manifestOutput);
	ByteArrayInputStream fileInput= new ByteArrayInputStream(manifestOutput.toByteArray());
	IFile manifestFile= fJarPackage.getManifestFile();
	if (manifestFile.isAccessible()) {
		if (fJarPackage.allowOverwrite() || JarPackagerUtil.askForOverwritePermission(fParentShell, manifestFile.getFullPath(), false))
			manifestFile.setContents(fileInput, true, true, null);
	} else
		manifestFile.create(fileInput, true, null);
}
 
Example #28
Source File: NetigsoModuleListTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testParseConfigXML() throws Exception {
    File c = new File(new File(getWorkDir(), "config"), "Modules");
    c.mkdirs();
    File j = new File(new File(getWorkDir(), "subdir"), "x-y-z.jar");
    j.getParentFile().mkdirs();
    Manifest mf = new Manifest();
    mf.getMainAttributes().putValue("Manifest-Version", "1.0");
    mf.getMainAttributes().putValue("Bundle-SymbolicName", "x.y.z;singleton:=true");
    JarOutputStream os = new JarOutputStream(new FileOutputStream(j), mf);
    os.close();

    String cnt = "<?xml version='1.0' encoding='UTF-8'?>" +
            "<!DOCTYPE module PUBLIC '-//NetBeans//DTD Module Status 1.0//EN'" +
            "   'http://www.netbeans.org/dtds/module-status-1_0.dtd'>" +
            "<module name='x.y.z'>" +
            "  <param name='autoload'>true</param>" +
            "  <param name='eager'>false</param>" +
            "  <param name='jar'>subdir/x-y-z.jar</param>" +
            "</module>";
    TestFileUtils.writeFile(new File(c, "x-y-z.xml"), cnt);

    ClusterInfo ci = ClusterInfo.createExternal(getWorkDir(), new URL[0], new URL[0], true);
    ModuleList ml = ModuleList.scanCluster(getWorkDir(), getWorkDir(), true, ci);

    assertEquals("One found", 1, ml.getAllEntries().size());
    ModuleEntry me = ml.getEntry("x.y.z");
    assertNotNull("Correct entry found", me);
    assertEquals("Cnb is OK", "x.y.z", me.getCodeNameBase());
    assertEquals("Jar file OK", j, me.getJarLocation());
}
 
Example #29
Source File: Package.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
private static Package defineSystemPackage(final String iname,
                                           final String fn)
{
    return AccessController.doPrivileged(new PrivilegedAction<Package>() {
        public Package run() {
            String name = iname;
            // Get the cached code source url for the file name
            URL url = urls.get(fn);
            if (url == null) {
                // URL not found, so create one
                File file = new File(fn);
                try {
                    url = ParseUtil.fileToEncodedURL(file);
                } catch (MalformedURLException e) {
                }
                if (url != null) {
                    urls.put(fn, url);
                    // If loading a JAR file, then also cache the manifest
                    if (file.isFile()) {
                        mans.put(fn, loadManifest(fn));
                    }
                }
            }
            // Convert to "."-separated package name
            name = name.substring(0, name.length() - 1).replace('/', '.');
            Package pkg;
            Manifest man = mans.get(fn);
            if (man != null) {
                pkg = new Package(name, man, url, null);
            } else {
                pkg = new Package(name, null, null, null,
                                  null, null, null, null, null);
            }
            pkgs.put(name, pkg);
            return pkg;
        }
    });
}
 
Example #30
Source File: URLClassLoader.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
private boolean isSealed(String name, Manifest man) {
    Attributes attr = SharedSecrets.javaUtilJarAccess()
            .getTrustedAttributes(man, name.replace('.', '/').concat("/"));
    String sealed = null;
    if (attr != null) {
        sealed = attr.getValue(Name.SEALED);
    }
    if (sealed == null) {
        if ((attr = man.getMainAttributes()) != null) {
            sealed = attr.getValue(Name.SEALED);
        }
    }
    return "true".equalsIgnoreCase(sealed);
}