Java Code Examples for java.util.jar.JarFile

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 ant4eclipse, under directory /org.ant4eclipse.lib.pde/src/org/ant4eclipse/lib/pde/internal/model/pluginproject/.

Source file: BundleDescriptionLoader.java

  18 
vote

private static BundleDescription parsePluginJarFile(File file){
  Assure.isFile("file",file);
  try {
    JarFile jarFile=new JarFile(file);
    Manifest manifest=jarFile.getManifest();
    if ((manifest != null) && isBundleManifest(manifest)) {
      return createBundleDescription(manifest,file.getAbsolutePath(),file);
    }
  }
 catch (  Exception e) {
    throw new RuntimeException("Exception while parsing plugin jar '" + file.getName() + "'!",e);
  }
  return null;
}
 

Example 2

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

Source file: JarClassLoader.java

  18 
vote

private JarEntryInfo findJarEntry(String sName){
  for (  JarFileInfo jarFileInfo : lstJarFile) {
    JarFile jarFile=jarFileInfo.jarFile;
    JarEntry jarEntry=jarFile.getJarEntry(sName);
    if (jarEntry != null) {
      return new JarEntryInfo(jarFileInfo,jarEntry);
    }
  }
  return null;
}
 

Example 3

From project aws-toolkit-for-eclipse, under directory /com.amazonaws.eclipse.sdk.ui/src/com/amazonaws/eclipse/sdk/ui/.

Source file: SdkInstall.java

  18 
vote

/** 
 * Returns version release notes pertaining to this particular version of the SDK
 * @return The version notes pertaining to this SDK install.
 */
public String getVersionNotes(){
  try {
    JarFile jarFile=new JarFile(getSdkJar());
    ZipEntry zipEntry=jarFile.getEntry(VERSION_INFO_PROPERTIES_PATH);
    Properties properties=new Properties();
    properties.load(jarFile.getInputStream(zipEntry));
    if (properties.containsKey("notes")) {
      return properties.getProperty("notes");
    }
  }
 catch (  IOException e) {
  }
  return "Could not find any version notes for this version of the SDK.";
}
 

Example 4

From project bundlemaker, under directory /main/org.bundlemaker.core/src/org/bundlemaker/core/internal/modules/modularizedsystem/.

Source file: AbstractTransformationAwareModularizedSystem.java

  18 
vote

/** 
 * <p> </p>
 * @param file
 * @return
 * @throws IOException
 */
private static List<String> getContainedTypesFromJarFile(File file) throws IOException {
  List<String> result=new LinkedList<String>();
  JarFile jarFile=new JarFile(file);
  Enumeration<JarEntry> entries=jarFile.entries();
  while (entries.hasMoreElements()) {
    JarEntry jarEntry=(JarEntry)entries.nextElement();
    if (jarEntry.getName().endsWith(".class")) {
      result.add(jarEntry.getName().substring(0,jarEntry.getName().length() - ".class".length()).replace('/','.'));
    }
  }
  return result;
}
 

Example 5

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

Source file: ResourceLoaderProvider.java

  18 
vote

/** 
 * Get resource loader.
 * @param moduleIdentifier the module identifier
 * @param repository       the repository
 * @param moduleFile       the module file
 * @return new resource loader
 * @throws IOException for any I/O error
 */
public static ResourceLoader getResourceLoader(ModuleIdentifier moduleIdentifier,RepositoryManager repository,File moduleFile) throws IOException {
  File classesRoot=null;
  if (classesRoot != null) {
    return new SourceResourceLoader(moduleFile,classesRoot,"");
  }
 else {
    JarFile jarFile=new JarFile(moduleFile);
    String rootName=moduleFile.getName();
    return ResourceLoaders.createJarResourceLoader(rootName,jarFile);
  }
}
 

Example 6

From project crash, under directory /shell/core/src/main/java/org/crsh/vfs/spi/jarurl/.

Source file: JarURLDriver.java

  18 
vote

public JarURLDriver(ClassLoader loader,JarURLConnection conn) throws IOException {
  JarFile file=conn.getJarFile();
  Map<String,Handle> handles=new HashMap<String,Handle>();
  handles.put("",root=new Handle(this,""));
  for (  JarEntry entry : Collections.list(file.entries())) {
    Handle handle=get(this,handles,entry.getName());
    handle.entry=entry;
  }
  this.jarURL=conn.getJarFileURL();
  this.loader=loader;
}
 

Example 7

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

  18 
vote

/** 
 * Return an Eclipse bundle's JAR Manifest
 * @param resource an Eclipse JAR path
 * @return The JAR Manifest
 */
private Manifest getManifestFromJAR(Resource resource){
  try {
    JarFile jar=new JarFile(resource.getFile());
    return jar.getManifest();
  }
 catch (  IOException e) {
    throw new IllegalStateException("Resource (" + resource + ") 's manifest could not be read.",e);
  }
}
 

Example 8

From project flyway, under directory /flyway-core/src/main/java/com/googlecode/flyway/core/util/scanner/.

Source file: JarFileLocationScanner.java

  18 
vote

/** 
 * Finds all the resource names contained in this directory within this jar file.
 * @param jarFileName The name of the jar file.
 * @param directory   The directory to look under.
 * @return The resource names.
 * @throws java.io.IOException when reading the jar file failed.
 */
private Set<String> findResourceNamesFromJarFile(String jarFileName,String directory) throws IOException {
  Set<String> resourceNames=new TreeSet<String>();
  JarFile jarFile=new JarFile(jarFileName);
  Enumeration<JarEntry> entries=jarFile.entries();
  while (entries.hasMoreElements()) {
    String entryName=entries.nextElement().getName();
    if (entryName.startsWith(directory)) {
      resourceNames.add(entryName);
    }
  }
  return resourceNames;
}
 

Example 9

From project gedcom5-conversion, under directory /src/test/java/org/gedcomx/tools/.

Source file: Gedcom2GedcomxTest.java

  18 
vote

private static void listContents(String ouputFile) throws IOException {
  JarFile jarFile=new JarFile(ouputFile);
  System.out.print("Main Attributes: ");
  printAttributes(jarFile.getManifest().getMainAttributes());
  Enumeration entries=jarFile.entries();
  while (entries.hasMoreElements()) {
    printEntry(entries.nextElement());
  }
}
 

Example 10

From project geronimo-xbean, under directory /xbean-blueprint/src/main/java/org/apache/xbean/blueprint/generator/.

Source file: QdoxMappingLoader.java

  18 
vote

private static void listAllJarEntries(File base,String[] excludedClasses,JavaDocBuilder builder) throws IOException {
  JarFile jarFile=new JarFile(base);
  for (Enumeration entries=jarFile.entries(); entries.hasMoreElements(); ) {
    JarEntry entry=(JarEntry)entries.nextElement();
    String name=entry.getName();
    if (name.endsWith(".java") && !isExcluded(name,excludedClasses) && !name.endsWith("/package-info.java")) {
      builder.addSource(new URL("jar:" + base.toURL().toString() + "!/"+ name));
    }
  }
}
 

Example 11

From project guice-automatic-injection, under directory /scanner/asm/src/main/java/de/devsurf/injection/guice/scanner/asm/.

Source file: ASMClasspathScanner.java

  18 
vote

private void visitJar(File file) throws IOException {
  if (_logger.isLoggable(Level.FINE)) {
    _logger.log(Level.FINE,"Scanning JAR-File: " + file.getAbsolutePath());
  }
  JarFile jarFile=new JarFile(file);
  _visitJar(jarFile);
}
 

Example 12

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

Source file: ManifestLoader.java

  18 
vote

public Manifest load(String jarPath) throws ManifestNotFound {
  final File jarFile=new File(jarPath);
  try {
    JarFile jar=new JarFile(jarFile);
    Manifest manifest=jar.getManifest();
    if (manifest == null) {
      throw new ManifestNotFound("Could not load manifest from jar:" + jarPath);
    }
    return manifest;
  }
 catch (  IOException e) {
    throw new ManifestNotFound("Could not load manifest from jar:" + jarPath,e);
  }
}
 

Example 13

From project Junit-DynamicSuite, under directory /src/main/java/org/junit/extensions/dynamicsuite/engine/.

Source file: ClassPathScanner.java

  18 
vote

private void addJar(File fromFile){
  JarFile jar=loadJarFile(fromFile);
  if (jar != null) {
    loadJarEntries(jar);
  }
}
 

Example 14

From project juzu, under directory /core/src/test/java/juzu/impl/fs/spi/jar/.

Source file: JarFileSystemTestCase.java

  18 
vote

