Esempio n. 1
0
  protected EMFBuilderServiceProxyHandler registerEMFBuilderService(
      EMFServiceProxyHandler emfServiceProxyHandler,
      String puName,
      Dictionary<String, String> props) {
    EMFBuilderServiceProxyHandler emfBuilderProxyHandler =
        new EMFBuilderServiceProxyHandler(osgiProvider, puName, emfServiceProxyHandler);
    Object emfBuilderServiceProxy = null;

    try {
      emfBuilderServiceProxy =
          Proxy.newProxyInstance(
              this.getClass().getClassLoader(),
              new Class[] {EntityManagerFactoryBuilder.class},
              emfBuilderProxyHandler);
    } catch (Exception e) {
      AbstractSessionLog.getLog()
          .finest("EclipseLink OSGi - Failed to create proxy for EMF builder service: " + e);
    }

    try {
      String[] serviceInterfaces = new String[] {EntityManagerFactoryBuilder.class.getName()};
      context.registerService(serviceInterfaces, emfBuilderServiceProxy, props);
    } catch (Exception e) {
      AbstractSessionLog.getLog()
          .finest("EclipseLink OSGi could not register EMF Builder service for " + puName + e);
    }
    AbstractSessionLog.getLog()
        .finer("EclipseLink OSGi registered EMF Builder service for " + puName);
    return emfBuilderProxyHandler;
  }
  /** Load the given class name with the given class loader. */
  public static Class loadClass(
      String className,
      ClassLoader loader,
      boolean throwExceptionIfNotFound,
      MetadataProject project) {
    Class candidateClass = null;

    try {
      candidateClass = loader.loadClass(className);
    } catch (ClassNotFoundException exc) {
      if (throwExceptionIfNotFound) {
        throw PersistenceUnitLoadingException.exceptionLoadingClassWhileLookingForAnnotations(
            className, exc);
      } else {
        AbstractSessionLog.getLog()
            .log(
                AbstractSessionLog.WARNING,
                "persistence_unit_processor_error_loading_class",
                exc.getClass().getName(),
                exc.getLocalizedMessage(),
                className);
      }
    } catch (NullPointerException npe) {
      // Bug 227630: If any weavable class is not found in the temporary
      // classLoader - disable weaving
      AbstractSessionLog.getLog()
          .log(
              AbstractSessionLog.WARNING,
              AbstractSessionLog.WEAVER,
              "persistence_unit_processor_error_loading_class_weaving_disabled",
              loader,
              project.getPersistenceUnitInfo().getPersistenceUnitName(),
              className);
      // Disable weaving (for 1->1 and many->1)only if the classLoader
      // returns a NPE on loadClass()
      project.disableWeaving();
    } catch (Exception exception) {
      AbstractSessionLog.getLog()
          .log(
              AbstractSessionLog.WARNING,
              AbstractSessionLog.WEAVER,
              "persistence_unit_processor_error_loading_class",
              exception.getClass().getName(),
              exception.getLocalizedMessage(),
              className);
    } catch (Error error) {
      AbstractSessionLog.getLog()
          .log(
              AbstractSessionLog.WARNING,
              AbstractSessionLog.WEAVER,
              "persistence_unit_processor_error_loading_class",
              error.getClass().getName(),
              error.getLocalizedMessage(),
              className);
      throw error;
    }

    return candidateClass;
  }
 /** Initialize the logging file if it is specified by the system property. */
 public static void initializeTopLinkLoggingFile() {
   String loggingFile = System.getProperty(PersistenceUnitProperties.LOGGING_FILE);
   try {
     if (loggingFile != null) {
       AbstractSessionLog.getLog().setWriter(new FileWriter(loggingFile));
     }
   } catch (IOException e) {
     AbstractSessionLog.getLog()
         .log(SessionLog.WARNING, "cmp_init_default_logging_file_is_invalid", loggingFile, e);
   }
 }
 // EclipseLink-specific logging functions
 protected void openEclipseLinkLogFileIfSpecified() {
   String loggingFile = System.getProperty(PersistenceUnitProperties.LOGGING_FILE);
   try {
     if (loggingFile != null) {
       eclipseLinkLog = new FileWriter(loggingFile);
       AbstractSessionLog.getLog().setWriter(eclipseLinkLog);
     }
   } catch (IOException e) {
     AbstractSessionLog.getLog()
         .log(SessionLog.WARNING, "cmp_init_default_logging_file_is_invalid", loggingFile, e);
   }
 }
  /**
   * INTERNAL: This method perform all necessary steps(verification, pre-build the target directory)
   * prior to the invocation of the weaving function.
   */
  private void preProcess() throws URISyntaxException, MalformedURLException {
    // Instantiate default session log
    AbstractSessionLog.getLog().setLevel(this.logLevel);
    if (logWriter != null) {
      ((DefaultSessionLog) AbstractSessionLog.getLog()).setWriter(logWriter);
    }

    // Make sure the source is existing
    if (!(new File(Helper.toURI(source)).exists())) {
      throw StaticWeaveException.missingSource();
    }

    URI targetURI = Helper.toURI(target);
    // Verification target and source, two use cases create warning or exception.
    // 1. If source is directory and target is jar -
    //   This will lead unknown outcome, user attempt to use this tool to pack outcome into a Jar.
    //   Warning message will be logged, this is can be worked around by other utilities.
    // 2. Both source and target are specified as a same jar -
    //   User was trying to perform weaving in same Jar which is not supported, an Exception will be
    // thrown.
    if (isDirectory(source) && targetURI.toString().endsWith(".jar")) {
      AbstractSessionLog.getLog()
          .log(
              SessionLog.WARNING,
              ToStringLocalization.buildMessage(
                  "staticweave_processor_unknown_outcome", new Object[] {null}));
    }

    if (!isDirectory(source) && target.toString().equals(source.toString())) {
      throw StaticWeaveException.weaveInplaceForJar(source.toString());
    }

    // pre-create target if it is directory and dose not exist.
    // Using the method File.isDirectory() is not enough to determine what the type(dir or jar)
    // of the target(specified by URL)that user want to create. File.isDirectory() will return false
    // in
    // two possibilities, the location either is not directory or the location dose not exist.
    // Therefore pre-build of the directory target is required. Pre-build for the file(JAR) target
    // is not required since it gets built automatically by opening outputstream.
    if (!(new File(targetURI)).exists()) {
      if (!targetURI.toString().endsWith(".jar")) {
        (new File(targetURI)).mkdirs();
        // if directory fails to build, which may leads to unknown outcome since it will
        // be treated as single file in the class StaticWeaveHandler and automatically gets built
        // by outputstream.

        // re-assign URL.
        target = (new File(targetURI)).toURL();
      }
    }
  }
  /**
   * This method fixes incorrect authority attribute that is set by JDK when UNC is used in
   * classpath. See JDK bug #6585937 and GlassFish issue #3209 for more details.
   */
  private static URL fixUNC(URL url)
      throws URISyntaxException, MalformedURLException, UnsupportedEncodingException {
    String protocol = url.getProtocol();
    if (!"file".equalsIgnoreCase(protocol)) {
      return url;
    }
    String authority = url.getAuthority();
    String file = url.getFile();
    if (authority != null) {
      AbstractSessionLog.getLog()
          .finer(
              "fixUNC: before fixing: url = "
                  + url
                  + ", authority = "
                  + authority
                  + ", file = "
                  + file);
      assert (url.getPort() == -1);

      // See GlassFish issue https://glassfish.dev.java.net/issues/show_bug.cgi?id=3209 and
      // JDK issue http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6585937
      // When there is UNC path in classpath, the classloader.getResource
      // returns a file: URL with an authority component in it.
      // The URL looks like this:
      // file://ahost/afile.
      // Interestingly, authority and file components for the above URL
      // are either "ahost" and "/afile" or "" and "//ahost/afile" depending on
      // how the URL is obtained. If classpath is set as a jar with UNC,
      // the former is true, if the classpath is set as a directory with UNC,
      // the latter is true.
      String prefix = "";
      if (authority.length() > 0) {
        prefix = "////";
      } else if (file.startsWith("//")) {
        prefix = "//";
      }
      file = prefix.concat(authority).concat(file);
      url = new URL(protocol, null, file);
      AbstractSessionLog.getLog()
          .finer(
              "fixUNC: after fixing: url = "
                  + url
                  + ", authority = "
                  + url.getAuthority()
                  + ", file = "
                  + url.getFile());
    }
    return url;
  }
 /**
  * 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;
   }
 }
 protected void closeEclipseLinkLogFileIfNecessary() {
   // Reset to default
   AbstractSessionLog.setLog(new DefaultSessionLog());
   try {
     if (eclipseLinkLog != null) {
       eclipseLinkLog.close();
     }
   } catch (IOException e) {
   }
 }
Esempio n. 9
0
  protected void registerEMFServices(String[] persistenceUnitNames) {
    for (String puName : persistenceUnitNames) {
      AbstractSessionLog.getLog()
          .finest("EclipseLink OSGi - registering services for PU '" + puName + "'");
      // Assemble the properties
      Dictionary<String, String> props = new Hashtable<String, String>();
      props.put("osgi.unit.name", puName);
      props.put("osgi.unit.provider", PersistenceProvider.class.getName());

      EMFServiceProxyHandler emfServiceProxyHandler = registerEMFService(puName, props);
      registerEMFBuilderService(emfServiceProxyHandler, puName, props);
    }
  }
Esempio n. 10
0
 /** Store a reference to a bundle as it is started so the bundle can be accessed later. */
 private void registerBundle(Bundle bundle) {
   if ((bundle.getState() & (Bundle.STARTING | Bundle.RESOLVED | Bundle.ACTIVE)) != 0) {
     AbstractSessionLog.getLog()
         .finest(
             "EclipseLink OSGi - examining bundle: "
                 + bundle.getSymbolicName()
                 + "_"
                 + bundle.getBundleId());
     if (!PersistenceProvider.includesBundle(bundle)) {
       try {
         String[] persistenceUnitNames = getPersistenceUnitNames(bundle);
         if (persistenceUnitNames != null) {
           // Bundle contains persistence unit(s)
           PersistenceProvider.addBundle(bundle, persistenceUnitNames);
           registerEMFServices(persistenceUnitNames);
         }
       } catch (Exception e) {
         AbstractSessionLog.getLog().logThrowable(SessionLog.WARNING, e);
       }
     }
   }
 }
  /**
   * Create a list of java.lang.Class that contains the classes of all the entities that we will be
   * deploying.
   */
  protected Set loadEntityClasses(Collection entityNames, ClassLoader classLoader) {
    Set entityClasses = new HashSet();

    // Load the classes using the loader passed in
    AbstractSessionLog.getLog()
        .log(SessionLog.FINER, "cmp_loading_entities_using_loader", classLoader);
    for (Iterator iter = entityNames.iterator(); iter.hasNext(); ) {
      String entityClassName = (String) iter.next();
      try {
        entityClasses.add(classLoader.loadClass(entityClassName));
      } catch (ClassNotFoundException cnfEx) {
        throw ValidationException.entityClassNotFound(entityClassName, classLoader, cnfEx);
      }
    }
    return entityClasses;
  }
