Search in sources :

Example 1 with PrivilegedGetDeclaredMethod

use of org.eclipse.persistence.internal.security.PrivilegedGetDeclaredMethod in project eclipselink by eclipse-ee4j.

the class MetadataProject method getSharedCacheModeName.

/**
 * INTERNAL:
 * This method will return the name of the SharedCacheMode if specified in
 * the persistence.xml file. Note, this is a JPA 2.0 feature, therefore,
 * this method needs to catch any exception as a result of trying to access
 * this information from a JPA 1.0 container.
 */
protected String getSharedCacheModeName() {
    if (!m_isSharedCacheModeInitialized && m_sharedCacheMode == null) {
        try {
            Method method = null;
            if (PrivilegedAccessHelper.shouldUsePrivilegedAccess()) {
                method = AccessController.doPrivileged(new PrivilegedGetDeclaredMethod(PersistenceUnitInfo.class, "getSharedCacheMode", null));
                m_sharedCacheMode = AccessController.doPrivileged(new PrivilegedMethodInvoker<SharedCacheMode>(method, m_persistenceUnitInfo));
            } else {
                method = PrivilegedAccessHelper.getDeclaredMethod(PersistenceUnitInfo.class, "getSharedCacheMode", null);
                m_sharedCacheMode = PrivilegedAccessHelper.invokeMethod(method, m_persistenceUnitInfo, null);
            }
        } catch (Throwable exception) {
            // Swallow any exceptions, shared cache mode will be null.
            m_sharedCacheMode = null;
        }
        // Set the shared cache mode as initialized to avoid the reflective
        // calls over and over again.
        m_isSharedCacheModeInitialized = true;
    }
    return (m_sharedCacheMode == null) ? null : m_sharedCacheMode.name();
}
Also used : PrivilegedGetDeclaredMethod(org.eclipse.persistence.internal.security.PrivilegedGetDeclaredMethod) PrivilegedMethodInvoker(org.eclipse.persistence.internal.security.PrivilegedMethodInvoker) Method(java.lang.reflect.Method) PrivilegedGetDeclaredMethod(org.eclipse.persistence.internal.security.PrivilegedGetDeclaredMethod) PersistenceUnitInfo(jakarta.persistence.spi.PersistenceUnitInfo)

Example 2 with PrivilegedGetDeclaredMethod

use of org.eclipse.persistence.internal.security.PrivilegedGetDeclaredMethod in project eclipselink by eclipse-ee4j.

the class AttributeImpl method getJavaMember.