@Test public void testFoo() throws Exception {
  URL url=Test.class.getProtectionDomain().getCodeSource().getLocation();
  System.out.println("url = " + url);
  JarFile file=new JarFile(new File(url.toURI()));
  final JarFileSystem filesystem=new JarFileSystem(file);
  filesystem.traverse(new Visitor.Default<JarPath>(){
    @Override public void enterDir(    JarPath dir,    String name) throws IOException {
      StringBuilder sb=new StringBuilder();
      filesystem.packageOf(dir,'/',sb);
      System.out.println("dir " + sb);
    }
  }
);
}
 

Example 15

From project linkedin-utils, under directory /org.linkedin.util-core/src/main/java/org/linkedin/util/io/resource/.

Source file: JarResource.java

  18 
vote

/** 
 * Important note: the caller of this method is responsible for properly closing the input stream!
 * @return an input stream to the resource.
 * @throws IOException if cannot get an input stream
 */
@Override public InputStream getInputStream() throws IOException {
  JarFile contentJarFile=getContentJarFile();
  try {
    CloseJarFileInputStream jarFileInputStream=new CloseJarFileInputStream(this,contentJarFile,_fullPath);
    contentJarFile=null;
    return jarFileInputStream;
  }
  finally {
    if (contentJarFile != null)     contentJarFile.close();
  }
}
 

Example 16

From project liquibase, under directory /liquibase-core/src/main/java/liquibase/integration/commandline/.

Source file: Main.java

  18 
vote

private void addWarFileClasspathEntries(File classPathFile,List<URL> urls) throws IOException {
  URL url=new URL("jar:" + classPathFile.toURL() + "!/WEB-INF/classes/");
  urls.add(url);
  JarFile warZip=new JarFile(classPathFile);
  Enumeration<? extends JarEntry> entries=warZip.entries();
  while (entries.hasMoreElements()) {
    JarEntry entry=entries.nextElement();
    if (entry.getName().startsWith("WEB-INF/lib") && entry.getName().toLowerCase().endsWith(".jar")) {
      File jar=extract(warZip,entry);
      urls.add(new URL("jar:" + jar.toURL() + "!/"));
      jar.deleteOnExit();
    }
  }
}
 

Example 17

From project ALP, under directory /workspace/alp-reporter/src/main/java/com/lohika/alp/reporter/helpers/.

Source file: Resources.java

  17 
vote

/** 
 * Copy own project resources to outside destination. <p> Works for regular files and JAR packages
 * @param clazz any java class that lives in the same place as the resources you want
 * @param path project resources path. Should end with "/", but not start with one
 * @param destination outside destination
 * @throws IOException
 */
public void copy(Class<?> clazz,String path,File destination) throws IOException {
  URL dirURL=clazz.getClassLoader().getResource(path);
  if (dirURL != null && dirURL.getProtocol().equals("file")) {
    logger.debug("Resources to copy is stored in file system " + dirURL);
    copy(new File(dirURL.getPath()),destination);
    return;
  }
  if (dirURL == null) {
    String me=clazz.getName().replace(".","/") + ".class";
    dirURL=clazz.getClassLoader().getResource(me);
  }
  logger.debug("Resources to copy is stored in jar " + dirURL);
  if (dirURL.getProtocol().equals("jar")) {
    String jarPath=dirURL.getPath().substring(5,dirURL.getPath().indexOf("!"));
    JarFile jar=new JarFile(URLDecoder.decode(jarPath,"UTF-8"));
    copy(jar,path,destination);
    return;
  }
  throw new UnsupportedOperationException("Cannot copy files from URL " + dirURL);
}
 

Example 18

From project any23, under directory /core/src/main/java/org/apache/any23/util/.

Source file: DiscoveryUtils.java

  17 
vote

/** 
 * Find all classes within a JAR in a given prefix addressed with syntax <code>file:<path/to.jar>!<path/to/package>.
 * @param location package location.
 * @return list of detected classes.
 */
private static List<Class> findClassesInJAR(String location){
  final String[] sections=location.split("!");
  if (sections.length != 2) {
    throw new IllegalArgumentException("Invalid JAR location.");
  }
  final String jarLocation=sections[0].substring(FILE_PREFIX.length());
  final String packagePath=sections[1].substring(1);
  try {
    final JarFile jarFile=new JarFile(jarLocation);
    final Enumeration<JarEntry> entries=jarFile.entries();
    final List<Class> result=new ArrayList<Class>();
    JarEntry current;
    String entryName;
    String clazzName;
    Class clazz;
    while (entries.hasMoreElements()) {
      current=entries.nextElement();
      entryName=current.getName();
      if (StringUtils.isPrefix(packagePath,entryName) && StringUtils.isSuffix(CLASS_SUFFIX,entryName) && !entryName.contains("$")) {
        try {
          clazzName=entryName.substring(0,entryName.length() - CLASS_SUFFIX.length()).replaceAll("/",".");
          clazz=Class.forName(clazzName);
        }
 catch (        ClassNotFoundException cnfe) {
          throw new IllegalStateException("Error while loading detected class.",cnfe);
        }
        result.add(clazz);
      }
    }
    return result;
  }
 catch (  IOException ioe) {
    throw new RuntimeException("Error while opening JAR file.",ioe);
  }
}
 

Example 19

From project apb, under directory /modules/apb-installer/src/apb/installer/.

Source file: Installer.java

  17 
vote

public void run() throws IOException {
  JarFile jar=new JarFile(jarFile);
  if (extract) {
    extract(jar,null,new File("./"));
  }
 else {
    if (libDir == null) {
      libDir=binDir;
    }
    generateScript();
    extract(jar,"bin/",binDir);
    extract(jar,"lib/",libDir);
    if (antlibDir != null) {
      extract(jar,"antlib/",antlibDir);
    }
  }
}
 

Example 20

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

Source file: AKFrameworkFactory.java

  17 
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 21

From project backend-update-center2, under directory /src/main/java/org/jvnet/hudson/update_center/.

Source file: MavenArtifact.java

  17 
vote

public Manifest getManifest() throws IOException {
  if (manifest == null) {
    File f=resolve();
    try {
      JarFile jar=new JarFile(f);
      ZipEntry e=jar.getEntry("META-INF/MANIFEST.MF");
      timestamp=e.getTime();
      manifest=jar.getManifest();
      jar.close();
    }
 catch (    IOException x) {
      throw (IOException)new IOException("Failed to open " + f).initCause(x);
    }
  }
  return manifest;
}
 

Example 22

From project BetterMechanics, under directory /src/net/edoxile/bettermechanics/handlers/.

Source file: ConfigHandler.java

  17 
vote

public static void createConfig(BetterMechanics plugin){
  configFile=new File(plugin.getDataFolder(),"config.yml");
  cauldronConfigFile=new File(plugin.getDataFolder(),"cauldron-recipes.yml");
  try {
    JarFile jar=new JarFile(plugin.getJarFile());
    JarEntry entry=jar.getJarEntry("config.yml");
    InputStream is=jar.getInputStream(entry);
    FileOutputStream os=new FileOutputStream(configFile);
    byte[] buf=new byte[(int)entry.getSize()];
    if (is.read(buf,0,(int)entry.getSize()) == (int)entry.getSize()) {
      os.write(buf);
      os.close();
    }
 else {
      BetterMechanics.log("Error while creating new config: buffer overflow",Level.WARNING);
    }
    jar=new JarFile(plugin.getJarFile());
    entry=jar.getJarEntry("cauldron-recipes.yml");
    is=jar.getInputStream(entry);
    os=new FileOutputStream(cauldronConfigFile);
    buf=new byte[(int)entry.getSize()];
    if (is.read(buf,0,(int)entry.getSize()) == (int)entry.getSize()) {
      os.write(buf);
      os.close();
    }
 else {
      BetterMechanics.log("Error while creating new cauldron-config: buffer overflow",Level.WARNING);
    }
  }
 catch (  IOException e) {
    BetterMechanics.log("Couldn't write to config file");
  }
}
 

Example 23

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

Source file: JarUtility.java

  17 
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 24

From project bndtools, under directory /bndtools.jareditor/src/bndtools/jareditor/internal/.

Source file: JARContentTreePart.java

  17 
vote

public void inputChanged(Viewer viewer,Object oldInput,Object newInput){
  entryMap=new TreeMap<String,ZipTreeNode>();
  URI uri=null;
  if (newInput instanceof IFileEditorInput) {
    uri=((IFileEditorInput)newInput).getFile().getLocationURI();
  }
 else   if (newInput instanceof IURIEditorInput) {
    uri=((IURIEditorInput)newInput).getURI();
  }
  if (uri != null) {
    JarFile jarFile=null;
    try {
      File ioFile=new File(uri);
      jarFile=new JarFile(ioFile);
      Enumeration<JarEntry> entries=jarFile.entries();
      while (entries.hasMoreElements()) {
        ZipTreeNode.addEntry(entryMap,entries.nextElement());
      }
    }
 catch (    IOException e) {
      Status status=new Status(IStatus.ERROR,PluginConstants.PLUGIN_ID,0,"I/O error reading JAR file contents",e);
      ErrorDialog.openError(managedForm.getForm().getShell(),"Error",null,status);
    }
 finally {
      try {
        if (jarFile != null) {
          jarFile.close();
        }
      }
 catch (      IOException e) {
      }
    }
  }
}
 

