Java Code Examples for java.util.jar.Manifest

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project artimate, under directory /artimate-demo/src/main/java/com/jdotsoft/jarloader/.

Source file: JarClassLoader.java

  23 
vote

/** 
 * Returns the name of the jar file main class, or null if no "Main-Class" manifest attributes was defined.
 * @return Main class declared in JAR's manifest.
 */
public String getManifestMainClass(){
  Attributes attr=null;
  if (isLaunchedFromJar()) {
    try {
      Manifest m=lstJarFile.get(0).jarFile.getManifest();
      attr=m.getMainAttributes();
    }
 catch (    IOException e) {
    }
  }
  return (attr == null ? null : attr.getValue(Attributes.Name.MAIN_CLASS));
}
 

Example 2

From project ant4eclipse, under directory /org.ant4eclipse.lib.core.test/src/org/ant4eclipse/lib/core/util/.

Source file: ManifestHelperTest.java

  22 
vote

@Test public void testManifestHelper(){
  Manifest manifest=new Manifest();
  manifest.getMainAttributes().putValue(ManifestHelper.BUNDLE_SYMBOLICNAME,"org.bruni;singleton:=true");
  ManifestHeaderElement[] elements=ManifestHelper.getManifestHeaderElements(manifest,ManifestHelper.BUNDLE_SYMBOLICNAME);
  Assert.assertNotNull(elements);
  Assert.assertEquals(elements.length,1);
  Assert.assertEquals(elements[0].getValues().length,1);
  Assert.assertEquals(elements[0].getValues()[0],"org.bruni");
}
 

Example 3

From project arquillian-container-osgi, under directory /container-common/src/main/java/org/jboss/arquillian/container/osgi/.

Source file: AbstractOSGiApplicationArchiveProcessor.java

  22 
vote

@Override public void process(Archive<?> appArchive,TestClass testClass){
  Manifest manifest=getBundleManifest(appArchive);
  if (manifest == null) {
    manifest=createBundleManifest(appArchive.getName());
  }
  if (manifest != null) {
    enhanceApplicationArchive(appArchive,testClass,manifest);
    assertValidBundleArchive(appArchive);
  }
}
 

Example 4

From project backend-update-center2, under directory /src/test/java/.

Source file: HPIResolver.java

  22 
vote

public void resolveHPI(String groupId,String artifactId,String version) throws Exception {
  System.out.format("Resolving HPI %s:%s:%s\n",groupId,artifactId,version);
  MavenRepositoryImpl mavenRepository=DefaultMavenRepositoryBuilder.createStandardInstance();
  HPI plugin=mavenRepository.findPlugin(groupId,artifactId,version);
  MavenArtifact mavenArtifact=new MavenArtifact(mavenRepository,plugin.artifact);
  Manifest manifest=mavenArtifact.getManifest();
  Attributes mainAttributes=manifest.getMainAttributes();
  List<Attributes.Name> attributeNames=sortAttributes(mainAttributes);
  for (  Object entry : attributeNames) {
    System.out.println(entry + ":" + mainAttributes.get(entry));
  }
}
 

Example 5

From project bundlemaker, under directory /main/org.bundlemaker.core.osgi/src/org/bundlemaker/core/osgi/utils/.

Source file: ManifestUtils.java

  22 
vote

/** 
 * <p> </p>
 * @param manifestContents
 * @return
 */
public static Manifest toManifest(ManifestContents manifestContents){
  Manifest manifest=new Manifest();
  for (  Entry<String,String> entry : manifestContents.getMainAttributes().entrySet()) {
    manifest.getMainAttributes().putValue(entry.getKey(),entry.getValue());
  }
  for (  String sectionName : manifestContents.getSectionNames()) {
    Attributes attributes=new Attributes();
    for (    Entry<String,String> entry : manifestContents.getAttributesForSection(sectionName).entrySet()) {
      attributes.putValue(entry.getKey(),entry.getValue());
    }
    manifest.getEntries().put(sectionName,attributes);
  }
  return manifest;
}
 

Example 6

From project caustic, under directory /applet/src/net/microscraper/client/applet/.

Source file: MicroScraperApplet.java

  22 
vote

public String manifest(String key){
  try {
    String className=MicroScraperApplet.class.getSimpleName() + ".class";
    String classPath=MicroScraperApplet.class.getResource(className).toString();
    String manifestPath=classPath.substring(0,classPath.lastIndexOf("!") + 1) + "/META-INF/MANIFEST.MF";
    Manifest manifest=new Manifest(new URL(manifestPath).openStream());
    Attributes attr=manifest.getMainAttributes();
    return (String)attr.getValue(key);
  }
 catch (  Throwable e) {
    e.printStackTrace();
    return "Error obtaining " + key + " from manifest: "+ e.toString();
  }
}
 

Example 7

From project core_4, under directory /impl/src/main/java/org/richfaces/.

Source file: VersionBean.java

  22 
vote

private void initialize(){
  Manifest manifest=null;
  try {
    manifest=readManifest();
  }
 catch (  Exception e) {
    LOGGER.error(MessageFormat.format("Error reading project metadata: {0}",e.getMessage()),e);
  }
  if (manifest != null) {
    initializePropertiesFromManifest(manifest);
    initializeDerivativeProperties();
  }
}
 

Example 8

From project cxf-dosgi, under directory /systests/common/src/main/java/org/apache/cxf/dosgi/systests/common/.

Source file: AbstractDosgiSystemTest.java

  22 
vote

protected Manifest getManifest(){
  Manifest mf=super.getManifest();
  String importP=mf.getMainAttributes().getValue(Constants.IMPORT_PACKAGE);
  mf.getMainAttributes().putValue(Constants.IMPORT_PACKAGE,importP);
  mf.getMainAttributes().putValue(Constants.DYNAMICIMPORT_PACKAGE,"*");
  return mf;
}
 

Example 9

From project descriptors, under directory /impl-base/src/test/java/org/jboss/shrinkwrap/descriptor/api/.

Source file: ManifestDescriptorTestCase.java

  22 
vote

