/** INTERNAL: Load a class from a given class name. (XMLEntityMappings calls this one) */
 public static Class getClassForName(String classname, ClassLoader loader) {
   try {
     if (PrivilegedAccessHelper.shouldUsePrivilegedAccess()) {
       try {
         return (Class)
             AccessController.doPrivileged(new PrivilegedClassForName(classname, true, loader));
       } catch (PrivilegedActionException exception) {
         throw ValidationException.unableToLoadClass(classname, exception.getException());
       }
     } else {
       return PrivilegedAccessHelper.getClassForName(classname, true, loader);
     }
   } catch (ClassNotFoundException exception) {
     if (classname.indexOf('$') != -1) {
       String outer = classname.substring(0, classname.indexOf('$'));
       Class outerClass = getClassForName(outer, loader);
       for (int index = 0; index < outerClass.getClasses().length; index++) {
         if (outerClass.getClasses()[index].getName().equals(classname)) {
           return outerClass.getClasses()[index];
         }
       }
     }
     throw ValidationException.unableToLoadClass(classname, exception);
   }
 }
 /**
  * INTERNAL: Convert all the class-name-based settings in this InheritancePolicy to actual
  * class-based settings. This method is used when converting a project that has been built with
  * class names to a project with classes. It will also convert referenced classes to the versions
  * of the classes from the classLoader.
  */
 public void convertClassNamesToClasses(ClassLoader classLoader) {
   Vector newParentInterfaces = new Vector();
   for (Iterator iterator = getParentInterfaceNames().iterator(); iterator.hasNext(); ) {
     String interfaceName = (String) iterator.next();
     Class interfaceClass = null;
     try {
       if (PrivilegedAccessHelper.shouldUsePrivilegedAccess()) {
         try {
           interfaceClass =
               (Class)
                   AccessController.doPrivileged(
                       new PrivilegedClassForName(interfaceName, true, classLoader));
         } catch (PrivilegedActionException exception) {
           throw ValidationException.classNotFoundWhileConvertingClassNames(
               interfaceName, exception.getException());
         }
       } else {
         interfaceClass =
             org.eclipse.persistence.internal.security.PrivilegedAccessHelper.getClassForName(
                 interfaceName, true, classLoader);
       }
     } catch (ClassNotFoundException exc) {
       throw ValidationException.classNotFoundWhileConvertingClassNames(interfaceName, exc);
     }
     newParentInterfaces.add(interfaceClass);
   }
   this.parentInterfaces = newParentInterfaces;
 }
  /**
   * Indicates if this <code>JavaClass</code> is either the same as, or is a superclass of, the
   * <code>javaClass</code> argument.
   *
   * @param javaClass the <code>Class</code> to test.
   * @return <code>true</code> if this <code>JavaClass</code> is assignable from <code>javaClass
   *     </code>, otherwise <code>false</code>.
   * @see java.lang.Class#isAssignableFrom(Class)
   */
  @SuppressWarnings("unchecked")
  public boolean isAssignableFrom(JavaClass arg0) {
    String thisJavaName = EMPTY_STRING;
    String argJavaName = arg0.getName();

    if (this.javaName != null) {
      thisJavaName = this.javaName;
    } else {
      thisJavaName = this.javaType.getName();
    }

    if (thisJavaName.startsWith(JAVA) && argJavaName.startsWith(JAVA)) {
      // Only try class lookup if this is a JDK class, because
      // we won't ever find classes for dynamically generated types.
      try {
        Class thisClass = PrivilegedAccessHelper.getClassForName(thisJavaName);
        Class argClass = PrivilegedAccessHelper.getClassForName(argJavaName);
        return thisClass.isAssignableFrom(argClass);
      } catch (Exception e) {
        return false;
      }
    } else {
      return thisJavaName.equals(argJavaName);
    }
  }
 /**
  * INTERNAL: Convert all the class-name-based settings to actual class-based settings. This method
  * is used when converting a project that has been built with class names to a project with
  * classes.
  */
 public void convertClassNamesToClasses(ClassLoader classLoader) {
   if (getPartitioningClasName() == null) {
     setPartitioningClasName("");
   }
   try {
     if (PrivilegedAccessHelper.shouldUsePrivilegedAccess()) {
       Class partitioningClass =
           (Class)
               AccessController.doPrivileged(
                   new PrivilegedClassForName(getPartitioningClasName(), true, classLoader));
       this.policy =
           (PartitioningPolicy)
               AccessController.doPrivileged(
                   new PrivilegedNewInstanceFromClass(partitioningClass));
     } else {
       Class partitioningClass =
           PrivilegedAccessHelper.getClassForName(getPartitioningClasName(), true, classLoader);
       this.policy =
           (PartitioningPolicy) PrivilegedAccessHelper.newInstanceFromClass(partitioningClass);
     }
   } catch (PrivilegedActionException exception) {
     throw ValidationException.classNotFoundWhileConvertingClassNames(
         getPartitioningClasName(), exception.getException());
   } catch (ClassNotFoundException exception) {
     throw ValidationException.classNotFoundWhileConvertingClassNames(
         getPartitioningClasName(), exception);
   } catch (IllegalAccessException exception) {
     throw ValidationException.reflectiveExceptionWhileCreatingClassInstance(
         getPartitioningClasName(), exception);
   } catch (InstantiationException exception) {
     throw ValidationException.reflectiveExceptionWhileCreatingClassInstance(
         getPartitioningClasName(), exception);
   }
 }
 /**
  * INTERNAL: Convert all the class-name-based settings in this mapping to actual class-based
  * settings. This method is used when converting a project that has been built with class names to
  * a project with classes.
  */
 @Override
 public void convertClassNamesToClasses(ClassLoader classLoader) {
   super.convertClassNamesToClasses(classLoader);
   Iterator iterator = getTypeIndicatorNameTranslation().entrySet().iterator();
   this.typeIndicatorTranslation = new HashMap();
   while (iterator.hasNext()) {
     Map.Entry entry = (Map.Entry) iterator.next();
     String referenceClassName = (String) entry.getKey();
     Object indicator = entry.getValue();
     Class referenceClass = null;
     try {
       if (PrivilegedAccessHelper.shouldUsePrivilegedAccess()) {
         try {
           referenceClass =
               (Class)
                   AccessController.doPrivileged(
                       new PrivilegedClassForName(referenceClassName, true, classLoader));
         } catch (PrivilegedActionException exception) {
           throw ValidationException.classNotFoundWhileConvertingClassNames(
               referenceClassName, exception.getException());
         }
       } else {
         referenceClass =
             PrivilegedAccessHelper.getClassForName(referenceClassName, true, classLoader);
       }
     } catch (ClassNotFoundException exception) {
       throw ValidationException.classNotFoundWhileConvertingClassNames(
           referenceClassName, exception);
     }
     addClassIndicator(referenceClass, indicator);
   }
 }
 private void initCycleRecoverableClasses() {
   try {
     this.cycleRecoverableClass = PrivilegedAccessHelper.getClassForName(CYCLE_RECOVERABLE);
     this.cycleRecoverableContextClass =
         PrivilegedAccessHelper.getClassForName(CYCLE_RECOVERABLE_CONTEXT);
   } catch (Exception e) {
   }
 }
 /**
  * Internal: Helper to load class. Please do not make this method protected or public else it
  * would expose a security hole that would allow malicious code to use this method to load any
  * class without security permission
  *
  * @param className Fully qualified class name
  * @param classLoader ClassLoader to be used for loading the class
  * @return Loaded Class
  * @throws java.security.PrivilegedActionException
  * @throws ClassNotFoundException
  */
 private Class loadClass(String className, ClassLoader classLoader)
     throws PrivilegedActionException, ClassNotFoundException {
   Class loadedClass = null;
   if (PrivilegedAccessHelper.shouldUsePrivilegedAccess()) {
     loadedClass =
         AccessController.doPrivileged(new PrivilegedClassForName(className, true, classLoader));
   } else {
     loadedClass = PrivilegedAccessHelper.getClassForName(className, true, classLoader);
   }
   return loadedClass;
 }
 /**
  * Parse constraints file (referenced in validation.xml). Add all classes declared under <bean
  * class="clazz"> to {@link
  * org.eclipse.persistence.jaxb.BeanValidationHelper#constraintsOnClasses} with value {@link
  * Boolean#TRUE}.
  */
 private void parseConstraintFile(String constraintsFile, DefaultHandler referencedFileHandler) {
   InputStream constraintsXml = null;
   if (PrivilegedAccessHelper.shouldUsePrivilegedAccess()) {
     try {
       constraintsXml =
           AccessController.doPrivileged(
                   new PrivilegedGetContextClassLoader(Thread.currentThread()))
               .getResourceAsStream(constraintsFile);
     } catch (PrivilegedActionException e) {
       String msg =
           "Loading of custom constraints file: "
               + constraintsFile
               + " failed. Exception: "
               + e.getMessage();
       LOGGER.warning(msg);
     }
   } else {
     constraintsXml =
         Thread.currentThread().getContextClassLoader().getResourceAsStream(constraintsFile);
   }
   try {
     //noinspection ConstantConditions
     saxParser.parse(constraintsXml, referencedFileHandler);
   } catch (SAXException | IOException | NullPointerException e) {
     String msg =
         "Loading of custom constraints file: "
             + constraintsFile
             + " failed. Exception: "
             + e.getMessage();
     LOGGER.warning(msg);
   }
 }