Example 25

From project byteman, under directory /agent/src/main/java/org/jboss/byteman/agent/.

Source file: TransformListener.java

  17 
vote

private void loadJars(BufferedReader in,PrintWriter out,boolean isBoot) throws IOException {
  final String endMarker=(isBoot) ? "ENDBOOT" : "ENDSYS";
  String line=in.readLine().trim();
  while (line != null && !line.equals(endMarker)) {
    try {
      JarFile jarfile=new JarFile(new File(line));
      retransformer.appendJarFile(out,jarfile,isBoot);
    }
 catch (    Exception e) {
      out.append("EXCEPTION ");
      out.append("Unable to add jar file " + line + "\n");
      out.append(e.toString());
      out.append("\n");
      e.printStackTrace(out);
    }
    line=in.readLine().trim();
  }
  if (line == null || !line.equals(endMarker)) {
    out.append("ERROR\n");
    out.append("Unexpected end of line reading " + ((isBoot) ? "boot" : "system") + " jars\n");
  }
  out.println("OK");
  out.flush();
}
 

Example 26

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

Source file: BuildInfo.java

  17 
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 27

From project ceylon-module-resolver, under directory /impl/src/main/java/com/redhat/ceylon/cmr/util/.

Source file: JarUtils.java

  17 
vote

public static void finishUpdatingJar(File originalFile,File outputFile,ArtifactContext context,JarOutputStream jarOutputStream,JarEntryFilter filter,RepositoryManager repoManager,boolean verbose,Logger log) throws IOException {
  if (originalFile != null) {
    JarFile jarFile=new JarFile(originalFile);
    Enumeration<JarEntry> entries=jarFile.entries();
    while (entries.hasMoreElements()) {
      JarEntry entry=entries.nextElement();
      if (filter.avoid(entry.getName()))       continue;
      ZipEntry copiedEntry=new ZipEntry(entry.getName());
      copiedEntry.setTime(entry.getTime());
      copiedEntry.setComment(entry.getComment());
      jarOutputStream.putNextEntry(copiedEntry);
      InputStream inputStream=jarFile.getInputStream(entry);
      copy(inputStream,jarOutputStream);
      inputStream.close();
      jarOutputStream.closeEntry();
    }
    jarFile.close();
  }
  jarOutputStream.flush();
  jarOutputStream.close();
  if (verbose) {
    log.info("[done writing to jar: " + outputFile.getPath() + "]");
  }
  File sha1File=ShaSigner.sign(outputFile,log,verbose);
  try {
    context.setForceOperation(true);
    repoManager.putArtifact(context,outputFile);
    ArtifactContext sha1Context=context.getSha1Context();
    sha1Context.setForceOperation(true);
    repoManager.putArtifact(sha1Context,sha1File);
  }
 catch (  RuntimeException x) {
    log.error("Failed to write module to repository: " + x.getMessage());
    throw x;
  }
 finally {
    outputFile.delete();
    sha1File.delete();
  }
}
 

Example 28

From project chukwa, under directory /src/main/java/org/apache/hadoop/chukwa/hicc/.

Source file: HiccWebServer.java

  17 
vote

public List<String> getResourceListing(String path) throws URISyntaxException, IOException {
  ClassLoader contextClassLoader=Thread.currentThread().getContextClassLoader();
  URL dirURL=contextClassLoader.getResource(path);
  if (dirURL == null) {
    dirURL=contextClassLoader.getResource(path);
  }
  if (dirURL.getProtocol().equals("jar")) {
    String jarPath=dirURL.getPath().substring(5,dirURL.getPath().indexOf("!"));
    JarFile jar=new JarFile(jarPath);
    Enumeration<JarEntry> entries=jar.entries();
    List<String> result=new ArrayList<String>();
    while (entries.hasMoreElements()) {
      String name=entries.nextElement().getName();
      if (name.startsWith(path)) {
        String entry=name.substring(path.length());
        int checkSubdir=entry.indexOf("/");
        if (checkSubdir == 0 && entry.length() > 1) {
          result.add(name);
        }
      }
    }
    return result;
  }
  throw new UnsupportedOperationException("Cannot list files for URL " + dirURL);
}
 

Example 29

From project cilia-workbench, under directory /cilia-workbench-common/src/fr/liglab/adele/cilia/workbench/common/xml/.

Source file: XMLHelpers.java

  17 
vote

/** 
 * Gets an Input stream from a file embedded in a jar archive.
 * @param jarFile the jar archive file, on the hard disk.
 * @param fileName the file name, in the archive. The file must be located at the archive root.
 * @return the input stream
 * @throws CiliaException if any error.
 */
public static InputStream inputStreamFromFileInJarArchive(File jarFile,String fileName) throws CiliaException {
  JarFile file;
  try {
    file=new JarFile(jarFile);
  }
 catch (  IOException e) {
    throw new CiliaException("Can't open jar file " + jarFile.getAbsolutePath(),e);
  }
  ZipEntry entry=file.getEntry(fileName);
  if (entry == null)   throw new CiliaException("File " + fileName + " not found in "+ jarFile.getAbsolutePath());
  BufferedInputStream is;
  try {
    is=new BufferedInputStream(file.getInputStream(entry));
  }
 catch (  IOException e) {
    throw new CiliaException("Can't access file " + fileName + " in jar file "+ jarFile.getAbsolutePath(),e);
  }
  return is;
}
 

Example 30

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

Source file: Commons.java

  17 
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 31

From project CloudReports, under directory /src/main/java/cloudreports/utils/.

Source file: FileIO.java

  17 
vote

/** 
 * List directory contents for a resource folder. Not recursive. This is basically a brute-force implementation. Works for regular files and also JARs.
 * @author Greg Briggs
 * @param clazz Any java class that lives in the same place as the resources you want.
 * @param path Should end with "/", but not start with one.
 * @return Just the name of each member item, not the full paths.
 * @throws URISyntaxException 
 * @throws IOException 
 */
public static String[] getResourceListing(Class clazz,String path) throws URISyntaxException, IOException {
  URL dirURL=clazz.getClassLoader().getResource(path);
  if (dirURL != null && dirURL.getProtocol().equals("file")) {
    return new File(dirURL.toURI()).list();
  }
  if (dirURL == null) {
    String me=clazz.getName().replace(".","/") + ".class";
    dirURL=clazz.getClassLoader().getResource(me);
  }
  if (dirURL.getProtocol().equals("jar")) {
    String jarPath=dirURL.getPath().substring(5,dirURL.getPath().indexOf("!"));
    JarFile jar=new JarFile(URLDecoder.decode(jarPath,"UTF-8"));
    Enumeration<JarEntry> entries=jar.entries();
    Set<String> result=new HashSet<String>();
    while (entries.hasMoreElements()) {
      String name=entries.nextElement().getName();
      if (name.startsWith(path)) {
        String entry=name.substring(path.length());
        int checkSubdir=entry.indexOf("/");
        if (checkSubdir >= 0) {
          entry=entry.substring(0,checkSubdir);
        }
        result.add(entry);
      }
    }
    return result.toArray(new String[result.size()]);
  }
  throw new UnsupportedOperationException("Cannot list files for URL " + dirURL);
}
 

Example 32

From project commons-compress, under directory /src/main/java/org/apache/commons/compress/compressors/pack200/.

Source file: Pack200Utils.java

  17 
vote

/** 
 * Normalizes a JAR archive so it can be safely signed and packed. <p>As stated in <a href="http://download.oracle.com/javase/1.5.0/docs/api/java/util/jar/Pack200.Packer.html">Pack200.Packer's</a> javadocs applying a Pack200 compression to a JAR archive will in general make its sigantures invalid.  In order to prepare a JAR for signing it should be "normalized" by packing and unpacking it.  This is what this method does.</p> <p>This method does not replace the existing archive but creates a new one.</p>
 * @param from the JAR archive to normalize
 * @param to the normalized archive
 * @param props properties to set for the pack operation.  Thismethod will implicitly set the segment limit to -1.
 */
public static void normalize(File from,File to,Map<String,String> props) throws IOException {
  if (props == null) {
    props=new HashMap<String,String>();
  }
  props.put(Pack200.Packer.SEGMENT_LIMIT,"-1");
  File f=File.createTempFile("commons-compress","pack200normalize");
  f.deleteOnExit();
  try {
    OutputStream os=new FileOutputStream(f);
    JarFile j=null;
    try {
      Pack200.Packer p=Pack200.newPacker();
      p.properties().putAll(props);
      p.pack(j=new JarFile(from),os);
      j=null;
      os.close();
      os=null;
      Pack200.Unpacker u=Pack200.newUnpacker();
      os=new JarOutputStream(new FileOutputStream(to));
      u.unpack(f,(JarOutputStream)os);
    }
  finally {
      if (j != null) {
        j.close();
      }
      if (os != null) {
        os.close();
      }
    }
  }
  finally {
    f.delete();
  }
}
 