@Test public void shouldBeAbleToCreateComplexManifest() throws Exception {
  Descriptor manifestDescriptor=Descriptors.create(ManifestDescriptor.class).version("2.0.0.GA-M").createdBy("Creator").implementationTitle("Implementation Title").implementationUrl("http://test.com").implementationVendor("Very Important Vendor (Main)").implementationVendorId("VIV").implementationVersion("1.0.0.GA-VIV-M").addToClassPath("lib1.jar").addToClassPath("lib2.jar").addToClassPath("/f1/f2/f3/lib3").mainClass("test.manifest.MainClass").sealed().signatureVersion("2.0.0.GA-M-SIG").specificationTitle("Specification Title").specificationVendor("Specfication Vendor").specificationVersion("5.0.0.GA-M-SPEC").attribute("CustomAttribute","Whatever").entry("Entry1").contentType("application/xml").notJavaBean().xDigestY("digestAlgorithm1").magic("Magic1").version("2.1.0").createdBy("Creator Entry 1").implementationTitle("Implementation Title Entry 1").implementationUrl("http://entry1.test.com").implementationVendor("Very Important Vendor (Entry 1)").implementationVendorId("VIV-E1").implementationVersion("1.0.0.GA-VIV-E1").addToClassPath("entry1-lib1.jar").addToClassPath("entry1-lib2.jar").addToClassPath("/f1/f2/f3/entry1-lib3.jar").mainClass("test.manifest.Entry1MainClass").notSealed().signatureVersion("2.0.0.GA-E1-SIG").specificationTitle("Specification Title Entry1").specificationVendor("Specfication Vendor Entry1").specificationVersion("5.0.0.GA-E1-SPEC").attribute("CustomAttribute","WhateverEntry1").entry("Entry2").contentType("text/html").javaBean().xDigestY("digestAlgorithm2").magic("Magic2").version("2.1.0").createdBy("Creator Entry 2").implementationTitle("Implementation Title Entry 2").implementationUrl("http://entry2.test.com").implementationVendor("Very Important Vendor (Entry 2)").implementationVendorId("VIV-E2").implementationVersion("1.0.0.GA-VIV-E2").addToClassPath("entry2-lib1.jar").addToClassPath("entry2-lib2.jar").addToClassPath("/f1/f2/f3/entry2-lib3.jar").mainClass("test.manifest.Entry2MainClass").sealed().signatureVersion("2.0.0.GA-E2-SIG").specificationTitle("Specification Title Entry2").specificationVendor("Specfication Vendor Entry2").specificationVersion("5.0.0.GA-E2-SPEC").attribute("CustomAttribute","WhateverEntry2").applet("applet1").appletExtensionName("applet1-Name").appletImplementationUrl("http://applet1.test.com").appletImplementationVersion("2.0.GA-A1").appletImplementationVendorId("VIV-A1").appletSpecificationVersion("2.0.GA-A1-SPEC").applet("applet2").appletExtensionName("applet2-Name").appletImplementationUrl("http://applet2.test.com").appletImplementationVersion("2.0.GA-A2").appletImplementationVendorId("VIV-A2").appletSpecificationVersion("2.0.GA-A2-SPEC");
  Manifest manifest=new Manifest(new ByteArrayInputStream(manifestDescriptor.exportAsString().getBytes()));
  ByteArrayOutputStream stream=new ByteArrayOutputStream();
  manifest.write(stream);
  String expected=stream.toString();
  String actual=manifestDescriptor.exportAsString();
  String[] expectedArray=expected.split("\r\n");
  String[] actualArray=actual.split("\r\n");
  Arrays.sort(expectedArray);
  Arrays.sort(actualArray);
  assertEquals("Corrupted manifest generated,",Arrays.toString(expectedArray),Arrays.toString(actualArray));
}
 

Example 10

From project Eclipse, under directory /com.mobilesorcery.sdk.builder.java/src/com/mobilesorcery/sdk/builder/java/.

Source file: JavaPackager2.java

  22 
vote

private void createManifest(IBuildVariant variant,String appName,String vendorName,IApplicationPermissions permissions,Version version,File manifestFile) throws IOException {
  manifestFile.getParentFile().mkdirs();
  Manifest manifest=getManifest(variant,null,appName,vendorName,permissions,version,false);
  FileOutputStream manifestOutput=new FileOutputStream(manifestFile);
  try {
    manifest.write(manifestOutput);
  }
  finally {
    Util.safeClose(manifestOutput);
  }
}
 

Example 11

From project Gemini-Blueprint, under directory /integration-tests/tests/src/test/java/org/eclipse/gemini/blueprint/iandt/.

Source file: BaseIntegrationTest.java

  22 
vote

protected Manifest getManifest(){
  String permissionPackage="org.osgi.service.permissionadmin";
  Manifest mf=super.getManifest();
  String impPackage=mf.getMainAttributes().getValue(Constants.IMPORT_PACKAGE);
  int startIndex=impPackage.indexOf(permissionPackage);
  String newImpPackage=impPackage;
  if (startIndex >= 0) {
    newImpPackage=impPackage.substring(0,startIndex) + permissionPackage + ";resolution:=optional"+ impPackage.substring(startIndex + permissionPackage.length());
  }
  mf.getMainAttributes().putValue(Constants.IMPORT_PACKAGE,newImpPackage);
  return mf;
}
 

Example 12

From project gemini.web.gemini-web-container, under directory /org.eclipse.gemini.web.core/src/main/java/org/eclipse/gemini/web/internal/url/.

Source file: WebBundleUrlStreamHandlerService.java

  22 
vote

private static Manifest toManifest(Dictionary<String,String> headers){
  Manifest manifest=new Manifest();
  Attributes attributes=manifest.getMainAttributes();
  Enumeration<String> names=headers.keys();
  while (names.hasMoreElements()) {
    String name=names.nextElement();
    String value=headers.get(name);
    attributes.putValue(name,value);
  }
  return manifest;
}
 

Example 13

From project geronimo-xbean, under directory /xbean-bundleutils/src/main/java/org/apache/xbean/osgi/bundle/util/jar/.

Source file: BundleJarFile.java

  22 
vote

public Enumeration entries(){
  Manifest manifest=getManifestSafe();
  Enumeration e=bundle.findEntries("/","*",true);
  LinkedList entries=new LinkedList();
  while (e.hasMoreElements()) {
    URL entryURL=(URL)e.nextElement();
    entries.add(new BundleJarEntry(entryURL.getPath(),entryURL,manifest));
  }
  return Collections.enumeration(entries);
}
 

Example 14

From project jbosgi, under directory /testsuite/performance/src/test/java/org/jboss/osgi/test/performance/bundle/arq/.