示例#9
0
  /** INTERNAL: Return a new instance of the class provided. */
  public Object getClassInstance(Class cls) {
    if (cls != null) {
      try {
        if (PrivilegedAccessHelper.shouldUsePrivilegedAccess()) {
          return AccessController.doPrivileged(new PrivilegedNewInstanceFromClass(cls));
        } else {
          return org.eclipse.persistence.internal.security.PrivilegedAccessHelper
              .newInstanceFromClass(cls);
        }
      } catch (Exception e) {
        throw ValidationException.reflectiveExceptionWhileCreatingClassInstance(cls.getName(), e);
      }
    }

    return null;
  }
 /** INTERNAL: Create a new instance of the class given. */
 static Object getClassInstance(Class cls) {
   try {
     if (PrivilegedAccessHelper.shouldUsePrivilegedAccess()) {
       try {
         return AccessController.doPrivileged(new PrivilegedNewInstanceFromClass(cls));
       } catch (PrivilegedActionException exception) {
         throw ValidationException.errorInstantiatingClass(cls, exception.getException());
       }
     } else {
       return PrivilegedAccessHelper.newInstanceFromClass(cls);
     }
   } catch (IllegalAccessException exception) {
     throw ValidationException.errorInstantiatingClass(cls, exception);
   } catch (InstantiationException exception) {
     throw ValidationException.errorInstantiatingClass(cls, exception);
   }
 }
 protected void setup() {
   orgIntegrityChecker = getSession().getIntegrityChecker();
   getSession().setIntegrityChecker(new IntegrityChecker()); // moved into setup
   getSession().getIntegrityChecker().dontCatchExceptions(); // moved into setup
   orgSecurityManager = System.getSecurityManager(); // security java.policy must allow full access
   System.setSecurityManager(new TestSecurityManager());
   orgDefaultUseDoPrivilegedValue = getOrgDefaultUseDoPrivilegedValue();
   PrivilegedAccessHelper.setDefaultUseDoPrivilegedValue(true);
   descriptor = new RelationalDescriptor();
   descriptor.setJavaClass(getTestClass());
 }
  /**
   * Return the "actual" type from a parameterized type. For example, if this <code>JavaClass</code>
   * represents <code>List&lt;Employee</code>, this method will return the <code>Employee</code>
   * <code>JavaClass</code>.
   *
   * @return a <code>Collection</code> containing the actual type's <code>JavaClass</code>.
   */
  public Collection<JavaClass> getActualTypeArguments() {
    Object jType = null;
    if (this.javaType != null) {
      jType = this.javaType;
    } else {
      try {
        Class<?> jTypeClass = PrivilegedAccessHelper.getClassForName(this.javaName);
        jType = PrivilegedAccessHelper.newInstanceFromClass(jTypeClass);
      } catch (Exception e) {
        return new ArrayList<JavaClass>();
      }
    }

    ArrayList<JavaClass> argCollection = new ArrayList<JavaClass>();
    if (jType instanceof ParameterizedType) {
      ParameterizedType pType = (ParameterizedType) jType;
      Type[] params = pType.getActualTypeArguments();
      for (Type type : params) {
        if (type instanceof ParameterizedType) {
          ParameterizedType pt = (ParameterizedType) type;
          argCollection.add(this.javaModel.getClass(pt.getRawType().getClass()));
        } else if (type instanceof WildcardType) {
          Type[] upperTypes = ((WildcardType) type).getUpperBounds();
          if (upperTypes.length > 0) {
            Type upperType = upperTypes[0];
            if (upperType instanceof Class<?>) {
              argCollection.add(this.javaModel.getClass(upperType.getClass()));
            }
          }
        } else if (type instanceof Class<?>) {
          argCollection.add(this.javaModel.getClass(type.getClass()));
        } else if (type instanceof GenericArrayType) {
          Class<?> genericTypeClass =
              (Class<?>) ((GenericArrayType) type).getGenericComponentType();
          genericTypeClass = java.lang.reflect.Array.newInstance(genericTypeClass, 0).getClass();
          argCollection.add(this.javaModel.getClass(genericTypeClass.getClass()));
        }
      }
    }
    return argCollection;
  }
  public static ArchiveFactory getArchiveFactory(ClassLoader loader) {
    if (ARCHIVE_FACTORY != null) {
      return ARCHIVE_FACTORY;
    }

    ArchiveFactory factory = null;
    String factoryClassName = System.getProperty(SystemProperties.ARCHIVE_FACTORY, null);

    if (factoryClassName == null) {
      return new ArchiveFactoryImpl();
    } else {
      try {
        if (loader != null) {
          Class archiveClass = loader.loadClass(factoryClassName);
          if (PrivilegedAccessHelper.shouldUsePrivilegedAccess()) {
            try {
              factory =
                  (ArchiveFactory)
                      AccessController.doPrivileged(
                          new PrivilegedNewInstanceFromClass(archiveClass));
            } catch (PrivilegedActionException exception) {
              throw PersistenceUnitLoadingException.exceptionCreatingArchiveFactory(
                  factoryClassName, exception);
            }
          } else {
            factory = (ArchiveFactory) PrivilegedAccessHelper.newInstanceFromClass(archiveClass);
          }
        }
      } catch (ClassNotFoundException cnfe) {
        throw PersistenceUnitLoadingException.exceptionCreatingArchiveFactory(
            factoryClassName, cnfe);
      } catch (IllegalAccessException iae) {
        throw PersistenceUnitLoadingException.exceptionCreatingArchiveFactory(
            factoryClassName, iae);
      } catch (InstantiationException ie) {
        throw PersistenceUnitLoadingException.exceptionCreatingArchiveFactory(factoryClassName, ie);
      }
    }

    return factory;
  }
 /**
  * INTERNAL: Convert all the class-name-based settings in this Descriptor to actual class-based
  * settings. This method is used when converting a project that has been built with class names to
  * a project with classes.
  *
  * @param classLoader
  */
 public void convertClassNamesToClasses(ClassLoader classLoader) {
   if (this.type == null) {
     try {
       if (PrivilegedAccessHelper.shouldUsePrivilegedAccess()) {
         try {
           this.type =
               AccessController.doPrivileged(
                   new PrivilegedClassForName(this.typeName, true, classLoader));
         } catch (PrivilegedActionException exception) {
           throw ValidationException.classNotFoundWhileConvertingClassNames(
               this.typeName, exception.getException());
         }
       } else {
         this.type =
             org.eclipse.persistence.internal.security.PrivilegedAccessHelper.getClassForName(
                 this.typeName, true, classLoader);
       }
     } catch (ClassNotFoundException exc) {
       throw ValidationException.classNotFoundWhileConvertingClassNames(this.typeName, exc);
     }
     if (this.items != null) {
       for (ATTRIBUTE_ITEM item : this.items.values()) {
         item.convertClassNamesToClasses(classLoader);
       }
     }
     if (this.allsubclasses != null) {
       Map<Object, CoreAttributeGroup> allGroups = new HashMap<Object, CoreAttributeGroup>();
       this.subClasses = new HashSet<CoreAttributeGroup>();
       for (CoreAttributeGroup subClass : allsubclasses.values()) {
         subClass.convertClassNamesToClasses(classLoader);
         allGroups.put(subClass.getType(), subClass);
       }
       this.allsubclasses = allGroups;
       for (CoreAttributeGroup subClass : allsubclasses.values()) {
         if (CoreAttributeItem.orderInheritance(subClass, allGroups)) {
           this.insertSubClass(subClass);
         }
       }
     }
   }
 }
  /**
   * INTERNAL: This method will return the key to be used to store/retrieve the delegates for a
   * given application.
   *
   * <p>OC4J classLoader levels: 0 - APP.web (servlet/jsp) or APP.wrapper (ejb) 1 - APP.root (parent
   * for helperContext) 2 - default.root 3 - system.root 4 - oc4j.10.1.3 (remote EJB) or
   * org.eclipse.persistence:11.1.1.0.0 5 - api:1.4.0 6 - jre.extension:0.0.0 7 -
   * jre.bootstrap:1.5.0_07 (with various J2SE versions)
   *
   * @return Application classloader for OC4J, application name for WebLogic, otherwise
   *     Thread.currentThread().getContextClassLoader()
   */
  private static Object getDelegateMapKey(ClassLoader classLoader) {
    String classLoaderName = classLoader.getClass().getName();

    // Default to Thread.currentThread().getContextClassLoader()
    Object delegateKey = classLoader;

    // Delegates in OC4J server will be keyed on classloader
    if (classLoaderName.startsWith(OC4J_CLASSLOADER_NAME)) {
      // Check to see if we are running in a Servlet container or a local EJB container
      if ((classLoader.getParent() != null) //
          && ((classLoader.toString().indexOf(SDOConstants.CLASSLOADER_WEB_FRAGMENT) != -1) //
              || (classLoader.toString().indexOf(SDOConstants.CLASSLOADER_EJB_FRAGMENT) != -1))) {
        classLoader = classLoader.getParent();
      }
      delegateKey = classLoader;
      // Delegates in WebLogic server will be keyed on application name
    } else if (classLoaderName.contains(WLS_CLASSLOADER_NAME)) {
      Object executeThread = getExecuteThread();
      if (executeThread != null) {
        try {
          Method getMethod =
              PrivilegedAccessHelper.getPublicMethod(
                  executeThread.getClass(),
                  WLS_APPLICATION_NAME_GET_METHOD_NAME,
                  PARAMETER_TYPES,
                  false);
          delegateKey = PrivilegedAccessHelper.invokeMethod(getMethod, executeThread);
          // ExecuteThread returns null
          if (delegateKey == null) {
            delegateKey = classLoader;
          }
        } catch (Exception e) {
          throw SDOException.errorInvokingWLSMethodReflectively(
              WLS_APPLICATION_NAME_GET_METHOD_NAME, WLS_EXECUTE_THREAD, e);
        }
      }
    }
    return delegateKey;
  }
 /**
  * @return true if someone is just not letting the async thread do anything or if we possibly
  *     failed due to using jdk executor and not having access to resources managed by container.
  */
 static boolean asyncAttemptFailed() {
   try {
     return !didSomething
         || (possibleResourceVisibilityFail
             && (PrivilegedAccessHelper.shouldUsePrivilegedAccess()
                     ? AccessController.doPrivileged(
                             new PrivilegedGetContextClassLoader(Thread.currentThread()))
                         .getResource(VALIDATION_XML)
                     : Thread.currentThread().getContextClassLoader().getResource(VALIDATION_XML))
                 != null);
   } catch (PrivilegedActionException exception) {
     return true;
   }
 }
