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";
	}
Пример #2
0
  /** Add the SHA1 of every file to the manifest, creating it if necessary. */
  private Manifest addDigestsToManifest(Map<String, ZioEntry> entries)
      throws IOException, GeneralSecurityException {
    Manifest input = null;
    ZioEntry manifestEntry = entries.get(JarFile.MANIFEST_NAME);
    if (manifestEntry != null) {
      input = new Manifest();
      input.read(manifestEntry.getInputStream());
    }
    Manifest output = new Manifest();
    Attributes main = output.getMainAttributes();
    if (input != null) {
      main.putAll(input.getMainAttributes());
    } else {
      main.putValue("Manifest-Version", "1.0");
      main.putValue("Created-By", "1.0 (Android SignApk)");
    }

    // BASE64Encoder base64 = new BASE64Encoder();
    MessageDigest md = MessageDigest.getInstance("SHA1");
    byte[] buffer = new byte[512];
    int num;

    // We sort the input entries by name, and add them to the
    // output manifest in sorted order.  We expect that the output
    // map will be deterministic.

    TreeMap<String, ZioEntry> byName = new TreeMap<String, ZioEntry>();
    byName.putAll(entries);

    boolean debug = getLogger().isDebugEnabled();
    if (debug) getLogger().debug("Manifest entries:");
    for (ZioEntry entry : byName.values()) {
      if (canceled) break;
      String name = entry.getName();
      if (debug) getLogger().debug(name);
      if (!entry.isDirectory()
          && !name.equals(JarFile.MANIFEST_NAME)
          && !name.equals(CERT_SF_NAME)
          && !name.equals(CERT_RSA_NAME)
          && (stripPattern == null || !stripPattern.matcher(name).matches())) {

        progressHelper.progress(ProgressEvent.PRORITY_NORMAL, "Generating manifest");
        InputStream data = entry.getInputStream();
        while ((num = data.read(buffer)) > 0) {
          md.update(buffer, 0, num);
        }

        Attributes attr = null;
        if (input != null) {
          java.util.jar.Attributes inAttr = input.getAttributes(name);
          if (inAttr != null) attr = new Attributes(inAttr);
        }
        if (attr == null) attr = new Attributes();
        attr.putValue("SHA1-Digest", Base64.encode(md.digest()));
        output.getEntries().put(name, attr);
      }
    }

    return output;
  }
Пример #3
0
  /**
   * Create the new manifest from the existing jar file and the new entries
   *
   * @param jar
   * @param manifestentries
   * @return Manifest
   * @throws MojoExecutionException
   */
  protected Manifest createManifest(File jar, Map<String, String> manifestentries)
      throws MojoExecutionException {
    JarFile jarFile = null;
    try {
      jarFile = new JarFile(jar);

      // read manifest from jar
      Manifest manifest = jarFile.getManifest();

      if (manifest == null || manifest.getMainAttributes().isEmpty()) {
        manifest = new Manifest();
        manifest.getMainAttributes().putValue(Name.MANIFEST_VERSION.toString(), "1.0");
      }

      // add or overwrite entries
      Set<Entry<String, String>> entrySet = manifestentries.entrySet();
      for (Entry<String, String> entry : entrySet) {
        manifest.getMainAttributes().putValue(entry.getKey(), entry.getValue());
      }

      return manifest;
    } catch (IOException e) {
      throw new MojoExecutionException(
          "Error while reading manifest from " + jar.getAbsolutePath(), e);
    } finally {
      ioUtil.close(jarFile);
    }
  }
Пример #4
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;
  }