Example 33

From project Core_2, under directory /plugin-loader/src/main/java/org/jboss/forge/loader/.

Source file: ModularPluginLoader.java

  17 
vote

@Override protected ModuleSpec findModule(final ModuleIdentifier id) throws ModuleLoadException {
  try {
    id.getName();
    id.getSlot();
    Builder builder=ModuleSpec.build(id);
    builder.addResourceRoot(ResourceLoaderSpec.createResourceLoaderSpec(ResourceLoaders.createJarResourceLoader("name-of-jar",new JarFile(new File("path to jar")))));
    builder.addDependency(DependencySpec.createLocalDependencySpec());
    builder.addDependency(DependencySpec.createModuleDependencySpec(ModuleIdentifier.create("org.jboss.forge")));
    return builder.create();
  }
 catch (  IOException e) {
    throw new ModuleLoadException("Failed to load module",e);
  }
}
 

Example 34

From project cp-common-utils, under directory /src/com/clarkparsia/common/util/.

Source file: ClassPath.java

  17 
vote

/** 
 * Returns the list of classes in the Jar file at the specified file location
 * @param theFile the file location of the jar
 * @return the list of classes in the jar file
 */
public static Collection<? extends Class> listClassesFromJar(File theFile){
  try {
    if (theFile.canRead()) {
      return listClassesFromJarFile(new JarFile(theFile));
    }
  }
 catch (  IOException e) {
    if (!QUIET) {
      e.printStackTrace();
    }
  }
  return new HashSet<Class>();
}
 

Example 35

From project dolphin, under directory /org.adarsh.jutils/src/com/tan/util/.

Source file: JarSearcher.java

  17 
vote

public void process(boolean searchClass){
  JarFile jarFile=null;
  JarEntry jarEntry=null;
  String name;
  File file;
  Enumeration<JarEntry> entries;
  for (Iterator<File> iter=lists.iterator(); iter.hasNext(); ) {
    file=(File)iter.next();
    try {
      jarFile=new JarFile(file);
    }
 catch (    IOException e) {
      e.printStackTrace();
    }
    if (null != jarFile) {
      entries=jarFile.entries();
      while (entries.hasMoreElements()) {
        jarEntry=(JarEntry)entries.nextElement();
        name=jarEntry.getName();
        name=name.toLowerCase();
        if (searchClass) {
          searchClass(name,file,jarEntry);
        }
 else {
          searchJarContent(name,jarFile,jarEntry);
        }
      }
    }
  }
}
 

Example 36

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

Source file: AboutTab.java

  17 
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 37

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

Source file: Osgiify.java

  17 
vote

private static TreeSet<String> findPackages(File file) throws IOException {
  TreeSet<String> result=new TreeSet<String>();
  JarFile jarFile=new JarFile(file);
  try {
    for (Enumeration<JarEntry> e=jarFile.entries(); e.hasMoreElements(); ) {
      JarEntry entry=e.nextElement();
      if (entry.getName().endsWith(".class")) {
        int index=entry.getName().lastIndexOf('/');
        if (index > 0) {
          String packageName=entry.getName().substring(0,index).replace('/','.');
          result.add(packageName);
        }
      }
    }
  }
  finally {
    jarFile.close();
  }
  return result;
}
 

Example 38

From project etherpad, under directory /infrastructure/yuicompressor/src/com/yahoo/platform/yui/compressor/.

Source file: JarClassLoader.java

  17 
vote

private static String getJarPath(){
  if (jarPath != null) {
    return jarPath;
  }
  String classname=JarClassLoader.class.getName().replace('.','/') + ".class";
  String classpath=System.getProperty("java.class.path");
  String classpaths[]=classpath.split(System.getProperty("path.separator"));
  for (int i=0; i < classpaths.length; i++) {
    String path=classpaths[i];
    JarFile jarFile=null;
    JarEntry jarEntry=null;
    try {
      jarFile=new JarFile(path);
      jarEntry=findJarEntry(jarFile,classname);
    }
 catch (    IOException ioe) {
    }
 finally {
      if (jarFile != null) {
        try {
          jarFile.close();
        }
 catch (        IOException ioe) {
        }
      }
    }
    if (jarEntry != null) {
      jarPath=path;
      break;
    }
  }
  return jarPath;
}
 

Example 39

From project flapjack, under directory /flapjack-annotation/src/main/java/flapjack/annotation/util/.

Source file: JarFileClassLocator.java

  17 
vote

protected void findClasses(List<Class> classes,URL url,Pattern packageName){
  JarFile jarFile=null;
  try {
    JarURLConnection connection=(JarURLConnection)url.openConnection();
    connection.setUseCaches(false);
    jarFile=connection.getJarFile();
    Enumeration<JarEntry> entries=jarFile.entries();
    while (entries.hasMoreElements()) {
      JarEntry entry=entries.nextElement();
      if (isClass(entry) && isInPackage(entry,packageName)) {
        String fixedPath=entry.getName().replace("/",".");
        classes.add(loadClass(fixedPath.substring(0,fixedPath.lastIndexOf('.'))));
      }
    }
  }
 catch (  IOException e) {
    throw new RuntimeException(e);
  }
catch (  ClassNotFoundException e) {
    throw new RuntimeException(e);
  }
 finally {
    if (jarFile != null) {
      try {
        jarFile.close();
      }
 catch (      IOException e) {
      }
    }
  }
}
 

Example 40

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

Source file: BundleClassPathWildcardTest.java

  17 
vote

private void testJarConnectionOn(Resource jar) throws Exception {
  String toString=jar.getURL().toExternalForm();
  String urlString="jar:" + toString + "!/";
  URL newURL=new URL(urlString);
  System.out.println(newURL);
  System.out.println(newURL.toExternalForm());
  URLConnection con=newURL.openConnection();
  System.out.println(con);
  System.out.println(con instanceof JarURLConnection);
  JarURLConnection jarCon=(JarURLConnection)con;
  JarFile jarFile=jarCon.getJarFile();
  System.out.println(jarFile.getName());
  Enumeration enm=jarFile.entries();
  while (enm.hasMoreElements())   System.out.println(enm.nextElement());
}
 

Example 41

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

Source file: WebappConfigLocator.java

  17 
vote

private static URL resolveWebappContextXmlFromJarURLConnection(Bundle bundle){
  URL bundleUrl;
  try {
    bundleUrl=new URL(JAR_SCHEMA + bundle.getLocation() + JAR_TO_ENTRY_SEPARATOR+ CONTEXT_XML);
  }
 catch (  MalformedURLException e) {
    return null;
  }
  JarFile jarFile=null;
  try {
    URLConnection connection=bundleUrl.openConnection();
    if (connection instanceof JarURLConnection) {
      JarURLConnection jarURLConnection=(JarURLConnection)connection;
      jarURLConnection.setUseCaches(false);
      jarFile=jarURLConnection.getJarFile();
      String entryName=jarURLConnection.getEntryName();
      if (entryName != null && jarFile != null && jarFile.getEntry(entryName) != null) {
        return bundleUrl;
      }
    }
  }
 catch (  IOException e) {
    return null;
  }
 finally {
    if (jarFile != null) {
      try {
        jarFile.close();
      }
 catch (      IOException _) {
      }
    }
  }
  return null;
}
 

Example 42

From project GraphLab, under directory /src/graphlab/platform/plugin/.

Source file: Plugger.java

  17 
vote

/** 
 * Read manifest of a jar file and make that plugin candidate to be loaded.
 * @param ff file object
 */
public void init(File ff){
  try {
    JarFile jf=new JarFile(ff);
    System.out.println("------------------------------------------------------------");
    String name=jf.getManifest().getMainAttributes().getValue("plugin-name");
    String verStr=jf.getManifest().getMainAttributes().getValue("plugin-version");
    String dependsStr=jf.getManifest().getMainAttributes().getValue("plugin-depends");
    if (name == null || verStr == null) {
      System.out.println("Skipping " + name + "("+ verStr+ ")");
      return;
    }
    Long ver=Long.parseLong(verStr);
    System.out.println("Detected " + name + "("+ ver+ ") ...");
    for (    Entry<Object,Object> s : jf.getManifest().getMainAttributes().entrySet()) {
      if (!"plugin-name".equals(s.getKey()) && !"plugin-version".equals(s.getKey()))       System.out.println(s.getKey() + " : " + s.getValue());
    }
    ArrayList<Object[]> dependsArray=new ArrayList<Object[]>();
    if (dependsStr != null) {
      StringTokenizer st=new StringTokenizer(dependsStr);
      while (st.hasMoreElements()) {
        String depName=st.nextToken();
        String depVerStr=st.nextToken();
        Long depVer=Long.parseLong(depVerStr);
        dependsArray.add(new Object[]{depName,depVer});
      }
    }
    versions.put(name,ver);
    mark.put(name,-1);
    files.put(name,ff);
    childs.put(name,new ArrayList<String>());
    depends.put(name,dependsArray);
    initializer.put(name,jf.getManifest().getMainAttributes().getValue("plugin-initializer"));
    configxml.put(name,jf.getManifest().getMainAttributes().getValue("plugin-configxml"));
  }
 catch (  Exception ex) {
    ex.printStackTrace();
  }
}
 