/**
 * 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();
    // 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) {
            // 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;
}
Also used : PrivilegedActionException(java.security.PrivilegedActionException) InstanceVariableAttributeAccessor(org.eclipse.persistence.internal.descriptors.InstanceVariableAttributeAccessor) PrivilegedGetDeclaredMethod(org.eclipse.persistence.internal.security.PrivilegedGetDeclaredMethod) Method(java.lang.reflect.Method) PrivilegedGetDeclaredField(org.eclipse.persistence.internal.security.PrivilegedGetDeclaredField) PrivilegedGetDeclaredMethod(org.eclipse.persistence.internal.security.PrivilegedGetDeclaredMethod) MethodAttributeAccessor(org.eclipse.persistence.internal.descriptors.MethodAttributeAccessor) AttributeAccessor(org.eclipse.persistence.mappings.AttributeAccessor) InstanceVariableAttributeAccessor(org.eclipse.persistence.internal.descriptors.InstanceVariableAttributeAccessor) MethodAttributeAccessor(org.eclipse.persistence.internal.descriptors.MethodAttributeAccessor) Member(java.lang.reflect.Member)

Example 3 with PrivilegedGetDeclaredMethod

use of org.eclipse.persistence.internal.security.PrivilegedGetDeclaredMethod in project eclipselink by eclipse-ee4j.

the class QueryOperation method createSimpleXMLFormat.

@SuppressWarnings({ "unchecked" })
public Object createSimpleXMLFormat(XRServiceAdapter xrService, Object value) {
    XMLRoot xmlRoot = new XMLRoot();
    SimpleXMLFormat simpleXMLFormat = result.getSimpleXMLFormat();
    String tempSimpleXMLFormatTag = SimpleXMLFormat.DEFAULT_SIMPLE_XML_FORMAT_TAG;
    String simpleXMLFormatTag = simpleXMLFormat.getSimpleXMLFormatTag();
    if (simpleXMLFormatTag != null && !EMPTY_STR.equals(simpleXMLFormatTag)) {
        tempSimpleXMLFormatTag = simpleXMLFormatTag;
    }
    xmlRoot.setLocalName(tempSimpleXMLFormatTag);
    String tempXMLTag = DEFAULT_SIMPLE_XML_TAG;
    String xmlTag = simpleXMLFormat.getXMLTag();
    if (xmlTag != null && !EMPTY_STR.equals(xmlTag)) {
        tempXMLTag = xmlTag;
    }
    Vector<DatabaseRecord> records = null;
    if (value instanceof ArrayList) {
        // JPA query results in a list of raw values
        // Here we have raw values returned as opposed to DatabaseRecords - this means
        // we need to figure out the tag names based on the call's output parameters.
        // assumes JPAQuery
        JPAQuery jpaQuery = (JPAQuery) queryHandler.getDatabaseQuery();
        // to match field names with results, we need to gather the database fields from each of the Output parameters
        List<DatabaseField> paramFlds = new ArrayList<>();
        DatasourceCall dsCall = (DatasourceCall) jpaQuery.getDatabaseQuery().getDatasourceCall();
        for (Object obj : dsCall.getParameters()) {
            if (obj instanceof OutputParameterForCallableStatement) {
                paramFlds.add(((OutputParameterForCallableStatement) obj).getOutputField());
            } else if (obj instanceof Object[]) {
                Object[] objArray = (Object[]) obj;
                for (int i = 0; i < objArray.length; i++) {
                    Object o = objArray[i];
                    if (o instanceof OutputParameterForCallableStatement) {
                        paramFlds.add(((OutputParameterForCallableStatement) o).getOutputField());
                    }
                }
            }
        }
        // now create a record using DatabaseField/value pairs
        DatabaseRecord dr = new DatabaseRecord();
        if (paramFlds.size() > 0) {
            for (int i = 0; i < ((ArrayList<?>) value).size(); i++) {
                dr.add(paramFlds.get(i), ((ArrayList<?>) value).get(i));
            }
        } else {
            dr.add(new DatabaseField(RESULT_STR), ((ArrayList<?>) value).get(0));
        }
        records = new Vector<>();
        records.add(dr);
    } else if (value instanceof Vector) {
        Class<?> vectorContent = ((Vector<?>) value).firstElement().getClass();
        if (DatabaseRecord.class.isAssignableFrom(vectorContent)) {
            records = (Vector<DatabaseRecord>) value;
        } else {
            records = new Vector<>();
            DatabaseRecord dr = new DatabaseRecord();
            dr.add(new DatabaseField(RESULT_STR), ((Vector<?>) value).firstElement());
            records.add(dr);
        }
    } else {
        records = new Vector<>();
        DatabaseRecord dr = new DatabaseRecord();
        dr.add(new DatabaseField(RESULT_STR), value);
        records.add(dr);
    }
    SimpleXMLFormatModel simpleXMLFormatModel = new SimpleXMLFormatModel();
    XMLConversionManager conversionManager = (XMLConversionManager) xrService.getOXSession().getDatasourcePlatform().getConversionManager();
    SessionLog log = xrService.getOXSession().getSessionLog();
    for (DatabaseRecord dr : records) {
        Element rowElement = TEMP_DOC.createElement(tempXMLTag);
        for (DatabaseField field : dr.getFields()) {
            // handle complex types, i.e. ones we have a descriptor for
            if (field instanceof ObjectRelationalDatabaseField) {
                ObjectRelationalDatabaseField ordtField = (ObjectRelationalDatabaseField) field;
                if (xrService.getOXSession().getDescriptor(ordtField.getType()) != null) {
                    xrService.getXMLContext().createMarshaller().marshal(dr.get(field), rowElement);
                    continue;
                }
            }
            Object fieldValue = dr.get(field);
            if (fieldValue != null) {
                if (fieldValue instanceof Calendar) {
                    Calendar cValue = (Calendar) fieldValue;
                    fieldValue = conversionManager.convertObject(cValue, STRING, DATE_TIME_QNAME);
                }
                if (fieldValue instanceof Date) {
                    Date dValue = (Date) fieldValue;
                    fieldValue = conversionManager.convertObject(dValue, STRING, DATE_QNAME);
                } else if (fieldValue instanceof Time) {
                    Time tValue = (Time) fieldValue;
                    fieldValue = conversionManager.convertObject(tValue, STRING, TIME_QNAME);
                } else if (fieldValue instanceof Timestamp) {
                    Timestamp tsValue = (Timestamp) fieldValue;
                    fieldValue = conversionManager.convertObject(tsValue, STRING, DATE_TIME_QNAME);
                } else if (fieldValue instanceof Blob) {
                    fieldValue = conversionManager.convertObject(fieldValue, ClassConstants.APBYTE);
                } else if (SQLXML.class.isAssignableFrom(fieldValue.getClass())) {
                    // handle XMLType case where an oracle.jdbc.driver.OracleSQLXML instance was returned
                    SQLXML sqlXml = (SQLXML) fieldValue;
                    try {
                        String str = sqlXml.getString();
                        sqlXml.free();
                        // Oracle 12c appends a \n character to the xml string
                        fieldValue = str.endsWith("\n") ? str.substring(0, str.length() - 1) : str;
                    } catch (SQLException e) {
                        log.logThrowable(SessionLog.FINE, SessionLog.DBWS, e);
                    }
                } else if (fieldValue.getClass().getName().equalsIgnoreCase(ORACLEOPAQUE_STR)) {
                    // handle XMLType case where an oracle.sql.OPAQUE instance was returned
                    try {
                        Class<?> oracleOPAQUE;
                        Class<?> xmlTypeFactoryClass;
                        Constructor<?> xmlTypeFactoryConstructor;
                        Object xmlTypeFactory;
                        Method getStringMethod;
                        if (PrivilegedAccessHelper.shouldUsePrivilegedAccess()) {
                            oracleOPAQUE = AccessController.doPrivileged(new PrivilegedClassForName<>(IORACLEOPAQUE_STR, true, this.getClass().getClassLoader()));
                            xmlTypeFactoryClass = AccessController.doPrivileged(new PrivilegedClassForName<>(XMLTYPEFACTORY_STR, true, this.getClass().getClassLoader()));
                            xmlTypeFactoryConstructor = AccessController.doPrivileged(new PrivilegedGetConstructorFor<>(xmlTypeFactoryClass, new Class<?>[0], true));
                            xmlTypeFactory = AccessController.doPrivileged(new PrivilegedInvokeConstructor<>(xmlTypeFactoryConstructor, new Object[0]));
                            getStringMethod = AccessController.doPrivileged(new PrivilegedGetDeclaredMethod(xmlTypeFactoryClass, GETSTRING_METHOD, new Class<?>[] { oracleOPAQUE }));
                            fieldValue = AccessController.doPrivileged(new PrivilegedMethodInvoker<>(getStringMethod, xmlTypeFactory, new Object[] { fieldValue }));
                        } else {
                            oracleOPAQUE = PrivilegedAccessHelper.getClassForName(IORACLEOPAQUE_STR, false, this.getClass().getClassLoader());
                            xmlTypeFactoryClass = PrivilegedAccessHelper.getClassForName(XMLTYPEFACTORY_STR, true, this.getClass().getClassLoader());
                            xmlTypeFactoryConstructor = PrivilegedAccessHelper.getConstructorFor(xmlTypeFactoryClass, new Class<?>[0], true);
                            xmlTypeFactory = PrivilegedAccessHelper.invokeConstructor(xmlTypeFactoryConstructor, new Object[0]);
                            getStringMethod = PrivilegedAccessHelper.getDeclaredMethod(xmlTypeFactoryClass, GETSTRING_METHOD, new Class<?>[] { oracleOPAQUE });
                            fieldValue = PrivilegedAccessHelper.invokeMethod(getStringMethod, xmlTypeFactory, new Object[] { fieldValue });
                        }
                    } catch (ReflectiveOperationException | PrivilegedActionException e) {
                        // if the required resources are not available there's nothing we can do...
                        log.logThrowable(SessionLog.FINE, SessionLog.DBWS, e);
                    }
                }
                String elementName;
                if (field.getName() == null || (elementName = sqlToXmlName(field.getName())).equals(EMPTY_STR)) {
                    // return arg from stored function has no name
                    elementName = RESULT_STR;
                }
                Element columnElement = TEMP_DOC.createElement(elementName);
                rowElement.appendChild(columnElement);
                String fieldValueString = fieldValue.toString();
                // handle binary content - attachments dealt with in invoke() above
                if (result.getType().equals(BASE_64_BINARY_QNAME)) {
                    fieldValueString = Helper.buildHexStringFromBytes(Base64.base64Encode((byte[]) fieldValue));
                    columnElement.setAttributeNS(XMLNS_URL, XSD_STR, SCHEMA_URL);
                    columnElement.setAttributeNS(XMLNS_URL, XSI_STR, SCHEMA_INSTANCE_URL);
                    columnElement.setAttributeNS(SCHEMA_INSTANCE_URL, XSITYPE_STR, BASE64_BINARY_STR);
                }
                columnElement.appendChild(TEMP_DOC.createTextNode(fieldValueString));
            }
        }
        simpleXMLFormatModel.simpleXML.add(rowElement);
    }
    xmlRoot.setObject(simpleXMLFormatModel);
    return xmlRoot;
}
Also used : SQLException(java.sql.SQLException) Element(org.w3c.dom.Element) ArrayList(java.util.ArrayList) Time(java.sql.Time) SimpleXMLFormat(org.eclipse.persistence.internal.xr.sxf.SimpleXMLFormat) DatasourceCall(org.eclipse.persistence.internal.databaseaccess.DatasourceCall) Timestamp(java.sql.Timestamp) PrivilegedGetDeclaredMethod(org.eclipse.persistence.internal.security.PrivilegedGetDeclaredMethod) Vector(java.util.Vector) ObjectRelationalDatabaseField(org.eclipse.persistence.mappings.structures.ObjectRelationalDatabaseField) Blob(java.sql.Blob) DatabaseRecord(org.eclipse.persistence.sessions.DatabaseRecord) XMLRoot(org.eclipse.persistence.oxm.XMLRoot) PrivilegedInvokeConstructor(org.eclipse.persistence.internal.security.PrivilegedInvokeConstructor) Constructor(java.lang.reflect.Constructor) Calendar(java.util.Calendar) Method(java.lang.reflect.Method) PrivilegedGetDeclaredMethod(org.eclipse.persistence.internal.security.PrivilegedGetDeclaredMethod) JPAQuery(org.eclipse.persistence.internal.jpa.JPAQuery) SimpleXMLFormatModel(org.eclipse.persistence.internal.xr.sxf.SimpleXMLFormatModel) Date(java.sql.Date) SessionLog(org.eclipse.persistence.logging.SessionLog) SQLXML(java.sql.SQLXML) OutputParameterForCallableStatement(org.eclipse.persistence.internal.databaseaccess.OutputParameterForCallableStatement) ObjectRelationalDatabaseField(org.eclipse.persistence.mappings.structures.ObjectRelationalDatabaseField) DatabaseField(org.eclipse.persistence.internal.helper.DatabaseField) XMLConversionManager(org.eclipse.persistence.internal.oxm.XMLConversionManager)

Example 4 with PrivilegedGetDeclaredMethod

use of org.eclipse.persistence.internal.security.PrivilegedGetDeclaredMethod in project eclipselink by eclipse-ee4j.

the class ManagedTypeImpl method initialize.

/**
 * INTERNAL:
 * Initialize the members of this ManagedType based on the mappings defined on the descriptor.
 * We process the appropriate Map, List, Set, Collection or Object/primitive types.<p>
 * Initialization should occur after all types in the metamodel have been created already.
 */