Пример #5
0
  public static void transform(URL url, OutputStream os) throws Exception {
    // Build dom document
    Document doc = parse(url);
    // Heuristicly retrieve name and version
    String name = getPath(url);
    int idx = name.lastIndexOf('/');
    if (idx >= 0) {
      name = name.substring(idx + 1);
    }
    String[] str = DeployerUtils.extractNameVersionType(name);
    // Create manifest
    Manifest m = new Manifest();
    m.getMainAttributes().putValue("Manifest-Version", "2");
    m.getMainAttributes().putValue(Constants.BUNDLE_MANIFESTVERSION, "2");
    m.getMainAttributes().putValue(Constants.BUNDLE_SYMBOLICNAME, str[0]);
    m.getMainAttributes().putValue(Constants.BUNDLE_VERSION, str[1]);
    String importPkgs = getImportPackages(analyze(new DOMSource(doc)));
    if (importPkgs != null && importPkgs.length() > 0) {
      m.getMainAttributes().putValue(Constants.IMPORT_PACKAGE, importPkgs);
    }
    m.getMainAttributes().putValue(Constants.DYNAMICIMPORT_PACKAGE, "*");
    // Extract manifest entries from the DOM
    NodeList l = doc.getElementsByTagName("manifest");
    if (l != null) {
      for (int i = 0; i < l.getLength(); i++) {
        Element e = (Element) l.item(i);
        String text = e.getTextContent();
        Properties props = new Properties();
        props.load(new ByteArrayInputStream(text.trim().getBytes()));
        Enumeration en = props.propertyNames();
        while (en.hasMoreElements()) {
          String k = (String) en.nextElement();
          String v = props.getProperty(k);
          m.getMainAttributes().putValue(k, v);
        }
        e.getParentNode().removeChild(e);
      }
    }

    JarOutputStream out = new JarOutputStream(os);
    ZipEntry e = new ZipEntry(JarFile.MANIFEST_NAME);
    out.putNextEntry(e);
    m.write(out);
    out.closeEntry();
    e = new ZipEntry("OSGI-INF/");
    out.putNextEntry(e);
    e = new ZipEntry("OSGI-INF/blueprint/");
    out.putNextEntry(e);
    out.closeEntry();
    // check .xml file extension
    if (!name.endsWith(".xml")) {
      name += ".xml";
    }
    e = new ZipEntry("OSGI-INF/blueprint/" + name);
    out.putNextEntry(e);
    // Copy the new DOM
    XmlUtils.transform(new DOMSource(doc), new StreamResult(out));
    out.closeEntry();
    out.close();
  }
Пример #6
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();
  }
Пример #7
0
  static EngineVersionInfo fromManifest(Manifest pManifest) {
    String lVersion =
        XFUtil.nvl(pManifest.getMainAttributes().getValue("FOX-Version"), UNSPECIFIED);
    String lBuildTag = XFUtil.nvl(pManifest.getMainAttributes().getValue("Build-Tag"), UNSPECIFIED);
    String lTime = XFUtil.nvl(pManifest.getMainAttributes().getValue("Build-Time"), UNSPECIFIED);

    return new EngineVersionInfo(lVersion, lBuildTag, lTime);
  }
Пример #8
0
  /** Returns the version number of this plugin */
  @Exported
  public String getVersion() {
    String v = manifest.getMainAttributes().getValue("Plugin-Version");
    if (v != null) return v;

    // plugins generated before maven-hpi-plugin 1.3 should still have this attribute
    v = manifest.getMainAttributes().getValue("Implementation-Version");
    if (v != null) return v;

    return "???";
  }
 @NotNull
 public static ManifestFileConfiguration createManifestFileConfiguration(
     @NotNull VirtualFile manifestFile) {
   final String path = manifestFile.getPath();
   Manifest manifest = readManifest(manifestFile);
   String mainClass = manifest.getMainAttributes().getValue(Attributes.Name.MAIN_CLASS);
   final String classpathText = manifest.getMainAttributes().getValue(Attributes.Name.CLASS_PATH);
   final List<String> classpath = new ArrayList<String>();
   if (classpathText != null) {
     classpath.addAll(StringUtil.split(classpathText, " "));
   }
   return new ManifestFileConfiguration(path, classpath, mainClass, manifestFile.isWritable());
 }
Пример #10
0
  private String computeShortName(Manifest manifest, File archive) {
    // use the name captured in the manifest, as often plugins
    // depend on the specific short name in its URLs.
    String n = manifest.getMainAttributes().getValue("Short-Name");
    if (n != null) return n;

    // maven seems to put this automatically, so good fallback to check.
    n = manifest.getMainAttributes().getValue("Extension-Name");
    if (n != null) return n;

    // otherwise infer from the file name, since older plugins don't have
    // this entry.
    return getBaseName(archive);
  }
Пример #11
0
  private String doRoundTrip(Object versionName) throws Exception {
    Manifest m1 = new Manifest();
    m1.getMainAttributes().put(Attributes.Name.CONTENT_TYPE, "image/pr0n");
    if (versionName != null) {
      m1.getMainAttributes().putValue(versionName.toString(), "1.2.3");
    }
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    m1.write(os);

    ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray());
    Manifest m2 = new Manifest();
    m2.read(is);
    return (String) m2.getMainAttributes().get(Attributes.Name.CONTENT_TYPE);
  }
Пример #12
0
  public void test_clone() throws IOException {
    Manifest emptyManifest = new Manifest();
    Manifest emptyClone = (Manifest) emptyManifest.clone();
    assertTrue("Should have no entries", emptyClone.getEntries().isEmpty());
    assertTrue("Should have no main attributes", emptyClone.getMainAttributes().isEmpty());
    assertEquals(emptyClone, emptyManifest);
    assertEquals(emptyManifest.clone().getClass().getName(), "java.util.jar.Manifest");

    Manifest manifest =
        new Manifest(new URL(Support_Resources.getURL("manifest/hyts_MANIFEST.MF")).openStream());
    Manifest manifestClone = (Manifest) manifest.clone();
    manifestClone.getMainAttributes();
    checkManifest(manifestClone);
  }