Source file: TestBundleProviderImpl.java

  22 
vote

private InputStream getVersionBasedBundle(String prefix,String version) throws IOException, FileNotFoundException {
  File exploded=getRawBundleDir(prefix);
  Manifest mf=new Manifest(new FileInputStream(new File(exploded,"META-INF/MANIFEST.MF")));
  Attributes attrs=mf.getMainAttributes();
  for (  Map.Entry<Object,Object> entry : new HashSet<Map.Entry<Object,Object>>(attrs.entrySet())) {
    String newVal=entry.getValue().toString().replaceAll(BundleTestBase.VERSION_UNDEFINED,version);
    attrs.put(entry.getKey(),newVal);
  }
  return jar(exploded,mf);
}
 

Example 15

From project jbosgi-metadata, under directory /src/main/java/org/jboss/osgi/metadata/.

Source file: ManifestBuilder.java

  22 
vote

@Override public InputStream openStream(){
  Manifest manifest=getManifest();
  ByteArrayOutputStream baos=new ByteArrayOutputStream();
  try {
    manifest.write(baos);
    return new ByteArrayInputStream(baos.toByteArray());
  }
 catch (  IOException ex) {
    throw MESSAGES.illegalStateCannotProvideManifestInputStream(ex);
  }
}
 

Example 16

From project jbosgi-resolver, under directory /felix/src/test/java/org/jboss/test/osgi/resolver/.

Source file: AbstractResolverTest.java

  22 
vote

XResource createResource(Archive<?> archive) throws Exception {
  Node node=archive.get(JarFile.MANIFEST_NAME);
  Manifest manifest=new Manifest(node.getAsset().openStream());
  OSGiMetaData metadata=OSGiMetaDataBuilder.load(manifest);
  return XBundleRevisionBuilderFactory.create().loadFrom(metadata).getResource();
}
 

Example 17

From project jbosgi-spi, under directory /src/main/java/org/jboss/osgi/spi/.

Source file: BundleInfo.java

  22 
vote

/** 
 * Validate manifest from the given virtual file.
 * @param virtualFile The virtualFile that is checked for a valid manifest
 * @return True if the virtualFile conatains a valid manifest
 */
public static boolean isValidBundle(VirtualFile virtualFile){
  try {
    Manifest manifest=VFSUtils.getManifest(virtualFile);
    return OSGiManifestBuilder.isValidBundleManifest(manifest);
  }
 catch (  IOException e) {
    return false;
  }
}
 

Example 18

From project jbosgi-vfs, under directory /vfs30/src/test/java/org/jboss/test/osgi/vfs30/.

Source file: SimpleVFS30TestCase.java

  22 
vote

@Test public void testStreamURLAccess() throws Exception {
  VirtualFile virtualFile=AbstractVFS.toVirtualFile(file.toURI());
  try {
    URL streamURL=virtualFile.getStreamURL();
    JarInputStream jarIn=new JarInputStream(streamURL.openStream());
    Manifest manifest=jarIn.getManifest();
    Attributes attributes=manifest.getMainAttributes();
    String symbolicName=attributes.getValue(Constants.BUNDLE_SYMBOLICNAME);
    assertEquals("example-simple",symbolicName);
  }
  finally {
    virtualFile.close();
  }
}
 

Example 19

From project jboss-vfs, under directory /src/test/java/org/jboss/test/vfs/.

Source file: FileVFSUnitTestCase.java

  22 
vote

public void testFindResourceUnpackedJar() throws Exception {
  VirtualFile testdir=getVirtualFile("/vfs/test");
  VirtualFile jar=testdir.getChild("unpacked-outer.jar");
  assertTrue("unpacked-outer.jar != null",jar != null);
  VirtualFile metaInf=jar.getChild("META-INF/MANIFEST.MF");
  assertTrue("META-INF/MANIFEST.MF != null",metaInf != null);
  InputStream mfIS=metaInf.openStream();
  assertTrue("META-INF/MANIFEST.MF.openStream != null",mfIS != null);
  Manifest mf=new Manifest(mfIS);
  Attributes mainAttrs=mf.getMainAttributes();
  String version=mainAttrs.getValue(Attributes.Name.SPECIFICATION_VERSION);
  assertEquals("1.0.0.GA",version);
  mfIS.close();
}
 

Example 20

From project JsTestDriver, under directory /JsTestDriver/src/com/google/jstestdriver/.

Source file: Plugin.java

  22 
vote

/** 
 * This is accessor for the plugin name, used to identify the plugin. It can be read either from the configuration file, or from the  jar manifest.
 */
public String getName(ManifestLoader manifestLoader){
  if (name == null) {
    try {
      Manifest manifest=manifestLoader.load(pathToJar);
      return manifest.getAttributes("jstd").getValue("plugin-name");
    }
 catch (    ManifestNotFound e) {
      throw new RuntimeException(e);
    }
  }
  return name;
}
 

Example 21

From project jumpnevolve, under directory /src/com/jdotsoft/jarloader/.

Source file: JarClassLoader.java

  22 
vote

/** 
 * Returns the name of the jar file main class, or null if no "Main-Class" manifest attributes was defined.
 * @return main class declared in JAR's manifest
 */
public String getManifestMainClass(){
  Attributes attr=null;
  if (isLaunchedFromJar()) {
    try {
      Manifest m=this.lstJarFile.get(0).getManifest();
      attr=m.getMainAttributes();
    }
 catch (    IOException e) {
    }
  }
  return (attr == null ? null : attr.getValue(Attributes.Name.MAIN_CLASS));
}
 

Example 22

From project karaf, under directory /kar/core/src/main/java/org/apache/karaf/kar/internal/.

Source file: KarServiceImpl.java

  22 
vote

private Manifest createNonAutoStartManifest(URI repoUri) throws UnsupportedEncodingException, IOException {
  String manifestSt="Manifest-Version: 1.0\n" + Kar.MANIFEST_ATTR_KARAF_FEATURE_START + ": false\n"+ Kar.MANIFEST_ATTR_KARAF_FEATURE_REPOS+ ": "+ repoUri.toString()+ "\n";
  InputStream manifestIs=new ByteArrayInputStream(manifestSt.getBytes("UTF-8"));
  Manifest manifest=new Manifest(manifestIs);
  return manifest;
}
 

Example 23