Example 43

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

Source file: Configurator.java

  17 
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 44

From project hecl, under directory /build-tools/.

Source file: BBJDEVersion.java

  17 
vote

public static void main(String[] args){
  try {
    if (args.length == 0) {
      throw new Exception("Need a jar file to process!");
    }
    JarFile jf=new JarFile(args[0]);
    JarEntry entry=jf.getJarEntry("app.version");
    InputStream is=jf.getInputStream(entry);
    byte[] buf=new byte[4096];
    is.read(buf);
    String sversion=(new String(buf)).trim();
    String[] res=sversion.split("\\.");
    System.out.println(res[0] + "." + res[1]);
    jf.close();
  }
 catch (  Exception e) {
    System.err.println("BBJDEVersion Exception: " + e.toString());
    System.exit(-1);
  }
}
 

Example 45

From project HiTune_1, under directory /chukwa-hitune-dist/src/java/org/apache/hadoop/chukwa/hicc/.

Source file: HiccWebServer.java

  17 
vote

public List<String> getResourceListing(String path) throws URISyntaxException, IOException {
  ClassLoader contextClassLoader=Thread.currentThread().getContextClassLoader();
  URL dirURL=contextClassLoader.getResource(path);
  if (dirURL == null) {
    dirURL=contextClassLoader.getResource(path);
  }
  if (dirURL.getProtocol().equals("jar")) {
    String jarPath=dirURL.getPath().substring(5,dirURL.getPath().indexOf("!"));
    JarFile jar=new JarFile(jarPath);
    Enumeration<JarEntry> entries=jar.entries();
    List<String> result=new ArrayList<String>();
    while (entries.hasMoreElements()) {
      String name=entries.nextElement().getName();
      if (name.startsWith(path)) {
        String entry=name.substring(path.length());
        int checkSubdir=entry.indexOf("/");
        if (checkSubdir == 0 && entry.length() > 1) {
          result.add(name);
        }
      }
    }
    return result;
  }
  throw new UnsupportedOperationException("Cannot list files for URL " + dirURL);
}
 

Example 46

From project ihtika, under directory /Incubator/ForInstaller/PackLibs/src/com/google/code/ihtika/IhtikaClient/packlibs/.

Source file: Pack.java

  17 
vote

private void recursivePack(File currentDir){
  Pack200.Packer packer=Pack200.newPacker();
  Map p=packer.properties();
  p.put(packer.EFFORT,"9");
  FileFilter filefilter=new FileFilter(){
    @Override public boolean accept(    File file){
      if ((file.getName().endsWith(".jar") || file.getName().endsWith(".jar.svn-base")) && !file.getName().equals("PackLibs.jar")) {
        return true;
      }
      return false;
    }
  }
;
  for (  File lib : currentDir.listFiles(filefilter)) {
    try {
      throw new Exception();
    }
 catch (    Exception ex) {
    }
    try {
      System.out.println("Processing file " + lib.getAbsolutePath());
      JarFile jarFile=new JarFile(lib);
      FileOutputStream fos=new FileOutputStream(lib.getAbsolutePath() + PACKEXT);
      packer.pack(jarFile,fos);
      jarFile.close();
      fos.close();
      gZip.gzipFile(lib.getAbsolutePath() + PACKEXT,lib.getAbsolutePath() + PACKEXT + ".gz");
      new File(lib.getAbsolutePath() + PACKEXT).delete();
      lib.delete();
    }
 catch (    Exception ex) {
    }
  }
  for (  File dir : currentDir.listFiles()) {
    if (dir.isDirectory()) {
      recursivePack(dir);
    }
  }
}
 

Example 47

From project imageflow, under directory /src/de/danielsenff/imageflow/controller/.

Source file: JarUnitXMLLoader.java

  17 
vote

/** 
 * Reads contents of a jar file and manages the traversal of the file tree.
 * @param node 
 * @param url 
 * @throws MalformedURLException 
 */
public void readDelegates(UnitMutableTreeNode node,URL url) throws MalformedURLException {
  String jarPath=url.getPath().substring(5,url.getPath().indexOf("!"));
  try {
    JarFile jar=new JarFile(URLDecoder.decode(jarPath,"UTF-8"));
    Enumeration<JarEntry> entries=jar.entries();
    retrieveRelevantXMLPaths(entries,relevantXmlFiles);
    String[] paths=sortPaths(relevantXmlFiles);
    for (    String unitPath : paths) {
      reflectUnitsInMenu(getEntries(),node,unitPath,"",url);
    }
  }
 catch (  java.io.UnsupportedEncodingException e) {
    e.printStackTrace();
  }
catch (  java.io.IOException e) {
    e.printStackTrace();
  }
}
 

Example 48

From project incubator-s4, under directory /subprojects/s4-core/src/main/java/org/apache/s4/core/.

Source file: Server.java

  17 
vote

public App loadApp(File s4r,String appName){
  logger.info("Loading application [{}] from file [{}]",appName,s4r.getAbsolutePath());
  S4RLoaderFactory loaderFactory=injector.getInstance(S4RLoaderFactory.class);
  S4RLoader cl=loaderFactory.createS4RLoader(s4r.getAbsolutePath());
  try {
    JarFile s4rFile=new JarFile(s4r);
    if (s4rFile.getManifest() == null) {
      logger.warn("Cannot load s4r archive [{}] : missing manifest file");
      return null;
    }
    if (!s4rFile.getManifest().getMainAttributes().containsKey(new Name(MANIFEST_S4_APP_CLASS))) {
      logger.warn("Cannot load s4r archive [{}] : missing attribute [{}] in manifest",s4r.getAbsolutePath(),MANIFEST_S4_APP_CLASS);
      return null;
    }
    String appClassName=s4rFile.getManifest().getMainAttributes().getValue(MANIFEST_S4_APP_CLASS);
    logger.info("App class name is: " + appClassName);
    App app=null;
    try {
      Object o=(cl.loadClass(appClassName)).newInstance();
      app=(App)o;
      injector.injectMembers(app);
    }
 catch (    Exception e) {
      logger.error("Could not load s4 application form s4r file [{" + s4r.getAbsolutePath() + "}]",e);
      return null;
    }
    logger.info("Loaded application from file {}",s4r.getAbsolutePath());
    signalOneAppLoaded.countDown();
    return app;
  }
 catch (  IOException e) {
    logger.error("Could not load s4 application form s4r file [{" + s4r.getAbsolutePath() + "}]",e);
    return null;
  }
}
 

Example 49

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

Source file: BuildInfo.java

  17 
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 50

From project ipdburt, under directory /iddb-cli/src/main/java/iddb/cli/.

Source file: ClassFinder.java

  17 
vote

private void includeJar(File file,Map<URL,String> map){
  if (file.isDirectory())   return;
  URL jarURL=null;
  JarFile jar=null;
  try {
    jarURL=new URL("file:/" + file.getCanonicalPath());
    jarURL=new URL("jar:" + jarURL.toExternalForm() + "!/");
    JarURLConnection conn=(JarURLConnection)jarURL.openConnection();
    jar=conn.getJarFile();
  }
 catch (  Exception e) {
    return;
  }
  if (jar == null || jarURL == null)   return;
  map.put(jarURL,"");
  Enumeration<JarEntry> e=jar.entries();
  while (e.hasMoreElements()) {
    JarEntry entry=e.nextElement();
    if (entry.isDirectory()) {
      if (entry.getName().toUpperCase().equals("META-INF/"))       continue;
      try {
        map.put(new URL(jarURL.toExternalForm() + entry.getName()),packageNameFor(entry));
      }
 catch (      MalformedURLException murl) {
        continue;
      }
    }
  }
}
 

Example 51

From project james-mime4j, under directory /core/src/test/java/org/apache/james/mime4j/parser/.

Source file: MimeStreamParserExampleMessagesTest.java

  17 
vote

