Example #1
1
  /** @throws IOException */
  public void createJar() throws IOException {
    Manifest manifest = new Manifest();

    setDefaultAttributes(metaInfAttributes);

    for (String attrName : metaInfAttributes.keySet()) {
      manifest.getMainAttributes().putValue(attrName, metaInfAttributes.get(attrName));
    }

    removeOldJar();

    if (unpackaged) {
      for (File inputDir : inputDirectory) {
        FileUtils.copyFilesFromDir(inputDir, outputFile, getIncludes(), getExcludes());
      }
      File metaInfDir = new File(outputFile, "META-INF");
      metaInfDir.mkdirs();
      manifest.write(new FileOutputStream(new File(metaInfDir, "MANIFEST.MF")));
    } else {
      File parentFile = outputFile.getParentFile();
      if (parentFile != null && !parentFile.exists()) {
        parentFile.mkdirs();
      }

      JarOutputStream target = new JarOutputStream(new FileOutputStream(outputFile), manifest);

      if (inputDirectory != null) {
        Set<String> added = new HashSet<String>();
        for (File inputDir : inputDirectory) {
          addFile(inputDir, target, inputDir.getCanonicalPath().length(), added);
        }
      }
      target.close();
    }
  }
Example #2
0
  private Set<Object> injectManifestProperties(Manifest manifest) {

    //		System.out.println(" inject manifest properties ");

    Set<Object> ks = manifest.getMainAttributes().keySet();
    for (Object o : ks) {
      if (o instanceof Attributes.Name) {
        Attributes.Name an = (Attributes.Name) o;

        if (an.toString().startsWith("Field-Property-")) {
          String prop = an.toString().substring("Field-Property-".length());

          if (prop.startsWith("Append-")) {
            prop = prop.substring("Append-".length());
            prop = prop.replace("-", ".");

            String pp = SystemProperties.getProperty(prop, null);
            pp =
                (pp == null
                    ? pathify(manifest.getMainAttributes().getValue(an))
                    : (pp + ":" + pathify(manifest.getMainAttributes().getValue(an))));
            SystemProperties.setProperty(prop, pp);

            //						System.out.println(" property <" + prop + "> now <" + pp + ">");

          } else {
            SystemProperties.setProperty(prop, manifest.getMainAttributes().getValue(an));
          }
        }
      }
    }
    return ks;
  }
Example #3
0
  public static String getVersion(ServletContext application) {
    String defaultVersion = "";
    try {
      InputStream inputStream = application.getResourceAsStream("/META-INF/MANIFEST.MF");
      Manifest manifest = new Manifest(inputStream);
      Attributes attributes = manifest.getMainAttributes();
      String version = attributes.getValue("Application-Version");
      String builtTime = attributes.getValue("HudsonBuildId");
      String revision = attributes.getValue("HudsonBuildNumber");

      if (version != null
          && version != ""
          && builtTime != null
          && builtTime != ""
          && revision != null
          && revision != "") {

        String versionTmp = "";
        if (version.contains("SNAPSHOT")) {
          versionTmp = version.substring(0, version.indexOf("-"));
        } else {
          versionTmp = version;
        }

        return versionTmp + " Build " + builtTime.substring(0, 10) + " Rev:" + revision;
      }
    } catch (IOException e) {
    }
    return defaultVersion;
  }
 private Map<String, URLClassLoader> createClassLoaderMap(File dir, String[] files)
     throws IOException {
   Map<String, URLClassLoader> m = new TreeMap<String, URLClassLoader>();
   for (int i = 0; i < files.length; i++) {
     File moduleJar = new File(dir, files[i]);
     Manifest manifest;
     JarFile jar = new JarFile(moduleJar);
     try {
       manifest = jar.getManifest();
     } finally {
       jar.close();
     }
     if (manifest == null) {
       log(moduleJar + " has no manifest", Project.MSG_WARN);
       continue;
     }
     String codename = JarWithModuleAttributes.extractCodeName(manifest.getMainAttributes());
     if (codename == null) {
       log(moduleJar + " is not a module", Project.MSG_WARN);
       continue;
     }
     m.put(
         codename.replaceFirst("/[0-9]+$", ""),
         new URLClassLoader(
             new URL[] {moduleJar.toURI().toURL()},
             ClassLoader.getSystemClassLoader().getParent(),
             new NbDocsStreamHandler.Factory()));
   }
   return m;
 }
  /** Reads the jar's manifest. */
  private void loadManifest() {
    if (_isManifestRead) return;

    synchronized (this) {
      if (_isManifestRead) return;

      try {
        _manifest = _jarPath.getManifest();
        if (_manifest == null) return;

        Attributes attr = _manifest.getMainAttributes();
        if (attr != null) addManifestPackage("", attr);

        Map<String, Attributes> entries = _manifest.getEntries();

        for (Map.Entry<String, Attributes> entry : entries.entrySet()) {
          String pkg = entry.getKey();

          attr = entry.getValue();
          if (attr == null) continue;

          addManifestPackage(pkg, attr);
        }
      } catch (IOException e) {
        log.log(Level.WARNING, e.toString(), e);
      } finally {
        _isManifestRead = true;
      }
    }
  }