Esempio n. 12
0
  /**
   * INTERNAL: For this Type generate classes
   *
   * @param packageName
   * @param nr
   */
  public void preInitialize(String packageName, List namespaceResolvers) {
    String instanceClassName = getInstanceClassName();
    if (null == instanceClassName) {
      if (null == packageName) {
        String uri = getURI();
        if (null == uri) {
          packageName = SDOUtil.getDefaultPackageName() + SDOConstants.JAVA_PACKAGE_NAME_SEPARATOR;
        } else {
          packageName =
              SDOUtil.getPackageNameFromURI(uri) + SDOConstants.JAVA_PACKAGE_NAME_SEPARATOR;
        }
      }

      // Verify and fix any Class name that does not conform to conventions
      // run the class name through the JAXB mangler
      String mangledClassName = SDOUtil.className(getName(), false, true, true);

      // we will not fix any type collision at this time as a result of class renaming
      // write fully qualified java class name
      StringBuffer fullClassName = new StringBuffer(packageName);
      fullClassName.append(mangledClassName);
      setInstanceClassName(fullClassName.toString());
    }
    AbstractSessionLog.getLog()
        .log(
            AbstractSessionLog.FINER, //
            "sdo_type_generation_processing_type", //
            new Object[] {Helper.getShortClassName(getClass()), getInstanceClassName()});

    initializeNamespaces(namespaceResolvers);
    getXmlDescriptor().setJavaClassName(getImplClassName());

    // See SDOResolvable enhancement
    String schemaContext = getName();
    if (getXmlDescriptor().getNamespaceResolver() != null) {
      String prefix = getXmlDescriptor().getNamespaceResolver().resolveNamespaceURI(getURI());
      if ((prefix != null) && !prefix.equals(SDOConstants.EMPTY_STRING)) {
        schemaContext = prefix + SDOConstants.SDO_XPATH_NS_SEPARATOR_FRAGMENT + schemaContext;
      }
    }
    String schemaContextWithSlash = SDOConstants.SDO_XPATH_SEPARATOR_FRAGMENT + schemaContext;

    XMLSchemaReference schemaRef = new XMLSchemaClassPathReference();
    schemaRef.setSchemaContext(schemaContextWithSlash);
    schemaRef.setType(XMLSchemaReference.COMPLEX_TYPE);
    getXmlDescriptor().setSchemaReference(schemaRef);
  }