protected void initialize() {
    // See MappedSuperclassType.getMemberFromInheritingType()
    if (null != this.members) {
        // this is already initialized
        return;
    }
    this.members = new HashMap<String, Attribute<X, ?>>();
    // Get and process all mappings on the relationalDescriptor
    for (DatabaseMapping mapping : getDescriptor().getMappings()) {
        AttributeImpl<X, ?> member = null;
        // Tie into the collection hierarchy at a lower level
        if (mapping instanceof CollectionMapping) {
            // Handle 1:m, n:m collection mappings
            CollectionMapping colMapping = (CollectionMapping) mapping;
            ContainerPolicy collectionContainerPolicy = colMapping.getContainerPolicy();
            if (collectionContainerPolicy.isMapPolicy()) {
                // Handle the 3 Map type mappings (policy.isMappedKeyMapPolicy()) is handled by isMapPolicy())
                member = new MapAttributeImpl(this, colMapping, true);
            // check mapping.attributeAcessor.attributeField.type=Collection
            } else if (collectionContainerPolicy.isListPolicy()) {
                // This seems very over complex...
                /**
                 * Handle lazy Collections and Lists and the fact that both return an IndirectList policy.
                 * We check the type on the attributeField of the attributeAccessor on the mapping
                 */
                Class<?> aType = null;
                // 325699: AttributeAccessor is subclassed by both IntanceVariableAttributeAccessor (JPA) and ValuesAccessor (Dynamic JPA)
                if (colMapping.getAttributeAccessor() instanceof ValuesAccessor) {
                    member = new ListAttributeImpl(this, colMapping);
                } else if (colMapping.getAttributeAccessor() instanceof InstanceVariableAttributeAccessor) {
                    Field aField = ((InstanceVariableAttributeAccessor) colMapping.getAttributeAccessor()).getAttributeField();
                    // MappedSuperclasses need special handling to get their type from an inheriting subclass
                    if (null == aField) {
                        // MappedSuperclass field will not be set
                        if (this.isMappedSuperclass()) {
                            // get inheriting subtype member (without handling @override annotations)
                            MappedSuperclassTypeImpl aMappedSuperclass = ((MappedSuperclassTypeImpl) this);
                            AttributeImpl inheritingTypeMember = aMappedSuperclass.getMemberFromInheritingType(colMapping.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
                                aField = ((InstanceVariableAttributeAccessor) inheritingTypeMember.getMapping().getAttributeAccessor()).getAttributeField();
                            }
                        }
                    }
                    // 322166: The attribute may be defined on the current ManagedType - not inherited
                    if (null == aField) {
                        // Check attributeName when the field is null
                        aType = this.getTypeClassFromAttributeOrMethodLevelAccessor(mapping);
                    } else {
                        aType = aField.getType();
                    }
                    // This attribute is declared as List
                    if ((aType != null) && List.class.isAssignableFrom(aType)) {
                        member = new ListAttributeImpl(this, colMapping, true);
                    } else if ((aType != null) && Collection.class.isAssignableFrom(aType)) {
                        // This attribute is therefore declared as Collection
                        member = new CollectionAttributeImpl(this, colMapping, true);
                    } else {
                        member = initializePluralAttributeTypeNotFound(this, colMapping, true);
                    }
                } else {
                    // handle variations of missing get/set methods - only for Collection vs List
                    if (colMapping.getAttributeAccessor() instanceof MethodAttributeAccessor) {
                        /**
                         * The following call will perform a getMethod call for us.
                         * If no getMethod exists, we will secondarily check the getMethodName below.
                         */
                        aType = colMapping.getAttributeAccessor().getAttributeClass();
                        if ((aType != null) && List.class.isAssignableFrom(aType)) {
                            member = new ListAttributeImpl(this, colMapping, true);
                        } else if ((aType != null) && Collection.class.isAssignableFrom(aType)) {
                            member = new CollectionAttributeImpl(this, colMapping, true);
                        } else {
                            /**
                             * In this block we have the following scenario:
                             * 1) The access type is "field"
                             * 2) The get method is not set on the entity
                             * 3) The get method is named differently than the attribute
                             */
                            // Type may be null when no getMethod exists for the class for a ManyToMany mapping
                            // Here we check the returnType on the declared method on the class directly
                            String getMethodName = ((MethodAttributeAccessor) colMapping.getAttributeAccessor()).getGetMethodName();
                            if (null == getMethodName) {
                                // Check declaredFields in the case where we have no getMethod or getMethodName
                                try {
                                    Field field = null;
                                    if (PrivilegedAccessHelper.shouldUsePrivilegedAccess()) {
                                        try {
                                            field = AccessController.doPrivileged(new PrivilegedGetDeclaredField(this.getJavaType(), colMapping.getAttributeName(), false));
                                        } catch (PrivilegedActionException exception) {
                                            member = initializePluralAttributeTypeNotFound(this, colMapping, true);
                                        }
                                    } else {
                                        field = PrivilegedAccessHelper.getDeclaredField(this.getJavaType(), colMapping.getAttributeName(), false);
                                    }
                                    if (null == field) {
                                        member = initializePluralAttributeTypeNotFound(this, colMapping, true);
                                    } else {
                                        aType = field.getType();
                                        if ((aType != null) && List.class.isAssignableFrom(aType)) {
                                            member = new ListAttributeImpl(this, colMapping, true);
                                        } else if ((aType != null) && Collection.class.isAssignableFrom(aType)) {
                                            member = new CollectionAttributeImpl(this, colMapping, true);
                                        } else {
                                            member = initializePluralAttributeTypeNotFound(this, colMapping, true);
                                        }
                                    }
                                } catch (Exception e) {
                                    member = initializePluralAttributeTypeNotFound(this, colMapping, true);
                                }
                            } else {
                                /**
                                 * Field access Handling:
                                 * If a get method name exists, we check the return type on the method directly
                                 * using reflection.
                                 * In all failure cases we default to the List type.
                                 */
                                try {
                                    Method aMethod = null;
                                    if (PrivilegedAccessHelper.shouldUsePrivilegedAccess()) {
                                        aMethod = AccessController.doPrivileged(new PrivilegedGetDeclaredMethod(this.getJavaType(), getMethodName, null));
                                    } else {
                                        aMethod = PrivilegedAccessHelper.getDeclaredMethod(this.getJavaType(), getMethodName, null);
                                    }
                                    if (null == aMethod) {
                                        member = initializePluralAttributeTypeNotFound(this, colMapping, true);
                                    } else {
                                        aType = aMethod.getReturnType();
                                        if ((aType != null) && List.class.isAssignableFrom(aType)) {
                                            member = new ListAttributeImpl(this, colMapping, true);
                                        } else if ((aType != null) && Collection.class.isAssignableFrom(aType)) {
                                            member = new CollectionAttributeImpl(this, colMapping, true);
                                        } else {
                                            member = initializePluralAttributeTypeNotFound(this, colMapping, true);
                                        }
                                    }
                                } catch (Exception e) {
                                    member = initializePluralAttributeTypeNotFound(this, colMapping, true);
                                }
                            }
                        }
                    }
                }
            } else {
                // Handle non-lazy Collection or Set type mappings (IndirectSet.isAssignableFrom(Set.class) == false)
                if ((collectionContainerPolicy.getContainerClass() != null) && Set.class.isAssignableFrom(collectionContainerPolicy.getContainerClass())) {
                    member = new SetAttributeImpl(this, colMapping, true);
                } else {
                    // Check for non-lazy Collection policy possibly instantiated to a Set or List (both of which is ignored)
                    if (collectionContainerPolicy.isCollectionPolicy()) {
                        member = new CollectionAttributeImpl(this, colMapping, true);
                    } else {
                        // Handle Collection type mappings as a default (we should never get here)
                        // TODO: System.out.println("_Warning: defaulting to non-Set specific Collection type on " + colMapping);
                        member = new CollectionAttributeImpl(this, colMapping);
                    }
                }
            }
        } else {
            // Handle 1:1 single object and direct mappings including EnumSet
            member = new SingularAttributeImpl(this, mapping, true);
        }
        // 303063: secondary check for a null value put - should never happen but this will show on code coverage
        if (null == member) {
            AbstractSessionLog.getLog().log(SessionLog.FINEST, "metamodel_attribute_getmember_is_null", mapping.getAttributeName(), this, descriptor);
        }
        this.members.put(mapping.getAttributeName(), member);
    }
}
Also used : CollectionAttribute(jakarta.persistence.metamodel.CollectionAttribute) PluralAttribute(jakarta.persistence.metamodel.PluralAttribute) Attribute(jakarta.persistence.metamodel.Attribute) MapAttribute(jakarta.persistence.metamodel.MapAttribute) SingularAttribute(jakarta.persistence.metamodel.SingularAttribute) SetAttribute(jakarta.persistence.metamodel.SetAttribute) ListAttribute(jakarta.persistence.metamodel.ListAttribute) InstanceVariableAttributeAccessor(org.eclipse.persistence.internal.descriptors.InstanceVariableAttributeAccessor) PrivilegedGetDeclaredField(org.eclipse.persistence.internal.security.PrivilegedGetDeclaredField) Field(java.lang.reflect.Field) PrivilegedGetDeclaredField(org.eclipse.persistence.internal.security.PrivilegedGetDeclaredField) PrivilegedGetDeclaredMethod(org.eclipse.persistence.internal.security.PrivilegedGetDeclaredMethod) List(java.util.List) PrivilegedActionException(java.security.PrivilegedActionException) ValuesAccessor(org.eclipse.persistence.internal.dynamic.ValuesAccessor) DatabaseMapping(org.eclipse.persistence.mappings.DatabaseMapping) PrivilegedGetDeclaredMethod(org.eclipse.persistence.internal.security.PrivilegedGetDeclaredMethod) Method(java.lang.reflect.Method) PrivilegedActionException(java.security.PrivilegedActionException) ContainerPolicy(org.eclipse.persistence.internal.queries.ContainerPolicy) Collection(java.util.Collection) MethodAttributeAccessor(org.eclipse.persistence.internal.descriptors.MethodAttributeAccessor) CollectionMapping(org.eclipse.persistence.mappings.CollectionMapping)