From project 3Dto2DApplet, under directory /src/java/nl/dannyarends/generic/.

Source file: JavaCompiler.java

  21 
vote

void toJarFile(String jarfilepath){
  try {
    File tofp=new File(jarfilepath);
    File fromfp=new File(tocompile.loc_output);
    if (tofp.exists()) {
      System.err.println("Overwriting old jar: " + jarfilepath);
      tofp.delete();
    }
    File f=new File(tocompile.loc_output + File.separator + "/MANIFEST.MF");
    JarOutputStream zos;
    FileOutputStream fos;
    if (f.exists()) {
      FileInputStream i=new FileInputStream(f);
      Manifest manifest=new Manifest(i);
      fos=new FileOutputStream(tofp);
      zos=new JarOutputStream(fos,manifest);
    }
 else {
      fos=new FileOutputStream(tofp);
      zos=new JarOutputStream(fos);
    }
    File[] files=fromfp.listFiles();
    FileUtils.writeInJar(zos,files,"",true);
    zos.close();
    System.out.println("Build a JAR: " + jarfilepath);
  }
 catch (  Exception e) {
    Utils.log("Something wrong: ",e);
  }
}
 

Example 24

From project Aardvark, under directory /aardvark-core/src/test/java/gw/vark/.

Source file: TestprojectTest.java

  21 
vote

private static List<File> yankClasspathFromSurefireBooter(URL mfUrl) throws IOException {
  List<File> cp=new ArrayList<File>();
  InputStream mfIn=null;
  try {
    mfIn=mfUrl.openStream();
    Manifest mf=new Manifest(mfIn);
    String mfCp=mf.getMainAttributes().getValue("Class-Path");
    StringTokenizer cpSt=new StringTokenizer(mfCp);
    while (cpSt.hasMoreTokens()) {
      String cpElement=cpSt.nextToken();
      URL cpElementUrl=new URL(cpElement);
      File cpFile=new File(cpElementUrl.getFile());
      cp.add(cpFile);
    }
  }
  finally {
    try {
      StreamUtil.close(mfIn);
    }
 catch (    IOException e) {
    }
  }
  return cp;
}
 

Example 25

From project android_build, under directory /tools/signapk/.

Source file: SignApk.java

  21 
vote

/** 
 * Add the SHA1 of every file to the manifest, creating it if necessary. 
 */
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 (Android SignApk)");
  }
  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(CERT_SF_NAME)&& !name.equals(CERT_RSA_NAME)&& (stripPattern == null || !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;
}
 

Example 26

From project apb, under directory /modules/apb-base/src/apb/tasks/.

Source file: JarTask.java

  21 
vote

private JarTask(@NotNull File jarFile,@NotNull List<FileSet> sources){
  this.jarFile=jarFile;
  this.sources=sources;
  services=Collections.emptyMap();
  manifest=new Manifest();
  manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION,"1.0");
  manifest.getMainAttributes().putValue("Created-By","APB");
}
 

Example 27

From project arkadiko, under directory /src/com/liferay/arkadiko/util/.

Source file: AKFrameworkFactory.java

  21 
vote

public static Bundle getBundle(BundleContext bundleContext,File bundleFile) throws IOException {
  JarFile jarFile=new JarFile(bundleFile);
  Manifest manifest=jarFile.getManifest();
  jarFile.close();
  Attributes attributes=manifest.getMainAttributes();
  String bundleSymbolicNameAttribute=attributes.getValue(Constants.BUNDLE_SYMBOLICNAME);
  Map<String,Map<String,String>> bundleSymbolicNamesMap=OSGiHeader.parseHeader(bundleSymbolicNameAttribute);
  Set<String> bundleSymbolicNamesSet=bundleSymbolicNamesMap.keySet();
  Iterator<String> bundleSymbolicNamesIterator=bundleSymbolicNamesSet.iterator();
  String bundleSymbolicName=bundleSymbolicNamesIterator.next();
  String bundleVersionAttribute=attributes.getValue(Constants.BUNDLE_VERSION);
  Version bundleVersion=Version.parseVersion(bundleVersionAttribute);
  for (  Bundle bundle : bundleContext.getBundles()) {
    Version curBundleVersion=Version.parseVersion(bundle.getVersion().toString());
    if (bundleSymbolicName.equals(bundle.getSymbolicName()) && bundleVersion.equals(curBundleVersion)) {
      return bundle;
    }
  }
  return null;
}
 

Example 28

From project big-data-plugin, under directory /src/org/pentaho/di/job/entries/hadoopjobexecutor/.

Source file: JarUtility.java

  21 
vote

/** 
 * Get the Main-Class declaration from a Jar's manifest.
 * @param jarUrl URL to the Jar file
 * @param parentClassLoader Class loader to delegate to when loading classes outside the jar.
 * @return Class defined by Main-Class manifest attribute, {@code null} if not defined.
 * @throws IOException Error opening jar file
 * @throws ClassNotFoundException Error locating the main class as defined in the manifest
 */
public Class<?> getMainClassFromManifest(URL jarUrl,ClassLoader parentClassLoader) throws IOException, ClassNotFoundException {
  if (jarUrl == null || parentClassLoader == null) {
    throw new NullPointerException();
  }
  JarFile jarFile;
  try {
    jarFile=new JarFile(new File(jarUrl.toURI()));
  }
 catch (  URISyntaxException ex) {
    throw new IOException("Error locating jar: " + jarUrl);
  }
catch (  IOException ex) {
    throw new IOException("Error opening job jar: " + jarUrl,ex);
  }
  try {
    Manifest manifest=jarFile.getManifest();
    String className=manifest == null ? null : manifest.getMainAttributes().getValue("Main-Class");
    if (className != null) {
      URLClassLoader cl=new URLClassLoader(new URL[]{jarUrl},parentClassLoader);
      return cl.loadClass(className);
    }
 else {
      return null;
    }
  }
  finally {
    jarFile.close();
  }
}
 

Example 29

From project bndtools, under directory /bndtools.core/src/bndtools/classpath/.

Source file: BndContainerInitializer.java

  21 
vote

