/**
  * This method initializes the container. Essentially, it will try to load the class that contains
  * the list of entities and reflectively call the method that contains that list. It will then
  * initialize the container with that list.
  */
 public void initialize(Map m) {
   boolean keepInitialMaps = keepAllPredeployedPersistenceUnits();
   if (keepInitialMaps) {
     this.initialPuInfos = new HashMap();
   }
   // always create initialEmSetupImpls - it's used to check for puName uniqueness in
   // initPersistenceUnits
   this.initialEmSetupImpls = new HashMap();
   // ailitchev - copied from findPersistenceUnitInfoInArchives: mkeith - get resource name from
   // prop and include in subsequent call
   String descriptorPath = (String) m.get(PersistenceUnitProperties.ECLIPSELINK_PERSISTENCE_XML);
   final Set<Archive> pars;
   if (descriptorPath != null) {
     pars =
         PersistenceUnitProcessor.findPersistenceArchives(
             initializationClassloader, descriptorPath);
   } else {
     pars = PersistenceUnitProcessor.findPersistenceArchives(initializationClassloader);
   }
   try {
     for (Archive archive : pars) {
       AbstractSessionLog.getLog().log(SessionLog.FINER, "cmp_init_initialize", archive);
       initPersistenceUnits(archive, m);
     }
   } finally {
     for (Archive archive : pars) {
       archive.close();
     }
     this.initialEmSetupImpls = null;
   }
 }
  public static Set<String> getClassNamesFromURL(URL url, ClassLoader loader, Map properties) {
    Set<String> classNames = new HashSet<String>();
    Archive archive = null;
    try {
      archive = PersistenceUnitProcessor.getArchiveFactory(loader).createArchive(url, properties);

      if (archive != null) {
        for (Iterator<String> entries = archive.getEntries(); entries.hasNext(); ) {
          String entry = entries.next();
          if (entry.endsWith(".class")) { // NOI18N
            classNames.add(buildClassNameFromEntryString(entry));
          }
        }
      }
    } catch (URISyntaxException e) {
      throw new RuntimeException("url = [" + url + "]", e); // NOI18N
    } catch (IOException e) {
      throw new RuntimeException("url = [" + url + "]", e); // NOI18N
    } finally {
      if (archive != null) {
        archive.close();
      }
    }
    return classNames;
  }
 /**
  * Find PersistenceUnitInfo corresponding to the persistence unit name. Returns null if either
  * persistence unit either not found or provider is not supported.
  */
 protected SEPersistenceUnitInfo findPersistenceUnitInfoInArchives(String puName, Map m) {
   SEPersistenceUnitInfo persistenceUnitInfo = null;
   // mkeith - get resource name from prop and include in subsequent call
   String descriptorPath = (String) m.get(PersistenceUnitProperties.ECLIPSELINK_PERSISTENCE_XML);
   final Set<Archive> pars;
   if (descriptorPath != null) {
     pars =
         PersistenceUnitProcessor.findPersistenceArchives(
             initializationClassloader, descriptorPath);
   } else {
     pars = PersistenceUnitProcessor.findPersistenceArchives(initializationClassloader);
   }
   try {
     for (Archive archive : pars) {
       persistenceUnitInfo = findPersistenceUnitInfoInArchive(puName, archive, m);
       if (persistenceUnitInfo != null) {
         break;
       }
     }
   } finally {
     for (Archive archive : pars) {
       archive.close();
     }
   }
   return persistenceUnitInfo;
 }
  /**
   * Return a list of Archives representing the root of the persistence descriptor. It is the
   * caller's responsibility to close all the archives.
   *
   * @param loader the class loader to get the class path from
   */
  public static Set<Archive> findPersistenceArchives(
      ClassLoader loader, String descriptorPath, List<URL> jarFileUrls) {
    Archive archive = null;

    Set<Archive> archives = new HashSet<Archive>();

    // See if we are talking about an embedded descriptor
    // If not embedded descriptor then just use the regular descriptor path
    int splitPosition = descriptorPath.indexOf("!/");
    if (splitPosition != -1) {
      // It is an embedded archive, so split up the parts
      descriptorPath = descriptorPath.substring(splitPosition + 2);
    }

    try {
      for (int i = 0; i < jarFileUrls.size(); i++) {
        URL puRootUrl = jarFileUrls.get(i);
        archive =
            PersistenceUnitProcessor.getArchiveFactory(loader)
                .createArchive(puRootUrl, descriptorPath, null);

        // archive = new BundleArchive(puRootUrl, descUrl);
        if (archive != null) {
          archives.add(archive);
        }
      }
    } catch (Exception ex) {
      // clean up first
      for (Archive a : archives) {
        a.close();
      }
      throw PersistenceUnitLoadingException.exceptionSearchingForPersistenceResources(loader, ex);
    }
    return archives;
  }
 /**
  * Go through the jar file for this PersistenceUnitProcessor and process any XML provided in it.
  */
 public static List<SEPersistenceUnitInfo> processPersistenceArchive(
     Archive archive, ClassLoader loader) {
   URL puRootURL = archive.getRootURL();
   try {
     return processPersistenceXML(puRootURL, archive.getDescriptorStream(), loader);
   } catch (Exception e) {
     throw PersistenceUnitLoadingException.exceptionLoadingFromUrl(puRootURL.toString(), e);
   }
 }
  /**
   * Return a list of Archives representing the root of the persistence descriptor. It is the
   * caller's responsibility to close all the archives.
   *
   * @param loader the class loader to get the class path from
   */
  public static Set<Archive> findPersistenceArchives(ClassLoader loader, String descriptorPath) {
    Archive archive = null;

    Set<Archive> archives = new HashSet<Archive>();

    // See if we are talking about an embedded descriptor
    int splitPosition = descriptorPath.indexOf("!/");

    try {
      // If not embedded descriptor then just use the regular descriptor path
      if (splitPosition == -1) {
        Enumeration<URL> resources = loader.getResources(descriptorPath);
        while (resources.hasMoreElements()) {

          URL descUrl = resources.nextElement();
          if (descUrl != null) {
            URL puRootUrl = computePURootURL(descUrl, descriptorPath);
            archive =
                PersistenceUnitProcessor.getArchiveFactory(loader)
                    .createArchive(puRootUrl, descriptorPath, null);

            // archive = new BundleArchive(puRootUrl, descUrl);
            if (archive != null) {
              archives.add(archive);
            }
          }
        }
      } else {
        // It is an embedded archive, so split up the parts
        String jarPrefixPath = descriptorPath.substring(0, splitPosition);
        String descPath = descriptorPath.substring(splitPosition + 2);
        // TODO This causes the bundle to be resolved (not what we want)!
        URL prefixUrl = loader.getResource(jarPrefixPath);
        archive =
            PersistenceUnitProcessor.getArchiveFactory(loader)
                .createArchive(prefixUrl, descPath, null);

        if (archive != null) {
          archives.add(archive);
        }
      }
    } catch (Exception ex) {
      // clean up first
      for (Archive a : archives) {
        a.close();
      }
      throw PersistenceUnitLoadingException.exceptionSearchingForPersistenceResources(loader, ex);
    }
    return archives;
  }
 public static Set<SEPersistenceUnitInfo> getPersistenceUnits(
     ClassLoader loader, Map m, List<URL> jarFileUrls) {
   String descriptorPath = (String) m.get(PersistenceUnitProperties.ECLIPSELINK_PERSISTENCE_XML);
   if (descriptorPath == null) {
     descriptorPath =
         System.getProperty(
             PersistenceUnitProperties.ECLIPSELINK_PERSISTENCE_XML,
             PersistenceUnitProperties.ECLIPSELINK_PERSISTENCE_XML_DEFAULT);
   }
   Set<Archive> archives = findPersistenceArchives(loader, descriptorPath, jarFileUrls);
   Set<SEPersistenceUnitInfo> puInfos = new HashSet();
   try {
     for (Archive archive : archives) {
       List<SEPersistenceUnitInfo> puInfosFromArchive = getPersistenceUnits(archive, loader);
       puInfos.addAll(puInfosFromArchive);
     }
   } finally {
     for (Archive archive : archives) {
       archive.close();
     }
   }
   return puInfos;
 }
  /** INTERNAL: The method performs weaving function */
  private void process() throws IOException, URISyntaxException {
    // Instantiate output handler.
    AbstractStaticWeaveOutputHandler swoh;
    if (isDirectory(this.target)) {
      swoh = new StaticWeaveDirectoryOutputHandler(this.source, this.target);
    } else {
      swoh =
          new StaticWeaveJAROutputHandler(
              new JarOutputStream(new FileOutputStream(new File(Helper.toURI(this.target)))));
    }

    // Instantiate classloader.
    this.classLoader =
        (this.classLoader == null)
            ? Thread.currentThread().getContextClassLoader()
            : this.classLoader;
    this.classLoader = new URLClassLoader(getURLs(), this.classLoader);

    // Instantiate the classtransformer, we check if the persistenceinfo URL has been specified.
    StaticWeaveClassTransformer classTransformer = null;
    if (persistenceInfo != null) {
      classTransformer =
          new StaticWeaveClassTransformer(
              persistenceInfo,
              persistenceXMLLocation,
              this.classLoader,
              this.logWriter,
              this.logLevel);
    } else {
      classTransformer =
          new StaticWeaveClassTransformer(
              source, persistenceXMLLocation, this.classLoader, this.logWriter, this.logLevel);
    }

    // Starting process.
    Archive sourceArchive = (new ArchiveFactoryImpl()).createArchive(source, null, null);
    if (sourceArchive != null) {
      try {
        Iterator entries = sourceArchive.getEntries();
        while (entries.hasNext()) {
          String entryName = (String) entries.next();
          InputStream entryInputStream = sourceArchive.getEntry(entryName);

          // Add a directory entry
          swoh.addDirEntry(getDirectoryFromEntryName(entryName));

          // Add a regular entry
          JarEntry newEntry = new JarEntry(entryName);

          // Ignore non-class files.
          if (!(entryName.endsWith(".class"))) {
            swoh.addEntry(entryInputStream, newEntry);
            continue;
          }

          String className = PersistenceUnitProcessor.buildClassNameFromEntryString(entryName);

          byte[] originalClassBytes = null;
          byte[] transferredClassBytes = null;
          try {
            Class thisClass = this.classLoader.loadClass(className);
            // If the class is not in the classpath, we simply copy the entry
            // to the target(no weaving).
            if (thisClass == null) {
              swoh.addEntry(entryInputStream, newEntry);
              continue;
            }

            // Try to read the loaded class bytes, the class bytes is required for
            // classtransformer to perform transfer. Simply copy entry to the target(no weaving)
            // if the class bytes can't be read.
            InputStream is = this.classLoader.getResourceAsStream(entryName);
            if (is != null) {
              ByteArrayOutputStream baos = null;
              try {
                baos = new ByteArrayOutputStream();
                byte[] bytes = new byte[NUMBER_OF_BYTES];
                int bytesRead = is.read(bytes, 0, NUMBER_OF_BYTES);
                while (bytesRead >= 0) {
                  baos.write(bytes, 0, bytesRead);
                  bytesRead = is.read(bytes, 0, NUMBER_OF_BYTES);
                }
                originalClassBytes = baos.toByteArray();
              } finally {
                baos.close();
              }
            } else {
              swoh.addEntry(entryInputStream, newEntry);
              continue;
            }

            // If everything is OK so far, we perform the weaving. we need three parameters in order
            // to
            // class to perform weaving for that class, the class name,the class object and class
            // bytes.
            transferredClassBytes =
                classTransformer.transform(
                    className.replace('.', '/'), thisClass, originalClassBytes);

            // If transferredClassBytes is null means the class dose not get woven.
            if (transferredClassBytes != null) {
              swoh.addEntry(newEntry, transferredClassBytes);
            } else {
              swoh.addEntry(entryInputStream, newEntry);
            }
          } catch (IllegalClassFormatException e) {
            AbstractSessionLog.getLog().logThrowable(AbstractSessionLog.WARNING, e);
            // Anything went wrong, we need log a warning message, copy the entry to the target and
            // process next entry.
            swoh.addEntry(entryInputStream, newEntry);
            continue;
          } catch (ClassNotFoundException e) {
            AbstractSessionLog.getLog().logThrowable(AbstractSessionLog.WARNING, e);
            swoh.addEntry(entryInputStream, newEntry);
            continue;
          } finally {
            // Need close the inputstream for current entry before processing next one.
            entryInputStream.close();
          }
        }
      } finally {
        sourceArchive.close();
        swoh.closeOutputStream();
      }
    }
  }