Пример #13
0
 private static String getVersionInfo(final String section) {
   try {
     final Enumeration<URL> resources =
         Main.class.getClassLoader().getResources("META-INF/MANIFEST.MF");
     while (resources.hasMoreElements()) {
       final Manifest manifest = new Manifest(resources.nextElement().openStream());
       if ("DSL Platform - Compiler Command-Line Client"
           .equals(manifest.getMainAttributes().getValue("Specification-Title"))) {
         return manifest.getMainAttributes().getValue(section);
       }
     }
   } catch (IOException ignore) {
   }
   return "unknown";
 }
Пример #14
0
  private static Manifest addDigestsToManifest(JarFile jar)
      throws IOException, GeneralSecurityException {
    Manifest input = jar.getManifest();
    Manifest output = new Manifest();
    Attributes main = output.getMainAttributes();
    if (input != null) {
      main.putAll(input.getMainAttributes());
    } else {
      main.putValue("Manifest-Version", "1.0");
      main.putValue("Created-By", "1.0 (KApkSigner)");
    }

    BASE64Encoder base64 = new BASE64Encoder();
    MessageDigest md = MessageDigest.getInstance("SHA1");
    byte[] buffer = new byte[4096];
    int num;

    TreeMap<String, JarEntry> byName = new TreeMap<String, JarEntry>();

    for (Enumeration<JarEntry> e = jar.entries(); e.hasMoreElements(); ) {
      JarEntry entry = e.nextElement();
      byName.put(entry.getName(), entry);
    }

    for (JarEntry entry : byName.values()) {
      String name = entry.getName();
      if (!entry.isDirectory()
          && !name.equals(JarFile.MANIFEST_NAME)
          && !name.equals(Signer.CERT_SF_NAME)
          && !name.equals(Signer.CERT_RSA_NAME)
          && (Signer.stripPattern == null || !Signer.stripPattern.matcher(name).matches())) {
        InputStream data = jar.getInputStream(entry);
        while ((num = data.read(buffer)) > 0) {
          md.update(buffer, 0, num);
        }

        Attributes attr = null;
        if (input != null) {
          attr = input.getAttributes(name);
        }
        attr = attr != null ? new Attributes(attr) : new Attributes();
        attr.putValue("SHA1-Digest", base64.encode(md.digest()));
        output.getEntries().put(name, attr);
      }
    }

    return output;
  }
Пример #15
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;
  }
  /** 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;
      }
    }
  }
Пример #17
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();
 }
Пример #18
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;
  }
Пример #19
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")));
    }
  }
Пример #20
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;
  }
Пример #21
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 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));
    }
  }
Пример #23
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;
 }
  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;
  }
Пример #25
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;
  }
 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;
 }
  @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;
  }
Пример #28
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);
  } // }}}
  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);
    }
  }
Пример #30
0
  private static void writeSignatureFile(Manifest manifest, SignatureOutputStream out)
      throws IOException, GeneralSecurityException {
    Manifest sf = new Manifest();
    Attributes main = sf.getMainAttributes();
    main.putValue("Signature-Version", "1.0");
    main.putValue("Created-By", "1.0 (KApkSigner)");
    BASE64Encoder base64 = new BASE64Encoder();
    MessageDigest md = MessageDigest.getInstance("SHA1");
    PrintStream print =
        new PrintStream(new DigestOutputStream(new ByteArrayOutputStream(), md), true, "UTF-8");
    manifest.write(print);
    print.flush();
    main.putValue("SHA1-Digest-Manifest", base64.encode(md.digest()));
    Map<String, Attributes> entries = manifest.getEntries();
    for (Map.Entry<String, Attributes> entry : entries.entrySet()) {
      // Digest of the manifest stanza for this entry.
      print.print("Name: " + entry.getKey() + "\r\n");
      for (Map.Entry<Object, Object> att : entry.getValue().entrySet()) {
        print.print(att.getKey() + ": " + att.getValue() + "\r\n");
      }
      print.print("\r\n");
      print.flush();

      Attributes sfAttr = new Attributes();
      sfAttr.putValue("SHA1-Digest", base64.encode(md.digest()));
      sf.getEntries().put(entry.getKey(), sfAttr);
    }
    sf.write(out);
    if (out.size() % 1024 == 0) {
      out.write('\r');
      out.write('\n');
    }
  }