Example 5 with PrivilegedGetDeclaredMethod

use of org.eclipse.persistence.internal.security.PrivilegedGetDeclaredMethod in project eclipselink by eclipse-ee4j.

the class ManagedTypeImpl method getTypeClassFromAttributeOrMethodLevelAccessor.

/**
 * INTERNAL:
 * Get the elementType directly from the class using a reflective method call
 * directly on the containing java class associated with this managedType.
 */
protected Class<?> getTypeClassFromAttributeOrMethodLevelAccessor(DatabaseMapping mapping) {
    /**
     * In this block we have the following scenario:
     * 1) The access type is "method" or "field"
     * 1a) The get method is set on the entity (method access)
     * 1b) The get method is not set on the entity (field access)
     * 1c) The get method is named differently than the attribute
     */
    // Type may be null when no getMethod exists for the class for a ManyToMany mapping
    // Here we check the returnType on the declared method on the class directly
    Class<?> aType = null;
    Field aField = null;
    String getMethodName = null;
    // 1) Check access Type
    if (mapping.getAttributeAccessor() instanceof MethodAttributeAccessor) {
        // isFieldLevelAccess = false;
        getMethodName = ((MethodAttributeAccessor) mapping.getAttributeAccessor()).getGetMethodName();
    } else if (mapping.getAttributeAccessor() instanceof InstanceVariableAttributeAccessor) {
        // isFieldLevelAccess = true;
        aField = ((InstanceVariableAttributeAccessor) mapping.getAttributeAccessor()).getAttributeField();
    }
    // 3) If field level access - perform a getDeclaredField call
    if (null == aField && this.getJavaType() != null) {
        // Check declaredFields in the case where we have no getMethod or getMethodName
        try {
            if (PrivilegedAccessHelper.shouldUsePrivilegedAccess()) {
                aField = AccessController.doPrivileged(new PrivilegedGetDeclaredField(this.getJavaType(), mapping.getAttributeName(), false));
            } else {
                aField = PrivilegedAccessHelper.getDeclaredField(this.getJavaType(), mapping.getAttributeName(), false);
            }
        } catch (PrivilegedActionException pae) {
        } catch (NoSuchFieldException nsfe) {
        }
    }
    /**
     * Field access Handling:
     * If a get method name exists, we check the return type on the method directly
     * using reflection.
     * In all failure cases we default to the List type.
     */
    if (null == aField && this.getJavaType() != null && getMethodName != null) {
        Method aMethod = null;
        try {
            if (PrivilegedAccessHelper.shouldUsePrivilegedAccess()) {
                aMethod = AccessController.doPrivileged(new PrivilegedGetDeclaredMethod(this.getJavaType(), getMethodName, null));
            } else {
                aMethod = PrivilegedAccessHelper.getDeclaredMethod(this.getJavaType(), getMethodName, null);
            }
        } catch (PrivilegedActionException pae) {
        } catch (NoSuchMethodException nsfe) {
        } catch (NullPointerException npe) {
            // case: null name arg to Class.searchMethods from getDeclaredMethod if getMethodName is null
            // because we do not know the javaType on the Type (descriptor.javaClass was null)
            // See bug# 303063
            npe.printStackTrace();
        }
        if (null != aMethod) {
            aType = aMethod.getReturnType();
        }
    }
    // MappedSuperclasses need special handling to get their type from an inheriting subclass
    if (null == aField && null == aType && this.isMappedSuperclass()) {
        // get inheriting subtype member (without handling @override annotations)
        MappedSuperclassTypeImpl aMappedSuperclass = ((MappedSuperclassTypeImpl) this);
        AttributeImpl inheritingTypeMember = aMappedSuperclass.getMemberFromInheritingType(mapping.getAttributeName());
        aField = ((InstanceVariableAttributeAccessor) inheritingTypeMember.getMapping().getAttributeAccessor()).getAttributeField();
    }
    // 6) get the type from the resulting field (method level access was handled)
    if (null != aField) {
        // field access
        aType = aField.getType();
    }
    // 7) catch unsupported element type
    if (null == aType) {
        aType = MetamodelImpl.DEFAULT_ELEMENT_TYPE_FOR_UNSUPPORTED_MAPPINGS;
    }
    // 303063: secondary check for case where descriptor has no java class set - should never happen but this will show on code coverage
    if (null == this.getJavaType()) {
        AbstractSessionLog.getLog().log(SessionLog.FINEST, SessionLog.METAMODEL, "metamodel_relationaldescriptor_javaclass_null_on_managedType", descriptor, this);
    }
    return aType;
}
Also used : InstanceVariableAttributeAccessor(org.eclipse.persistence.internal.descriptors.InstanceVariableAttributeAccessor) PrivilegedActionException(java.security.PrivilegedActionException) PrivilegedGetDeclaredMethod(org.eclipse.persistence.internal.security.PrivilegedGetDeclaredMethod) Method(java.lang.reflect.Method) PrivilegedGetDeclaredField(org.eclipse.persistence.internal.security.PrivilegedGetDeclaredField) Field(java.lang.reflect.Field) PrivilegedGetDeclaredField(org.eclipse.persistence.internal.security.PrivilegedGetDeclaredField) PrivilegedGetDeclaredMethod(org.eclipse.persistence.internal.security.PrivilegedGetDeclaredMethod) MethodAttributeAccessor(org.eclipse.persistence.internal.descriptors.MethodAttributeAccessor)