static void calculateWorkspaceBundleAccessRules(Map<Project,List<IAccessRule>> projectAccessRules,Container c){
  String packageList=c.getAttributes().get("packages");
  if (packageList != null) {
    List<IAccessRule> tmp=new LinkedList<IAccessRule>();
    StringTokenizer tokenizer=new StringTokenizer(packageList,",");
    while (tokenizer.hasMoreTokens()) {
      String token=tokenizer.nextToken();
      String pathStr=token.replace('.','/') + "/*";
      tmp.add(JavaCore.newAccessRule(new Path(pathStr),IAccessRule.K_ACCESSIBLE));
    }
    addAccessRules(projectAccessRules,c.getProject(),tmp);
  }
 else   if (isProjectContainer(c)) {
    addAccessRules(projectAccessRules,c.getProject(),null);
  }
 else   if (c.getType() == TYPE.PROJECT) {
    Manifest mf=null;
    try {
      mf=JarUtils.loadJarManifest(new FileInputStream(c.getFile()));
    }
 catch (    IOException e) {
      logger.logError("Unable to generate access rules from bundle " + c.getFile(),e);
      return;
    }
    Parameters exportPkgs=new Parameters(mf.getMainAttributes().getValue(new Name(Constants.EXPORT_PACKAGE)));
    List<IAccessRule> tmp=new LinkedList<IAccessRule>();
    for (    String exportPkg : exportPkgs.keySet()) {
      String pathStr=exportPkg.replace('.','/') + "/*";
      tmp.add(JavaCore.newAccessRule(new Path(pathStr),IAccessRule.K_ACCESSIBLE));
    }
    addAccessRules(projectAccessRules,c.getProject(),tmp);
  }
}
 

Example 30

From project Cafe, under directory /webapp/src/org/openqa/selenium/internal/.

Source file: BuildInfo.java

  21 
vote

private static Properties loadBuildProperties(){
  Properties properties=new Properties();
  Manifest manifest=null;
  try {
    URL url=BuildInfo.class.getProtectionDomain().getCodeSource().getLocation();
    File file=new File(url.toURI());
    JarFile jar=new JarFile(file);
    manifest=jar.getManifest();
  }
 catch (  NullPointerException ignored) {
  }
catch (  URISyntaxException ignored) {
  }
catch (  IOException ignored) {
  }
catch (  IllegalArgumentException ignored) {
  }
  if (manifest == null) {
    return properties;
  }
  try {
    Attributes attributes=manifest.getAttributes("Build-Info");
    Set<Entry<Object,Object>> entries=attributes.entrySet();
    for (    Entry<Object,Object> e : entries) {
      properties.put(String.valueOf(e.getKey()),String.valueOf(e.getValue()));
    }
  }
 catch (  NullPointerException e) {
  }
  return properties;
}
 

Example 31

From project ceylon-runtime, under directory /impl/src/main/java/ceylon/modules/jboss/repository/.

Source file: SourceResourceLoader.java

  21 
vote

private static Manifest readManifestFile(final File manifestFile){
  try {
    InputStream is=new FileInputStream(manifestFile);
    try {
      return new Manifest(is);
    }
  finally {
      safeClose(is);
    }
  }
 catch (  IOException e) {
    return null;
  }
}
 

Example 32

From project ChkBugReport, under directory /src/com/sonyericsson/chkbugreport/.

Source file: Module.java

  21 
vote

public Module(String fileName){
  mDoc=new Doc(this);
  mDoc.setFileName(fileName);
  mDoc.addChapter(mHeader=createHeader());
  try {
    File homeDir=new File(System.getProperty("user.home"));
    File pluginDir=new File(homeDir,".chkbugreport-plugins");
    if (pluginDir.exists() && pluginDir.isDirectory()) {
      String files[]=pluginDir.list();
      for (      String fn : files) {
        if (fn.startsWith(".") || !fn.endsWith(".jar")) {
          continue;
        }
        File jar=new File(pluginDir,fn);
        JarInputStream jis=new JarInputStream(new FileInputStream(jar));
        Manifest mf=jis.getManifest();
        if (mf != null) {
          String pluginClassName=mf.getMainAttributes().getValue("ChkBugReport-Plugin");
          URL urls[]={jar.toURI().toURL()};
          URLClassLoader cl=new URLClassLoader(urls,getClass().getClassLoader());
          Class<?> extClass=Class.forName(pluginClassName,true,cl);
          ExternalPlugin ext=(ExternalPlugin)extClass.newInstance();
          System.out.println("Loading plugins from: " + jar.getAbsolutePath());
          ext.initExternalPlugin(this);
        }
      }
    }
  }
 catch (  Exception e) {
    System.err.println("Error loading external plugins");
    e.printStackTrace();
  }
}
 

Example 33

From project Clotho-Core, under directory /ClothoApps/SequenceChecker/src/jaligner/util/.

Source file: Commons.java

  21 
vote