private void addTests(String testsFolder) throws URISyntaxException, MalformedURLException, IOException {
  URL resource=MimeStreamParserExampleMessagesTestSuite.class.getResource(testsFolder);
  if (resource != null) {
    if (resource.getProtocol().equalsIgnoreCase("file")) {
      File dir=new File(resource.toURI());
      File[] files=dir.listFiles();
      for (      File f : files) {
        if (f.getName().endsWith(".msg")) {
          addTest(new MimeStreamParserExampleMessagesTest(f.getName(),f.toURI().toURL()));
        }
      }
    }
 else     if (resource.getProtocol().equalsIgnoreCase("jar")) {
      JarURLConnection conn=(JarURLConnection)resource.openConnection();
      JarFile jar=conn.getJarFile();
      for (Enumeration<JarEntry> it=jar.entries(); it.hasMoreElements(); ) {
        JarEntry entry=it.nextElement();
        String s="/" + entry.toString();
        File f=new File(s);
        if (s.startsWith(testsFolder) && s.endsWith(".msg")) {
          addTest(new MimeStreamParserExampleMessagesTest(f.getName(),new URL("jar:file:" + jar.getName() + "!"+ s)));
        }
      }
    }
  }
}
 

Example 52

From project jarjar-maven-plugin, under directory /src/main/java/com/tonicsystems/jarjar/util/.

Source file: StandaloneJarProcessor.java

  17 
vote

public static void run(File from,File to,JarProcessor proc,boolean ignoreDuplicates) throws IOException {
  byte[] buf=new byte[0x2000];
  JarFile in=new JarFile(from);
  final File tmpTo=File.createTempFile("jarjar",".jar");
  JarOutputStream out=new JarOutputStream(new FileOutputStream(tmpTo));
  Set<String> entries=new HashSet<String>();
  try {
    EntryStruct struct=new EntryStruct();
    Enumeration<JarEntry> e=in.entries();
    while (e.hasMoreElements()) {
      JarEntry entry=e.nextElement();
      struct.name=entry.getName();
      struct.time=entry.getTime();
      ByteArrayOutputStream baos=new ByteArrayOutputStream();
      IoUtil.pipe(in.getInputStream(entry),baos,buf);
      struct.data=baos.toByteArray();
      if (proc.process(struct)) {
        if (entries.add(struct.name)) {
          entry=new JarEntry(struct.name);
          entry.setTime(struct.time);
          entry.setCompressedSize(-1);
          out.putNextEntry(entry);
          out.write(struct.data);
        }
 else         if (struct.name.endsWith("/")) {
        }
 else         if (!ignoreDuplicates) {
          throw new IllegalArgumentException("Duplicate jar entries: " + struct.name);
        }
      }
    }
  }
  finally {
    in.close();
    out.close();
  }
  IoUtil.copyZipWithoutEmptyDirectories(tmpTo,to);
  tmpTo.delete();
}
 

Example 53

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

Source file: JarFileResourceLoader.java

  17 
vote

public Resource getResource(String name){
  try {
    final JarFile jarFile=this.jarFile;
    if (name.startsWith("/"))     name=name.substring(1);
    final JarEntry entry=getJarEntry(name);
    if (entry == null) {
      return null;
    }
    return new JarEntryResource(jarFile,entry,getJarURI(new File(jarFile.getName()).toURI(),entry.getName()).toURL());
  }
 catch (  MalformedURLException e) {
    return null;
  }
catch (  URISyntaxException e) {
    return null;
  }
}
 

Example 54

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

Source file: JavaZipFileSystem.java

  17 
vote

/** 
 * Create a new instance.
 * @param archiveFile the original archive file
 * @param tempDir the temp dir into which zip information is stored
 * @throws java.io.IOException if an I/O error occurs
 */
public JavaZipFileSystem(File archiveFile,TempDir tempDir) throws IOException {
  zipTime=archiveFile.lastModified();
  final JarFile zipFile;
  this.zipFile=zipFile=new JarFile(archiveFile);
  this.archiveFile=archiveFile;
  this.tempDir=tempDir;
  final Enumeration<? extends JarEntry> entries=zipFile.entries();
  final ZipNode rootNode=new ZipNode(new HashMap<String,ZipNode>(),"",null);
  FILES:   for (  JarEntry entry : iter(entries)) {
    final String name=entry.getName();
    final boolean isDirectory=entry.isDirectory();
    final List<String> tokens=PathTokenizer.getTokens(name);
    ZipNode node=rootNode;
    final Iterator<String> it=tokens.iterator();
    while (it.hasNext()) {
      String token=it.next();
      if (PathTokenizer.isCurrentToken(token) || PathTokenizer.isReverseToken(token)) {
        continue FILES;
      }
      final Map<String,ZipNode> children=node.children;
      if (children == null) {
        continue FILES;
      }
      ZipNode child=children.get(token);
      if (child == null) {
        child=it.hasNext() || isDirectory ? new ZipNode(new HashMap<String,ZipNode>(),token,null) : new ZipNode(null,token,entry);
        children.put(token,child);
      }
      node=child;
    }
  }
  this.rootNode=rootNode;
  contentsDir=tempDir.getFile("contents");
  contentsDir.mkdir();
  log.tracef("Created zip filesystem for file %s in temp dir %s",archiveFile,tempDir);
}
 

Example 55

From project jmd, under directory /src/net/contra/jmd/transformers/allatori/.

Source file: AllatoriTransformer.java

  17 
vote

public AllatoriTransformer(String jarfile,boolean strong) throws Exception {
  logger.log("Allatori Deobfuscator");
  isStrong=strong;
  File jar=new File(jarfile);
  JAR_NAME=jarfile;
  JarFile jf=new JarFile(jar);
  Enumeration<JarEntry> entries=jf.entries();
  while (entries.hasMoreElements()) {
    JarEntry entry=entries.nextElement();
    if (entry == null) {
      break;
    }
    if (entry.getName().endsWith(".class")) {
      ClassGen cg=new ClassGen(new ClassParser(jf.getInputStream(entry),entry.getName()).parse());
      if (isStringClass(cg) || isStringClassB(cg)) {
        ALLATORI_CLASS=cg;
        logger.debug("Allatori Class: " + ALLATORI_CLASS.getClassName());
      }
      cgs.put(cg.getClassName(),cg);
    }
 else {
      NonClassEntries.add(entry,jf.getInputStream(entry));
    }
  }
}
 

Example 56

From project jumpnevolve, under directory /src/com/googlecode/jumpnevolve/game/menu/.

Source file: LevelSelection.java

  17 
vote

private ArrayList<String> jarFileSearch(){
  ArrayList<String> re=new ArrayList<String>();
  JarFile jFile=JarHandler.getJarFile();
  Enumeration<JarEntry> jEntries=jFile.entries();
  while (jEntries.hasMoreElements()) {
    JarEntry jEntry=jEntries.nextElement();
    if (jEntry.getName().endsWith(".txt") || jEntry.getName().endsWith(".lvl")) {
      String entryName=jEntry.getName();
      if (entryName.startsWith(this.levelPath.substring(1))) {
        entryName=entryName.replaceAll(this.levelPath.substring(1),"");
        re.add(entryName);
      }
    }
  }
  return re;
}
 

Example 57

From project karaf, under directory /deployer/wrap/src/main/java/org/apache/karaf/deployer/wrap/.

Source file: WrapDeploymentListener.java

  17 
vote

public boolean canHandle(File artifact){
  try {
    if (!artifact.getPath().endsWith(".jar")) {
      return false;
    }
    JarFile jar=new JarFile(artifact);
    try {
      Manifest manifest=jar.getManifest();
      if (manifest != null && manifest.getMainAttributes().getValue(new Attributes.Name("Bundle-SymbolicName")) != null && manifest.getMainAttributes().getValue(new Attributes.Name("Bundle-Version")) != null) {
        return false;
      }
      return true;
    }
  finally {
      jar.close();
    }
  }
 catch (  Exception e) {
    return false;
  }
}
 

Example 58

From project kevoree-library, under directory /kalimucho/org.kevoree.library.kalimucho.kalimuchoNode/src/main/java/platform/plugins/installables/jarRepository/.

Source file: JarRepositoryManager.java

  17 
vote

private void scanRepository(String type,HashMap<String,String> liste){
  String chemin=new String(Parameters.COMPONENTS_REPOSITORY + "/" + type);
  File depot=new File(chemin);
  File[] fichiers=depot.listFiles();
  for (int i=0; i < fichiers.length; i++) {
    if (fichiers[i].isFile()) {
      if (fichiers[i].getName().endsWith(".jar")) {
        try {
          JarFile accesJar=new JarFile(fichiers[i]);
          Manifest manifest=accesJar.getManifest();
          String classeCM=manifest.getMainAttributes().getValue(KalimuchoClassLoader.BC_CLASS);
          liste.put(classeCM,fichiers[i].getName());
        }
 catch (        IOException ioe) {
          System.err.println("Can't access to jar file " + fichiers[i].getName() + " in "+ chemin);
        }
      }
    }
  }
}
 

Example 59

From project knime-scripting, under directory /groovy4knime/src/de/mpicbg/tds/knime/scripting/util/.