Example #6
0
  @Override
  public String getVersion() {
    Class<BricketApplication> clazz = BricketApplication.class;
    String classPath = clazz.getResource(clazz.getSimpleName() + ".class").toString();
    if (!classPath.startsWith("jar")) {
      // class not from JAR
      return UNKNOWN_VERSION;
    }

    try {
      String manifestPath =
          classPath.substring(0, classPath.lastIndexOf("!") + 1) + "/META-INF/MANIFEST.MF";
      Manifest manifest = new Manifest(new URL(manifestPath).openStream());
      Attributes attr = manifest.getMainAttributes();
      String version = attr.getValue(Name.IMPLEMENTATION_VERSION);
      return version != null ? version : UNKNOWN_VERSION;
    } catch (MalformedURLException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    return UNKNOWN_VERSION;
  }
Example #7
0
 static {
   final Enumeration<URL> resources;
   String jarName = "(unknown)";
   String versionString = "(unknown)";
   try {
     final ClassLoader classLoader = Main.class.getClassLoader();
     resources =
         classLoader == null
             ? ModuleClassLoader.getSystemResources("META-INF/MANIFEST.MF")
             : classLoader.getResources("META-INF/MANIFEST.MF");
     while (resources.hasMoreElements()) {
       final URL url = resources.nextElement();
       try {
         final InputStream stream = url.openStream();
         if (stream != null)
           try {
             final Manifest manifest = new Manifest(stream);
             final Attributes mainAttributes = manifest.getMainAttributes();
             if (mainAttributes != null
                 && "JBoss Modules".equals(mainAttributes.getValue("Specification-Title"))) {
               jarName = mainAttributes.getValue("Jar-Name");
               versionString = mainAttributes.getValue("Jar-Version");
             }
           } finally {
             StreamUtil.safeClose(stream);
           }
       } catch (IOException ignored) {
       }
     }
   } catch (IOException ignored) {
   }
   JAR_NAME = jarName;
   VERSION_STRING = versionString;
 }
  private String getConfigInfoFromManifest(String configType, IPath portalDir) {
    File implJar = portalDir.append("/WEB-INF/lib/portal-impl.jar").toFile();

    String version = null;
    String serverInfo = null;

    if (implJar.exists()) {
      try (JarFile jar = new JarFile(implJar)) {
        Manifest manifest = jar.getManifest();

        Attributes attributes = manifest.getMainAttributes();

        version = attributes.getValue("Liferay-Portal-Version");
        serverInfo = attributes.getValue("Liferay-Portal-Server-Info");

        if (CoreUtil.compareVersions(Version.parseVersion(version), MANIFEST_VERSION_REQUIRED)
            < 0) {
          version = null;
          serverInfo = null;
        }
      } catch (IOException e) {
        LiferayServerCore.logError(e);
      }
    }

    if (configType.equals(CONFIG_TYPE_VERSION)) {
      return version;
    }

    if (configType.equals(CONFIG_TYPE_SERVER)) {
      return serverInfo;
    }

    return null;
  }
Example #9
0
  public void test_1562() throws Exception {
    Manifest man = new Manifest();
    Attributes att = man.getMainAttributes();
    att.put(Attributes.Name.MANIFEST_VERSION, "1.0");
    att.put(Attributes.Name.MAIN_CLASS, "foo.bar.execjartest.Foo");

    File outputZip = File.createTempFile("hyts_", ".zip");
    outputZip.deleteOnExit();
    ZipOutputStream zout = new ZipOutputStream(new FileOutputStream(outputZip));
    File resources = Support_Resources.createTempFolder();

    for (String zipClass : new String[] {"Foo", "Bar"}) {
      zout.putNextEntry(new ZipEntry("foo/bar/execjartest/" + zipClass + ".class"));
      zout.write(getResource(resources, "hyts_" + zipClass + ".ser"));
    }

    zout.putNextEntry(new ZipEntry("META-INF/MANIFEST.MF"));
    man.write(zout);
    zout.close();

    // set up the VM parameters
    String[] args = new String[] {"-jar", outputZip.getAbsolutePath()};

    // execute the JAR and read the result
    String res = Support_Exec.execJava(args, null, false);

    assertTrue("Error executing ZIP : result returned was incorrect.", res.startsWith("FOOBAR"));
  }
Example #10
0
  /**
   * tests case when Main-Class is not in the zip launched but in another zip referenced by
   * Class-Path
   *
   * @throws Exception in case of troubles
   */
  public void test_main_class_in_another_zip() throws Exception {
    File fooZip = File.createTempFile("hyts_", ".zip");
    File barZip = File.createTempFile("hyts_", ".zip");
    fooZip.deleteOnExit();
    barZip.deleteOnExit();

    // create the manifest
    Manifest man = new Manifest();
    Attributes att = man.getMainAttributes();
    att.put(Attributes.Name.MANIFEST_VERSION, "1.0");
    att.put(Attributes.Name.MAIN_CLASS, "foo.bar.execjartest.Foo");
    att.put(Attributes.Name.CLASS_PATH, fooZip.getName());

    File resources = Support_Resources.createTempFolder();

    ZipOutputStream zoutFoo = new ZipOutputStream(new FileOutputStream(fooZip));
    zoutFoo.putNextEntry(new ZipEntry("foo/bar/execjartest/Foo.class"));
    zoutFoo.write(getResource(resources, "hyts_Foo.ser"));
    zoutFoo.close();

    ZipOutputStream zoutBar = new ZipOutputStream(new FileOutputStream(barZip));
    zoutBar.putNextEntry(new ZipEntry("META-INF/MANIFEST.MF"));
    man.write(zoutBar);

    zoutBar.putNextEntry(new ZipEntry("foo/bar/execjartest/Bar.class"));
    zoutBar.write(getResource(resources, "hyts_Bar.ser"));
    zoutBar.close();

    String[] args = new String[] {"-jar", barZip.getAbsolutePath()};

    // execute the JAR and read the result
    String res = Support_Exec.execJava(args, null, false);

    assertTrue("Error executing JAR : result returned was incorrect.", res.startsWith("FOOBAR"));
  }
Example #11
0
  public static Manifest s_create(
      String strSpecVend,
      String strSpecVers,
      String strImplVend,
      String strImplVers,
      String strImplVendId) {

    // create the manifest object
    Manifest man = S_Manifest.s_create();

    Attributes attAttributes = man.getMainAttributes();

    if (strSpecVend != null) attAttributes.putValue(S_Manifest.f_s_strKeySpecVend, strSpecVend);

    if (strSpecVers != null) attAttributes.putValue(S_Manifest.f_s_strKeySpecVers, strSpecVers);

    if (strImplVend != null) attAttributes.putValue(S_Manifest.f_s_strKeyImplVend, strImplVend);

    if (strImplVers != null) attAttributes.putValue(S_Manifest.f_s_strKeyImplVers, strImplVers);

    if (strImplVendId != null)
      attAttributes.putValue(S_Manifest.f_s_strKeyImplVendId, strImplVendId);

    return man;
  }
 // TODO: includeRuntime should be not a flag but a path to runtime
 public static void writeToJar(
     ClassFileFactory factory,
     final OutputStream fos,
     @Nullable FqName mainClass,
     boolean includeRuntime) {
   try {
     Manifest manifest = new Manifest();
     final Attributes mainAttributes = manifest.getMainAttributes();
     mainAttributes.putValue("Manifest-Version", "1.0");
     mainAttributes.putValue("Created-By", "JetBrains Kotlin");
     if (mainClass != null) {
       mainAttributes.putValue("Main-Class", mainClass.getFqName());
     }
     JarOutputStream stream = new JarOutputStream(fos, manifest);
     for (String file : factory.files()) {
       stream.putNextEntry(new JarEntry(file));
       stream.write(factory.asBytes(file));
     }
     if (includeRuntime) {
       writeRuntimeToJar(stream);
     }
     stream.finish();
   } catch (IOException e) {
     throw new CompileEnvironmentException("Failed to generate jar file", e);
   }
 }
  public static void main(String[] args) {
    // Get JAR file
    JarFile jar = ExecJarName.getJar(args[0]);

    // Look for manifest
    Manifest manifest = null;
    try {
      manifest = jar.getManifest();
      if (manifest == null) {
        System.err.println("No manifest found in ``" + args[0] + "''");
        System.exit(1);
      }
    } catch (IOException e) {
      System.err.println("Can't access manifest in ``" + args[0] + "'': " + e);
      System.exit(1);
    }

    // Get "Main-Class" attribute
    String mainClass = manifest.getMainAttributes().getValue(Attributes.Name.MAIN_CLASS);
    if (mainClass == null) {
      System.err.println("No ``Main-Class'' found in manifest");
      System.exit(1);
    }

    // Now call ExecJarName's main()
    String[] newArgs = new String[args.length + 1];
    System.arraycopy(args, 1, newArgs, 2, args.length - 1);
    newArgs[0] = args[0];
    newArgs[1] = mainClass.replace('/', '.');
    ExecJarName.main(newArgs);
  }
Example #14
0
 /**
  * Returns the manifest of the jar which contains one of the specified extensions. The provided
  * ClassLoader is used for resource loading.
  *
  * @param cl A ClassLoader which should find the manifest.
  * @param extensions The values of many 'Extension-Name's jar-manifest attribute; used to identify
  *     the manifest. Matching is applied in decreasing order, i.e. first element is favored over
  *     the second, etc.
  * @return the requested manifest or null when not found.
  */
 public static Manifest getManifest(ClassLoader cl, String[] extensions) {
   final Manifest[] extManifests = new Manifest[extensions.length];
   try {
     Enumeration<URL> resources = cl.getResources("META-INF/MANIFEST.MF");
     while (resources.hasMoreElements()) {
       final InputStream is = resources.nextElement().openStream();
       final Manifest manifest;
       try {
         manifest = new Manifest(is);
       } finally {
         IOUtil.close(is, false);
       }
       Attributes attributes = manifest.getMainAttributes();
       if (attributes != null) {
         for (int i = 0; i < extensions.length && null == extManifests[i]; i++) {
           final String extension = extensions[i];
           if (extension.equals(attributes.getValue(Attributes.Name.EXTENSION_NAME))) {
             if (0 == i) {
               return manifest; // 1st one has highest prio - done
             }
             extManifests[i] = manifest;
           }
         }
       }
     }
   } catch (IOException ex) {
     throw new RuntimeException("Unable to read manifest.", ex);
   }
   for (int i = 1; i < extManifests.length; i++) {
     if (null != extManifests[i]) {
       return extManifests[i];
     }
   }
   return null;
 }
  public void execute() throws MojoExecutionException {
    try {
      File out = new File(project.getBasedir(), jars);
      for (Iterator i = getIncludedArtifacts().iterator(); i.hasNext(); ) {
        Artifact a = (Artifact) i.next();
        FileUtils.copyFileToDirectory(a.getFile(), out);
      }

      if (packageSources) {
        packageSources(getIncludedArtifacts());
      }

      Manifest manifest = getManifest();
      File metaInf = new File(project.getBasedir(), "META-INF");
      metaInf.mkdirs();
      BufferedOutputStream os =
          new BufferedOutputStream(new FileOutputStream(new File(metaInf, "MANIFEST.MF")));
      manifest.write(os);
      os.close();

      //			packageBundle();
    } catch (Exception e) {
      throw new MojoExecutionException(e.getMessage(), e);
    }
  }
  // assuming that application was packaged according to the rules
  // we must have application jar, i.e. jar where we embed launcher
  // and have main application class listed as main class!
  // If there are more than one, or none - it will be treated as deployment error
  //
  // Note we look for both JavaFX executable jars and regular executable jars
  // As long as main "application" entry point is the same it is main class
  // (i.e. for FX jar we will use JavaFX manifest entry ...)
  public String getMainApplicationJar() {
    if (mainJar != null) {
      return mainJar;
    }

    if (appResources == null || applicationClass == null) {
      return null;
    }
    File srcdir = appResources.getBaseDirectory();
    for (String fname : appResources.getIncludedFiles()) {
      JarFile jf;
      try {
        jf = new JarFile(new File(srcdir, fname));
        Manifest m = jf.getManifest();
        Attributes attrs = (m != null) ? m.getMainAttributes() : null;
        if (attrs != null) {
          boolean javaMain = applicationClass.equals(attrs.getValue(Attributes.Name.MAIN_CLASS));
          boolean fxMain =
              applicationClass.equals(attrs.getValue(PackagerLib.MANIFEST_JAVAFX_MAIN));
          if (javaMain || fxMain) {
            useFXPackaging = fxMain;
            mainJar = fname;
            mainJarClassPath = attrs.getValue(Attributes.Name.CLASS_PATH);
            return mainJar;
          }
        }
      } catch (IOException ex) {
      }
    }
    return null;
  }
Example #17
0
  protected static String getClassJarVersion(Class<?> clazz) {
    StringBuilder output = new StringBuilder();

    String path = clazz.getResource(clazz.getSimpleName() + ".class").toString();
    LOGGER.debug("Output: {}, path: {}", output, path);
    boolean unknown = true;
    if (path.startsWith("jar")) {
      String manifestPath = path.replaceFirst("\\!.*", "!/META-INF/MANIFEST.MF");
      try {
        LOGGER.debug("manifestPath: {}", manifestPath);
        Manifest manifest = new Manifest(new URL(manifestPath).openStream());
        LOGGER.debug("manifest main attributes: {}", manifest.getMainAttributes().toString());

        String value = manifest.getMainAttributes().getValue(IMPL_VER);
        if (value != null) {
          output.append(value);
          unknown = false;
        }

        if (LOGGER.isDebugEnabled()) {
          for (Entry<Object, Object> entry : manifest.getMainAttributes().entrySet()) {
            LOGGER.debug("entry = {} value = {}", entry.getKey(), entry.getValue());
          }
        }

      } catch (Exception e) {
        LOGGER.debug("Error Loading Manifest", e);
      }
    }
    if (unknown) {
      output.append("unknown");
    }
    return output.toString();
  }
Example #18
0
  /** Generate output JAR-file and packages */
  public void outputToJar() throws IOException {
    // create the manifest
    final Manifest manifest = new Manifest();
    final java.util.jar.Attributes atrs = manifest.getMainAttributes();
    atrs.put(java.util.jar.Attributes.Name.MANIFEST_VERSION, "1.2");

    final Map map = manifest.getEntries();
    // create manifest
    Enumeration classes = _bcelClasses.elements();
    final String now = (new Date()).toString();
    final java.util.jar.Attributes.Name dateAttr = new java.util.jar.Attributes.Name("Date");
    while (classes.hasMoreElements()) {
      final JavaClass clazz = (JavaClass) classes.nextElement();
      final String className = clazz.getClassName().replace('.', '/');
      final java.util.jar.Attributes attr = new java.util.jar.Attributes();
      attr.put(dateAttr, now);
      map.put(className + ".class", attr);
    }

    final File jarFile = new File(_destDir, _jarFileName);
    final JarOutputStream jos = new JarOutputStream(new FileOutputStream(jarFile), manifest);
    classes = _bcelClasses.elements();
    while (classes.hasMoreElements()) {
      final JavaClass clazz = (JavaClass) classes.nextElement();
      final String className = clazz.getClassName().replace('.', '/');
      jos.putNextEntry(new JarEntry(className + ".class"));
      final ByteArrayOutputStream out = new ByteArrayOutputStream(2048);
      clazz.dump(out); // dump() closes it's output stream
      out.writeTo(jos);
    }
    jos.close();
  }
Example #19
0
  /** Write the signature file to the given output stream. */
  private void generateSignatureFile(Manifest manifest, OutputStream out)
      throws IOException, GeneralSecurityException {
    out.write(("Signature-Version: 1.0\r\n").getBytes());
    out.write(("Created-By: 1.0 (Android SignApk)\r\n").getBytes());

    // BASE64Encoder base64 = new BASE64Encoder();
    MessageDigest md = MessageDigest.getInstance("SHA1");
    PrintStream print =
        new PrintStream(new DigestOutputStream(new ByteArrayOutputStream(), md), true, "UTF-8");

    // Digest of the entire manifest
    manifest.write(print);
    print.flush();

    out.write(("SHA1-Digest-Manifest: " + Base64.encode(md.digest()) + "\r\n\r\n").getBytes());

    Map<String, Attributes> entries = manifest.getEntries();
    for (Map.Entry<String, Attributes> entry : entries.entrySet()) {
      if (canceled) break;
      progressHelper.progress(ProgressEvent.PRORITY_NORMAL, "Generating signature file");
      // Digest of the manifest stanza for this entry.
      String nameEntry = "Name: " + entry.getKey() + "\r\n";
      print.print(nameEntry);
      for (Map.Entry<Object, Object> att : entry.getValue().entrySet()) {
        print.print(att.getKey() + ": " + att.getValue() + "\r\n");
      }
      print.print("\r\n");
      print.flush();

      out.write(nameEntry.getBytes());
      out.write(("SHA1-Digest: " + Base64.encode(md.digest()) + "\r\n\r\n").getBytes());
    }
  }
	public static String findVersion(InputStream manifestIn) {
		// runnnable war
		try {
			Enumeration<URL> manifests = ApplicationHelper.class
					.getClassLoader().getResources("META-INF/MANIFEST.MF");
			while (manifests.hasMoreElements()) {
				URL res = manifests.nextElement();
				Manifest manifest = new Manifest(res.openStream());
				String versionManifest = manifest.getMainAttributes().getValue(
						MANIFEST_VERSION_KEY);
				if (versionManifest != null) {
					return versionManifest;
				}
			}
		} catch (IOException e) {
		}

		// tomcat like
		try {
			Manifest manifest = new Manifest(manifestIn);
			String versionManifest = manifest.getMainAttributes().getValue(
					MANIFEST_VERSION_KEY);
			if (versionManifest != null) {
				return versionManifest;
			}
		} catch (IOException e) {
		}
		return "Unknow Version";
	}
Example #21
0
  // {{{ definePackage(packageName, manifest) method
  private void definePackage(String name, Manifest mf) {
    if (mf == null) {
      definePackage(name, null, null, null, null, null, null, null);
      return;
    }

    Attributes sa = mf.getAttributes(name.replace('.', '/') + '/');
    Attributes ma = mf.getMainAttributes();

    URL sealBase = null;
    if (Boolean.valueOf(getMfValue(sa, ma, Name.SEALED)).booleanValue()) {
      try {
        sealBase = jar.getFile().toURL();
      } catch (MalformedURLException e) {
      }
    }

    Package pkg =
        definePackage(
            name,
            getMfValue(sa, ma, Name.SPECIFICATION_TITLE),
            getMfValue(sa, ma, Name.SPECIFICATION_VERSION),
            getMfValue(sa, ma, Name.SPECIFICATION_VENDOR),
            getMfValue(sa, ma, Name.IMPLEMENTATION_TITLE),
            getMfValue(sa, ma, Name.IMPLEMENTATION_VERSION),
            getMfValue(sa, ma, Name.IMPLEMENTATION_VENDOR),
            sealBase);
  } // }}}
  private void generateLauncherJar(ProjectLauncher launcher, File folder, MultiStatus status) {
    Jar launcherJar = new Jar("launch");

    // Merge in the classpath JARs
    Collection<String> classpath = launcher.getClasspath();
    for (String classpathEntry : classpath) {
      try {
        Jar classpathJar = new Jar(new File(classpathEntry));
        launcherJar.addAll(classpathJar);
      } catch (IOException e) {
        status.add(
            new Status(
                IStatus.ERROR,
                Plugin.PLUGIN_ID,
                0,
                String.format("Failed to add classpath JAR '%s'.", classpathEntry),
                e));
      }
    }

    // Set the Main-Class
    Manifest manifest = new Manifest();
    manifest.getMainAttributes().putValue("Main-Class", "launch");
    launcherJar.setManifest(manifest);
    launcherJar.putResource(
        "launch.class",
        new URLResource(ExecutableJarExportWizard.class.getResource("launch.clazz")));

    try {
      launcherJar.write(new File(folder, "launch.jar"));
    } catch (Exception e) {
      status.add(new Status(IStatus.ERROR, Plugin.PLUGIN_ID, 0, "Error generating launch JAR.", e));
    }
  }
Example #23
0
 public void start() {
   vlog.debug("start called");
   if (version == null || build == null) {
     ClassLoader cl = this.getClass().getClassLoader();
     InputStream stream = cl.getResourceAsStream("com/tigervnc/vncviewer/timestamp");
     try {
       Manifest manifest = new Manifest(stream);
       Attributes attributes = manifest.getMainAttributes();
       version = attributes.getValue("Version");
       build = attributes.getValue("Build");
     } catch (java.io.IOException e) {
     }
   }
   nViewers++;
   if (firstApplet) {
     alwaysShowServerDialog.setParam(true);
     Configuration.readAppletParams(this);
     String host = getCodeBase().getHost();
     if (vncServerName.getValue() == null && vncServerPort.getValue() != 0) {
       int port = vncServerPort.getValue();
       vncServerName.setParam(
           host + ((port >= 5900 && port <= 5999) ? (":" + (port - 5900)) : ("::" + port)));
     }
   }
   thread = new Thread(this);
   thread.start();
 }
Example #24
0
 public boolean canHandle(File artifact) {
   JarFile jar = null;
   try {
     // Handle OSGi bundles with the default deployer
     String name = artifact.getName();
     if (!artifact.canRead()
         || name.endsWith(".txt")
         || name.endsWith(".xml")
         || name.endsWith(".properties")
         || name.endsWith(".cfg")) {
       // that's file type which is not supported as bundle and avoid
       // exception in the log
       return false;
     }
     jar = new JarFile(artifact);
     Manifest m = jar.getManifest();
     if (m != null
         && m.getMainAttributes().getValue(new Attributes.Name("Bundle-SymbolicName")) != null) {
       return true;
     }
   } catch (Exception e) {
     // Ignore
   } finally {
     if (jar != null) {
       try {
         jar.close();
       } catch (IOException e) {
         // Ignore
       }
     }
   }
   return false;
 }
Example #25
0
  /**
   * Gets the build teimstamp from the jar manifest
   *
   * @return build timestamp
   */
  private static String getManifestBuildTimestamp() {
    JarURLConnection connection = null;
    JarFile jarFile = null;
    URL url = Commons.class.getClassLoader().getResource("jaligner");
    try {
      // Get jar connection
      connection = (JarURLConnection) url.openConnection();

      // Get the jar file
      jarFile = connection.getJarFile();

      // Get the manifest
      Manifest manifest = jarFile.getManifest();

      // Get the manifest entries
      Attributes attributes = manifest.getMainAttributes();

      Attributes.Name name = new Attributes.Name(BUILD_TIMESTAMP);
      return attributes.getValue(name);
    } catch (Exception e) {
      String message = "Failed getting the current release info: " + e.getMessage();
      logger.log(Level.WARNING, message);
    }
    return null;
  }
Example #26
0
  private Set<Resource> addProjectBuildBundles(Resolver resolver) {
    if (!Project.BNDFILE.equals(runFile.getName())) return Collections.emptySet();

    Set<Resource> result = new HashSet<Resource>();
    try {

      Project model = Workspace.getProject(runFile.getProject().getLocation().toFile());
      for (Builder builder : model.getSubBuilders()) {
        File file = new File(model.getTarget(), builder.getBsn() + ".jar");
        if (file.isFile()) {
          JarInputStream stream = null;
          try {
            stream = new JarInputStream(new FileInputStream(file));
            Manifest manifest = stream.getManifest();

            Resource resource = helper.createResource(manifest.getMainAttributes());
            result.add(resource);
            resolver.add(resource);
          } catch (IOException e) {
            Plugin.logError("Error reading project bundle " + file, e);
          } finally {
            if (stream != null) stream.close();
          }
        }
      }
    } catch (Exception e) {
      Plugin.logError("Error getting builders for project: " + runFile.getProject(), e);
    }
    return result;
  }
  @Override
  public ContainerBundleAnalyzer analyze(File bundle) {
    packageExports = null;
    Analyzer analyzer = new Analyzer();
    Jar jar = null;
    try {
      jar = new Jar(bundle);
      Manifest manifest = jar.getManifest();
      String exportHeader = manifest.getMainAttributes().getValue(Constants.EXPORT_PACKAGE);
      if (exportHeader != null) {
        Map<String, Map<String, String>> exported = analyzer.parseHeader(exportHeader);

        packageExports = exported.keySet();
      } else {
        packageExports = new HashSet<>();
      }
    } catch (Exception e) {
      throw new SmartSpacesException(
          String.format("Could not analyze bundle %s", bundle.getAbsolutePath()), e);
    } finally {
      fileSupport.close(analyzer, false);
      fileSupport.close(jar, false);
    }

    return this;
  }
Example #28
0
  /** Check if the getSubBuilders properly predicts the output. */
  public static void testSubBuilders() throws Exception {
    Workspace ws = Workspace.getWorkspace(new File("test/ws"));
    Project project = ws.getProject("p4-sub");

    Collection<? extends Builder> bs = project.getSubBuilders();
    assertNotNull(bs);
    assertEquals(3, bs.size());
    Set<String> names = new HashSet<String>();
    for (Builder b : bs) {
      names.add(b.getBsn());
    }
    assertTrue(names.contains("p4-sub.a"));
    assertTrue(names.contains("p4-sub.b"));
    assertTrue(names.contains("p4-sub.c"));

    File[] files = project.build();
    assertTrue(project.check());

    System.err.println(Processor.join(project.getErrors(), "\n"));
    System.err.println(Processor.join(project.getWarnings(), "\n"));
    assertEquals(0, project.getErrors().size());
    assertEquals(0, project.getWarnings().size());
    assertNotNull(files);
    assertEquals(3, files.length);
    for (File file : files) {
      Jar jar = new Jar(file);
      Manifest m = jar.getManifest();
      assertTrue(names.contains(m.getMainAttributes().getValue("Bundle-SymbolicName")));
    }
  }
  public static void indexTargetPlatform(
      OutputStream outputStream,
      List<File> additionalJarFiles,
      long stopWaitTimeout,
      String... dirNames)
      throws Exception {

    Framework framework = null;

    Path tempPath = Files.createTempDirectory(null);

    ClassLoader classLoader = TargetPlatformIndexerUtil.class.getClassLoader();

    try (InputStream inputStream =
        classLoader.getResourceAsStream("META-INF/system.packages.extra.mf")) {

      Map<String, String> properties = new HashMap<>();

      properties.put(Constants.FRAMEWORK_STORAGE, tempPath.toString());

      Manifest extraPackagesManifest = new Manifest(inputStream);

      Attributes attributes = extraPackagesManifest.getMainAttributes();

      properties.put(
          Constants.FRAMEWORK_SYSTEMPACKAGES_EXTRA, attributes.getValue("Export-Package"));

      ServiceLoader<FrameworkFactory> serviceLoader = ServiceLoader.load(FrameworkFactory.class);

      FrameworkFactory frameworkFactory = serviceLoader.iterator().next();

      framework = frameworkFactory.newFramework(properties);

      framework.init();

      BundleContext bundleContext = framework.getBundleContext();

      Bundle systemBundle = bundleContext.getBundle(0);

      TargetPlatformIndexer targetPlatformIndexer =
          new TargetPlatformIndexer(systemBundle, additionalJarFiles, dirNames);

      targetPlatformIndexer.index(outputStream);
    } finally {
      framework.stop();

      FrameworkEvent frameworkEvent = framework.waitForStop(stopWaitTimeout);

      if (frameworkEvent.getType() == FrameworkEvent.WAIT_TIMEDOUT) {
        throw new Exception(
            "OSGi framework event "
                + frameworkEvent
                + " triggered after a "
                + stopWaitTimeout
                + "ms timeout");
      }

      PathUtil.deltree(tempPath);
    }
  }
Example #30
0
  /**
   * Display package name and version information for javax.mail.internet.
   *
   * <p>This example is a bit artificial, since examining the version of a jar from Sun Microsystems
   * is unusual.
   *
   * @return _more_
   * @throws IOException _more_
   */
  private static HashMap<String, String> getBuildInfo() throws IOException {
    GribVariableRenamer renamer = new GribVariableRenamer();
    HashMap<String, String> buildInfo = new HashMap<String, String>();

    Enumeration<URL> resources =
        renamer.getClass().getClassLoader().getResources("META-INF/MANIFEST.MF");
    while (resources.hasMoreElements()) {
      try {
        Manifest manifest = new Manifest(resources.nextElement().openStream());
        Attributes attrs = manifest.getMainAttributes();
        if (attrs != null) {
          String implTitle = attrs.getValue("Implementation-Title");
          if ((implTitle != null) && (implTitle.contains("ncIdv"))) {
            buildInfo.put("version", attrs.getValue("Implementation-Version"));
            String strDate = attrs.getValue("Built-On");

            CalendarDate cd = CalendarDate.parseISOformat(null, strDate);
            buildInfo.put("buildDate", cd.toString());

            break;
          }
        }
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    return buildInfo;
  }