Aggregations

Method (java.lang.reflect.Method)6 PrivilegedGetDeclaredMethod (org.eclipse.persistence.internal.security.PrivilegedGetDeclaredMethod)6 PrivilegedActionException (java.security.PrivilegedActionException)3 InstanceVariableAttributeAccessor (org.eclipse.persistence.internal.descriptors.InstanceVariableAttributeAccessor)3 MethodAttributeAccessor (org.eclipse.persistence.internal.descriptors.MethodAttributeAccessor)3 PrivilegedGetDeclaredField (org.eclipse.persistence.internal.security.PrivilegedGetDeclaredField)3 PersistenceUnitInfo (jakarta.persistence.spi.PersistenceUnitInfo)2 Field (java.lang.reflect.Field)2 PrivilegedMethodInvoker (org.eclipse.persistence.internal.security.PrivilegedMethodInvoker)2 ValidationMode (jakarta.persistence.ValidationMode)1 Attribute (jakarta.persistence.metamodel.Attribute)1 CollectionAttribute (jakarta.persistence.metamodel.CollectionAttribute)1 ListAttribute (jakarta.persistence.metamodel.ListAttribute)1 MapAttribute (jakarta.persistence.metamodel.MapAttribute)1 PluralAttribute (jakarta.persistence.metamodel.PluralAttribute)1 SetAttribute (jakarta.persistence.metamodel.SetAttribute)1 SingularAttribute (jakarta.persistence.metamodel.SingularAttribute)1 Constructor (java.lang.reflect.Constructor)1 Member (java.lang.reflect.Member)1 Blob (java.sql.Blob)1