idx int64 0 41.2k | question stringlengths 74 4.04k | target stringlengths 7 750 |
|---|---|---|
34,800 | private String getPropertyName ( final String windowIdStr , final String fullAttributeName ) { final String attributeName ; if ( this . nonNamespacedProperties . contains ( fullAttributeName ) ) { attributeName = fullAttributeName ; } else if ( fullAttributeName . startsWith ( windowIdStr ) ) { attributeName = fullAttributeName . substring ( windowIdStr . length ( ) ) ; } else { return null ; } final String mappedPropertyName = this . attributeToPropertyMappings . get ( attributeName ) ; if ( mappedPropertyName == null ) { logger . warn ( "Attribute {} found that matches the portlet window ID but it is not listed in the propertyMappings or nonNamespacedProperties and will not be returned to the portlet" , attributeName ) ; return null ; } return mappedPropertyName ; } | Convert a request attribute name to a portlet property name |
34,801 | public void addParameter ( String paramName , String paramValue ) { this . parameters . add ( new StructureParameter ( paramName , paramValue ) ) ; } | Add a parameter to this LayoutStructure . |
34,802 | protected void addFetches ( final Root < StylesheetUserPreferencesImpl > descriptorRoot ) { descriptorRoot . fetch ( StylesheetUserPreferencesImpl_ . layoutAttributes , JoinType . LEFT ) ; descriptorRoot . fetch ( StylesheetUserPreferencesImpl_ . outputProperties , JoinType . LEFT ) ; descriptorRoot . fetch ( StylesheetUserPreferencesImpl_ . parameters , JoinType . LEFT ) ; } | Add the needed fetches to a critera query |
34,803 | private void initialize ( ) { String sep ; try { sep = GroupServiceConfiguration . getConfiguration ( ) . getNodeSeparator ( ) ; } catch ( Exception ex ) { sep = DEFAULT_NODE_SEPARATOR ; } groupNodeSeparator = sep ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "RDBMEntityGroupStore.initialize(): Node separator set to " + sep ) ; } } | Get the node separator character from the GroupServiceConfiguration . Default it to IGroupConstants . DEFAULT_NODE_SEPARATOR . |
34,804 | public void delete ( IEntityGroup group ) throws GroupsException { if ( existsInDatabase ( group ) ) { try { primDelete ( group ) ; } catch ( SQLException sqle ) { throw new GroupsException ( "Problem deleting " + group , sqle ) ; } } } | If this entity exists delete it . |
34,805 | private boolean existsInDatabase ( IEntityGroup group ) throws GroupsException { IEntityGroup ug = this . find ( group . getLocalKey ( ) ) ; return ug != null ; } | Answer if the IEntityGroup entity exists in the database . |
34,806 | public java . util . Iterator findParentGroups ( IEntity ent ) throws GroupsException { String memberKey = ent . getKey ( ) ; Integer type = EntityTypesLocator . getEntityTypes ( ) . getEntityIDFromType ( ent . getLeafType ( ) ) ; return findParentGroupsForEntity ( memberKey , type . intValue ( ) ) ; } | Find the groups that this entity belongs to . |
34,807 | public java . util . Iterator findParentGroups ( IEntityGroup group ) throws GroupsException { String memberKey = group . getLocalKey ( ) ; String serviceName = group . getServiceName ( ) . toString ( ) ; Integer type = EntityTypesLocator . getEntityTypes ( ) . getEntityIDFromType ( group . getLeafType ( ) ) ; return findParentGroupsForGroup ( serviceName , memberKey , type . intValue ( ) ) ; } | Find the groups that this group belongs to . |
34,808 | public Iterator findParentGroups ( IGroupMember gm ) throws GroupsException { if ( gm . isGroup ( ) ) { IEntityGroup group = ( IEntityGroup ) gm ; return findParentGroups ( group ) ; } else { IEntity ent = ( IEntity ) gm ; return findParentGroups ( ent ) ; } } | Find the groups that this group member belongs to . |
34,809 | private java . util . Iterator findParentGroupsForEntity ( String memberKey , int type ) throws GroupsException { Connection conn = null ; Collection groups = new ArrayList ( ) ; IEntityGroup eg = null ; try { conn = RDBMServices . getConnection ( ) ; String sql = getFindParentGroupsForEntitySql ( ) ; PreparedStatement ps = conn . prepareStatement ( sql ) ; try { ps . setString ( 1 , memberKey ) ; ps . setInt ( 2 , type ) ; if ( LOG . isDebugEnabled ( ) ) LOG . debug ( "RDBMEntityGroupStore.findParentGroupsForEntity(): " + ps + " (" + memberKey + ", " + type + ", memberIsGroup = F)" ) ; ResultSet rs = ps . executeQuery ( ) ; try { while ( rs . next ( ) ) { eg = instanceFromResultSet ( rs ) ; groups . add ( eg ) ; } } finally { rs . close ( ) ; } } finally { ps . close ( ) ; } } catch ( Exception e ) { LOG . error ( "RDBMEntityGroupStore.findParentGroupsForEntity(): " + e ) ; throw new GroupsException ( "Problem retrieving containing groups: " + e ) ; } finally { RDBMServices . releaseConnection ( conn ) ; } return groups . iterator ( ) ; } | Find the groups associated with this member key . |
34,810 | public String [ ] findMemberGroupKeys ( IEntityGroup group ) throws GroupsException { Connection conn = null ; Collection groupKeys = new ArrayList ( ) ; String groupKey = null ; try { conn = RDBMServices . getConnection ( ) ; String sql = getFindMemberGroupKeysSql ( ) ; PreparedStatement ps = conn . prepareStatement ( sql ) ; try { ps . setString ( 1 , group . getLocalKey ( ) ) ; if ( LOG . isDebugEnabled ( ) ) LOG . debug ( "RDBMEntityGroupStore.findMemberGroupKeys(): " + ps + " (" + group . getLocalKey ( ) + ")" ) ; ResultSet rs = ps . executeQuery ( ) ; try { while ( rs . next ( ) ) { groupKey = rs . getString ( 1 ) + groupNodeSeparator + rs . getString ( 2 ) ; groupKeys . add ( groupKey ) ; } } finally { rs . close ( ) ; } } finally { ps . close ( ) ; } } catch ( Exception sqle ) { LOG . error ( "RDBMEntityGroupStore.findMemberGroupKeys(): " + sqle ) ; throw new GroupsException ( "Problem retrieving member group keys: " + sqle ) ; } finally { RDBMServices . releaseConnection ( conn ) ; } return ( String [ ] ) groupKeys . toArray ( new String [ groupKeys . size ( ) ] ) ; } | Find the keys of groups that are members of group . |
34,811 | public Iterator findMemberGroups ( IEntityGroup group ) throws GroupsException { Connection conn = null ; Collection groups = new ArrayList ( ) ; IEntityGroup eg = null ; String serviceName = group . getServiceName ( ) . toString ( ) ; String localKey = group . getLocalKey ( ) ; try { conn = RDBMServices . getConnection ( ) ; String sql = getFindMemberGroupsSql ( ) ; PreparedStatement ps = conn . prepareStatement ( sql ) ; try { ps . setString ( 1 , localKey ) ; ps . setString ( 2 , serviceName ) ; if ( LOG . isDebugEnabled ( ) ) LOG . debug ( "RDBMEntityGroupStore.findMemberGroups(): " + ps + " (" + localKey + ", " + serviceName + ")" ) ; ResultSet rs = ps . executeQuery ( ) ; try { while ( rs . next ( ) ) { eg = instanceFromResultSet ( rs ) ; groups . add ( eg ) ; } } finally { rs . close ( ) ; } } finally { ps . close ( ) ; } } catch ( Exception sqle ) { LOG . error ( "RDBMEntityGroupStore.findMemberGroups(): " + sqle ) ; throw new GroupsException ( "Problem retrieving member groups: " + sqle ) ; } finally { RDBMServices . releaseConnection ( conn ) ; } return groups . iterator ( ) ; } | Find the IUserGroups that are members of the group . |
34,812 | private void primDelete ( IEntityGroup group ) throws SQLException { Connection conn = null ; String deleteGroupSql = getDeleteGroupSql ( group ) ; String deleteMembershipSql = getDeleteMembersInGroupSql ( group ) ; try { conn = RDBMServices . getConnection ( ) ; Statement stmnt = conn . createStatement ( ) ; setAutoCommit ( conn , false ) ; try { if ( LOG . isDebugEnabled ( ) ) LOG . debug ( "RDBMEntityGroupStore.primDelete(): " + deleteMembershipSql ) ; stmnt . executeUpdate ( deleteMembershipSql ) ; if ( LOG . isDebugEnabled ( ) ) LOG . debug ( "RDBMEntityGroupStore.primDelete(): " + deleteGroupSql ) ; stmnt . executeUpdate ( deleteGroupSql ) ; } finally { stmnt . close ( ) ; } commit ( conn ) ; } catch ( SQLException sqle ) { rollback ( conn ) ; throw sqle ; } finally { try { setAutoCommit ( conn , true ) ; } finally { RDBMServices . releaseConnection ( conn ) ; } } } | Delete this entity from the database after first deleting its memberships . Exception SQLException - if we catch a SQLException we rollback and re - throw it . |
34,813 | private void primUpdate ( IEntityGroup group , Connection conn ) throws SQLException , GroupsException { try { PreparedStatement ps = conn . prepareStatement ( getUpdateGroupSql ( ) ) ; try { Integer typeID = EntityTypesLocator . getEntityTypes ( ) . getEntityIDFromType ( group . getLeafType ( ) ) ; ps . setString ( 1 , group . getCreatorID ( ) ) ; ps . setInt ( 2 , typeID . intValue ( ) ) ; ps . setString ( 3 , group . getName ( ) ) ; ps . setString ( 4 , group . getDescription ( ) ) ; ps . setString ( 5 , group . getLocalKey ( ) ) ; if ( LOG . isDebugEnabled ( ) ) LOG . debug ( "RDBMEntityGroupStore.primUpdate(): " + ps + "(" + group . getCreatorID ( ) + ", " + typeID + ", " + group . getName ( ) + ", " + group . getDescription ( ) + ", " + group . getLocalKey ( ) + ")" ) ; int rc = ps . executeUpdate ( ) ; if ( rc != 1 ) { String errString = "Problem updating " + group ; LOG . error ( errString ) ; throw new GroupsException ( errString ) ; } } finally { ps . close ( ) ; } } catch ( SQLException sqle ) { LOG . error ( "Error updating entity in database. Group: " + group , sqle ) ; throw sqle ; } } | Update the entity in the database . |
34,814 | public void update ( IEntityGroup group ) throws GroupsException { Connection conn = null ; boolean exists = existsInDatabase ( group ) ; try { conn = RDBMServices . getConnection ( ) ; setAutoCommit ( conn , false ) ; try { if ( exists ) { primUpdate ( group , conn ) ; } else { primAdd ( group , conn ) ; } primUpdateMembers ( ( EntityGroupImpl ) group , conn ) ; commit ( conn ) ; } catch ( Exception ex ) { rollback ( conn ) ; throw new GroupsException ( "Problem updating " + this + ex ) ; } } catch ( SQLException sqlex ) { throw new GroupsException ( sqlex ) ; } finally { if ( conn != null ) { try { setAutoCommit ( conn , true ) ; } catch ( SQLException sqle ) { throw new GroupsException ( sqle ) ; } finally { RDBMServices . releaseConnection ( conn ) ; } } } } | Commit this entity AND ITS MEMBERSHIPS to the underlying store . |
34,815 | public void updateMembers ( IEntityGroup eg ) throws GroupsException { Connection conn = null ; EntityGroupImpl egi = ( EntityGroupImpl ) eg ; if ( egi . isDirty ( ) ) try { conn = RDBMServices . getConnection ( ) ; setAutoCommit ( conn , false ) ; try { primUpdateMembers ( egi , conn ) ; commit ( conn ) ; } catch ( SQLException sqle ) { rollback ( conn ) ; throw new GroupsException ( "Problem updating memberships for " + egi , sqle ) ; } } catch ( SQLException sqlex ) { throw new GroupsException ( sqlex ) ; } finally { if ( conn != null ) { try { setAutoCommit ( conn , true ) ; } catch ( SQLException sqle ) { throw new GroupsException ( sqle ) ; } finally { RDBMServices . releaseConnection ( conn ) ; } } } } | Insert and delete group membership rows inside a transaction . |
34,816 | protected String evaluateSpelExpression ( String value , PortletRequest request ) { if ( StringUtils . isNotBlank ( value ) ) { String result = portletSpELService . parseString ( value , request ) ; return result ; } throw new IllegalArgumentException ( "SQL Query expression required" ) ; } | Substitute any SpEL expressions with values from the PortletRequest and other attributes added to the SpEL context . |
34,817 | private Cache getCache ( PortletRequest req ) { String cacheName = req . getPreferences ( ) . getValue ( PREF_CACHE_NAME , DEFAULT_CACHE_NAME ) ; if ( StringUtils . isNotBlank ( cacheName ) ) { log . debug ( "Looking up cache '{}'" , cacheName ) ; Cache cache = CacheManager . getInstance ( ) . getCache ( cacheName ) ; if ( cache == null ) { throw new RuntimeException ( "Unable to find cache named " + cacheName + ". Check portlet preference value " + PREF_CACHE_NAME + " and configuration in ehcache.xml" ) ; } return cache ; } else { log . debug ( "Portlet preference {} set to empty string; disabling caching for this portlet instance" , PREF_CACHE_NAME ) ; return null ; } } | Obtain the cache configured for this portlet instance . |
34,818 | public boolean preHandle ( HttpServletRequest request , HttpServletResponse response , Object handler ) throws Exception { final List < IRequestParameterProcessor > incompleteDynamicProcessors = new LinkedList < IRequestParameterProcessor > ( this . dynamicRequestParameterProcessors ) ; int cycles = 0 ; while ( incompleteDynamicProcessors . size ( ) > 0 ) { for ( final Iterator < IRequestParameterProcessor > processorItr = incompleteDynamicProcessors . iterator ( ) ; processorItr . hasNext ( ) ; ) { final IRequestParameterProcessor requestParameterProcessor = processorItr . next ( ) ; final boolean complete = requestParameterProcessor . processParameters ( request , response ) ; if ( complete ) { processorItr . remove ( ) ; } } cycles ++ ; if ( cycles >= this . maxNumberOfProcessingCycles ) { this . logger . warn ( incompleteDynamicProcessors . size ( ) + " IDynamicRequestParameterProcessors did not complete processing after " + cycles + " attempts. Execution will continue but this situation should be reviewed. Incomplete Processors=" + incompleteDynamicProcessors , new Throwable ( "Stack Trace" ) ) ; break ; } } return true ; } | Process the request first with the dynamic processors until all are complete and then the static processors . |
34,819 | private HashMap < String , String > getPropertyFromRequest ( HashMap < String , String > tokens , HttpServletRequest request ) { HashMap < String , String > retHash = new HashMap < > ( ) ; for ( Map . Entry < String , String > entry : tokens . entrySet ( ) ) { String contextName = entry . getKey ( ) ; String parmName = entry . getValue ( ) ; String parmValue ; if ( request . getAttribute ( parmName ) != null ) { try { parmValue = ( String ) request . getAttribute ( parmName ) ; } catch ( ClassCastException cce ) { String msg = "The request attribute '" + parmName + "' must be a String." ; throw new RuntimeException ( msg , cce ) ; } } else { parmValue = request . getParameter ( parmName ) ; } if ( "password" . equals ( parmName ) ) { parmValue = ( parmValue == null ? "" : parmValue ) ; } else { parmValue = ( parmValue == null ? "" : parmValue ) . trim ( ) ; } String key = ( contextName . startsWith ( "root." ) ? contextName . substring ( 5 ) : contextName ) ; retHash . put ( key , parmValue ) ; } return ( retHash ) ; } | Get the values represented by each token from the request and load them into a HashMap that is returned . |
34,820 | public void add ( IEntityLock lock ) throws LockingException { Connection conn = null ; try { conn = RDBMServices . getConnection ( ) ; primDeleteExpired ( new Date ( ) , lock . getEntityType ( ) , lock . getEntityKey ( ) , conn ) ; primAdd ( lock , conn ) ; } catch ( SQLException sqle ) { throw new LockingException ( "Problem creating " + lock , sqle ) ; } finally { RDBMServices . releaseConnection ( conn ) ; } } | Adds the lock to the underlying store . |
34,821 | public void delete ( IEntityLock lock ) throws LockingException { Connection conn = null ; try { conn = RDBMServices . getConnection ( ) ; primDelete ( lock , conn ) ; } catch ( SQLException sqle ) { throw new LockingException ( "Problem deleting " + lock , sqle ) ; } finally { RDBMServices . releaseConnection ( conn ) ; } } | If this IEntityLock exists delete it . |
34,822 | public void deleteAll ( ) throws LockingException { Connection conn = null ; Statement stmnt = null ; try { String sql = "DELETE FROM " + LOCK_TABLE ; if ( log . isDebugEnabled ( ) ) log . debug ( "RDBMEntityLockStore.deleteAll(): " + sql ) ; conn = RDBMServices . getConnection ( ) ; try { stmnt = conn . createStatement ( ) ; int rc = stmnt . executeUpdate ( sql ) ; if ( log . isDebugEnabled ( ) ) { String msg = "Deleted " + rc + " locks." ; log . debug ( "RDBMEntityLockStore.deleteAll(): " + msg ) ; } } finally { if ( stmnt != null ) stmnt . close ( ) ; } } catch ( SQLException sqle ) { throw new LockingException ( "Problem deleting locks" , sqle ) ; } finally { RDBMServices . releaseConnection ( conn ) ; } } | Delete all IEntityLocks from the underlying store . |
34,823 | public void deleteExpired ( IEntityLock lock ) throws LockingException { deleteExpired ( new Date ( ) , lock . getEntityType ( ) , lock . getEntityKey ( ) ) ; } | Delete all expired IEntityLocks from the underlying store . |
34,824 | public IEntityLock [ ] findUnexpired ( Date expiration , Class entityType , String entityKey , Integer lockType , String lockOwner ) throws LockingException { Timestamp ts = new Timestamp ( expiration . getTime ( ) ) ; return selectUnexpired ( ts , entityType , entityKey , lockType , lockOwner ) ; } | Retrieve IEntityLocks from the underlying store . Expiration must not be null . |
34,825 | private static String getDeleteLockSql ( ) { if ( deleteLockSql == null ) { deleteLockSql = "DELETE FROM " + LOCK_TABLE + " WHERE " + ENTITY_TYPE_COLUMN + EQ + "?" + " AND " + ENTITY_KEY_COLUMN + EQ + "?" + " AND " + EXPIRATION_TIME_COLUMN + EQ + "?" + " AND " + LOCK_TYPE_COLUMN + EQ + "?" + " AND " + LOCK_OWNER_COLUMN + EQ + "?" ; } return deleteLockSql ; } | SQL for deleting a row on the lock table . |
34,826 | private static String getUpdateSql ( ) { if ( updateSql == null ) { updateSql = "UPDATE " + LOCK_TABLE + " SET " + EXPIRATION_TIME_COLUMN + EQ + "?, " + LOCK_TYPE_COLUMN + EQ + "?" + " WHERE " + ENTITY_TYPE_COLUMN + EQ + "?" + " AND " + ENTITY_KEY_COLUMN + EQ + "?" + " AND " + LOCK_OWNER_COLUMN + EQ + "?" + " AND " + EXPIRATION_TIME_COLUMN + EQ + "?" + " AND " + LOCK_TYPE_COLUMN + EQ + "?" ; } return updateSql ; } | SQL for updating a row on the lock table . |
34,827 | private void initialize ( ) throws LockingException { Date expiration = new Date ( System . currentTimeMillis ( ) - ( 60 * 60 * 1000 ) ) ; deleteExpired ( expiration , null , null ) ; } | Cleanup the store by deleting locks expired an hour ago . |
34,828 | private IEntityLock instanceFromResultSet ( java . sql . ResultSet rs ) throws SQLException , LockingException { Integer entityTypeID = rs . getInt ( 1 ) ; Class entityType = EntityTypesLocator . getEntityTypes ( ) . getEntityTypeFromID ( entityTypeID ) ; String key = rs . getString ( 2 ) ; int lockType = rs . getInt ( 3 ) ; Timestamp ts = rs . getTimestamp ( 4 ) ; String lockOwner = rs . getString ( 5 ) ; return newInstance ( entityType , key , lockType , ts , lockOwner ) ; } | Extract values from ResultSet and create a new lock . |
34,829 | private void primAdd ( IEntityLock lock , Connection conn ) throws SQLException , LockingException { Integer typeID = EntityTypesLocator . getEntityTypes ( ) . getEntityIDFromType ( lock . getEntityType ( ) ) ; String key = lock . getEntityKey ( ) ; int lockType = lock . getLockType ( ) ; Timestamp ts = new Timestamp ( lock . getExpirationTime ( ) . getTime ( ) ) ; String owner = lock . getLockOwner ( ) ; try { PreparedStatement ps = conn . prepareStatement ( getAddSql ( ) ) ; try { ps . setInt ( 1 , typeID . intValue ( ) ) ; ps . setString ( 2 , key ) ; ps . setInt ( 3 , lockType ) ; ps . setTimestamp ( 4 , ts ) ; ps . setString ( 5 , owner ) ; if ( log . isDebugEnabled ( ) ) log . debug ( "RDBMEntityLockStore.primAdd(): " + ps ) ; int rc = ps . executeUpdate ( ) ; if ( rc != 1 ) { String errString = "Problem adding " + lock ; log . error ( errString ) ; throw new LockingException ( errString ) ; } } finally { if ( ps != null ) ps . close ( ) ; } } catch ( java . sql . SQLException sqle ) { log . error ( sqle , sqle ) ; throw sqle ; } } | Add the lock to the underlying store . |
34,830 | private IEntityLock [ ] primSelect ( String sql ) throws LockingException { Connection conn = null ; Statement stmnt = null ; ResultSet rs = null ; List locks = new ArrayList ( ) ; if ( log . isDebugEnabled ( ) ) log . debug ( "RDBMEntityLockStore.primSelect(): " + sql ) ; try { conn = RDBMServices . getConnection ( ) ; stmnt = conn . createStatement ( ) ; try { rs = stmnt . executeQuery ( sql ) ; try { while ( rs . next ( ) ) { locks . add ( instanceFromResultSet ( rs ) ) ; } } finally { rs . close ( ) ; } } finally { stmnt . close ( ) ; } } catch ( SQLException sqle ) { log . error ( sqle , sqle ) ; throw new LockingException ( "Problem retrieving EntityLocks" , sqle ) ; } finally { RDBMServices . releaseConnection ( conn ) ; } return ( ( IEntityLock [ ] ) locks . toArray ( new IEntityLock [ locks . size ( ) ] ) ) ; } | Retrieve IEntityLocks from the underlying store . |
34,831 | public IEntityGroupStore newGroupStore ( ComponentGroupServiceDescriptor svcDescriptor ) throws GroupsException { FileSystemGroupStore fsGroupStore = ( FileSystemGroupStore ) getGroupStore ( ) ; String groupsRoot = ( String ) svcDescriptor . get ( "groupsRoot" ) ; if ( groupsRoot != null ) { fsGroupStore . setGroupsRootPath ( groupsRoot ) ; } return fsGroupStore ; } | Return an instance of the entity group store implementation . |
34,832 | public static DataSource getDataSource ( String name ) { if ( PORTAL_DB . equals ( name ) ) { return PortalDbLocator . getPortalDb ( ) ; } final ApplicationContext applicationContext = PortalApplicationContextLocator . getApplicationContext ( ) ; final DataSource dataSource = ( DataSource ) applicationContext . getBean ( name , DataSource . class ) ; return dataSource ; } | Gets a named DataSource from JNDI with special handling for the PORTAL_DB datasource . Successful lookups are cached and not done again . Lookup failure is remembered and blocks retry for a number of milliseconds specified by JNDI_RETRY_TIME to reduce JNDI overhead and log spam . |
34,833 | public static Connection getConnection ( String dbName ) { final DataSource dataSource = getDataSource ( dbName ) ; try { final long start = System . currentTimeMillis ( ) ; final Connection c = dataSource . getConnection ( ) ; lastDatabase = databaseTimes . add ( System . currentTimeMillis ( ) - start ) ; final int current = activeConnections . incrementAndGet ( ) ; if ( current > maxConnections ) { maxConnections = current ; } return c ; } catch ( SQLException e ) { throw new DataAccessResourceFailureException ( "RDBMServices sql error trying to get connection to " + dbName , e ) ; } } | Returns a connection produced by a DataSource found in the JNDI context . The DataSource should be configured and loaded into JNDI by the J2EE container or may be the portal default database . |
34,834 | public static void closeResultSet ( final ResultSet rs ) { if ( rs == null ) { return ; } try { rs . close ( ) ; } catch ( Exception e ) { if ( LOG . isWarnEnabled ( ) ) LOG . warn ( "Error closing ResultSet: " + rs , e ) ; } } | Close a ResultSet |
34,835 | public static void closeStatement ( final Statement st ) { if ( st == null ) { return ; } try { st . close ( ) ; } catch ( Exception e ) { if ( LOG . isWarnEnabled ( ) ) LOG . warn ( "Error closing Statement: " + st , e ) ; } } | Close a Statement |
34,836 | public static final void rollback ( final Connection connection ) { try { connection . rollback ( ) ; } catch ( Exception e ) { if ( LOG . isWarnEnabled ( ) ) LOG . warn ( "Error rolling back Connection: " + connection , e ) ; } } | rollback unwanted changes to the database |
34,837 | public static final boolean dbFlag ( final String flag ) { return flag != null && ( FLAG_TRUE . equalsIgnoreCase ( flag ) || FLAG_TRUE_OTHER . equalsIgnoreCase ( flag ) ) ; } | Return boolean value of DB flag Y or N . |
34,838 | public static final String sqlEscape ( final String sql ) { if ( sql == null ) { return "" ; } int primePos = sql . indexOf ( "'" ) ; if ( primePos == - 1 ) { return sql ; } final StringBuffer sb = new StringBuffer ( sql . length ( ) + 4 ) ; int startPos = 0 ; do { sb . append ( sql . substring ( startPos , primePos + 1 ) ) ; sb . append ( "'" ) ; startPos = primePos + 1 ; primePos = sql . indexOf ( "'" , startPos ) ; } while ( primePos != - 1 ) ; sb . append ( sql . substring ( startPos ) ) ; return sb . toString ( ) ; } | Make a string SQL safe |
34,839 | protected EvaluationContext getEvaluationContext ( WebRequest request ) { final HttpServletRequest httpRequest = this . portalRequestUtils . getOriginalPortalRequest ( request ) ; final IUserInstance userInstance = this . userInstanceManager . getUserInstance ( httpRequest ) ; final IPerson person = userInstance . getPerson ( ) ; final SpELEnvironmentRoot root = new SpELEnvironmentRoot ( request , person ) ; final StandardEvaluationContext context = new StandardEvaluationContext ( root ) ; context . setBeanResolver ( this . beanResolver ) ; return context ; } | Return a SpEL evaluation context for the supplied web request . |
34,840 | public IPermission [ ] getPermissions ( String activity , String target ) throws AuthorizationException { return getAuthorizationService ( ) . getPermissionsForOwner ( getOwner ( ) , activity , target ) ; } | Retrieve an array of IPermission objects based on the given parameters . Any null parameters will be ignored . |
34,841 | protected void addFetches ( final Root < PortletEntityImpl > definitionRoot ) { definitionRoot . fetch ( PortletEntityImpl_ . portletPreferences , JoinType . LEFT ) . fetch ( PortletPreferencesImpl_ . portletPreferences , JoinType . LEFT ) . fetch ( PortletPreferenceImpl_ . values , JoinType . LEFT ) ; definitionRoot . fetch ( PortletEntityImpl_ . windowStates , JoinType . LEFT ) ; } | Add all the fetches needed for completely loading the object graph |
34,842 | public void mark ( int eventLimit ) { this . eventLimit = eventLimit ; if ( this . eventLimit == 0 ) { this . eventBuffer . clear ( ) ; this . bufferReader = null ; } else if ( this . eventLimit > 0 ) { int iteratorIndex = 0 ; if ( this . bufferReader != null ) { final int nextIndex = this . bufferReader . nextIndex ( ) ; iteratorIndex = Math . max ( 0 , nextIndex - ( this . eventBuffer . size ( ) - this . eventLimit ) ) ; } while ( this . eventBuffer . size ( ) > this . eventLimit ) { this . eventBuffer . poll ( ) ; } if ( this . bufferReader != null ) { this . bufferReader = this . eventBuffer . listIterator ( iteratorIndex ) ; } } } | Start buffering events |
34,843 | private void addToLocaleList ( List localeList , List < Locale > locales ) { if ( locales != null ) { for ( Locale locale : locales ) { if ( locale != null && ! localeList . contains ( locale ) ) localeList . add ( locale ) ; } } } | Add locales to the locale list if they aren t in there already |
34,844 | public static String permissionTargetIdForPortletDefinition ( final IPortletDefinition portletDefinition ) { Validate . notNull ( portletDefinition , "Cannot compute permission target ID for a null portlet definition." ) ; final String portletPublicationId = portletDefinition . getPortletDefinitionId ( ) . getStringId ( ) ; return IPermission . PORTLET_PREFIX . concat ( portletPublicationId ) ; } | Static utility method computing the permission target ID for a portlet definition . |
34,845 | public void startServer ( ) { if ( ! System . getProperties ( ) . containsKey ( JMX_ENABLED_PROPERTY ) ) { this . logger . info ( "System Property '" + JMX_ENABLED_PROPERTY + "' is not set, skipping initialization." ) ; return ; } try { final int portOne = this . getPortOne ( ) ; final int portTwo = this . calculatePortTwo ( portOne ) ; try { LocateRegistry . createRegistry ( portOne ) ; if ( this . logger . isDebugEnabled ( ) ) { this . logger . debug ( "Started RMI Registry on port " + portOne ) ; } } catch ( RemoteException re ) { throw new IllegalStateException ( "Could not create RMI Registry on port " + portOne , re ) ; } final JMXServiceURL jmxServiceUrl = this . getServiceUrl ( portOne , portTwo ) ; final Map < String , Object > jmxEnv = this . getJmxServerEnvironment ( ) ; final MBeanServer mbeanServer = ManagementFactory . getPlatformMBeanServer ( ) ; try { this . jmxConnectorServer = JMXConnectorServerFactory . newJMXConnectorServer ( jmxServiceUrl , jmxEnv , mbeanServer ) ; if ( this . logger . isDebugEnabled ( ) ) { this . logger . debug ( "Created JMXConnectorServer for JMXServiceURL='" + jmxServiceUrl + "', jmxEnv='" + jmxEnv + "' MBeanServer='" + mbeanServer + "'" ) ; } } catch ( IOException ioe ) { throw new IllegalStateException ( "Failed to create a new JMXConnectorServer for JMXServiceURL='" + jmxServiceUrl + "', jmxEnv='" + jmxEnv + "' MBeanServer='" + mbeanServer + "'" , ioe ) ; } try { this . jmxConnectorServer . start ( ) ; this . logger . info ( "Started JMXConnectorServer. Listening on '" + jmxServiceUrl + "'" ) ; } catch ( IOException ioe ) { throw new IllegalStateException ( "Failed to start the JMXConnectorServer" , ioe ) ; } } catch ( RuntimeException re ) { if ( this . failOnException ) { throw re ; } this . logger . error ( "Failed to initialize the JMX Server" , re ) ; } } | Starts the RMI server and JMX connector server |
34,846 | public void stopServer ( ) { if ( this . jmxConnectorServer == null ) { this . logger . info ( "No JMXConnectorServer to stop" ) ; return ; } try { try { this . jmxConnectorServer . stop ( ) ; this . logger . info ( "Stopped JMXConnectorServer" ) ; } catch ( IOException ioe ) { throw new IllegalStateException ( "Failed to stop the JMXConnectorServer" , ioe ) ; } this . jmxConnectorServer = null ; } catch ( RuntimeException re ) { if ( this . failOnException ) { throw re ; } this . logger . error ( "Failed to shutdown the JMX Server" , re ) ; } } | Stops the JMX connector server and RMI server |
34,847 | protected int calculatePortTwo ( final int portOne ) { int portTwo = this . portTwo ; if ( portTwo <= 0 ) { portTwo = portOne + 1 ; } if ( this . logger . isDebugEnabled ( ) ) { this . logger . debug ( "Using " + portTwo + " for portTwo." ) ; } return portTwo ; } | Get the second rmi port from the init parameters or calculate it |
34,848 | protected JMXServiceURL getServiceUrl ( final int portOne , int portTwo ) { final String jmxHost ; if ( this . host == null ) { final InetAddress inetHost ; try { inetHost = InetAddress . getLocalHost ( ) ; } catch ( UnknownHostException uhe ) { throw new IllegalStateException ( "Cannot resolve localhost InetAddress." , uhe ) ; } jmxHost = inetHost . getHostName ( ) ; } else { jmxHost = this . host ; } final String jmxUrl = "service:jmx:rmi://" + jmxHost + ":" + portTwo + "/jndi/rmi://" + jmxHost + ":" + portOne + "/server" ; final JMXServiceURL jmxServiceUrl ; try { jmxServiceUrl = new JMXServiceURL ( jmxUrl ) ; } catch ( MalformedURLException mue ) { throw new IllegalStateException ( "Failed to create JMXServiceURL for url String '" + jmxUrl + "'" , mue ) ; } if ( this . logger . isDebugEnabled ( ) ) { this . logger . debug ( "Generated JMXServiceURL='" + jmxServiceUrl + "' from String " + jmxUrl + "'." ) ; } return jmxServiceUrl ; } | Generates the JMXServiceURL for the two specified ports . |
34,849 | protected Map < String , Object > getJmxServerEnvironment ( ) { final Map < String , Object > jmxEnv = new HashMap < String , Object > ( ) ; final String enableSSL = System . getProperty ( JMX_SSL_PROPERTY ) ; if ( Boolean . getBoolean ( enableSSL ) ) { SslRMIClientSocketFactory csf = new SslRMIClientSocketFactory ( ) ; jmxEnv . put ( RMIConnectorServer . RMI_CLIENT_SOCKET_FACTORY_ATTRIBUTE , csf ) ; SslRMIServerSocketFactory ssf = new SslRMIServerSocketFactory ( ) ; jmxEnv . put ( RMIConnectorServer . RMI_SERVER_SOCKET_FACTORY_ATTRIBUTE , ssf ) ; } final String passwordFile = System . getProperty ( JMX_PASSWORD_FILE_PROPERTY ) ; if ( passwordFile != null ) { jmxEnv . put ( JMX_REMOTE_X_PASSWORD_FILE , passwordFile ) ; } final String accessFile = System . getProperty ( JMX_ACCESS_FILE_PROPERTY ) ; if ( accessFile != null ) { jmxEnv . put ( JMX_REMOTE_X_ACCESS_FILE , accessFile ) ; } if ( this . logger . isDebugEnabled ( ) ) { this . logger . debug ( "Configured JMX Server Environment = '" + jmxEnv + "'" ) ; } return jmxEnv ; } | Generates the environment Map for the JMX server based on system properties |
34,850 | protected final Set < AggregatedGroupMapping > collectAllGroupsFromParams ( Set < K > keys , AggregatedGroupMapping [ ] aggregatedGroupMappings ) { final Builder < AggregatedGroupMapping > groupsBuilder = ImmutableSet . < AggregatedGroupMapping > builder ( ) ; for ( K aggregationKey : keys ) { groupsBuilder . add ( aggregationKey . getAggregatedGroup ( ) ) ; } groupsBuilder . add ( aggregatedGroupMappings ) ; return groupsBuilder . build ( ) ; } | and set in query . |
34,851 | public String getSelectedProfile ( PortletRequest request ) { final PortletSession session = request . getPortletSession ( ) ; String profileName = ( String ) session . getAttribute ( SessionAttributeProfileMapperImpl . DEFAULT_SESSION_ATTRIBUTE_NAME , PortletSession . APPLICATION_SCOPE ) ; if ( profileName == null ) { final HttpServletRequest httpServletRequest = portalRequestUtils . getPortletHttpRequest ( request ) ; final IUserInstance ui = userInstanceManager . getUserInstance ( httpServletRequest ) ; final IUserProfile profile = ui . getPreferencesManager ( ) . getUserProfile ( ) ; for ( Map . Entry < String , String > entry : mappings . entrySet ( ) ) { if ( entry . getValue ( ) . equals ( profile . getProfileFname ( ) ) ) { profileName = entry . getKey ( ) ; break ; } } } return profileName ; } | Get the profile that should be pre - selected in the local login form . |
34,852 | public static void addParameter ( IUrlBuilder urlBuilder , String name , String value ) { urlBuilder . addParameter ( name , value ) ; } | Needed due to compile - time type checking limitations of the XSLTC compiler |
34,853 | public boolean nameExists ( final String name ) { boolean rslt = false ; try { final ITenant tenant = this . tenantDao . getTenantByName ( name ) ; rslt = tenant != null ; } catch ( IllegalArgumentException iae ) { rslt = false ; } return rslt ; } | Returns true if a tenant with the specified name exists otherwise false . |
34,854 | public boolean fnameExists ( final String fname ) { boolean rslt = false ; try { final ITenant tenant = getTenantByFName ( fname ) ; rslt = tenant != null ; } catch ( IllegalArgumentException iae ) { rslt = false ; } return rslt ; } | Returns true if a tenant with the specified fname exists otherwise false . |
34,855 | public void validateName ( final String name ) { Validate . validState ( TENANT_NAME_VALIDATOR_PATTERN . matcher ( name ) . matches ( ) , "Invalid tenant name '%s' -- names must match %s ." , name , TENANT_NAME_VALIDATOR_REGEX ) ; } | Throws an exception if the specified String isn t a valid tenant name . |
34,856 | public void validateFname ( final String fname ) { Validate . validState ( TENANT_FNAME_VALIDATOR_PATTERN . matcher ( fname ) . matches ( ) , "Invalid tenant fname '%s' -- fnames must match %s ." , fname , TENANT_FNAME_VALIDATOR_REGEX ) ; } | Throws an exception if the specified String isn t a valid tenant fname . |
34,857 | public String showConfigPage ( RenderRequest request , PortletPreferences preferences , Model model ) { SortedSet < String > skins = skinService . getSkinNames ( request ) ; model . addAttribute ( "skinNames" , skins ) ; Enumeration < String > preferenceNames = preferences . getNames ( ) ; while ( preferenceNames . hasMoreElements ( ) ) { String name = preferenceNames . nextElement ( ) ; if ( name . startsWith ( DynamicRespondrSkinConstants . CONFIGURABLE_PREFIX ) ) { model . addAttribute ( name , preferences . getValue ( name , "" ) ) ; } } return "jsp/DynamicRespondrSkin/skinConfig" ; } | Display a form to manage skin choices . |
34,858 | public static synchronized IEntityGroupStore getGroupStore ( ) { if ( groupStore == null ) { groupStore = new GrouperEntityGroupStore ( ) ; } if ( LOGGER . isDebugEnabled ( ) ) { LOGGER . debug ( "returning IEntityGroupStore: " + groupStore ) ; } return groupStore ; } | returns the instance of GrouperEntityGroupStore . |
34,859 | public IEntityGroupStore newGroupStore ( ComponentGroupServiceDescriptor svcDescriptor ) throws GroupsException { if ( LOGGER . isDebugEnabled ( ) ) { LOGGER . debug ( "Creating New Grouper IEntityGroupStore" ) ; } return getGroupStore ( ) ; } | Construction with parameters . |
34,860 | public void onApplicationEvent ( LoginEvent loginEvent ) { if ( enableMarketplacePreloading ) { final IPerson person = loginEvent . getPerson ( ) ; final Set < PortletCategory > empty = Collections . emptySet ( ) ; loadMarketplaceEntriesFor ( person , empty ) ; } } | Handle the portal LoginEvent . If marketplace caching is enabled will preload marketplace entries for the currently logged in user . |
34,861 | private void collectSpecifiedAndDescendantCategories ( PortletCategory specified , Set < PortletCategory > gathered ) { final Set < PortletCategory > children = portletCategoryRegistry . getAllChildCategories ( specified ) ; for ( PortletCategory child : children ) { collectSpecifiedAndDescendantCategories ( child , gathered ) ; } gathered . add ( specified ) ; } | Called recursively to gather all specified categories and descendants |
34,862 | public boolean mayAddPortlet ( final IPerson user , final IPortletDefinition portletDefinition ) { Validate . notNull ( user , "Cannot determine if null users can browse portlets." ) ; Validate . notNull ( portletDefinition , "Cannot determine whether a user can browse a null portlet definition." ) ; return user . isGuest ( ) ? false : authorizationService . canPrincipalSubscribe ( AuthorizationPrincipalHelper . principalFromUser ( user ) , portletDefinition . getPortletDefinitionId ( ) . getStringId ( ) ) ; } | Answers whether the given user may add the portlet to their layout |
34,863 | void lock ( String serverId ) { Assert . notNull ( serverId ) ; if ( this . locked ) { throw new IllegalStateException ( "Cannot lock already locked mutex: " + this ) ; } this . locked = true ; this . lockStart = new Date ( ) ; this . lastUpdate = this . lockStart ; this . serverId = serverId ; } | Mark the mutex as locked by the specific server |
34,864 | public static void setUserPreference ( Element compViewNode , String attributeName , IPerson person ) { Document doc = compViewNode . getOwnerDocument ( ) ; NodeList nodes = doc . getElementsByTagName ( "layout" ) ; boolean layoutOwner = false ; Attr attrib ; Element e ; for ( int i = 0 ; i < nodes . getLength ( ) ; i ++ ) { e = ( Element ) nodes . item ( i ) ; attrib = e . getAttributeNodeNS ( Constants . NS_URI , Constants . LCL_FRAGMENT_NAME ) ; if ( attrib != null ) { layoutOwner = true ; } } if ( ! layoutOwner ) { Element plfNode = HandlerUtils . getPLFNode ( compViewNode , person , true , false ) ; if ( plfNode . getAttributeNodeNS ( Constants . NS_URI , Constants . LCL_ORIGIN ) != null ) EditManager . addPrefsDirective ( plfNode , attributeName , person ) ; } } | Records changes made to element attributes that are defined as being part of a user s user preferences object and not part of the layout . These attributes are specified in the . sdf files for the structure and theme stylesheets . The value is not stored in the layout but the loading of user prefs joins to a layout struct and hence that struct must exist in the layout . This call gets that node into the PLF if not there already and prevents it from being removed if no other changes were made to it or its children by the user . |
34,865 | public Set < String > getPossibleUserAttributeNames ( ) { final Set < String > names = new HashSet < String > ( ) ; names . addAll ( this . possibleUserAttributes ) ; names . addAll ( localAccountDao . getCurrentAttributeNames ( ) ) ; names . add ( displayNameAttribute ) ; return names ; } | Return the list of all possible attribute names . This implementation queries the database to provide a list of all mapped attribute names plus all attribute keys currently in - use in the database . |
34,866 | public Set < String > getAvailableQueryAttributes ( ) { if ( this . queryAttributeMapping == null ) { return Collections . emptySet ( ) ; } return Collections . unmodifiableSet ( this . queryAttributeMapping . keySet ( ) ) ; } | Return the list of all possible query attributes . This implementation queries the database to provide a list of all mapped query attribute names plus all attribute keys currently in - use in the database . |
34,867 | protected IPersonAttributes mapPersonAttributes ( final ILocalAccountPerson person ) { final Map < String , List < Object > > mappedAttributes = new LinkedHashMap < String , List < Object > > ( ) ; mappedAttributes . putAll ( person . getAttributes ( ) ) ; mappedAttributes . put ( this . getUsernameAttributeProvider ( ) . getUsernameAttribute ( ) , Collections . < Object > singletonList ( person . getName ( ) ) ) ; if ( ! mappedAttributes . containsKey ( displayNameAttribute ) || mappedAttributes . get ( displayNameAttribute ) . size ( ) == 0 || StringUtils . isBlank ( ( String ) mappedAttributes . get ( displayNameAttribute ) . get ( 0 ) ) ) { final List < Object > firstNames = mappedAttributes . get ( "givenName" ) ; final List < Object > lastNames = mappedAttributes . get ( "sn" ) ; final StringBuilder displayName = new StringBuilder ( ) ; if ( firstNames != null && firstNames . size ( ) > 0 ) { displayName . append ( firstNames . get ( 0 ) ) . append ( " " ) ; } if ( lastNames != null && lastNames . size ( ) > 0 ) { displayName . append ( lastNames . get ( 0 ) ) ; } mappedAttributes . put ( displayNameAttribute , Collections . < Object > singletonList ( displayName . toString ( ) ) ) ; } for ( final Map . Entry < String , Set < String > > resultAttrEntry : this . getResultAttributeMapping ( ) . entrySet ( ) ) { final String dataKey = resultAttrEntry . getKey ( ) ; if ( mappedAttributes . containsKey ( dataKey ) ) { Set < String > resultKeys = resultAttrEntry . getValue ( ) ; if ( resultKeys == null ) { resultKeys = Collections . singleton ( dataKey ) ; } final List < Object > value = mappedAttributes . get ( dataKey ) ; for ( final String resultKey : resultKeys ) { if ( resultKey == null ) { if ( ! mappedAttributes . containsKey ( dataKey ) ) { mappedAttributes . put ( dataKey , value ) ; } } else if ( ! mappedAttributes . containsKey ( resultKey ) ) { mappedAttributes . put ( resultKey , value ) ; } } } } final IPersonAttributes newPerson ; final String name = person . getName ( ) ; if ( name != null ) { newPerson = new NamedPersonImpl ( name , mappedAttributes ) ; } else { final String userNameAttribute = this . getConfiguredUserNameAttribute ( ) ; newPerson = new AttributeNamedPersonImpl ( userNameAttribute , mappedAttributes ) ; } return newPerson ; } | This implementation uses the result attribute mapping to supplement rather than replace the attributes returned from the database . |
34,868 | public EntityIdentifier [ ] searchForGroups ( String query , IGroupConstants . SearchMethod method , Class leaftype ) throws GroupsException { Set allIds = new HashSet ( ) ; for ( Iterator services = getComponentServices ( ) . values ( ) . iterator ( ) ; services . hasNext ( ) ; ) { IIndividualGroupService service = ( IIndividualGroupService ) services . next ( ) ; EntityIdentifier [ ] ids = service . searchForGroups ( query , method , leaftype ) ; for ( int i = 0 ; i < ids . length ; i ++ ) { try { CompositeEntityIdentifier cei = new CompositeEntityIdentifier ( ids [ i ] . getKey ( ) , ids [ i ] . getType ( ) ) ; cei . setServiceName ( service . getServiceName ( ) ) ; allIds . add ( cei ) ; } catch ( javax . naming . InvalidNameException ine ) { } } } return ( EntityIdentifier [ ] ) allIds . toArray ( new EntityIdentifier [ allIds . size ( ) ] ) ; } | Find EntityIdentifiers for groups whose name matches the query string according to the specified method and matches the provided leaf type |
34,869 | public IEntityGroupStore newInstance ( ) throws GroupsException { try { return new RDBMEntityGroupStore ( ) ; } catch ( Exception ex ) { log . error ( "ReferenceEntityGroupStoreFactory.newInstance(): " + ex ) ; throw new GroupsException ( ex ) ; } } | Return an instance of the group store implementation . |
34,870 | private void initMapper ( ) { final BeanPropertyFilter filterOutAllExcept = SimpleBeanPropertyFilter . filterOutAllExcept ( "fname" , "executionTimeNano" ) ; this . mapper . addMixInAnnotations ( PortalEvent . class , PortletRenderExecutionEventFilterMixIn . class ) ; final SimpleFilterProvider filterProvider = new SimpleFilterProvider ( ) ; filterProvider . addFilter ( PortletRenderExecutionEventFilterMixIn . FILTER_NAME , filterOutAllExcept ) ; this . portletEventWriter = this . mapper . writer ( filterProvider ) ; } | Configure the ObjectMapper to filter out all fields on the events except those that are actually needed for the analytics reporting |
34,871 | protected Properties mergeProperties ( ) throws IOException { Properties rslt = null ; final String encryptionKey = System . getenv ( JAYSYPT_ENCRYPTION_KEY_VARIABLE ) ; if ( encryptionKey != null ) { logger . info ( "Jasypt support for encrypted property values ENABLED" ) ; StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor ( ) ; encryptor . setPassword ( encryptionKey ) ; rslt = new EncryptableProperties ( encryptor ) ; if ( this . localOverride ) { loadProperties ( rslt ) ; } if ( this . localProperties != null ) { for ( int i = 0 ; i < this . localProperties . length ; i ++ ) { CollectionUtils . mergePropertiesIntoMap ( this . localProperties [ i ] , rslt ) ; } } if ( ! this . localOverride ) { loadProperties ( rslt ) ; } } else { logger . info ( "Jasypt support for encrypted property values DISABLED; " + "specify environment variable {} to use this feature" , JAYSYPT_ENCRYPTION_KEY_VARIABLE ) ; return super . mergeProperties ( ) ; } return rslt ; } | Override PropertiesLoaderSupport . mergeProprties in order to slip in a properly - configured EncryptableProperties instance allowing us to encrypt property values at rest . |
34,872 | public String generateRandomToken ( int length ) { final char [ ] token = new char [ length ] ; for ( int i = 0 ; i < length ; i ++ ) { final int tokenIndex = random . nextInt ( this . tokenChars . length ) ; token [ i ] = tokenChars [ tokenIndex ] ; } return new String ( token ) ; } | Generate a random token of the specified length |
34,873 | private void init ( ) { if ( this . internalPortletDefinitionId != - 1 && ( this . portletDefinitionId == null || this . portletDefinitionId . getLongId ( ) != this . internalPortletDefinitionId ) ) { this . portletDefinitionId = PortletDefinitionIdImpl . create ( this . internalPortletDefinitionId ) ; } } | Used to initialize fields after persistence actions . |
34,874 | public void resetUserLayoutAllProfiles ( final IPersonAttributes personAttributes ) { final IPerson person = PersonFactory . createRestrictedPerson ( ) ; person . setAttributes ( personAttributes . getAttributes ( ) ) ; int uid = userIdentityStore . getPortalUID ( person , false ) ; person . setID ( uid ) ; final Hashtable < Integer , UserProfile > map = userLayoutStore . getUserProfileList ( person ) ; for ( UserProfile profile : map . values ( ) ) { resetUserLayoutForProfileByName ( person , profile ) ; resetStylesheetUserPreferencesForProfile ( person , profile ) ; } } | Resets a users layout for all the users profiles |
34,875 | public IMarketplaceRating createOrUpdateRating ( IMarketplaceRating marketplaceRatingImplementation ) { Validate . notNull ( marketplaceRatingImplementation , "MarketplaceRatingImpl must not be null" ) ; final EntityManager entityManager = this . getEntityManager ( ) ; IMarketplaceRating temp = this . getRating ( marketplaceRatingImplementation . getMarketplaceRatingPK ( ) ) ; if ( ! entityManager . contains ( marketplaceRatingImplementation ) && temp != null ) { temp = entityManager . merge ( marketplaceRatingImplementation ) ; } else { temp = marketplaceRatingImplementation ; } entityManager . persist ( temp ) ; return temp ; } | This method will either create a new rating or update an existing rating |
34,876 | protected void afterMarkup ( ) { final Set < StackState > state = scopeState . getFirst ( ) ; state . add ( StackState . WROTE_MARKUP ) ; } | Note that markup or indentation was written . |
34,877 | protected void afterData ( ) { final Set < StackState > state = scopeState . getFirst ( ) ; state . add ( StackState . WROTE_DATA ) ; } | Note that data were written . |
34,878 | protected String getIndent ( int depth , int size ) { final int length = depth * size ; String indent = indentCache . get ( length ) ; if ( indent == null ) { indent = getLineSeparator ( ) + StringUtils . repeat ( " " , length ) ; indentCache . put ( length , indent ) ; } return indent ; } | Generate an indentation string for the specified depth and indent size |
34,879 | protected Tuple < String , IPortletWindowId > parsePortletParameterName ( HttpServletRequest request , String name , Set < String > additionalPortletIds ) { for ( final String additionalPortletId : additionalPortletIds ) { final int windowIdIdx = name . indexOf ( additionalPortletId ) ; if ( windowIdIdx == - 1 ) { continue ; } final String paramName = name . substring ( PORTLET_PARAM_PREFIX . length ( ) + additionalPortletId . length ( ) + SEPARATOR . length ( ) ) ; final IPortletWindowId portletWindowId = this . portletWindowRegistry . getPortletWindowId ( request , additionalPortletId ) ; return new Tuple < String , IPortletWindowId > ( paramName , portletWindowId ) ; } final String paramName = this . safeSubstringAfter ( PORTLET_PARAM_PREFIX , name ) ; return new Tuple < String , IPortletWindowId > ( paramName , null ) ; } | Parse the parameter name and the optional portlet window id from a fully qualified query parameter . |
34,880 | protected void addPortletUrlData ( final HttpServletRequest request , final UrlStringBuilder url , final UrlType urlType , final IPortletUrlBuilder portletUrlBuilder , final IPortletWindowId targetedPortletWindowId , final boolean statelessUrl ) { final IPortletWindowId portletWindowId = portletUrlBuilder . getPortletWindowId ( ) ; final boolean targeted = portletWindowId . equals ( targetedPortletWindowId ) ; IPortletWindow portletWindow = null ; final String prefixedPortletWindowId ; final String suffixedPortletWindowId ; boolean addedNonTargetedPortletParam = false ; if ( targeted ) { prefixedPortletWindowId = "" ; suffixedPortletWindowId = "" ; } else { final String portletWindowIdStr = portletWindowId . toString ( ) ; prefixedPortletWindowId = SEPARATOR + portletWindowIdStr ; suffixedPortletWindowId = portletWindowIdStr + SEPARATOR ; portletWindow = this . portletWindowRegistry . getPortletWindow ( request , portletWindowId ) ; final IPortletWindowId delegationParentId = portletWindow . getDelegationParentId ( ) ; if ( delegationParentId != null ) { url . addParameter ( PARAM_DELEGATE_PARENT + prefixedPortletWindowId , delegationParentId . getStringId ( ) ) ; addedNonTargetedPortletParam = true ; } } switch ( urlType ) { case RESOURCE : { final String cacheability = portletUrlBuilder . getCacheability ( ) ; if ( cacheability != null ) { url . addParameter ( PARAM_CACHEABILITY + prefixedPortletWindowId , cacheability ) ; addedNonTargetedPortletParam = ! targeted ? true : addedNonTargetedPortletParam ; } final String resourceId = portletUrlBuilder . getResourceId ( ) ; if ( ! targeted && resourceId != null ) { url . addParameter ( PARAM_RESOURCE_ID + prefixedPortletWindowId , resourceId ) ; addedNonTargetedPortletParam = ! targeted ? true : addedNonTargetedPortletParam ; } break ; } default : { final PortletMode portletMode = portletUrlBuilder . getPortletMode ( ) ; if ( portletMode != null ) { url . addParameter ( PARAM_PORTLET_MODE + prefixedPortletWindowId , portletMode . toString ( ) ) ; addedNonTargetedPortletParam = ! targeted ? true : addedNonTargetedPortletParam ; } else if ( targeted && statelessUrl ) { portletWindow = portletWindow != null ? portletWindow : this . portletWindowRegistry . getPortletWindow ( request , portletWindowId ) ; final PortletMode currentPortletMode = portletWindow . getPortletMode ( ) ; url . addParameter ( PARAM_PORTLET_MODE + prefixedPortletWindowId , currentPortletMode . toString ( ) ) ; addedNonTargetedPortletParam = ! targeted ? true : addedNonTargetedPortletParam ; } final WindowState windowState = portletUrlBuilder . getWindowState ( ) ; if ( windowState != null && ( ! targeted || ! PATH_WINDOW_STATES . contains ( windowState ) ) ) { url . addParameter ( PARAM_WINDOW_STATE + prefixedPortletWindowId , windowState . toString ( ) ) ; addedNonTargetedPortletParam = ! targeted ? true : addedNonTargetedPortletParam ; } break ; } } if ( portletUrlBuilder . getCopyCurrentRenderParameters ( ) ) { url . addParameter ( PARAM_COPY_PARAMETERS + suffixedPortletWindowId ) ; addedNonTargetedPortletParam = ! targeted ? true : addedNonTargetedPortletParam ; } final Map < String , String [ ] > parameters = portletUrlBuilder . getParameters ( ) ; if ( ! parameters . isEmpty ( ) ) { url . addParametersArray ( PORTLET_PARAM_PREFIX + suffixedPortletWindowId , parameters ) ; addedNonTargetedPortletParam = ! targeted ? true : addedNonTargetedPortletParam ; } if ( addedNonTargetedPortletParam ) { url . addParameter ( PARAM_ADDITIONAL_PORTLET , portletWindowId . toString ( ) ) ; } } | Add the provided portlet url builder data to the url string builder |
34,881 | protected String getEncoding ( HttpServletRequest request ) { final String encoding = request . getCharacterEncoding ( ) ; if ( encoding != null ) { return encoding ; } return this . defaultEncoding ; } | Tries to determine the encoded from the request if not available falls back to configured default . |
34,882 | public void updateIndex ( ) { if ( ! isEnabled ( ) ) { return ; } final IndexWriterConfig indexWriterConfig = new IndexWriterConfig ( new StandardAnalyzer ( ) ) ; indexWriterConfig . setCommitOnClose ( true ) . setOpenMode ( IndexWriterConfig . OpenMode . CREATE_OR_APPEND ) ; try ( IndexWriter indexWriter = new IndexWriter ( directory , indexWriterConfig ) ) { final List < IPortletDefinition > portlets = portletRegistry . getAllPortletDefinitions ( ) ; portlets . forEach ( portlet -> indexPortlet ( portlet , indexWriter ) ) ; } catch ( Exception e ) { logger . error ( "Unable to update index" , e ) ; } } | Called by Quatrz . |
34,883 | public IEntitySearcher newEntitySearcher ( ) throws GroupsException { if ( LOGGER . isDebugEnabled ( ) ) { LOGGER . debug ( "Creating New Grouper GrouperEntitySearcherFactory" ) ; } return ( IEntitySearcher ) new GrouperEntityGroupStoreFactory ( ) . newGroupStore ( ) ; } | Creates an instance of EntitySearcher . |
34,884 | private boolean checkDatabaseVersion ( String databaseName ) { final Version softwareVersion = this . requiredProductVersions . get ( databaseName ) ; if ( softwareVersion == null ) { throw new IllegalStateException ( "No version number is configured for: " + databaseName ) ; } final Version databaseVersion = this . versionDao . getVersion ( databaseName ) ; if ( databaseVersion == null ) { throw new IllegalStateException ( "No version number is exists in the database for: " + databaseName ) ; } return softwareVersion . equals ( databaseVersion ) ; } | Check if the database and software versions match |
34,885 | public SearchResults getSearchResults ( PortletRequest request , SearchRequest query ) { final String queryString = query . getSearchTerms ( ) . toLowerCase ( ) ; final List < IPortletDefinition > portlets = portletDefinitionRegistry . getAllPortletDefinitions ( ) ; final HttpServletRequest httpServletRequest = this . portalRequestUtils . getPortletHttpRequest ( request ) ; final SearchResults results = new SearchResults ( ) ; for ( IPortletDefinition portlet : portlets ) { if ( this . matches ( queryString , new MarketplacePortletDefinition ( portlet , this . marketplaceService , this . portletCategoryRegistry ) ) ) { final SearchResult result = new SearchResult ( ) ; result . setTitle ( portlet . getTitle ( ) ) ; result . setSummary ( portlet . getDescription ( ) ) ; result . getType ( ) . add ( "marketplace" ) ; final IPortletWindow portletWindow = this . portletWindowRegistry . getOrCreateDefaultPortletWindowByFname ( httpServletRequest , portlet . getFName ( ) ) ; if ( portletWindow != null && authorizationService . canPrincipalBrowse ( authorizationService . newPrincipal ( request . getRemoteUser ( ) , EntityEnum . PERSON . getClazz ( ) ) , portlet ) ) { final IPortletWindowId portletWindowId = portletWindow . getPortletWindowId ( ) ; final IPortalUrlBuilder portalUrlBuilder = this . portalUrlProvider . getPortalUrlBuilderByPortletFName ( httpServletRequest , portlet . getFName ( ) , UrlType . RENDER ) ; final IPortletUrlBuilder portletUrlBuilder = portalUrlBuilder . getPortletUrlBuilder ( portletWindowId ) ; portletUrlBuilder . setWindowState ( PortletUtils . getWindowState ( "maximized" ) ) ; result . setExternalUrl ( portalUrlBuilder . getUrlString ( ) ) ; PortletUrl url = new PortletUrl ( ) ; url . setType ( PortletUrlType . RENDER ) ; url . setPortletMode ( "VIEW" ) ; url . setWindowState ( "maximized" ) ; PortletUrlParameter actionParam = new PortletUrlParameter ( ) ; actionParam . setName ( "action" ) ; actionParam . getValue ( ) . add ( "view" ) ; url . getParam ( ) . add ( actionParam ) ; PortletUrlParameter fNameParam = new PortletUrlParameter ( ) ; fNameParam . setName ( "fName" ) ; fNameParam . getValue ( ) . add ( portlet . getFName ( ) ) ; url . getParam ( ) . add ( fNameParam ) ; result . setPortletUrl ( url ) ; results . getSearchResult ( ) . add ( result ) ; } } } return results ; } | Returns a list of search results that pertain to the marketplace query is the query to search will search name title description fname and captions |
34,886 | public IOpaqueCredentials getOpaqueCredentials ( ) { if ( parentContext != null && parentContext . isAuthenticated ( ) ) { NotSoOpaqueCredentials oc = new CacheOpaqueCredentials ( ) ; oc . setCredentials ( this . cachedcredentials ) ; return oc ; } else return null ; } | We need to override this method in order to return a class that implements the NotSoOpaqueCredentials interface . |
34,887 | public static boolean isAdmin ( IPerson p ) { IAuthorizationPrincipal iap = AuthorizationServiceFacade . instance ( ) . newPrincipal ( p . getEntityIdentifier ( ) . getKey ( ) , p . getEntityIdentifier ( ) . getType ( ) ) ; return isAdmin ( iap ) ; } | Determines if the passed - in IPerson represents a user that is a member of the administrator group or any of its sub groups . |
34,888 | public static boolean isAdmin ( IAuthorizationPrincipal ap ) { IGroupMember member = AuthorizationServiceFacade . instance ( ) . getGroupMember ( ap ) ; return isAdmin ( member ) ; } | Determines if the passed - in authorization principal represents a user that is a member of the administrator group or any of its sub groups . |
34,889 | public static boolean isAdmin ( IGroupMember member ) { IEntityGroup adminGroup = null ; try { adminGroup = GroupService . getDistinguishedGroup ( PORTAL_ADMINISTRATORS_DISTINGUISHED_GROUP ) ; } catch ( GroupsException ge ) { cLog . error ( "Administrative group not found, cannot determine " + "user's admininstrative membership." , ge ) ; } return ( null != adminGroup && adminGroup . deepContains ( member ) ) ; } | Determines if the passed - in group member represents a user that is a member of the administrator group or any of its sub groups . |
34,890 | public boolean skinCssFileExists ( DynamicSkinInstanceData data ) { final String cssInstanceKey = getCssInstanceKey ( data ) ; if ( instanceKeysForExistingCss . contains ( cssInstanceKey ) ) { return true ; } boolean exists = innerSkinCssFileExists ( data ) ; if ( exists ) { if ( ! supportsRetainmentOfNonCurrentCss ( ) ) { instanceKeysForExistingCss . clear ( ) ; } instanceKeysForExistingCss . add ( cssInstanceKey ) ; } return exists ; } | Return true if the skin file already exists . Check memory first in a concurrent manner to allow multiple threads to check simultaneously . |
34,891 | public void generateSkinCssFile ( DynamicSkinInstanceData data ) { final String cssInstanceKey = getCssInstanceKey ( data ) ; synchronized ( cssInstanceKey ) { if ( instanceKeysForExistingCss . contains ( cssInstanceKey ) ) { return ; } try { if ( ! cssSkinFailureCache . getKeysWithExpiryCheck ( ) . contains ( cssInstanceKey ) ) { createLessIncludeFile ( data ) ; processLessFile ( data ) ; if ( ! supportsRetainmentOfNonCurrentCss ( ) ) { instanceKeysForExistingCss . clear ( ) ; } instanceKeysForExistingCss . add ( cssInstanceKey ) ; } else { logger . warn ( "Skipping generation of CSS file {} due to previous LESS compilation failures" , cssInstanceKey ) ; } } catch ( Exception e ) { cssSkinFailureCache . put ( new Element ( cssInstanceKey , cssInstanceKey ) ) ; throw new RuntimeException ( "Error compiling the LESS file to create: " + cssInstanceKey , e ) ; } } } | Creates the skin css file in a thread - safe manner that allows multiple different skin files to be created simultaneously to handle large tenant situations where all the custom CSS files were cleared away after a uPortal deploy . |
34,892 | private void processLessFile ( DynamicSkinInstanceData data ) throws IOException , LessException { final LessSource lessSource = new LessSource ( new File ( getSkinLessPath ( data ) ) ) ; if ( logger . isDebugEnabled ( ) ) { final String result = lessSource . getNormalizedContent ( ) ; final File lessSourceOutput = new File ( getSkinCssTempFileAbsolutePath ( data ) + "lesssource" ) ; IOUtils . write ( result , new FileOutputStream ( lessSourceOutput ) ) ; logger . debug ( "Full Less source from include file {} is at {}, output css will be written to {}" , getSkinLessPath ( data ) , lessSourceOutput , getSkinCssPath ( data ) ) ; } final LessCompiler compiler = new LessCompiler ( ) ; compiler . setCompress ( true ) ; final File tempOutputFile = new File ( getSkinCssTempFileAbsolutePath ( data ) ) ; compiler . compile ( lessSource , tempOutputFile ) ; moveCssFileToFinalLocation ( data , tempOutputFile ) ; } | Less compile the include file into a temporary css file . When done rename the temporary css file to the correct output filename . Since the less compilation phase takes several seconds this insures the output css file is does not exist on the filesystem until it is complete . |
34,893 | public SortedSet < String > getSkinNames ( PortletRequest request ) { PortletContext ctx = request . getPortletSession ( ) . getPortletContext ( ) ; String skinsFilepath = ctx . getRealPath ( localRelativeRootPath + "/skinList.xml" ) ; File skinList = new File ( skinsFilepath ) ; TreeSet < String > skins = new TreeSet < > ( ) ; try { DocumentBuilderFactory dbFactory = DocumentBuilderFactory . newInstance ( ) ; DocumentBuilder dBuilder = dbFactory . newDocumentBuilder ( ) ; Document doc = dBuilder . parse ( skinList ) ; doc . getDocumentElement ( ) . normalize ( ) ; NodeList nList = doc . getElementsByTagName ( "skin-key" ) ; for ( int temp = 0 ; temp < nList . getLength ( ) ; temp ++ ) { org . w3c . dom . Element element = ( org . w3c . dom . Element ) nList . item ( temp ) ; String skinName = element . getTextContent ( ) ; logger . debug ( "Found skin-key value {}" , skinName ) ; skins . add ( skinName ) ; } } catch ( SAXException | ParserConfigurationException | IOException e ) { logger . error ( "Error processing skinsFilepath {}" , skinsFilepath , e ) ; } return skins ; } | Returns the set of skins to use . This implementation parses the skinList . xml file and returns the set of skin - key element values . If there is an error parsing the XML file return an empty set . |
34,894 | public ClientHttpResponse intercept ( HttpRequest req , byte [ ] body , ClientHttpRequestExecution execution ) throws IOException { Assert . notNull ( propertyResolver ) ; Assert . notNull ( id ) ; try { String authString = getOAuthAuthString ( req ) ; req . getHeaders ( ) . add ( Headers . Authorization . name ( ) , authString ) ; } catch ( Exception e ) { throw new IOException ( "Error building OAuth header" , e ) ; } return execution . execute ( req , body ) ; } | Intercept a request and add the oauth headers . |
34,895 | private String getOAuthAuthString ( HttpRequest req ) throws OAuthException , IOException , URISyntaxException { RealmOAuthConsumer consumer = getConsumer ( ) ; OAuthAccessor accessor = new OAuthAccessor ( consumer ) ; String method = req . getMethod ( ) . name ( ) ; URI uri = req . getURI ( ) ; OAuthMessage msg = accessor . newRequestMessage ( method , uri . toString ( ) , null ) ; return msg . getAuthorizationHeader ( consumer . getRealm ( ) ) ; } | Get the oauth Authorization string . |
34,896 | private synchronized RealmOAuthConsumer getConsumer ( ) { if ( consumer == null ) { OAuthServiceProvider serviceProvider = new OAuthServiceProvider ( "" , "" , "" ) ; String realm = propertyResolver . getProperty ( "org.jasig.rest.interceptor.oauth." + id + ".realm" ) ; String consumerKey = propertyResolver . getProperty ( "org.jasig.rest.interceptor.oauth." + id + ".consumerKey" ) ; String secretKey = propertyResolver . getProperty ( "org.jasig.rest.interceptor.oauth." + id + ".secretKey" ) ; Assert . notNull ( consumerKey , "The property \"org.jasig.rest.interceptor.oauth." + id + ".consumerKey\" must be set." ) ; Assert . notNull ( secretKey , "The property \"org.jasig.rest.interceptor.oauth." + id + ".secretKey\" must be set." ) ; consumer = new RealmOAuthConsumer ( consumerKey , secretKey , realm , serviceProvider ) ; } return consumer ; } | Get the OAuthConsumer . Will initialize it lazily . |
34,897 | public String getView ( RenderRequest req , Model model ) { final String [ ] images = imageSetSelectionStrategy . getImageSet ( req ) ; model . addAttribute ( "images" , images ) ; final String [ ] thumbnailImages = imageSetSelectionStrategy . getImageThumbnailSet ( req ) ; model . addAttribute ( "thumbnailImages" , thumbnailImages ) ; final String [ ] imageCaptions = imageSetSelectionStrategy . getImageCaptions ( req ) ; model . addAttribute ( "imageCaptions" , imageCaptions ) ; final String preferredBackgroundImage = imageSetSelectionStrategy . getSelectedImage ( req ) ; model . addAttribute ( "backgroundImage" , preferredBackgroundImage ) ; final String backgroundContainerSelector = imageSetSelectionStrategy . getBackgroundContainerSelector ( req ) ; model . addAttribute ( "backgroundContainerSelector" , backgroundContainerSelector ) ; final PortletPreferences prefs = req . getPreferences ( ) ; model . addAttribute ( "applyOpacityTo" , prefs . getValue ( "applyOpacityTo" , null ) ) ; model . addAttribute ( "opacityCssValue" , prefs . getValue ( "opacityCssValue" , "1.0" ) ) ; return "/jsp/BackgroundPreference/viewBackgroundPreference" ; } | Display the main user - facing view of the portlet . |
34,898 | private int getElementIndex ( Node node ) { final String nodeName = node . getNodeName ( ) ; int count = 1 ; for ( Node previousSibling = node . getPreviousSibling ( ) ; previousSibling != null ; previousSibling = previousSibling . getPreviousSibling ( ) ) { if ( previousSibling . getNodeType ( ) == Node . ELEMENT_NODE && previousSibling . getNodeName ( ) . equals ( nodeName ) ) { count ++ ; } } return count ; } | Gets the index of this element relative to other siblings with the same node name |
34,899 | static void applyAndUpdateDeleteSet ( Document plf , Document ilf , IntegrationResult result ) { Element dSet = null ; try { dSet = getDeleteSet ( plf , null , false ) ; } catch ( Exception e ) { LOG . error ( "Exception occurred while getting user's DLM delete-set." , e ) ; } if ( dSet == null ) return ; NodeList deletes = dSet . getChildNodes ( ) ; for ( int i = deletes . getLength ( ) - 1 ; i >= 0 ; i -- ) { if ( applyDelete ( ( Element ) deletes . item ( i ) , ilf ) == false ) { dSet . removeChild ( deletes . item ( i ) ) ; result . setChangedPLF ( true ) ; } else { result . setChangedILF ( true ) ; } } if ( dSet . getChildNodes ( ) . getLength ( ) == 0 ) { plf . getDocumentElement ( ) . removeChild ( dSet ) ; result . setChangedPLF ( true ) ; } } | Get the delete set if any from the plf and process each delete command removing any that fail from the delete set so that the delete set is self cleaning . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.