Esempio n. 13
0
 /** On start, we do two things We register a listener for bundles and we start our JPA server */
 public void start(BundleContext context) throws Exception {
   Activator.context = context;
   String initializer = null;
   ServiceReference packageAdminRef =
       context.getServiceReference("org.osgi.service.packageadmin.PackageAdmin");
   PackageAdmin packageAdmin = (PackageAdmin) context.getService(packageAdminRef);
   Bundle[] fragments = packageAdmin.getFragments(context.getBundle());
   if (fragments != null) {
     for (int i = 0; i < fragments.length; i++) {
       Bundle fragment = fragments[i];
       initializer = (String) fragment.getHeaders().get("JPA-Initializer");
       if (initializer != null) {
         AbstractSessionLog.getLog()
             .log(
                 SessionLog.CONFIG,
                 LoggingLocalization.buildMessage("osgi_initializer", new Object[] {initializer}));
         break;
       }
     }
   }
   osgiProvider = new PersistenceProvider(initializer);
   registerBundleListener();
 }
  /**
   * predeploy (with deploy) is one of the two steps required in deployment of entities This method
   * will prepare to call predeploy, call it and finally register the transformer returned to be
   * used for weaving.
   */
  public EntityManagerSetupImpl callPredeploy(
      SEPersistenceUnitInfo persistenceUnitInfo,
      Map m,
      String persistenceUnitUniqueName,
      String sessionName) {
    AbstractSessionLog.getLog()
        .log(
            SessionLog.FINER,
            "cmp_init_invoke_predeploy",
            persistenceUnitInfo.getPersistenceUnitName());
    Map mergedProperties =
        EntityManagerFactoryProvider.mergeMaps(m, persistenceUnitInfo.getProperties());
    // Bug#4452468  When globalInstrumentation is null, there is no weaving
    checkWeaving(mergedProperties);

    Set tempLoaderSet = PersistenceUnitProcessor.buildClassSet(persistenceUnitInfo, m);
    // Create the temp loader that will not cache classes for entities in our persistence unit
    ClassLoader tempLoader = createTempLoader(tempLoaderSet);
    persistenceUnitInfo.setNewTempClassLoader(tempLoader);

    EntityManagerSetupImpl emSetupImpl =
        new EntityManagerSetupImpl(persistenceUnitUniqueName, sessionName);

    // A call to predeploy will partially build the session we will use
    final ClassTransformer transformer =
        emSetupImpl.predeploy(persistenceUnitInfo, mergedProperties);

    // After preDeploy it's impossible to weave again - so may substitute the temporary classloader
    // with the real one.
    // The temporary classloader could be garbage collected even if the puInfo is cached for the
    // future use by other emSetupImpls.
    persistenceUnitInfo.setNewTempClassLoader(persistenceUnitInfo.getClassLoader());

    registerTransformer(transformer, persistenceUnitInfo, m);
    return emSetupImpl;
  }
 private int getLogLevel() {
   return AbstractSessionLog.translateStringToLoggingLevel(logLevel);
 }
  @Override
  public void buildSessions() {
    XRDynamicClassLoader xrdecl = new XRDynamicClassLoader(parentClassLoader);
    DatasourceLogin login = new DatabaseLogin();
    login.setUserName(username);
    login.setPassword(password);
    ((DatabaseLogin) login).setConnectionString(url);
    ((DatabaseLogin) login).setDriverClassName(DATABASE_PLATFORM);
    Platform platform = builder.getDatabasePlatform();
    ConversionManager conversionManager = platform.getConversionManager();
    if (conversionManager != null) {
      conversionManager.setLoader(xrdecl);
    }
    login.setDatasourcePlatform(platform);
    ((DatabaseLogin) login).bindAllParameters();
    ((DatabaseLogin) login).setUsesStreamsForBinding(true);

    Project orProject = null;
    if (DBWS_OR_STREAM.size() != 0) {
      MetadataProcessor processor =
          new MetadataProcessor(
              new XRPersistenceUnitInfo(xrdecl),
              new DatabaseSessionImpl(login),
              xrdecl,
              false,
              true,
              false,
              false,
              false,
              null,
              null);
      processor.setMetadataSource(
          new JPAMetadataSource(xrdecl, new StringReader(DBWS_OR_STREAM.toString())));
      PersistenceUnitProcessor.processORMetadata(
          processor, true, PersistenceUnitProcessor.Mode.ALL);
      processor.addNamedQueries();
      orProject = processor.getProject().getProject();
    } else {
      orProject = new Project();
    }
    orProject.setName(builder.getProjectName().concat(OR_PRJ_SUFFIX));
    orProject.setDatasourceLogin(login);
    DatabaseSession databaseSession = orProject.createDatabaseSession();
    if ("off".equalsIgnoreCase(builder.getLogLevel())) {
      databaseSession.dontLogMessages();
    } else {
      databaseSession.setLogLevel(
          AbstractSessionLog.translateStringToLoggingLevel(builder.getLogLevel()));
    }
    xrService.setORSession(databaseSession);
    orProject.convertClassNamesToClasses(xrdecl);

    Project oxProject = null;
    Map<String, OXMMetadataSource> metadataMap = new HashMap<String, OXMMetadataSource>();
    StreamSource xml = new StreamSource(new StringReader(DBWS_OX_STREAM.toString()));
    try {
      JAXBContext jc = JAXBContext.newInstance(XmlBindingsModel.class);
      Unmarshaller unmarshaller = jc.createUnmarshaller();

      JAXBElement<XmlBindingsModel> jaxbElt = unmarshaller.unmarshal(xml, XmlBindingsModel.class);
      XmlBindingsModel model = jaxbElt.getValue();
      for (XmlBindings xmlBindings : model.getBindingsList()) {
        metadataMap.put(xmlBindings.getPackageName(), new OXMMetadataSource(xmlBindings));
      }
    } catch (JAXBException jaxbex) {
      jaxbex.printStackTrace();
    }

    Map<String, Map<String, OXMMetadataSource>> properties =
        new HashMap<String, Map<String, OXMMetadataSource>>();
    properties.put(JAXBContextProperties.OXM_METADATA_SOURCE, metadataMap);
    try {
      org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContext jCtx =
          org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContextFactory.createContextFromOXM(
              parentClassLoader, properties);
      oxProject = jCtx.getXMLContext().getSession(0).getProject();
    } catch (JAXBException e) {
      e.printStackTrace();
    }
    ((XMLLogin) oxProject.getDatasourceLogin()).setPlatformClassName(DOM_PLATFORM_CLASSNAME);
    ((XMLLogin) oxProject.getDatasourceLogin()).setEqualNamespaceResolvers(false);

    prepareDescriptors(oxProject, orProject, xrdecl);
    ProjectHelper.fixOROXAccessors(orProject, oxProject);
    xrService.setORSession(databaseSession);
    xrService.setXMLContext(new XMLContext(oxProject));
    xrService.setOXSession(xrService.getXMLContext().getSession(0));
  }