Source file: PluginClassLoader.java

  17 
vote

private List<URL> collectDependcyJarURLs(URL pluginJarURL){
  List<URL> dependencyURLs=new ArrayList<URL>();
  try {
    JarFile jar=new JarFile(new File(pluginJarURL.toURI()));
    Enumeration<JarEntry> jarentries=jar.entries();
    while (jarentries.hasMoreElements()) {
      JarEntry jarEntry=jarentries.nextElement();
      String jarEntryName=jarEntry.getName();
      if (jarEntryName.endsWith(".jar")) {
        String pluginInDepUrl="jar:jarjar:" + pluginJarURL.toString() + "^/"+ jarEntryName+ "!/";
        dependencyURLs.add(new URL(pluginInDepUrl));
      }
    }
  }
 catch (  Throwable t) {
    throw new RuntimeException(t);
  }
  return dependencyURLs;
}
 

Example 60

From project l2jserver2, under directory /l2jserver2-gameserver/l2jserver2-gameserver-core/src/main/java/com/l2jserver/service/game/scripting/impl/ecj/.

Source file: EclipseCompilerScriptClassLoader.java

  17 
vote

/** 
 * AddsLibrary jar
 * @param file jar file to add
 * @throws IOException if any I/O error occur
 */
@Override public void addLibrary(File file) throws IOException {
  URL fileURL=file.toURI().toURL();
  addURL(fileURL);
  JarFile jarFile=new JarFile(file);
  Enumeration<JarEntry> entries=jarFile.entries();
  while (entries.hasMoreElements()) {
    JarEntry entry=entries.nextElement();
    String name=entry.getName();
    if (name.endsWith(".class")) {
      name=name.substring(0,name.length() - 6);
      name=name.replace('/','.');
      libraryClasses.add(name);
    }
  }
  jarFile.close();
}
 

Example 61

From project la-clojure, under directory /src/org/jetbrains/plugins/clojure/config/.

Source file: ClojureConfigUtil.java

  17 
vote

static boolean checkLibrary(Library library,String jarNamePrefix,String necessaryClass){
  boolean result=false;
  VirtualFile[] classFiles=library.getFiles(OrderRootType.CLASSES);
  for (  VirtualFile file : classFiles) {
    String path=file.getPath();
    if (path != null && "jar".equals(file.getExtension())) {
      path=StringUtil.trimEnd(path,"!/");
      String name=file.getName();
      File realFile=new File(path);
      if (realFile.exists()) {
        try {
          JarFile jarFile=new JarFile(realFile);
          if (name.startsWith(jarNamePrefix)) {
            result=jarFile.getJarEntry(necessaryClass) != null;
          }
          jarFile.close();
        }
 catch (        IOException e) {
          result=false;
        }
      }
    }
  }
  return result;
}
 

Example 62

From project Application-Builder, under directory /src/main/java/org/silverpeas/applicationbuilder/.

Source file: ReadOnlyArchive.java

  16 
vote

/** 
 * Sets the Archive file
 * @since 1.0
 */
private void setJar() throws AppBuilderException {
  if (!getPath().exists()) {
    throw new AppBuilderException(getPath().getAbsolutePath() + " not found");
  }
  if (!getPath().isFile()) {
    throw new AppBuilderException(getPath().getAbsolutePath() + " is not a file");
  }
  if (!getPath().canRead()) {
    throw new AppBuilderException(getPath().getAbsolutePath() + " is not readable");
  }
  try {
    myJar=new JarFile(getPath(),false);
  }
 catch (  IOException ioe) {
    throw new AppBuilderException(getName() + " : could not instantiate JarFile",ioe);
  }
}
 

Example 63

From project Blitz, under directory /src/com/laxser/blitz/scanning/vfs/.

Source file: JarFileObject.java

  16 
vote

JarFileObject(FileSystemManager fs,URL url) throws FileNotFoundException, IOException {
  this.fs=fs;
  String urlString=url.toString();
  String entryName=urlString.substring(urlString.indexOf(ResourceUtils.JAR_URL_SEPARATOR) + ResourceUtils.JAR_URL_SEPARATOR.length());
  if (entryName.length() == 0) {
    this.root=this;
    int beginIndex=urlString.indexOf(ResourceUtils.FILE_URL_PREFIX) + ResourceUtils.FILE_URL_PREFIX.length();
    int endIndex=urlString.indexOf(ResourceUtils.JAR_URL_SEPARATOR);
    this.jarFile=new JarFile(urlString.substring(beginIndex,endIndex));
  }
 else {
    this.root=(JarFileObject)fs.resolveFile(urlString.substring(0,urlString.indexOf(ResourceUtils.JAR_URL_SEPARATOR) + ResourceUtils.JAR_URL_SEPARATOR.length()));
    this.jarFile=root.jarFile;
  }
  this.entry=jarFile.getJarEntry(entryName);
  this.url=url;
  this.urlString=urlString;
  int indexSep=entryName.lastIndexOf('/');
  if (indexSep == -1) {
    this.fileName=new FileNameImpl(this,entryName);
  }
 else {
    if (entryName.endsWith("/")) {
      int index=entryName.lastIndexOf('/',entryName.length() - 2);
      this.fileName=new FileNameImpl(this,entryName.substring(index + 1,indexSep));
    }
 else {
      this.fileName=new FileNameImpl(this,entryName.substring(indexSep + 1));
    }
  }
}
 

Example 64

From project LateralGM, under directory /org/lateralgm/main/.

Source file: LGM.java

  16 
vote

public static void loadPlugins(){
  File dir=new File(workDir.getParent(),"plugins");
  if (!dir.exists())   dir=new File(workDir.getParent(),"Plugins");
  File[] ps=dir.listFiles(new CustomFileFilter(null,".jar"));
  if (ps == null)   return;
  for (  File f : ps) {
    if (!f.exists())     continue;
    try {
      String pluginEntry="LGM-Plugin";
      Manifest mf=new JarFile(f).getManifest();
      String clastr=mf.getMainAttributes().getValue(pluginEntry);
      if (clastr == null)       throw new Exception(Messages.format("LGM.PLUGIN_MISSING_ENTRY",pluginEntry));
      URLClassLoader ucl=new URLClassLoader(new URL[]{f.toURI().toURL()});
      ucl.loadClass(clastr).newInstance();
    }
 catch (    Exception e) {
      String msgInd="LGM.PLUGIN_LOAD_ERROR";
      System.out.println(Messages.format(msgInd,f.getName(),e.getClass().getName(),e.getMessage()));
      continue;
    }
  }
}
 

Example 65

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

Source file: SignApk.java

  15 
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 66

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

Source file: AbstractOSGiApplicationArchiveProcessor.java

  15 
vote

private void enhanceApplicationArchive(Archive<?> appArchive,TestClass testClass,Manifest manifest){
  if (ClassContainer.class.isAssignableFrom(appArchive.getClass()) == false)   throw new IllegalArgumentException("ClassContainer expected: " + appArchive);
  Class<?> javaClass=testClass.getJavaClass();
  String path=javaClass.getName().replace('.','/') + ".class";
  if (appArchive.contains(path) == false)   ((ClassContainer<?>)appArchive).addClass(javaClass);
  final OSGiManifestBuilder builder=OSGiManifestBuilder.newInstance();
  Attributes attributes=manifest.getMainAttributes();
  for (  Entry<Object,Object> entry : attributes.entrySet()) {
    String key=entry.getKey().toString();
    String value=(String)entry.getValue();
    if (key.equals("Manifest-Version"))     continue;
    if (key.equals(Constants.IMPORT_PACKAGE)) {
      String[] imports=value.split(",");
      builder.addImportPackages(imports);
      continue;
    }
    if (key.equals(Constants.EXPORT_PACKAGE)) {
      String[] exports=value.split(",");
      builder.addExportPackages(exports);
      continue;
    }
    builder.addManifestHeader(key,value);
  }
  builder.addExportPackages(javaClass);
  addImportsForClass(builder,javaClass);
  builder.addImportPackages("org.jboss.arquillian.container.test.api","org.jboss.arquillian.junit","org.jboss.arquillian.osgi","org.jboss.arquillian.test.api");
  builder.addImportPackages("org.jboss.shrinkwrap.api","org.jboss.shrinkwrap.api.asset","org.jboss.shrinkwrap.api.spec");
  builder.addImportPackages("org.junit","org.junit.runner","javax.inject","org.osgi.framework");
  appArchive.delete(ArchivePaths.create(JarFile.MANIFEST_NAME));
  appArchive.add(new Asset(){
    public InputStream openStream(){
      return builder.openStream();
    }
  }
,JarFile.MANIFEST_NAME);
}
 

Example 67

From project com.idega.content, under directory /src/java/com/idega/content/themes/business/.

Source file: TemplatesLoader.java

  15 
vote