/** 
 * 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 {
    connection=(JarURLConnection)url.openConnection();
    jarFile=connection.getJarFile();
    Manifest manifest=jarFile.getManifest();
    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 34

From project cogroo4, under directory /lang/pt_br/cogroo-addon/src/org/cogroo/addon/.

Source file: CentralRegistrationClass.java

  21 
vote

private static String getRegistrationClasses(){
  CentralRegistrationClass c=new CentralRegistrationClass();
  String name=c.getClass().getCanonicalName().replace('.','/').concat(".class");
  try {
    Enumeration<URL> urlEnum=c.getClass().getClassLoader().getResources("META-INF/MANIFEST.MF");
    while (urlEnum.hasMoreElements()) {
      URL url=urlEnum.nextElement();
      String file=url.getFile();
      JarURLConnection jarConnection=(JarURLConnection)url.openConnection();
      Manifest mf=jarConnection.getManifest();
      Attributes attrs=(Attributes)mf.getAttributes(name);
      if (attrs != null) {
        String classes=attrs.getValue("RegistrationClasses");
        return classes;
      }
    }
  }
 catch (  IOException ex) {
    ex.printStackTrace();
  }
  return "";
}
 

Example 35

From project community-plugins, under directory /deployit-cli-plugins/dar-manifest-exporter/src/main/java/ext/deployit/community/cli/manifestexport/dar/.

Source file: ManifestBuilder.java

  21 
vote

public @Nonnull Manifest build(){
  Manifest manifest=new Manifest();
  Attributes manifestMainAttributes=manifest.getMainAttributes();
  manifestMainAttributes.putValue(Name.MANIFEST_VERSION.toString(),GENERATED_MANIFEST_VERSION);
  Map<String,Attributes> manifestEntries=manifest.getEntries();
  lock.lock();
  try {
    for (    Entry<String,String> mainAttribute : mainAttributes.entrySet()) {
      manifestMainAttributes.putValue(mainAttribute.getKey(),mainAttribute.getValue());
    }
    for (    Entry<String,Map<String,String>> attributesForEntry : entryAttributes.entrySet()) {
      manifestEntries.put(attributesForEntry.getKey(),toAttributes(attributesForEntry.getValue()));
    }
  }
  finally {
    lock.unlock();
  }
  return manifest;
}
 

Example 36

From project dolphin, under directory /texcel/compile/sun/misc/.

Source file: URLClassPath.java

  21 
vote

URL[] getClassPath() throws IOException {
  if (index != null) {
    return null;
  }
  if (metaIndex != null) {
    return null;
  }
  ensureOpen();
  parseExtensionsDependencies();
  if (SharedSecrets.javaUtilJarAccess().jarFileHasClassPathAttribute(jar)) {
    Manifest man=jar.getManifest();
    if (man != null) {
      Attributes attr=man.getMainAttributes();
      if (attr != null) {
        String value=attr.getValue(Name.CLASS_PATH);
        if (value != null) {
          return parseClassPath(csu,value);
        }
      }
    }
  }
  return null;
}
 

Example 37

From project drools-chance, under directory /drools-shapes/drools-shapes-reasoner-generator/src/main/java/org/drools/semantics/builder/model/.

Source file: JarModelImpl.java

  21 
vote

public ByteArrayOutputStream buildJar(){
  Date now=new Date();
  Manifest manifest=new Manifest();
  manifest.getMainAttributes().putValue("Manifest-Version","1.0");
  manifest.getMainAttributes().putValue("Manifest-Version","1.0");
  try {
    ByteArrayOutputStream stream=new ByteArrayOutputStream();
    JarOutputStream out=new JarOutputStream(stream,manifest);
    for (    String name : getTraitNames()) {
      JarEntry jarAdd=new JarEntry(getDefaultPackage().replace(".","/") + "/" + name+ ".java");
      jarAdd.setTime(now.getTime());
      out.putNextEntry(jarAdd);
      out.write(((InterfaceHolder)getTrait(name)).getSource().getBytes());
      jarAdd=new JarEntry(getDefaultPackage().replace(".","/") + "/" + name+ ".class");
      jarAdd.setTime(now.getTime());
      out.putNextEntry(jarAdd);
      out.write(getCompiledTrait(name));
    }
    out.close();
    stream.close();
    return stream;
  }
 catch (  Exception ex) {
    ex.printStackTrace();
  }
  return null;
}
 

Example 38

From project drools-semantics, under directory /src/main/java/org/drools/semantics/builder/model/.

Source file: JarModelImpl.java

  21 
vote

public ByteArrayOutputStream buildJar(){
  Date now=new Date();
  Manifest manifest=new Manifest();
  manifest.getMainAttributes().putValue("Manifest-Version","1.0");
  manifest.getMainAttributes().putValue("Manifest-Version","1.0");
  try {
    ByteArrayOutputStream stream=new ByteArrayOutputStream();
    JarOutputStream out=new JarOutputStream(stream,manifest);
    for (    String name : getTraitNames()) {
      System.out.println("Adding " + name);
      JarEntry jarAdd=new JarEntry(getPackage().replace(".","/") + "/" + name+ ".java");
      jarAdd.setTime(now.getTime());
      out.putNextEntry(jarAdd);
      out.write(((String)getTrait(name)).getBytes());
      jarAdd=new JarEntry(getPackage().replace(".","/") + "/" + name+ ".class");
      jarAdd.setTime(now.getTime());
      out.putNextEntry(jarAdd);
      out.write(getCompiledTrait(name));
    }
    out.close();
    stream.close();
    System.out.println("Adding completed OK");
    return stream;
  }
 catch (  Exception ex) {
    ex.printStackTrace();
    System.out.println("Error: " + ex.getMessage());
  }
  return null;
}
 

Example 39

From project droolsjbpm-build-distribution, under directory /drools-osgi-bundles/org.drools.osgi.test/src/test/java/org/drools/osgi/test/utils/.

Source file: EclipseArtifactFinder.java

  21 
vote

private void importPluginFromFolder(File folder,Set<Plugin> plugins){
  log.info("Importing plugins from folder " + folder.getAbsolutePath());
  Set<Resource> eclipseProjects=new HashSet<Resource>();
  for (  File projectFolder : folder.listFiles(m_DirectoryFilter)) {
    eclipseProjects.add(new FileSystemResource(projectFolder));
  }
  for (  Resource resource : eclipseProjects) {
    Manifest man=getManifestFromProject(resource);
    if (man != null) {
      addPlugin(plugins,resource,man,true);
    }
 else {
      List<String> list=Arrays.asList(((FileSystemResource)resource).getFile().list());
      for (      String str : list) {
        if (str.contains("drools-eclipse") || str.contains("osgi-bundles")) {
          list=null;
        }
      }
      if (list != null && list.contains("pom.xml")) {
        importPluginFromFolder(((FileSystemResource)resource).getFile(),plugins);
      }
    }
  }
  Set<Resource> packagedBundles=new HashSet<Resource>();
  for (  File jarFile : folder.listFiles(m_JARFileFilter))   packagedBundles.add(new FileSystemResource(jarFile));
  for (  Resource resource : packagedBundles) {
    Manifest man=getManifestFromJAR(resource);
    if (man != null)     addPlugin(plugins,resource,man,false);
  }
}
 

Example 40

From project eclipse.pde.build, under directory /org.eclipse.pde.build/src_ant/org/eclipse/pde/internal/build/tasks/.

Source file: ManifestModifier.java

  21 
vote

private void loadManifest(){
  try {
    InputStream is=new SequenceInputStream(new BufferedInputStream(new FileInputStream(manifestLocation)),new ByteArrayInputStream(new byte[]{'\n'}));
    try {
      manifest=new Manifest(is);
    }
  finally {
      is.close();
    }
  }
 catch (  IOException e) {
    throw new BuildException("Problem reading the content of the manifest : " + manifestLocation);
  }
}
 

Example 41

From project eik, under directory /plugins/info.evanchik.eclipse.karaf.core/src/main/java/info/evanchik/eclipse/karaf/core/model/.

Source file: GenericKarafPlatformDetails.java

  21 
vote

@Override public String getDescription(){
  final String description;
  try {
    final Manifest manifest=platformDetailsBundle.getManifest();
    if (manifest == null) {
      description="";
    }
 else {
      final String bundleDescription=manifest.getMainAttributes().getValue(Constants.BUNDLE_DESCRIPTION);
      if (bundleDescription == null) {
        description="";
      }
 else {
        description=bundleDescription;
      }
    }
  }
 catch (  final IOException e) {
    return "";
  }
  return description;
}
 

Example 42

From project encog-java-workbench, under directory /src/main/java/org/encog/workbench/tabs/.

Source file: AboutTab.java

  21 
vote

public AboutTab(){
  super(null);
  setPreferredSize(new Dimension(800,3000));
  final String path=System.getProperty("java.class.path");
  final StringTokenizer tok=new StringTokenizer(path,"" + File.pathSeparatorChar);
  while (tok.hasMoreTokens()) {
    final String jarPath=tok.nextToken();
    final File jarFile=new File(jarPath);
    if (jarFile.isFile()) {
      try {
        final JarFile jarData=new JarFile(jarFile);
        final Manifest manifest=jarData.getManifest();
        this.jars.add(jarFile.getName() + " (" + jarFile+ ")");
      }
 catch (      final IOException e) {
      }
    }
  }
  generate();
}
 

Example 43

From project glg2d, under directory /src/test/java/glg2d/misc/.

Source file: InstrumentPaint.java

  21 
vote

/** 
 * I hacked this together with duct tape and wire hangers, along with help from these two sites: <a href= "http://sleeplessinslc.blogspot.com/2008/09/java-instrumentation-with-jdk-16x-class.html" >http://sleeplessinslc.blogspot.com/2008/09/java-instrumentation-with-jdk- 16x-class.html</a> and <a href= "http://sleeplessinslc.blogspot.com/2008/07/java-instrumentation.html" >http://sleeplessinslc.blogspot.com/2008/07/java-instrumentation.html</a>.
 */