Esempio n. 17
0
  /**
   * Return the java.lang.reflect.Member for the represented attribute. In the case of property
   * access the get method will be returned
   *
   * @return corresponding java.lang.reflect.Member
   */
  @Override
  public Member getJavaMember() {
    AttributeAccessor accessor = getMapping().getAttributeAccessor();
    if (accessor.isMethodAttributeAccessor()) {
      // Method level access here
      Method aMethod = ((MethodAttributeAccessor) accessor).getGetMethod();
      if (null == aMethod) {
        // 316991: If the getMethod is not set - use a reflective call via the getMethodName
        String getMethodName = null;
        try {
          getMethodName =
              ((MethodAttributeAccessor) mapping.getAttributeAccessor()).getGetMethodName();
          if (PrivilegedAccessHelper.shouldUsePrivilegedAccess()) {
            aMethod =
                AccessController.doPrivileged(
                    new PrivilegedGetDeclaredMethod(
                        this.getManagedTypeImpl().getJavaType(), getMethodName, null));
          } else {
            aMethod =
                PrivilegedAccessHelper.getDeclaredMethod(
                    this.getManagedTypeImpl().getJavaType(), getMethodName, null);
          }
          // Exceptions are to be ignored for reflective calls - if the methodName is also null - it
          // will catch here
        } catch (PrivilegedActionException pae) {
          // pae.printStackTrace();
        } catch (NoSuchMethodException nsfe) {
          // nsfe.printStackTrace();
        }
      }
      return aMethod;
    }

    // Field level access here
    Member aMember = ((InstanceVariableAttributeAccessor) accessor).getAttributeField();
    // For primitive and basic types - we should not return null - the attributeAccessor on the
    // MappedSuperclass is not initialized - see
    // http://wiki.eclipse.org/EclipseLink/Development/JPA_2.0/metamodel_api#DI_95:_20091017:_Attribute.getJavaMember.28.29_returns_null_for_a_BasicType_on_a_MappedSuperclass_because_of_an_uninitialized_accessor
    // MappedSuperclasses need special handling to get their type from an inheriting subclass
    // Note: This code does not handle attribute overrides on any entity subclass tree - use
    // descriptor initialization instead
    if (null == aMember) {
      if (this.getManagedTypeImpl().isMappedSuperclass()) {
        // get inheriting subtype member (without handling @override annotations)
        AttributeImpl inheritingTypeMember =
            ((MappedSuperclassTypeImpl) this.getManagedTypeImpl())
                .getMemberFromInheritingType(mapping.getAttributeName());
        // 322166: If attribute is defined on this current ManagedType (and not on a superclass) -
        // do not attempt a reflective call on a superclass
        if (null != inheritingTypeMember) {
          // Verify we have an attributeAccessor
          aMember =
              ((InstanceVariableAttributeAccessor)
                      inheritingTypeMember.getMapping().getAttributeAccessor())
                  .getAttributeField();
        }
      }

      if (null == aMember) {
        // 316991: Handle Embeddable types
        // If field level access - perform a getDeclaredField call
        // Field level access
        // Check declaredFields in the case where we have no getMethod or getMethodName
        try {
          if (PrivilegedAccessHelper.shouldUsePrivilegedAccess()) {
            aMember =
                AccessController.doPrivileged(
                    new PrivilegedGetDeclaredField(
                        this.getManagedTypeImpl().getJavaType(),
                        mapping.getAttributeName(),
                        false));
          } else {
            aMember =
                PrivilegedAccessHelper.getDeclaredField(
                    this.getManagedTypeImpl().getJavaType(), mapping.getAttributeName(), false);
          }
          // Exceptions are to be ignored for reflective calls - if the methodName is also null - it
          // will catch here
        } catch (PrivilegedActionException pae) {
          // pae.printStackTrace();
        } catch (NoSuchFieldException nsfe) {
          // nsfe.printStackTrace();
        }
      }
    }

    // 303063: secondary check for attribute override case - this will show on code coverage
    if (null == aMember) {
      AbstractSessionLog.getLog()
          .log(
              SessionLog.FINEST,
              AbstractSessionLog.METAMODEL,
              "metamodel_attribute_getmember_is_null",
              this,
              this.getManagedTypeImpl(),
              this.getDescriptor());
    }

    return aMember;
  }
  /** 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();
      }
    }
  }