public void loadJar(File bundleJarFile,JarFile jarFile,String jarPath){
  JarEntry pageTemplatesEntry=jarFile.getJarEntry("resources/templates/" + PAGE_TEMPLATES_XML_FILE_NAME);
  JarEntry siteTemplatesEntry=jarFile.getJarEntry("resources/templates/" + SITE_TEMPLATES_XML_FILE_NAME);
  InputStream stream=null;
  if (pageTemplatesEntry != null) {
    try {
      stream=jarFile.getInputStream(pageTemplatesEntry);
      Document pageDocument=XmlUtil.getJDOMXMLDocument(stream);
      addPageTypesFromDocument(pageDocument);
    }
 catch (    Exception e) {
      e.printStackTrace();
    }
 finally {
      IOUtil.closeInputStream(stream);
    }
  }
  if (siteTemplatesEntry != null) {
    try {
      stream=jarFile.getInputStream(siteTemplatesEntry);
      Document pageDocument=XmlUtil.getJDOMXMLDocument(stream);
      addSiteTemplatesFromDocument(pageDocument);
    }
 catch (    Exception e) {
      e.printStackTrace();
    }
 finally {
      IOUtil.closeInputStream(stream);
    }
  }
}
 

Example 68

From project Custom-Salem, under directory /src/haven/.

Source file: JarSignersHardLinker.java

  15 
vote

protected static void makeHardSignersRef(JarFile jar) throws java.io.IOException {
  System.out.println("Making hard refs for: " + jar);
  if (jar != null && jar.getClass().getName().equals("com.sun.deploy.cache.CachedJarFile")) {
    callNoArgMethod("getSigners",jar);
    makeHardLink("signersRef",jar);
    callNoArgMethod("getSignerMap",jar);
    makeHardLink("signerMapRef",jar);
    callNoArgMethod("getCodeSourceCache",jar);
    makeHardLink("codeSourceCacheRef",jar);
  }
}
 

Example 69

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

Source file: AssembleConfigScriptGenerator.java

  15 
vote

protected void generatePackagingTargets(){
  String fileName=Utils.getPropertyFormat(PROPERTY_SOURCE) + '/' + Utils.getPropertyFormat(PROPERTY_ELEMENT_NAME);
  String fileExists=Utils.getPropertyFormat(PROPERTY_SOURCE) + '/' + Utils.getPropertyFormat(PROPERTY_ELEMENT_NAME)+ "_exists";
  script.printComment("Beginning of the jarUp task");
  script.printTargetDeclaration(TARGET_JARUP,null,null,null,Messages.assemble_jarUp);
  script.printAvailableTask(fileExists,fileName);
  Map params=new HashMap(2);
  params.put(PROPERTY_SOURCE,Utils.getPropertyFormat(PROPERTY_SOURCE));
  params.put(PROPERTY_ELEMENT_NAME,Utils.getPropertyFormat(PROPERTY_ELEMENT_NAME));
  script.printAvailableTask(PROPERTY_JARING_MANIFEST,fileName + '/' + JarFile.MANIFEST_NAME);
  script.printConditionIsSet(PROPERTY_JARING_TASK,TARGET_JARING,PROPERTY_JARING_MANIFEST,TARGET_JARING + "_NoManifest");
  script.printAntCallTask(Utils.getPropertyFormat(PROPERTY_JARING_TASK),true,params);
  script.printTargetEnd();
  script.println();
  script.printTargetDeclaration(TARGET_JARING,null,fileExists,null,null);
  script.printJarTask(fileName + ".jar",fileName,fileName + '/' + JarFile.MANIFEST_NAME,"skip");
  script.printDeleteTask(fileName,null,null);
  script.printTargetEnd();
  script.println();
  script.printTargetDeclaration(TARGET_JARING + "_NoManifest",null,fileExists,null,null);
  script.printJarTask(fileName + ".jar",fileName,null,"merge");
  script.printDeleteTask(fileName,null,null);
  script.printTargetEnd();
  script.printComment("End of the jarUp task");
  script.println();
  script.printComment("Beginning of the jar signing  target");
  script.printTargetDeclaration(TARGET_JARSIGNING,null,null,null,Messages.sign_Jar);
  printCustomAssemblyAntCall(PROPERTY_PRE + TARGET_JARSIGNING,null);
  if (generateJnlp)   script.printProperty(PROPERTY_UNSIGN,"true");
  script.println("<eclipse.jarProcessor sign=\"" + Utils.getPropertyFormat(PROPERTY_SIGN) + "\" pack=\""+ Utils.getPropertyFormat(PROPERTY_PACK)+ "\" unsign=\""+ Utils.getPropertyFormat(PROPERTY_UNSIGN)+ "\" jar=\""+ fileName+ ".jar"+ "\" alias=\""+ Utils.getPropertyFormat(PROPERTY_SIGN_ALIAS)+ "\" keystore=\""+ Utils.getPropertyFormat(PROPERTY_SIGN_KEYSTORE)+ "\" storepass=\""+ Utils.getPropertyFormat(PROPERTY_SIGN_STOREPASS)+ "\" keypass=\""+ Utils.getPropertyFormat(PROPERTY_SIGN_KEYPASS)+ "\"/>");
  script.printTargetEnd();
  script.printComment("End of the jarUp task");
  script.println();
}
 

Example 70

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

Source file: JarIndexer.java

  15 
vote

private static void safeClose(JarFile close){
  try {
    close.close();
  }
 catch (  Exception ignore) {
  }
}
 

Example 71

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

Source file: BundleServicesTestCase.java

  15 
vote

@Test public void testBundleLifecycle() throws Exception {
  Bundle bundle=installBundle(getTestArchive());
  AbstractBundleState bundleState=AbstractBundleState.assertBundleState(bundle);
  ServiceContainer serviceContainer=getBundleManager().getServiceContainer();
  ServiceController<?> controller=serviceContainer.getService(bundleState.getServiceName(Bundle.INSTALLED));
  assertServiceState(controller,State.UP);
  controller=serviceContainer.getService(bundleState.getServiceName(Bundle.RESOLVED));
  assertServiceState(controller,State.DOWN);
  controller=serviceContainer.getService(bundleState.getServiceName(Bundle.ACTIVE));
  assertServiceState(controller,State.DOWN);
  URL url=bundle.getResource(JarFile.MANIFEST_NAME);
  assertNotNull("URL not null",url);
  controller=serviceContainer.getService(bundleState.getServiceName(Bundle.RESOLVED));
  assertServiceState(controller,State.UP);
  bundle.start();
  controller=serviceContainer.getService(bundleState.getServiceName(Bundle.ACTIVE));
  assertServiceState(controller,State.UP);
  bundle.stop();
  controller=serviceContainer.getService(bundleState.getServiceName(Bundle.ACTIVE));
  assertServiceState(controller,State.DOWN);
  bundle.uninstall();
  assertBundleState(Bundle.UNINSTALLED,bundle.getState());
}
 

Example 72

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

Source file: AbstractResolverTest.java

  15 
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 73

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

Source file: VFSUtils.java

  15 
vote

public static Manifest getManifest(VirtualFile archive) throws IOException {
  if (archive == null)   throw MESSAGES.illegalArgumentNull("archive");
  VirtualFile manifest=archive.getChild(JarFile.MANIFEST_NAME);
  if (manifest == null)   return null;
  InputStream stream=manifest.openStream();
  try {
    return new Manifest(stream);
  }
  finally {
    try {
      stream.close();
    }
 catch (    IOException ignored) {
    }
  }
}
 

Example 74

From project jira-hudson-integration, under directory /hudson-apiv2-plugin/src/main/java/com/marvelution/hudson/plugins/apiv2/wink/.

Source file: HudsonWinkApplication.java

  15 
vote

/** 
 * Get all the classes that are in a  {@link JarFile} and that are in the given package
 * @param jarFile the {@link JarFile} to filter
 * @param resourcePackageName the package to filter with
 * @return {@link Set} of {@link Class} objects
 * @since 4.1.0
 */
private Set<Class<?>> getClassesFromJarFile(JarFile jarFile,String resourcePackageName){
  Set<Class<?>> classes=new HashSet<Class<?>>();
  Enumeration<JarEntry> entries=jarFile.entries();
  while (entries.hasMoreElements()) {
    JarEntry jarEntry=entries.nextElement();
    if (!jarEntry.isDirectory() && jarEntry.getName().endsWith(".class")) {
      String className=jarEntry.getName().substring(0,jarEntry.getName().lastIndexOf('.'));
      className=className.replaceAll("/",".");
      if (className.startsWith(resourcePackageName)) {
        try {
          classes.add(Class.forName(className));
          LOGGER.log(Level.FINE,"Loaded Resource: " + className);
        }
 catch (        ClassNotFoundException e) {
          LOGGER.log(Level.SEVERE,"Failed to load REST Resources: " + className,e);
        }
      }
    }
  }
  return classes;
}