private static void instrument0() throws Exception {
  File jarFile=File.createTempFile("agent",".jar");
  jarFile.deleteOnExit();
  Manifest manifest=new Manifest();
  Attributes mainAttributes=manifest.getMainAttributes();
  mainAttributes.put(Attributes.Name.MANIFEST_VERSION,"1.0");
  mainAttributes.put(new Attributes.Name("Agent-Class"),InstrumentPaint.class.getName());
  mainAttributes.put(new Attributes.Name("Can-Retransform-Classes"),"true");
  mainAttributes.put(new Attributes.Name("Can-Redefine-Classes"),"true");
  JarOutputStream jos=new JarOutputStream(new FileOutputStream(jarFile),manifest);
  JarEntry agent=new JarEntry(InstrumentPaint.class.getName().replace('.','/') + ".class");
  jos.putNextEntry(agent);
  CtClass ctClass=ClassPool.getDefault().get(InstrumentPaint.class.getName());
  jos.write(ctClass.toBytecode());
  jos.closeEntry();
  JarEntry snip=new JarEntry("instrumentation.snip");
  jos.putNextEntry(snip);
  jos.write(getInstrumentationCode().getBytes());
  jos.closeEntry();
  jos.close();
  String name=ManagementFactory.getRuntimeMXBean().getName();
  VirtualMachine vm=VirtualMachine.attach(name.substring(0,name.indexOf('@')));
  vm.loadAgent(jarFile.getAbsolutePath());
  vm.detach();
}
 

Example 44

From project hama, under directory /core/src/main/java/org/apache/hama/monitor/.

Source file: Configurator.java

  21 
vote

/** 
 * Load jar from specified path.
 * @param path to the jar file.
 * @param loader of the current thread.  
 * @return task to be run.
 */
private static Task load(File path,ClassLoader loader) throws IOException {
  JarFile jar=new JarFile(path);
  Manifest manifest=jar.getManifest();
  String pkg=manifest.getMainAttributes().getValue("Package");
  String main=manifest.getMainAttributes().getValue("Main-Class");
  if (null == pkg || null == main)   throw new NullPointerException("Package or main class not found " + "in menifest file.");
  String namespace=pkg + File.separator + main;
  namespace=namespace.replaceAll(File.separator,".");
  LOG.debug("Task class to be loaded: " + namespace);
  URLClassLoader child=new URLClassLoader(new URL[]{path.toURI().toURL()},loader);
  Thread.currentThread().setContextClassLoader(child);
  Class<?> taskClass=null;
  try {
    taskClass=Class.forName(namespace,true,child);
  }
 catch (  ClassNotFoundException cnfe) {
    LOG.warn("Task class is not found.",cnfe);
  }
  if (null == taskClass)   return null;
  try {
    return (Task)taskClass.newInstance();
  }
 catch (  InstantiationException ie) {
    LOG.warn("Unable to instantiate task class." + namespace,ie);
  }
catch (  IllegalAccessException iae) {
    LOG.warn(iae);
  }
  return null;
}
 

Example 45

From project incubator-deltaspike, under directory /deltaspike/core/api/src/main/java/org/apache/deltaspike/core/util/.

Source file: ClassUtils.java

  21 
vote

/** 
 * Reads the version of the jar which contains the given class
 * @param targetClass class within the jar
 * @return version-string which has been found in the manifest or null if there is no version information available
 */
public static String getJarVersion(Class targetClass){
  String manifestFileLocation=getManifestFileLocationOfClass(targetClass);
  try {
    return new Manifest(new URL(manifestFileLocation).openStream()).getMainAttributes().getValue(Attributes.Name.IMPLEMENTATION_VERSION);
  }
 catch (  Exception e) {
    return null;
  }
}
 

Example 46

From project ios-driver, under directory /server/src/main/java/org/uiautomation/ios/server/utils/.

Source file: BuildInfo.java

  21 
vote

private static Properties loadBuildProperties(){
  Properties properties=new Properties();
  try {
    Manifest manifest=null;
    URL url=BuildInfo.class.getProtectionDomain().getCodeSource().getLocation();
    File file=new File(url.toURI());
    JarFile jar=new JarFile(file);
    manifest=jar.getManifest();
    Attributes attributes=manifest.getMainAttributes();
    Set<Entry<Object,Object>> entries=attributes.entrySet();
    for (    Entry<Object,Object> e : entries) {
      properties.put(String.valueOf(e.getKey()),String.valueOf(e.getValue()));
    }
  }
 catch (  Exception e) {
  }
  return properties;
}
 

