List of usage examples for org.springframework.util ReflectionUtils invokeMethod
@Nullable public static Object invokeMethod(Method method, @Nullable Object target)
From source file:org.springframework.orm.hibernate3.SessionFactoryBuilderSupport.java
/** * Populate the underlying {@code Configuration} instance with the various * properties of this builder. Customization may be performed through * {@code pre*} and {@code post*} methods. * @see #preBuildSessionFactory()// w w w. j a va2 s . com * @see #postProcessMappings() * @see #postBuildSessionFactory() * @see #postBuildSessionFactory() */ protected final SessionFactory doBuildSessionFactory() throws Exception { initializeConfigurationIfNecessary(); if (this.dataSource != null) { // Make given DataSource available for SessionFactory configuration. configTimeDataSourceHolder.set(this.dataSource); } if (this.jtaTransactionManager != null) { // Make Spring-provided JTA TransactionManager available. configTimeTransactionManagerHolder.set(this.jtaTransactionManager); } if (this.cacheRegionFactory != null) { // Make Spring-provided Hibernate RegionFactory available. configTimeRegionFactoryHolder.set(this.cacheRegionFactory); } if (this.lobHandler != null) { // Make given LobHandler available for SessionFactory configuration. // Do early because because mapping resource might refer to custom types. configTimeLobHandlerHolder.set(this.lobHandler); } try { if (isExposeTransactionAwareSessionFactory()) { // Set Hibernate 3.1+ CurrentSessionContext implementation, // providing the Spring-managed Session as current Session. // Can be overridden by a custom value for the corresponding Hibernate property. this.configuration.setProperty(Environment.CURRENT_SESSION_CONTEXT_CLASS, SpringSessionContext.class.getName()); } if (this.jtaTransactionManager != null) { // Set Spring-provided JTA TransactionManager as Hibernate property. this.configuration.setProperty(Environment.TRANSACTION_STRATEGY, JTATransactionFactory.class.getName()); this.configuration.setProperty(Environment.TRANSACTION_MANAGER_STRATEGY, LocalTransactionManagerLookup.class.getName()); } else { // Makes the Hibernate Session aware of the presence of a Spring-managed transaction. // Also sets connection release mode to ON_CLOSE by default. this.configuration.setProperty(Environment.TRANSACTION_STRATEGY, SpringTransactionFactory.class.getName()); } if (this.entityInterceptor != null) { // Set given entity interceptor at SessionFactory level. this.configuration.setInterceptor(this.entityInterceptor); } if (this.namingStrategy != null) { // Pass given naming strategy to Hibernate Configuration. this.configuration.setNamingStrategy(this.namingStrategy); } if (this.typeDefinitions != null) { // Register specified Hibernate type definitions. // Use reflection for compatibility with both Hibernate 3.3 and 3.5: // the returned Mappings object changed from a class to an interface. Method createMappings = Configuration.class.getMethod("createMappings"); Method addTypeDef = createMappings.getReturnType().getMethod("addTypeDef", String.class, String.class, Properties.class); Object mappings = ReflectionUtils.invokeMethod(createMappings, this.configuration); for (TypeDefinitionBean typeDef : this.typeDefinitions) { ReflectionUtils.invokeMethod(addTypeDef, mappings, typeDef.getTypeName(), typeDef.getTypeClass(), typeDef.getParameters()); } } if (this.filterDefinitions != null) { // Register specified Hibernate FilterDefinitions. for (FilterDefinition filterDef : this.filterDefinitions) { this.configuration.addFilterDefinition(filterDef); } } if (this.configLocations != null) { for (Resource resource : this.configLocations) { // Load Hibernate configuration from given location. this.configuration.configure(resource.getURL()); } } if (this.hibernateProperties != null) { // Add given Hibernate properties to Configuration. this.configuration.addProperties(this.hibernateProperties); } if (dataSource != null) { Class<?> providerClass = LocalDataSourceConnectionProvider.class; if (isUseTransactionAwareDataSource() || dataSource instanceof TransactionAwareDataSourceProxy) { providerClass = TransactionAwareDataSourceConnectionProvider.class; } else if (this.configuration.getProperty(Environment.TRANSACTION_MANAGER_STRATEGY) != null) { providerClass = LocalJtaDataSourceConnectionProvider.class; } // Set Spring-provided DataSource as Hibernate ConnectionProvider. this.configuration.setProperty(Environment.CONNECTION_PROVIDER, providerClass.getName()); } if (this.cacheRegionFactory != null) { // Expose Spring-provided Hibernate RegionFactory. this.configuration.setProperty(Environment.CACHE_REGION_FACTORY, "org.springframework.orm.hibernate3.LocalRegionFactoryProxy"); } if (this.mappingResources != null) { // Register given Hibernate mapping definitions, contained in resource files. for (String mapping : this.mappingResources) { Resource resource = new ClassPathResource(mapping.trim(), this.beanClassLoader); this.configuration.addInputStream(resource.getInputStream()); } } if (this.mappingLocations != null) { // Register given Hibernate mapping definitions, contained in resource files. for (Resource resource : this.mappingLocations) { this.configuration.addInputStream(resource.getInputStream()); } } if (this.cacheableMappingLocations != null) { // Register given cacheable Hibernate mapping definitions, read from the file system. for (Resource resource : this.cacheableMappingLocations) { this.configuration.addCacheableFile(resource.getFile()); } } if (this.mappingJarLocations != null) { // Register given Hibernate mapping definitions, contained in jar files. for (Resource resource : this.mappingJarLocations) { this.configuration.addJar(resource.getFile()); } } if (this.mappingDirectoryLocations != null) { // Register all Hibernate mapping definitions in the given directories. for (Resource resource : this.mappingDirectoryLocations) { File file = resource.getFile(); if (!file.isDirectory()) { throw new IllegalArgumentException( "Mapping directory location [" + resource + "] does not denote a directory"); } this.configuration.addDirectory(file); } } // Tell Hibernate to eagerly compile the mappings that we registered, // for availability of the mapping information in further processing. postProcessMappings(); this.configuration.buildMappings(); if (this.entityCacheStrategies != null) { // Register cache strategies for mapped entities. for (Enumeration<?> classNames = this.entityCacheStrategies.propertyNames(); classNames .hasMoreElements();) { String className = (String) classNames.nextElement(); String[] strategyAndRegion = StringUtils .commaDelimitedListToStringArray(this.entityCacheStrategies.getProperty(className)); if (strategyAndRegion.length > 1) { // method signature declares return type as Configuration on Hibernate 3.6 // but as void on Hibernate 3.3 and 3.5 Method setCacheConcurrencyStrategy = Configuration.class .getMethod("setCacheConcurrencyStrategy", String.class, String.class, String.class); ReflectionUtils.invokeMethod(setCacheConcurrencyStrategy, this.configuration, className, strategyAndRegion[0], strategyAndRegion[1]); } else if (strategyAndRegion.length > 0) { this.configuration.setCacheConcurrencyStrategy(className, strategyAndRegion[0]); } } } if (this.collectionCacheStrategies != null) { // Register cache strategies for mapped collections. for (Enumeration<?> collRoles = this.collectionCacheStrategies.propertyNames(); collRoles .hasMoreElements();) { String collRole = (String) collRoles.nextElement(); String[] strategyAndRegion = StringUtils .commaDelimitedListToStringArray(this.collectionCacheStrategies.getProperty(collRole)); if (strategyAndRegion.length > 1) { this.configuration.setCollectionCacheConcurrencyStrategy(collRole, strategyAndRegion[0], strategyAndRegion[1]); } else if (strategyAndRegion.length > 0) { this.configuration.setCollectionCacheConcurrencyStrategy(collRole, strategyAndRegion[0]); } } } if (this.eventListeners != null) { // Register specified Hibernate event listeners. for (Map.Entry<String, Object> entry : this.eventListeners.entrySet()) { String listenerType = entry.getKey(); Object listenerObject = entry.getValue(); if (listenerObject instanceof Collection) { Collection<?> listeners = (Collection<?>) listenerObject; EventListeners listenerRegistry = this.configuration.getEventListeners(); Object[] listenerArray = (Object[]) Array .newInstance(listenerRegistry.getListenerClassFor(listenerType), listeners.size()); listenerArray = listeners.toArray(listenerArray); this.configuration.setListeners(listenerType, listenerArray); } else { this.configuration.setListener(listenerType, listenerObject); } } } preBuildSessionFactory(); // Perform custom post-processing in subclasses. postProcessConfiguration(); // Build SessionFactory instance. logger.info("Building new Hibernate SessionFactory"); return this.sessionFactory = newSessionFactory(); } finally { if (dataSource != null) { SessionFactoryBuilderSupport.configTimeDataSourceHolder.remove(); } if (this.jtaTransactionManager != null) { SessionFactoryBuilderSupport.configTimeTransactionManagerHolder.remove(); } if (this.cacheRegionFactory != null) { SessionFactoryBuilderSupport.configTimeRegionFactoryHolder.remove(); } if (this.lobHandler != null) { SessionFactoryBuilderSupport.configTimeLobHandlerHolder.remove(); } postBuildSessionFactory(); } }
From source file:org.springframework.orm.hibernate4.SessionFactoryUtils.java
/** * Determine the DataSource of the given SessionFactory. * @param sessionFactory the SessionFactory to check * @return the DataSource, or {@code null} if none found * @see org.hibernate.engine.spi.SessionFactoryImplementor#getConnectionProvider *//*from w w w.j a v a 2 s .co m*/ public static DataSource getDataSource(SessionFactory sessionFactory) { if (getConnectionProviderMethod != null && sessionFactory instanceof SessionFactoryImplementor) { Wrapped cp = (Wrapped) ReflectionUtils.invokeMethod(getConnectionProviderMethod, sessionFactory); if (cp != null) { return cp.unwrap(DataSource.class); } } return null; }
From source file:org.springframework.orm.hibernate4.SpringSessionContext.java
/** * Create a new SpringSessionContext for the given Hibernate SessionFactory. * @param sessionFactory the SessionFactory to provide current Sessions for */// w w w . java 2 s. c o m public SpringSessionContext(SessionFactoryImplementor sessionFactory) { this.sessionFactory = sessionFactory; try { Object jtaPlatform = sessionFactory.getServiceRegistry() .getService(ConfigurableJtaPlatform.jtaPlatformClass); Method rtmMethod = ConfigurableJtaPlatform.jtaPlatformClass.getMethod("retrieveTransactionManager"); this.transactionManager = (TransactionManager) ReflectionUtils.invokeMethod(rtmMethod, jtaPlatform); if (this.transactionManager != null) { this.jtaSessionContext = new SpringJtaSessionContext(sessionFactory); } } catch (Exception ex) { LogFactory.getLog(SpringSessionContext.class) .warn("Could not introspect Hibernate JtaPlatform for SpringJtaSessionContext", ex); } }
From source file:org.springframework.orm.hibernate5.SessionFactoryUtils.java
/** * Get the native Hibernate FlushMode, adapting between Hibernate 5.0/5.1 and 5.2+. * @param session the Hibernate Session to get the flush mode from * @return the FlushMode (never {@code null}) * @since 4.3/* www . ja v a 2s . c o m*/ */ static FlushMode getFlushMode(Session session) { FlushMode flushMode = (FlushMode) ReflectionUtils.invokeMethod(getFlushMode, session); Assert.state(flushMode != null, "No FlushMode from Session"); return flushMode; }
From source file:org.springframework.orm.hibernate5.SessionFactoryUtils.java
/** * Determine the DataSource of the given SessionFactory. * @param sessionFactory the SessionFactory to check * @return the DataSource, or {@code null} if none found * @see ConnectionProvider//ww w.j av a2 s.c om */ @Nullable public static DataSource getDataSource(SessionFactory sessionFactory) { Method getProperties = ClassUtils.getMethodIfAvailable(sessionFactory.getClass(), "getProperties"); if (getProperties != null) { Map<?, ?> props = (Map<?, ?>) ReflectionUtils.invokeMethod(getProperties, sessionFactory); if (props != null) { Object dataSourceValue = props.get(Environment.DATASOURCE); if (dataSourceValue instanceof DataSource) { return (DataSource) dataSourceValue; } } } if (sessionFactory instanceof SessionFactoryImplementor) { SessionFactoryImplementor sfi = (SessionFactoryImplementor) sessionFactory; try { ConnectionProvider cp = sfi.getServiceRegistry().getService(ConnectionProvider.class); if (cp != null) { return cp.unwrap(DataSource.class); } } catch (UnknownServiceException ex) { if (logger.isDebugEnabled()) { logger.debug( "No ConnectionProvider found - cannot determine DataSource for SessionFactory: " + ex); } } } return null; }
From source file:org.springframework.orm.jpa.vendor.HibernateJpaDialect.java
@SuppressWarnings("deprecation") @Nullable//from w ww . j av a2 s .c om protected FlushMode prepareFlushMode(Session session, boolean readOnly) throws PersistenceException { FlushMode flushMode = (FlushMode) ReflectionUtils.invokeMethod(getFlushMode, session); Assert.state(flushMode != null, "No FlushMode from Session"); if (readOnly) { // We should suppress flushing for a read-only transaction. if (!flushMode.equals(FlushMode.MANUAL)) { session.setFlushMode(FlushMode.MANUAL); return flushMode; } } else { // We need AUTO or COMMIT for a non-read-only transaction. if (flushMode.lessThan(FlushMode.COMMIT)) { session.setFlushMode(FlushMode.AUTO); return flushMode; } } // No FlushMode change needed... return null; }
From source file:org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener.java
@Nullable private DataSource getDataSourceFromTransactionManager(PlatformTransactionManager transactionManager) { try {/* w w w . j av a 2 s .c om*/ Method getDataSourceMethod = transactionManager.getClass().getMethod("getDataSource"); Object obj = ReflectionUtils.invokeMethod(getDataSourceMethod, transactionManager); if (obj instanceof DataSource) { return (DataSource) obj; } } catch (Exception ex) { // ignore } return null; }
From source file:org.springframework.test.util.ReflectionTestUtils.java
/** * Invoke the getter method with the given {@code name} on the supplied * target object with the supplied {@code value}. * <p>This method traverses the class hierarchy in search of the desired * method. In addition, an attempt will be made to make non-{@code public} * methods <em>accessible</em>, thus allowing one to invoke {@code protected}, * {@code private}, and <em>package-private</em> getter methods. * <p>In addition, this method supports JavaBean-style <em>property</em> * names. For example, if you wish to get the {@code name} property on the * target object, you may pass either "name" or * "getName" as the method name. * @param target the target object on which to invoke the specified getter * method//from w w w . ja v a 2 s .co m * @param name the name of the getter method to invoke or the corresponding * property name * @return the value returned from the invocation * @see ReflectionUtils#findMethod(Class, String, Class[]) * @see ReflectionUtils#makeAccessible(Method) * @see ReflectionUtils#invokeMethod(Method, Object, Object[]) */ @Nullable public static Object invokeGetterMethod(Object target, String name) { Assert.notNull(target, "Target object must not be null"); Assert.hasText(name, "Method name must not be empty"); String getterMethodName = name; if (!name.startsWith(GETTER_PREFIX)) { getterMethodName = GETTER_PREFIX + StringUtils.capitalize(name); } Method method = ReflectionUtils.findMethod(target.getClass(), getterMethodName); if (method == null && !getterMethodName.equals(name)) { getterMethodName = name; method = ReflectionUtils.findMethod(target.getClass(), getterMethodName); } if (method == null) { throw new IllegalArgumentException(String.format("Could not find getter method '%s' on %s", getterMethodName, safeToString(target))); } if (logger.isDebugEnabled()) { logger.debug( String.format("Invoking getter method '%s' on %s", getterMethodName, safeToString(target))); } ReflectionUtils.makeAccessible(method); return ReflectionUtils.invokeMethod(method, target); }
From source file:org.springframework.web.context.request.FacesRequestAttributes.java
@Override public String getSessionId() { Object session = getExternalContext().getSession(true); try {//from w w w .j av a2 s. c o m // Both HttpSession and PortletSession have a getId() method. Method getIdMethod = session.getClass().getMethod("getId"); return String.valueOf(ReflectionUtils.invokeMethod(getIdMethod, session)); } catch (NoSuchMethodException ex) { throw new IllegalStateException("Session object [" + session + "] does not have a getId() method"); } }
From source file:org.springframework.yarn.support.compat.NMTokenCacheCompat.java
/** * Gets the Hadoop {@code NMTokenCache}. Access token cache via singleton * method if exists, otherwise assumes that class is hadoop vanilla * implementation with static methods where we can just use default * constructor and further access for those static method would * got via instance itself.//from w w w . j a va 2s. c om * <p> * This is due to a fact that i.e. cloudera modified this class by * removing static methods and made access to it via singleton pattern. * * @return the token cache */ public static NMTokenCache getNMTokenCache() { if (nmTokenCache == null) { synchronized (lock) { if (nmTokenCache == null) { Method singletonMethod = ReflectionUtils.findMethod(NMTokenCache.class, "getSingleton"); if (singletonMethod != null) { if (log.isDebugEnabled()) { log.debug("Creating NMTokenCache using NMTokenCache.getSingleton()"); } nmTokenCache = (NMTokenCache) ReflectionUtils.invokeMethod(singletonMethod, null); } else { log.debug( "Creating NMTokenCache using constructor, further access via instance static methods."); nmTokenCache = new NMTokenCache(); } } } } return nmTokenCache; }