示例#17
0
 /** Verify that the class is a valid instance class. */
 private boolean isValidInstanceClass(Class clazz) {
   if (isDataType) {
     return true;
   }
   if (!clazz.isInterface()) {
     return false;
   }
   for (Object object : this.getDeclaredProperties()) {
     SDOProperty sdoProperty = (SDOProperty) object;
     SDOType sdoPropertyType = sdoProperty.getType();
     if (!sdoPropertyType.isChangeSummaryType()) {
       String javaType = SDOUtil.getJavaTypeForProperty(sdoProperty);
       try {
         // Verify get method
         String getMethodName = SDOUtil.getMethodName(sdoProperty.getName(), javaType);
         PrivilegedAccessHelper.getPublicMethod(clazz, getMethodName, EMPTY_CLASS_ARRAY, false);
       } catch (NoSuchMethodException e) {
         // if the method isn't found and the type is boolean try looking for a "get" method
         // instead of an "is" method
         if (sdoPropertyType == SDOConstants.SDO_BOOLEAN
             || sdoPropertyType == SDOConstants.SDO_BOOLEANOBJECT) {
           try {
             String booleanGetterMethodName =
                 SDOUtil.getBooleanGetMethodName(sdoProperty.getName(), javaType);
             PrivilegedAccessHelper.getPublicMethod(
                 clazz, booleanGetterMethodName, EMPTY_CLASS_ARRAY, false);
           } catch (NoSuchMethodException e2) {
             return false;
           }
         } else {
           return false;
         }
       }
     }
   }
   return true;
 }
 /**
  * INTERNAL: Lazy initialization of xmlTypeFactory allows to avoid loading xdb-dependent class
  * XMLTypeFactoryImpl unless xdb is used.
  *
  * @return XMLTypeFactory
  */
 protected XMLTypeFactory getXMLTypeFactory() {
   if (xmlTypeFactory == null) {
     String className =
         "org.eclipse.persistence.internal.platform.database.oracle.xdb.XMLTypeFactoryImpl";
     try {
       if (PrivilegedAccessHelper.shouldUsePrivilegedAccess()) {
         Class xmlTypeFactoryClass =
             (Class)
                 AccessController.doPrivileged(
                     new PrivilegedClassForName(
                         className, true, this.getClass().getClassLoader()));
         Constructor xmlTypeFactoryConstructor =
             (Constructor)
                 AccessController.doPrivileged(
                     new PrivilegedGetConstructorFor(xmlTypeFactoryClass, new Class[0], true));
         xmlTypeFactory =
             (XMLTypeFactory)
                 AccessController.doPrivileged(
                     new PrivilegedInvokeConstructor(xmlTypeFactoryConstructor, new Object[0]));
       } else {
         Class xmlTypeFactoryClass =
             PrivilegedAccessHelper.getClassForName(
                 className, true, this.getClass().getClassLoader());
         Constructor xmlTypeFactoryConstructor =
             PrivilegedAccessHelper.getConstructorFor(xmlTypeFactoryClass, new Class[0], true);
         xmlTypeFactory =
             (XMLTypeFactory)
                 PrivilegedAccessHelper.invokeConstructor(
                     xmlTypeFactoryConstructor, new Object[0]);
       }
     } catch (Exception e) {
       throw QueryException.reflectiveCallOnTopLinkClassFailed(className, e);
     }
   }
   return xmlTypeFactory;
 }
 private boolean getOrgDefaultUseDoPrivilegedValue() {
   Field def = null;
   try {
     def =
         PrivilegedAccessHelper.getDeclaredField(
             PrivilegedAccessHelper.class, "defaultUseDoPrivilegedValue", true);
     return (Boolean) def.get(null);
   } catch (Exception e) {
     throw new TestErrorException(e.getMessage());
   } finally {
     if (def != null) {
       def.setAccessible(false);
     }
   }
 }
 /**
  * This method will be used to set a new type of identity map for a particular class type. If
  * objects of that class type are in use loss of object identity will result. For prevention
  * client may wish to initialize all identity maps first.
  *
  * @param className the fully qualified className to set the identity map for.
  * @param identityMapClassType the fully qualified class name of the new identity map type.
  * @param maxSize the maximum size to be specified for the new identity map.
  * @exception ClassNotFoundException thrown then the IdenityMap for that class name could not be
  *     found
  */
 public void setIdentityMapForClass(String className, String identityMapClassType, int maxSize)
     throws ClassNotFoundException {
   Class classToChange =
       (Class)
           getSession()
               .getDatasourcePlatform()
               .getConversionManager()
               .convertObject(className, ClassConstants.CLASS);
   Class identityMapClass = null;
   if (PrivilegedAccessHelper.shouldUsePrivilegedAccess()) {
     try {
       identityMapClass =
           (Class) AccessController.doPrivileged(new PrivilegedClassForName(identityMapClassType));
     } catch (PrivilegedActionException ex) {
       throw (RuntimeException) ex.getCause();
     }
   } else {
     identityMapClass = PrivilegedAccessHelper.getClassForName(identityMapClassType);
   }
   ClassDescriptor descriptor = getSession().getDescriptor(classToChange);
   descriptor.setIdentityMapClass(identityMapClass);
   descriptor.setIdentityMapSize(maxSize);
   getSession().getIdentityMapAccessorInstance().initializeIdentityMap(classToChange);
 }
  /** Return the method for the WebSphere JDBC connection wrapper vendorConnection. */
  protected Method getVendorConnectionMethod() {
    if ((this.vendorConnectionMethod == null) && (!getWebsphereUtilClass().equals(void.class))) {
      try {
        Class args[] = new Class[1];
        args[0] = getWebsphereConnectionClass();
        this.vendorConnectionMethod =
            PrivilegedAccessHelper.getDeclaredMethod(
                getWebsphereUtilClass(), "getNativeConnection", args);
      } catch (NoSuchMethodException exception) {
        getDatabaseSession()
            .getSessionLog()
            .logThrowable(SessionLog.WARNING, SessionLog.SERVER, exception);
      }
    }

    return this.vendorConnectionMethod;
  }
  /** Unwraps the WebSphere JDBC connection wrapping using the WebLogic API reflectively. */
  @Override
  public Connection unwrapConnection(Connection connection) {
    if (getWebsphereConnectionClass().isInstance(connection)
        && getVendorConnectionMethod() != null) {
      try {
        return (Connection)
            PrivilegedAccessHelper.invokeMethod(
                getVendorConnectionMethod(), null, new Object[] {connection});
      } catch (IllegalAccessException exception) {
        getDatabaseSession()
            .getSessionLog()
            .logThrowable(SessionLog.WARNING, SessionLog.SERVER, exception);
      } catch (InvocationTargetException exception) {
        getDatabaseSession()
            .getSessionLog()
            .logThrowable(SessionLog.WARNING, SessionLog.SERVER, exception);
      }
    }

    return super.unwrapConnection(connection);
  }
 private void parseValidationXML() throws SAXException, IOException {
   InputStream validationXml = null;
   if (PrivilegedAccessHelper.shouldUsePrivilegedAccess()) {
     try {
       validationXml =
           AccessController.doPrivileged(
                   new PrivilegedGetContextClassLoader(Thread.currentThread()))
               .getResourceAsStream(VALIDATION_XML);
     } catch (PrivilegedActionException e) {
       String msg = "Loading of " + VALIDATION_XML + " file failed. Exception: " + e.getMessage();
       LOGGER.warning(msg);
     }
   } else {
     validationXml =
         Thread.currentThread().getContextClassLoader().getResourceAsStream(VALIDATION_XML);
   }
   if (validationXml != null) {
     saxParser.parse(validationXml, validationHandler);
   } else if (jdkExecutor) {
     possibleResourceVisibilityFail = true;
   }
 }
 public void reset() {
   getSession()
       .setIntegrityChecker(orgIntegrityChecker); // security java.policy must allow full access
   System.setSecurityManager(orgSecurityManager);
   PrivilegedAccessHelper.setDefaultUseDoPrivilegedValue(orgDefaultUseDoPrivilegedValue);
 }
  public void persistExample(Session session) {
    Vector allObjects = new Vector();
    allObjects.add(example1());
    allObjects.add(example2());
    allObjects.add(example3());
    allObjects.add(example4());

    // Bug 387491 - Three JUnitJPQLDateTimeTestSuite tests fail with Oracle jdbc 12.1 driver
    // Starting with Oracle jdbc 12.1 Statement.setDate no longer truncates time component of
    // sql.Date.
    // The following code makes Oracle9Platform to do that by setting shouldTruncateDate flag to
    // "true".
    boolean hasSetTruncateDate = false;
    if (session.getPlatform().isOracle9()) {
      try {
        Class clazz =
            PrivilegedAccessHelper.getClassForName(
                "org.eclipse.persistence.platform.database.oracle.Oracle9Platform");
        Method getDriverVersionMethod =
            PrivilegedAccessHelper.getMethod(clazz, "getDriverVersion", null, false);
        String driverVersion =
            (String)
                PrivilegedAccessHelper.invokeMethod(
                    getDriverVersionMethod, session.getPlatform(), null);
        if (Helper.compareVersions(driverVersion, "12.1") >= 0) {
          Method shouldTruncateDateMethod =
              PrivilegedAccessHelper.getMethod(clazz, "shouldTruncateDate", null, false);
          boolean shouldTruncateDate =
              (Boolean)
                  PrivilegedAccessHelper.invokeMethod(
                      shouldTruncateDateMethod, session.getPlatform(), null);
          if (!shouldTruncateDate) {
            Method setShouldTruncateDateMethod =
                PrivilegedAccessHelper.getMethod(
                    clazz, "setShouldTruncateDate", new Class[] {boolean.class}, false);
            PrivilegedAccessHelper.invokeMethod(
                setShouldTruncateDateMethod, session.getPlatform(), new Object[] {true});
            hasSetTruncateDate = true;
          }
        }
      } catch (Exception ex) {
        throw new RuntimeException("Failed oracle9Platform.setShouldTruncateDate(true)", ex);
      }
    }

    UnitOfWork unitOfWork = session.acquireUnitOfWork();
    unitOfWork.registerAllObjects(allObjects);
    unitOfWork.commit();

    if (hasSetTruncateDate) {
      // Now setting shouldTruncateDate flag back to its original value "false".
      try {
        Class clazz =
            PrivilegedAccessHelper.getClassForName(
                "org.eclipse.persistence.platform.database.oracle.Oracle9Platform");
        Method setShouldTruncateDateMethod =
            PrivilegedAccessHelper.getMethod(
                clazz, "setShouldTruncateDate", new Class[] {boolean.class}, false);
        PrivilegedAccessHelper.invokeMethod(
            setShouldTruncateDateMethod, session.getPlatform(), new Object[] {false});
      } catch (Exception ex) {
        throw new RuntimeException("Failed oracle9Platform.setShouldTruncateDate(false)", ex);
      }
    }
  }
  /**
   * 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;
  }
  @Override
  public XMLRecord buildRow(
      XMLRecord record,
      Object object,
      CoreAbstractSession session,
      Marshaller marshaller,
      XPathFragment rootFragment) {
    lazyInitialize();
    XPathNode textNode = rootXPathNode.getTextNode();
    List<XPathNode> nonAttributeChildren = rootXPathNode.getNonAttributeChildren();
    if (null == textNode && null == nonAttributeChildren) {
      return record;
    }

    Descriptor xmlDescriptor = (Descriptor) descriptor;
    XPathNode node = rootXPathNode;
    MarshalRecord marshalRecord = (MarshalRecord) record;
    QName schemaType = null;

    if (marshalRecord.getCycleDetectionStack().contains(object, marshaller.isEqualUsingIdenity())) {
      if (cycleRecoverableClass == null) {
        initCycleRecoverableClasses();
      }
      if (cycleRecoverableClass != null
          && cycleRecoverableClass.isAssignableFrom(object.getClass())) {
        try {
          Object jaxbMarshaller = marshaller.getProperty(Constants.JAXB_MARSHALLER);
          // Create a proxy instance of CycleRecoverable$Context, a parameter to
          // the onCycleDetected method
          Object contextProxy =
              CycleRecoverableContextProxy.getProxy(cycleRecoverableContextClass, jaxbMarshaller);
          // Invoke onCycleDetected method, passing in proxy, and reset
          // 'object' to the returned value
          Method onCycleDetectedMethod =
              object
                  .getClass()
                  .getMethod(ON_CYCLE_DETECTED, new Class[] {cycleRecoverableContextClass});
          object =
              PrivilegedAccessHelper.invokeMethod(
                  onCycleDetectedMethod, object, new Object[] {contextProxy});
        } catch (Exception e) {
          throw XMLMarshalException.marshalException(e);
        }

        // Returned object might have a different descriptor
        xmlDescriptor = (Descriptor) session.getDescriptor(object.getClass());
        if (xmlDescriptor != null) {
          node = ((ObjectBuilder) xmlDescriptor.getObjectBuilder()).getRootXPathNode();
        } else {
          node = null;
        }

        // Push new object
        marshalRecord.getCycleDetectionStack().push(object);

        // Write xsi:type if onCycleDetected returned an object of a type different than the one
        // mapped
        if (xmlDescriptor != descriptor) {
          if (xmlDescriptor == null) {
            schemaType = record.getConversionManager().schemaType(object.getClass());
          } else {
            schemaType = xmlDescriptor.getSchemaReference().getSchemaContextAsQName();
          }
          marshalRecord.writeXsiTypeAttribute(
              xmlDescriptor,
              schemaType.getNamespaceURI(),
              schemaType.getLocalPart(),
              schemaType.getPrefix(),
              false);
        }
      } else {
        // Push the duplicate object anyway, so that we can get the complete cycle string
        marshalRecord.getCycleDetectionStack().push(object);
        throw XMLMarshalException.objectCycleDetected(
            marshalRecord.getCycleDetectionStack().getCycleString());
      }
    } else {
      marshalRecord.getCycleDetectionStack().push(object);
    }

    NamespaceResolver namespaceResolver = null;
    if (xmlDescriptor != null) {
      namespaceResolver = xmlDescriptor.getNamespaceResolver();
    }
    MarshalContext marshalContext = null;
    if (xmlDescriptor != null && xmlDescriptor.isSequencedObject()) {
      SequencedObject sequencedObject = (SequencedObject) object;
      marshalContext = new SequencedMarshalContext(sequencedObject.getSettings());
    } else {
      marshalContext = ObjectMarshalContext.getInstance();
    }
    if (null == nonAttributeChildren) {
      textNode.marshal(
          (MarshalRecord) record,
          object,
          session,
          namespaceResolver,
          marshaller,
          marshalContext,
          rootFragment);
    } else {
      if (node == null) {
        // No descriptor for this object, so manually create a MappingNodeValue and marshal it
        XPathNode n = new XPathNode();
        CompositeObjectMapping m = new XMLCompositeObjectMapping();
        m.setXPath(".");
        XMLCompositeObjectMappingNodeValue nv = new XMLCompositeObjectMappingNodeValue(m);
        n.setMarshalNodeValue(nv);
        nv.marshalSingleValue(
            new XPathFragment("."),
            marshalRecord,
            null,
            object,
            session,
            namespaceResolver,
            marshalContext);
      } else {
        for (int x = 0, size = marshalContext.getNonAttributeChildrenSize(node); x < size; x++) {
          XPathNode xPathNode = (XPathNode) marshalContext.getNonAttributeChild(x, node);
          xPathNode.marshal(
              (MarshalRecord) record,
              object,
              session,
              namespaceResolver,
              marshaller,
              marshalContext.getMarshalContext(x),
              rootFragment);
        }
      }
    }
    marshalRecord.getCycleDetectionStack().pop();
    return record;
  }