Example 47

From project jbosgi-framework, under directory /core/src/main/java/org/jboss/osgi/framework/internal/.

Source file: DeploymentFactoryPlugin.java

  21 
vote

Deployment createDeployment(String location,VirtualFile rootFile) throws BundleException {
  BundleException cause=null;
  try {
    BundleInfo info=BundleInfo.createBundleInfo(rootFile,location);
    Deployment dep=DeploymentFactory.createDeployment(info);
    OSGiMetaData metadata=info.getOSGiMetadata();
    dep.addAttachment(BundleInfo.class,info);
    dep.addAttachment(OSGiMetaData.class,metadata);
    return dep;
  }
 catch (  NumberFormatException nfe) {
    throw FrameworkMessages.MESSAGES.invalidNumberFormat(nfe,nfe.getMessage());
  }
catch (  BundleException ex) {
    cause=ex;
  }
  OSGiMetaData metadata=getXServiceMetaData(rootFile);
  if (metadata != null) {
    String symbolicName=metadata.getBundleSymbolicName();
    Version version=metadata.getBundleVersion();
    Deployment dep=DeploymentFactory.createDeployment(rootFile,location,symbolicName,version);
    dep.addAttachment(OSGiMetaData.class,metadata);
    return dep;
  }
  Manifest manifest=null;
  try {
    manifest=VFSUtils.getManifest(rootFile);
  }
 catch (  IOException ex) {
  }
  if (manifest != null && manifest.getMainAttributes().keySet().size() < 2) {
    Deployment dep=DeploymentFactory.createDeployment(rootFile,location,null,Version.emptyVersion);
    metadata=OSGiMetaDataBuilder.load(manifest);
    dep.addAttachment(OSGiMetaData.class,metadata);
    return dep;
  }
  throw (cause != null ? cause : new BundleException("Cannot create deployment from: " + rootFile));
}
 

Example 48

From project jbosgi-repository, under directory /api/src/main/java/org/jboss/osgi/repository/.

Source file: URLResourceBuilderFactory.java

  21 
vote

public static XResourceBuilder create(URL contentURL,Map<String,Object> contentAtts,boolean loadMetadata){
  URLResource urlres=new URLResource(contentURL);
  URLResourceBuilderFactory factory=new URLResourceBuilderFactory(urlres);
  XResourceBuilder builder=XResourceBuilderFactory.create(factory);
  XCapability ccap=builder.addCapability(ContentNamespace.CONTENT_NAMESPACE,contentAtts,null);
  Map<String,Object> atts=ccap.getAttributes();
  atts.put(ContentNamespace.CAPABILITY_URL_ATTRIBUTE,contentURL.toExternalForm());
  if (atts.get(ContentNamespace.CONTENT_NAMESPACE) == null)   atts.put(ContentNamespace.CONTENT_NAMESPACE,XContentCapability.DEFAULT_DIGEST);
  if (atts.get(ContentNamespace.CAPABILITY_MIME_ATTRIBUTE) == null)   atts.put(ContentNamespace.CAPABILITY_MIME_ATTRIBUTE,XContentCapability.DEFAULT_MIME_TYPE);
  if (atts.get(ContentNamespace.CAPABILITY_SIZE_ATTRIBUTE) == null)   atts.put(ContentNamespace.CAPABILITY_SIZE_ATTRIBUTE,XContentCapability.DEFAULT_SIZE);
  if (loadMetadata) {
    InputStream content=urlres.getContent();
    try {
      Manifest manifest=new JarInputStream(content).getManifest();
      OSGiMetaData metaData=OSGiMetaDataBuilder.load(manifest);
      builder.loadFrom(metaData);
    }
 catch (    Exception ex) {
      throw new IllegalStateException("Cannot create capability from: " + contentURL,ex);
    }
 finally {
      if (content != null) {
        try {
          content.close();
        }
 catch (        IOException e) {
        }
      }
    }
  }
  return builder;
}
 

Example 49

From project jboss-modules, under directory /src/main/java/org/jboss/modules/.

Source file: FileResourceLoader.java

  21 
vote

private static Manifest readManifestFile(final File manifestFile){
  try {
    return new Manifest(new FileInputStream(manifestFile));
  }
 catch (  IOException e) {
    return null;
  }
}
 

Example 50

From project esbt, under directory /src/org/scalastuff/osgitools/.

Source file: Osgiify.java

  19 
vote

public static String getValue(Manifest manifest,String name){
  String value=manifest.getMainAttributes().getValue(name);
  if (value != null) {
    int index=value.indexOf(';');
    if (index >= 0) {
      value=value.substring(0,index);
    }
  }
  return value;
}
 

Example 51

From project hoop, under directory /hoop-server/src/main/java/com/cloudera/lib/lang/.

Source file: ClassUtils.java

  19 
vote

/** 
 * Writes the specified classes to an outputstream.
 * @param os outputstream to write the classes to.
 * @param classes classes to write to the outputstream.
 * @throws IOException thrown if an IO error occurred.
 */
public static void createJar(OutputStream os,Class... classes) throws IOException {
  Check.notNull(os,"os");
  File classesDir=File.createTempFile("createJar","classes");
  if (!classesDir.delete()) {
    throw new IOException(MessageFormat.format("could not delete temp file [{0}]",classesDir));
  }
  for (  Class clazz : classes) {
    String classPath=clazz.getName().replace(".","/") + ".class";
    String classFileName=classPath;
    if (classPath.lastIndexOf("/") > -1) {
      classFileName=classPath.substring(classPath.lastIndexOf("/") + 1);
    }
    String packagePath=new File(classPath).getParent();
    File dir=new File(classesDir,packagePath);
    if (!dir.exists()) {
      if (!dir.mkdirs()) {
        throw new IOException(MessageFormat.format("could not create dir [{0}]",dir));
      }
    }
    InputStream is=getResource(classPath);
    OutputStream classOS=new FileOutputStream(new File(dir,classFileName));
    IOUtils.copy(is,classOS);
  }
  JarOutputStream zos=new JarOutputStream(os,new Manifest());
  IOUtils.zipDir(classesDir,"",zos);
  IOUtils.delete(classesDir);
}